content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2021, Cisco Systems # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" --- module: trusted_certificate_info short_description: Information module for Trusted Certificate description: - Get all Trus...
documentation = '\n---\nmodule: trusted_certificate_info\nshort_description: Information module for Trusted Certificate\ndescription:\n- Get all Trusted Certificate.\n- Get Trusted Certificate by id.\nversion_added: \'1.0.0\'\nauthor: Rafael Campos (@racampos)\noptions:\n page:\n description:\n - Page query para...
class InvalidColorMapException(Exception): def __init__(self, *args): if len(args)==1 and isinstance(args[0], str): self.message = args[0] else: self.message = "Invalid colormap." class InvalidFileFormatException(Exception): def __init__(self, *args): if ...
class Invalidcolormapexception(Exception): def __init__(self, *args): if len(args) == 1 and isinstance(args[0], str): self.message = args[0] else: self.message = 'Invalid colormap.' class Invalidfileformatexception(Exception): def __init__(self, *args): if len(...
""" Naive approaches: Using two loops: for each node in list: from start to curr each node: check curr node is its next node using modified Node structure using visited field in each node traverse list and mark each curr node as visited while traversing check if curr node is alre...
""" Naive approaches: Using two loops: for each node in list: from start to curr each node: check curr node is its next node using modified Node structure using visited field in each node traverse list and mark each curr node as visited while traversing check if curr node is alre...
line = input().split(', ') my_dict = {} counter = 1 country = [] while counter <= 2: for n in range(len(line)): if counter ==1: country.append(line[n]) else: my_dict[country[n]] = line[n] counter+=1 if counter >2: break line = input(). split(', ') for ...
line = input().split(', ') my_dict = {} counter = 1 country = [] while counter <= 2: for n in range(len(line)): if counter == 1: country.append(line[n]) else: my_dict[country[n]] = line[n] counter += 1 if counter > 2: break line = input().split(', ') for (...
def is_prime(number): """checks if a given number is prime""" prime = True for n in range(2, number): if prime and number % n == 0: prime = False print("The number is not prime") if prime: print("The number is prime") return prime if __name__ == "__main__": ...
def is_prime(number): """checks if a given number is prime""" prime = True for n in range(2, number): if prime and number % n == 0: prime = False print('The number is not prime') if prime: print('The number is prime') return prime if __name__ == '__main__': ...
# NOTE: You need to check directory's permission MAX_HEIGHT = 1536 # 1536 # 768 # 1280 # 1024 # 2048 # 2688 MAX_WIDTH = 3072 # 3072 # 1536 # 2560 # 2048 # 4096 # 5376 CROP_HEIGHT = 512 # 256, 384, 512 CROP_WIDTH = 512 # 512, 768, 1024 RESIZE_HEIGHT = 1536 RESIZE_WIDTH = 3072 # MNT_PATH = '/nfs/host/PConv-Kera...
max_height = 1536 max_width = 3072 crop_height = 512 crop_width = 512 resize_height = 1536 resize_width = 3072 mnt_path = '/nfs/host/PConv-Keras' original_path = ['{}/house-dataset-src/original/'.format(MNT_PATH)] resized_path = ['{}/house-dataset/resize-train-1536x3072/00'.format(MNT_PATH)] train_path = '{}/house-data...
# O(n+k) time complexity (Worst time complexity - O(2n-1)): # O(k) (Get Slice 1) # O(n-k) (Get Slice 2) # O(k) (Concatenate Slices) # CPython time-complexity - https://wiki.python.org/moin/TimeComplexity # O(1) space complexity # Rotates the characters in a string by a given input and have the overflow appear ...
def rotated_string(input_string, input_number): input_number = input_number % len(input_string) print(input_string[-input_number:] + input_string[:-input_number]) return input_string[-input_number:] + input_string[:-input_number] def test_rotated_string(): assert rotated_string('MyString', 2) == 'ngMyS...
def main(): print ('Filter data') input_f = open('../data/result_size_large_files.tsv') output_f = open('../data/result_size_large.csv', 'w') lines = input_f.readlines() distributions = ['Combo', 'Diagonal', 'DiagonalRot', 'Gauss', 'Parcel', 'Uniform'] for line in lines: print (line) ...
def main(): print('Filter data') input_f = open('../data/result_size_large_files.tsv') output_f = open('../data/result_size_large.csv', 'w') lines = input_f.readlines() distributions = ['Combo', 'Diagonal', 'DiagonalRot', 'Gauss', 'Parcel', 'Uniform'] for line in lines: print(line) ...
# Implementation of a Stack. class Stack: class Node: # Node class (or pointers that hold a value and direction to next node). def __init__(self, val=None): self.val = val self.nextNode = None def __init__(self): self.head = None # Add new node with value to stack...
class Stack: class Node: def __init__(self, val=None): self.val = val self.nextNode = None def __init__(self): self.head = None def push(self, val): new_node = self.Node(val) if self.head is None: self.head = newNode else: ...
""" Constants and other config variables used throughout the packagemanager module Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ # Location of ca certs file on Linux LINUX_CA_FILE = '/etc/ssl/certs/ca-certificates.crt' # Buffer size for streaming the downlaod file to c...
""" Constants and other config variables used throughout the packagemanager module Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ linux_ca_file = '/etc/ssl/certs/ca-certificates.crt' stream_buffer = 4000
j= 7 for i in range(9+1): if i%2 ==1: print(f"I={i} J={j}") print(f"I={i} J={j-1}") print(f"I={i} J={j-2}") j =j+2
j = 7 for i in range(9 + 1): if i % 2 == 1: print(f'I={i} J={j}') print(f'I={i} J={j - 1}') print(f'I={i} J={j - 2}') j = j + 2
class BearToy: def __init__(self, name, size, color): self.name = name self.size = size self.color = color def sing(self): print('I am %s, lalala...' % self.name) class NewBear(BearToy): def __init__(self, name, size, color, material): # BearToy.__init__(self, name,...
class Beartoy: def __init__(self, name, size, color): self.name = name self.size = size self.color = color def sing(self): print('I am %s, lalala...' % self.name) class Newbear(BearToy): def __init__(self, name, size, color, material): super(NewBear, self).__init_...
class DesignerSummary(object): def __init__(self, designer_name, summary): self.designer_name = designer_name self.summary = summary def print_summary(self): print("[%s]" % self.designer_name) print(" %s" % self.max_price()) print(" %s" % self.avg_price()) ...
class Designersummary(object): def __init__(self, designer_name, summary): self.designer_name = designer_name self.summary = summary def print_summary(self): print('[%s]' % self.designer_name) print(' %s' % self.max_price()) print(' %s' % self.avg_price()) pri...
qrel_input = 'data/expert/qrels-covid_d4_j3.5-4.txt' doc_type = 'expert' qrel_name = 'baseline_doc' qrel_path = f'qrels/{doc_type}/{qrel_name}' with open(qrel_path, 'w') as fo: with open(qrel_input) as f: for line in f: line = line.strip().split() if line: query_id, _, doc_id, dq_rank = line query_i...
qrel_input = 'data/expert/qrels-covid_d4_j3.5-4.txt' doc_type = 'expert' qrel_name = 'baseline_doc' qrel_path = f'qrels/{doc_type}/{qrel_name}' with open(qrel_path, 'w') as fo: with open(qrel_input) as f: for line in f: line = line.strip().split() if line: (query_id, ...
class BoundingBox: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.k = 2 # scaling factor def get_x_center(self): return(self.x1 + self.x2) / 2 def get_y_center(self): return(self.y1 + self.y2)...
class Boundingbox: def __init__(self, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.k = 2 def get_x_center(self): return (self.x1 + self.x2) / 2 def get_y_center(self): return (self.y1 + self.y2) / 2 def compute_outp...
s = 0 for i in range(2,100): for j in range(2,i): if i % j == 0: break else: s += i print(s)
s = 0 for i in range(2, 100): for j in range(2, i): if i % j == 0: break else: s += i print(s)
n1= input() n2 = input() j = 1 for i in range(1,n1+1): j = i*j k = j%n2 print(k) print("\n")
n1 = input() n2 = input() j = 1 for i in range(1, n1 + 1): j = i * j k = j % n2 print(k) print('\n')
# Used to test import statements for the NoopAugmentor plugin. def noop(x): return x
def noop(x): return x
C = int(input()) if C>=2 and C<=99: for i in range(C): x =input() print("gzuz")
c = int(input()) if C >= 2 and C <= 99: for i in range(C): x = input() print('gzuz')
def my_bilateral_filter(ImgNoisy, window_size = 3 , sigma_d = 4, sigma_r = 40): # sigma_d : smoothing weight factor # sigma_r : range weight factor height = ImgNoisy.shape[0] width = ImgNoisy.shape[1] # Initialize the filtered image: filtered_image = np.empty([height,width]) # S...
def my_bilateral_filter(ImgNoisy, window_size=3, sigma_d=4, sigma_r=40): height = ImgNoisy.shape[0] width = ImgNoisy.shape[1] filtered_image = np.empty([height, width]) window_boundary = int(np.ceil(window_size / 2)) for i in range(height): for j in range(width): normalization_co...
input = """ % This is most similar to nonground.query.3, just without the second % constraint. We originally failed to process this correctly. color(red,X) | color(green,X) | color(blue,X) :- node(X). node("Cosenza"). node("Vienna"). node("Diamante"). redish :- color(red,"Vienna"). dark :- not color(red,"V...
input = '\n% This is most similar to nonground.query.3, just without the second\n% constraint. We originally failed to process this correctly.\n\ncolor(red,X) | color(green,X) | color(blue,X) :- node(X).\n\nnode("Cosenza").\nnode("Vienna").\nnode("Diamante").\n\nredish :- color(red,"Vienna").\ndark :- not color(red,"Vi...
class EventTableData: def __init__(self): self._header_tag = 'th' self._dispo_header = False self._event_row = -1 def store_data(self, case_parser, data): if self._dispo_header: self._event_row += 1 case_parser.event_table_data.append([]) ...
class Eventtabledata: def __init__(self): self._header_tag = 'th' self._dispo_header = False self._event_row = -1 def store_data(self, case_parser, data): if self._dispo_header: self._event_row += 1 case_parser.event_table_data.append([]) cas...
"""Ogre Package @author Michael Reimpell """ # epydoc doc format __docformat__ = "javadoc en" __all__ = ["base", "gui", "materialexport", "armatureexport", "meshexport"]
"""Ogre Package @author Michael Reimpell """ __docformat__ = 'javadoc en' __all__ = ['base', 'gui', 'materialexport', 'armatureexport', 'meshexport']
class IceCreamMachine: all={} def __init__(self, ingredients, toppings): self.ingredients = ingredients self.toppings = toppings def scoops(self): res = [] for i in self.ingredients: for j in self.toppings: res.append([i, j]) return res m...
class Icecreammachine: all = {} def __init__(self, ingredients, toppings): self.ingredients = ingredients self.toppings = toppings def scoops(self): res = [] for i in self.ingredients: for j in self.toppings: res.append([i, j]) return res...
class lennox_period(object): def __init__(self, id): self.id = id self.enabled = False self.startTime = None self.systemMode = None self.hsp = None self.hspC = None self.csp = None self.cspC = None self.sp = None self.spC = None ...
class Lennox_Period(object): def __init__(self, id): self.id = id self.enabled = False self.startTime = None self.systemMode = None self.hsp = None self.hspC = None self.csp = None self.cspC = None self.sp = None self.spC = None ...
#Write a function that reverses a string. The input string is given as an array of characters char[]. #Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. #You may assume all the characters consist of printable ascii characters. #Runtime: beats ...
class Solution(object): def reverse_string(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ half = int(len(s) - 1) / 2 last = len(s) - 1 print(len(s)) print(half) for i in range(0, half + 1):...
#Inverter valores de 2 variaveis lidas. a = input("Insira o valor de A: "); b = input("Insira o valor de B: ") c = a a = b b = c print("O valor de A (invertida): " + str(a) + " e o de B (invertido): " + str(b))
a = input('Insira o valor de A: ') b = input('Insira o valor de B: ') c = a a = b b = c print('O valor de A (invertida): ' + str(a) + ' e o de B (invertido): ' + str(b))
### Insert a node at the head of a linked list - Solution class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def print_singly_linked_list(node): whi...
class Singlylinkedlistnode: def __init__(self, node_data): self.data = node_data self.next = None class Singlylinkedlist: def __init__(self): self.head = None self.tail = None def print_singly_linked_list(node): while node != None: print(node.data) node = ...
# function to increase the pixel by one inside each box def add_heat(heatmap, bbox_list): # Iterate through list of bboxes for box in bbox_list: # Add += 1 for all pixels inside each bbox # Assuming each "box" takes the form ((x1, y1), (x2, y2)) heatmap[box[0][1]:box[1][1], box[0][0]:box...
def add_heat(heatmap, bbox_list): for box in bbox_list: heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 return heatmap def apply_threshold(heatmap, threshold): heatmap[heatmap <= threshold] = 0 return heatmap
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null,...
class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.range = [] while head: self.range.append(head.val) head = h...
fim = int(input("Digite um numero: ")) x = 0 while x <= fim: if not x % 2 == 0: print(x) x += 1
fim = int(input('Digite um numero: ')) x = 0 while x <= fim: if not x % 2 == 0: print(x) x += 1
# !/usr/bin/env python """ Provides the gcd and s, t of Euclidian algorithim for a given m, n The algorithim states that the GCD of 2 numbers is equal to a product of the one of the numbers and a coefficient, s added with the product of the remaining number and a coefficient, t. """ def gcd(m,n,buffer): """Retu...
""" Provides the gcd and s, t of Euclidian algorithim for a given m, n The algorithim states that the GCD of 2 numbers is equal to a product of the one of the numbers and a coefficient, s added with the product of the remaining number and a coefficient, t. """ def gcd(m, n, buffer): """Returns the GCD through rec...
class EmployeeApi: endpoint = 'Employee.json' def __init__(self, client): self.client = client def get_employee(self, employeeId): return self.client.get(endpoint=self.endpoint, payload={ "employeeID": employeeId, "load_relations": '["Contact"]' })
class Employeeapi: endpoint = 'Employee.json' def __init__(self, client): self.client = client def get_employee(self, employeeId): return self.client.get(endpoint=self.endpoint, payload={'employeeID': employeeId, 'load_relations': '["Contact"]'})
# HARD # Input: "abcd" # reverse input => as rev = "dcba" # compare s[:n-i] with rev[i:] # abcd vs dcba # abc vs cba # ab vs ba # a vs a => i == 3 # the same substring is the overlapped part of the result, thus rev[:i] + s is the result # Time O(N^2) Space O(n) # KMP prefix tabl...
class Solution: def shortest_palindrome(self, s: str) -> str: return self.slow(s) def slow(self, s): n = len(s) rev = ''.join(reversed(list(s))) for i in range(n): if s[:n - i] == rev[i:]: return rev[:i] + s return '' def fast(self, s): ...
''' Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. Permutation and combination ''' class Solution: def dfs(self, result, combination, nums, start_index, depth): if depth==0: result.append(combinat...
""" Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. Permutation and combination """ class Solution: def dfs(self, result, combination, nums, start_index, depth): if depth == 0: result.append(combi...
def build_schema_query(table_schema): schema_query = """ SELECT table_name, column_name, column_default, is_nullable, data_type, character_maximum_length FROM information_schema.columns WHERE table_schema =...
def build_schema_query(table_schema): schema_query = "\n SELECT table_name,\n column_name,\n column_default,\n is_nullable,\n data_type,\n character_maximum_length\n FROM information_schema.columns\n WHERE table_sc...
{ 'application':{ 'type':'Application', 'name':'HtmlPreview', 'backgrounds': [ { 'type':'Background', 'name':'bgMin', 'title':'HTML Preview', #'size':(800, 600), 'statusBar':1, 'style':['resizeable'], 'components': [ { 'type':'HtmlWindow', 'name':'html', ...
{'application': {'type': 'Application', 'name': 'HtmlPreview', 'backgrounds': [{'type': 'Background', 'name': 'bgMin', 'title': 'HTML Preview', 'statusBar': 1, 'style': ['resizeable'], 'components': [{'type': 'HtmlWindow', 'name': 'html', 'size': (400, 200), 'text': ''}]}]}}
expected_output = { "vrf": { "default": { "address_family": { "ipv4": { "instance": { "1": { "areas": { "0.0.0.0": { "database": { ...
expected_output = {'vrf': {'default': {'address_family': {'ipv4': {'instance': {'1': {'areas': {'0.0.0.0': {'database': {'lsa_types': {1: {'lsa_type': 1, 'lsas': {'10.4.1.1 10.4.1.1': {'adv_router': '10.4.1.1', 'lsa_id': '10.4.1.1', 'ospfv2': {'body': {'router': {'links': {'10.4.1.1': {'link_data': '255.255.255.255', '...
pkgname = "fontconfig" pkgver = "2.14.0" pkgrel = 0 build_style = "gnu_configure" configure_args = [ "--enable-static", "--enable-docs", f"--with-cache-dir=/var/cache/{pkgname}", ] make_cmd = "gmake" hostmakedepends = ["pkgconf", "gperf", "gmake", "python"] makedepends = ["libexpat-devel", "freetype-bootstrap",...
pkgname = 'fontconfig' pkgver = '2.14.0' pkgrel = 0 build_style = 'gnu_configure' configure_args = ['--enable-static', '--enable-docs', f'--with-cache-dir=/var/cache/{pkgname}'] make_cmd = 'gmake' hostmakedepends = ['pkgconf', 'gperf', 'gmake', 'python'] makedepends = ['libexpat-devel', 'freetype-bootstrap', 'libuuid-d...
# second_index # Created by JKChang # 10/04/2018, 09:15 # Tag: # Description: You are given two strings and you have to find an index of the second occurrence of the second string in # the first one. # # Input: Two strings. # # Output: Int or None def second_index(text: str, symbol: str): """ returns the s...
def second_index(text: str, symbol: str): """ returns the second index of a symbol in a given text """ res = [i for (i, x) in enumerate(text) if x == symbol] if len(res) >= 2: return res[1] return None if __name__ == '__main__': print('Example:') print(second_index('sims', 's...
""" Print the pattern of * * * * * * * * * * * * * * * """ n = 5 k = n - 1 for i in range(0, n): for j in range(0, k): print(end=" ") k = k - 1 for j in range(0, i + 1): print("* ", end="") print()
""" Print the pattern of * * * * * * * * * * * * * * * """ n = 5 k = n - 1 for i in range(0, n): for j in range(0, k): print(end=' ') k = k - 1 for j in range(0, i + 1): print('* ', end='') print()
''' Created on 09-May-2017 @author: Sathesh Rgs ''' print("Program to display armstrong numbers between two intervals") try: print("Enter the starting and ending intervals") si=int(input()) ei=int(input()) print("The armstrong numbers between",si,"and",ei,"are") for num in range(si,ei+1): ...
""" Created on 09-May-2017 @author: Sathesh Rgs """ print('Program to display armstrong numbers between two intervals') try: print('Enter the starting and ending intervals') si = int(input()) ei = int(input()) print('The armstrong numbers between', si, 'and', ei, 'are') for num in range(si, ei + 1)...
class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: answer=0 u=[0]*len(points) unionMap={} if len(points)==1: return 0 edges=[] for i in range(len(points)): u[i]=i unionMap[i]=[i] f...
class Solution: def min_cost_connect_points(self, points: List[List[int]]) -> int: answer = 0 u = [0] * len(points) union_map = {} if len(points) == 1: return 0 edges = [] for i in range(len(points)): u[i] = i unionMap[i] = [i] ...
"""Top-level package for simplecarboncleaner.""" __author__ = """Abhishek Bhatia""" __email__ = 'bhatiaabhishek8893@gmail.com' __version__ = '0.1.0'
"""Top-level package for simplecarboncleaner.""" __author__ = 'Abhishek Bhatia' __email__ = 'bhatiaabhishek8893@gmail.com' __version__ = '0.1.0'
''' A simple test ''' def test_pytest(): '''test_pytest Summary ------- Dummy test function. ''' assert True
""" A simple test """ def test_pytest(): """test_pytest Summary ------- Dummy test function. """ assert True
#!/usr/bin/env python def yell(text): return text.upper() + '!' print(yell('hello')) # Functions are objects bark = yell print(bark('woof')) del yell print(bark('hey')) # error # print(yell('hello')) print(bark.__name__) print(bark.__qualname__) funcs = [bark, str.lower, str.capitalize] print(funcs) for f in ...
def yell(text): return text.upper() + '!' print(yell('hello')) bark = yell print(bark('woof')) del yell print(bark('hey')) print(bark.__name__) print(bark.__qualname__) funcs = [bark, str.lower, str.capitalize] print(funcs) for f in funcs: print(f, f('hey there')) print(funcs[0]('hey yo')) def greet(func): ...
#Python number # int # float # complex x = 1 y = 13.23 z = 1j print(x) print(y) print(z) print("-----------------------------------") print(type(x)) print(type(y)) print(type(z)) print("-----------------------------------")
x = 1 y = 13.23 z = 1j print(x) print(y) print(z) print('-----------------------------------') print(type(x)) print(type(y)) print(type(z)) print('-----------------------------------')
class BaseError(Exception): pass class UnknownError(BaseError): pass class AccessTokenRequired(BaseError): pass class BadOAuthTokenError(BaseError): pass class BadRequestError(BaseError): pass class TokenError(BaseError): pass
class Baseerror(Exception): pass class Unknownerror(BaseError): pass class Accesstokenrequired(BaseError): pass class Badoauthtokenerror(BaseError): pass class Badrequesterror(BaseError): pass class Tokenerror(BaseError): pass
def numIslands(self, grid: List[List[str]]) -> int: count = 0 rows = len(grid) cols = len(grid[0]) ''' very similar solution to all these permuation problems going through each coordinate and changing them if they are connected ''' ...
def num_islands(self, grid: List[List[str]]) -> int: count = 0 rows = len(grid) cols = len(grid[0]) ' very similar solution to all these permuation problems\n going through each coordinate and changing them if they are\n connected\n ' def explore(i, j): if grid[...
""" For address = "prettyandsimple@example.com", the output should be findEmailDomain(address) = "example.com"; """ def findEmailDomain(address): return address.split('@')[-1] def findEmailDomain(address): return address[address.rfind('@')+1:]
""" For address = "prettyandsimple@example.com", the output should be findEmailDomain(address) = "example.com"; """ def find_email_domain(address): return address.split('@')[-1] def find_email_domain(address): return address[address.rfind('@') + 1:]
extension = ''' # from sqlalchemy.ext.declarative import declarative_base # # from core.factories import Session from sqlalchemy import MetaData from gino.ext.starlette import Gino from core.factories import settings db: MetaData = Gino(dsn=settings.DATABASE_URL) '''
extension = '\n# from sqlalchemy.ext.declarative import declarative_base\n# # from core.factories import Session\nfrom sqlalchemy import MetaData\nfrom gino.ext.starlette import Gino\nfrom core.factories import settings\n\n\ndb: MetaData = Gino(dsn=settings.DATABASE_URL)\n\n'
STATS = [ { "num_node_expansions": 0, "search_time": 0.0553552, "total_time": 0.13778, "plan_length": 231, "plan_cost": 231, "objects_used": 140, "objects_total": 250, "neural_net_time": 0.07324552536010742, "num_replanning_steps": 0, "...
stats = [{'num_node_expansions': 0, 'search_time': 0.0553552, 'total_time': 0.13778, 'plan_length': 231, 'plan_cost': 231, 'objects_used': 140, 'objects_total': 250, 'neural_net_time': 0.07324552536010742, 'num_replanning_steps': 0, 'wall_time': 0.7697024345397949}, {'num_node_expansions': 0, 'search_time': 0.0617813, ...
def jwt_response_payload_handler(token,user=None,request=None): return { 'token': token, 'user_id': user.id, 'username': user.username } def jwt_get_user_secret(user): print(user) return user.user_secret
def jwt_response_payload_handler(token, user=None, request=None): return {'token': token, 'user_id': user.id, 'username': user.username} def jwt_get_user_secret(user): print(user) return user.user_secret
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres...
#!/usr/bin/env python3 k = int(input()) a, b = map(int, input().split()) for i in range(a, b+1): if i%k == 0: print("OK") exit() print("NG")
k = int(input()) (a, b) = map(int, input().split()) for i in range(a, b + 1): if i % k == 0: print('OK') exit() print('NG')
def user_choice(): """This function is used for navigating user""" userWeight = int(input("\nSelect weight conversion\n" + "1. kg\n" + "2. stone\n" + "3. pound\n")) if userWeight == 1: kilograms() elif...
def user_choice(): """This function is used for navigating user""" user_weight = int(input('\nSelect weight conversion\n' + '1. kg\n' + '2. stone\n' + '3. pound\n')) if userWeight == 1: kilograms() elif userWeight == 2: stone() elif userWeight == 3: pound() def kilograms(): ...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/kinova/MillenCapstone/catkin_ws/src/kinova-ros/kinova_msgs/msg/FingerPosition.msg;/home/kinova/MillenCapstone/catkin_ws/src/kinova-ros/kinova_msgs/msg/JointAngles.msg;/home/kinova/MillenCapstone/catkin_ws/src/kinova-ros/kinova_msgs/msg/JointVelo...
messages_str = '/home/kinova/MillenCapstone/catkin_ws/src/kinova-ros/kinova_msgs/msg/FingerPosition.msg;/home/kinova/MillenCapstone/catkin_ws/src/kinova-ros/kinova_msgs/msg/JointAngles.msg;/home/kinova/MillenCapstone/catkin_ws/src/kinova-ros/kinova_msgs/msg/JointVelocity.msg;/home/kinova/MillenCapstone/catkin_ws/src/ki...
# 5! = 120 # # 5 * 4 * 3 * 2 * 1 def factorial(n): if n == 1: return 1 return n * factorial(n - 1) print(f'5!={factorial(5):,},' # 120 f' 3!={factorial(3):,},' # 6 f' 11!={factorial(11):,}') # HUGE
def factorial(n): if n == 1: return 1 return n * factorial(n - 1) print(f'5!={factorial(5):,}, 3!={factorial(3):,}, 11!={factorial(11):,}')
""" Central location for all hard coded data needed for tests. """ DOWNLOAD_OPTIONS_FROM_ALL_SERVICES = { # 'svc://nasa:srtm-3-arc-second': {}, # 'svc://nasa:srtm-30-arc-second': {}, 'svc://noaa-ncdc:ghcn-daily': { 'properties': [{ 'default': None, 'description': 'parameter'...
""" Central location for all hard coded data needed for tests. """ download_options_from_all_services = {'svc://noaa-ncdc:ghcn-daily': {'properties': [{'default': None, 'description': 'parameter', 'name': 'parameter', 'range': [['air_temperature:daily:mean', 'air_temperature:daily:mean'], ['air_temperature:daily:minimu...
class Solution(object): def isReflected(self, points): """ :type points: List[List[int]] :rtype: bool """ if len(points) < 2: return True twoTimesMid = min(points)[0] + max(points)[0] d = set([(i, j) for i, j in points]) for i, j ...
class Solution(object): def is_reflected(self, points): """ :type points: List[List[int]] :rtype: bool """ if len(points) < 2: return True two_times_mid = min(points)[0] + max(points)[0] d = set([(i, j) for (i, j) in points]) for (i, j) in...
r""" Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ...
""" Invert a binary tree. Example: Input: 4 / \\ 2 7 / \\ / \\ 1 3 6 9 Output: 4 / \\ 7 2 / \\ / \\ 9 6 3 1 """ class Solution: def invert_tree(self, root): """Recursive""" if not root: return root left = self.invertTree(root.righ...
''' Write a Python program to parse a string to Float or Integer. ''' varStr = input("Enter a number: ") print("The string above was parsed an an integer", int(varStr))
""" Write a Python program to parse a string to Float or Integer. """ var_str = input('Enter a number: ') print('The string above was parsed an an integer', int(varStr))
# Compute the Factorial of a given value (n!) # multiply all whole numbers from our chosen number # down to 1. # 4! = 4 * 3 * 2 * 1 # 1 * 1 = 1 # 1 * 2 = 2 # 2 * 3 # iterative approach def fact_i(n): # set a end point fact initial value fact = 1 # loop from 1 to n+1 using an index for i in range(1, ...
def fact_i(n): fact = 1 for i in range(1, n + 1): fact = fact * i return fact print(fact_i(4)) def rec_fact(n): if n <= 1: return 1 else: return n * rec_fact(n - 1) print(rec_fact(4))
def indent_dotcode(dotcode, indent): return '\n'.join(['%s%s' % (indent, line) for line in dotcode.split('\n')]) def sphinx_format(dotcode): dotcode = indent_dotcode(dotcode, ' ') warning_comment = '.. Autogenerated graphviz code. Do not edit manually.' dotcode = "%s\n\n.. graphviz::\n\n%s" ...
def indent_dotcode(dotcode, indent): return '\n'.join(['%s%s' % (indent, line) for line in dotcode.split('\n')]) def sphinx_format(dotcode): dotcode = indent_dotcode(dotcode, ' ') warning_comment = '.. Autogenerated graphviz code. Do not edit manually.' dotcode = '%s\n\n.. graphviz::\n\n%s' % (warni...
"""Small utility functions""" def string_is_true(s: str) -> bool: return s.lower() == 'true'
"""Small utility functions""" def string_is_true(s: str) -> bool: return s.lower() == 'true'
# -*- coding: utf-8 -*- class BaseEndpoint: """ A class used to implement base functionality for Lacework API Endpoints """ def __init__(self, session, object_type, endpoint_root="/api/v2"): """ :param session: An instance of the HttpS...
class Baseendpoint: """ A class used to implement base functionality for Lacework API Endpoints """ def __init__(self, session, object_type, endpoint_root='/api/v2'): """ :param session: An instance of the HttpSession class. :param object_type: The Lacework object type to use. ...
#!/usr/bin/env python # # String Parser. # file : Parser.py # author : Tom Regan <noreply.tom.regan@gmail.com> # since : 2011-07-28 # last modified : 2011-08-04 class BaseParser(object): def parse(self, line): pass class Parser(BaseParser): def parse(self, line): ""...
class Baseparser(object): def parse(self, line): pass class Parser(BaseParser): def parse(self, line): """Reads a line of input and returns a tuple: (method:str, args:tuple) Raises: Exception. NB: Exceptions from other frames must be handled. ...
def cal(n, data): for x in range(1, n+1): if (n % x == 0): tmp = data[:x] for y in range(x, n, x): if data[y:y+x] != tmp: break if(y+x >= n): return x return n n = int(input()) data = list(input()) print(ca...
def cal(n, data): for x in range(1, n + 1): if n % x == 0: tmp = data[:x] for y in range(x, n, x): if data[y:y + x] != tmp: break if y + x >= n: return x return n n = int(input()) data = list(input()) print(c...
def resolve(): ''' code here ''' N = int(input()) As = [int(item) for item in input().split()] As.sort() max_num = max(As) res = 10**9 + 1 if max_num % 2 == 0: if max_num //2 in As: res = max_num //2 else: for item in As: if a...
def resolve(): """ code here """ n = int(input()) as = [int(item) for item in input().split()] As.sort() max_num = max(As) res = 10 ** 9 + 1 if max_num % 2 == 0: if max_num // 2 in As: res = max_num // 2 else: for item in As: if...
#!/usr/bin/python3 for i in range(1,10): for j in range(1,10): print("%d * %d = %d "%(j,i,i*j), end="") print("")
for i in range(1, 10): for j in range(1, 10): print('%d * %d = %d ' % (j, i, i * j), end='') print('')
def heapify(arr, n, i): """This is to max heapify Parameters: arr(list): List of integers n(int): Length of list i(int): Root element """ largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[i] < arr[left]: larges...
def heapify(arr, n, i): """This is to max heapify Parameters: arr(list): List of integers n(int): Length of list i(int): Root element """ largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[i] < arr[left]: largest = left if r...
expected_output = { 'vrf': { 'default': { 'interface': { 'GigabitEthernet0/0/0/0': { 'counters': { 'joins': 18, 'leaves': 5 }, 'enable': True, 'interne...
expected_output = {'vrf': {'default': {'interface': {'GigabitEthernet0/0/0/0': {'counters': {'joins': 18, 'leaves': 5}, 'enable': True, 'internet_address': 'fe80::5054:ff:fefa:9ad7', 'interface_status': 'up', 'last_member_query_interval': 1, 'oper_status': 'up', 'querier': 'fe80::5054:ff:fed7:c01f', 'querier_timeout': ...
while True: n=int(input('ENTER A NUMBER TO CHECK DIVISIBILITY: ')) for i in range (2,n): if n%i == 0: print('THE ENTER NO. IS DIVISIBLE BY: ',i)
while True: n = int(input('ENTER A NUMBER TO CHECK DIVISIBILITY: ')) for i in range(2, n): if n % i == 0: print('THE ENTER NO. IS DIVISIBLE BY: ', i)
# SCENARIO: Calculator - Do a substraction # GIVEN a running calculator app type(Key.WIN + "calculator" + Key.ENTER) wait("1471901583292.png") # AND '5' is displayed click("1471901439420.png") wait("1471901563200.png") # WHEN I click on '-', '1', '=' click("1471901612968.png") click("1471901595751.png") click...
type(Key.WIN + 'calculator' + Key.ENTER) wait('1471901583292.png') click('1471901439420.png') wait('1471901563200.png') click('1471901612968.png') click('1471901595751.png') click('1471901627768.png') wait('1471901656932.png')
"""Tests for the module 'api_v1'.""" # TODO enable when new test(s) will be added # from f8a_jobs.api_v1 import * class TestApiV1Functions(object): """Tests for the module 'api_v1'.""" def setup_method(self, method): """Set up any state tied to the execution of the given method in a class.""" ...
"""Tests for the module 'api_v1'.""" class Testapiv1Functions(object): """Tests for the module 'api_v1'.""" def setup_method(self, method): """Set up any state tied to the execution of the given method in a class.""" assert method def teardown_method(self, method): """Teardown any...
DbName = "FantasyDraftHost.db" tables = { "leagues": { "name": "Leagues", "columnIndexes": { "Id": 0, "Name": 1 } }, "playerPositions": { "name": "PlayerPositions", "columnIndexes": { "Id": 0, "PlayerId": 1, ...
db_name = 'FantasyDraftHost.db' tables = {'leagues': {'name': 'Leagues', 'columnIndexes': {'Id': 0, 'Name': 1}}, 'playerPositions': {'name': 'PlayerPositions', 'columnIndexes': {'Id': 0, 'PlayerId': 1, 'PositionId': 2}}, 'players': {'name': 'Players', 'columnIndexes': {'Id': 0, 'FirstName': 1, 'LastName': 2, 'TeamId': ...
a = [100,2,1,3,5,200,300,400,2,3,0,1,23,24,56,30,500,20,1000,3000] #print(a.index(max(a))) b = [] for i in range(0,9): b.append(a.index(max(a))) a[a.index(max(a))] = 0 print(b)
a = [100, 2, 1, 3, 5, 200, 300, 400, 2, 3, 0, 1, 23, 24, 56, 30, 500, 20, 1000, 3000] b = [] for i in range(0, 9): b.append(a.index(max(a))) a[a.index(max(a))] = 0 print(b)
""" core/exceptions.py useful custom exceptions for different cases author: @alexzander """ class core_Exception(Exception): def __init__(self, message=""): self.message = message class HTTP_RequestError(core_Exception): """ handles the http stuff""" pass ...
""" core/exceptions.py useful custom exceptions for different cases author: @alexzander """ class Core_Exception(Exception): def __init__(self, message=''): self.message = message class Http_Requesterror(core_Exception): """ handles the http stuff""" pass class Notfound_404_Err...
class MovieCard: def __init__(self, price): self._price = price self._tickets = 10 if price == 70 else 15 # assume price = 70 or 100 only @property def tickets(self): return self._tickets def redeem_ticket(self, qty=1): if qty > 2: raise ValueError("Ma...
class Moviecard: def __init__(self, price): self._price = price self._tickets = 10 if price == 70 else 15 @property def tickets(self): return self._tickets def redeem_ticket(self, qty=1): if qty > 2: raise value_error('Maximum ticket redemptions is 2.') ...
''' # O(N^2) # it is hard to pass the test big cases class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ sizeOfNums = len(nums) for i in range(sizeOfNums): for j in range(i+1, s...
''' # O(N^2) # it is hard to pass the test big cases class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ sizeOfNums = len(nums) for i in range(sizeOfNums): for j in range(i+1, s...
#!/usr/bin/env python # _*_ coding: utf-8 # See LICENSE for details. class BaseConfig: def __init__(self, logger=None, BaseConfig=None): self self.logger = logger self.stageing = False self.config_directory = None self.default_key_type = 'RSA' # TODO: Support 'ECDS...
class Baseconfig: def __init__(self, logger=None, BaseConfig=None): self self.logger = logger self.stageing = False self.config_directory = None self.default_key_type = 'RSA' self.ec_curve = 'secp256r1' self.storage_mode = 'file' self.storage_file_dir...
# Team 5 def save_to_excel(datatables: list, directory=None): pass def open_excel(): pass
def save_to_excel(datatables: list, directory=None): pass def open_excel(): pass
class Solution: def isValidSerialization(self, preorder: str) -> bool: nodes = preorder.split(",") cnt = 1 for i, x in enumerate(nodes): if x == "#": cnt -= 1 if cnt == 0: return i == len(nodes) - 1 else: ...
class Solution: def is_valid_serialization(self, preorder: str) -> bool: nodes = preorder.split(',') cnt = 1 for (i, x) in enumerate(nodes): if x == '#': cnt -= 1 if cnt == 0: return i == len(nodes) - 1 else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Where is my access point? Console Script. Copyright (c) 2020 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://dev...
"""Where is my access point? Console Script. Copyright (c) 2020 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of the...
# -*- coding: utf-8 class Document: __slots__ = ('root',) def __init__(self): self.root = None
class Document: __slots__ = ('root',) def __init__(self): self.root = None
def includeme(config): config.add_static_view('static', 'static', cache_max_age=None) config.add_route('home', '/') config.add_route('auth', '/auth') config.add_route('portfolio', '/portfolio') config.add_route('detail', '/portfolio/{symbol}') config.add_route('add', '/add') config.add_route...
def includeme(config): config.add_static_view('static', 'static', cache_max_age=None) config.add_route('home', '/') config.add_route('auth', '/auth') config.add_route('portfolio', '/portfolio') config.add_route('detail', '/portfolio/{symbol}') config.add_route('add', '/add') config.add_route...
print("BMI Calculator") print("=" * 20) height = input("Enter height (m): ") weight = input("Enter weight (kg): ") try: height = float(height) weight = float(weight) except ValueError: print("One or more invalid values entered.") exit(1) print("Your BMI is %d." % int((weight / (height ** 2)))) # 35.5...
print('BMI Calculator') print('=' * 20) height = input('Enter height (m): ') weight = input('Enter weight (kg): ') try: height = float(height) weight = float(weight) except ValueError: print('One or more invalid values entered.') exit(1) print('Your BMI is %d.' % int(weight / height ** 2))
class Solution: def rob(self, nums: List[int]) -> int: n = len(nums) if(n==0): return 0 dp = [0]*n dp[0] = nums[0] for i in range(1,n): if(i == 1): dp[i] = max(nums[0], nums[1]) ...
class Solution: def rob(self, nums: List[int]) -> int: n = len(nums) if n == 0: return 0 dp = [0] * n dp[0] = nums[0] for i in range(1, n): if i == 1: dp[i] = max(nums[0], nums[1]) else: dp[i] = max(dp[i - 1...
def bmw_finder_price_gt_25k(mileage, price): if price > 25000: return 1 else: return 0 def bmw_finder_price_gt_20k(mileage, price): if price > 20000: return 1 else: return 0 def bmw_finder_price_gt_cutoff_price(cutoff_price): def c(x,p): if p > cutoff_pric...
def bmw_finder_price_gt_25k(mileage, price): if price > 25000: return 1 else: return 0 def bmw_finder_price_gt_20k(mileage, price): if price > 20000: return 1 else: return 0 def bmw_finder_price_gt_cutoff_price(cutoff_price): def c(x, p): if p > cutoff_pric...
logs = """Log: Log file open, 15/01/{} 00:00:00 Log: GPsyonixBuildID 190326.60847.228380 Log: Command line: Init: WinSock: version 1.1 (2.2), MaxSocks=32767, MaxUdp=65467 Log: ... running in INSTALLED mode Warning: Warning, Unknown language extension . Defaulting to INT Init: Language extension: INT Init: Language ex...
logs = "Log: Log file open, 15/01/{} 00:00:00\nLog: GPsyonixBuildID 190326.60847.228380\nLog: Command line: \nInit: WinSock: version 1.1 (2.2), MaxSocks=32767, MaxUdp=65467\nLog: ... running in INSTALLED mode\nWarning: Warning, Unknown language extension . Defaulting to INT\nInit: Language extension: INT\nInit: Langua...
STATS = [ { "num_node_expansions": 1733, "plan_length": 142, "search_time": 1.66, "total_time": 1.66 }, { "num_node_expansions": 2128, "plan_length": 153, "search_time": 1.93, "total_time": 1.93 }, { "num_node_expansions": 2114,...
stats = [{'num_node_expansions': 1733, 'plan_length': 142, 'search_time': 1.66, 'total_time': 1.66}, {'num_node_expansions': 2128, 'plan_length': 153, 'search_time': 1.93, 'total_time': 1.93}, {'num_node_expansions': 2114, 'plan_length': 148, 'search_time': 29.02, 'total_time': 29.02}, {'num_node_expansions': 1614, 'pl...
LINE_DICT_TEMPLATE = { 'kind': '', 'buy_cur': '', 'buy_amount': 0, 'sell_cur': '', 'sell_amount': 0, 'fee_cur': '', 'fee_amount': 0, 'exchange': 'Bitshares', 'mark': -1, 'comment': '', 'order_id': '', } # CSV format is ccGains generic format HEADER = 'Kind,Date,Buy currency,...
line_dict_template = {'kind': '', 'buy_cur': '', 'buy_amount': 0, 'sell_cur': '', 'sell_amount': 0, 'fee_cur': '', 'fee_amount': 0, 'exchange': 'Bitshares', 'mark': -1, 'comment': '', 'order_id': ''} header = 'Kind,Date,Buy currency,Buy amount,Sell currency,Sell amount,Fee currency,Fee amount,Exchange,Mark,Comment\n' l...
globalval=6 def checkglobalvalue(): return globalval def localvariablevalue(): globalval=8 return globalval print ("This is global value",checkglobalvalue()) print ("This is global value",globalval) print ("This is local value",localvariablevalue()) print ("This is global value",globalval)
globalval = 6 def checkglobalvalue(): return globalval def localvariablevalue(): globalval = 8 return globalval print('This is global value', checkglobalvalue()) print('This is global value', globalval) print('This is local value', localvariablevalue()) print('This is global value', globalval)
class Logger: def __init__(self, simulator, time, image_analyzer, speed_controller, car, gyro, asservissement, sequencer, handles, tachometer): self.tachometer = tachometer self.handles = handles self.time = time self.image_analyzer = image_analyzer self.seq...
class Logger: def __init__(self, simulator, time, image_analyzer, speed_controller, car, gyro, asservissement, sequencer, handles, tachometer): self.tachometer = tachometer self.handles = handles self.time = time self.image_analyzer = image_analyzer self.sequencer = sequence...
""" Algorithms to find biconnected components in the graph considering only dovetails overlaps. Adapted using the networkx biconnected module: networkx/networkx/algorithms/components/biconnected.py """ # Copyright (C) 2011-2013 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Piet...
""" Algorithms to find biconnected components in the graph considering only dovetails overlaps. Adapted using the networkx biconnected module: networkx/networkx/algorithms/components/biconnected.py """ def _dovetails_biconnected_dfs(gfa_, components=True): visited = set() for start in gfa_.nodes(): if...
total = 0 for line in open('input.txt'): l, w, h = [int(side) for side in line.split('x')] sides = [2*(l+w), 2*(w+h), 2*(h+l)] total += min(sides) + l*w*h print(total)
total = 0 for line in open('input.txt'): (l, w, h) = [int(side) for side in line.split('x')] sides = [2 * (l + w), 2 * (w + h), 2 * (h + l)] total += min(sides) + l * w * h print(total)
def missions_per_year(df): ''' From a dataframe with the 'Year' column, Plot a graph showing the number of missions per year ''' missions_per_year = df.Year.value_counts() plt.plot(missions_per_year.sort_index()) plt.show() def missions_per_week(df): ''' From a dataframe with the '...
def missions_per_year(df): """ From a dataframe with the 'Year' column, Plot a graph showing the number of missions per year """ missions_per_year = df.Year.value_counts() plt.plot(missions_per_year.sort_index()) plt.show() def missions_per_week(df): """ From a dataframe with the 'Y...
def sum_func(a, *args): s = a+sum(args) print(s) sum_func(10) sum_func(10,20) sum_func(10,20,30) sum_func(10, 20, 30, 40)
def sum_func(a, *args): s = a + sum(args) print(s) sum_func(10) sum_func(10, 20) sum_func(10, 20, 30) sum_func(10, 20, 30, 40)
# 81. Search in Rotated Sorted Array II """ There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., n...
""" There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-...
TAG_MAP = { ('landuse', 'forest'): {"TYPE": "forest", "DRAW_TYPE": "plane"}, ('natural', 'wood'): {"TYPE": "forest", "SUBTYPE": "natural", "DRAW_TYPE": "plane"} } def find_type(tags): keys = list(tags.items()) return [TAG_MAP[key] for key in keys if key in TAG_MAP]
tag_map = {('landuse', 'forest'): {'TYPE': 'forest', 'DRAW_TYPE': 'plane'}, ('natural', 'wood'): {'TYPE': 'forest', 'SUBTYPE': 'natural', 'DRAW_TYPE': 'plane'}} def find_type(tags): keys = list(tags.items()) return [TAG_MAP[key] for key in keys if key in TAG_MAP]