content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def hip(a, b, c): if b < a > c and a ** 2 == b ** 2 + c ** 2: return True elif a < b > c and b ** 2 == a ** 2 + c ** 2: return True elif a < c > b and c ** 2 == a ** 2 + b ** 2: return True else: return False e = str(input()).split() a = int(e[0]) b = int(e[1]) c = int(e[2]) if(a < b + c and b < a + c and c < a + b): if(a == b == c): print('Valido-Equilatero') elif(a == b or a == c or b == c): print('Valido-Isoceles') else: print('Valido-Escaleno') if hip(a, b, c): print('Retangulo: S') else: print('Retangulo: N') else: print('Invalido')
def hip(a, b, c): if b < a > c and a ** 2 == b ** 2 + c ** 2: return True elif a < b > c and b ** 2 == a ** 2 + c ** 2: return True elif a < c > b and c ** 2 == a ** 2 + b ** 2: return True else: return False e = str(input()).split() a = int(e[0]) b = int(e[1]) c = int(e[2]) if a < b + c and b < a + c and (c < a + b): if a == b == c: print('Valido-Equilatero') elif a == b or a == c or b == c: print('Valido-Isoceles') else: print('Valido-Escaleno') if hip(a, b, c): print('Retangulo: S') else: print('Retangulo: N') else: print('Invalido')
#!/usr/bin/env python3 def left_join(phrases): return ','.join(phrases).replace("right", "left") if __name__ == '__main__': print(left_join(["right", "right", "left", "left", "forward"])) assert left_join(["right", "right", "left", "left", "forward"]) == "left,left,left,left,forward" assert left_join(["alright outright", "squirrel"]) == "alleft outleft,squirrel" assert left_join(["frightened", "eyebright"]) == "fleftened,eyebleft" assert left_join(["little", "squirrel"]) == "little,squirrel"
def left_join(phrases): return ','.join(phrases).replace('right', 'left') if __name__ == '__main__': print(left_join(['right', 'right', 'left', 'left', 'forward'])) assert left_join(['right', 'right', 'left', 'left', 'forward']) == 'left,left,left,left,forward' assert left_join(['alright outright', 'squirrel']) == 'alleft outleft,squirrel' assert left_join(['frightened', 'eyebright']) == 'fleftened,eyebleft' assert left_join(['little', 'squirrel']) == 'little,squirrel'
DATABASE_NAME = "lzhaoDemoDB" TABLE_NAME = "MarketPriceGTest" HT_TTL_HOURS = 24 CT_TTL_DAYS = 7 ONE_GB_IN_BYTES = 1073741824
database_name = 'lzhaoDemoDB' table_name = 'MarketPriceGTest' ht_ttl_hours = 24 ct_ttl_days = 7 one_gb_in_bytes = 1073741824
class Solution: def recursion(self,idx,arr,n,maxx,size,k): if idx == n: return maxx * size if (idx,size,maxx) in self.dp: return self.dp[(idx,size,maxx)] ch1 = self.recursion(idx+1,arr,n,max(maxx,arr[idx]),size+1,k) if size < k else 0 ch2 = self.recursion(idx+1,arr,n,arr[idx],1,k) + maxx*size best = ch1 if ch1 > ch2 else ch2 self.dp[(idx,size,maxx)] = best return best def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: self.dp = {} return self.recursion(1,arr,len(arr),arr[0],1,k)
class Solution: def recursion(self, idx, arr, n, maxx, size, k): if idx == n: return maxx * size if (idx, size, maxx) in self.dp: return self.dp[idx, size, maxx] ch1 = self.recursion(idx + 1, arr, n, max(maxx, arr[idx]), size + 1, k) if size < k else 0 ch2 = self.recursion(idx + 1, arr, n, arr[idx], 1, k) + maxx * size best = ch1 if ch1 > ch2 else ch2 self.dp[idx, size, maxx] = best return best def max_sum_after_partitioning(self, arr: List[int], k: int) -> int: self.dp = {} return self.recursion(1, arr, len(arr), arr[0], 1, k)
class Action: def do(self) -> None: raise NotImplementedError def undo(self) -> None: raise NotImplementedError def redo(self) -> None: raise NotImplementedError
class Action: def do(self) -> None: raise NotImplementedError def undo(self) -> None: raise NotImplementedError def redo(self) -> None: raise NotImplementedError
# # PySNMP MIB module INCOGNITO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INCOGNITO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:42:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, enterprises, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ModuleIdentity, ObjectIdentity, Gauge32, Counter64, iso, IpAddress, NotificationType, MibIdentifier, Unsigned32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "enterprises", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ModuleIdentity", "ObjectIdentity", "Gauge32", "Counter64", "iso", "IpAddress", "NotificationType", "MibIdentifier", "Unsigned32", "Counter32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") incognito = ModuleIdentity((1, 3, 6, 1, 4, 1, 3606)) if mibBuilder.loadTexts: incognito.setLastUpdated('200304151442Z') if mibBuilder.loadTexts: incognito.setOrganization('Incognito Software Inc.') incognitoSNMPObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 1)) if mibBuilder.loadTexts: incognitoSNMPObjects.setStatus('obsolete') incognitoReg = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 2)) if mibBuilder.loadTexts: incognitoReg.setStatus('current') incognitoGeneric = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 3)) if mibBuilder.loadTexts: incognitoGeneric.setStatus('current') incognitoProducts = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 4)) if mibBuilder.loadTexts: incognitoProducts.setStatus('current') incognitoCaps = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 5)) if mibBuilder.loadTexts: incognitoCaps.setStatus('current') incognitoReqs = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 6)) if mibBuilder.loadTexts: incognitoReqs.setStatus('current') incognitoExpr = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 7)) if mibBuilder.loadTexts: incognitoExpr.setStatus('current') mibBuilder.exportSymbols("INCOGNITO-MIB", incognitoSNMPObjects=incognitoSNMPObjects, incognitoReqs=incognitoReqs, incognitoGeneric=incognitoGeneric, incognitoReg=incognitoReg, PYSNMP_MODULE_ID=incognito, incognitoProducts=incognitoProducts, incognitoCaps=incognitoCaps, incognito=incognito, incognitoExpr=incognitoExpr)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (bits, enterprises, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, module_identity, object_identity, gauge32, counter64, iso, ip_address, notification_type, mib_identifier, unsigned32, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'enterprises', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'ModuleIdentity', 'ObjectIdentity', 'Gauge32', 'Counter64', 'iso', 'IpAddress', 'NotificationType', 'MibIdentifier', 'Unsigned32', 'Counter32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') incognito = module_identity((1, 3, 6, 1, 4, 1, 3606)) if mibBuilder.loadTexts: incognito.setLastUpdated('200304151442Z') if mibBuilder.loadTexts: incognito.setOrganization('Incognito Software Inc.') incognito_snmp_objects = object_identity((1, 3, 6, 1, 4, 1, 3606, 1)) if mibBuilder.loadTexts: incognitoSNMPObjects.setStatus('obsolete') incognito_reg = object_identity((1, 3, 6, 1, 4, 1, 3606, 2)) if mibBuilder.loadTexts: incognitoReg.setStatus('current') incognito_generic = object_identity((1, 3, 6, 1, 4, 1, 3606, 3)) if mibBuilder.loadTexts: incognitoGeneric.setStatus('current') incognito_products = object_identity((1, 3, 6, 1, 4, 1, 3606, 4)) if mibBuilder.loadTexts: incognitoProducts.setStatus('current') incognito_caps = object_identity((1, 3, 6, 1, 4, 1, 3606, 5)) if mibBuilder.loadTexts: incognitoCaps.setStatus('current') incognito_reqs = object_identity((1, 3, 6, 1, 4, 1, 3606, 6)) if mibBuilder.loadTexts: incognitoReqs.setStatus('current') incognito_expr = object_identity((1, 3, 6, 1, 4, 1, 3606, 7)) if mibBuilder.loadTexts: incognitoExpr.setStatus('current') mibBuilder.exportSymbols('INCOGNITO-MIB', incognitoSNMPObjects=incognitoSNMPObjects, incognitoReqs=incognitoReqs, incognitoGeneric=incognitoGeneric, incognitoReg=incognitoReg, PYSNMP_MODULE_ID=incognito, incognitoProducts=incognitoProducts, incognitoCaps=incognitoCaps, incognito=incognito, incognitoExpr=incognitoExpr)
#list example for insertion order and the dupicates l1 = [] print(type(l1)) l1.append(1) l1.append(2) l1.append(3) l1.append(4) l1.append(1) print(l1)
l1 = [] print(type(l1)) l1.append(1) l1.append(2) l1.append(3) l1.append(4) l1.append(1) print(l1)
def maximum_subarray_sum(lst): '''Finds the maximum sum of all subarrays in lst in O(n) time and O(1) additional space. >>> maximum_subarray_sum([34, -50, 42, 14, -5, 86]) 137 >>> maximum_subarray_sum([-5, -1, -8, -101]) 0 ''' current_sum = 0 maximum_sum = 0 for value in lst: current_sum = max(current_sum + value, 0) maximum_sum = max(maximum_sum, current_sum) return maximum_sum
def maximum_subarray_sum(lst): """Finds the maximum sum of all subarrays in lst in O(n) time and O(1) additional space. >>> maximum_subarray_sum([34, -50, 42, 14, -5, 86]) 137 >>> maximum_subarray_sum([-5, -1, -8, -101]) 0 """ current_sum = 0 maximum_sum = 0 for value in lst: current_sum = max(current_sum + value, 0) maximum_sum = max(maximum_sum, current_sum) return maximum_sum
# Alternative solution using compound conditional statement in_class_test = int(input('Please enter your mark for the In Class Test: ')) exam_mark = int(input('Please input your mark for the exam: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) # Calculating mark by adding the marks together and dividing by 2 component_a_mark = (in_class_test * 0.25) + (exam_mark * 0.75) module_mark = (component_a_mark + coursework_mark) / 2 print('Your mark is', module_mark, 'Calculating your result') # Uses compound boolean proposition if coursework_mark < 35 and component_a_mark < 35: print('You have not passed the module') elif module_mark < 40: print('You have failed the module') else: print('You have passed the module')
in_class_test = int(input('Please enter your mark for the In Class Test: ')) exam_mark = int(input('Please input your mark for the exam: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) component_a_mark = in_class_test * 0.25 + exam_mark * 0.75 module_mark = (component_a_mark + coursework_mark) / 2 print('Your mark is', module_mark, 'Calculating your result') if coursework_mark < 35 and component_a_mark < 35: print('You have not passed the module') elif module_mark < 40: print('You have failed the module') else: print('You have passed the module')
# Implementation of a singly linked list data structure # By: Jacob Rockland # node class for linked list class Node(object): def __init__(self, data): self.data = data self.next = None # implementation of singly linked list class SinglyLinkedList(object): # initializes linked list def __init__(self, head = None, tail = None): self.head = head self.tail = tail # returns a string representation of linked list [data1, data2, ...] def __repr__(self): return repr(self.array()) # returns an array representation of linked list def array(self): array = [] curr = self.head while curr is not None: array.append(curr.data) curr = curr.next return array # adds node to end of list, O(1) def append(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node # adds node to front of list, O(1) def prepend(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: node.next = self.head self.head = node # inserts node into list after given position, O(1) def insert_after(self, curr, item): node = Node(item) if self.head is None: self.head = node self.tail = node elif curr is None: node.next = self.head self.head = node elif curr is self.tail: self.tail.next = node self.tail = node else: node.next = curr.next curr.next = node # inserts node into list in sorted position, O(n) def insert_sorted(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: last = None curr = self.head while curr is not None and item > curr.data: last = curr curr = curr.next if curr is None: self.tail.next = node self.tail = node elif last is None: node.next = self.head self.head = node else: last.next = node node.next = curr # removes node from list after given position, O(1) def remove_after(self, curr): if self.head is None: return elif curr is None: succ = self.head.next self.head = succ if succ is None: # checks if removed last item self.tail = None elif curr.next is not None: succ = curr.next.next curr.next = succ if succ is None: # checks if removed tail item self.tail = curr # searches for a given data value in list and returns first node if found, O(n) def search(self, key): curr = self.head while curr is not None: if curr.data == key: return curr curr = curr.next return None # reverses linked list in place, O(n) def reverse(self): self.tail = self.head prev = None curr = self.head while curr is not None: succ = curr.next curr.next = prev prev = curr curr = succ self.head = prev # remove duplicates from linked list def remove_duplicates(self): if self.head is None: return curr = self.head while curr.next is not None: if curr.data == curr.next.data: curr.next = curr.next.next else: curr = curr.next
class Node(object): def __init__(self, data): self.data = data self.next = None class Singlylinkedlist(object): def __init__(self, head=None, tail=None): self.head = head self.tail = tail def __repr__(self): return repr(self.array()) def array(self): array = [] curr = self.head while curr is not None: array.append(curr.data) curr = curr.next return array def append(self, item): node = node(item) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node def prepend(self, item): node = node(item) if self.head is None: self.head = node self.tail = node else: node.next = self.head self.head = node def insert_after(self, curr, item): node = node(item) if self.head is None: self.head = node self.tail = node elif curr is None: node.next = self.head self.head = node elif curr is self.tail: self.tail.next = node self.tail = node else: node.next = curr.next curr.next = node def insert_sorted(self, item): node = node(item) if self.head is None: self.head = node self.tail = node else: last = None curr = self.head while curr is not None and item > curr.data: last = curr curr = curr.next if curr is None: self.tail.next = node self.tail = node elif last is None: node.next = self.head self.head = node else: last.next = node node.next = curr def remove_after(self, curr): if self.head is None: return elif curr is None: succ = self.head.next self.head = succ if succ is None: self.tail = None elif curr.next is not None: succ = curr.next.next curr.next = succ if succ is None: self.tail = curr def search(self, key): curr = self.head while curr is not None: if curr.data == key: return curr curr = curr.next return None def reverse(self): self.tail = self.head prev = None curr = self.head while curr is not None: succ = curr.next curr.next = prev prev = curr curr = succ self.head = prev def remove_duplicates(self): if self.head is None: return curr = self.head while curr.next is not None: if curr.data == curr.next.data: curr.next = curr.next.next else: curr = curr.next
def print_formatted(number): width = len("{0:b}".format(number)) for num in range(1, number+1): print("{0:{w}}\t{0:{w}o}\t{0:{w}X}\t{0:{w}b}".format(num, w=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
def print_formatted(number): width = len('{0:b}'.format(number)) for num in range(1, number + 1): print('{0:{w}}\t{0:{w}o}\t{0:{w}X}\t{0:{w}b}'.format(num, w=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
####################################################### # Author: Mwiza Simbeye # # Institution: African Leadership University Rwanda # # Program: Playing Card Sorting Algorithm # ####################################################### cards = [9, 10, 'J', 'K', 'Q', 'Q', 4, 5, 6, 7, 8,'A', 2, 3] ####################################################### # Convert cars to their numerical equivalent # # Example:[9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 1, 2, 3] # ####################################################### converted_cards = [] for i in cards: if i == 'A': converted_cards.append(1) elif i == 'J': converted_cards.append(11) elif i == 'K': converted_cards.append(12) elif i == 'Q': converted_cards.append(13) else: converted_cards.append(i) sort = [] z = 0 while z < len(cards): smallest = converted_cards[0] for x in converted_cards: if x < smallest: smallest = x else: pass converted_cards.remove(smallest) #print (converted_cards) sort.append(smallest) #print (sort) z+=1 ####################################################### # Convert numerical values to their card equivalent # # Example: [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, K, Q] # ####################################################### sorted_cards = [] for i in sort: if i == 1: sorted_cards.append('A') elif i == 11: sorted_cards.append('J') elif i == 12: sorted_cards.append('K') elif i == 13: sorted_cards.append('Q') else: sorted_cards.append(i) print ("The sorted cards are: "+str(sorted_cards))
cards = [9, 10, 'J', 'K', 'Q', 'Q', 4, 5, 6, 7, 8, 'A', 2, 3] converted_cards = [] for i in cards: if i == 'A': converted_cards.append(1) elif i == 'J': converted_cards.append(11) elif i == 'K': converted_cards.append(12) elif i == 'Q': converted_cards.append(13) else: converted_cards.append(i) sort = [] z = 0 while z < len(cards): smallest = converted_cards[0] for x in converted_cards: if x < smallest: smallest = x else: pass converted_cards.remove(smallest) sort.append(smallest) z += 1 sorted_cards = [] for i in sort: if i == 1: sorted_cards.append('A') elif i == 11: sorted_cards.append('J') elif i == 12: sorted_cards.append('K') elif i == 13: sorted_cards.append('Q') else: sorted_cards.append(i) print('The sorted cards are: ' + str(sorted_cards))
def DPLL(B, I): if len(B) == 0: return True, I for i in B: if len(i) == 0: return False, [] x = B[0][0] if x[0] != '!': x = '!' + x Bp = [[j for j in i if j != x] for i in B if not(x[1:] in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(True)) V, I1 = DPLL(Bp, Ip) if V: return True, I1 Bp = [[j for j in i if j != x[1:]] for i in B if not(x in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(False)) V, I2 = DPLL(Bp, Ip) if V: return True, I2 return False, [] expresion =[['!p', '!r', '!s'], ['!q', '!p', '!s'], ['p'], ['s']] t,r = DPLL(expresion, []) print(t) print(r)
def dpll(B, I): if len(B) == 0: return (True, I) for i in B: if len(i) == 0: return (False, []) x = B[0][0] if x[0] != '!': x = '!' + x bp = [[j for j in i if j != x] for i in B if not x[1:] in i] ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(True)) (v, i1) = dpll(Bp, Ip) if V: return (True, I1) bp = [[j for j in i if j != x[1:]] for i in B if not x in i] ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(False)) (v, i2) = dpll(Bp, Ip) if V: return (True, I2) return (False, []) expresion = [['!p', '!r', '!s'], ['!q', '!p', '!s'], ['p'], ['s']] (t, r) = dpll(expresion, []) print(t) print(r)
#multiplicar a nota pelo peso, depois divide a soma das notas pela soma dos pesos nota1=float(input())*2 nota2=float(input())*3 nota3=float(input())*5 media=float((nota1+nota2+nota3))/10 print("MEDIA =","%.1f"%media)
nota1 = float(input()) * 2 nota2 = float(input()) * 3 nota3 = float(input()) * 5 media = float(nota1 + nota2 + nota3) / 10 print('MEDIA =', '%.1f' % media)
VALUES_CONSTANT = "values" PREVIOUS_NODE_CONSTANT = "previous_vertex" START_NODE = "A" END_NODE = "F" # GRAPH IS 1A graph = { "A": { "B" : 5, "C" : 2 }, "B": { "E" : 4 , "D": 2 , }, "C" : { "B" : 8, "D" : 7 }, "E" : { "F" : 3 , "D" : 6 }, "D" : { "F" : 1 }, "F" : { } } # GRAPH 1B # graph = { # "A": { # "B" : 10 # }, # "B": { # "C" : 20 , # }, # "C" : { # "D" : 1 , # "E" : 30 # }, # "D" : { # "B" : 1, # }, # "E" : { # } # } # GENERATES SCORE TABLE FOR DIJKSTRA ALGORITHM def generate_score_table(): SCORE_TABLE = {} QUEUE = [START_NODE] SCORE_TABLE[START_NODE] = { VALUES_CONSTANT : 0 } VISITED = [] NEXT_FIRST_NEIGHBOR= list(graph[QUEUE[0]].keys())[0] shortest_path_length = 0 shortest_path_found_bool = False # IMPLEMENT BFS while len(QUEUE) > 0: # TRAVERSE THE EDGES for node in graph[QUEUE[0]].keys(): # IF THE !EXIST IN THE TABLE IT SHOULD INCLUDE IN THE TABLE, OTHERWISE CHECK THE VALUE cost = graph[QUEUE[0]][node] + SCORE_TABLE[QUEUE[0]][VALUES_CONSTANT] if node not in SCORE_TABLE: SCORE_TABLE[node] = { VALUES_CONSTANT : cost, PREVIOUS_NODE_CONSTANT : QUEUE[0] } else: if cost < SCORE_TABLE[node][VALUES_CONSTANT]: SCORE_TABLE[node] = { VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT : QUEUE[0]} if node not in VISITED and node not in QUEUE: if(NEXT_FIRST_NEIGHBOR==node and shortest_path_found_bool == False): shortest_path_length += 1 if(node == END_NODE): shortest_path_found_bool = True else: NEXT_FIRST_NEIGHBOR= list(graph[node].keys())[0] QUEUE += [node] VISITED += QUEUE[0] QUEUE.pop(0) return SCORE_TABLE,shortest_path_length def get_fastest_path(START_NODE, END_NODE, SCORE_TABLE,shortest_path): path = [] boolean_similar = False node = END_NODE while node != START_NODE: path.insert(0,node) node = SCORE_TABLE[node][PREVIOUS_NODE_CONSTANT] path.insert(0,node) if(len(path)-1 == shortest_path): boolean_similar = True else: boolean_similar = False return path, boolean_similar SCORE_TABLE,shortest_path_len = generate_score_table() fastest_path,boolean = get_fastest_path(START_NODE, END_NODE, SCORE_TABLE,shortest_path_len) print("FASTEST PATH:",fastest_path) print("BOOLEAN FOR SIMILARITY OF SHORTEST AND FASTEST:",boolean)
values_constant = 'values' previous_node_constant = 'previous_vertex' start_node = 'A' end_node = 'F' graph = {'A': {'B': 5, 'C': 2}, 'B': {'E': 4, 'D': 2}, 'C': {'B': 8, 'D': 7}, 'E': {'F': 3, 'D': 6}, 'D': {'F': 1}, 'F': {}} def generate_score_table(): score_table = {} queue = [START_NODE] SCORE_TABLE[START_NODE] = {VALUES_CONSTANT: 0} visited = [] next_first_neighbor = list(graph[QUEUE[0]].keys())[0] shortest_path_length = 0 shortest_path_found_bool = False while len(QUEUE) > 0: for node in graph[QUEUE[0]].keys(): cost = graph[QUEUE[0]][node] + SCORE_TABLE[QUEUE[0]][VALUES_CONSTANT] if node not in SCORE_TABLE: SCORE_TABLE[node] = {VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT: QUEUE[0]} elif cost < SCORE_TABLE[node][VALUES_CONSTANT]: SCORE_TABLE[node] = {VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT: QUEUE[0]} if node not in VISITED and node not in QUEUE: if NEXT_FIRST_NEIGHBOR == node and shortest_path_found_bool == False: shortest_path_length += 1 if node == END_NODE: shortest_path_found_bool = True else: next_first_neighbor = list(graph[node].keys())[0] queue += [node] visited += QUEUE[0] QUEUE.pop(0) return (SCORE_TABLE, shortest_path_length) def get_fastest_path(START_NODE, END_NODE, SCORE_TABLE, shortest_path): path = [] boolean_similar = False node = END_NODE while node != START_NODE: path.insert(0, node) node = SCORE_TABLE[node][PREVIOUS_NODE_CONSTANT] path.insert(0, node) if len(path) - 1 == shortest_path: boolean_similar = True else: boolean_similar = False return (path, boolean_similar) (score_table, shortest_path_len) = generate_score_table() (fastest_path, boolean) = get_fastest_path(START_NODE, END_NODE, SCORE_TABLE, shortest_path_len) print('FASTEST PATH:', fastest_path) print('BOOLEAN FOR SIMILARITY OF SHORTEST AND FASTEST:', boolean)
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. csv = 'perf_Us_3' cfg_dict = { 'aux_no_0': { 'dataset': 'aux_no_0', 'p': 3, 'd': 1, 'q': 1, 'taus': [1533, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'aux_smooth': { 'dataset': 'aux_smooth', 'p': 3, 'd': 1, 'q': 1, 'taus': [319, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'aux_raw': { 'dataset': 'aux_raw', 'p': 3, 'd': 1, 'q': 1, 'taus': [2246, 8], 'Rs': [5, 8], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'D1': { 'dataset': 'D1_qty', 'p': 3, 'd': 1, 'q': 1, 'taus': [607, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'PC_W': { 'dataset': 'PC_W', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'PC_M': { 'dataset': 'PC_M', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele40': { 'dataset': 'ele40', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele200': { 'dataset': 'ele_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele_big': { 'dataset': 'ele_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv }, 'traffic_40': { 'dataset': 'traffic_40', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'traffic_80': { 'dataset': 'traffic_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'traffic_big': { 'dataset': 'traffic_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [862, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv } }
csv = 'perf_Us_3' cfg_dict = {'aux_no_0': {'dataset': 'aux_no_0', 'p': 3, 'd': 1, 'q': 1, 'taus': [1533, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'aux_smooth': {'dataset': 'aux_smooth', 'p': 3, 'd': 1, 'q': 1, 'taus': [319, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'aux_raw': {'dataset': 'aux_raw', 'p': 3, 'd': 1, 'q': 1, 'taus': [2246, 8], 'Rs': [5, 8], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'D1': {'dataset': 'D1_qty', 'p': 3, 'd': 1, 'q': 1, 'taus': [607, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'PC_W': {'dataset': 'PC_W', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'PC_M': {'dataset': 'PC_M', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'ele40': {'dataset': 'ele40', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'ele200': {'dataset': 'ele_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'ele_big': {'dataset': 'ele_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv}, 'traffic_40': {'dataset': 'traffic_40', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'traffic_80': {'dataset': 'traffic_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'traffic_big': {'dataset': 'traffic_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [862, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv}}
sal = float(input('Qual o seu salario? ')) if sal > 1250.00: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 10)) else: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 15))
sal = float(input('Qual o seu salario? ')) if sal > 1250.0: print('Com o aumento seu salario sera R${:.2f}'.format(sal + sal / 100 * 10)) else: print('Com o aumento seu salario sera R${:.2f}'.format(sal + sal / 100 * 15))
class QuizQuestion: def __init__(self, text, answer): self.text = text self.answer = answer @property def text(self): return self.__text @text.setter def text(self, text): self.__text = text @property def answer(self): return self.__answer @answer.setter def answer(self, answer): self.__answer = answer
class Quizquestion: def __init__(self, text, answer): self.text = text self.answer = answer @property def text(self): return self.__text @text.setter def text(self, text): self.__text = text @property def answer(self): return self.__answer @answer.setter def answer(self, answer): self.__answer = answer
class Model: def __init__(self): self._classes = {} self._relations = {} self._generalizations = {} self._associationLinks = {} def addClass(self, _class): self._classes[_class.uid()] = _class def classByUid(self, uid): return self._classes[uid] def addRelation(self, relation): lClass = relation.leftAssociation()._class().relate(relation) rClass = relation.rightAssociation()._class().relate(relation) self._relations[relation.uid()] = relation def addGeneralization(self, generalization): self._generalizations[generalization.uid()] = generalization def addAssociationLink(self, assoclink): self._associationLinks[assoclink.uid()] = assoclink def relationByUid(self, uid): return self._relations[uid] def classes(self): return self._classes def relations(self): return self._relations def generalizations(self): return self._generalizations def associationLinks(self): return self._associationLinks def superClassOf(self, _class): superclass = None for generalization in self._generalizations.values(): if generalization.subclass() == _class: superclass = generalization.superclass() break return superclass
class Model: def __init__(self): self._classes = {} self._relations = {} self._generalizations = {} self._associationLinks = {} def add_class(self, _class): self._classes[_class.uid()] = _class def class_by_uid(self, uid): return self._classes[uid] def add_relation(self, relation): l_class = relation.leftAssociation()._class().relate(relation) r_class = relation.rightAssociation()._class().relate(relation) self._relations[relation.uid()] = relation def add_generalization(self, generalization): self._generalizations[generalization.uid()] = generalization def add_association_link(self, assoclink): self._associationLinks[assoclink.uid()] = assoclink def relation_by_uid(self, uid): return self._relations[uid] def classes(self): return self._classes def relations(self): return self._relations def generalizations(self): return self._generalizations def association_links(self): return self._associationLinks def super_class_of(self, _class): superclass = None for generalization in self._generalizations.values(): if generalization.subclass() == _class: superclass = generalization.superclass() break return superclass
''' 08 - Finding ambiguous datetimes At the end of lesson 2, we saw something anomalous in our bike trip duration data. Let's see if we can identify what the problem might be. The data is loaded as onebike_datetimes, and tz has already been imported from dateutil. Instructions - Loop over the trips in onebike_datetimes: - Print any rides whose start is ambiguous. - Print any rides whose end is ambiguous. ''' # Loop over trips for trip in onebike_datetimes: # Rides with ambiguous start if tz.datetime_ambiguous(trip['start']): print("Ambiguous start at " + str(trip['start'])) # Rides with ambiguous end if tz.datetime_ambiguous(trip['end']): print("Ambiguous end at " + str(trip['end'])) # Ambiguous start at 2017-11-05 01:56:50-04:00 # Ambiguous end at 2017-11-05 01: 01: 04-04: 00
""" 08 - Finding ambiguous datetimes At the end of lesson 2, we saw something anomalous in our bike trip duration data. Let's see if we can identify what the problem might be. The data is loaded as onebike_datetimes, and tz has already been imported from dateutil. Instructions - Loop over the trips in onebike_datetimes: - Print any rides whose start is ambiguous. - Print any rides whose end is ambiguous. """ for trip in onebike_datetimes: if tz.datetime_ambiguous(trip['start']): print('Ambiguous start at ' + str(trip['start'])) if tz.datetime_ambiguous(trip['end']): print('Ambiguous end at ' + str(trip['end']))
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openBrand_detection.py', '../_base_/default_runtime.py' ] data = dict( samples_per_gpu=4, workers_per_gpu=2, ) # model settings model = dict( neck=[ dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict( type='BFP', in_channels=256, num_levels=5, refine_level=2, refine_type='non_local') ], roi_head=dict( bbox_head=dict( num_classes=515, loss_bbox=dict( _delete_=True, type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=dict(sampler=dict(neg_pos_ub=5), allowed_border=-1), rcnn=dict( sampler=dict( _delete_=True, type='CombinedSampler', num=512, pos_fraction=0.25, add_gt_as_proposals=True, pos_sampler=dict(type='InstanceBalancedPosSampler'), neg_sampler=dict( type='IoUBalancedNegSampler', floor_thr=-1, floor_fraction=0, num_bins=3) ) ) ) ) # optimizer optimizer = dict(type='SGD', lr=0.04, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=10000, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12)
_base_ = ['../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openBrand_detection.py', '../_base_/default_runtime.py'] data = dict(samples_per_gpu=4, workers_per_gpu=2) model = dict(neck=[dict(type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict(type='BFP', in_channels=256, num_levels=5, refine_level=2, refine_type='non_local')], roi_head=dict(bbox_head=dict(num_classes=515, loss_bbox=dict(_delete_=True, type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0, loss_weight=1.0))), train_cfg=dict(rpn=dict(sampler=dict(neg_pos_ub=5), allowed_border=-1), rcnn=dict(sampler=dict(_delete_=True, type='CombinedSampler', num=512, pos_fraction=0.25, add_gt_as_proposals=True, pos_sampler=dict(type='InstanceBalancedPosSampler'), neg_sampler=dict(type='IoUBalancedNegSampler', floor_thr=-1, floor_fraction=0, num_bins=3))))) optimizer = dict(type='SGD', lr=0.04, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='step', warmup='linear', warmup_iters=10000, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12)
''' Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. ''' class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = None self.right = None def get_height(root): if root is None: return 0 return 1 + max(get_height(root.left), get_height(root.right)) def isBalanced(root): if root is None: return 1 left_tree_height = get_height(root.left) right_tree_height = get_height(root.right) if abs(left_tree_height - right_tree_height) > 1: return False return isBalanced(root.left) and isBalanced(root.right) # Initial Template for Python 3 if __name__ == '__main__': root = None t = int(input()) for i in range(t): # root = None n = int(input()) arr = input().strip().split() if n == 0: print(0) continue dictTree = dict() for j in range(n): if arr[3 * j] not in dictTree: dictTree[arr[3 * j]] = Node(arr[3 * j]) parent = dictTree[arr[3 * j]] if j is 0: root = parent else: parent = dictTree[arr[3 * j]] child = Node(arr[3 * j + 1]) if (arr[3 * j + 2] == 'L'): parent.left = child else: parent.right = child dictTree[arr[3 * j + 1]] = child if isBalanced(root): print(1) else: print(0)
""" Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. """ class Node: def __init__(self, data): self.data = data self.left = None self.right = None def get_height(root): if root is None: return 0 return 1 + max(get_height(root.left), get_height(root.right)) def is_balanced(root): if root is None: return 1 left_tree_height = get_height(root.left) right_tree_height = get_height(root.right) if abs(left_tree_height - right_tree_height) > 1: return False return is_balanced(root.left) and is_balanced(root.right) if __name__ == '__main__': root = None t = int(input()) for i in range(t): n = int(input()) arr = input().strip().split() if n == 0: print(0) continue dict_tree = dict() for j in range(n): if arr[3 * j] not in dictTree: dictTree[arr[3 * j]] = node(arr[3 * j]) parent = dictTree[arr[3 * j]] if j is 0: root = parent else: parent = dictTree[arr[3 * j]] child = node(arr[3 * j + 1]) if arr[3 * j + 2] == 'L': parent.left = child else: parent.right = child dictTree[arr[3 * j + 1]] = child if is_balanced(root): print(1) else: print(0)
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. inas = [('ina219', '0x40', 'pp1050_s', 1.05, 0.010, 'rem', True), ('ina219', '0x41', 'pp1800_a', 1.80, 0.010, 'rem', True), ('ina219', '0x42', 'pp1200_vddq', 1.20, 0.010, 'rem', True), ('ina219', '0x43', 'pp3300_a', 3.30, 0.010, 'rem', True), ('ina219', '0x44', 'ppvbat', 7.50, 0.010, 'rem', True), ('ina219', '0x47', 'ppvccgi', 1.00, 0.010, 'rem', True), ('ina219', '0x49', 'ppvnn', 1.00, 0.010, 'rem', True), ('ina219', '0x4a', 'pp1240_a', 1.24, 0.010, 'rem', True), ('ina219', '0x4b', 'pp5000_a', 5.00, 0.010, 'rem', True)]
inas = [('ina219', '0x40', 'pp1050_s', 1.05, 0.01, 'rem', True), ('ina219', '0x41', 'pp1800_a', 1.8, 0.01, 'rem', True), ('ina219', '0x42', 'pp1200_vddq', 1.2, 0.01, 'rem', True), ('ina219', '0x43', 'pp3300_a', 3.3, 0.01, 'rem', True), ('ina219', '0x44', 'ppvbat', 7.5, 0.01, 'rem', True), ('ina219', '0x47', 'ppvccgi', 1.0, 0.01, 'rem', True), ('ina219', '0x49', 'ppvnn', 1.0, 0.01, 'rem', True), ('ina219', '0x4a', 'pp1240_a', 1.24, 0.01, 'rem', True), ('ina219', '0x4b', 'pp5000_a', 5.0, 0.01, 'rem', True)]
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:shape.bzl", "shape") conf_t = shape.shape( nameservers = shape.list(str), search_domains = shape.list(str), )
load('//antlir/bzl:shape.bzl', 'shape') conf_t = shape.shape(nameservers=shape.list(str), search_domains=shape.list(str))
# Sudoku problem solved using backtracking def solve_sudoku(array): is_empty_cell_found = False; # Finding if there is any empty cell for i in range(0, 9): for j in range(0, 9): if array[i][j] == 0: row, col = i, j is_empty_cell_found = True break if is_empty_cell_found: break # print('row', row, 'col', col, 'is_empty_cell_found', is_empty_cell_found) if not is_empty_cell_found: return True for num in range(1, 10): # print(num) if _is_valid_move(array, row, col, num): # print('is valid move') array[row][col] = num if solve_sudoku(array): return True else: array[row][col] = 0 return False def _is_valid_move(array, row, col, num): # Checking row if same num already exists for i in range(0, 9): if array[row][i] == num: return False # Checking column if same num already exists for i in range(0, 9): if array[i][col] == num: return False # Checking the current cube row_start = row - row % 3 column_start = col - col % 3 # print(row_start, column_start) for i in range(row_start, row_start + 3): for j in range(column_start, column_start + 3): if array[i][j] == num: # print('matched in grid') return False return True def print_array(array): for i in range(0, 9): for j in range(0, 9): print(sudoku_array[i][j], end = " ") print() if __name__ == '__main__': sudoku_array = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] solve_sudoku(sudoku_array) print_array(sudoku_array)
def solve_sudoku(array): is_empty_cell_found = False for i in range(0, 9): for j in range(0, 9): if array[i][j] == 0: (row, col) = (i, j) is_empty_cell_found = True break if is_empty_cell_found: break if not is_empty_cell_found: return True for num in range(1, 10): if _is_valid_move(array, row, col, num): array[row][col] = num if solve_sudoku(array): return True else: array[row][col] = 0 return False def _is_valid_move(array, row, col, num): for i in range(0, 9): if array[row][i] == num: return False for i in range(0, 9): if array[i][col] == num: return False row_start = row - row % 3 column_start = col - col % 3 for i in range(row_start, row_start + 3): for j in range(column_start, column_start + 3): if array[i][j] == num: return False return True def print_array(array): for i in range(0, 9): for j in range(0, 9): print(sudoku_array[i][j], end=' ') print() if __name__ == '__main__': sudoku_array = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] solve_sudoku(sudoku_array) print_array(sudoku_array)
#SetExample4.py ------difference between discard() & remove() #from both remove() gives error if value not found nums = {1,2,3,4} #remove using discard() nums.discard(5) print("After discard(5) : ",nums) #reove using remove() try: nums.remove(5) print("After remove(5) : ",nums) except KeyError: print("KeyError : Value not found")
nums = {1, 2, 3, 4} nums.discard(5) print('After discard(5) : ', nums) try: nums.remove(5) print('After remove(5) : ', nums) except KeyError: print('KeyError : Value not found')
class Item: def __init__(self, name, price, quantity): self._name = name self.set_price(price) self.set_quantity(quantity) def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity def set_price(self, price): if price > 0: self._price = price # todo - defensive checks def set_quantity(self, quantity): if quantity >= 0: self._quantity = quantity # todo - defensive checks def buy(self, quantity_to_buy): if quantity_to_buy <= self._quantity: self._quantity -= quantity_to_buy return quantity_to_buy * self._price return 0
class Item: def __init__(self, name, price, quantity): self._name = name self.set_price(price) self.set_quantity(quantity) def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity def set_price(self, price): if price > 0: self._price = price def set_quantity(self, quantity): if quantity >= 0: self._quantity = quantity def buy(self, quantity_to_buy): if quantity_to_buy <= self._quantity: self._quantity -= quantity_to_buy return quantity_to_buy * self._price return 0
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n-1: return -1 adjacency = [set() for _ in range(n)] for x,y in connections: adjacency[x].add(y) adjacency[y].add(x) components = 0 visited = [False]*n for i in range(n): if visited[i]: continue stack = [i] components += 1 while stack: x = stack.pop() visited[x]=True for neighbor in adjacency[x]: if not visited[neighbor]: stack.append(neighbor) return components - 1
class Solution: def make_connected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n - 1: return -1 adjacency = [set() for _ in range(n)] for (x, y) in connections: adjacency[x].add(y) adjacency[y].add(x) components = 0 visited = [False] * n for i in range(n): if visited[i]: continue stack = [i] components += 1 while stack: x = stack.pop() visited[x] = True for neighbor in adjacency[x]: if not visited[neighbor]: stack.append(neighbor) return components - 1
class Solution: def bitwiseComplement(self, N: int) -> int: if N == 0: return 1 ans = 0 i = 0 while N: r = N % 2 ans += 2 ** i * (1 - r) i += 1 N //= 2 return ans
class Solution: def bitwise_complement(self, N: int) -> int: if N == 0: return 1 ans = 0 i = 0 while N: r = N % 2 ans += 2 ** i * (1 - r) i += 1 n //= 2 return ans
a, b, c = input().split(' ') d, e, f = input().split(' ') g, h, i = input().split(' ') a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) i = int(i) def resto(a, b, c): return (a + b) % c resultado_1 = resto(a, b, c) resultado_2 = resto(d, e, f) resultado_3 = resto(g, h, i) print(resultado_1) print(resultado_2) print(resultado_3)
(a, b, c) = input().split(' ') (d, e, f) = input().split(' ') (g, h, i) = input().split(' ') a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) i = int(i) def resto(a, b, c): return (a + b) % c resultado_1 = resto(a, b, c) resultado_2 = resto(d, e, f) resultado_3 = resto(g, h, i) print(resultado_1) print(resultado_2) print(resultado_3)
jogador = {} time = [] lista = [] total = 0 while True: jogador.clear() jogador['Nome'] = input('Nome do jogador: ') quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome']))) lista.clear() for i in range(0, quantidade): gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1))) total += gol_quantidade lista.append(gol_quantidade) jogador['Gols'] = lista jogador['Total'] = total time.append(jogador.copy()) resposta = str(input('Quer continuar ? [S/N] ')) if resposta in 'Nn': break for k, v in enumerate(time): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print('') print('-=' * 30) print('O jogador {} jogou {} partidas'.format(jogador['Nome'], quantidade)) for i, valor in enumerate(jogador['Gols']): print(' => Na partida {} , fez {} gols'.format(i + 1, valor)) print('Foi um total de {} gols'.format(total))
jogador = {} time = [] lista = [] total = 0 while True: jogador.clear() jogador['Nome'] = input('Nome do jogador: ') quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome']))) lista.clear() for i in range(0, quantidade): gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1))) total += gol_quantidade lista.append(gol_quantidade) jogador['Gols'] = lista jogador['Total'] = total time.append(jogador.copy()) resposta = str(input('Quer continuar ? [S/N] ')) if resposta in 'Nn': break for (k, v) in enumerate(time): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print('') print('-=' * 30) print('O jogador {} jogou {} partidas'.format(jogador['Nome'], quantidade)) for (i, valor) in enumerate(jogador['Gols']): print(' => Na partida {} , fez {} gols'.format(i + 1, valor)) print('Foi um total de {} gols'.format(total))
def df_restructure_values(data, structure='list', destructive=False): '''Takes in a dataframe, and restructures the values so that the output dataframe consist of columns where the value is coupled with the column header. data | DataFrame | a pandas dataframe structure | str | 'list', 'str', 'tuple', or 'dict' destructive | bool | if False, the original dataframe will be retained ''' if destructive is False: data = data.copy(deep=True) for col in data: if structure == 'list': data[col] = [[col, i] for i in data[col]] elif structure == 'str': data[col] = [col + ' ' + i for i in data[col].astype(str)] elif structure == 'dict': data[col] = [{col: i} for i in data[col]] elif structure == 'tuple': data[col] = [(col, i) for i in data[col]] return data
def df_restructure_values(data, structure='list', destructive=False): """Takes in a dataframe, and restructures the values so that the output dataframe consist of columns where the value is coupled with the column header. data | DataFrame | a pandas dataframe structure | str | 'list', 'str', 'tuple', or 'dict' destructive | bool | if False, the original dataframe will be retained """ if destructive is False: data = data.copy(deep=True) for col in data: if structure == 'list': data[col] = [[col, i] for i in data[col]] elif structure == 'str': data[col] = [col + ' ' + i for i in data[col].astype(str)] elif structure == 'dict': data[col] = [{col: i} for i in data[col]] elif structure == 'tuple': data[col] = [(col, i) for i in data[col]] return data
T,R=int(input('Enter no. Test Cases: ')),[] while(T>0): P=[int(x) for x in input('Enter No. Cases,Sum: ').split()] A=sorted([int(x) for x in input('Enter Numbers(A): ').split()][:P[0]]) B=sorted([int(x) for x in input('Enter Numbers(B): ').split()][:P[0]]) for i in range(P[0]): if A[i]+B[-(i+1)]>P[1]: R.append('No') break elif i==P[0]-1: R.append('Yes') T-=1 for T in R: print('Output:',T)
(t, r) = (int(input('Enter no. Test Cases: ')), []) while T > 0: p = [int(x) for x in input('Enter No. Cases,Sum: ').split()] a = sorted([int(x) for x in input('Enter Numbers(A): ').split()][:P[0]]) b = sorted([int(x) for x in input('Enter Numbers(B): ').split()][:P[0]]) for i in range(P[0]): if A[i] + B[-(i + 1)] > P[1]: R.append('No') break elif i == P[0] - 1: R.append('Yes') t -= 1 for t in R: print('Output:', T)
class Solution: def findMaximumXOR(self, nums: List[int]) -> int: L = len(bin(max(nums))) - 2 nums = [[(num >> i) & 1 for i in range(L)][::-1] for num in nums] maxXor, trie = 0, {} for num in nums: currentNode, xorNode, currentXor = trie, trie, 0 for bit in num: currentNode = currentNode.setdefault(bit, {}) toggledBit = 1 - bit if toggledBit in xorNode: currentXor = (currentXor << 1) | 1 xorNode = xorNode[toggledBit] else: currentXor = currentXor << 1 xorNode = xorNode[bit] maxXor = max(maxXor, currentXor) return maxXor
class Solution: def find_maximum_xor(self, nums: List[int]) -> int: l = len(bin(max(nums))) - 2 nums = [[num >> i & 1 for i in range(L)][::-1] for num in nums] (max_xor, trie) = (0, {}) for num in nums: (current_node, xor_node, current_xor) = (trie, trie, 0) for bit in num: current_node = currentNode.setdefault(bit, {}) toggled_bit = 1 - bit if toggledBit in xorNode: current_xor = currentXor << 1 | 1 xor_node = xorNode[toggledBit] else: current_xor = currentXor << 1 xor_node = xorNode[bit] max_xor = max(maxXor, currentXor) return maxXor
''' 2969 6299 9629 ''' def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True for x in range(1000, 10000-2*3330): if sorted(list(str(x))) == sorted(list(str(x + 3330))) == sorted(list(str(x + 2*3330))): if prime(x): if prime(x + 3330): if prime(x + 2*3330): print(f'{x}{x+3330}{x+2*3330}') ''' 148748178147 296962999629 '''
""" 2969 6299 9629 """ def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True for x in range(1000, 10000 - 2 * 3330): if sorted(list(str(x))) == sorted(list(str(x + 3330))) == sorted(list(str(x + 2 * 3330))): if prime(x): if prime(x + 3330): if prime(x + 2 * 3330): print(f'{x}{x + 3330}{x + 2 * 3330}') '\n148748178147\n296962999629\n'
class Rectangle: pass rect1 = Rectangle() rect2 = Rectangle() rect1.height = 30 rect1.width = 10 rect2.height = 5 rect2.width = 10 rect1.area = rect1.height * rect1.width rect2.area = rect2.height * rect2.width print(rect2.area)
class Rectangle: pass rect1 = rectangle() rect2 = rectangle() rect1.height = 30 rect1.width = 10 rect2.height = 5 rect2.width = 10 rect1.area = rect1.height * rect1.width rect2.area = rect2.height * rect2.width print(rect2.area)
# # Font compiler # fonts = [ None ] * 64 current = -1 for l in open("font.txt").readlines(): print(l) if l.strip() != "": if l[0] == ':': current = ord(l[1]) & 0x3F fonts[current] = [] else: l = l.strip().replace(".","0").replace("X","1") assert len(l) == 3 fonts[current].append(int(l,2)) for i in range(0,64): print(i,fonts[i]) assert(len(fonts[i]) == 5) n = 0 for g in fonts[i]: n = n * 8 + g n = n * 2 + 1 fonts[i] = n open("fonttable.asm","w").write("\n".join([" dw "+str(x) for x in fonts]))
fonts = [None] * 64 current = -1 for l in open('font.txt').readlines(): print(l) if l.strip() != '': if l[0] == ':': current = ord(l[1]) & 63 fonts[current] = [] else: l = l.strip().replace('.', '0').replace('X', '1') assert len(l) == 3 fonts[current].append(int(l, 2)) for i in range(0, 64): print(i, fonts[i]) assert len(fonts[i]) == 5 n = 0 for g in fonts[i]: n = n * 8 + g n = n * 2 + 1 fonts[i] = n open('fonttable.asm', 'w').write('\n'.join([' dw ' + str(x) for x in fonts]))
# Read a DNA Sequence def readSequence(): sequence = open(raw_input('Enter sequence filename: '),'r') sequence.readline() sequence = sequence.read().replace('\n', '') return sequence def match(a, b): if a == b: return 1 else: return -1 # Align two sequences using Smith-Waterman algorithm def alignSequences(s1, s2): gap = -2 s1 = '-'+s1 s2 = '-'+s2 mWidth = len(s1) mHeight = len(s2) similarity_matrix = [[i for i in xrange(mHeight)] for i in xrange(mWidth)] for i in range (mWidth): similarity_matrix[i][0] = 0 for j in range (mHeight): similarity_matrix[0][j] = 0 for i in range (1,mWidth): for j in range (1, mHeight): p0 = 0 p1 = similarity_matrix[i-1][j-1] + match(s1[i], s2[j]) p2 = similarity_matrix[i][j-1] + gap p3 = similarity_matrix[i-1][j] + gap similarity_matrix[i][j] = max(p0, p1, p2, p3) #Find biggest number in the similarity matrix maxNumber = 0 maxNumberI = 0 maxNumberJ = 0 for i in range(mWidth): for j in range(mHeight): if similarity_matrix[i][j] >= maxNumber: maxNumber = similarity_matrix[i][j] maxNumberI = i maxNumberJ = j i = maxNumberI j = maxNumberJ alignmentS1 = '' alignmentS2 = '' while similarity_matrix[i][j] > 0: if similarity_matrix[i][j] == similarity_matrix[i-1][j-1] + match(s1[i], s2[j]): alignmentS1 = s1[i] + alignmentS1 alignmentS2 = s2[j] + alignmentS2 j-=1 i-=1 elif similarity_matrix[i][j] == similarity_matrix[i-1][j] + gap: alignmentS1 = s1[i] + alignmentS1 alignmentS2 = '-' + alignmentS2 i-=1 else: alignmentS1 = '-' + alignmentS1 alignmentS2 = s2[j] + alignmentS2 j-=1 qtdeAlinhamento = 0 for i in range(max(len(alignmentS1), len(alignmentS2))): if alignmentS1[i] == alignmentS2[i]: qtdeAlinhamento+=1 print('Tabela final:',similarity_matrix) print('Melhor alinhamento local para a sequencia 1: ', alignmentS1) print('Melhor alinhamento local para a sequencia 2: ', alignmentS2) print('Identidade do alinhamento: ', qtdeAlinhamento) s1 = readSequence() s2 = readSequence() alignSequences(s1, s2)
def read_sequence(): sequence = open(raw_input('Enter sequence filename: '), 'r') sequence.readline() sequence = sequence.read().replace('\n', '') return sequence def match(a, b): if a == b: return 1 else: return -1 def align_sequences(s1, s2): gap = -2 s1 = '-' + s1 s2 = '-' + s2 m_width = len(s1) m_height = len(s2) similarity_matrix = [[i for i in xrange(mHeight)] for i in xrange(mWidth)] for i in range(mWidth): similarity_matrix[i][0] = 0 for j in range(mHeight): similarity_matrix[0][j] = 0 for i in range(1, mWidth): for j in range(1, mHeight): p0 = 0 p1 = similarity_matrix[i - 1][j - 1] + match(s1[i], s2[j]) p2 = similarity_matrix[i][j - 1] + gap p3 = similarity_matrix[i - 1][j] + gap similarity_matrix[i][j] = max(p0, p1, p2, p3) max_number = 0 max_number_i = 0 max_number_j = 0 for i in range(mWidth): for j in range(mHeight): if similarity_matrix[i][j] >= maxNumber: max_number = similarity_matrix[i][j] max_number_i = i max_number_j = j i = maxNumberI j = maxNumberJ alignment_s1 = '' alignment_s2 = '' while similarity_matrix[i][j] > 0: if similarity_matrix[i][j] == similarity_matrix[i - 1][j - 1] + match(s1[i], s2[j]): alignment_s1 = s1[i] + alignmentS1 alignment_s2 = s2[j] + alignmentS2 j -= 1 i -= 1 elif similarity_matrix[i][j] == similarity_matrix[i - 1][j] + gap: alignment_s1 = s1[i] + alignmentS1 alignment_s2 = '-' + alignmentS2 i -= 1 else: alignment_s1 = '-' + alignmentS1 alignment_s2 = s2[j] + alignmentS2 j -= 1 qtde_alinhamento = 0 for i in range(max(len(alignmentS1), len(alignmentS2))): if alignmentS1[i] == alignmentS2[i]: qtde_alinhamento += 1 print('Tabela final:', similarity_matrix) print('Melhor alinhamento local para a sequencia 1: ', alignmentS1) print('Melhor alinhamento local para a sequencia 2: ', alignmentS2) print('Identidade do alinhamento: ', qtdeAlinhamento) s1 = read_sequence() s2 = read_sequence() align_sequences(s1, s2)
def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 def findMax(arr, n): mi = 0 for i in range(0,n): if arr[i] > arr[mi]: mi = i return mi def pancakeSort(arr, n): curr_size = n while curr_size > 1: mi = findMax(arr, curr_size) if mi != curr_size-1: flip(arr, mi) flip(arr, curr_size-1) curr_size -= 1 n = int(input("Enter the size of array : ")) arr = list(map(int, input("Enter the array elements :\n").strip().split()))[:n] print("Before") print(arr) pancakeSort(arr, n); print ("Sorted Array ") print(arr)
def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 def find_max(arr, n): mi = 0 for i in range(0, n): if arr[i] > arr[mi]: mi = i return mi def pancake_sort(arr, n): curr_size = n while curr_size > 1: mi = find_max(arr, curr_size) if mi != curr_size - 1: flip(arr, mi) flip(arr, curr_size - 1) curr_size -= 1 n = int(input('Enter the size of array : ')) arr = list(map(int, input('Enter the array elements :\n').strip().split()))[:n] print('Before') print(arr) pancake_sort(arr, n) print('Sorted Array ') print(arr)
n = int(input()) s = [] while n != 0: n -= 1 name = input() s.append(name) r = input() for i in range(len(s)): if r in s[i]: while r in s[i]: s[i] = s[i].replace(r, "") max_seq = "" for i in range(len(s[0])): ans = "" for j in range(i, len(s[0])): ans += s[0][j] for k in range(1, len(s)): if ans in s[k]: if len(ans) > len(max_seq): max_seq = ans print(max_seq)
n = int(input()) s = [] while n != 0: n -= 1 name = input() s.append(name) r = input() for i in range(len(s)): if r in s[i]: while r in s[i]: s[i] = s[i].replace(r, '') max_seq = '' for i in range(len(s[0])): ans = '' for j in range(i, len(s[0])): ans += s[0][j] for k in range(1, len(s)): if ans in s[k]: if len(ans) > len(max_seq): max_seq = ans print(max_seq)
testArray = [1, 2, 3, 4, 5] testString = 'this is the test string' newString = testString + str(testArray) print(newString)
test_array = [1, 2, 3, 4, 5] test_string = 'this is the test string' new_string = testString + str(testArray) print(newString)
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. class DepthInfo: # The default depth that we travel before forcing a foreign key attribute DEFAULT_MAX_DEPTH = 2 # The max depth set if the user specified to not use max depth MAX_DEPTH_LIMIT = 32 def __init__(self, current_depth, max_depth, max_depth_exceeded): # The maximum depth that we can resolve entity attributes. # This value is set in resolution guidance. self.current_depth = current_depth # type: int # The current depth that we are resolving at. Each entity attribute that we resolve # into adds 1 to depth. self.max_depth = max_depth # type: int # Indicates if the maxDepth value has been hit when resolving self.max_depth_exceeded = max_depth_exceeded # type: int
class Depthinfo: default_max_depth = 2 max_depth_limit = 32 def __init__(self, current_depth, max_depth, max_depth_exceeded): self.current_depth = current_depth self.max_depth = max_depth self.max_depth_exceeded = max_depth_exceeded
class Solution: def isMatch(self, text, pattern): if not pattern: return not text first_match = bool(text) and pattern[0] in {text[0], '.'} if len(pattern) >= 2 and pattern[1] == '*': return (self.isMatch(text, pattern[2:]) or first_match and self.isMatch(text[1:], pattern)) else: return first_match and self.isMatch(text[1:], pattern[1:]) class Solution: def isMatch(self, text, pattern): memo = {} def dp(i, j): if (i, j) not in memo: if j == len(pattern): ans = i == len(text) else: first_match = i < len(text) and pattern[j] in {text[i], '.'} if j+1 < len(pattern) and pattern[j+1] == '*': ans = dp(i, j+2) or first_match and dp(i+1, j) else: ans = first_match and dp(i+1, j+1) memo[i, j] = ans return memo[i, j] return dp(0, 0) class Solution: def isMatch(self, text, pattern): dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)] dp[-1][-1] = True for i in range(len(text), -1, -1): for j in range(len(pattern) - 1, -1, -1): first_match = i < len(text) and pattern[j] in {text[i], '.'} if j+1 < len(pattern) and pattern[j+1] == '*': dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j] else: dp[i][j] = first_match and dp[i+1][j+1] return dp[0][0]
class Solution: def is_match(self, text, pattern): if not pattern: return not text first_match = bool(text) and pattern[0] in {text[0], '.'} if len(pattern) >= 2 and pattern[1] == '*': return self.isMatch(text, pattern[2:]) or (first_match and self.isMatch(text[1:], pattern)) else: return first_match and self.isMatch(text[1:], pattern[1:]) class Solution: def is_match(self, text, pattern): memo = {} def dp(i, j): if (i, j) not in memo: if j == len(pattern): ans = i == len(text) else: first_match = i < len(text) and pattern[j] in {text[i], '.'} if j + 1 < len(pattern) and pattern[j + 1] == '*': ans = dp(i, j + 2) or (first_match and dp(i + 1, j)) else: ans = first_match and dp(i + 1, j + 1) memo[i, j] = ans return memo[i, j] return dp(0, 0) class Solution: def is_match(self, text, pattern): dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)] dp[-1][-1] = True for i in range(len(text), -1, -1): for j in range(len(pattern) - 1, -1, -1): first_match = i < len(text) and pattern[j] in {text[i], '.'} if j + 1 < len(pattern) and pattern[j + 1] == '*': dp[i][j] = dp[i][j + 2] or (first_match and dp[i + 1][j]) else: dp[i][j] = first_match and dp[i + 1][j + 1] return dp[0][0]
def format_sql(table, obj: dict) -> str: cols = ','.join(obj.keys()) values = ','.join(obj.values()) sql = "insert into {table} ({cols}) values ({values})".format(table=table, cols=cols, values=values) return def format_sqls(table, objs: list) -> str: obj = objs.__getitem__(0) cols = ','.join(obj.keys()) values = get_values_str(objs) sql = "insert into {table} ({cols}) values {values}".format(table=table, cols=cols, values=values) return sql def get_values_str(objs: list): values = [] for obj in objs: values.append("({sqlValue})".format(sqlValue=','.join("'%s'" % o for o in obj.values()))) return ",".join(values) # format_sqls("coin", [{"a": "1", "b": "2"}, {"a": "3", "b": "4"}])
def format_sql(table, obj: dict) -> str: cols = ','.join(obj.keys()) values = ','.join(obj.values()) sql = 'insert into {table} ({cols}) values ({values})'.format(table=table, cols=cols, values=values) return def format_sqls(table, objs: list) -> str: obj = objs.__getitem__(0) cols = ','.join(obj.keys()) values = get_values_str(objs) sql = 'insert into {table} ({cols}) values {values}'.format(table=table, cols=cols, values=values) return sql def get_values_str(objs: list): values = [] for obj in objs: values.append('({sqlValue})'.format(sqlValue=','.join(("'%s'" % o for o in obj.values())))) return ','.join(values)
# Head ends here def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5) : count = 0 for j in range(5) : if board[i][j] == "d" : count += 1 if count == 1 : dmax = dmin = j elif count > 1 : dmax = j if count > 0 : for l in range(dmin , dmax + 1): if position < dmin : for k in range(position , dmin , 1) : print("RIGHT") position = k + 1 elif position > dmin : for k in range(position , dmin , -1) : if board[i][k] == "d" : print("CLEAN") board[i][k] == "-" print("LEFT") position = k - 1 elif position == dmin : print("CLEAN") board[i][dmin] = "-" if dmin != dmax : position += 1 print("RIGHT") if i != 4 : print("DOWN") # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board) # Slight Changes in the above code # Head ends here def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5) : count = 0 for j in range(5) : if board[i][j] == "d" : count += 1 if count == 1 : dmax = dmin = j elif count > 1 : dmax = j if count > 0 : for l in range(dmin , dmax + 1): if position < dmin : for k in range(position , dmin , 1) : print("RIGHT") position = k + 1 if position > dmin : for k in range(position , dmin , -1) : if board[i][k] == "d" : print("CLEAN") board[i][k] == "-" print("LEFT") position = k - 1 if position == dmin : print("CLEAN") board[i][dmin] = "-" if dmin != dmax : position += 1 print("RIGHT") if i != 4 : print("DOWN") # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board)
def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5): count = 0 for j in range(5): if board[i][j] == 'd': count += 1 if count == 1: dmax = dmin = j elif count > 1: dmax = j if count > 0: for l in range(dmin, dmax + 1): if position < dmin: for k in range(position, dmin, 1): print('RIGHT') position = k + 1 elif position > dmin: for k in range(position, dmin, -1): if board[i][k] == 'd': print('CLEAN') board[i][k] == '-' print('LEFT') position = k - 1 elif position == dmin: print('CLEAN') board[i][dmin] = '-' if dmin != dmax: position += 1 print('RIGHT') if i != 4: print('DOWN') if __name__ == '__main__': pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board) def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5): count = 0 for j in range(5): if board[i][j] == 'd': count += 1 if count == 1: dmax = dmin = j elif count > 1: dmax = j if count > 0: for l in range(dmin, dmax + 1): if position < dmin: for k in range(position, dmin, 1): print('RIGHT') position = k + 1 if position > dmin: for k in range(position, dmin, -1): if board[i][k] == 'd': print('CLEAN') board[i][k] == '-' print('LEFT') position = k - 1 if position == dmin: print('CLEAN') board[i][dmin] = '-' if dmin != dmax: position += 1 print('RIGHT') if i != 4: print('DOWN') if __name__ == '__main__': pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board)
class Person: def __init__(self, name): self.name = name # create the method greet here def greet(self): print(f"Hello, I am {self.name}!") in_name = input() p = Person(in_name) p.greet()
class Person: def __init__(self, name): self.name = name def greet(self): print(f'Hello, I am {self.name}!') in_name = input() p = person(in_name) p.greet()
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_xerial_snappy_snappy_java", artifact = "org.xerial.snappy:snappy-java:1.1.7.1", artifact_sha256 = "bb52854753feb1919f13099a53475a2a8eb65dbccd22839a9b9b2e1a2190b951", srcjar_sha256 = "a01c58c2af4bf16d2b841c74f76d98489bc03b5f9cf63aea33a8cb14ce376258", )
load('@wix_oss_infra//:import_external.bzl', import_external='safe_wix_scala_maven_import_external') def dependencies(): import_external(name='org_xerial_snappy_snappy_java', artifact='org.xerial.snappy:snappy-java:1.1.7.1', artifact_sha256='bb52854753feb1919f13099a53475a2a8eb65dbccd22839a9b9b2e1a2190b951', srcjar_sha256='a01c58c2af4bf16d2b841c74f76d98489bc03b5f9cf63aea33a8cb14ce376258')
'''from flask import render_template from flask import Response from flask import Flask app = Flask(__name__) @app.route('/') def index(): return render_template('streaming2.html') def generate(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpg\r\n\r\n' + frame + b'\r\n\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')'''
"""from flask import render_template from flask import Response from flask import Flask app = Flask(__name__) @app.route('/') def index(): return render_template('streaming2.html') def generate(camera): while True: frame = camera.get_frame() yield (b'--frame\r ' b'Content-Type: image/jpg\r \r ' + frame + b'\r \r ') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')"""
class StreamQueue: repeat = False current = None streams = [] def next(self): if self.repeat and self.current is not None: return self.current self.current = None if len(self.streams) > 0: self.current = self.streams.pop(0) return self.current def add(self, url): self.streams.append(url) def clear(self): self.current = None self.streams.clear() def __len__(self): return len(self.streams)
class Streamqueue: repeat = False current = None streams = [] def next(self): if self.repeat and self.current is not None: return self.current self.current = None if len(self.streams) > 0: self.current = self.streams.pop(0) return self.current def add(self, url): self.streams.append(url) def clear(self): self.current = None self.streams.clear() def __len__(self): return len(self.streams)
def Move(): global ArchiveIndex, gameData playerShip.landedBefore = playerShip.landedOn playerShip.landedOn = None for Thing in PlanetContainer: XDiff = playerShip.X - Thing.X YDiff = playerShip.Y + Thing.Y Distance = (XDiff ** 2 + YDiff ** 2) ** 0.5 if Distance > 40000: ArchiveContainer.append(Thing) PlanetContainer.remove(Thing) elif Distance <= Thing.size + 26: # collision OR landed --> check speed if playerShip.speed > 2: playerShip.hull -= playerShip.speed ** 2 if playerShip.hull <= 0: # crash! # Play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 DisplayMessage( "You crashed and died in the explosion. You lose.") gameData = None return "to menu" else: # land! playerShip.landedOn = PlanetContainer.index(Thing) if not Thing.playerLanded: if gameData.tutorial and gameData.stage == 1: checkProgress("player landed") if ( Thing.baseAt is not None and ( ( Thing.X + Thing.size * cos(radians(Thing.baseAt + 90)) - playerShip.X ) ** 2 + ( -Thing.Y - Thing.size * sin(radians(Thing.baseAt + 90)) - playerShip.Y ) ** 2 ) ** 0.5 < 60 ): Thing.playerLanded = "base" else: Thing.playerLanded = True playerShip.toX = 0 playerShip.toY = 0 continue else: NDistance = ( (playerShip.X + playerShip.toX - Thing.X) ** 2 + (playerShip.Y + playerShip.toY + Thing.Y) ** 2 ) ** 0.5 if NDistance < Distance: playerShip.toX = Thing.size / 20 / Distance * XDiff / Distance playerShip.toY = Thing.size / 20 / Distance * YDiff / Distance playerShip.speed = ( playerShip.toX ** 2 + playerShip.toY ** 2 ) ** 0.5 playerShip.angle = degrees( atan2(-playerShip.toX, playerShip.toY) ) playerShip.move() playerShip.toX = 0 playerShip.toY = 0 continue else: Thing.playerLanded = False if gameData.stage > 0 and Thing.enemyAt is not None: pos = radians(Thing.enemyAt + 90) X = Thing.X + Thing.size * cos(pos) Y = Thing.Y + Thing.size * sin(pos) if ((playerShip.X - X) ** 2 + (playerShip.Y + Y) ** 2) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: # Play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 DisplayMessage("You where shot and died. You lose.") gameData = None return "to menu" Acceleration = Thing.size / 20 / Distance playerShip.toX -= Acceleration * XDiff / Distance playerShip.toY -= Acceleration * YDiff / Distance playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5 playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY)) for Thing in ShipContainer: # move ships Thing.move() if gameData.stage > 0: if ( (playerShip.X - Thing.X) ** 2 + (playerShip.Y + Thing.Y) ** 2 ) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: Play("boom") if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 DisplayMessage("You where shot and died. You lose.") gameData = None return "to menu" for Thing in WreckContainer: Thing.explosion += 0.1 if Thing.explosion > 10: WreckContainer.remove(Thing) playerShip.move() if sectors.pixels2sector(playerShip.X, playerShip.Y) != sectors.pixels2sector( playerShip.X - playerShip.toX, playerShip.Y - playerShip.toY ): checkProgress("sector changed") playerView.X = playerShip.X playerView.Y = playerShip.Y if playerShip.oil <= 0: # Play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.oil = 0 DisplayMessage( "Your oilsupply is empty. You can't do anything anymore. You lose." ) gameData = None return "to menu" playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 playerShip.oil = 1000 if Frames % 10 == 0: try: Distance = ( (playerShip.X - ArchiveContainer[ArchiveIndex].X) ** 2 + (playerShip.Y + ArchiveContainer[ArchiveIndex].Y) ** 2 ) ** 0.5 if Distance < 35000: T = ArchiveContainer.pop(ArchiveIndex) if type(T) == Planet: PlanetContainer.append(T) elif T.dead: WreckContainer.append(T) else: ShipContainer.append(T) ArchiveIndex = ArchiveIndex % len(ArchiveContainer) else: ArchiveIndex = (ArchiveIndex + 1) % len(ArchiveContainer) except: # If the ArchiveContainer is empty pass
def move(): global ArchiveIndex, gameData playerShip.landedBefore = playerShip.landedOn playerShip.landedOn = None for thing in PlanetContainer: x_diff = playerShip.X - Thing.X y_diff = playerShip.Y + Thing.Y distance = (XDiff ** 2 + YDiff ** 2) ** 0.5 if Distance > 40000: ArchiveContainer.append(Thing) PlanetContainer.remove(Thing) elif Distance <= Thing.size + 26: if playerShip.speed > 2: playerShip.hull -= playerShip.speed ** 2 if playerShip.hull <= 0: if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 display_message('You crashed and died in the explosion. You lose.') game_data = None return 'to menu' else: playerShip.landedOn = PlanetContainer.index(Thing) if not Thing.playerLanded: if gameData.tutorial and gameData.stage == 1: check_progress('player landed') if Thing.baseAt is not None and ((Thing.X + Thing.size * cos(radians(Thing.baseAt + 90)) - playerShip.X) ** 2 + (-Thing.Y - Thing.size * sin(radians(Thing.baseAt + 90)) - playerShip.Y) ** 2) ** 0.5 < 60: Thing.playerLanded = 'base' else: Thing.playerLanded = True playerShip.toX = 0 playerShip.toY = 0 continue else: n_distance = ((playerShip.X + playerShip.toX - Thing.X) ** 2 + (playerShip.Y + playerShip.toY + Thing.Y) ** 2) ** 0.5 if NDistance < Distance: playerShip.toX = Thing.size / 20 / Distance * XDiff / Distance playerShip.toY = Thing.size / 20 / Distance * YDiff / Distance playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5 playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY)) playerShip.move() playerShip.toX = 0 playerShip.toY = 0 continue else: Thing.playerLanded = False if gameData.stage > 0 and Thing.enemyAt is not None: pos = radians(Thing.enemyAt + 90) x = Thing.X + Thing.size * cos(pos) y = Thing.Y + Thing.size * sin(pos) if ((playerShip.X - X) ** 2 + (playerShip.Y + Y) ** 2) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 display_message('You where shot and died. You lose.') game_data = None return 'to menu' acceleration = Thing.size / 20 / Distance playerShip.toX -= Acceleration * XDiff / Distance playerShip.toY -= Acceleration * YDiff / Distance playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5 playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY)) for thing in ShipContainer: Thing.move() if gameData.stage > 0: if ((playerShip.X - Thing.X) ** 2 + (playerShip.Y + Thing.Y) ** 2) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 display_message('You where shot and died. You lose.') game_data = None return 'to menu' for thing in WreckContainer: Thing.explosion += 0.1 if Thing.explosion > 10: WreckContainer.remove(Thing) playerShip.move() if sectors.pixels2sector(playerShip.X, playerShip.Y) != sectors.pixels2sector(playerShip.X - playerShip.toX, playerShip.Y - playerShip.toY): check_progress('sector changed') playerView.X = playerShip.X playerView.Y = playerShip.Y if playerShip.oil <= 0: if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.oil = 0 display_message("Your oilsupply is empty. You can't do anything anymore. You lose.") game_data = None return 'to menu' playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 playerShip.oil = 1000 if Frames % 10 == 0: try: distance = ((playerShip.X - ArchiveContainer[ArchiveIndex].X) ** 2 + (playerShip.Y + ArchiveContainer[ArchiveIndex].Y) ** 2) ** 0.5 if Distance < 35000: t = ArchiveContainer.pop(ArchiveIndex) if type(T) == Planet: PlanetContainer.append(T) elif T.dead: WreckContainer.append(T) else: ShipContainer.append(T) archive_index = ArchiveIndex % len(ArchiveContainer) else: archive_index = (ArchiveIndex + 1) % len(ArchiveContainer) except: pass
def names(l): # list way new = [] for i in l: if not i in new: new.append(i) # set way new = list(set(l)) print(new) names(["Michele", "Robin", "Sara", "Michele"])
def names(l): new = [] for i in l: if not i in new: new.append(i) new = list(set(l)) print(new) names(['Michele', 'Robin', 'Sara', 'Michele'])
mylist = [1, 2, 3] # Imprime 1,2,3 for x in mylist: print(x)
mylist = [1, 2, 3] for x in mylist: print(x)
#Print without newline or space print("\n") for j in range(10): print("") for i in range(10): print(' @ ', end="") print("\n")
print('\n') for j in range(10): print('') for i in range(10): print(' @ ', end='') print('\n')
class Entry: def __init__(self, obj, line_number = 1): self.obj = obj self.line_number = line_number def __repr__(self): return "In {}, line {}".format(self.obj.name, self.line_number) class CallStack: def __init__(self, initial = None): self.__stack = [] if not initial else initial def __repr__(self): stk = "\n".join([str(entry) for entry in self.__stack]) return "Traceback (Most recent call last):\n" + stk + "\n" __str__ = __repr__ def __len__(self): return len(self.__stack) def append(self, entry): self.__stack.append(entry) def pop(self): last = self.__stack[-1] self.__stack.pop() return last def __getitem__(self, index): if isinstance(index, slice): return CallStack(self.__stack[index]) else: return self.__stack[index]
class Entry: def __init__(self, obj, line_number=1): self.obj = obj self.line_number = line_number def __repr__(self): return 'In {}, line {}'.format(self.obj.name, self.line_number) class Callstack: def __init__(self, initial=None): self.__stack = [] if not initial else initial def __repr__(self): stk = '\n'.join([str(entry) for entry in self.__stack]) return 'Traceback (Most recent call last):\n' + stk + '\n' __str__ = __repr__ def __len__(self): return len(self.__stack) def append(self, entry): self.__stack.append(entry) def pop(self): last = self.__stack[-1] self.__stack.pop() return last def __getitem__(self, index): if isinstance(index, slice): return call_stack(self.__stack[index]) else: return self.__stack[index]
class BaseConfig(): API_PREFIX = '/api' TESTING = False DEBUG = False SECRET_KEY = '@!s3cr3t' AGENT_SOCK = 'cmdsrv__0' class DevConfig(BaseConfig): FLASK_ENV = 'development' DEBUG = True CELERY_BROKER = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' REDIS_URL = "redis://localhost:6379/0" IFACE = "eno2" class ProductionConfig(BaseConfig): FLASK_ENV = 'production' CELERY_BROKER = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' REDIS_URL = "redis://localhost:6379/0" class TestConfig(BaseConfig): FLASK_ENV = 'development' TESTING = True DEBUG = True # make celery execute tasks synchronously in the same process CELERY_ALWAYS_EAGER = True
class Baseconfig: api_prefix = '/api' testing = False debug = False secret_key = '@!s3cr3t' agent_sock = 'cmdsrv__0' class Devconfig(BaseConfig): flask_env = 'development' debug = True celery_broker = 'redis://localhost:6379/0' celery_result_backend = 'redis://localhost:6379/0' redis_url = 'redis://localhost:6379/0' iface = 'eno2' class Productionconfig(BaseConfig): flask_env = 'production' celery_broker = 'redis://localhost:6379/0' celery_result_backend = 'redis://localhost:6379/0' redis_url = 'redis://localhost:6379/0' class Testconfig(BaseConfig): flask_env = 'development' testing = True debug = True celery_always_eager = True
while True: x,y=map(int,input().split()) if x==0 and y==0: break print(x+y)
while True: (x, y) = map(int, input().split()) if x == 0 and y == 0: break print(x + y)
def encode(json, schema): payload = schema.Main() payload.github = json['github'] payload.patreon = json['patreon'] payload.open_collective = json['open_collective'] payload.ko_fi = json['ko_fi'] payload.tidelift = json['tidelift'] payload.community_bridge = json['community_bridge'] payload.liberapay = json['liberapay'] payload.issuehunt = json['issuehunt'] payload.otechie = json['otechie'] payload.custom = json['custom'] return payload def decode(payload): return payload.__dict__
def encode(json, schema): payload = schema.Main() payload.github = json['github'] payload.patreon = json['patreon'] payload.open_collective = json['open_collective'] payload.ko_fi = json['ko_fi'] payload.tidelift = json['tidelift'] payload.community_bridge = json['community_bridge'] payload.liberapay = json['liberapay'] payload.issuehunt = json['issuehunt'] payload.otechie = json['otechie'] payload.custom = json['custom'] return payload def decode(payload): return payload.__dict__
#!/usr/bin/python3 OPENVSWITCH_SERVICES_EXPRS = [r"ovsdb-\S+", r"ovs-vswitch\S+", r"ovn\S+"] OVS_PKGS = [r"libc-bin", r"openvswitch-switch", r"ovn", ] OVS_DAEMONS = {"ovs-vswitchd": {"logs": "var/log/openvswitch/ovs-vswitchd.log"}, "ovsdb-server": {"logs": "var/log/openvswitch/ovsdb-server.log"}}
openvswitch_services_exprs = ['ovsdb-\\S+', 'ovs-vswitch\\S+', 'ovn\\S+'] ovs_pkgs = ['libc-bin', 'openvswitch-switch', 'ovn'] ovs_daemons = {'ovs-vswitchd': {'logs': 'var/log/openvswitch/ovs-vswitchd.log'}, 'ovsdb-server': {'logs': 'var/log/openvswitch/ovsdb-server.log'}}
#!/usr/bin/env python3 inputs = {} reduced = {} with open("input.txt") as f: for line in f: inp, to = map(lambda x: x.strip(), line.split("->")) inputs[to] = inp.split(" ") inputs["b"] = "956" def reduce(name): try: return int(name) except: pass try: return int(inputs[name]) except: pass if name not in reduced: exp = inputs[name] if len(exp) == 1: res = reduce(exp[0]) else: op = exp[-2] if op == "NOT": res = ~reduce(exp[1]) & 0xffff elif op == "AND": res = reduce(exp[0]) & reduce(exp[2]) elif op == "OR": res = reduce(exp[0]) | reduce(exp[2]) elif op == "LSHIFT": res = reduce(exp[0]) << reduce(exp[2]) elif op == "RSHIFT": res = reduce(exp[0]) >> reduce(exp[2]) reduced[name] = res return reduced[name] print(reduce("a"))
inputs = {} reduced = {} with open('input.txt') as f: for line in f: (inp, to) = map(lambda x: x.strip(), line.split('->')) inputs[to] = inp.split(' ') inputs['b'] = '956' def reduce(name): try: return int(name) except: pass try: return int(inputs[name]) except: pass if name not in reduced: exp = inputs[name] if len(exp) == 1: res = reduce(exp[0]) else: op = exp[-2] if op == 'NOT': res = ~reduce(exp[1]) & 65535 elif op == 'AND': res = reduce(exp[0]) & reduce(exp[2]) elif op == 'OR': res = reduce(exp[0]) | reduce(exp[2]) elif op == 'LSHIFT': res = reduce(exp[0]) << reduce(exp[2]) elif op == 'RSHIFT': res = reduce(exp[0]) >> reduce(exp[2]) reduced[name] = res return reduced[name] print(reduce('a'))
LCGDIR = '../lib/sunos5' LIBDIR = '${LCGDIR}' BF_PYTHON = '/usr/local' BF_PYTHON_VERSION = '3.2' BF_PYTHON_INC = '${BF_PYTHON}/include/python${BF_PYTHON_VERSION}' BF_PYTHON_BINARY = '${BF_PYTHON}/bin/python${BF_PYTHON_VERSION}' BF_PYTHON_LIB = 'python${BF_PYTHON_VERSION}' #BF_PYTHON+'/lib/python'+BF_PYTHON_VERSION+'/config/libpython'+BF_PYTHON_VERSION+'.a' BF_PYTHON_LINKFLAGS = ['-Xlinker', '-export-dynamic'] WITH_BF_OPENAL = True WITH_BF_STATICOPENAL = False BF_OPENAL = '/usr/local' BF_OPENAL_INC = '${BF_OPENAL}/include' BF_OPENAL_LIBPATH = '${BF_OPENAL}/lib' BF_OPENAL_LIB = 'openal' # Warning, this static lib configuration is untested! users of this OS please confirm. BF_OPENAL_LIB_STATIC = '${BF_OPENAL}/lib/libopenal.a' # Warning, this static lib configuration is untested! users of this OS please confirm. BF_CXX = '/usr' WITH_BF_STATICCXX = False BF_CXX_LIB_STATIC = '${BF_CXX}/lib/libstdc++.a' WITH_BF_SDL = True BF_SDL = '/usr/local' #$(shell sdl-config --prefix) BF_SDL_INC = '${BF_SDL}/include/SDL' #$(shell $(BF_SDL)/bin/sdl-config --cflags) BF_SDL_LIBPATH = '${BF_SDL}/lib' BF_SDL_LIB = 'SDL' #BF_SDL #$(shell $(BF_SDL)/bin/sdl-config --libs) -lSDL_mixer WITH_BF_OPENEXR = True WITH_BF_STATICOPENEXR = False BF_OPENEXR = '/usr/local' BF_OPENEXR_INC = ['${BF_OPENEXR}/include', '${BF_OPENEXR}/include/OpenEXR' ] BF_OPENEXR_LIBPATH = '${BF_OPENEXR}/lib' BF_OPENEXR_LIB = 'Half IlmImf Iex Imath ' # Warning, this static lib configuration is untested! users of this OS please confirm. BF_OPENEXR_LIB_STATIC = '${BF_OPENEXR}/lib/libHalf.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_OPENEXR}/lib/libIex.a ${BF_OPENEXR}/lib/libImath.a ${BF_OPENEXR}/lib/libIlmThread.a' WITH_BF_DDS = True WITH_BF_JPEG = True BF_JPEG = '/usr/local' BF_JPEG_INC = '${BF_JPEG}/include' BF_JPEG_LIBPATH = '${BF_JPEG}/lib' BF_JPEG_LIB = 'jpeg' WITH_BF_PNG = True BF_PNG = '/usr/local' BF_PNG_INC = '${BF_PNG}/include' BF_PNG_LIBPATH = '${BF_PNG}/lib' BF_PNG_LIB = 'png' BF_TIFF = '/usr/local' BF_TIFF_INC = '${BF_TIFF}/include' WITH_BF_ZLIB = True BF_ZLIB = '/usr' BF_ZLIB_INC = '${BF_ZLIB}/include' BF_ZLIB_LIBPATH = '${BF_ZLIB}/lib' BF_ZLIB_LIB = 'z' WITH_BF_INTERNATIONAL = True BF_GETTEXT = '/usr/local' BF_GETTEXT_INC = '${BF_GETTEXT}/include' BF_GETTEXT_LIB = 'gettextlib' BF_GETTEXT_LIBPATH = '${BF_GETTEXT}/lib' WITH_BF_GAMEENGINE=False WITH_BF_PLAYER = False WITH_BF_BULLET = True BF_BULLET = '#extern/bullet2/src' BF_BULLET_INC = '${BF_BULLET}' BF_BULLET_LIB = 'extern_bullet' #WITH_BF_NSPR = True #BF_NSPR = $(LIBDIR)/nspr #BF_NSPR_INC = -I$(BF_NSPR)/include -I$(BF_NSPR)/include/nspr #BF_NSPR_LIB = # Uncomment the following line to use Mozilla inplace of netscape #CPPFLAGS += -DMOZ_NOT_NET # Location of MOZILLA/Netscape header files... #BF_MOZILLA = $(LIBDIR)/mozilla #BF_MOZILLA_INC = -I$(BF_MOZILLA)/include/mozilla/nspr -I$(BF_MOZILLA)/include/mozilla -I$(BF_MOZILLA)/include/mozilla/xpcom -I$(BF_MOZILLA)/include/mozilla/idl #BF_MOZILLA_LIB = # Will fall back to look in BF_MOZILLA_INC/nspr and BF_MOZILLA_LIB # if this is not set. # # Be paranoid regarding library creation (do not update archives) #BF_PARANOID = True # enable freetype2 support for text objects BF_FREETYPE = '/usr/local' BF_FREETYPE_INC = '${BF_FREETYPE}/include ${BF_FREETYPE}/include/freetype2' BF_FREETYPE_LIBPATH = '${BF_FREETYPE}/lib' BF_FREETYPE_LIB = 'freetype' WITH_BF_QUICKTIME = False # -DWITH_QUICKTIME BF_QUICKTIME = '/usr/local' BF_QUICKTIME_INC = '${BF_QUICKTIME}/include' WITH_BF_ICONV = True BF_ICONV = "/usr" BF_ICONV_INC = '${BF_ICONV}/include' BF_ICONV_LIB = 'iconv' BF_ICONV_LIBPATH = '${BF_ICONV}/lib' # enable ffmpeg support WITH_BF_FFMPEG = True # -DWITH_FFMPEG BF_FFMPEG = '/usr/local' BF_FFMPEG_INC = '${BF_FFMPEG}/include' BF_FFMPEG_LIBPATH='${BF_FFMPEG}/lib' BF_FFMPEG_LIB = 'avformat avcodec avutil avdevice' # Mesa Libs should go here if your using them as well.... WITH_BF_STATICOPENGL = False BF_OPENGL = '/usr/openwin' BF_OPENGL_INC = '${BF_OPENGL}/include' BF_OPENGL_LIB = 'GL GLU X11 Xi' BF_OPENGL_LIBPATH = '${BF_OPENGL}/lib' BF_OPENGL_LIB_STATIC = '${BF_OPENGL_LIBPATH}/libGL.a ${BF_OPENGL_LIBPATH}/libGLU.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a ${BF_OPENGL_LIBPATH}/libX11.a ${BF_OPENGL_LIBPATH}/libXi.a ${BF_OPENGL_LIBPATH}/libXext.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a' ## CC = 'gcc' CXX = 'g++' ##ifeq ($CPU),alpha) ## CFLAGS += -pipe -fPIC -funsigned-char -fno-strict-aliasing -mieee CCFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing'] CPPFLAGS = ['-DSUN_OGL_NO_VERTEX_MACROS'] CXXFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing'] REL_CFLAGS = ['-DNDEBUG', '-O2'] REL_CCFLAGS = ['-DNDEBUG', '-O2'] ##BF_DEPEND = True ## ##AR = ar ##ARFLAGS = ruv ##ARFLAGSQUIET = ru ## C_WARN = ['-Wno-char-subscripts', '-Wdeclaration-after-statement'] CC_WARN = ['-Wall'] ##FIX_STUBS_WARNINGS = -Wno-unused LLIBS = ['c', 'm', 'dl', 'pthread', 'stdc++'] ##LOPTS = --dynamic ##DYNLDFLAGS = -shared $(LDFLAGS) BF_PROFILE_CCFLAGS = ['-pg', '-g '] BF_PROFILE_LINKFLAGS = ['-pg'] BF_PROFILE = False BF_DEBUG = False BF_DEBUG_CCFLAGS = ['-D_DEBUG'] BF_BUILDDIR = '../build/sunos5' BF_INSTALLDIR='../install/sunos5' PLATFORM_LINKFLAGS = []
lcgdir = '../lib/sunos5' libdir = '${LCGDIR}' bf_python = '/usr/local' bf_python_version = '3.2' bf_python_inc = '${BF_PYTHON}/include/python${BF_PYTHON_VERSION}' bf_python_binary = '${BF_PYTHON}/bin/python${BF_PYTHON_VERSION}' bf_python_lib = 'python${BF_PYTHON_VERSION}' bf_python_linkflags = ['-Xlinker', '-export-dynamic'] with_bf_openal = True with_bf_staticopenal = False bf_openal = '/usr/local' bf_openal_inc = '${BF_OPENAL}/include' bf_openal_libpath = '${BF_OPENAL}/lib' bf_openal_lib = 'openal' bf_openal_lib_static = '${BF_OPENAL}/lib/libopenal.a' bf_cxx = '/usr' with_bf_staticcxx = False bf_cxx_lib_static = '${BF_CXX}/lib/libstdc++.a' with_bf_sdl = True bf_sdl = '/usr/local' bf_sdl_inc = '${BF_SDL}/include/SDL' bf_sdl_libpath = '${BF_SDL}/lib' bf_sdl_lib = 'SDL' with_bf_openexr = True with_bf_staticopenexr = False bf_openexr = '/usr/local' bf_openexr_inc = ['${BF_OPENEXR}/include', '${BF_OPENEXR}/include/OpenEXR'] bf_openexr_libpath = '${BF_OPENEXR}/lib' bf_openexr_lib = 'Half IlmImf Iex Imath ' bf_openexr_lib_static = '${BF_OPENEXR}/lib/libHalf.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_OPENEXR}/lib/libIex.a ${BF_OPENEXR}/lib/libImath.a ${BF_OPENEXR}/lib/libIlmThread.a' with_bf_dds = True with_bf_jpeg = True bf_jpeg = '/usr/local' bf_jpeg_inc = '${BF_JPEG}/include' bf_jpeg_libpath = '${BF_JPEG}/lib' bf_jpeg_lib = 'jpeg' with_bf_png = True bf_png = '/usr/local' bf_png_inc = '${BF_PNG}/include' bf_png_libpath = '${BF_PNG}/lib' bf_png_lib = 'png' bf_tiff = '/usr/local' bf_tiff_inc = '${BF_TIFF}/include' with_bf_zlib = True bf_zlib = '/usr' bf_zlib_inc = '${BF_ZLIB}/include' bf_zlib_libpath = '${BF_ZLIB}/lib' bf_zlib_lib = 'z' with_bf_international = True bf_gettext = '/usr/local' bf_gettext_inc = '${BF_GETTEXT}/include' bf_gettext_lib = 'gettextlib' bf_gettext_libpath = '${BF_GETTEXT}/lib' with_bf_gameengine = False with_bf_player = False with_bf_bullet = True bf_bullet = '#extern/bullet2/src' bf_bullet_inc = '${BF_BULLET}' bf_bullet_lib = 'extern_bullet' bf_freetype = '/usr/local' bf_freetype_inc = '${BF_FREETYPE}/include ${BF_FREETYPE}/include/freetype2' bf_freetype_libpath = '${BF_FREETYPE}/lib' bf_freetype_lib = 'freetype' with_bf_quicktime = False bf_quicktime = '/usr/local' bf_quicktime_inc = '${BF_QUICKTIME}/include' with_bf_iconv = True bf_iconv = '/usr' bf_iconv_inc = '${BF_ICONV}/include' bf_iconv_lib = 'iconv' bf_iconv_libpath = '${BF_ICONV}/lib' with_bf_ffmpeg = True bf_ffmpeg = '/usr/local' bf_ffmpeg_inc = '${BF_FFMPEG}/include' bf_ffmpeg_libpath = '${BF_FFMPEG}/lib' bf_ffmpeg_lib = 'avformat avcodec avutil avdevice' with_bf_staticopengl = False bf_opengl = '/usr/openwin' bf_opengl_inc = '${BF_OPENGL}/include' bf_opengl_lib = 'GL GLU X11 Xi' bf_opengl_libpath = '${BF_OPENGL}/lib' bf_opengl_lib_static = '${BF_OPENGL_LIBPATH}/libGL.a ${BF_OPENGL_LIBPATH}/libGLU.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a ${BF_OPENGL_LIBPATH}/libX11.a ${BF_OPENGL_LIBPATH}/libXi.a ${BF_OPENGL_LIBPATH}/libXext.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a' cc = 'gcc' cxx = 'g++' ccflags = ['-pipe', '-fPIC', '-funsigned-char', '-fno-strict-aliasing'] cppflags = ['-DSUN_OGL_NO_VERTEX_MACROS'] cxxflags = ['-pipe', '-fPIC', '-funsigned-char', '-fno-strict-aliasing'] rel_cflags = ['-DNDEBUG', '-O2'] rel_ccflags = ['-DNDEBUG', '-O2'] c_warn = ['-Wno-char-subscripts', '-Wdeclaration-after-statement'] cc_warn = ['-Wall'] llibs = ['c', 'm', 'dl', 'pthread', 'stdc++'] bf_profile_ccflags = ['-pg', '-g '] bf_profile_linkflags = ['-pg'] bf_profile = False bf_debug = False bf_debug_ccflags = ['-D_DEBUG'] bf_builddir = '../build/sunos5' bf_installdir = '../install/sunos5' platform_linkflags = []
t=input() while(t>0): s=raw_input() str=s.split(' ') b=int(str[0]) c=int(str[1]) d=int(str[2]) print (c-b)+(c-d) t=t-1
t = input() while t > 0: s = raw_input() str = s.split(' ') b = int(str[0]) c = int(str[1]) d = int(str[2]) print(c - b) + (c - d) t = t - 1
__version__ = "0.1" __requires__ = [ "apptools>=4.2.0", "numpy>=1.6", "traits>=4.4", "enable>4.2", "chaco>=4.4", "fiona>=1.0.2", "scimath>=4.1.2", "shapely>=1.2.17", "tables>=2.4.0", "sdi", ]
__version__ = '0.1' __requires__ = ['apptools>=4.2.0', 'numpy>=1.6', 'traits>=4.4', 'enable>4.2', 'chaco>=4.4', 'fiona>=1.0.2', 'scimath>=4.1.2', 'shapely>=1.2.17', 'tables>=2.4.0', 'sdi']
# A plugin is supposed to define a setup function # which returns the type that the plugin provides # # This plugin fails to do so def useless(): print("Hello World")
def useless(): print('Hello World')
class Number: def numSum(num): count = [] for x in range(1, (num+1)): count.append(x) print(sum(count)) if __name__ == "__main__": num = int(input("Enter A Number: ")) numSum(num)
class Number: def num_sum(num): count = [] for x in range(1, num + 1): count.append(x) print(sum(count)) if __name__ == '__main__': num = int(input('Enter A Number: ')) num_sum(num)
logging.info(" *** Step 3: Build features *** ".format()) # %% =========================================================================== # Feature - Pure Breed Boolean column # ============================================================================= def pure_breed(row): # print(row) mixed_breed_keywords = ['domestic', 'tabby', 'mixed'] # Mixed if labelled as such if row['Breed1'] == 'Mixed Breed': return False # Possible pure if no second breed elif row['Breed2'] == 'NA': # Reject domestic keywords if any([word in row['Breed1'].lower() for word in mixed_breed_keywords]): return False else: return True else: return False #%% Build the pipeline this_pipeline = sk.pipeline.Pipeline([ ('feat: Pure Breed', trf.MultipleToNewFeature(['Breed1','Breed2'], 'Pure Breed', pure_breed)), ]) logging.info("Created pipeline:") for i, step in enumerate(this_pipeline.steps): print(i, step[0], step[1].__str__()) #%% Fit Transform original_cols = df_all.columns df_all = this_pipeline.fit_transform(df_all) logging.info("Pipeline complete. {} new columns.".format(len(df_all.columns) - len(original_cols)))
logging.info(' *** Step 3: Build features *** '.format()) def pure_breed(row): mixed_breed_keywords = ['domestic', 'tabby', 'mixed'] if row['Breed1'] == 'Mixed Breed': return False elif row['Breed2'] == 'NA': if any([word in row['Breed1'].lower() for word in mixed_breed_keywords]): return False else: return True else: return False this_pipeline = sk.pipeline.Pipeline([('feat: Pure Breed', trf.MultipleToNewFeature(['Breed1', 'Breed2'], 'Pure Breed', pure_breed))]) logging.info('Created pipeline:') for (i, step) in enumerate(this_pipeline.steps): print(i, step[0], step[1].__str__()) original_cols = df_all.columns df_all = this_pipeline.fit_transform(df_all) logging.info('Pipeline complete. {} new columns.'.format(len(df_all.columns) - len(original_cols)))
aws_access_key_id=None aws_secret_access_key=None img_bucket_name=None
aws_access_key_id = None aws_secret_access_key = None img_bucket_name = None
def get_tickets(path): with open(path, 'r') as fh: yield fh.read().splitlines() def get_new_range(_min, _max, value): # print(_min, _max, value) if value == 'F' or value == 'L': mid = _min + (_max - _min) // 2 return (_min, mid) if value == 'B' or value == 'R': mid = _min + (_max - _min) // 2 + 1 return (mid, _max) print("something is wrong") def get_id(ticket): # print(ticket) range_min = 0 range_max = 127 tpl = (0, 127) for item in ticket[0:7]: tpl = get_new_range(range_min, range_max, item) range_min, range_max = tpl row = tpl[0] range_min = 0 range_max = 7 tpl = (0, 7) for item in ticket[-3:]: tpl = get_new_range(range_min, range_max, item) range_min, range_max = tpl column = tpl[0] return row * 8 + column _file = 'resources/day5_input.txt' _id = 0 ids = [] for tickets in get_tickets(_file): for ticket in tickets: ticket_id = get_id(ticket) ids.append(ticket_id) if ticket_id > _id: _id = ticket_id print("Day 5 - part I:", _id) # print(ids) for i in range(_id): if i not in ids and i-1 in ids and i+1 in ids: print("Day 5 - part II:", i)
def get_tickets(path): with open(path, 'r') as fh: yield fh.read().splitlines() def get_new_range(_min, _max, value): if value == 'F' or value == 'L': mid = _min + (_max - _min) // 2 return (_min, mid) if value == 'B' or value == 'R': mid = _min + (_max - _min) // 2 + 1 return (mid, _max) print('something is wrong') def get_id(ticket): range_min = 0 range_max = 127 tpl = (0, 127) for item in ticket[0:7]: tpl = get_new_range(range_min, range_max, item) (range_min, range_max) = tpl row = tpl[0] range_min = 0 range_max = 7 tpl = (0, 7) for item in ticket[-3:]: tpl = get_new_range(range_min, range_max, item) (range_min, range_max) = tpl column = tpl[0] return row * 8 + column _file = 'resources/day5_input.txt' _id = 0 ids = [] for tickets in get_tickets(_file): for ticket in tickets: ticket_id = get_id(ticket) ids.append(ticket_id) if ticket_id > _id: _id = ticket_id print('Day 5 - part I:', _id) for i in range(_id): if i not in ids and i - 1 in ids and (i + 1 in ids): print('Day 5 - part II:', i)
def cls_with_meta(mc, attrs): class _x_(object): __metaclass__ = mc for k, v in attrs.items(): setattr(_x_, k, v) return _x_
def cls_with_meta(mc, attrs): class _X_(object): __metaclass__ = mc for (k, v) in attrs.items(): setattr(_x_, k, v) return _x_
num = int(input('Digite um valor para saber seu fatorial: ')) d = num for c in range(num-1,1,-1): num += (num * c) - num print('Calculando {}! = {}.'.format(d, num))
num = int(input('Digite um valor para saber seu fatorial: ')) d = num for c in range(num - 1, 1, -1): num += num * c - num print('Calculando {}! = {}.'.format(d, num))
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: head = ListNode(0, head) p1, prev, p2 = head, head, head.next while p2: if p2.val < x: if p1 == prev: prev, p2 = p2, p2.next else: p1.next, p2.next, p2, prev.next = p2, p1.next, p2.next, p2.next p1 = p1.next else: prev, p2 = p2, p2.next return head.next
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: head = list_node(0, head) (p1, prev, p2) = (head, head, head.next) while p2: if p2.val < x: if p1 == prev: (prev, p2) = (p2, p2.next) else: (p1.next, p2.next, p2, prev.next) = (p2, p1.next, p2.next, p2.next) p1 = p1.next else: (prev, p2) = (p2, p2.next) return head.next
# # PySNMP MIB module BLUECOAT-HOST-RESOURCES-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-HOST-RESOURCES-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:39:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint") blueCoatMgmt, = mibBuilder.importSymbols("BLUECOAT-MIB", "blueCoatMgmt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") iso, Bits, Counter64, TimeTicks, IpAddress, Unsigned32, MibIdentifier, Counter32, ObjectIdentity, ModuleIdentity, Integer32, NotificationType, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Bits", "Counter64", "TimeTicks", "IpAddress", "Unsigned32", "MibIdentifier", "Counter32", "ObjectIdentity", "ModuleIdentity", "Integer32", "NotificationType", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") blueCoatHostResourcesMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 3417, 2, 9)) blueCoatHostResourcesMIB.setRevisions(('2007-04-24 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setRevisionsDescriptions(('Marked as deprecated.',)) if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setLastUpdated('200704240000Z') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setOrganization('Blue Coat') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setContactInfo('support@bluecoat.com') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setDescription('Internal MIB defines Blue Coat device serial number for Blue Coat Director use.') bchrDevice = MibIdentifier((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1)) bchrSerial = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly") if mibBuilder.loadTexts: bchrSerial.setStatus('deprecated') if mibBuilder.loadTexts: bchrSerial.setDescription('Serial number of the Blue Coat device.') mibBuilder.exportSymbols("BLUECOAT-HOST-RESOURCES-MIB", bchrDevice=bchrDevice, blueCoatHostResourcesMIB=blueCoatHostResourcesMIB, bchrSerial=bchrSerial, PYSNMP_MODULE_ID=blueCoatHostResourcesMIB)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint') (blue_coat_mgmt,) = mibBuilder.importSymbols('BLUECOAT-MIB', 'blueCoatMgmt') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (iso, bits, counter64, time_ticks, ip_address, unsigned32, mib_identifier, counter32, object_identity, module_identity, integer32, notification_type, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Bits', 'Counter64', 'TimeTicks', 'IpAddress', 'Unsigned32', 'MibIdentifier', 'Counter32', 'ObjectIdentity', 'ModuleIdentity', 'Integer32', 'NotificationType', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') blue_coat_host_resources_mib = module_identity((1, 3, 6, 1, 4, 1, 3417, 2, 9)) blueCoatHostResourcesMIB.setRevisions(('2007-04-24 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setRevisionsDescriptions(('Marked as deprecated.',)) if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setLastUpdated('200704240000Z') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setOrganization('Blue Coat') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setContactInfo('support@bluecoat.com') if mibBuilder.loadTexts: blueCoatHostResourcesMIB.setDescription('Internal MIB defines Blue Coat device serial number for Blue Coat Director use.') bchr_device = mib_identifier((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1)) bchr_serial = mib_scalar((1, 3, 6, 1, 4, 1, 3417, 2, 9, 1, 1), octet_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly') if mibBuilder.loadTexts: bchrSerial.setStatus('deprecated') if mibBuilder.loadTexts: bchrSerial.setDescription('Serial number of the Blue Coat device.') mibBuilder.exportSymbols('BLUECOAT-HOST-RESOURCES-MIB', bchrDevice=bchrDevice, blueCoatHostResourcesMIB=blueCoatHostResourcesMIB, bchrSerial=bchrSerial, PYSNMP_MODULE_ID=blueCoatHostResourcesMIB)
t = {} t["0"] = ["-113", "Marginal"] t["1"] = ["-111", "Marginal"] t["2"] = ["-109", "Marginal"] t["3"] = ["-107", "Marginal"] t["4"] = ["-105", "Marginal"] t["5"] = ["-103", "Marginal"] t["6"] = ["-101", "Marginal"] t["7"] = ["-99", "Marginal"] t["8"] = ["-97", "Marginal"] t["9"] = ["-95", "Marginal"] t["10"] = ["-93", "OK"] t["11"] = ["-91", "OK"] t["12"] = ["-89", "OK"] t["13"] = ["-87", "OK"] t["14"] = ["-85", "OK"] t["15"] = ["-83", "Good"] t["16"] = ["-81", "Good"] t["17"] = ["-79", "Good"] t["18"] = ["-77", "Good"] t["19"] = ["-75", "Good"] t["20"] = ["-73", "Excellent"] t["21"] = ["-71", "Excellent"] t["22"] = ["-69", "Excellent"] t["23"] = ["-67", "Excellent"] t["24"] = ["-65", "Excellent"] t["25"] = ["-63", "Excellent"] t["26"] = ["-61", "Excellent"] t["27"] = ["-59", "Excellent"] t["28"] = ["-57", "Excellent"] t["29"] = ["-55", "Excellent"] t["30"] = ["-53", "Excellent"] t["99"] = ["-53", "Excellent"]
t = {} t['0'] = ['-113', 'Marginal'] t['1'] = ['-111', 'Marginal'] t['2'] = ['-109', 'Marginal'] t['3'] = ['-107', 'Marginal'] t['4'] = ['-105', 'Marginal'] t['5'] = ['-103', 'Marginal'] t['6'] = ['-101', 'Marginal'] t['7'] = ['-99', 'Marginal'] t['8'] = ['-97', 'Marginal'] t['9'] = ['-95', 'Marginal'] t['10'] = ['-93', 'OK'] t['11'] = ['-91', 'OK'] t['12'] = ['-89', 'OK'] t['13'] = ['-87', 'OK'] t['14'] = ['-85', 'OK'] t['15'] = ['-83', 'Good'] t['16'] = ['-81', 'Good'] t['17'] = ['-79', 'Good'] t['18'] = ['-77', 'Good'] t['19'] = ['-75', 'Good'] t['20'] = ['-73', 'Excellent'] t['21'] = ['-71', 'Excellent'] t['22'] = ['-69', 'Excellent'] t['23'] = ['-67', 'Excellent'] t['24'] = ['-65', 'Excellent'] t['25'] = ['-63', 'Excellent'] t['26'] = ['-61', 'Excellent'] t['27'] = ['-59', 'Excellent'] t['28'] = ['-57', 'Excellent'] t['29'] = ['-55', 'Excellent'] t['30'] = ['-53', 'Excellent'] t['99'] = ['-53', 'Excellent']
class Solution: def longestWPI(self, hours: List[int]) -> int: acc = 0 seen = {0 : -1} mx_len = 0 for i, h in enumerate(hours): if h > 8: acc += 1 else: acc -= 1 if acc > 0: mx_len = i + 1 if acc not in seen: seen[acc] = i if (acc - 1) in seen: mx_len = max(mx_len, i - seen[acc - 1]) return mx_len
class Solution: def longest_wpi(self, hours: List[int]) -> int: acc = 0 seen = {0: -1} mx_len = 0 for (i, h) in enumerate(hours): if h > 8: acc += 1 else: acc -= 1 if acc > 0: mx_len = i + 1 if acc not in seen: seen[acc] = i if acc - 1 in seen: mx_len = max(mx_len, i - seen[acc - 1]) return mx_len
#log in process def login(): Username = input("Enter Username : ") if Username == 'betterllama' or NewUsername: Password = input("Enter Password : ") else: print("Username Incorrect") if Password == 'omoshi' or NewPassword: print("Welcome, " + Username) else: print("Password is incorrect") #sign up + log in process def signup(NewUsername = 'default', NewPassword = 'default'): NewUsername = input("Choose a Username : ") NewPassword = input("Choose a Password : ") print("Would you like to log in now?") x = input("Type 'yes' or 'no' : ") if x == 'yes': Username = input("Enter Username : ") if Username == 'betterllama' or NewUsername: Password = input("Enter Password : ") else: print("Username Incorrect") if Password == 'omoshi' or NewPassword: print("Welcome, " + Username) else: print("Password is incorrect") else: print("done") #start sequence def start(): print("Would you like to Login or Sign Up? ") x = input("Type 'login' or 'signup' : ") if x == 'login': login() else: signup() start()
def login(): username = input('Enter Username : ') if Username == 'betterllama' or NewUsername: password = input('Enter Password : ') else: print('Username Incorrect') if Password == 'omoshi' or NewPassword: print('Welcome, ' + Username) else: print('Password is incorrect') def signup(NewUsername='default', NewPassword='default'): new_username = input('Choose a Username : ') new_password = input('Choose a Password : ') print('Would you like to log in now?') x = input("Type 'yes' or 'no' : ") if x == 'yes': username = input('Enter Username : ') if Username == 'betterllama' or NewUsername: password = input('Enter Password : ') else: print('Username Incorrect') if Password == 'omoshi' or NewPassword: print('Welcome, ' + Username) else: print('Password is incorrect') else: print('done') def start(): print('Would you like to Login or Sign Up? ') x = input("Type 'login' or 'signup' : ") if x == 'login': login() else: signup() start()
# -*- coding: utf8 -*- def js_test(): pass
def js_test(): pass
#!/usr/bin/env python # ----------------------------------------------------------------------------- # This example will open a file and read it line by line, process each line, # and write the processed line to standard out. # ----------------------------------------------------------------------------- # Open a file for writing. Use 'a' instead of 'w' to append to the file. outfile = open('jenny.txt', 'w') # Create some data to write to a file. Need some numbers, text and a list num = 867 num2 = 5309 txt = 'Jenny' txt2 = 'Tommy Tutone' list = ['Everclear', 'Foo Fighters', 'Green Day', 'Goo Goo Dolls'] # The 2.x version of Python formats strings using the method below. The 3.x # version of python uses .format(). The method below will be phased out of # python eventually but I use it here because it is compatible with Python # 2.x, which is the default version of python in Ubuntu and BT5. # # UPDATE: The .format() string formatting method is supported in Python 2.6 # and higher. outfile.write('%d-%d/%s was sung by %s\n' % (num, num2, txt, txt2)) outfile.write('and was covered by:\n') for l in list: outfile.write('%s\n' % (l)) # Close the file because we are done with it. outfile.close()
outfile = open('jenny.txt', 'w') num = 867 num2 = 5309 txt = 'Jenny' txt2 = 'Tommy Tutone' list = ['Everclear', 'Foo Fighters', 'Green Day', 'Goo Goo Dolls'] outfile.write('%d-%d/%s was sung by %s\n' % (num, num2, txt, txt2)) outfile.write('and was covered by:\n') for l in list: outfile.write('%s\n' % l) outfile.close()
class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 if x < -(2 ** 31) or x > (2 ** 31) - 1: return 0 newNumber = 0 tempNumber = abs(x) while tempNumber > 0: newNumber = (newNumber * 10) + tempNumber % 10 tempNumber = tempNumber // 10 if newNumber < -(2 ** 31) or newNumber > (2 ** 31) - 1: return 0 if x < 0: return -1 * newNumber else: return newNumber
class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 if x < -2 ** 31 or x > 2 ** 31 - 1: return 0 new_number = 0 temp_number = abs(x) while tempNumber > 0: new_number = newNumber * 10 + tempNumber % 10 temp_number = tempNumber // 10 if newNumber < -2 ** 31 or newNumber > 2 ** 31 - 1: return 0 if x < 0: return -1 * newNumber else: return newNumber
good = 0 good_2 = 0 with open("day2.txt") as f: for line in f.readlines(): parts = line.strip().split() print(parts) cmin, cmax = [int(i) for i in parts[0].split('-')] letter = parts[1][0] pwd = parts[2] print(cmin, cmax, letter, pwd) count = pwd.count(letter) if count >= cmin and count <= cmax: good += 1 if (pwd[cmin - 1] == letter or pwd[cmax - 1] == letter) and not (pwd[cmin - 1] == letter and pwd[cmax - 1] == letter): good_2 += 1 print(good, good_2)
good = 0 good_2 = 0 with open('day2.txt') as f: for line in f.readlines(): parts = line.strip().split() print(parts) (cmin, cmax) = [int(i) for i in parts[0].split('-')] letter = parts[1][0] pwd = parts[2] print(cmin, cmax, letter, pwd) count = pwd.count(letter) if count >= cmin and count <= cmax: good += 1 if (pwd[cmin - 1] == letter or pwd[cmax - 1] == letter) and (not (pwd[cmin - 1] == letter and pwd[cmax - 1] == letter)): good_2 += 1 print(good, good_2)
description = 'PUMA multianalyzer device' group = 'lowlevel' includes = ['aliases'] level = False devices = dict( man = device('nicos_mlz.puma.devices.PumaMultiAnalyzer', description = 'PUMA multi analyzer', translations = ['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8', 'ta9', 'ta10', 'ta11'], rotations = ['ra1', 'ra2', 'ra3', 'ra4', 'ra5', 'ra6', 'ra7', 'ra8', 'ra9', 'ra10', 'ra11'], ), muslit_t = device('nicos.devices.generic.Axis', description = 'translation multianalyzer slit', motor = device('nicos.devices.generic.virtual.VirtualMotor', abslimits = (471, 565), unit = 'mm', ), precision = 1, fmtstr = '%.2f', ), ) for i in range(1, 12): devices['ta%d' % i] = device('nicos.devices.generic.Axis', description = 'Translation crystal %d multianalyzer' % i, motor = device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits = (-125.1, 125.1), userlimits = (-125, 125), unit = 'mm', refpos = 0., fmtstr = '%.3f', speed = 5.0, ), precision = 0.01, lowlevel = level, ) devices['ra%d' % i] = device('nicos.devices.generic.Axis', description = 'Rotation crystal %d multianalyzer' % i, motor = device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits = (-60.1, 0.5), userlimits = (-60.05, 0.5), unit = 'deg', refpos = 0.1, fmtstr = '%.3f', speed = 1.0, ), precision = 0.01, lowlevel = level, ) alias_config = { 'theta': {'ra6': 200}, }
description = 'PUMA multianalyzer device' group = 'lowlevel' includes = ['aliases'] level = False devices = dict(man=device('nicos_mlz.puma.devices.PumaMultiAnalyzer', description='PUMA multi analyzer', translations=['ta1', 'ta2', 'ta3', 'ta4', 'ta5', 'ta6', 'ta7', 'ta8', 'ta9', 'ta10', 'ta11'], rotations=['ra1', 'ra2', 'ra3', 'ra4', 'ra5', 'ra6', 'ra7', 'ra8', 'ra9', 'ra10', 'ra11']), muslit_t=device('nicos.devices.generic.Axis', description='translation multianalyzer slit', motor=device('nicos.devices.generic.virtual.VirtualMotor', abslimits=(471, 565), unit='mm'), precision=1, fmtstr='%.2f')) for i in range(1, 12): devices['ta%d' % i] = device('nicos.devices.generic.Axis', description='Translation crystal %d multianalyzer' % i, motor=device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits=(-125.1, 125.1), userlimits=(-125, 125), unit='mm', refpos=0.0, fmtstr='%.3f', speed=5.0), precision=0.01, lowlevel=level) devices['ra%d' % i] = device('nicos.devices.generic.Axis', description='Rotation crystal %d multianalyzer' % i, motor=device('nicos_mlz.puma.devices.virtual.VirtualReferenceMotor', abslimits=(-60.1, 0.5), userlimits=(-60.05, 0.5), unit='deg', refpos=0.1, fmtstr='%.3f', speed=1.0), precision=0.01, lowlevel=level) alias_config = {'theta': {'ra6': 200}}
class Solution: def longestPalindrome(self, s: str) -> str: if not s: return None result = '' maxPal = 0 record = [[0] * len(s) for i in range(len(s))] for j in range(len(s)): for i in range(j+1): record[i][j] = ((s[i] == s[j]) and (j-i<=2 or record[i+1][j-1])) if record[i][j] and j-i+1 > maxPal: maxPal = j-i+1 result = s[i:j+1] return result
class Solution: def longest_palindrome(self, s: str) -> str: if not s: return None result = '' max_pal = 0 record = [[0] * len(s) for i in range(len(s))] for j in range(len(s)): for i in range(j + 1): record[i][j] = s[i] == s[j] and (j - i <= 2 or record[i + 1][j - 1]) if record[i][j] and j - i + 1 > maxPal: max_pal = j - i + 1 result = s[i:j + 1] return result
__author__ = 'Liu' def quadrado_menores(n): return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n] assert [1] == quadrado_menores(1) assert [1, 4] == quadrado_menores(4) assert [1, 4, 9] == quadrado_menores(9) assert [1, 4, 9] == quadrado_menores(11) def soma_quadrados(n): if n > 0: menores = quadrado_menores(n) ultimo = menores[-1] if ultimo == n: return [n] else: lista_escolhida = gerar_solucao(menores, n) while menores: lista_escolhida_2 = gerar_solucao(menores, n) if len(lista_escolhida_2) < len(lista_escolhida): lista_escolhida = lista_escolhida_2 return lista_escolhida return[0] def gerar_solucao(menores, n): ultimo = menores.pop() lista_escolhida = [ultimo] lista_escolhida.extend(soma_quadrados(n - ultimo)) return lista_escolhida assert [0] == soma_quadrados(0) assert [1] == soma_quadrados(1) assert [4] == soma_quadrados(4) assert [9] == soma_quadrados(9) assert [1,1] == soma_quadrados(2) assert [1,1,1] == soma_quadrados(3) assert [4,1] == soma_quadrados(5) assert [4,4,4] == soma_quadrados(12) assert [9, 4] == soma_quadrados(13) assert [9, 4, 1] == soma_quadrados(14) numero = int (input("Adiciona o numero desejada: ")) print(soma_quadrados(numero))
__author__ = 'Liu' def quadrado_menores(n): return [i ** 2 for i in range(1, n + 1) if i ** 2 <= n] assert [1] == quadrado_menores(1) assert [1, 4] == quadrado_menores(4) assert [1, 4, 9] == quadrado_menores(9) assert [1, 4, 9] == quadrado_menores(11) def soma_quadrados(n): if n > 0: menores = quadrado_menores(n) ultimo = menores[-1] if ultimo == n: return [n] else: lista_escolhida = gerar_solucao(menores, n) while menores: lista_escolhida_2 = gerar_solucao(menores, n) if len(lista_escolhida_2) < len(lista_escolhida): lista_escolhida = lista_escolhida_2 return lista_escolhida return [0] def gerar_solucao(menores, n): ultimo = menores.pop() lista_escolhida = [ultimo] lista_escolhida.extend(soma_quadrados(n - ultimo)) return lista_escolhida assert [0] == soma_quadrados(0) assert [1] == soma_quadrados(1) assert [4] == soma_quadrados(4) assert [9] == soma_quadrados(9) assert [1, 1] == soma_quadrados(2) assert [1, 1, 1] == soma_quadrados(3) assert [4, 1] == soma_quadrados(5) assert [4, 4, 4] == soma_quadrados(12) assert [9, 4] == soma_quadrados(13) assert [9, 4, 1] == soma_quadrados(14) numero = int(input('Adiciona o numero desejada: ')) print(soma_quadrados(numero))
a = 1 if a == 1: print("ok") else: print("no") py_builtins = 1 if py_builtins == 1: print("ok") else: print("no") for py_builtins in range(5): a += py_builtins print(a)
a = 1 if a == 1: print('ok') else: print('no') py_builtins = 1 if py_builtins == 1: print('ok') else: print('no') for py_builtins in range(5): a += py_builtins print(a)
flag = [""] * 36 flag[0] = chr(0x46) flag[1] = chr(0x4c) flag[2] = chr(0x41) flag[3] = chr(0x47) flag[4] = chr(0x7b) flag[5] = chr(0x35) flag[6] = chr(0x69) flag[7] = chr(0x6d) flag[8] = chr(0x70) flag[9] = chr(0x31) flag[10] = chr(0x65) flag[11] = chr(0x5f) flag[12] = chr(0x52) flag[13] = chr(0x65) flag[14] = chr(0x76) flag[15] = chr(0x65) flag[16] = chr(0x72) flag[17] = chr(0x73) flag[18] = chr(0x31) flag[19] = chr(0x6e) flag[20] = chr(0x67) flag[21] = chr(0x5f) flag[22] = chr(0x34) flag[23] = chr(0x72) flag[24] = chr(0x72) flag[25] = chr(0x61) flag[26] = chr(0x79) flag[27] = chr(0x5f) flag[28] = chr(0x35) flag[29] = chr(0x74) flag[30] = chr(0x72) flag[31] = chr(0x69) flag[32] = chr(0x6e) flag[33] = chr(0x67) flag[34] = chr(0x73) flag[35] = chr(0x7d) print("".join(flag)) # FLAG{5imp1e_Revers1ng_4rray_5trings}
flag = [''] * 36 flag[0] = chr(70) flag[1] = chr(76) flag[2] = chr(65) flag[3] = chr(71) flag[4] = chr(123) flag[5] = chr(53) flag[6] = chr(105) flag[7] = chr(109) flag[8] = chr(112) flag[9] = chr(49) flag[10] = chr(101) flag[11] = chr(95) flag[12] = chr(82) flag[13] = chr(101) flag[14] = chr(118) flag[15] = chr(101) flag[16] = chr(114) flag[17] = chr(115) flag[18] = chr(49) flag[19] = chr(110) flag[20] = chr(103) flag[21] = chr(95) flag[22] = chr(52) flag[23] = chr(114) flag[24] = chr(114) flag[25] = chr(97) flag[26] = chr(121) flag[27] = chr(95) flag[28] = chr(53) flag[29] = chr(116) flag[30] = chr(114) flag[31] = chr(105) flag[32] = chr(110) flag[33] = chr(103) flag[34] = chr(115) flag[35] = chr(125) print(''.join(flag))
uno= Board('/dev/cu.wchusbserial1420') led= Led(13) led.setColor([0.84, 0.34, 0.67]) ledController= ExdTextInputBox(target= led, value="period", size="sm") APP.STACK.add_widget(ledController)
uno = board('/dev/cu.wchusbserial1420') led = led(13) led.setColor([0.84, 0.34, 0.67]) led_controller = exd_text_input_box(target=led, value='period', size='sm') APP.STACK.add_widget(ledController)
a, b = map(int, input().split()) if a + b == 15: print('+') elif a*b == 15: print('*') else: print('x')
(a, b) = map(int, input().split()) if a + b == 15: print('+') elif a * b == 15: print('*') else: print('x')
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: n = len(stoneValue) dp = [[0] * n for _ in range(n)] mx = [[0] * n for _ in range(n)] for i in range(n): mx[i][i] = stoneValue[i] for j in range(1, n): mid = j s = stoneValue[j] rightHalf = 0 for i in range(j - 1, -1, -1): s += stoneValue[i] while (rightHalf + stoneValue[mid]) * 2 <= s: rightHalf += stoneValue[mid] mid -= 1 if rightHalf * 2 == s: dp[i][j] = mx[i][mid] else: dp[i][j] = (0 if mid == i else mx[i][mid - 1]) if mid != j: dp[i][j] = max(dp[i][j], mx[j][mid + 1]) mx[i][j] = max(mx[i][j - 1], dp[i][j] + s) mx[j][i] = max(mx[j][i + 1], dp[i][j] + s) return dp[0][n - 1]
class Solution: def stone_game_v(self, stoneValue: List[int]) -> int: n = len(stoneValue) dp = [[0] * n for _ in range(n)] mx = [[0] * n for _ in range(n)] for i in range(n): mx[i][i] = stoneValue[i] for j in range(1, n): mid = j s = stoneValue[j] right_half = 0 for i in range(j - 1, -1, -1): s += stoneValue[i] while (rightHalf + stoneValue[mid]) * 2 <= s: right_half += stoneValue[mid] mid -= 1 if rightHalf * 2 == s: dp[i][j] = mx[i][mid] else: dp[i][j] = 0 if mid == i else mx[i][mid - 1] if mid != j: dp[i][j] = max(dp[i][j], mx[j][mid + 1]) mx[i][j] = max(mx[i][j - 1], dp[i][j] + s) mx[j][i] = max(mx[j][i + 1], dp[i][j] + s) return dp[0][n - 1]
# %% [404. Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: if not root: return 0 r = self.sumOfLeftLeaves(root.right) if (p := root.left) and not p.left and not p.right: return root.left.val + r return self.sumOfLeftLeaves(root.left) + r
class Solution: def sum_of_left_leaves(self, root: TreeNode) -> int: if not root: return 0 r = self.sumOfLeftLeaves(root.right) if (p := root.left) and (not p.left) and (not p.right): return root.left.val + r return self.sumOfLeftLeaves(root.left) + r
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 row, col = len(matrix), len(matrix[0]) dp = [0] * col ret = 0 for i in range(row): for j in range(col): if matrix[i][j] == '1': dp[j] += 1 else: dp[j] = 0 left = [] right = [None] * col stack = [] for idx, val in enumerate(dp): while stack and val <= dp[stack[-1]]: stack.pop(); if not stack: left.append(-1) else: left.append(stack[-1]) stack.append(idx) stack = [] for idx, val in enumerate(dp[::-1]): cidx = col - idx - 1 while stack and val <= dp[stack[-1]]: stack.pop(); if not stack: right[cidx] = col else: right[cidx] = stack[-1] stack.append(cidx) for l, r, v in zip(left, right, dp): ret = max(ret, v * (r - l - 1)) return ret
class Solution: def maximal_rectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 (row, col) = (len(matrix), len(matrix[0])) dp = [0] * col ret = 0 for i in range(row): for j in range(col): if matrix[i][j] == '1': dp[j] += 1 else: dp[j] = 0 left = [] right = [None] * col stack = [] for (idx, val) in enumerate(dp): while stack and val <= dp[stack[-1]]: stack.pop() if not stack: left.append(-1) else: left.append(stack[-1]) stack.append(idx) stack = [] for (idx, val) in enumerate(dp[::-1]): cidx = col - idx - 1 while stack and val <= dp[stack[-1]]: stack.pop() if not stack: right[cidx] = col else: right[cidx] = stack[-1] stack.append(cidx) for (l, r, v) in zip(left, right, dp): ret = max(ret, v * (r - l - 1)) return ret
database_name = "Health_Service" user_name = "postgres" password = "zhangheng" port = "5432"
database_name = 'Health_Service' user_name = 'postgres' password = 'zhangheng' port = '5432'
#Exercise 3.2: Rewrite your pay program using try and except so # that yourprogram handles non-numeric input gracefully by # printing a messageand exiting the program. The following # shows two executions of the program: # Enter Hours: 20 # Enter Rate: nine # Error, please enter numeric input # Enter Hours: forty # Error, please enter numeric input hrs = input("Enter Hours: ") try: h = float(hrs) rph = input("Enter Rate: ") try: r = float(rph) if h <= 40: pay = h * r else: overhours = h - 40 norm_pay = 40 * r over_pay = overhours * r * 1.5 pay = norm_pay + over_pay print(pay) except: print("Error, please enter numeric input") except: print("Error, please enter numeric input")
hrs = input('Enter Hours: ') try: h = float(hrs) rph = input('Enter Rate: ') try: r = float(rph) if h <= 40: pay = h * r else: overhours = h - 40 norm_pay = 40 * r over_pay = overhours * r * 1.5 pay = norm_pay + over_pay print(pay) except: print('Error, please enter numeric input') except: print('Error, please enter numeric input')
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_instance_isolated.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # data = dict( # samples_per_gpu=1, # workers_per_gpu=2) # optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
_base_ = ['../_base_/models/mask_rcnn_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_instance_isolated.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
HASS_EVENT_RECEIVE = 'HASS_EVENT_RECEIVE' # hass.bus --> hauto.bus HASS_STATE_CHANGED = 'HASS_STATE_CHANGE' # aka hass.EVENT_STATE_CHANGED HASS_ENTITY_CREATE = 'HASS_ENTITY_CREATE' # hass entity is newly created HASS_ENTITY_CHANGE = 'HASS_ENTITY_CHANGE' # hass entity's state changes HASS_ENTITY_UPDATE = 'HASS_ENTITY_UPDATE' # hass entity's state is same, but attributes change HASS_ENTITY_REMOVE = 'HASS_ENTITY_REMOVE' # hass entity is removed
hass_event_receive = 'HASS_EVENT_RECEIVE' hass_state_changed = 'HASS_STATE_CHANGE' hass_entity_create = 'HASS_ENTITY_CREATE' hass_entity_change = 'HASS_ENTITY_CHANGE' hass_entity_update = 'HASS_ENTITY_UPDATE' hass_entity_remove = 'HASS_ENTITY_REMOVE'
N, L = map(int, input().split()) amida = [] for _ in range(L+1): tmp = list(input()) amida.append(tmp) idx = amida[L].index('o') for i in reversed(range(L)): if idx != N*2-2 and amida[i][idx+1] == '-': idx += 2 elif idx != 0 and amida[i][idx-1] == '-': idx -= 2 print(idx//2+1)
(n, l) = map(int, input().split()) amida = [] for _ in range(L + 1): tmp = list(input()) amida.append(tmp) idx = amida[L].index('o') for i in reversed(range(L)): if idx != N * 2 - 2 and amida[i][idx + 1] == '-': idx += 2 elif idx != 0 and amida[i][idx - 1] == '-': idx -= 2 print(idx // 2 + 1)
# LSM6DSO 3D accelerometer and 3D gyroscope seneor micropython drive # ver: 1.0 # License: MIT # Author: shaoziyang (shaoziyang@micropython.org.cn) # v1.0 2019.7 LSM6DSO_CTRL1_XL = const(0x10) LSM6DSO_CTRL2_G = const(0x11) LSM6DSO_CTRL3_C = const(0x12) LSM6DSO_CTRL6_C = const(0x15) LSM6DSO_CTRL8_XL = const(0x17) LSM6DSO_STATUS = const(0x1E) LSM6DSO_OUT_TEMP_L = const(0x20) LSM6DSO_OUTX_L_G = const(0x22) LSM6DSO_OUTY_L_G = const(0x24) LSM6DSO_OUTZ_L_G = const(0x26) LSM6DSO_OUTX_L_A = const(0x28) LSM6DSO_OUTY_L_A = const(0x2A) LSM6DSO_OUTZ_L_A = const(0x2C) LSM6DSO_SCALEA = ('2g', '16g', '4g', '8g') LSM6DSO_SCALEG = ('250', '125', '500', '', '1000', '', '2000') class LSM6DSO(): def __init__(self, i2c, addr = 0x6B): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [[0, 0, 0], [0, 0, 0]] self._power = True self._power_a = 0x10 self._power_g = 0x10 # ODR_XL=1 FS_XL=0 self.setreg(LSM6DSO_CTRL1_XL, 0x10) # ODR_G=1 FS_125=1 self.setreg(LSM6DSO_CTRL2_G, 0x12) # BDU=1 IF_INC=1 self.setreg(LSM6DSO_CTRL3_C, 0x44) self.setreg(LSM6DSO_CTRL8_XL, 0) # scale=2G self._scale_a = 0 self._scale_g = 0 self._scale_a_c = 1 self._scale_g_c = 1 self.scale_a('2g') self.scale_g('125') def int16(self, d): return d if d < 0x8000 else d - 0x10000 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg+1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = (self.rb[0] & mask) | dat self.setreg(reg, self.rb[0]) def ax_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_A)) def ay_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_A)) def az_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_A)) def gx_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_G)) def gy_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_G)) def gz_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_G)) def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * self._scale_a_c) def mdps(self, reg): return round(self.int16(self.get2reg(reg)) * 4.375 * self._scale_g_c) def ax(self): return self.mg(LSM6DSO_OUTX_L_A) def ay(self): return self.mg(LSM6DSO_OUTY_L_A) def az(self): return self.mg(LSM6DSO_OUTZ_L_A) def gx(self): return self.mdps(LSM6DSO_OUTX_L_G) def gy(self): return self.mdps(LSM6DSO_OUTY_L_G) def gz(self): return self.mdps(LSM6DSO_OUTZ_L_G) def get_a(self): self.irq_v[0][0] = self.ax() self.irq_v[0][1] = self.ay() self.irq_v[0][2] = self.az() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx() self.irq_v[1][1] = self.gy() self.irq_v[1][2] = self.gz() return self.irq_v[1] def get(self): self.get_a() self.get_g() return self.irq_v def get_a_raw(self): self.irq_v[0][0] = self.ax_raw() self.irq_v[0][1] = self.ay_raw() self.irq_v[0][2] = self.az_raw() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx_raw() self.irq_v[1][1] = self.gy_raw() self.irq_v[1][2] = self.gz_raw() return self.irq_v[1] def get(self): self.get_a_raw() self.get_g_raw() return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LSM6DSO_OUT_TEMP_L))/256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LSM6DSO_OUT_TEMP_L+1) if self.rb[0] & 0x80: self.rb[0] -= 256 return self.rb[0] + 25 def scale_a(self, dat=None): if dat is None: return LSM6DSO_SCALEA[self._scale_a] else: if type(dat) is str: if not dat in LSM6DSO_SCALEA: return self._scale_a = LSM6DSO_SCALEA.index(dat) self._scale_a_c = int(dat.rstrip('g'))//2 else: return self.r_w_reg(LSM6DSO_CTRL1_XL, self._scale_a<<2, 0xF3) def scale_g(self, dat=None): if (dat is None) or (dat == ''): return LSM6DSO_SCALEG[self._scale_g] else: if type(dat) is str: if not dat in LSM6DSO_SCALEG: return self._scale_g = LSM6DSO_SCALEG.index(dat) self._scale_g_c = int(dat)//125 else: return self.r_w_reg(LSM6DSO_CTRL2_G, self._scale_g<<1, 0xF1) def power(self, on=None): if on is None: return self._power else: self._power = on if on: self.r_w_reg(LSM6DSO_CTRL1_XL, self._power_a, 0x0F) self.r_w_reg(LSM6DSO_CTRL2_G, self._power_g, 0x0F) else: self._power_a = self.getreg(LSM6DSO_CTRL1_XL) & 0xF0 self._power_g = self.getreg(LSM6DSO_CTRL2_G) & 0xF0 self.r_w_reg(LSM6DSO_CTRL1_XL, 0, 0x0F) self.r_w_reg(LSM6DSO_CTRL2_G, 0, 0x0F)
lsm6_dso_ctrl1_xl = const(16) lsm6_dso_ctrl2_g = const(17) lsm6_dso_ctrl3_c = const(18) lsm6_dso_ctrl6_c = const(21) lsm6_dso_ctrl8_xl = const(23) lsm6_dso_status = const(30) lsm6_dso_out_temp_l = const(32) lsm6_dso_outx_l_g = const(34) lsm6_dso_outy_l_g = const(36) lsm6_dso_outz_l_g = const(38) lsm6_dso_outx_l_a = const(40) lsm6_dso_outy_l_a = const(42) lsm6_dso_outz_l_a = const(44) lsm6_dso_scalea = ('2g', '16g', '4g', '8g') lsm6_dso_scaleg = ('250', '125', '500', '', '1000', '', '2000') class Lsm6Dso: def __init__(self, i2c, addr=107): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [[0, 0, 0], [0, 0, 0]] self._power = True self._power_a = 16 self._power_g = 16 self.setreg(LSM6DSO_CTRL1_XL, 16) self.setreg(LSM6DSO_CTRL2_G, 18) self.setreg(LSM6DSO_CTRL3_C, 68) self.setreg(LSM6DSO_CTRL8_XL, 0) self._scale_a = 0 self._scale_g = 0 self._scale_a_c = 1 self._scale_g_c = 1 self.scale_a('2g') self.scale_g('125') def int16(self, d): return d if d < 32768 else d - 65536 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg + 1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = self.rb[0] & mask | dat self.setreg(reg, self.rb[0]) def ax_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_A)) def ay_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_A)) def az_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_A)) def gx_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_G)) def gy_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_G)) def gz_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_G)) def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * self._scale_a_c) def mdps(self, reg): return round(self.int16(self.get2reg(reg)) * 4.375 * self._scale_g_c) def ax(self): return self.mg(LSM6DSO_OUTX_L_A) def ay(self): return self.mg(LSM6DSO_OUTY_L_A) def az(self): return self.mg(LSM6DSO_OUTZ_L_A) def gx(self): return self.mdps(LSM6DSO_OUTX_L_G) def gy(self): return self.mdps(LSM6DSO_OUTY_L_G) def gz(self): return self.mdps(LSM6DSO_OUTZ_L_G) def get_a(self): self.irq_v[0][0] = self.ax() self.irq_v[0][1] = self.ay() self.irq_v[0][2] = self.az() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx() self.irq_v[1][1] = self.gy() self.irq_v[1][2] = self.gz() return self.irq_v[1] def get(self): self.get_a() self.get_g() return self.irq_v def get_a_raw(self): self.irq_v[0][0] = self.ax_raw() self.irq_v[0][1] = self.ay_raw() self.irq_v[0][2] = self.az_raw() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx_raw() self.irq_v[1][1] = self.gy_raw() self.irq_v[1][2] = self.gz_raw() return self.irq_v[1] def get(self): self.get_a_raw() self.get_g_raw() return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LSM6DSO_OUT_TEMP_L)) / 256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LSM6DSO_OUT_TEMP_L + 1) if self.rb[0] & 128: self.rb[0] -= 256 return self.rb[0] + 25 def scale_a(self, dat=None): if dat is None: return LSM6DSO_SCALEA[self._scale_a] else: if type(dat) is str: if not dat in LSM6DSO_SCALEA: return self._scale_a = LSM6DSO_SCALEA.index(dat) self._scale_a_c = int(dat.rstrip('g')) // 2 else: return self.r_w_reg(LSM6DSO_CTRL1_XL, self._scale_a << 2, 243) def scale_g(self, dat=None): if dat is None or dat == '': return LSM6DSO_SCALEG[self._scale_g] else: if type(dat) is str: if not dat in LSM6DSO_SCALEG: return self._scale_g = LSM6DSO_SCALEG.index(dat) self._scale_g_c = int(dat) // 125 else: return self.r_w_reg(LSM6DSO_CTRL2_G, self._scale_g << 1, 241) def power(self, on=None): if on is None: return self._power else: self._power = on if on: self.r_w_reg(LSM6DSO_CTRL1_XL, self._power_a, 15) self.r_w_reg(LSM6DSO_CTRL2_G, self._power_g, 15) else: self._power_a = self.getreg(LSM6DSO_CTRL1_XL) & 240 self._power_g = self.getreg(LSM6DSO_CTRL2_G) & 240 self.r_w_reg(LSM6DSO_CTRL1_XL, 0, 15) self.r_w_reg(LSM6DSO_CTRL2_G, 0, 15)
class Solution: def findPeakElement(self, nums: List[int]) -> int: l=0 r=len(nums)-1 while l<r: mid=l+(r-l)//2 if nums[mid]<nums[mid+1]: l=mid+1 else: r=mid return l
class Solution: def find_peak_element(self, nums: List[int]) -> int: l = 0 r = len(nums) - 1 while l < r: mid = l + (r - l) // 2 if nums[mid] < nums[mid + 1]: l = mid + 1 else: r = mid return l
# Refers to `_RAND_INCREASING_TRANSFORMS` in pytorch-image-models rand_increasing_policies = [ dict(type='AutoContrast'), dict(type='Equalize'), dict(type='Invert'), dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)), dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)), dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)), dict(type='SolarizeAdd', magnitude_key='magnitude', magnitude_range=(0, 110)), dict(type='ColorTransform', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Contrast', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Brightness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Sharpness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='horizontal'), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='vertical'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='horizontal'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='vertical') ]
rand_increasing_policies = [dict(type='AutoContrast'), dict(type='Equalize'), dict(type='Invert'), dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)), dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)), dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)), dict(type='SolarizeAdd', magnitude_key='magnitude', magnitude_range=(0, 110)), dict(type='ColorTransform', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Contrast', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Brightness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Sharpness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='horizontal'), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='vertical'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='horizontal'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='vertical')]
def tickets(people): twenty_fives = 0 fifties = 0 for p in people: if p == 25: twenty_fives += 1 if p == 50: if twenty_fives == 0: return 'NO' twenty_fives -= 1 fifties += 1 if p == 100: if fifties >= 1 and twenty_fives >= 1: twenty_fives -= 1 fifties -= 1 elif twenty_fives >= 3: twenty_fives -= 3 else: return 'NO' return 'YES'
def tickets(people): twenty_fives = 0 fifties = 0 for p in people: if p == 25: twenty_fives += 1 if p == 50: if twenty_fives == 0: return 'NO' twenty_fives -= 1 fifties += 1 if p == 100: if fifties >= 1 and twenty_fives >= 1: twenty_fives -= 1 fifties -= 1 elif twenty_fives >= 3: twenty_fives -= 3 else: return 'NO' return 'YES'
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ # Disable DYNAMICBASE for these tests because it implies/doesn't imply # FIXED in certain cases so it complicates the test for FIXED. { 'target_name': 'test_fixed_default_exe', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_default_dll', 'type': 'shared_library', 'msvs_settings': { 'VCLinkerTool': { 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_no', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'FixedBaseAddress': '1', 'RandomizedBaseAddress': '1', } }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_yes', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'FixedBaseAddress': '2', 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, ] }
{'targets': [{'target_name': 'test_fixed_default_exe', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_default_dll', 'type': 'shared_library', 'msvs_settings': {'VCLinkerTool': {'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_no', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'FixedBaseAddress': '1', 'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}, {'target_name': 'test_fixed_yes', 'type': 'executable', 'msvs_settings': {'VCLinkerTool': {'FixedBaseAddress': '2', 'RandomizedBaseAddress': '1'}}, 'sources': ['hello.cc']}]}
# Python program to Find Numbers divisible by Another number def main(): x=int(input("Enter the number")) y=int(input("Enter the limit value")) print("The Numbers divisible by",x,"is") for i in range(1,y+1): if i%x==0: print(i) if __name__=='__main__': main()
def main(): x = int(input('Enter the number')) y = int(input('Enter the limit value')) print('The Numbers divisible by', x, 'is') for i in range(1, y + 1): if i % x == 0: print(i) if __name__ == '__main__': main()
class multi(): def insert(self,num): for i in range(1, 11): print(num, "X", i, "=", num * i) d=multi() d.insert(num=int(input('Enter the number')))
class Multi: def insert(self, num): for i in range(1, 11): print(num, 'X', i, '=', num * i) d = multi() d.insert(num=int(input('Enter the number')))