content stringlengths 7 1.05M |
|---|
class Solution:
def XXX(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
res = []
queue = [root]
while queue:
tmp = []
size = len(queue)
while size:
q = queue.pop(0)
tmp.append(q.val)
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
size -= 1
res.append(tmp)
return res
|
"""
The different types of errors the compiler can raise.
"""
class CompilerError(Exception):
"""
A general-purpose compiler error, which contains the position of the error
as well as a formatted message.
"""
def __init__(self, filename, line, col, fmt, *args, **kwargs):
super().__init__()
self.filename = filename
self.line = line
self.column = col
if line > 0 and col > 0:
self.message = (
"At {}:{}:{}: ".format(filename, line, col) +
fmt.format(*args, **kwargs))
else:
self.message = ('In {}: '.format(filename) +
fmt.format(*args, **kwargs))
@staticmethod
def from_token(tok, fmt, *args, **kwargs):
"""
Makes a new CompilerError, taking the position from the given token.
"""
return CompilerError(tok.filename, tok.line, tok.column,
fmt, *args, **kwargs)
|
#!/usr/bin/env python3
def get_stream(path):
with open(path, encoding='utf-8') as infile:
return infile.read()
stream = get_stream("input.txt")
def find_in_list(list_, x, start=0):
i = None
try:
i = list_.index(x, start)
except ValueError:
pass
return i
# Stream types:
# S = Stream (main)
# < = Garbage
# { = Group
# ! = Ignored
class Stream:
def __init__(self, text, stream_type=None):
self.stream_type = stream_type or 'S'
if self.stream_type == 'S':
text = self.cancel_chars(list(text))
text = self.identify_garbage(text)
if self.stream_type in ['S', '{']:
text = self.identify_groups(text)
self.data = text
def cancel_chars(self, text):
start = find_in_list(text, '!')
while start is not None:
if (start + 1) < len(text):
text[start] = Stream(text.pop(start + 1), '!')
start = find_in_list(text, '!', start + 1)
return text
def identify_garbage(self, text):
start = find_in_list(text, '<')
while start is not None:
end = text.index('>', start)
text[start] = Stream(text[start + 1:end], '<')
del text[start + 1:end + 1]
start = find_in_list(text, '<', start + 1)
return text
def identify_groups(self, text):
count = 0
groups = []
start = None
for i in range(len(text)):
if text[i] == '{':
count += 1
if count == 1:
start = i
elif text[i] == '}':
count -= 1
if count == 0:
groups.append((start, i))
removed = 0
for group in groups:
start = group[0] - removed
end = group[1] - removed
removed += (end - start)
text[start] = Stream(text[start + 1:end], '{')
del text[start + 1:end + 1]
return text
def count_groups(self):
count = 0
for s in self.data:
if hasattr(s, 'stream_type') and s.stream_type == '{':
count += 1
count += s.count_groups()
return count
def score_groups(self, outer=0):
score = 0
if self.stream_type == '{':
score += outer + 1
outer += 1
for s in self.data:
if hasattr(s, 'stream_type') and s.stream_type == '{':
score += s.score_groups(outer)
return score
def count_garbage(self):
count = 0
for s in self.data:
if hasattr(s, 'stream_type'):
if s.stream_type == '{':
count += s.count_garbage()
elif s.stream_type == '<':
count += len(
[s for s in s.data if type(s) == str]
)
return count
def __repr__(self):
if self.stream_type == 'S':
return ''.join([str(d) for d in self.data])
elif self.stream_type == '{':
return ' {' + ''.join(str(d) for d in self.data) + '} '
elif self.stream_type == '<':
return ' <' + ''.join(str(d) for d in self.data) + '> '
else:
return ' !' + str(self.data) + ' '
s = Stream(stream)
#print('Stream:', s)
print('Num groups:', s.count_groups())
print('Score:', s.score_groups())
print('Garbage:', s.count_garbage())
|
sum = 0
for i in range(1, 101):
sum += i
print(sum)
|
interest = [
(0, "Hadoop"), (0, "Big Data"), (0, "HBase"), (0, "Java"),
(0, "Spark"), (0, "Storm"), (0, "Cassandra"),
(1, "NoSQL"), (1, "MongDB"), (1, "Cassandra"), (1, "HBase"),
(1, "Postgres"), (2, "Python"), (2, "scikit-learn"), (2, "scipy"),
(2, "numpy"), (2, "statsmodels"), (2, "pandas"), (3, "R"), (3, "Python"),
(3, "statistics"), (3, "regression"), (3, "probability"),
(4, "machine learning"), (4, "regression"), (4, "decision trees"),
(4, "libsvm"), (5, "Python"), (5, "R"), (5, "Java"), (5, "C++"),
(5, "Haskell"), (5, "programming languages"), (6, "statistics"),
(6, "probability"), (6, "mathematics"), (6, "theory"),
(7, "machine learning"), (7, "scikit-learn"), (7, "Mahout"),
(7, "neural networks"), (8, "neural networks"), (8, "deep learning"),
(8, "Big data"), (8, "artificial intelligence"), (9, "Hadoop"),
(9, "Java"), (9, "MapReduce"), (9, "Big data")
]
|
#!python
def is_sorted(items):
#TODO: write code to implement the selection sort algorithm
for i in range(len(items)):
#moving the boundary of the sorted section forward
min_location = i
for j in range(i + 1, len(items)):
#finding the min value location in the unsorted section
if items[j] < items[min_location]:
min_location = j
temp = items[i]
items[i] = items[min_location]
items[min_location] = temp
items = [3,1,7,0]
#i i j->
is_sorted(items)
#print(items) #should print [0, 1, 3, 7]
def bubble_sort(list_a):
'''
Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
TODO: Running time: ??? Why and under what conditions?
TODO: Memory usage: ??? Why and under what conditions?
# TODO: Repeat until all items are in sorted order
# TODO: Swap adjacent items that are out of order
'''
indexing_length = len(list_a) - 1 #SCan not apply comparision starting with last item of list (No item to right)
sorted = False #Create variable of sorted and set it equal to false
while not sorted: #Repeat until sorted = True
sorted = True # Break the while loop whenever we have gone through all the values
for i in range(0, indexing_length): # For every value in the list
if list_a[i] > list_a[i+1]: #if value in list is greater than value directly to the right of it,
sorted = False # These values are unsorted
list_a[i], list_a[i+1] = list_a[i+1], list_a[i] #Switch these values
return list_a # Return our list "unsorted_list" which is not sorted.
# print(bubble_sort([4,8,1,14,8,2,9,5,7,6,6]))
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n^2) because as the numbers of items grow the so does the outter and inner loop, also the function increases in a quadratic way
Memory usage: O(1) because as items grow no additional spaces are created and everything done in place"""
# pseudo seperates list into 2 sections, sorted and unsorted, goes through the unsorted section and finds the index with lowest value among all and swaps it with the sorted section
## can use while or for outter loop
# i = 0
# this is 'sorted' section
# while i < len(items) - 1:
for i in range(len(items)-1):
lowest_index = i
lowest_value = items[lowest_index]
# this is 'unsorted' section
for j in range(lowest_index + 1, len(items)):
if items[j] < lowest_value:
# lowest_index gets updated and settles with the lowest index of lowest value
lowest_index = j
lowest_value = items[j]
# performs the swap
items[i], items[lowest_index] = items[lowest_index], items[i]
# moves pointer up
# i += 1
return items
def insertion_sort(items):
"""Sort given items by taking first unsorted item, inserting it in sorted
order in front of items, and repeating until all items are in order.
Running time: O(n^2) because as items grow outter and inner loop both increases, also the function increases in a quadratic way
Memory usage: O(1) because everything is done in place """
# similar to selection sort where list is pseudo broken into 'sorted' and 'unsorted' sections
# an item is selected from 'unsorted' and checks against the 'sorted' section to see where to add
# this is our selection section of the list
for i in range(1, len(items)):
# range is non inclusive so i is never reached only i-1
# loop through our 'sorted' section
for j in range(0, i):
# the moment it finds an item in this part of the list which is greater or equal 'unsorted' selected item, it is removed from the 'unsorted' section and inserted into the 'sorted' section
if items[j] >= items[i]:
removed_item = items.pop(i)
items.insert(j, removed_item)
continue
return items
|
#$ID$
class Participant:
"""This class is used to create object for participant."""
def __init__(self):
"""Initialize parameters for participant object."""
self.participant_id = ""
self.participant_person = ""
def set_participant_id(self, participant_id):
"""Set participant id.
Args:
participant_id(str): Participant id.
"""
self.participant_id = participant_id
def get_participant_id(self):
"""Get participant id.
Returns:
str: Participant id.
"""
return self.participant_id
def set_participant_person(self, participant_person):
"""Set participant person.
Args:
participant_person(str): Participant person.
"""
self.participant_person = participant_person
def get_participant_person(self):
"""Get participant person.
Returns:
str: Participant person.
"""
return self.participant_person
|
def count_neigbors_on(lights, i, j):
return (lights[i-1][j-1] if i > 0 and j > 0 else 0) \
+ (lights[i-1][j] if i > 0 else 0) \
+ (lights[i-1][j+1] if i > 0 and j < len(lights) - 1 else 0) \
+ (lights[i][j-1] if j > 0 else 0) \
+ (lights[i][j+1] if j < len(lights) - 1 else 0) \
+ (lights[i+1][j-1] if i < len(lights) - 1 and j > 0 else 0) \
+ (lights[i+1][j] if i < len(lights) - 1 else 0) \
+ (lights[i+1][j+1] if i < len(lights) - 1 and j < len(lights) - 1 else 0)
def get_next_state(curr_state):
next_state = []
for i in range(0, len(curr_state)):
row = [0] * len(curr_state[0])
for j in range(0, len(row)):
on_stays_on = curr_state[i][j] == 1 and count_neigbors_on(curr_state, i, j) in [2, 3]
off_turns_on = curr_state[i][j] == 0 and count_neigbors_on(curr_state, i, j) == 3
if on_stays_on or off_turns_on:
row[j] = 1
next_state.append(row)
return next_state
def solve(lights):
curr_state = lights
for turn in range(0, 100):
curr_state = get_next_state(curr_state)
return sum([sum(line) for line in curr_state])
def parse(file_name):
with open(file_name, "r") as f:
lights = []
lines = [line.strip() for line in f.readlines()]
for i in range(0, len(lines)):
row = [0] * len(lines[0])
for j in range(0, len(row)):
if lines[i][j] == "#":
row[j] = 1
lights.append(row)
return lights
if __name__ == '__main__':
print(solve(parse("data.txt")))
|
'''Publisher form
Provides a form for publisher creation
'''
__version__ = '0.1'
|
"""Desenvolva um programa que pergunte a distância de uma viagem em km.
Calcule o preço da passagem, cobrando R$ 0.50 po km para viagens de até 200km e R$ 0.45 para viagens mais longas"""
dist = float(input('Informe a distância da viagem: '))
if dist > 200:
valor = dist * 0.45
print('Valor da viagem é: {}'.format(valor))
else:
valor = dist * 0.50
print('Valor da viagem é: {}'.format(valor))
print('Boa viagem') |
# Valores iniciais
m = 0.5
g = 10
h = e = 0
# recebendo H
h = float(input("Digite a altura: "))
# 1° quicada
e = m*g*h-(0.2*m*g*h)
# 2° Quicada
e = e - (0.2*e)
# 3° Quicada
e = e - (0.2*e)
# calculando novo h
h = e/(m*10)
# exibindo resultado
print(f'A altura é de {h} após as 3 quicadas')
|
class Item():
def __init__(self, id_, value):
self.id_ = id_
self.value = value
class Stack():
def __init__(self):
self.size = 0
self._items = []
def push(self, item):
self._items.append(item)
self.size += 1
def pop(self):
item = None
if self.size > 0:
item = self._items.pop()
self.size -= 1
return item
|
NON_TERMINALS = [
"S",
"SBAR",
"SQ",
"SBARQ",
"SINV",
"ADJP",
"ADVP",
"CONJP",
"FRAG",
"INTJ",
"LST",
"NAC",
"NP",
"NX",
"PP",
"PRN",
"QP",
"RRC",
"UCP",
"VP",
"WHADJP",
"WHAVP",
"WHNP",
"WHPP",
"WHADVP",
"X",
"ROOT",
"NP-TMP",
"PRT",
]
class Token(object):
def __init__(self, word, idx):
self.word = word
self.idx = idx
def __repr__(self):
return repr(self.word)
class Node(object):
def __init__(self):
self.root = False
self.children = []
self.label = None
self.parent = None
self.phrase = ""
self.terminal = False
self.start_idx = 0
self.end_idx = 0
class Sentence(object):
def __init__(self, parse_string):
self.num_nodes = 0
self.tree = self.get_tree(parse_string)
self.sent = self.tree.phrase
tokens = {}
for idx, tok in enumerate(self.tree.phrase.split(" ")):
tokens[idx] = Token(tok, idx)
self.tokens = tokens
self.num_tokens = len(tokens)
def get_tree(self, parse_string):
tree = self.contruct_tree_from_parse(parse_string, None)
tree = self.reduce_tree(tree)
phrase_whole = self.assign_phrases(tree, 0)
tree.phrase = phrase_whole
tree.start_idx = 0
tree.end_idx = len(phrase_whole.split(" "))
tree.parent_idx = -1
self.assign_ids(tree)
return tree
def assign_ids(self, tree):
tree.idx = self.num_nodes
self.num_nodes += 1
for child in tree.children:
child.parent_idx = tree.idx
self.assign_ids(child)
@staticmethod
def get_subtrees(parse_txt_partial):
parse_txt_partial = parse_txt_partial[1:-1]
if "(" in parse_txt_partial:
idx_first_lb = parse_txt_partial.index("(")
name_const = parse_txt_partial[:idx_first_lb].strip()
parse_txt_partial = parse_txt_partial[idx_first_lb:]
count = 0
partition_indices = []
for idx in range(len(parse_txt_partial)):
if parse_txt_partial[idx] == "(":
count += 1
elif parse_txt_partial[idx] == ")":
count -= 1
if count == 0:
partition_indices.append(idx + 1)
partitions = []
part_idx_prev = 0
for i, part_idx in enumerate(partition_indices):
partitions.append(parse_txt_partial[part_idx_prev:part_idx])
part_idx_prev = part_idx
else:
temp = parse_txt_partial.split(" ")
name_const = temp[0]
partitions = [temp[1]]
return name_const, partitions
# constructs constituency tree from the parse string
@staticmethod
def contruct_tree_from_parse(parse_txt, node):
if parse_txt.startswith("("):
phrase_name, divisions = Sentence.get_subtrees(parse_txt)
if node is None:
node = Node()
node.root = True
node.label = phrase_name
if phrase_name in NON_TERMINALS:
for phrase in divisions:
if phrase.strip() == "":
continue
node_temp = Node()
node_temp.parent = node
node.children.append(
Sentence.contruct_tree_from_parse(phrase, node_temp)
)
else:
node.terminal = True
node.phrase = divisions[0]
return node
# only used for debugging
@staticmethod
def print_tree(tree):
print(tree.label)
print(tree.phrase)
print(tree.start_idx)
print(tree.end_idx)
for child in tree.children:
Sentence.print_tree(child)
# remove single child nodes
@staticmethod
def reduce_tree(tree):
while len(tree.children) == 1:
tree = tree.children[0]
children = []
for child in tree.children:
child = Sentence.reduce_tree(child)
children.append(child)
tree.children = children
return tree
@staticmethod
def assign_phrases(tree, phrase_start_idx):
if tree.terminal:
tree.start_idx = phrase_start_idx
tree.end_idx = phrase_start_idx + len(
tree.phrase.strip().split(" ")
)
return tree.phrase
else:
phrase = ""
phrase_idx_add = 0
for child in tree.children:
child_phrase = Sentence.assign_phrases(
child, phrase_start_idx + phrase_idx_add
).strip()
child.start_idx = phrase_start_idx + phrase_idx_add
phrase_idx_add += len(child_phrase.strip().split(" "))
child.end_idx = phrase_start_idx + phrase_idx_add
child.phrase = child_phrase
phrase += " " + child_phrase
phrase = phrase.strip()
return phrase
|
# Error handling
def fatal_error(error):
"""Print out the error message that gets passed, then quit the program.
Inputs:
error = error message text
:param error: str
:return:
"""
raise RuntimeError(error)
|
# Problem:
# In one cinema hall, the chairs are arranged in rectangular shape in r row and c columns.
# There are three types of projections with Tickets at different rates:
# -> Premiere - Premiere, at a price of 12.00 BGN.
# -> Normal - standard screening, at a price of 7.50 leva.
# -> Discount - screening for children, students and students at a reduced price of 5.00 BGN.
# Write a program that introduces a screen type, number of rows, and number of columns in the room
# numbers) and calculates total ticket revenue in a full room.
# Print the result in a format such as the examples below, with 2 decimal places.
projections_Type = input()
row = int(input())
cow = int(input())
tickets_Price = 0
total_Price = 0
if projections_Type == "Premiere":
tickets_Price = 12
elif projections_Type == "Normal":
tickets_Price = 7.5
elif projections_Type == "Discount":
tickets_Price = 5
total_Price = tickets_Price * (row * cow)
print("{0:.2f} leva".format(total_Price))
|
# Title : TODO
# Objective : TODO
# Created by: Wenzurk
# Created on: 2018/2/19
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets) |
class NotInServer(Exception): # The whole point of this is to do nothing
def __init__(self):
pass
class NotWhitelisted(Exception):
def __init__(self):
pass
|
# Exercício Python 096:
# Faça um programa que tenha uma função chamada área(),
# que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.
def area(l, c):
a = l * c
print(f'A área de um terreno {l}x{c} é de {a}m².')
print('Controle de Terrenos')
print('-' * 20)
x = float(input('LARGURA (m): '))
y = float(input('COMPRIMENTO (m): '))
area(x, y)
|
class Pagination(object):
count = None
def paginate_queryset(self, request, queryset, handler):
raise NotImplementedError
def get_paginated_response(self, request, data):
raise NotImplementedError
|
# hello world
def print_lol(the_list, indent=false, level=0):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item, indent, level+1)
else:
if indent:
for tab_stop in range(level):
print("\t", end=' ')
print(each_item)
|
def read_samplesCSV(spls):
# reads in samples.csv file, format: Batch,Lane,Barcode,Sample,Alignments,ProviderName,Patient
hdr_check = ['Batch', 'Lane', 'Barcode', 'Sample', 'Alignments', 'ProviderName', 'Patient']
switch = "on"
file = open(spls, 'r')
list_path = []
list_splID = []
list_providerNames = []
list_refG = []
list_patient = []
for line in file:
line = line.strip('\n').split(',')
# Test Header. Note: Even when header wrong code continues (w/ warning), but first line not read.
if switch == "on":
if (line == hdr_check):
print("Passed CSV header check")
else:
Warning("CSV did NOT pass header check! Code continues, but first line ignored")
switch = "off"
continue
# build lists
list_path.append(line[0])
list_splID.append(line[3])
list_refG.append(line[4])
list_providerNames.append(line[5])
list_patient.append(line[6])
return [list_path,list_splID,list_refG,list_providerNames,set(list_patient)] # set(list_patient) provides only unique subject IDs
def read_samples_caseCSV(spls):
# reads in samples_case.csv file, format: Path,Sample,ReferenceGenome,Outgroup
hdr_check = ['Path','Sample','ReferenceGenome','Outgroup']
switch = "on"
file = open(spls, 'r')
list_path = []
list_splID = []
list_refG = []
list_outgroup = []
for line in file:
line = line.strip('\n').split(',')
# Test Header. Note: Even when header wrong code continues (w/ warning), but first line not read.
if switch == "on":
if (line == hdr_check):
print("Passed CSV header check")
else:
Warning("CSV did NOT pass header check! Code continues, but first line ignored")
switch = "off"
continue
# build lists
list_path.append(line[0])
list_splID.append(line[1])
list_refG.append(line[2])
list_outgroup.append(line[3])
return [list_path,list_splID,list_refG,list_outgroup]
|
while True:
n_peer = int(input())
counter = 1
for i in range(2, n_peer):
if n_peer%i == 1:
print(i, end=' ')
counter += 1
print()
print(counter) |
def read_next(*args):
for el in args:
for i in el:
yield i
for item in read_next('string', (2,), {'d': 1, 'i': 2, 'c': 3, 't': 4}):
print(item, end='')
|
# ---------------------------------------------------------- #
# Title: Listing 07
# Description: A module of multiple processing classes
# ChangeLog (Who,When,What):
# RRoot,1.1.2030,Created started script
# ---------------------------------------------------------- #
if __name__ == "__main__":
raise Exception("This file is not meant to ran by itself")
class FileProcessor:
"""Processes data to and from a file and a list of objects:
methods:
save_data_to_file(file_name,list_of_objects):
read_data_from_file(file_name): -> (a list of objects)
changelog: (When,Who,What)
RRoot,1.1.2030,Created Class
"""
@staticmethod
def save_data_to_file(file_name: str, list_of_objects: list):
""" Write data to a file from a list of object rows
:param file_name: (string) with name of file
:param list_of_objects: (list) of objects data saved to file
:return: (bool) with status of success status
"""
success_status = False
try:
file = open(file_name, "w")
for row in list_of_objects:
file.write(row.__str__() + "\n")
file.close()
success_status = True
except Exception as e:
print("There was a general error!")
print(e, e.__doc__, type(e), sep='\n')
return success_status
@staticmethod
def read_data_from_file(file_name: str):
""" Reads data from a file into a list of object rows
:param file_name: (string) with name of file
:return: (list) of object rows
"""
list_of_rows = []
try:
file = open(file_name, "r")
for line in file:
row = line.split(",")
list_of_rows.append(row)
file.close()
except Exception as e:
print("There was a general error!")
print(e, e.__doc__, type(e), sep='\n')
return list_of_rows
class DatabaseProcessor:
pass
# TODO: Add code to process to and from a database
|
"""
4 - Fizz Buzz - Se o parâmetro da função for divisível por 3, returne Fizz,
se o parâmetro da função for divisível por 5, retorne buzz. Se o parâmetro da função for
fivissível por 5 e por 3, return FizzBuzz, caso contrário, retorne o número enviado.
"""
def fizzBuzz(valor):
if valor % 3 == 0 and valor % 5 == 0:
return 'FizzBuzz'
if valor % 5 == 0:
return 'Buzz'
if valor % 3 == 0:
return 'Fizz'
return f'{valor}'
print(fizzBuzz(15))
print(fizzBuzz(7))
print(fizzBuzz(10))
print(fizzBuzz(9)) |
califications = {
'anartz': 9.99,
'mikel': 5.01,
'aitor': 1.22,
'maite': 10,
'miren': 7.8,
'olatz': 9.89
}
pass_students = []
# Obtener clave, valor elemento a elemento
for key, value in califications.items():
if (value >= 5): pass_students.append(key)
print("Notas del curso:")
print(califications)
print("Aprobados:")
print(pass_students)
|
def qsort(arr):
if len(arr) <= 1:
return arr
pivot = arr.pop()
greater, lesser = [], []
for item in arr:
if item > pivot:
greater.append(item)
else:
lesser.append(item)
return qsort(lesser) + [pivot] + qsort(greater)
|
class A():
def load_data(self):
return [1,2,3,4,5]
def __getitem__(self, item):
a = self.load_data()
return a[item]
class B(A):
def load_data(self):
return ['a','b','c']
a = B()
print(a[1]) |
"""
Fixes the extra commas in some of the regions in the Russian data.
"""
file = open("data/2018-Russia-election-data.csv", "r", encoding="utf-8")
TEXT = ""
for line in file:
if len(line.split(",")) == 5:
last_char_index = line.rfind(",")
new_line = line[:last_char_index] + "" + line[last_char_index + 1:]
TEXT += new_line
else:
TEXT += line
file.close()
x = open("data/2018-Russia-election-data.csv", "w", encoding="utf-8")
x.writelines(TEXT)
x.close()
|
class CidrMaskConvert:
def cidr_to_mask(self, val):
val = int(val)
if 1 > val or val > 32:
return "Invalid"
val = '.'.join([str((0xffffffff << (32 - val) >> i) & 0xff)
for i in [24, 16, 8, 0]])
return val
def mask_to_cidr(self, val):
mask_list = val.split(".")
check = IpValidate().ipv4_validation(val)
binary = [bin(int(i))[2:].count('1') for i in mask_list]
if not check or binary[0] ==3:
return 'Invalid'
val = sum(binary) if sum(binary) > 0 else 'Invalid'
return str(val)
class IpValidate:
def ipv4_validation(self, val):
octets = val.split(".")
return len(octets) == 4 and \
all(o.isdigit() and 0 <= int(o) < 256 for o in octets) |
# name = input("Enter your name: ")
# age = input("Enter your age: ")
# print("Hello " + name + "! You are " + age)
# create a calculator, be careful the input is a string
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
# int does not work for decimal numbers
result1 = int(num1) + int(num2)
result2 = float(num1) + float(num2)
result = int(num1) + int(num2)
print(result1)
print(result2)
print(result)
|
class Solution:
# @param A : string
# @return an integer
def solve(self, s):
n = len(s)
lps = [0]*n
i,l = 1,0
while i < n:
if s[i]==s[l]:
lps[i] = l+1
l+=1
i+=1
elif l > 0:
l = lps[l-1]
else:
i+=1
ans = n
for i in range(n):
x = i-lps[i]
if lps[i]>=x:
ans = n-i-1
return ans
|
"""
Platform for DS-AIR of Daikin
https://www.daikin-china.com.cn/newha/products/4/19/DS-AIR/
"""
|
# formatting
menu = [
["egg", "bacon"],
["egg", "bacon", "sausage"],
["egg", "spam"],
["egg", "spam", "tomato"],
["egg", "spam", "tomato", "spam", "tomato"],
]
for meal in menu:
if "spam" in meal:
print("Yeah, not there")
else:
print("{0} has the spam score of {1}"
.format(meal, meal.count("spam")))
# challenge: print all the values just not spam
for meal in menu:
if "spam" in meal:
meal.remove("spam")
print(meal)
|
class RandomResponseFrequency:
"""A RandomResponseFrequency is an object used to define frequency over a range of modes.
This page discusses:
Attributes
----------
lower: float
A Float specifying the lower limit of the frequency range in cycles per time.
upper: float
A Float specifying the upper limit of the frequency range in cycles per time.
nCalcs: int
An Int specifying the number of points between eigenfrequencies at which the response
should be calculated.
bias: float
A Float specifying the bias parameter.
Notes
-----
This object can be accessed by:
.. code-block:: python
import step
mdb.models[name].steps[name].freq[i]
"""
# A Float specifying the lower limit of the frequency range in cycles per time.
lower: float = None
# A Float specifying the upper limit of the frequency range in cycles per time.
upper: float = None
# An Int specifying the number of points between eigenfrequencies at which the response
# should be calculated.
nCalcs: int = None
# A Float specifying the bias parameter.
bias: float = None
|
#
# coding=utf-8
def normalize(block):
""" Normalize a block of text to perform comparison.
Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace
from each line.
"""
assert isinstance(block, str)
block = block.strip('\n')
return [line.rstrip() for line in block.splitlines()]
def run_cmd(app, cmd):
""" Clear StdSim buffer, run the command, extract the buffer contents, """
app.stdout.clear()
app.onecmd_plus_hooks(cmd)
out = app.stdout.getvalue()
app.stdout.clear()
return normalize(out)
|
"""
Swap two variables' contents without using a 3rd variable.
Not really useful in Python since you can do: `a, b = b, a`.
Author:
Christos Nitsas
(nitsas)
(nitsas.chris)
Language:
Python 3(.4)
Date:
April, 2016
"""
__all__ = ['xor_swap']
def xor_swap(a, b):
a ^= b # invert those bits of a where b has 1s
b ^= a # reverse the above and store in b
# current b is the original a
# current a still has the result of the 1st operation
# but viewed differently:
# current a is original b with inverted bits where original a had 1s
a ^= b # use b (original a) to invert 1st operation & get original b
return a, b
|
class Solution(object):
def strWithout3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
if A >= 2*B:
return 'aab'* B + 'a'* (A-2*B)
elif A >= B:
return 'aab' * (A-B) + 'ab' * (2*B - A)
elif B >= 2*A:
return 'bba' * A + 'b' *(B-2*A)
else:
return 'bba' * (B-A) + 'ab' * (2*A - B)
'''
class Solution {
public String strWithout3a3b(int A, int B) {
StringBuilder res = new StringBuilder(A + B);
char a = 'a', b = 'b';
int i = A, j = B;
if (B > A) { a = 'b'; b = 'a'; i = B; j = A; }
while (i-- > 0) {
res.append(a);
if (i > j) { res.append(a); --i; }
if (j-- > 0) res.append(b);
}
return res.toString();
}
}
''' |
class Database:
'''
A generic database that must implement at least the two methods declared below.
The specific implementation of the database is left to Admin, but it can be any typical SQL or other database so long as it can implement a table where the key is a Hashable type and the value is Any type.
A database instance is exposed to the origin server (and is only exposed to the origin server) by passing the instance to the Origin constructor.
'''
def get(self, key):
'''
Translates to a query where the key is the given parameter key.
'''
pass
def put(self, key, value):
'''
Translates to a database insert if the key is not already in the database, or a database update if the key is already in the database.
'''
pass |
# 190. Reverse Bits
class Solution:
def reverseBits(self, n: int) -> int:
bin_num = format(n, 'b')
res = '0' * (32-len(bin_num)) + bin_num
return int('0b' + res[::-1], 2)
|
T = int(input())
a=list(map(int,input().split()))
for i in range(0,T):
b = input()
if(b == '+'):
print(a[0]+a[1])
elif(b == '-'):
print(a[0]-a[1])
elif(b == '*'):
print(a[0]*a[1])
elif(b == '/'):
print(a[0]//a[1])
elif(b == '%'):
print(a[0]%a[1])
|
'''
Quadrado
Um quadrado quase mágico, de dimensões N N, é um quadrado que obedece à seguinte condição. Existe um número inteiro positivo M tal que: para qualquer linha, a soma dos números da linha é igual a M; e para qualquer coluna, a soma dos números da coluna é também igual a M. O quadrado seria mágico, e não apenas quase mágico, se a soma das
diagonais também fosse M. Por exemplo, a figura abaixo, parte (a), apresenta um quadrado quase mágico onde M = 21.
Laura construiu um quadrado quase mágico e alterou, propositalmente, um dos números!
Nesta tarefa, você deve escrever um programa que, dado o quadrado quase mágico alterado por Laura, descubra qual era o número original antes da alteração e qual número foi colocado no lugar. Por exemplo, na parte (b) da figura, o número original era 1, que Laura alterou para 7.
Entrada
A primeira linha da entrada contém apenas um número N, representando a dimensão do quadrado. As N linhas seguintes contêm, cada uma, N números inteiros, definindo o quadrado. A entrada é garantidamente um quadrado quase mágico onde exatamente um número foi alterado.
Saída
Seu programa deve imprimir apenas uma linha contendo dois números: primeiro o número
original e depois o número que Laura colocou no seu lugar.
Restrições
• 3<=N<=50; e o valor de todos os números está entre 1 e 10000
'''
lado = int(input()) #qntdd lados
square = [list(map(int,input().split())) for x in range(lado)] #formando linhas da matriz que forma o quadrado.
listasomas = []#lista p guardar somas e desc a soma True.
for e in square:
listasomas.append(sum(e))
b = 0 #indica a linha p coordenada errada do final
somaT = 0;somaF = 0
for elem in listasomas: #cada soma corresponde ao msm num da linha
if listasomas.count(elem) == 1 :
somaF = elem #soma equivocada
linha = b
elif listasomas.count(elem) != 1 :
somaT = elem #valor correto da soma do sqr magico
if somaT!=0 and somaF!=0:
break
b+=1
#--------------------------------------------------------------------------------------------------------------------------
#descobrir coluna
j = 0;i = 0;s = 0
while j < lado:
if i < lado:
s += square[i][j]
i+=1
else:
if s == somaF:
break
j+=1;i = 0;s = 0
coordenadaerrada = square[linha][j]
if somaF > somaT:
a = somaF - somaT #Valor a diminuir do numero erroneo para sair na primeira parte da saida.
print(coordenadaerrada-a, coordenadaerrada)
else:
a = somaT - somaF
print(coordenadaerrada+a, coordenadaerrada)
|
name = input("whats your name\n")
bebe = "october"
print(bebe)
print("hi")
print (name)
print("?!")
print("tova")
# pavtuk smiatam
h = 2
c = 2
d = h*2 + c
print(d) |
"""
Connected components and graph resilience
"""
def bfs_visited(ugraph, start_node):
"""
Takes the undirected graph ugraph and the node start_node and returns
the set consisting of all nodes that are visited by a breadth-first search
that starts at start_node.
"""
visited = set()
stack = [start_node]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(ugraph[vertex] - visited)
return visited
def cc_visited(ugraph):
"""
Takes the undirected graph ugraph and returns a list of sets,
where each set consists of all the nodes (and nothing else)
in a connected component, and there is exactly one set in the list
for each connected component in ugraph and nothing else.
"""
ccc = []
remaining_nodes = ugraph.keys()
while remaining_nodes:
node = remaining_nodes.pop()
www = bfs_visited(ugraph, node)
if www not in ccc:
ccc.append(www)
return ccc
def largest_cc_size(ugraph):
"""
Takes the undirected graph ugraph and returns the size (an integer)
of the largest connected component in ugraph.
"""
ccc = cc_visited(ugraph)
max_cc = 0
for elem in ccc:
if len(elem) > max_cc:
max_cc = len(elem)
return max_cc
def compute_resilience(ugraph, attack_order):
"""
Takes the undirected graph ugraph, a list of nodes attack_order
and iterates through the nodes in attack_order. For each node in the list,
the function removes the given node and its edges from the graph and then
computes the size of the largest connected component for the resulting graph.
"""
resilience = []
resilience.append(largest_cc_size(ugraph))
for removed_node in attack_order:
del ugraph[removed_node]
for node in ugraph:
if removed_node in ugraph[node]:
ugraph[node].remove(removed_node)
resilience.append(largest_cc_size(ugraph))
return resilience
GRAPH0 = {0: set([1]),
1: set([0, 2]),
2: set([1, 3]),
3: set([2])}
GRAPH1 = {0: set([1, 2, 3, 4]),
1: set([0, 2, 3, 4]),
2: set([0, 1, 3, 4]),
3: set([0, 1, 2, 4]),
4: set([0, 1, 2, 3])}
GRAPH2 = {1: set([2, 4, 6, 8]),
2: set([1, 3, 5, 7]),
3: set([2, 4, 6, 8]),
4: set([1, 3, 5, 7]),
5: set([2, 4, 6, 8]),
6: set([1, 3, 5, 7]),
7: set([2, 4, 6, 8]),
8: set([1, 3, 5, 7])}
GRAPH3 = {0: set([]),
1: set([2]),
2: set([1]),
3: set([4]),
4: set([3])}
GRAPH4 = {0: set([1, 2, 3, 4]),
1: set([0]),
2: set([0]),
3: set([0]),
4: set([0]),
5: set([6, 7]),
6: set([5]),
7: set([5])}
GRAPH5 = {"dog": set(["cat"]),
"cat": set(["dog"]),
"monkey": set(["banana"]),
"banana": set(["monkey", "ape"]),
"ape": set(["banana"])}
GRAPH6 = {1: set([2, 5]),
2: set([1, 7]),
3: set([4, 6, 9]),
4: set([3, 6, 9]),
5: set([1, 7]),
6: set([3, 4, 9]),
7: set([2, 5]),
9: set([3, 4, 6])}
GRAPH7 = {0: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
1: set([0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
2: set([0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
3: set([0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
4: set([0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
5: set([0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
6: set([0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
7: set([0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
8: set([0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
9: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
10: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
11: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
12: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
13: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
14: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
15: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
16: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
17: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
18: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
19: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
20: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
21: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
22: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
23: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
24: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
25: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
26: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
27: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
28: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
29: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
30: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
31: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
32: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
33: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
34: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
35: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
36: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
37: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
38: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
39: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
40: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49]),
41: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49]),
42: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49]),
43: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49]),
44: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49]),
45: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49]),
46: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 48, 49]),
47: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 48, 49]),
48: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 49]),
49: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48])}
GRAPH8 = {0: set([]),
1: set([]),
2: set([]),
3: set([]),
4: set([]),
5: set([]),
6: set([]),
7: set([]),
8: set([]),
9: set([]),
10: set([]),
11: set([]),
12: set([]),
13: set([]),
14: set([]),
15: set([]),
16: set([]),
17: set([]),
18: set([]),
19: set([]),
20: set([]),
21: set([]),
22: set([]),
23: set([]),
24: set([]),
25: set([]),
26: set([]),
27: set([]),
28: set([]),
29: set([]),
30: set([]),
31: set([]),
32: set([]),
33: set([]),
34: set([]),
35: set([]),
36: set([]),
37: set([]),
38: set([]),
39: set([]),
40: set([]),
41: set([]),
42: set([]),
43: set([]),
44: set([]),
45: set([]),
46: set([]),
47: set([]),
48: set([]),
49: set([])}
GRAPH9 = {0: set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
1: set([0, 3, 4, 7, 8, 9, 10]),
2: set([0, 5, 6, 11, 12, 13, 14]),
3: set([0, 1, 7, 8]),
4: set([0, 1, 9, 10]),
5: set([0, 2, 11, 12]),
6: set([0, 2, 13, 14]),
7: set([0, 1, 3]),
8: set([0, 1, 3]),
9: set([0, 1, 4]),
10: set([0, 1, 4]),
11: set([0, 2, 5]),
12: set([0, 2, 5]),
13: set([0, 2, 6]),
14: set([0, 2, 6])}
GRAPH10 = {0: set([1, 2]),
1: set([0]),
2: set([0, 3, 4]),
3: set([2]),
4: set([2, 5, 6,]),
5: set([4]),
6: set([4, 7, 8]),
7: set([6]),
8: set([6, 9 , 10]),
9: set([8]),
10: set([8, 11, 12]),
11: set([10]),
12: set([10,13, 14]),
13: set([12]),
14: set([12, 15, 16]),
15: set([14]),
16: set([14, 17, 18]),
17: set([16]),
18: set([16, 19, 20]),
19: set([18]),
20: set([18])}
#print cc_visited(GRAPH0)
#print cc_visited(GRAPH1)
#print cc_visited(GRAPH2)
#print cc_visited(GRAPH3)
#print cc_visited(GRAPH4)
#print cc_visited(GRAPH5)
#print cc_visited(GRAPH6)
#print cc_visited(GRAPH7)
#print cc_visited(GRAPH8)
#print cc_visited(GRAPH9)
#print cc_visited(GRAPH10)
#print bfs_visited(GRAPH0, 0)
#print bfs_visited(GRAPH0, 1)
#print bfs_visited(GRAPH0, 2)
#print bfs_visited(GRAPH0, 3)
#print largest_cc_size(GRAPH0)
#print compute_resilience(GRAPH0, [1, 2])
|
calories_per_click = dict([(str(index + 1), int(calories)) for index, calories in enumerate(input().split())])
total_calories_burned = sum([calories_per_click[c] for c in input()])
print(total_calories_burned)
|
# Notation x.y.z:
# x: major release
# y: minor release / new feature
# z: build number / bug maintenance
version = '0.5.1'
|
"""
Utilities for VCF files.
"""
def walk_together(*readers, **kwargs):
"""
Simultaneously iteratate over two or more VCF readers. For each
genomic position with a variant, return a list of size equal to the number
of VCF readers. This list contains the VCF record from readers that have
this variant, and None for readers that don't have it.
The caller must make sure that inputs are sorted in the same way and use the
same reference otherwise behaviour is undefined.
Args:
vcf_record_sort_key: function that takes a VCF record and returns a
tuple that can be used as a key for comparing and sorting VCF
records across all readers. This tuple defines what it means for two
variants to be equal (eg. whether it's only their position or also
their allele values), and implicitly determines the chromosome
ordering since the tuple's 1st element is typically the chromosome
name (or calculated from it).
"""
if 'vcf_record_sort_key' in kwargs:
get_key = kwargs['vcf_record_sort_key']
else:
get_key = lambda r: (r.CHROM, r.POS) #, r.REF, r.ALT)
nexts = []
for reader in readers:
try:
nexts.append(reader.next())
except StopIteration:
nexts.append(None)
min_k = (None,) # keep track of the previous min key's contig
while any([r is not None for r in nexts]):
next_idx_to_k = dict(
(i, get_key(r)) for i, r in enumerate(nexts) if r is not None)
keys_with_prev_contig = [
k for k in next_idx_to_k.values() if k[0] == min_k[0]]
if any(keys_with_prev_contig):
min_k = min(keys_with_prev_contig) # finish previous contig
else:
min_k = min(next_idx_to_k.values()) # move on to next contig
min_k_idxs = set([i for i, k in next_idx_to_k.items() if k == min_k])
yield [nexts[i] if i in min_k_idxs else None for i in range(len(nexts))]
for i in min_k_idxs:
try:
nexts[i] = readers[i].next()
except StopIteration:
nexts[i] = None
def trim_common_suffix(*sequences):
"""
Trim a list of sequences by removing the longest common suffix while
leaving all of them at least one character in length.
Standard convention with VCF is to place an indel at the left-most
position, but some tools add additional context to the right of the
sequences (e.g. samtools). These common suffixes are undesirable when
comparing variants, for example in variant databases.
>>> trim_common_suffix('TATATATA', 'TATATA')
['TAT', 'T']
>>> trim_common_suffix('ACCCCC', 'ACCCCCCCC', 'ACCCCCCC', 'ACCCCCCCCC')
['A', 'ACCC', 'ACC', 'ACCCC']
"""
if not sequences:
return []
reverses = [seq[::-1] for seq in sequences]
rev_min = min(reverses)
rev_max = max(reverses)
if len(rev_min) < 2:
return sequences
for i, c in enumerate(rev_min[:-1]):
if c != rev_max[i]:
if i == 0:
return sequences
return [seq[:-i] for seq in sequences]
return [seq[:-(i + 1)] for seq in sequences]
|
class EvaluateConfig:
def __init__(self):
self.game_num = 100
self.replace_rate = 0.55
self.play_config = PlayConfig()
self.play_config.c_puct = 1
self.play_config.change_tau_turn = 0
self.play_config.noise_eps = 0
self.evaluate_latest_first = True
class PlayDataConfig:
def __init__(self):
self.nb_game_in_file = 100
self.max_file_num = 10
self.save_policy_of_tau_1 = True
class PlayConfig:
def __init__(self):
self.simulation_num_per_move = 10
self.share_mtcs_info_in_self_play = True
self.reset_mtcs_info_per_game = 10
self.thinking_loop = 1
self.logging_thinking = False
self.c_puct = 5
self.noise_eps = 0.25
self.dirichlet_alpha = 0.5
self.dirichlet_noise_only_for_legal_moves = True
self.change_tau_turn = 10
self.virtual_loss = 3
self.prediction_queue_size = 16
self.parallel_search_num = 4
self.prediction_worker_sleep_sec = 0.00001
self.wait_for_expanding_sleep_sec = 0.000001
self.resign_threshold = -0.8
self.allowed_resign_turn = 30
self.disable_resignation_rate = 0.1
self.false_positive_threshold = 0.05
self.resign_threshold_delta = 0.01
self.use_newest_next_generation_model = True
self.simulation_num_per_move_schedule = [
(300, 8),
(500, 20),
]
class TrainerConfig:
def __init__(self):
self.batch_size = 2048
self.min_data_size_to_learn = 100
self.epoch_to_checkpoint = 1
self.start_total_steps = 0
self.save_model_steps = 200
self.lr_schedules = [
(0, 0.01),
(100000, 0.001),
(200000, 0.0001)
]
class ModelConfig:
cnn_filter_num = 16
cnn_filter_size = 3
res_layer_num = 1
l2_reg = 1e-4
value_fc_size = 16
|
class FakeSingleton:
def __init__(self, payload):
self._payload = payload
def instance(self):
return self._payload
|
""" This module has various utilities for managing the CTCP protocol. It is
is responsible for parsing CTCP data and making data ready to be sent
via CTCP.
"""
X_DELIM = "\x01"
M_QUOTE = "\x10"
X_QUOTE = "\\"
commands = ["ACTION", "VERSION", "USERINFO", "CLIENTINFO", "ERRMSG", "PING",
"TIME", "FINGER"]
_ctcp_level_quote_map = [
("\\", "\\\\"),
("\x01", "\\a")
]
_low_level_quote_map = [
("\x10", "\x10\x10"),
("\x00", "\x100"),
("\n", "\x10n"),
("\r", "\x10r")
]
def tag(message):
""" Wraps an X-DELIM (``\\x01``) around a message to indicate that it needs
to be CTCP tagged.
"""
return X_DELIM + message + X_DELIM
def low_level_quote(text):
""" Performs a low-level quoting in order to escape characters that could
otherwise not be represented in the typical IRC protocol.
"""
# TODO: Strip cases where M_QUOTE is on its own
for (search, replace) in _low_level_quote_map:
text = text.replace(search, replace)
return text
def low_level_dequote(text):
""" Performs the complete opposite of ``low_level_quote`` as it converts the
quoted character back to their original forms.
"""
# TODO: Strip cases where M_QUOTE is on its own
for (replace, search) in reversed(_low_level_quote_map):
text = text.replace(search, replace)
return text
def quote(text):
""" This is CTCP-level quoting. It's only purpose is to quote out ``\\x01``
characters so they can be represented INSIDE tagged CTCP data.
"""
for (search, replace) in _ctcp_level_quote_map:
text = text.replace(search, replace)
return text
def dequote(text):
""" Performs the opposite of ``quote()`` as it will essentially strip the
quote character.
"""
for (replace, search) in reversed(_ctcp_level_quote_map):
text = text.replace(search, replace)
return text
def extract(message):
""" Splits a message between the actual message and any CTCP requests.
It returns a 2-part tuple of ``(message, ctcp_requests)`` where
``ctcp_requests`` is a list of requests.
"""
stripped_message = []
ctcp_requests = []
in_tag = False
index = 0
while index < len(message):
if in_tag:
ctcp_request = []
while index < len(message) and message[index] != X_DELIM:
ctcp_request.append(message[index])
index += 1
ctcp_requests.append(_parse_request("".join(ctcp_request)))
in_tag = False
else:
while index < len(message) and message[index] != X_DELIM:
stripped_message.append(message[index])
index += 1
in_tag = True
index += 1
return "".join(stripped_message), ctcp_requests
def _parse_request(section):
""" This function takes a CTCP-tagged section of a message and breaks it in
to a two-part tuple in the form of ``(command, parameters)`` where
``command`` is a string and ``parameters`` is a tuple.
"""
sections = section.split(" ")
if len(sections) > 1:
command, params = (sections[0], tuple(sections[1:]))
else:
command, params = (sections[0], tuple())
return command, params |
'''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to check multiple ifs?
You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine.
There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this.
Instead, you can use what is called the "elif" here in python... which is short for "else if"
'''
x = 5
y = 10
z = 22
# first run the default like this, then
# change the x > y to x < y...
# then change both of these to an ==
if x > y:
print('x is greater than y')
elif x < z:
print('x is less than z')
else:
print('if and elif never ran...')
|
steps = 363
buffer = [0]
currentValue = 1
currentPosition = 0
for i in range(1, 2018):
currentPosition = (currentPosition+steps)%len(buffer)
buffer.insert(currentPosition+1, currentValue)
currentValue += 1
currentPosition += 1
print(buffer[(currentPosition+1)%len(buffer)])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'cprint'
__author__ = 'JieYuan'
__mtime__ = '19-1-10'
"""
class Cprint(object):
def __init__(self):
colors = ['green', 'yellow', 'black', 'cyan', 'blue', 'red', 'white', 'purple']
self.fc = dict(zip(colors, range(40, 97)))
self.bc = dict(zip(colors, range(90, 97)))
def cstring(self, s='Hello World !', bg='blue', fg='', mode=1):
"""
:param s: string
:param fg/bg: foreground/background
'black', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white'
:param mode:
0(默认值)
1(高亮)
22(非粗体)
4(下划线)
24(非下划线)
5(闪烁)
25(非闪烁)
7(反显)
27(非反显)
https://www.cnblogs.com/hellojesson/p/5961570.html
:return:
"""
if fg:
string = '\033[%s;%s;%sm%s\033[0m' % (mode, self.fc[fg], self.bc[bg], s)
else:
string = '\033[%s;%sm%s\033[0m' % (mode, self.bc[bg], s)
return string
def cprint(self, s='Hello World !', bg='blue', fg='', mode=1):
print(self.cstring(s, bg, fg, mode))
c = Cprint()
cprint = c.cprint
cstring = c.cstring
if __name__ == '__main__':
Cprint().cprint()
|
quizzes = {
'moon': 'Most planets have at least one of this orbiting around.',
'black hole': "What comes in, never goes out.",
'sun': "Hot, hot, hot... It loves to be the center everything!.",
'elon musk': "He is a billionaire entrepreneur, philanthropist and visionary South-African-Canadian-American. Founder, CEO and CTO of SpaceX.",
'asteroid': 'Something fell from the sky and... R.I.P my fellow dinosaurs!',
"milky way": "Which galaxy is home to the Solar system?",
"pluto": "Which object lost its status as a planet in 2006?",
"a hypothetical reservoir for comets": "What is the Oort cloud?",
"venus": "What is the third brightest astronomical object in the sky?",
"2": "How many moons does Mars have?",
"galileo galilei": "Who discovered the four main moons of Jupiter in 1610?",
"polarity reverse of the sun": "What is the Solar Cycle?",
"a unit of measurement used to describe the expansion of the universe": "What is the Hubble constant?",
"helium": "Hydrogen and which other gas make up the majority of the Suns composition?",
"proxima centauri": "Which star is closest to the Sun?",
"asteroid": "Vesta is which type of heavenly body?",
"encke": "The comet with the shortest orbital period of 3.3 years is named what?",
"jupiter": "Which planet has the largest moon in the Solar system?",
"a highly magnetised rotating neutron star": "What is a pulsar?",
"4": "How many terrestrial planets are there in the Solar system?",
"88": "How many named constellations are there?",
"olympus mons": "What is the name of the largest volcano in the Solar system?",
"vega, deneb, altair": "Which three stars make the Summer Triangle?",
"eugene cernan": "Who was the last man on the Moon?",
"a powerful star explosion": "What is a supernova?",
"a measure of distance": "What is an astronomical unit?",
"a massive release of plasma from the sun": "What is a Coronal Mass Ejection?",
"2": "How many Ice giants are in the Solar system?",
"76 years": "What is the orbital period of Halley’s comet?",
"42km/s": "What is the escape velocity from the Solar system at the distance of Earth?",
"8": "How many planets there are in the Solar system?",
"hans lippershey": "Telescopes have significantly changed over time. Do you know who invented the first telescope though?",
"4": "How many planets with rings are there in our solar system?",
"180": "Approximately, how many moons are there in our solar system?",
"usually more expensive than reflecting telescopes": "Refractor telescopes are __",
"they could differentiate the planets from stars": "Before the first telescope was invented what were ancient astronomers able to learn about planets?",
"1975, venera 9": "When and which spacecraft did first send back surface images from a planet in our solar system?",
"venus": "Which was the first planet to be explored by a space probe?",
"606 days": "How long did it take for Pioneer 11 to reach Jupiter?",
"norton’s star atlas": "Which astronomy book for beginners was written by Ian Ridpath?",
"arthur c. clarke": "Who is the author of this famous quote: “I’m sure the universe is full of intelligent life. It’s just been too intelligent to come here.”"
} |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance
# {"feature": "Coupon", "instances": 51, "metric_value": 0.9931, "depth": 1}
if obj[0]>1:
# {"feature": "Occupation", "instances": 36, "metric_value": 0.9183, "depth": 2}
if obj[2]<=19:
# {"feature": "Education", "instances": 33, "metric_value": 0.8454, "depth": 3}
if obj[1]<=2:
# {"feature": "Distance", "instances": 26, "metric_value": 0.7063, "depth": 4}
if obj[3]<=2:
return 'True'
elif obj[3]>2:
return 'True'
else: return 'True'
elif obj[1]>2:
# {"feature": "Distance", "instances": 7, "metric_value": 0.9852, "depth": 4}
if obj[3]<=2:
return 'True'
elif obj[3]>2:
return 'False'
else: return 'False'
else: return 'False'
elif obj[2]>19:
return 'False'
else: return 'False'
elif obj[0]<=1:
# {"feature": "Occupation", "instances": 15, "metric_value": 0.8366, "depth": 2}
if obj[2]<=6:
# {"feature": "Education", "instances": 11, "metric_value": 0.9457, "depth": 3}
if obj[1]<=3:
# {"feature": "Distance", "instances": 10, "metric_value": 0.8813, "depth": 4}
if obj[3]<=1:
return 'False'
elif obj[3]>1:
return 'True'
else: return 'True'
elif obj[1]>3:
return 'True'
else: return 'True'
elif obj[2]>6:
return 'False'
else: return 'False'
else: return 'False'
|
class JSONWriter:
def __init__(self, alerts, row_parser):
self.alerts = alerts
self.row_parser = row_parser
def parse_alerts(self, vendor, url,product, webpage_name):
collection = list()
alerts_list = self.alerts
failed_count = 0
skipped_count = 0
for alert in alerts_list:
row = self.row_parser.parse(
alert, vendor, url,product, webpage_name)
if row == "Skipped":
skipped_count += 1
break
elif row is not None:
collection.append(row)
else:
failed_count += 1
return (collection, failed_count, skipped_count)
|
class Partisan_Gauge:
def __init__(self):
self.cultural_axis = 0
self.economic_axis = 0
self.authoritarian_axis = 0
def set_cultural_axis(self,cultural_axis):
self.cultural_axis = cultural_axis
def set_cultural_axis(self,cultural_axis):
self.cultural_axis = cultural_axis
def set_cultural_axis(self,cultural_axis):
self.cultural_axis = cultural_axis
class DogWhistles:
def __init__(self):
self.whistles = {}
def add_whistle(self, whistle_name, whistle_description, found_on_node):
whistle_name = str(whistle_name)
whistle_description = str(whistle_description)
self.whistles[whistle_name] = whistle_description
class ProperNouns:
def __init__(self):
self.proper_nouns = {}
def add_noun(self, noun_name, noun_description, found_on_node):
whistle_name = str(noun_name)
whistle_description = str(noun_description)
self.proper_nouns[noun_name] = noun_description
|
# Write your solution for 1.3 here!
n = 0
i = 1
while i < 10000:
n = n + i
i = i + 1
print(i)
|
"""Windchill module.
Connect to Windchill server, use workspaces (create/delete/list)
List files and checkout status.
"""
def authorize(client, user, password):
"""Set user's Windchill login/password.
Args:
client (obj): creopyson Client
user (str): user name
password (str): password
Returns:
None
"""
data = {"user": user, "password": password}
return client._creoson_post("windchill", "authorize", data)
def clear_workspace(client, workspace=None, filenames=None):
"""Clear a workspace on the active server.
Args:
client (obj):
creopyson Client
workspace (str, optionnal):
Workspace name. Default is current workspace.
filenames (str|list, optionnal):
List of files to delete from the workspace.
Default: All files are deleted.
Returns:
None
"""
active_workspace = client.windchill_get_workspace()
data = {"workspace": active_workspace}
if workspace:
data["workspace"] = workspace
if filenames:
data["filenames"] = filenames
return client._creoson_post("windchill", "clear_workspace", data)
def create_workspace(client, workspace, context_name):
"""Create a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
context_name (str): Context name
Returns:
None
"""
data = {"workspace": workspace, "context": context_name}
return client._creoson_post("windchill", "create_workspace", data)
def delete_workspace(client, workspace):
"""Delete a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
None
"""
data = {"workspace": workspace}
return client._creoson_post("windchill", "delete_workspace", data)
def file_checked_out(client, filename, workspace=None):
"""Check whether a file is checked out in a workspace on the active server.
Args:
client (obj):
creopyson Client
filename (str):
File name
workspace (str, optionnal):
Workspace name. Default is current workspace.
Returns:
Boolean: Whether the file is checked out in the workspace.
"""
active_workspace = client.windchill_get_workspace()
data = {"workspace": active_workspace, "filename": filename}
if workspace:
data["workspace"] = workspace
return client._creoson_post("windchill", "file_checked_out", data, "checked_out")
def get_workspace(client):
"""Retrieve the name of the active workspace on the active server.
Args:
client (obj): creopyson Client
Returns:
str: Active Workspace name.
"""
return client._creoson_post("windchill", "get_workspace", key_data="workspace")
def list_workspace_files(client, workspace=None, filename=None):
"""Get a list of files in a workspace on the active server.
Args:
client (obj):
creopyson Client
workspace (str, optionnal):
Workspace name. Default is current workspace.
filename (str, optional):
File name or search. Default is all files.
ex: `*.asm`, `screw_*.prt`
Returns:
list: List of files in the workspace correspnding to the data.
"""
active_workspace = client.windchill_get_workspace()
data = {"workspace": active_workspace, "filename": "*"}
if workspace:
data["workspace"] = workspace
if filename:
data["filename"] = filename
return client._creoson_post("windchill", "list_workspace_files", data, "filelist")
def list_workspaces(client):
"""Get a list of workspaces the user can access on the active server.
Args:
client (obj): creopyson Client
Returns:
list: List of workspaces
"""
return client._creoson_post("windchill", "list_workspaces", key_data="workspaces")
def server_exists(client, server_url):
"""Check whether a server exists.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
Boolean: Whether the server exists
"""
data = {"server_url": server_url}
return client._creoson_post("windchill", "server_exists", data, "exists")
def set_server(client, server_url):
"""Select a Windchill server.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
None
"""
data = {"server_url": server_url}
return client._creoson_post("windchill", "set_server", data)
def set_workspace(client, workspace):
"""Select a workspace on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
None
"""
data = {"workspace": workspace}
return client._creoson_post("windchill", "set_workspace", data)
def workspace_exists(client, workspace):
"""Check whether a workspace exists on the active server.
Args:
client (obj): creopyson Client
workspace (str): Workspace name
Returns:
Boolean: Whether the workspace exists
"""
data = {"workspace": workspace}
return client._creoson_post("windchill", "workspace_exists", data, "exists")
|
# Задача 2. Вариант 28.
#Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Эпикур. Не забудьте о том, что автор должен быть упомянут на отдельной строке.
# Цкипуришвили Александр
# 25.05.2016
print("Каждый уходит из жизни так, словно только что вошел.")
print("\n\t\t\t\t\t Эпикур")
input("нажимте Enter для выхода") |
with open('./6/input_a.txt', 'r') as f:
input = list(map(int,f.readline().strip().split(',')))
fish = list([0,0,0,0,0,0,0,0,0])
for i in range(0,8):
fish[i] = sum([1 for a in input if a == i])
def observe(days):
for d in range(0,days):
newfish = fish[0]
for i in range(0,8):
fish[i] = fish[i+1] + (newfish if i == 6 else 0)
fish[8] = newfish
return sum([a for a in fish])
print(f'Part A: after 80 days {observe(80)} lanternfish remaining')
print(f'Part B: after 256 days {observe(256-80)} lanternfish remaining') |
def center_text(*args, sep=' ', end='\n', file=None, flush=False):
text=''
for arg in args:
text += str(arg) + sep
left_margin = (80 - len(text)) // 2
print(" " * left_margin, text, end=end, file=file, flush=flush)
# calling the function
center_text("spams and eggs")
center_text(12)
center_text("first", "second", 3, 4)
|
"""
Design your implementation of the circular queue. The circular queue is a
linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to
the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the
spaces in front of the queue. In a normal queue, once the queue becomes
full, we cannot insert the next element even if there is a space in front
of the queue. But using the circular queue, we can use the space to store
new values.
Your implementation should support following operations:
MyCircularQueue(k): Constructor, set the size of the queue to be k.
Front: Get the front item from the queue. If the queue is empty, return -1.
Rear: Get the last item from the queue. If the queue is empty, return -1.
enQueue(value): Insert an element into the circular queue. Return true if
the operation is successful.
deQueue(): Delete an element from the circular queue. Return true if the
operation is successful.
isEmpty(): Checks whether the circular queue is empty or not.
isFull(): Checks whether the circular queue is full or not.
Example:
MyCircularQueue circularQueue = new MyCircularQueue(3);
// set the size to be 3
circularQueue.enQueue(1); // return true
circularQueue.enQueue(2); // return true
circularQueue.enQueue(3); // return true
circularQueue.enQueue(4); // return false, the queue is full
circularQueue.Rear(); // return 3
circularQueue.isFull(); // return true
circularQueue.deQueue(); // return true
circularQueue.enQueue(4); // return true
circularQueue.Rear(); // return 4
Note:
All values will be in the range of [0, 1000].
The number of operations will be in the range of [1, 1000].
Please do not use the built-in Queue library.
"""
#Difficulty: Medium
#52 / 52 test cases passed.
#Runtime: 100 ms
#Memory Usage: 14 MB
#Runtime: 100 ms, faster than 9.41% of Python3 online submissions for Design Circular Queue.
#Memory Usage: 14 MB, less than 5.26% of Python3 online submissions for Design Circular Queue.
class MyCircularQueue: # First time. Solved by myself without theory
def __init__(self, k: int):
self.k = k - 1
self.front = self.rear = -1
self.queue = [None] * k
def enQueue(self, value: int) -> bool:
r = False
if self.isFull():
return r
if self.rear == -1:
self.front += 1
self.rear += 1
self.queue[self.rear] = value
r = True
elif self.rear != self.k:
self.rear += 1
self.queue[self.rear] = value
r = True
elif self.rear == self.k and not self.isFull():
self.rear = 0
self.queue[self.rear] = value
r = True
return r
def deQueue(self) -> bool:
r = False
if self.front == -1 or self.isEmpty():
return r
elif self.front != self.k:
self.queue[self.front] = None
self.front += 1
if self.isEmpty():
self.front = -1
self.rear = -1
r = True
elif self.front == self.k and not self.isEmpty():
self.queue[self.front] = None
self.front = 0
r = True
return r
def Front(self) -> int:
if self.isEmpty():
self.front = -1
self.rear = -1
return self.front
return self.queue[self.front]
def Rear(self) -> int:
if self.isEmpty():
self.front = -1
self.rear = -1
return self.rear
return self.queue[self.rear]
def isEmpty(self) -> bool:
return True if self.queue.count(None) == self.k + 1 else False
def isFull(self) -> bool:
return True if None not in self.queue else False
|
#!/usr/bin/env python
# encoding: utf-8
name = "R_Addition_COm/groups"
shortDesc = u""
longDesc = u"""
"""
template(reactants=["COm", "Y_rad"], products=["YC.=O"], ownReverse=False)
reverse = "COM_Elimination_From_Carbonyl"
recipe(actions=[
['LOSE_PAIR', '*1', '1'],
['CHANGE_BOND', '*1', -1, '*3'],
['GAIN_PAIR', '*3', '1'],
['GAIN_RADICAL', '*1', '1'],
['FORM_BOND', '*1', 1, '*2'],
['LOSE_RADICAL', '*2', '1'],
])
entry(
index = 1,
label = "COm",
group =
"""
1 *1 C2tc u0 p1 c-1 {2,T}
2 *3 O4tc u0 p1 c+1 {1,T}
""",
kinetics = None,
)
entry(
index = 2,
label = "Y_rad",
group =
"""
1 *2 R u1
""",
kinetics = None,
)
entry(
index = 3,
label = "H_rad",
group =
"""
1 *2 H u1
""",
kinetics = None,
)
entry(
index = 4,
label = "O_rad",
group =
"""
1 *2 O u1
""",
kinetics = None,
)
entry(
index = 5,
label = "O_pri_rad",
group =
"""
1 *2 O u1 {2,S}
2 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 6,
label = "O_sec_rad",
group =
"""
1 *2 O u1 {2,S}
2 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 7,
label = "O_rad/NonDe",
group =
"""
1 *2 O u1 {2,S}
2 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 8,
label = "O_rad/OneDe",
group =
"""
1 *2 O u1 {2,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 9,
label = "Ct_rad",
group =
"""
1 *2 C u1 {2,T}
2 C u0 {1,T}
""",
kinetics = None,
)
entry(
index = 10,
label = "CO_rad",
group =
"""
1 *2 C u1 {2,D}
2 O u0 {1,D}
""",
kinetics = None,
)
entry(
index = 11,
label = "CO_pri_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 O u0 {1,D}
3 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 12,
label = "CO_sec_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 O u0 {1,D}
3 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 70,
label = "CS_rad",
group =
"""
1 *2 C u1 {2,D}
2 S u0 {1,D}
""",
kinetics = None,
)
entry(
index = 71,
label = "CS_pri_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 S u0 {1,D}
3 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 72,
label = "CS_sec_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 S u0 {1,D}
3 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 13,
label = "Cd_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 R u0 {1,S}
""",
kinetics = None,
)
entry(
index = 14,
label = "Cd_pri_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 15,
label = "Cd_sec_rad",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 16,
label = "Cd_rad/NonDe",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 17,
label = "Cd_rad/OneDe",
group =
"""
1 *2 C u1 {2,D} {3,S}
2 C u0 {1,D}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 18,
label = "Cb_rad",
group =
"""
1 *2 Cb u1 {2,B} {3,B}
2 [Cb,Cbf] u0 {1,B}
3 [Cb,Cbf] u0 {1,B}
""",
kinetics = None,
)
entry(
index = 19,
label = "Cs_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 R u0 {1,S}
3 R u0 {1,S}
4 R u0 {1,S}
""",
kinetics = None,
)
entry(
index = 20,
label = "C_methyl",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 21,
label = "C_pri_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 22,
label = "C_rad/H2/Cs",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cs u0 {1,S}
""",
kinetics = None,
)
entry(
index = 23,
label = "CH2CH3",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cs u0 {1,S} {5,S} {6,S} {7,S}
5 H u0 {4,S}
6 H u0 {4,S}
7 H u0 {4,S}
""",
kinetics = None,
)
entry(
index = 24,
label = "CH2CH2CH3",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cs u0 {1,S} {5,S} {6,S} {7,S}
5 H u0 {4,S}
6 H u0 {4,S}
7 C u0 {4,S} {8,S} {9,S} {10,S}
8 H u0 {7,S}
9 H u0 {7,S}
10 H u0 {7,S}
""",
kinetics = None,
)
entry(
index = 25,
label = "C_rad/H2/Cd",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cd u0 {1,S}
""",
kinetics = None,
)
entry(
index = 26,
label = "C_rad/H2/Ct",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Ct u0 {1,S}
""",
kinetics = None,
)
entry(
index = 27,
label = "C_rad/H2/Cb",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 Cb u0 {1,S}
""",
kinetics = None,
)
entry(
index = 28,
label = "C_rad/H2/CO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 CO u0 {1,S}
""",
kinetics = None,
)
entry(
index = 29,
label = "C_rad/H2/O",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 O u0 {1,S}
""",
kinetics = None,
)
entry(
index = 72,
label = "C_rad/H2/CS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 CS u0 {1,S}
""",
kinetics = None,
)
entry(
index = 73,
label = "C_rad/H2/S",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 H u0 {1,S}
4 S u0 {1,S}
""",
kinetics = None,
)
entry(
index = 30,
label = "C_sec_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 R!H u0 {1,S}
4 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 31,
label = "C_rad/H/NonDeC",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S}
4 Cs u0 {1,S}
""",
kinetics = None,
)
entry(
index = 32,
label = "CH(CH3)2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S} {5,S} {6,S} {7,S}
4 Cs u0 {1,S} {8,S} {9,S} {10,S}
5 H u0 {3,S}
6 H u0 {3,S}
7 H u0 {3,S}
8 H u0 {4,S}
9 H u0 {4,S}
10 H u0 {4,S}
""",
kinetics = None,
)
entry(
index = 33,
label = "C_rad/H/NonDeO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 O u0 {1,S}
4 [Cs,O] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 34,
label = "C_rad/H/CsO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S}
4 O u0 {1,S}
""",
kinetics = None,
)
entry(
index = 35,
label = "C_rad/H/O2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 O u0 {1,S}
4 O u0 {1,S}
""",
kinetics = None,
)
entry(
index = 74,
label = "C_rad/H/NonDeS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [S,C] u0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 75,
label = "C_rad/H/CsS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 Cs u0 {1,S}
4 S2s u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 76,
label = "C_rad/H/S2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 S u0 {1,S}
4 [O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 36,
label = "C_rad/H/OneDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 37,
label = "C_rad/H/OneDeC",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 38,
label = "C_rad/H/OneDeO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 O u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 77,
label = "C_rad/H/OneDeS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 S2s u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 39,
label = "C_rad/H/TwoDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 H u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 40,
label = "C_ter_rad",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 R!H u0 {1,S}
3 R!H u0 {1,S}
4 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 41,
label = "C_rad/NonDeC",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cs,O,S2s] u0 px c0 {1,S}
3 [Cs,O,S2s] u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 42,
label = "C_rad/Cs3",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 Cs u0 px c0 {1,S}
3 Cs u0 px c0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 43,
label = "C_rad/NDMustO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 O u0 px c0 {1,S}
3 [Cs,O] u0 px c0 {1,S}
4 [Cs,O] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 78,
label = "C_rad/NDMustS",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 S2s u0 px c0 {1,S}
3 [Cs,O,S2s] u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 44,
label = "C_rad/OneDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cs,O,S2s] u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 45,
label = "C_rad/OD_Cs2",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 Cs u0 px c0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 46,
label = "C_rad/ODMustO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 O u0 px c0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 47,
label = "C_rad/TwoDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 48,
label = "C_rad/TD_Cs",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 Cs u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 49,
label = "C_rad/TDMustO",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 O u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 50,
label = "C_rad/ThreeDe",
group =
"""
1 *2 C u1 {2,S} {3,S} {4,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
3 [Cd,Ct,Cb,CO,CS] u0 {1,S}
4 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
entry(
index = 51,
label = "S_rad",
group =
"""
1 *2 S u1
""",
kinetics = None,
)
entry(
index = 52,
label = "S_pri_rad",
group =
"""
1 *2 S u1 {2,S}
2 H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 53,
label = "S_sec_rad",
group =
"""
1 *2 S u1 {2,S}
2 R!H u0 {1,S}
""",
kinetics = None,
)
entry(
index = 54,
label = "S_rad/NonDe",
group =
"""
1 *2 S u1 {2,S}
2 [Cs,O,S2s] u0 px c0 {1,S}
""",
kinetics = None,
)
entry(
index = 55,
label = "S_rad/OneDe",
group =
"""
1 *2 S u1 {2,S}
2 [Cd,Ct,Cb,CO,CS] u0 {1,S}
""",
kinetics = None,
)
tree(
"""
L1: COm
L1: Y_rad
L2: H_rad
L2: O_rad
L3: O_pri_rad
L3: O_sec_rad
L4: O_rad/NonDe
L4: O_rad/OneDe
L2: S_rad
L3: S_pri_rad
L3: S_sec_rad
L4: S_rad/NonDe
L4: S_rad/OneDe
L2: Ct_rad
L2: CO_rad
L3: CO_pri_rad
L3: CO_sec_rad
L2: CS_rad
L3: CS_pri_rad
L3: CS_sec_rad
L2: Cd_rad
L3: Cd_pri_rad
L3: Cd_sec_rad
L4: Cd_rad/NonDe
L4: Cd_rad/OneDe
L2: Cb_rad
L2: Cs_rad
L3: C_methyl
L3: C_pri_rad
L4: C_rad/H2/Cs
L5: CH2CH3
L5: CH2CH2CH3
L4: C_rad/H2/Cd
L4: C_rad/H2/Ct
L4: C_rad/H2/Cb
L4: C_rad/H2/CO
L4: C_rad/H2/O
L4: C_rad/H2/CS
L4: C_rad/H2/S
L3: C_sec_rad
L4: C_rad/H/NonDeC
L5: CH(CH3)2
L4: C_rad/H/NonDeO
L5: C_rad/H/CsO
L5: C_rad/H/O2
L4: C_rad/H/NonDeS
L5: C_rad/H/CsS
L5: C_rad/H/S2
L5: C_rad/H/OneDe
L6: C_rad/H/OneDeC
L6: C_rad/H/OneDeO
L6: C_rad/H/OneDeS
L4: C_rad/H/TwoDe
L3: C_ter_rad
L4: C_rad/NonDeC
L5: C_rad/Cs3
L5: C_rad/NDMustO
L5: C_rad/NDMustS
L4: C_rad/OneDe
L5: C_rad/OD_Cs2
L5: C_rad/ODMustO
L4: C_rad/TwoDe
L5: C_rad/TD_Cs
L5: C_rad/TDMustO
L4: C_rad/ThreeDe
"""
)
forbidden(
label = "O2_birad",
group =
"""
1 *2 O u1 p2 {2,S}
2 O u1 p2 {1,S}
""",
shortDesc = u"""""",
longDesc =
u"""
""",
)
|
# ceasar_cypher_encryptor
# rotate each letter by k
# wrap around alphabet
def ceasar_cypher_encryptor(s, k):
ciphered = []
overflow_adjust = ord('z') - ord('a')
for c in s:
new_c = ord(c) + k
if new_c > ord('z'): # overflow adjustment
new_c = new_c - overflow_adjust
ciphered.append(chr(new_c))
return "".join(ciphered)
def main():
res = ceasar_cypher_encryptor("abcdefgxyz", 2)
print(f'{res}')
if __name__ == "__main__":
main() |
# Write a program to read through the mbox-short.txt
# and figure out the distribution by hour of the day
# for each of the messages. You can pull the hour out
# from the 'From ' line by finding the time and then
# splitting the string a second time using a colon.
#
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#
# Once you have accumulated the counts for each hour,
# print out the counts, sorted by hour as shown below.
name = input("Enter file:")
handle = open(name)
hours = {}
for line in handle:
line = line.strip()
if line.find('From ') == 0:
hour_sent = line[line.find(':')-2:line.find(':')]
# use dict get method to retrieve each hour_sent, or add it
# to the dict if it isn't present already (with default value of 0).
# Then set the value to value + 1
hours[hour_sent] = hours.get(hour_sent, 0) + 1
tups = hours.items() # get keys/values from hours as list of tuples
tups.sort() # sort by keys (first item in each tuple)
for tup in tups:
print(tup[0], str(tup[1]))
|
def foo(a = 1, b = 2):
return a + b
price = foo(b = 4)
for item in [[1, 2, 3], [4, 5, 6]]:
print(item[0])
mylist = [['abc'], ['def', 'ghi']]
mylist[-1][-1][-1]
def eur_to_usd(euros, rate=0.8):
return euros * rate
print(eur_to_usd(10))
weight = input("How many kg?")
price = weight * 2.5
print(price)
x = [len(item) for item in ['abc', 'def', 'ghi']]
y = [i * 2 if i > 0 else 0 for i in [1, -2, 10]]
def foo(x):
return x ** 2
print(foo("Hello"))
def foo(a = 1, b = 'John'):
return a + b
foo() |
class RawNode(object):
def __init__(self, chunk):
self.chunk = chunk
def render(self, ctx={}):
return str(self.chunk) |
RegionsVariablesMap = {
"Zarem": {
"Apple": {
"Wofost": "Supply of apple zr",
"Vensim": "apple zr",
"KeyInVensimModel": "apple_zr"
},
"Rice": {
"Wofost": "supply of rice zr",
"Vensim": "rice zr",
"KeyInVensimModel": "rice_zr"
},
"Citrus": {
"Wofost": "Supply of citrus zr",
"Vensim": "citrus zr",
"KeyInVensimModel": "citrus_zr"
},
"Rapeseed": {
"Wofost": "Supply of rapeseed zr",
"Vensim": "rapeseed zr",
"KeyInVensimModel": "rapeseed_zr"
}
},
"Finesk": {
"Tomato": {
"Wofost": "supply of tomato",
"Vensim": "tomato",
"KeyInVensimModel": "tomato"
},
"Rapeseed": {
"Wofost": "Supply of rapeseed",
"Vensim": "rapeseed",
"KeyInVensimModel": "rapeseed"
},
"Apple": {
"Wofost": "Supply of apple",
"Vensim": "apple",
"KeyInVensimModel": "apple"
},
"Citrus": {
"Wofost": "Supply of citrus",
"Vensim": "citrus",
"KeyInVensimModel": "citrus"
},
"Grainmaize": {
"Wofost": "Supply grainmaize",
"Vensim": "grainmaize",
"KeyInVensimModel": "grainmaize"
},
"Wheat": {
"Wofost": "Supply of wheat",
"Vensim": "wheat",
"KeyInVensimModel": "wheat"
},
"Chickpea": {
"Wofost": "Supply of chickpea",
"Vensim": "chickpea",
"KeyInVensimModel": "chickpea"
},
"Rice": {
"Wofost": "Supply of rice",
"Vensim": "rice",
"KeyInVensimModel": "rice"
}
},
"shah R D": {
"Rice": {
"Wofost": "Supply of Rice Tj",
"Vensim": "Rice Tj",
"KeyInVensimModel": "Rice_Tj"
},
"Apple": {
"Wofost": "Supply of apple Tj",
"Vensim": "apple Tj",
"KeyInVensimModel": "apple_Tj"
},
"Citrus": {
"Wofost": "Supply of Citrus Tj",
"Vensim": "citrs_tj",
"KeyInVensimModel": "Citrs_Tj"
},
"Tomato": {
"Wofost": "Supply of tomato tj",
"Vensim": "tomato tj",
"KeyInVensimModel": "tomato_Tj"
},
"Wheat": {
"Wofost": "Supply of wheat Tj",
"Vensim": "wheat Tj",
"KeyInVensimModel": "wheat_Tj"
},
"Rapeseed": {
"Wofost": "Supply of rapeseed Tj",
"Vensim": "Rapeseed Tj",
"KeyInVensimModel": "Rapeseed_Tj"
}
},
"Tj dd":
{
"Rice": {
"Wofost": "Sup- Rice tjj dd",
"Vensim": "rice tjj dd",
"KeyInVensimModel": "rice_tjj_dd"
},
"Citrus": {
"Wofost": "sup-Citrus tjj dd",
"Vensim": "citrud tjj dd",
"KeyInVensimModel": "citrud_tjj_dd"
},
"Apple": {
"Wofost": "sup-Apple tjj dd",
"Vensim": "apple tjj dd",
"KeyInVensimModel": "apple_tjj_dd"
},
"Sorgum": {
"Wofost": "sup-Sorgum tjdd",
"Vensim": "sorgum tjj dd",
"KeyInVensimModel": "sorgum_tjj_dd"
},
"Wheat": {
"Wofost": "sup-Wheat tjj dd",
"Vensim": "wheat tjj dd",
"KeyInVensimModel": "wheat_tjj_dd"
},
"Rapeseed": {
"Wofost": "sup-Rapeseed tjdd",
"Vensim": "rapeseed tjj dd",
"KeyInVensimModel": "rapeseed_tjj_dd"
},
"Grainmaize": {
"Wofost": "Sup-grainmaize Tjdd",
"Vensim": "grain maiz tjj dd",
"KeyInVensimModel": "grain_maiz_tjj_dd"
},
"Tomato": {
"Wofost": "Sup-tomato tjdd",
"Vensim": "tomato tjj dd",
"KeyInVensimModel": "tomato_tjj_dd"
}
}
}
CropNameMaps = {
"Apple": "APP301 - TJ.CAB",
"Chickpea": "CHICKPEA - TJ.W41",
"Citrus": "CIT301 - TJ.CAB",
"Grainmaize": "MAIZ - TJ.W41",
"Tomato": "POT701-TJ.CAB",
"Rice": "RIC501 - TJ.CAB",
"Rapeseed": "SOYBEAN - TJ.W41",
"Wheat": "WWH101 - TJ.CAB",
"Sorgum": "MAIZ - TJ.W41"
}
MeteoNameMaps = {
"Apple": "SAP2.014",
"Chickpea": "SCK2.014",
"Citrus": "SCT2.014",
"Grainmaize": "SMZ2.014",
"Tomato": "SPT2.014",
"Rice": "SRC2.014",
"Rapeseed": "SRP2.014",
"rapeseed": "SRP2.014", # added for fixing key error
"Wheat": "SWT2.014",
"Sorgum": "SMZ2.014"
}
Coefficient: dict = {
"Tomato": {
"Finesk": 0.02782949291,
"Zarem": 0,
"Tj dd": 0.000234943,
"shah R D": 0.0000351
},
"Chickpea": {
"Finesk": 0.000061,
"Zarem": 0,
"Tj dd": 0,
"shah R D": 0
},
"Rapeseed": {
"Finesk": 0.00013,
"Zarem": 0.000017,
"Tj dd": 0.004354075,
"shah R D": 0.000003
},
"Grainmaize": {
"Finesk": 0.00001,
"Zarem": 0, # 0.000017,
"Tj dd": 0.003685,
"shah R D": 0
},
"Apple": {
"Finesk": 0.02752754991,
"Zarem": 0.041570141,
"Tj dd": 0.03405931491,
"shah R D": 0.005011631
},
"Rice": {
"Finesk": 0.019067016,
"Zarem": 0.0097329009,
"Tj dd": 0.2196073774,
"shah R D": 0.0105982088
},
"Wheat": {
"Finesk": 0.009012,
"Zarem": 0,
"Tj dd": 0.017090164,
"shah R D": 0.000008
},
"Citrus": {
"Finesk": 0.0009526,
"Zarem": 0.001605887,
"Tj dd": 0.1293910401,
"shah R D": 0.00038915
},
"Sorgum": {
"Finesk": 0, # 0.00001,
"Zarem": 0, # 0.000017,
"Tj dd": 0.01708,
"shah R D": 0
}
}
Regions = {
"Finesk",
"Zarem",
"Tj dd",
"shah R D"
}
keys_in_vensim_output = [
'"sup-Wheat tjj dd"',
'"sup-Citrus tjj dd"',
'"Sup- Rice tjj dd"',
'"sup-Apple tjj dd"',
'"sup-Sorgum tjdd"',
'"Sup-grainmaize Tjdd"',
'"Sup-tomato tjdd"',
'"sup-Rapeseed tjdd"',
"supply of tomato tj",
"supply of apple Tj",
"supply of Rice Tj",
"supply of citrus Tj",
"spply of wheat Tj",
"supply of rapeseed Tj",
"supply of rice zr",
"supply of citrus zr",
"supply of rapeseed zr",
"Supply of apple zr",
"supply of wheat",
"supply of apple",
"supply of tomato",
"supply of grainmaize",
"supply of chickpea",
"supply of rice",
"supply of rapeseed",
"supply of citrus",
]
WeatherContainerRanges = {"LAT": (-90., 90.),
"LON": (-180., 180.),
"ELEV": (-300, 6000),
"IRRAD": (0., 40e30),
"TMIN": (-50., 60.),
"TMAX": (-50., 60.),
"VAP": (0.06, 2000000.3),
"RAIN": (0, 25),
"E0": (0., 20000000.5),
"ES0": (0., 2000000.5),
"ET0": (0., 2000000.5),
"WIND": (0., 100.),
"SNOWDEPTH": (0., 250.),
"TEMP": (-50., 60.),
"TMINRA": (-50., 60.)}
ArgoMap = {
"Apple": "apple_calendar.agro",
"Chickpea": "chickpea_calendar.agro",
"Citrus": "citrus_calendar.agro",
"Grainmaize": "grainmaiz_calendar.agro",
"Sorgum": "grainmaiz_calendar.agro",
"Tomato": "potato_calendar.agro",
"Rice": "rice_calendar.agro",
"Rapeseed": "rapeseed_calendar.agro",
"Wheat": 'wheat_calendar.agro'
}
SoilMap = {
"Soil": "EC11.NEW"
}
|
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2019-10-29 11:22
# @Author : Fabrice LI
# @File : 20191029_135_combination_sum.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given a set of candidtate numbers candidates and a target number target.
# Find all unique combinations in candidates where the numbers sums to target.
#
# The same repeated number may be chosen from candidates unlimited number of times.
# 1. All numbers (including target) will be positive integers.
# 2. Numbers in a combination a1, a2, … , ak must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak)
# 3. Different combinations can be in any order.
# 4. The solution set must not contain duplicate combinations.
#Reference:**********************************************
'''
E.g
Input: candidates = [2, 3, 6, 7], target = 7
Output: [[7], [2, 2, 3]]
Input: candidates = [1], target = 3
Output: [[1, 1, 1]]
'''
class Solution:
"""
@param candidates: A list of integers
@param target: An integer
@return: A list of lists of integers
"""
def combinationSum(self, candidates, target):
if not candidates:
return []
res = []
candidates.sort()
self.dfs(candidates, 0, len(candidates), [], res, target)
return res
def dfs(self, data, begin, size, path, res, target):
if target == 0:
if path not in res:
res.append(path[:])
return
for index in range(begin, size):
reduce = target - data[index]
if reduce < 0:
break
path.append(data[index])
self.dfs(data, index, size, path, res, reduce)
path.pop()
def combinationSum2(self, candidates, target):
if len(candidates) <= 0:
return []
res = []
candidates.sort()
self.__dfs(candidates, target, 0, [], res)
return res
# 递归的定义
# 找到所有以condidate开头的的哪些和为target的结果都放到res里,下一个加入path的数,
# 至少从candidate的start_index开始
def __dfs(self, candidates, remain_target, start_index, path, res):
if remain_target == 0:
res.append(path[:])
return
# 递归的拆解
for i in range(start_index, len(candidates)):
if remain_target < candidates[i]:
break
# 去掉candidate中重复的,[2,2,3,4,6]
if i > 0 and candidates[i] == candidates[i - 1]:
continue
path.append(candidates[i])
self.__dfs(candidates, remain_target - candidates[i], i, path, res)
path.pop()
if __name__ == '__main__':
s = Solution()
candidates = [2, 3, 6, 7]
target = 7
print(s.combinationSum2(candidates, target))
|
#Criação das 4 listas
filmes = ['Harry Potter', 'Zumbilandia', 'Invocação do Mal', 'O elo perdido']
jogos = ['Valorant', 'Dark Souls', 'Dont Starve Together', 'Cup Head']
livros = ['O homem de giz', 'Diario de um banana', 'A guerra dos tronos']
esporte = ['xadrez', 'futebol', 'basquete', 'volei']
#Adicionar 2 itens em cada lista
filmes.append("Ta dando onda")
filmes.append("O grito")
jogos.append("Minecraft")
jogos.append("Hollow Night")
livros.append("Diario de Anne Frank")
livros.append("Vida de droga")
esporte.append("Tênis")
esporte.append("Corrida")
#Criação de uma lista para as outras 4
listageral = [filmes, jogos, livros, esporte]
print(listageral)
#print de um item da lista livros
print(livros[2])
#Removendo item da lista esportes
del esporte[0]
print(esporte)
print(listageral)
#Adicionando lista na lista geral
disciplinas = ['Matematica', 'Portugues', 'Ciencias', 'Biologia']
print(listageral)
|
ctx.rule(u'START',u'{PROGRAM}')
ctx.rule(u'PROGRAM',u'{STATEMENT}\n{PROGRAM}')
ctx.rule(u'PROGRAM',u'')
ctx.rule(u'STATEMENT',u';')
ctx.rule(u'STATEMENT',u'')
ctx.rule(u'STATEMENT',u'break')
ctx.rule(u'STATEMENT',u'{VAR} = {EXPR}')
ctx.rule(u'STATEMENT',u'local {VARLIST} = {EXPRLIST}')
ctx.rule(u'STATEMENT',u'{FUNCTION}')
ctx.rule(u'STATEMENT',u'{COROUTINE}')
ctx.rule(u'STATEMENT',u'{CONDITIONAL}')
ctx.rule(u'STATEMENT',u'{LOOP}')
ctx.rule(u'STATEMENT',u'return {EXPRLIST}')
ctx.rule(u'STATEMENT',u'goto {LABELNAME}')
ctx.rule(u'STATEMENT',u'::{LABELNAME}::')
ctx.rule(u'LABELNAME',u'labela')
ctx.rule(u'LABELNAME',u'labelb')
ctx.rule(u'FUNCTION',u'{FUNCDEF} ({FUNCTION_ARGS}) {PROGRAM}\nend')
ctx.rule(u'FUNCDEF',u'function {VAR}.{IDENTIFIER}')
ctx.rule(u'FUNCDEF',u'function {VAR}:{IDENTIFIER}')
ctx.rule(u'FUNCDEF',u'function {IDENTIFIER}')
ctx.rule(u'LAMBDA',u'function ({FUNCTION_ARGS}) {PROGRAM} end')
ctx.rule(u'FUNCTION_ARGS',u'')
ctx.rule(u'FUNCTION_ARGS',u'{FUNCTION_ARGLIST}')
ctx.rule(u'FUNCTION_ARGLIST',u'{VAR}, {FUNCTION_ARGLIST}')
ctx.rule(u'FUNCTION_ARGLIST',u'{VAR}')
ctx.rule(u'FUNCTION_ARGLIST',u'...')
ctx.rule(u'COROUTINE',u'{VAR} = coroutine.create({LAMBDA})')
ctx.rule(u'COROUTINE',u'{VAR} = coroutine.wrap({LAMBDA})')
ctx.rule(u'COROUTINE',u'coroutine.resume({VAR}, {ARGS})')
ctx.rule(u'COROUTINE',u'coroutine.yield({ARGS})')
ctx.rule(u'FUNCTIONCALL',u'{IDENTIFIER} {ARGS}')
ctx.rule(u'FUNCTIONCALL',u'{EXPR}:{IDENTIFIER} {ARGS}')
ctx.rule(u'FUNCTIONCALL',u'{EXPR}.{IDENTIFIER} {ARGS}')
ctx.rule(u'ARGS',u'({EXPRLIST})')
ctx.rule(u'ARGS',u'{TABLECONSTRUCTOR}')
ctx.rule(u'ARGS',u'{LITERALSTRING}')
ctx.rule(u'CONDITIONAL',u'if {EXPR} then\n{PROGRAM}\nend')
ctx.rule(u'CONDITIONAL',u'if {EXPR} then\n{PROGRAM}\nelse\n{PROGRAM}\nend')
ctx.rule(u'LOOP',u'while ({EXPR})\ndo\n{PROGRAM}\nend')
ctx.rule(u'LOOP',u'for {VAR}={EXPR}, {EXPR}, {EXPR}\ndo\n{PROGRAM}\nend')
ctx.rule(u'LOOP',u'repeat\n{PROGRAM}\nuntil ({EXPR})')
ctx.rule(u'EXPRLIST',u'{EXPR}, {EXPRLIST}')
ctx.rule(u'EXPRLIST',u'{EXPR}')
ctx.rule(u'EXPR',u'(nil)')
ctx.rule(u'EXPR',u'(false)')
ctx.rule(u'EXPR',u'(true)')
ctx.rule(u'EXPR',u'({NUMERAL})')
ctx.rule(u'EXPR',u'{LITERALSTRING}')
ctx.rule(u'EXPR',u'{TABLECONSTRUCTOR}')
ctx.rule(u'EXPR',u'({VAR}[{EXPR}])')
ctx.rule(u'EXPR',u'({EXPR}{BINOP}{EXPR})')
ctx.rule(u'EXPR',u'({UNOP}{EXPR})')
ctx.rule(u'EXPR',u'{LAMBDA}')
ctx.rule(u'EXPR',u'{VAR}')
ctx.rule(u'EXPR',u'{FUNCTIONCALL}')
ctx.rule(u'EXPR',u'({EXPR})')
ctx.rule(u'EXPR',u'...')
ctx.rule(u'BINOP',u'+')
ctx.rule(u'BINOP',u'-')
ctx.rule(u'BINOP',u'*')
ctx.rule(u'BINOP',u'/')
ctx.rule(u'BINOP',u'//')
ctx.rule(u'BINOP',u'^')
ctx.rule(u'BINOP',u'%')
ctx.rule(u'BINOP',u'&')
ctx.rule(u'BINOP',u'~')
ctx.rule(u'BINOP',u'|')
ctx.rule(u'BINOP',u'>>')
ctx.rule(u'BINOP',u'<<')
ctx.rule(u'BINOP',u' .. ')
ctx.rule(u'BINOP',u'<')
ctx.rule(u'BINOP',u'<=')
ctx.rule(u'BINOP',u'>')
ctx.rule(u'BINOP',u'>=')
ctx.rule(u'BINOP',u'==')
ctx.rule(u'BINOP',u'~=')
ctx.rule(u'BINOP',u' and ')
ctx.rule(u'BINOP',u' or ')
ctx.rule(u'UNOP',u'-')
ctx.rule(u'UNOP',u' not ')
ctx.rule(u'UNOP',u'#')
ctx.rule(u'UNOP',u'~')
ctx.rule(u'TABLECONSTRUCTOR',u'\\{{FIELDLIST}\\}')
ctx.rule(u'METATABLE',u'{VAR} = setmetatable({VAR}, {TABLECONSTRUCTOR})')
ctx.rule(u'FIELDLIST',u'{FIELD},{FIELDLIST}')
ctx.rule(u'FIELDLIST',u'{FIELD}')
ctx.rule(u'FIELD',u'[{EXPR}]={EXPR}')
ctx.rule(u'FIELD',u'{IDENTIFIER}={EXPR}')
ctx.rule(u'FIELD',u'{EXPR}')
ctx.rule(u'VARLIST',u'{VAR}, {VARLIST}')
ctx.rule(u'VARLIST',u'{VAR}')
ctx.rule(u'VAR',u'a')
ctx.rule(u'VAR',u'b')
ctx.rule(u'VAR',u'c')
ctx.rule(u'VAR',u'd')
ctx.rule(u'VAR',u'e')
ctx.rule(u'VAR',u'coroutine')
ctx.rule(u'VAR',u'debug')
ctx.rule(u'VAR',u'math')
ctx.rule(u'VAR',u'io')
ctx.rule(u'VAR',u'os')
ctx.rule(u'VAR',u'package')
ctx.rule(u'VAR',u'string')
ctx.rule(u'VAR',u'table')
ctx.rule(u'VAR',u'utf8')
ctx.rule(u'VAR',u'self')
ctx.rule(u'LITERALSTRING',u'"{STRING}"')
ctx.rule(u'LITERALSTRING',u'[[{STRING}]]')
ctx.rule(u'STRING',u'')
ctx.rule(u'STRING',u'{STRCHR}{STRING}')
ctx.rule(u'STRCHR',u'\n')
ctx.rule(u'STRCHR',u'\r')
ctx.rule(u'STRCHR',u' ')
ctx.rule(u'STRCHR',u'\t')
ctx.rule(u'STRCHR',u'0')
ctx.rule(u'STRCHR',u'a')
ctx.rule(u'STRCHR',u'/')
ctx.rule(u'STRCHR',u'.')
ctx.rule(u'STRCHR',u'$')
ctx.rule(u'STRCHR',u'{ESCAPESEQUENCE}')
ctx.rule(u'ESCAPESEQUENCE',u'\\a')
ctx.rule(u'ESCAPESEQUENCE',u'\\b')
ctx.rule(u'ESCAPESEQUENCE',u'\\f')
ctx.rule(u'ESCAPESEQUENCE',u'\\n')
ctx.rule(u'ESCAPESEQUENCE',u'\\r')
ctx.rule(u'ESCAPESEQUENCE',u'\\t')
ctx.rule(u'ESCAPESEQUENCE',u'\\v')
ctx.rule(u'ESCAPESEQUENCE',u'\\z')
ctx.rule(u'ESCAPESEQUENCE',u'\n')
ctx.rule(u'ESCAPESEQUENCE',u'\\x{HEXADECIMAL}')
ctx.rule(u'ESCAPESEQUENCE',u'\\u\\{{HEXADECIMAL}\\}')
ctx.rule(u'NUMERAL',u'{DECIMAL}')
ctx.rule(u'NUMERAL',u'0x{HEXADECIMAL}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}e{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}e-{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}e{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMAL',u'{DECIMALDIGIT}{DECIMALDIGITS}.{DECIMALDIGIT}{DECIMALDIGITS}e-{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}p{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}p-{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}p{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXADECIMAL',u'{HEXDIGIT}{HEXDIGITS}.{HEXDIGIT}{HEXDIGITS}p-{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'DECIMALDIGITS',u'{DECIMALDIGIT}{DECIMALDIGITS}')
ctx.rule(u'DECIMALDIGITS',u'')
ctx.rule(u'HEXDIGITS',u'{HEXDIGIT}{HEXDIGITS}')
ctx.rule(u'HEXDIGITS',u'')
ctx.rule(u'DECIMALDIGIT',u'0')
ctx.rule(u'DECIMALDIGIT',u'1')
ctx.rule(u'DECIMALDIGIT',u'2')
ctx.rule(u'DECIMALDIGIT',u'3')
ctx.rule(u'DECIMALDIGIT',u'4')
ctx.rule(u'DECIMALDIGIT',u'5')
ctx.rule(u'DECIMALDIGIT',u'6')
ctx.rule(u'DECIMALDIGIT',u'7')
ctx.rule(u'DECIMALDIGIT',u'8')
ctx.rule(u'DECIMALDIGIT',u'9')
ctx.rule(u'HEXDIGIT',u'a')
ctx.rule(u'HEXDIGIT',u'b')
ctx.rule(u'HEXDIGIT',u'c')
ctx.rule(u'HEXDIGIT',u'd')
ctx.rule(u'HEXDIGIT',u'e')
ctx.rule(u'HEXDIGIT',u'f')
ctx.rule(u'HEXDIGIT',u'A')
ctx.rule(u'HEXDIGIT',u'B')
ctx.rule(u'HEXDIGIT',u'C')
ctx.rule(u'HEXDIGIT',u'D')
ctx.rule(u'HEXDIGIT',u'E')
ctx.rule(u'HEXDIGIT',u'F')
ctx.rule(u'HEXDIGIT',u'{DECIMALDIGIT}')
ctx.rule(u'IDENTIFIER',u'self')
ctx.rule(u'IDENTIFIER',u'G')
ctx.rule(u'IDENTIFIER',u'_VERSION')
ctx.rule(u'IDENTIFIER',u'assert')
ctx.rule(u'IDENTIFIER',u'collectgarbage')
ctx.rule(u'IDENTIFIER',u'dofile')
ctx.rule(u'IDENTIFIER',u'error')
ctx.rule(u'IDENTIFIER',u'getmetatable')
ctx.rule(u'IDENTIFIER',u'ipairs')
ctx.rule(u'IDENTIFIER',u'load')
ctx.rule(u'IDENTIFIER',u'loadfile')
ctx.rule(u'IDENTIFIER',u'next')
ctx.rule(u'IDENTIFIER',u'pairs')
ctx.rule(u'IDENTIFIER',u'pcall')
ctx.rule(u'IDENTIFIER',u'print')
ctx.rule(u'IDENTIFIER',u'rawequal')
ctx.rule(u'IDENTIFIER',u'rawget')
ctx.rule(u'IDENTIFIER',u'rawlen')
ctx.rule(u'IDENTIFIER',u'rawset')
ctx.rule(u'IDENTIFIER',u'require')
ctx.rule(u'IDENTIFIER',u'select')
ctx.rule(u'IDENTIFIER',u'setmetatable')
ctx.rule(u'IDENTIFIER',u'tonumber')
ctx.rule(u'IDENTIFIER',u'tostring')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'xpcall')
ctx.rule(u'IDENTIFIER',u'coroutine')
ctx.rule(u'IDENTIFIER',u'create')
ctx.rule(u'IDENTIFIER',u'isyieldable')
ctx.rule(u'IDENTIFIER',u'resume')
ctx.rule(u'IDENTIFIER',u'running')
ctx.rule(u'IDENTIFIER',u'status')
ctx.rule(u'IDENTIFIER',u'wrap')
ctx.rule(u'IDENTIFIER',u'yield')
ctx.rule(u'IDENTIFIER',u'debug')
ctx.rule(u'IDENTIFIER',u'debug')
ctx.rule(u'IDENTIFIER',u'gethook')
ctx.rule(u'IDENTIFIER',u'getinfo')
ctx.rule(u'IDENTIFIER',u'getlocal')
ctx.rule(u'IDENTIFIER',u'getmetatable')
ctx.rule(u'IDENTIFIER',u'getregistry')
ctx.rule(u'IDENTIFIER',u'getupvalue')
ctx.rule(u'IDENTIFIER',u'getuservalue')
ctx.rule(u'IDENTIFIER',u'sethook')
ctx.rule(u'IDENTIFIER',u'setlocal')
ctx.rule(u'IDENTIFIER',u'setmetatable')
ctx.rule(u'IDENTIFIER',u'setupvalue')
ctx.rule(u'IDENTIFIER',u'setuservalue')
ctx.rule(u'IDENTIFIER',u'traceback')
ctx.rule(u'IDENTIFIER',u'upvalueid')
ctx.rule(u'IDENTIFIER',u'upvaluejoin')
ctx.rule(u'IDENTIFIER',u'io')
ctx.rule(u'IDENTIFIER',u'close')
ctx.rule(u'IDENTIFIER',u'flush')
ctx.rule(u'IDENTIFIER',u'input')
ctx.rule(u'IDENTIFIER',u'lines')
ctx.rule(u'IDENTIFIER',u'open')
ctx.rule(u'IDENTIFIER',u'output')
ctx.rule(u'IDENTIFIER',u'popen')
ctx.rule(u'IDENTIFIER',u'read')
ctx.rule(u'IDENTIFIER',u'stderr')
ctx.rule(u'IDENTIFIER',u'stdin')
ctx.rule(u'IDENTIFIER',u'stdout')
ctx.rule(u'IDENTIFIER',u'tmpfile')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'write')
ctx.rule(u'IDENTIFIER',u'math')
ctx.rule(u'IDENTIFIER',u'abs')
ctx.rule(u'IDENTIFIER',u'acos')
ctx.rule(u'IDENTIFIER',u'asin')
ctx.rule(u'IDENTIFIER',u'atan')
ctx.rule(u'IDENTIFIER',u'ceil')
ctx.rule(u'IDENTIFIER',u'cos')
ctx.rule(u'IDENTIFIER',u'deg')
ctx.rule(u'IDENTIFIER',u'exp')
ctx.rule(u'IDENTIFIER',u'floor')
ctx.rule(u'IDENTIFIER',u'fmod')
ctx.rule(u'IDENTIFIER',u'huge')
ctx.rule(u'IDENTIFIER',u'log')
ctx.rule(u'IDENTIFIER',u'max')
ctx.rule(u'IDENTIFIER',u'maxinteger')
ctx.rule(u'IDENTIFIER',u'min')
ctx.rule(u'IDENTIFIER',u'mininteger')
ctx.rule(u'IDENTIFIER',u'modf')
ctx.rule(u'IDENTIFIER',u'pi')
ctx.rule(u'IDENTIFIER',u'rad')
ctx.rule(u'IDENTIFIER',u'random')
ctx.rule(u'IDENTIFIER',u'randomseed')
ctx.rule(u'IDENTIFIER',u'sin')
ctx.rule(u'IDENTIFIER',u'sqrt')
ctx.rule(u'IDENTIFIER',u'tan')
ctx.rule(u'IDENTIFIER',u'tointeger')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'ult')
ctx.rule(u'IDENTIFIER',u'os')
ctx.rule(u'IDENTIFIER',u'clock')
ctx.rule(u'IDENTIFIER',u'date')
ctx.rule(u'IDENTIFIER',u'difftime')
ctx.rule(u'IDENTIFIER',u'exit')
ctx.rule(u'IDENTIFIER',u'getenv')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'rename')
ctx.rule(u'IDENTIFIER',u'setlocale')
ctx.rule(u'IDENTIFIER',u'time')
ctx.rule(u'IDENTIFIER',u'tmpname')
ctx.rule(u'IDENTIFIER',u'package')
ctx.rule(u'IDENTIFIER',u'config')
ctx.rule(u'IDENTIFIER',u'cpath')
ctx.rule(u'IDENTIFIER',u'loaded')
ctx.rule(u'IDENTIFIER',u'loadlib')
ctx.rule(u'IDENTIFIER',u'path')
ctx.rule(u'IDENTIFIER',u'preload')
ctx.rule(u'IDENTIFIER',u'searchers')
ctx.rule(u'IDENTIFIER',u'searchpath')
ctx.rule(u'IDENTIFIER',u'string')
ctx.rule(u'IDENTIFIER',u'byte')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'dump')
ctx.rule(u'IDENTIFIER',u'find')
ctx.rule(u'IDENTIFIER',u'format')
ctx.rule(u'IDENTIFIER',u'gmatch')
ctx.rule(u'IDENTIFIER',u'gsub')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'lower')
ctx.rule(u'IDENTIFIER',u'match')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'packsize')
ctx.rule(u'IDENTIFIER',u'rep')
ctx.rule(u'IDENTIFIER',u'reverse')
ctx.rule(u'IDENTIFIER',u'sub')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'upper')
ctx.rule(u'IDENTIFIER',u'table')
ctx.rule(u'IDENTIFIER',u'concat')
ctx.rule(u'IDENTIFIER',u'insert')
ctx.rule(u'IDENTIFIER',u'move')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'sort')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'utf8')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'charpattern')
ctx.rule(u'IDENTIFIER',u'codepoint')
ctx.rule(u'IDENTIFIER',u'codes')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'offset')
ctx.rule(u'IDENTIFIER',u'create')
ctx.rule(u'IDENTIFIER',u'isyieldable')
ctx.rule(u'IDENTIFIER',u'resume')
ctx.rule(u'IDENTIFIER',u'running')
ctx.rule(u'IDENTIFIER',u'status')
ctx.rule(u'IDENTIFIER',u'wrap')
ctx.rule(u'IDENTIFIER',u'yield')
ctx.rule(u'IDENTIFIER',u'debug')
ctx.rule(u'IDENTIFIER',u'gethook')
ctx.rule(u'IDENTIFIER',u'getinfo')
ctx.rule(u'IDENTIFIER',u'getlocal')
ctx.rule(u'IDENTIFIER',u'getmetatable')
ctx.rule(u'IDENTIFIER',u'getregistry')
ctx.rule(u'IDENTIFIER',u'getupvalue')
ctx.rule(u'IDENTIFIER',u'getuservalue')
ctx.rule(u'IDENTIFIER',u'sethook')
ctx.rule(u'IDENTIFIER',u'setlocal')
ctx.rule(u'IDENTIFIER',u'setmetatable')
ctx.rule(u'IDENTIFIER',u'setupvalue')
ctx.rule(u'IDENTIFIER',u'setuservalue')
ctx.rule(u'IDENTIFIER',u'traceback')
ctx.rule(u'IDENTIFIER',u'upvalueid')
ctx.rule(u'IDENTIFIER',u'upvaluejoin')
ctx.rule(u'IDENTIFIER',u'close')
ctx.rule(u'IDENTIFIER',u'flush')
ctx.rule(u'IDENTIFIER',u'input')
ctx.rule(u'IDENTIFIER',u'lines')
ctx.rule(u'IDENTIFIER',u'open')
ctx.rule(u'IDENTIFIER',u'output')
ctx.rule(u'IDENTIFIER',u'popen')
ctx.rule(u'IDENTIFIER',u'read')
ctx.rule(u'IDENTIFIER',u'stderr')
ctx.rule(u'IDENTIFIER',u'stdin')
ctx.rule(u'IDENTIFIER',u'stdout')
ctx.rule(u'IDENTIFIER',u'tmpfile')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'write')
ctx.rule(u'IDENTIFIER',u'close')
ctx.rule(u'IDENTIFIER',u'flush')
ctx.rule(u'IDENTIFIER',u'lines')
ctx.rule(u'IDENTIFIER',u'read')
ctx.rule(u'IDENTIFIER',u'seek')
ctx.rule(u'IDENTIFIER',u'setvbuf')
ctx.rule(u'IDENTIFIER',u'write')
ctx.rule(u'IDENTIFIER',u'abs')
ctx.rule(u'IDENTIFIER',u'acos')
ctx.rule(u'IDENTIFIER',u'asin')
ctx.rule(u'IDENTIFIER',u'atan')
ctx.rule(u'IDENTIFIER',u'ceil')
ctx.rule(u'IDENTIFIER',u'cos')
ctx.rule(u'IDENTIFIER',u'deg')
ctx.rule(u'IDENTIFIER',u'exp')
ctx.rule(u'IDENTIFIER',u'floor')
ctx.rule(u'IDENTIFIER',u'fmod')
ctx.rule(u'IDENTIFIER',u'huge')
ctx.rule(u'IDENTIFIER',u'log')
ctx.rule(u'IDENTIFIER',u'max')
ctx.rule(u'IDENTIFIER',u'maxinteger')
ctx.rule(u'IDENTIFIER',u'min')
ctx.rule(u'IDENTIFIER',u'mininteger')
ctx.rule(u'IDENTIFIER',u'modf')
ctx.rule(u'IDENTIFIER',u'pi')
ctx.rule(u'IDENTIFIER',u'rad')
ctx.rule(u'IDENTIFIER',u'random')
ctx.rule(u'IDENTIFIER',u'randomseed')
ctx.rule(u'IDENTIFIER',u'sin')
ctx.rule(u'IDENTIFIER',u'sqrt')
ctx.rule(u'IDENTIFIER',u'tan')
ctx.rule(u'IDENTIFIER',u'tointeger')
ctx.rule(u'IDENTIFIER',u'type')
ctx.rule(u'IDENTIFIER',u'ult')
ctx.rule(u'IDENTIFIER',u'clock')
ctx.rule(u'IDENTIFIER',u'date')
ctx.rule(u'IDENTIFIER',u'difftime')
ctx.rule(u'IDENTIFIER',u'exit')
ctx.rule(u'IDENTIFIER',u'getenv')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'rename')
ctx.rule(u'IDENTIFIER',u'setlocale')
ctx.rule(u'IDENTIFIER',u'time')
ctx.rule(u'IDENTIFIER',u'tmpname')
ctx.rule(u'IDENTIFIER',u'config')
ctx.rule(u'IDENTIFIER',u'cpath')
ctx.rule(u'IDENTIFIER',u'loaded')
ctx.rule(u'IDENTIFIER',u'loadlib')
ctx.rule(u'IDENTIFIER',u'path')
ctx.rule(u'IDENTIFIER',u'preload')
ctx.rule(u'IDENTIFIER',u'searchers')
ctx.rule(u'IDENTIFIER',u'searchpath')
ctx.rule(u'IDENTIFIER',u'byte')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'dump')
ctx.rule(u'IDENTIFIER',u'find')
ctx.rule(u'IDENTIFIER',u'format')
ctx.rule(u'IDENTIFIER',u'gmatch')
ctx.rule(u'IDENTIFIER',u'gsub')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'lower')
ctx.rule(u'IDENTIFIER',u'match')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'packsize')
ctx.rule(u'IDENTIFIER',u'rep')
ctx.rule(u'IDENTIFIER',u'reverse')
ctx.rule(u'IDENTIFIER',u'sub')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'upper')
ctx.rule(u'IDENTIFIER',u'concat')
ctx.rule(u'IDENTIFIER',u'insert')
ctx.rule(u'IDENTIFIER',u'move')
ctx.rule(u'IDENTIFIER',u'pack')
ctx.rule(u'IDENTIFIER',u'remove')
ctx.rule(u'IDENTIFIER',u'sort')
ctx.rule(u'IDENTIFIER',u'unpack')
ctx.rule(u'IDENTIFIER',u'char')
ctx.rule(u'IDENTIFIER',u'charpattern')
ctx.rule(u'IDENTIFIER',u'codepoint')
ctx.rule(u'IDENTIFIER',u'codes')
ctx.rule(u'IDENTIFIER',u'len')
ctx.rule(u'IDENTIFIER',u'offset')
ctx.rule(u'IDENTIFIER',u'__index')
ctx.rule(u'IDENTIFIER',u'__newindex')
ctx.rule(u'IDENTIFIER',u'__add')
ctx.rule(u'IDENTIFIER',u'__sub')
ctx.rule(u'IDENTIFIER',u'__mul')
ctx.rule(u'IDENTIFIER',u'__div')
ctx.rule(u'IDENTIFIER',u'__mod')
ctx.rule(u'IDENTIFIER',u'__unm')
ctx.rule(u'IDENTIFIER',u'__concat')
ctx.rule(u'IDENTIFIER',u'__eq')
ctx.rule(u'IDENTIFIER',u'__lt')
ctx.rule(u'IDENTIFIER',u'__le')
ctx.rule(u'IDENTIFIER',u'__call')
ctx.rule(u'IDENTIFIER',u'__tostring')
|
#urnEletronica
candidato_prefeito_1 = 0
candidato_prefeito_2 = 0
votos_brancos = 0
anulados = 0
def msg():
mensagem = input('INICIAR?SIM OU NÃO?')
mensagem.lower()
return mensagem
def verdade_falso():
mensagem =msg()
if mensagem == 'sim':
return True
else:
return False
def resultado():
if candidato_prefeito_1 > candidato_prefeito_2:
print('VENCEDOR:',candidato_prefeito_1)
elif candidato_prefeito_2 > candidato_prefeito_1:
print('VENCEDOR:',candidato_prefeito_2)
elif candidato_prefeito_1 == candidato_prefeito_2:
print('EMPATE ,SEGUNDO TURNO!:')
else:
print('NENHUM RECEBEU VOTOS!')
print('-'*50)
print(
'QUANTIDADES DE VONTANTES: ',
anulados+votos_brancos+candidato_prefeito_2+candidato_prefeito_1
)
print('NULOS:',anulados)
print('EM BRANCOS:',votos_brancos)
print('QUANTIDA CANDIDATOS 01:',candidato_prefeito_1)
print('QUANTIDA CANDIDATOS 02:',candidato_prefeito_2)
button_power = verdade_falso()
while button_power:
voto = int(input('DIGITE O CODIGO DO SEU CANDIDATO: '))
if voto == 1:
candidato_prefeito_1 += 1
print('Votação realizada! Candidato 1!')
button_power = verdade_falso()
elif voto == 2:
candidato_prefeito_2+=1
print('Votação realizada! Candidato 2!')
button_power = verdade_falso()
elif voto == 0:
votos_brancos += 1
print ('Voto em branco!')
button_power = verdade_falso()
else:
anulados += 1
print('Anulado!')
button_power = verdade_falso()
resultado() |
def detectHashtag(inputs):
data = []
for tweet in inputs:
hashtag = tweet.entities['hashtags']
for hash in hashtag:
if hash['text'].lower() == 'testtweet':
data.append(tweet)
return data
def interact(inputs, api, FILE_NAME):
data = detectHashtag(inputs)
for i in data[::-1]:
api.update_status("Hello @" + i.user.screen_name + ", this is an automated response to your tweet. ", i.id)
api.create_favorite(i.id)
api.retweet(i.id)
store_last_seen(FILE_NAME, i.id)
def read_last_seen(FILE_NAME):
file_read = open(FILE_NAME, 'r')
last_seen_id = int(file_read.read().strip())
file_read.close()
return last_seen_id
def store_last_seen(FILE_NAME, last_seen_id):
file_write = open(FILE_NAME, 'w')
file_write.write(str(last_seen_id))
file_write.close()
|
class Element:
__slots__ = ('attributes', 'children')
name = 'element'
def __init__(self, *args, **kwargs):
self.attributes = {k.replace('_', '-'): v for k, v in kwargs.items()}
self.children = []
for item in args:
if type(item) in (list, tuple):
self.children.extend(item)
elif isinstance(item, dict):
self.attributes.update(item)
elif isinstance(item, Element):
self.children.append(item)
else:
self.children.append(str(item))
def __str__(self):
if self.attributes:
opener = '<{} {}>'.format(self.name, ' '.join('{}="{}"'.format(key, value) for key, value in self.attributes.items()))
else:
opener = '<{}>'.format(self.name)
closer = '</{0}>'.format(self.name)
descendants = self.descendants
if descendants == 0:
return opener[:-1] + '/>'
elif descendants == 1:
return opener + str(self.children[0]) + closer
else:
return '{}\n{}\n{}'.format(
opener,
indent_string('\n'.join(
str(child) for child in self.children
)),
closer
)
@property
def descendants(self):
total = 0
for child in self.children:
total += 1
if not isinstance(child, str):
total += child.descendants
return total
class Html(Element):
name = 'html'
def __str__(self):
return '<!DOCTYPE html>\n' + super().__str__()
class A(Element):
name = 'a'
class P(Element):
name = 'p'
class H1(Element):
name = 'h1'
class H2(Element):
name = 'h2'
class H3(Element):
name = 'h3'
class H4(Element):
name = 'h4'
class H5(Element):
name = 'h5'
class H6(Element):
name = 'h6'
class Br(Element):
name = 'br'
class Tr(Element):
name = 'tr'
class Th(Element):
name = 'th'
class Td(Element):
name = 'td'
class Table(Element):
name = 'table'
class Head(Element):
name = 'head'
class Body(Element):
name = 'body'
class Div(Element):
name = 'div'
class Span(Element):
name = 'span'
class Meta(Element):
name = 'meta'
class Title(Element):
name = 'title'
class Link(Element):
name = 'link'
class Script(Element):
name = 'script'
def indent_string(s, level=1):
indent = ' '*level
return indent + s.replace('\n', '\n' + indent)
|
# factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
def factorial(n: int) -> int:
"""
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(20))
True
>>> factorial(0.1)
Traceback (most recent call last):
...
ValueError: factorial() only accepts integral values
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: factorial() not defined for negative values
"""
if n != int(n):
raise ValueError("factorial() only accepts integral values")
if n < 0:
raise ValueError("factorial() not defined for negative values")
value = 1
for i in range(1, n + 1):
value *= i
return value
if __name__ == "__main__":
n = int(input("Enter a positive integer: ").strip() or 0)
print(f"factorial{n} is {factorial(n)}")
|
class FileExtensions:
"""
Class containing names for
valid File Extensions
"""
spark: str = "spark"
keras: str = "h5"
h2o: str = "h2o"
sklearn: str = "pkl"
@staticmethod
def get_valid() -> tuple:
"""
Return a tuple of the valid file extensions
in Database
:return: (tuple) valid statuses
"""
return (
FileExtensions.spark, FileExtensions.keras, FileExtensions.h2o, FileExtensions.sklearn
)
@staticmethod
def map_from_mlflow_flavor(flavor: str):
return {
'spark': 'spark',
'h2o': 'h2o',
'keras': 'h5',
'sklearn': 'pkl'
}[flavor]
@staticmethod
def map_to_module(flavor: str):
"""
Maps the flavor to the module that is imported
:param flavor: Mlflow flavor
:return: Python module string
"""
return {
'spark': 'pyspark',
'h2o': 'h2o',
'keras': 'tensorflow.keras',
'sklearn': 'sklearn'
}[flavor]
class DatabaseSupportedLibs:
"""
Class containing supported model libraries for native database model deployment
"""
@staticmethod
def get_valid():
return (
'spark', 'h2o', 'sklearn', 'keras'
)
class ModelStatuses:
"""
Class containing names
for In Database Model Deployments
"""
deployed: str = 'DEPLOYED'
deleted: str = 'DELETED'
SUPPORTED_STATUSES = [deployed, deleted]
|
'''
Ряд - 3
'''
def printRangeOdd(n):
start = int('1' + '0' * n) - 1
if (n == 1):
end = 0
else:
end = int('9' + '9' * (n - 2))
for i in range(start, end, -2):
print(i, end=' ')
print('')
n = int(input())
printRangeOdd(n)
|
class Solution:
"""
@param nums: the gievn integers
@return: the total Hamming distance between all pairs of the given numbers
@ Time O(32*n) ~= O(n)
@ for i in range(32):
mask = 1 << i
print(i)
print("{0:b}".format(mask))
"""
def totalHammingDistance(self, nums):
# Write your code here
ans = 0
for i in range(32):
zero = one = 0
mask = 1 << i
for num in nums:
if mask & num:
one += 1
else:
zero += 1
ans += one * zero
return ans |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Copyright Zeta Co., Ltd.
## written by @moeseth based on research by @aye_hnin_khine
class MatchedWord():
def __init__(self, word, start):
self.word = word
self.start = start
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class Student(object):
"""构造函数, 从 info 中解析出 name, hours, qpoints, 并计算出 GPA"""
def __init__(self, info):
# 每一条 info 的格式是 'name\thours\tqpoints'
name, hours, qpoints = info.split('\t')
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
# 根据公式计算 GPA
self.GPA = self.qpoints/self.hours
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQPoints (self):
return self.qpoints
def getGPA(self):
return self.GPA
def show(self):
"""打印学生信息"""
print('%s: %.2f' % (self.name, self.GPA) )
if __name__ == '__main__':
# 首先从文件 `stu.dat` 读取信息, 得到 `infoList`
filename = 'stu.dat'
with open(filename) as f:
infoList = f.read().split('\n')
# 通过 `infoList` 中的每一条 `info`, 逐个构造学生对象 `stu`, 并形成数组 `stuList`
stuList = []
for info in infoList:
if info != '':
# 每一条 info 的格式是 'name\thours\tqpoints'
stu = Student(info)
stuList.append(stu)
print('排序前的 [姓名, GPA]')
for stu in stuList:
stu.show()
# 根据 `stu.getGPA()` 对 `stuList` 进行降序排序
sortedStuList = sorted(stuList, key=lambda stu: stu.getGPA(), reverse=True)
print('\n排序后的 [姓名, GPA]')
for stu in sortedStuList:
stu.show()
# 最后打印出所有并列第一的学生的信息
print('\nGPA 最高的同学(们)')
highestGPA = sortedStuList[0].getGPA()
for stu in sortedStuList:
if( stu.getGPA() == highestGPA ):
stu.show()
|
'''
LEGACY CODE
Only use this to steal ideas from
import time
import hashlib
import sys
import json
import os
import secrets
import string
import base64
import ecdsa
import secrets
import string
import logging
# Node's blockchain copy
""" Stores the transactions that this node has in a list.
If the node you sent the transaction adds a block
it will get accepted, but there is a chance it gets
discarded and your transaction goes back as if it was never
processed"""
NODE_PENDING_TRANSACTIONS = []
BLOCKCHAIN = []
ROOT = False
if len(PEER_NODES) == 0:
ROOT = True
BLOCKCHAIN.append(create_genesis_block())
def proof_of_work(a,last_block, data):
start_time = time.time()
global ROOT
if ROOT:
new_block_index = last_block.index + 1
new_block_timestamp = time.time()
NODE_PENDING_TRANSACTIONS = []
lead = 0
if ROOT:
effort, pow_hash = genhash()
global WORK
lead = leadingzeroes(pow_hash.digest())
while lead < WORK:
if len(BLOCKCHAIN) == 0:
ROOT = False
# Check if any node found the solution every 60 seconds
if not ROOT or int((time.time() - start_time) % 60) == 0:
ROOT = True
# If any other node got the proof, stop searching
new_blockchain = consensus(a)
if new_blockchain:
return False, new_blockchain
# generate new hash for next time
effort, pow_hash = genhash()
lead = leadingzeroes(pow_hash.digest())
if not a.empty():
qget = a.get()
qfrom = qget[0]
new_block = qget[1]
print("received a block",qfrom)
if validate(new_block) and new_block.previous_hash == BLOCKCHAIN[len(BLOCKCHAIN) - 1].previous_hash:
BLOCKCHAIN.append(new_block)
return False, BLOCKCHAIN
# Once that hash is found, we can return it as a proof of our work
mined_block = Block(new_block_index, new_block_timestamp, pow_hash.hexdigest(),effort, data, last_block.hash)
return True, mined_block
def mine(a, blockchain, node_pending_transactions):
global BLOCKCHAIN
global WORK
NODE_PENDING_TRANSACTIONS = node_pending_transactions
while True:
"""Mining_classes is the only way that new coins can be created.
In order to prevent too many coins to be created, the process
is slowed down by a proof of work algorithm.
"""
# Get the last proof of work
last_block = None
new_block_data = None
if ROOT:
last_block = BLOCKCHAIN[len(BLOCKCHAIN) - 1]
NODE_PENDING_TRANSACTIONS = requests.get(
"http://" + MINER_NODE_URL + ":" + str(PORT) + "/txion?update=" + user.public_key).content
NODE_PENDING_TRANSACTIONS = json.loads(NODE_PENDING_TRANSACTIONS)
# Then we add the mining reward
NODE_PENDING_TRANSACTIONS.append({
"from": "network",
"to": user.public_key,
"amount": 1.0})
new_block_data = {"transactions": list(NODE_PENDING_TRANSACTIONS)}
proof = proof_of_work(a,last_block, new_block_data)
if not proof[0]:
BLOCKCHAIN = proof[1]
continue
else:
mined_block = proof[1]
String
print("#",mined_block)
String
REPR
# print("b{} = ".format(mined_block.index), repr(mined_block))
# if last_block.index == 1:
# print('work = {}'.format(work))
# print("blockchain = [", end="")
# for i in range(0, len(BLOCKCHAIN)+1):
# print("b{}".format(i), end=",")
# print("]")
# sys.exit()
END REPR
BLOCKCHAIN.append(mined_block)
a.put(["mined_lower",BLOCKCHAIN])
requests.get("http://" + MINER_NODE_URL + ":" + str(PORT) + "/blocks?update=" + user.public_key)
for node in PEER_NODES:
url = "http://" + node + ":" + str(PORT) + "/block"
headers = {"Content-Type": "application/json"}
data = mined_block.exportjson();
requests.post(url,json = data, headers = headers)
'''
|
# https://leetcode.com/problems/remove-element/description/
#
# algorithms
# Easy (41.9%)
# Total Accepted: 312.2k
# Total Submissions: 745.1k
# beats 100.00% of python submissions
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
length = len(nums)
head, tail = 0, length - 1
while head <= tail:
if nums[head] == val:
while head <= tail and nums[tail] == val:
tail -= 1
if head < tail:
nums[head], nums[tail] = nums[tail], nums[head]
tail -= 1
head += 1
return tail + 1
|
NPep = int(input())
NLKgH = []
LKgH = []
rank = []
for each in range(NPep):
KgH = list(input("The format should be: mass, height ").split(" "))
LKgH.append(KgH[0])
LKgH.append(KgH[1])
NLKgH.append(LKgH)
LKgH = []
for each in range(1, len(LKgH)):
rank.append(each)
for each in range(1, len(rank)-1):
if NLKgH[each][0] > NLKgH[each-1][0] and NLKgH[each][1] < NLKgH[each-1][1]:
rank[each] = rank[each-1]
elif NLKgH[each][0] < NLKgH[each-1][0] and NLKgH[each][1] > NLKgH[each-1][1]:
rank[each] = rank[each-1]
elif NLKgH[each][0] > NLKgH[each-1][0] and NLKgH[each][1] > NLKgH[each-1][1]:
pass
for i in rank:
print(i) |
#
# @lc app=leetcode id=349 lang=python3
#
# [349] Intersection of Two Arrays
#
# @lc code=start
class Solution:
def intersection(self, nums1: [], nums2: []) -> []:
# * 直接转换成set计算交集
return list(set(nums1).intersection(set(nums2)))
def test(self):
assert(self.intersection([1,2,2,1], [2,2]) == [2])
assert(self.intersection([4,9,5], [9,4,9,8,4]) == [9,4])
sol = Solution()
sol.test()
# @lc code=end
|
def lower_bound(nums, target):
l, r = 0, len(nums)
while l < r:
mid = (l + r) // 2
if nums[mid] < target:
l = mid + 1
else:
r = mid
return l
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
l, r = lower_bound(nums, lower), lower_bound(nums, upper)
# print(l, r)
if lower == upper:
if l == len(nums) or (l < len(nums) and nums[l] != lower):
return [str(lower)]
else:
return []
if lower > upper:
return []
if r == 0:
if len(nums) > 0 and nums[0] == upper:
upper -= 1
if lower == upper:
return [str(lower)]
return ['{}->{}'.format(lower, upper)]
if l == len(nums):
return ['{}->{}'.format(lower, upper)]
ret = []
if nums[l] > lower:
_upnum = nums[l] - 1
if lower == _upnum:
ret.append(str(lower))
else:
ret.append('{}->{}'.format(lower, _upnum))
while l + 1 < r:
_lower = nums[l] + 1
_upper = nums[l + 1] - 1
if _lower < _upper:
ret.append('{}->{}'.format(_lower, _upper))
elif _lower == _upper:
ret.append(str(_lower))
l += 1
if r < len(nums) and upper == nums[r]:
upper -= 1
_lower = nums[l] + 1
_upper = upper
if _lower < _upper:
ret.append('{}->{}'.format(_lower, _upper))
elif _lower == _upper:
ret.append(str(_lower))
return ret
|
""" Apache Avro dependencies. """
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def avro_repositories():
http_file(
name = "avro_tools",
sha256 = "ab158f4af8f767d2358a29d8678939b2a0f96017490acfb4e7ed0708cea07913",
urls = ["https://archive.apache.org/dist/avro/avro-1.10.2/java/avro-tools-1.10.2.jar"],
)
AVRO_ARTIFACTS = ["org.apache.avro:avro:1.10.2"]
|
number = int(input("Number? "))
factorial = 1
while number > 0:
factorial += factorial * (number - 1)
number -= 1
print("Factorial: " + str(factorial)) |
__version__ = "0.9.6"
__title__ = "joulescope"
__description__ = 'Joulescope™ host driver and utilities'
__url__ = 'https://joulescope.readthedocs.io'
__author__ = 'Jetperch LLC'
__author_email__ = 'joulescope-dev@jetperch.com'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2018-2021 Jetperch LLC'
|
"""
index: 018
problem: 삼각형을 따라 내려가면서 합이 최대가 되는 경로 찾기
"""
triangle = """75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"""
triangle = list(map(lambda x: list(map(int, x.split(" "))), triangle.split("\n")))
def main(i, depth):
if depth >= len(triangle):
return 0
return max(main(i, depth + 1), main(i + 1, depth + 1)) + triangle[depth][i]
print("\n", main(0, 0))
|
## Multiply
## 8 kyu
## https://www.codewars.com//kata/50654ddff44f800200000004
def multiply(a, b):
return a * b |
def get_value_from_node_by_name(node, value_name):
tmp_value_name = value_name
if value_name == 'Color' and node.type == 'BSDF_PRINCIPLED':
tmp_value_name = "Base Color"
if tmp_value_name in node.inputs.keys():
if node.inputs[tmp_value_name].type == 'RGBA':
r, g, b, a = node.inputs[tmp_value_name].default_value
return [r, g, b, a]
else:
return node.inputs[value_name].default_value
|
class ExamRoom:
def __init__(self, n: int):
self.occupied = []
self.n = n
def seat(self) -> int:
if not self.occupied:
self.occupied.append(0)
return 0
left, right = -self.occupied[0], self.occupied[0]
maximum = (right - left) // 2
for start, end in zip(self.occupied, self.occupied[1:] + [2* self.n - 2 - self.occupied[-1]]):
if (end - start) // 2 > maximum:
left, right = start, end
maximum = (right - left) //2
bisect.insort(self.occupied, left + maximum)
return left + maximum
def leave(self, p: int) -> None:
self.occupied.remove(p)
# Your ExamRoom object will be instantiated and called as such:
# obj = ExamRoom(n)
# param_1 = obj.seat()
# obj.leave(p)
|
DATA_DIR = './data/'
SAVE_DIR = './pts/'
DATA_FPATH = 'ml-100k/u.data'
DATA_COLS = ['user_id', 'item_id', 'rating', 'timestamp']
POS_THRESH = 3.5
TRAIN_PATH = DATA_DIR + 'train.dat'
VALID_PATH = DATA_DIR + 'valid.txt'
|
# -*- Python -*-
# Given a source file, generate a test name.
# i.e. "common_runtime/direct_session_test.cc" becomes
# "common_runtime_direct_session_test"
load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda", "cuda_default_copts")
# Sanitize a dependency so that it works correctly from code that includes
# TensorFlow as a submodule.
def clean_dep(dep):
return str(Label(dep))
# LINT.IfChange
def tf_copts():
return ([
"-DEIGEN_AVOID_STL_ARRAY",
"-Iexternal/gemmlowp",
"-Wno-sign-compare",
"-fno-exceptions",
] + if_cuda(["-DGOOGLE_CUDA=1"]))
def _cuda_copts():
"""Gets the appropriate set of copts for (maybe) CUDA compilation.
If we're doing CUDA compilation, returns copts for our particular CUDA
compiler. If we're not doing CUDA compilation, returns an empty list.
"""
return cuda_default_copts() + select({
"//conditions:default": [],
"@local_config_cuda//cuda:using_nvcc": ([
"-nvcc_options=relaxed-constexpr",
"-nvcc_options=ftz=true",
]),
"@local_config_cuda//cuda:using_clang": ([
"-fcuda-flush-denormals-to-zero",
]),
})
def tf_cuda_library(deps=None, cuda_deps=None, copts=None, **kwargs):
"""Generate a cc_library with a conditional set of CUDA dependencies.
When the library is built with --config=cuda:
- both deps and cuda_deps are used as dependencies
- the cuda runtime is added as a dependency (if necessary)
- The library additionally passes -DGOOGLE_CUDA=1 to the list of copts
Args:
- cuda_deps: BUILD dependencies which will be linked if and only if:
'--config=cuda' is passed to the bazel command line.
- deps: dependencies which will always be linked.
- copts: copts always passed to the cc_library.
- kwargs: Any other argument to cc_library.
"""
if not deps:
deps = []
if not cuda_deps:
cuda_deps = []
if not copts:
copts = []
native.cc_library(
deps=deps + if_cuda(cuda_deps + [
# clean_dep("//tensorflow/core:cuda"),
"@local_config_cuda//cuda:cuda_headers"
]),
copts=copts + if_cuda(["-DGOOGLE_CUDA=1"]),
**kwargs)
# When this target is built using --config=cuda, a cc_library is built
# that passes -DGOOGLE_CUDA=1 and '-x cuda', linking in additional
# libraries needed by GPU kernels.
def tf_gpu_kernel_library(srcs,
copts=[],
cuda_copts=[],
deps=[],
hdrs=[],
**kwargs):
copts = copts + _cuda_copts() + if_cuda(cuda_copts) + tf_copts()
native.cc_library(
srcs=srcs,
hdrs=hdrs,
copts=copts,
deps=deps + if_cuda([
# clean_dep("//tensorflow/core:cuda"),
# clean_dep("//tensorflow/core:gpu_lib"),
"@local_config_cuda//cuda:cuda_headers"
]),
alwayslink=1,
**kwargs)
|
#Файл созданный для записи необходимых токенов для сервиса
#оформлен в виде get функций для того, чтобы данные нельзя было изменить
def bot_token():
return "your_token"
def yandex_token():
return "your_token" |
class Solution:
def minSubArrayLen(self, s: int, nums: list) -> int:
# Time Complexity: O(n)
# Space Complexity: O(1)
# TODO Binary Search O(nlog(n))
if not nums or sum(nums) < s:
return 0
min_len = len(nums)
current_sum = 0
left = 0
for right in range(len(nums)):
current_sum += nums[right]
while current_sum >= s:
min_len = min(min_len, right - left + 1)
current_sum -= nums[left]
left += 1
return min_len
s = 7; nums = [2,3,1,2,4,3]
s = 3; nums = [1,1]
sol = Solution()
print(sol.minSubArrayLen(s, nums))
|
# Adding an if statement so that the print statements aren't so wrong!
# This was not part of the exercise
animals = ['Dog', 'Cat', 'Dolphin', 'Wolf', 'Polar bear', 'Penguin']
for animal in animals:
if animal == 'Dog' or animal == 'Cat':
print(f"A {animal.lower()} would make a great pet!")
else:
print(f"A {animal.lower()} would NOT make a great pet.")
print("You should be careful about what sort of animal you pick as a pet!")
|
# Fibonacci series
class FibonacciSeriesDemo:
Instances = 0
def __init__(self):
FibonacciSeriesDemo.Instances += 1
def displayFibonacci(self, title, value):
first, second = 0, 1
print(f"----- {title}till {value} -----")
print(f'FibonacciSeriesDemo.Instances: {self.Instances}')
while first < value:
print(first)
# print(f'----- {first} {second} -----')
first, second = second, first+second
title = "Fibonacci Series Demo"
fibonacci = FibonacciSeriesDemo()
fibonacci.displayFibonacci(title, 10)
fibonacci.displayFibonacci(title, 20)
# first, second = 0, 1
# while first < 10:
# print(first)
# print(f'----- {first} {second} -----')
# first, second = second, first+second
|
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: lines.py
#
# Tests: mesh - 2D lines (unstructured), 3D lines (unstructured)
# plots - mesh
#
# Programmer: Alister Maguire
# Date: Tue Mar 17 08:50:32 PDT 2020
#
# Modifications:
#
# Mark C. Miller, Mon Jan 11 10:32:17 PST 2021
# Replace AssertEqual() with TestValueEQ()
# ----------------------------------------------------------------------------
def TestMeshPlot():
#
# First, let's make sure that 3d lines are read appropriately.
#
v = GetView3D()
v.viewNormal = (0.9, 0.35, -0.88)
SetView3D(v)
OpenDatabase(data_path("lines_test_data/spring.lines"))
AddPlot("Mesh", "Lines", 1, 1)
DrawPlots()
Query("SpatialExtents")
# Check dimensionality.
ext_len = len(GetQueryOutputValue())
TestValueEQ("Verifying 3D lines", ext_len, 6)
# Check the rendering.
Test("mesh_plot_00")
DeleteAllPlots()
CloseDatabase(data_path("lines_test_data/spring.lines"))
#
# Next, let's check 2d lines.
#
OpenDatabase(data_path("lines_test_data/2d.lines"))
AddPlot("Mesh", "Lines", 1, 1)
DrawPlots()
Query("SpatialExtents")
# Check dimensionality.
ext_len = len(GetQueryOutputValue())
TestValueEQ("Verifying 2D lines", ext_len, 4)
# Check the rendering.
Test("mesh_plot_01")
DeleteAllPlots()
CloseDatabase(data_path("lines_test_data/2d.lines"))
#
# This test makes sure that consecutive points are only
# removed from one line at a time.
#
OpenDatabase(data_path("lines_test_data/consecutive.lines"))
AddPlot("Mesh", "Lines", 1, 1)
DrawPlots()
# Check the rendering.
Test("mesh_plot_02")
DeleteAllPlots()
CloseDatabase(data_path("lines_test_data/consecutive.lines"))
def main():
TestMeshPlot()
Exit()
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.