content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python """ https://leetcode.com/problems/plus-one/description/ Created on 2018-11-14 @author: 'Jiezhi.G@gmail.com' Reference: """ class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ l = len(digits) - 1 while...
""" https://leetcode.com/problems/plus-one/description/ Created on 2018-11-14 @author: 'Jiezhi.G@gmail.com' Reference: """ class Solution: def plus_one(self, digits): """ :type digits: List[int] :rtype: List[int] """ l = len(digits) - 1 while l >= 0 and digits[l]...
key = {'f':'l', 'd': 'l','j':'r', 'k':'r'} words = {} for _ in range(int(input())): n = int(input()) for _ in range(n): s = input() if words.get(s): words[s] += 1 else : words[s] = 1 # print(words) final_ans = 0 for i in words: c_word_ans = 0.2 pre = key[i[0]] for j in i[1::]: if(key[j] == pre):c_wo...
key = {'f': 'l', 'd': 'l', 'j': 'r', 'k': 'r'} words = {} for _ in range(int(input())): n = int(input()) for _ in range(n): s = input() if words.get(s): words[s] += 1 else: words[s] = 1 final_ans = 0 for i in words: c_word_ans = 0.2 pre = k...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. class PotentialEdgeColumnPair: def __init__(self, source, destination, score): self._source = source self._destination = destination self._score = score def source(self): return self._source def dest...
class Potentialedgecolumnpair: def __init__(self, source, destination, score): self._source = source self._destination = destination self._score = score def source(self): return self._source def destination(self): return self._destination def score(self): ...
class ModelOutput: # Class that defines model output structure def __init__(self, arg_type, arg_size, is_spacial): self.arg_type = arg_type self.arg_size = arg_size self.is_spacial = is_spacial
class Modeloutput: def __init__(self, arg_type, arg_size, is_spacial): self.arg_type = arg_type self.arg_size = arg_size self.is_spacial = is_spacial
class DateGetter: '''Parse a date using the datetime format string defined in the current jxn's config. ''' def _get_date(self, label_text): fmt = self.get_config_value('datetime_format') text = self.get_field_text(label_text) if text is not None: dt = datetime.strpti...
class Dategetter: """Parse a date using the datetime format string defined in the current jxn's config. """ def _get_date(self, label_text): fmt = self.get_config_value('datetime_format') text = self.get_field_text(label_text) if text is not None: dt = datetime.strpt...
n = int(input()) alph = ["A",'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','Q','X','Y','Z'] boxes = [] for x in range(n): box = [] length = int(input()) for y in range(length): box.append([]) for i in range(length): box[y].append("...
n = int(input()) alph = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'Q', 'X', 'Y', 'Z'] boxes = [] for x in range(n): box = [] length = int(input()) for y in range(length): box.append([]) for i in range(length): b...
PROCESS_CREATE = 0 PROCESS_EDIT = 1 PROCESS_VIEW = 2 PROCESS_DELETE = 3 PROCESS_EDIT_DELETE = 4 # Edit with delete button PROCESS_VIEW_EDIT = 5 # View with edit button PERMISSION_DISABLE = 2 PERMISSION_ON = 1 PERMISSION_OFF = 0 PERMISSION_AUTHENTICATED = 3 PERMISSION_STAFF = 4 PERMISSION_METHOD = 5 class P...
process_create = 0 process_edit = 1 process_view = 2 process_delete = 3 process_edit_delete = 4 process_view_edit = 5 permission_disable = 2 permission_on = 1 permission_off = 0 permission_authenticated = 3 permission_staff = 4 permission_method = 5 class Processsetup: def __init__(self, modal_title, django_permi...
# Copyright (c) 2020 Greg Dubicki # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # # See the License for the specific language governing permissions and # limitations under the License. # # MIT License # # Copyright (c) 2018 Shane ...
class Cachenode(object): def __init__(self, key, value, freq_node, pre, nxt): self.key = key self.value = value self.freq_node = freq_node self.pre = pre self.nxt = nxt def free_myself(self): if self.freq_node.cache_head == self.freq_node.cache_tail: ...
def solution(clothes): answer = {} for i in clothes: if i[1] in answer: answer[i[1]]+=1 else: answer[i[1]] = 1 cnt = 1 for i in answer.values(): cnt *= (i+1) return cnt - 1
def solution(clothes): answer = {} for i in clothes: if i[1] in answer: answer[i[1]] += 1 else: answer[i[1]] = 1 cnt = 1 for i in answer.values(): cnt *= i + 1 return cnt - 1
# Request Link and Long Polling Use TELEGRAM_TOKEN = '' WEBHOOK_URL = '' TELEGRAM_BASE = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}' TELEGRAM_WEBHOOK_URL = TELEGRAM_BASE + f'/setWebhook?url={WEBHOOK_URL}/hook' FUGLE_API_TOKEN = '' # Other Chatbot Token EXAMPLE_TOKEN = '' # WEBHOOK_URL = ''
telegram_token = '' webhook_url = '' telegram_base = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}' telegram_webhook_url = TELEGRAM_BASE + f'/setWebhook?url={WEBHOOK_URL}/hook' fugle_api_token = '' example_token = ''
# Speed Fine Problem # input limit = int(input('Enter the speed limit: ')) speed = int(input('Enter the recorded speed of the car: ')) # processing & output if speed <= limit: print('Congratulations, you are within the speed limit!') else: difference = speed - limit if difference > 30: print('You ...
limit = int(input('Enter the speed limit: ')) speed = int(input('Enter the recorded speed of the car: ')) if speed <= limit: print('Congratulations, you are within the speed limit!') else: difference = speed - limit if difference > 30: print('You are speeding and your fine is $500.') elif differ...
# coding=utf-8 """ Data Integration """ __author__ = 'Seray Beser' __copyright__ = 'Copyright 2018 Seray Beser' __license__ = 'Apache License 2.0' __version__ = '0.0.1' __email__ = 'seraybeserr@gmail.com' __status__ = 'Development' class DataIntegration(object): """ Data Integration """ def __init__...
""" Data Integration """ __author__ = 'Seray Beser' __copyright__ = 'Copyright 2018 Seray Beser' __license__ = 'Apache License 2.0' __version__ = '0.0.1' __email__ = 'seraybeserr@gmail.com' __status__ = 'Development' class Dataintegration(object): """ Data Integration """ def __init__(self, data): ...
# # PySNMP MIB module DEVICE (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DEVICE # Produced by pysmi-0.3.4 at Mon Apr 29 18:26: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) ...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ...
# Question # 17. Write a menu driven program to find the area of circle, square, rectangle & triangle. # Code types = ["circle", "square", "rectangle", "triangle"] print("-"*15) # 15 is length of Area Calculator. not intentional though it was a random rumber print("Area Calculator") print("-"*15) print() print("Plea...
types = ['circle', 'square', 'rectangle', 'triangle'] print('-' * 15) print('Area Calculator') print('-' * 15) print() print('Please enter the following numbers according to the shape you want to calculate the area of.') print() for (i, type) in enumerate(types): print(i, ':', types[i]) print() shape = int(input())...
""".""" # import time # import logging class SCPI(object): """SCPI helper functions.""" @property def SCPI_OPT(self): return self.query(':SYSTem:OPTions?').strip('"').split(',') @property def SystemErrorQueue(self): """Get System Error Queue. :returns: List of e...
""".""" class Scpi(object): """SCPI helper functions.""" @property def scpi_opt(self): return self.query(':SYSTem:OPTions?').strip('"').split(',') @property def system_error_queue(self): """Get System Error Queue. :returns: List of errors """ responces = [...
####################### # Login configuration # ####################### weblab_db_username = 'weblab' weblab_db_password = 'weblab' ######################################## # User Processing Server configuration # ######################################## core_session_type = 'Memory' core_coordinator_db_username = '...
weblab_db_username = 'weblab' weblab_db_password = 'weblab' core_session_type = 'Memory' core_coordinator_db_username = 'weblab' core_coordinator_db_password = 'weblab' core_coordinator_laboratory_servers = {'laboratory:lab_and_experiment1@main_machine': {'exp1|ud-dummy|Dummy experiments': 'dummy1@ud-dummy', 'exp2|ud-d...
# DomirScire def get_final_line(filename): final_line = '' for current_line in open(filename): final_line = current_line return final_line if __name__ == "__main__": print(get_final_line('./'))
def get_final_line(filename): final_line = '' for current_line in open(filename): final_line = current_line return final_line if __name__ == '__main__': print(get_final_line('./'))
class MockArgs(object): """Mock for command line args.""" def __init__(self, **kwargs): self.doctype = kwargs.get('doctype') self.output = kwargs.get('output') self.path = kwargs.get('path') class NameOptions(object): """Mock of configurable names.""" def __init__(self): ...
class Mockargs(object): """Mock for command line args.""" def __init__(self, **kwargs): self.doctype = kwargs.get('doctype') self.output = kwargs.get('output') self.path = kwargs.get('path') class Nameoptions(object): """Mock of configurable names.""" def __init__(self): ...
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return None redcount=0 whilecount=0 bluecount=0 for num in nu...
class Solution(object): def sort_colors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if not nums: return None redcount = 0 whilecount = 0 bluecount = 0 for num in num...
class Solution: def makeString(self, s: str) -> str: result = [] for c in s: if c != '#': result.append(c) elif len(result) > 0: result.pop() return str(result) def backspaceCompare(self, s: str, t: str) -> bool: return sel...
class Solution: def make_string(self, s: str) -> str: result = [] for c in s: if c != '#': result.append(c) elif len(result) > 0: result.pop() return str(result) def backspace_compare(self, s: str, t: str) -> bool: return ...
# Get frequencies of attributes def get_frequencies(plant_dict): frequencies = {} # First keep count of how many times an attribute appears count = 0 # Keep track of the number of plants for plant in plant_dict: plant_attributes = set() # Don't count duplicate attributes (such as a flower having...
def get_frequencies(plant_dict): frequencies = {} count = 0 for plant in plant_dict: plant_attributes = set() plant_tuples = plant_dict[plant] for tup in plant_tuples: attribute = tup[0] if attribute in plant_attributes: continue if...
squares = [] for value in range(1,11): squares.append(value **2) print(squares) digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) squares = [value**2 for value in range(1,11)] print(squares) odd_numbers = list(range(1,20,1)) print(odd_numbers) cars = ['audi', 'bmw...
squares = [] for value in range(1, 11): squares.append(value ** 2) print(squares) digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) squares = [value ** 2 for value in range(1, 11)] print(squares) odd_numbers = list(range(1, 20, 1)) print(odd_numbers) cars = ['audi', 'b...
# Stub only, D support was broken with Python2.6 and unnecessary to Nuitka def generate(env): return def exists(env): return False
def generate(env): return def exists(env): return False
class Base: def __init__(self, x=0): self.x = x class Slave(Base): def __init__(self, x): super(Slave, self).__init__() self.x = x s1 = Slave(x=2) print(s1.x)
class Base: def __init__(self, x=0): self.x = x class Slave(Base): def __init__(self, x): super(Slave, self).__init__() self.x = x s1 = slave(x=2) print(s1.x)
def strStr(haystack: str, needle: str) -> int: i = 0 j = 0 len1 = len(haystack) len2 = len(needle) while i < len1 and j < len2: if haystack[i] == needle[j]: i += 1 j += 1 else: i = i - (j - 1) j = 0 if j == len2: return i-j else: return -1 print(strStr("abcdeabc", "bcd"))
def str_str(haystack: str, needle: str) -> int: i = 0 j = 0 len1 = len(haystack) len2 = len(needle) while i < len1 and j < len2: if haystack[i] == needle[j]: i += 1 j += 1 else: i = i - (j - 1) j = 0 if j == len2: return i -...
#!/usr/bin/env python3 # coding:utf-8 def getCommonDivisor(m, d): while d: m, d = d, m%d return m def calc(m, d): if d == 0: return "X -- ZeroDivisionError" elif m == 0: return '0' elif m == d: return '1' com_div = getCommonDivisor(m, d) return str(m//com...
def get_common_divisor(m, d): while d: (m, d) = (d, m % d) return m def calc(m, d): if d == 0: return 'X -- ZeroDivisionError' elif m == 0: return '0' elif m == d: return '1' com_div = get_common_divisor(m, d) return str(m // com_div) + '/' + str(d // com_div...
''' Program to count number of trees in a forest. Approach: The idea is to apply Depth First Search on every node. If every connected node is visited from one source then increment count by one. If some nodes yet not visited again perform DFS traversal. Return the count. Example: Input : edges[] = {0, 1}, {0, ...
""" Program to count number of trees in a forest. Approach: The idea is to apply Depth First Search on every node. If every connected node is visited from one source then increment count by one. If some nodes yet not visited again perform DFS traversal. Return the count. Example: Input : edges[] = {0, 1}, {0, ...
def reverseInput(word): # str[start:stop:step] return word[::-1] def reverseInput2(word): new_word = "" for char in word: new_word = char + new_word return new_word if __name__ == "__main__": word = input("Enter the word: ") print(reverseInput(word)) print(reverseInput2(word)...
def reverse_input(word): return word[::-1] def reverse_input2(word): new_word = '' for char in word: new_word = char + new_word return new_word if __name__ == '__main__': word = input('Enter the word: ') print(reverse_input(word)) print(reverse_input2(word))
''' In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you can pick up and pass through; -1 means the cell contains a thorn that blocks your way. Your task is to collect maximu...
""" In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 means the cell is empty, so you can pass through; 1 means the cell contains a cherry, that you can pick up and pass through; -1 means the cell contains a thorn that blocks your way. Your task is to collect maximu...
EXAMPLE = '''\ |+1|-1|+2|-2|+3|-3|+sg|+pl|-sg|-pl| 1sg| X| | | X| | X| X| | | X| 1pl| X| | | X| | X| | X| X| | 2sg| | X| X| | | X| X| | | X| 2pl| | X| X| | | X| | X| X| | 3sg| | X| | X| X| | X| | | X| 3pl| | X| | X| X| | | X| X| | '''
example = ' |+1|-1|+2|-2|+3|-3|+sg|+pl|-sg|-pl|\n1sg| X| | | X| | X| X| | | X|\n1pl| X| | | X| | X| | X| X| |\n2sg| | X| X| | | X| X| | | X|\n2pl| | X| X| | | X| | X| X| |\n3sg| | X| | X| X| | X| | | X|\n3pl| | X| | X| X| | | X| X| |\n'
class Solution: def intToRoman(self, num): """ :type num: int :rtype: str """ roman = 'MDCLXVI' romandiv = [1000, 500, 100, 50, 10, 5, 1] ans = '' strnum = str(num) i = 6 - (len(strnum) - 1) * 2 for c in strnum: if c == ...
class Solution: def int_to_roman(self, num): """ :type num: int :rtype: str """ roman = 'MDCLXVI' romandiv = [1000, 500, 100, 50, 10, 5, 1] ans = '' strnum = str(num) i = 6 - (len(strnum) - 1) * 2 for c in strnum: if c == '...
def is_valid_row_col(next_r, next_c): if 0 <= next_r < 8 and 0 <= next_c < 8: return True return False matrix = [] queens = [] for _ in range(8): data = input().split(" ") matrix.append(data) row_king = int col_king = int for row in range(8): for column in range(8): if matrix[ro...
def is_valid_row_col(next_r, next_c): if 0 <= next_r < 8 and 0 <= next_c < 8: return True return False matrix = [] queens = [] for _ in range(8): data = input().split(' ') matrix.append(data) row_king = int col_king = int for row in range(8): for column in range(8): if matrix[row][co...
# O(n) time and O(log n) space def max_path_sum(tree): _, max_path_sum = max_path_sum_helper(tree) return max_path_sum def max_path_sum_helper(tree): if not tree: # Base case of not a node return (0, 0) # Depth first bottom up approach to calculate the max path sum left_branch_sum,...
def max_path_sum(tree): (_, max_path_sum) = max_path_sum_helper(tree) return max_path_sum def max_path_sum_helper(tree): if not tree: return (0, 0) (left_branch_sum, left_triangle_sum) = max_path_sum_helper(tree.left) (right_branch_sum, right_triangle_sum) = max_path_sum_helper(tree.right) ...
""" Mouse Press. Saves one PDF of the contents of the display window each time the mouse is pressed. """ add_library('pdf') saveOneFrame = False def setup(): size(600, 600) frameRate(24) def draw(): global saveOneFrame if saveOneFrame: beginRecord(PDF, "Line.pdf") background(255) ...
""" Mouse Press. Saves one PDF of the contents of the display window each time the mouse is pressed. """ add_library('pdf') save_one_frame = False def setup(): size(600, 600) frame_rate(24) def draw(): global saveOneFrame if saveOneFrame: begin_record(PDF, 'Line.pdf') background(255) ...
# # PySNMP MIB module SW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:36:37 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, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) ...
text = '''aaaaaa aaaaaa aaaa aaaa a aa aa a aa0 bbbbbb bbbbbb bbbbbbbbbb.ccc ccccc c0 dddd ddddd ddddd.eeeee eeeeeee.fffff0 fffff fff ffffff.ggg ggg gg g.eeefaa0.''' lines = list(text.split('\n')) words = list(text.split(' ')) sentenses = list(text.split('.')) print(len(lines), lines, '\n') print(len(words), words, '...
text = 'aaaaaa aaaaaa aaaa aaaa a aa aa a aa0\nbbbbbb bbbbbb bbbbbbbbbb.ccc ccccc c0\ndddd ddddd ddddd.eeeee eeeeeee.fffff0\nfffff fff ffffff.ggg ggg gg g.eeefaa0.' lines = list(text.split('\n')) words = list(text.split(' ')) sentenses = list(text.split('.')) print(len(lines), lines, '\n') print(len(words), words, '\n'...
class BinaryTree: def __init__(self, rootValue): self.value = rootValue self.left = None self.right = None def addLeftChild(self, val): newNode = BinaryTree(val) self.left = newNode def addRightChild(self, val): newNode = BinaryTree(val) self.right...
class Binarytree: def __init__(self, rootValue): self.value = rootValue self.left = None self.right = None def add_left_child(self, val): new_node = binary_tree(val) self.left = newNode def add_right_child(self, val): new_node = binary_tree(val) sel...
#!/usr/bin/env python """Args, Kwargs""" __author__ = "Petar Stoyanov" def main(*args, **kwargs): """Docstring""" for arg in args: print(arg) for (key, value) in kwargs.items(): print("{} - {}".format(key, value)) if __name__ == '__main__': main(1, 2, 3, name='pesho', age=30)
"""Args, Kwargs""" __author__ = 'Petar Stoyanov' def main(*args, **kwargs): """Docstring""" for arg in args: print(arg) for (key, value) in kwargs.items(): print('{} - {}'.format(key, value)) if __name__ == '__main__': main(1, 2, 3, name='pesho', age=30)
#a = 3 #b = 4 #c = a ** b #print (c) #x = 5 #print(x) #x = 5 #x += 3 # #print(x) #x = 5 #x -= 3 # #print(x) #x = 5 #x *= 3 #print(x) #x = 5 #x /= 3 #print(x) #x = 5 #x%=3 #print(x) # comparisin opperraters #x = 5 #y = 3 # #print(x == y) # # returns False because 5 is not equal to 3 #x = 5 #y = 3 ...
x = 5 y = 3 print(x <= y)
fruit = ["apple", "banana", "peach"] fruit # outputs # >>> ['apple', 'banana', 'peach']
fruit = ['apple', 'banana', 'peach'] fruit
#!/usr/bin/env python #--- Day 6: Universal Orbit Map --- #You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often involves transferring between orbits, the orbit maps here are useful for finding efficient routes between, for example, you and Santa. You download a map of the loc...
puzzle_input = [] with open('day06.txt', 'r') as file: for entry in file.readlines(): puzzle_input.append(entry.rstrip().split(')')) orbit_dict = {key: value for (value, key) in puzzle_input} calc_orbits = 0 for obj in orbit_dict.keys(): obj_tmp = obj while obj_tmp in orbit_dict: calc_orbits...
""" Classes which create external representations of core objects. This allows the core objects to remain decoupled from the API and clients. These classes act as an adapter between the data format api clients expect, and the internal data of an object. """
""" Classes which create external representations of core objects. This allows the core objects to remain decoupled from the API and clients. These classes act as an adapter between the data format api clients expect, and the internal data of an object. """
def print_name(prefix): print("searchingname with" + prefix) try: while True: name = (yield) if prefix in name: print(name) except GeneratorExit as identifier: print("Coroutine Exited") corou = print_name("Dear") corou.__next__() corou.send("Atul")...
def print_name(prefix): print('searchingname with' + prefix) try: while True: name = (yield) if prefix in name: print(name) except GeneratorExit as identifier: print('Coroutine Exited') corou = print_name('Dear') corou.__next__() corou.send('Atul') cor...
n = int(input()) s = [1 if element == 'U' else -1 for element in input()] counter = 0 status = 0 step = 0 while step < n: if status == 0 and s[step] == -1: status = 1 start_pt = step step += 1 sum_val = -1 while step < n and status != 0: sum_val += s[step] if sum_val == 0: counter += 1 ...
n = int(input()) s = [1 if element == 'U' else -1 for element in input()] counter = 0 status = 0 step = 0 while step < n: if status == 0 and s[step] == -1: status = 1 start_pt = step step += 1 sum_val = -1 while step < n and status != 0: sum_val += s[step] ...
''' Author: tusikalanse Date: 2021-07-10 18:07:33 LastEditTime: 2021-07-10 18:10:07 LastEditors: tusikalanse Description: ''' cnt = 0 def gao(i: int) -> int: for _ in range(50): i = i + int(str(i)[::-1]) if str(i) == str(i)[::-1]: return 0 return 1 for i in range(10000): cnt ...
""" Author: tusikalanse Date: 2021-07-10 18:07:33 LastEditTime: 2021-07-10 18:10:07 LastEditors: tusikalanse Description: """ cnt = 0 def gao(i: int) -> int: for _ in range(50): i = i + int(str(i)[::-1]) if str(i) == str(i)[::-1]: return 0 return 1 for i in range(10000): cnt +=...
# To demonstrate, we insert the number 8 to specify the available space for the value. # Use "=" to place the plus/minus sign at the left most position: txt = "The temperature is {:=8} degrees celsius." print(txt.format(-5))
txt = 'The temperature is {:=8} degrees celsius.' print(txt.format(-5))
# Given a sentence, reverse each word in the sentence while keeping the order the same! # Code def word_flipper(our_string): """ Flip the individual words in a sentence Args: our_string(string): String with words to flip Returns: string: String with words flipped """ split...
def word_flipper(our_string): """ Flip the individual words in a sentence Args: our_string(string): String with words to flip Returns: string: String with words flipped """ split = our_string.split(' ') retval = [] for s in split: retval.append(s[::-1]) retvals...
""" sort and two pointers (twosum2) """ class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] nums.sort() for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: ...
""" sort and two pointers (twosum2) """ class Solution(object): def three_sum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] nums.sort() for i in range(len(nums)): if i > 0 and nums[i] == nums[i - 1]: ...
''' Flask config. ''' display = {} CREDS_PATH = "app/creds.txt" TEMPLATES_AUTO_RELOAD = True
""" Flask config. """ display = {} creds_path = 'app/creds.txt' templates_auto_reload = True
# equation constants # gas diffusivity CONST_EQ_GAS_DIFFUSIVITY = { "Chapman-Enskog": 1, "Wilke-Lee": 2 } # gas viscosity CONST_EQ_GAS_VISCOSITY = { "eq1": 1, "eq2": 2 } # sherwood number CONST_EQ_Sh = { "Frossling": 1, "Rosner": 2, "Garner-and-Keey": 3 } # thermal conductivity CONST_EQ_...
const_eq_gas_diffusivity = {'Chapman-Enskog': 1, 'Wilke-Lee': 2} const_eq_gas_viscosity = {'eq1': 1, 'eq2': 2} const_eq__sh = {'Frossling': 1, 'Rosner': 2, 'Garner-and-Keey': 3} const_eq_gas_thermal_conductivity = {'eq1': 1, 'eq2': 2}
#shape of rectangle: def for_rectangle(): """printing shape of'rectangle' using for loop""" for row in range(5): for col in range(11): if row in(0,4) or col in(0,10): print("*",end=" ") else: print(" ",end=" ") print() ...
def for_rectangle(): """printing shape of'rectangle' using for loop""" for row in range(5): for col in range(11): if row in (0, 4) or col in (0, 10): print('*', end=' ') else: print(' ', end=' ') print() def while_rectangle(): """prin...
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] list = [] num = int(input('check wich number is smaller than : ')) for x in a: if x < num: list.append(x) # print(x) print(list)
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] list = [] num = int(input('check wich number is smaller than : ')) for x in a: if x < num: list.append(x) print(list)
# Write a function named combine_sort that has two parameters named lst1 and lst2. # The function should combine these two lists into one new list and sort the result. Return the new sorted list. #print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])) def combine_sort(lst1, lst2): new_lst = lst1 + lst2 return sor...
def combine_sort(lst1, lst2): new_lst = lst1 + lst2 return sorted(new_lst) print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))
input_line_number = 0 lines = [] def input(): global input_line_number input_line_number += 1 return lines[input_line_number - 1] def solution(): # Solution starts here number_of_lines = int(input()) for i in range(0, number_of_lines): full_name = input() # Find the location ...
input_line_number = 0 lines = [] def input(): global input_line_number input_line_number += 1 return lines[input_line_number - 1] def solution(): number_of_lines = int(input()) for i in range(0, number_of_lines): full_name = input() space_index = full_name.index(' ') first_...
# 104. Maximum Depth of Binary Tree """ Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, v...
""" Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. """ class Solution: def max_depth(self, root: Optional[TreeNode]) -> int: def helper(value): i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 26 20:46:03 2018 @author: daniel cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: ...
""" Created on Wed Sep 26 20:46:03 2018 @author: daniel cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return...
# Allows for easier debugging and unit testing. For example in dev mode functions don't expect a Flask request input. DEV_MODE = False KEYFILE = 'keyfile.json'
dev_mode = False keyfile = 'keyfile.json'
class BrokenLinkWarning(UserWarning): """ Raised when a group has a key with a None value. """ pass
class Brokenlinkwarning(UserWarning): """ Raised when a group has a key with a None value. """ pass
elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] l=len(elements) i=0 sum_even=0 sum_odd=0 average_even=0 average_odd=0 while i<l: if elements[i]%2==0: sum_even=sum_even+elements[i] average_even+=1 else: sum_odd=sum_odd+elements[i] average_odd+=1 i+=1 print(sum_even//ave...
elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] l = len(elements) i = 0 sum_even = 0 sum_odd = 0 average_even = 0 average_odd = 0 while i < l: if elements[i] % 2 == 0: sum_even = sum_even + elements[i] average_even += 1 else: sum_odd = sum_odd + elements[i] average_odd += ...
""" Session related utilities """ def session(self): """ Simple function that will be bound to the current request object to make the session retrievable inside a handler """ # Returns a session using the default cookie key. return self.session_store.get_session()
""" Session related utilities """ def session(self): """ Simple function that will be bound to the current request object to make the session retrievable inside a handler """ return self.session_store.get_session()
# for local # It's probably helpful for us to demonstrate what the URL should be, etc. SECRET_KEY = b'keycloak' # http, not https for some reason SERVER_URL = "http://keycloak-idp:8080/auth/" ADMIN_USERNAME = "admin" ADMIN_PASS = "admin" REALM_NAME = "master" # created in keycloak per https://github.com/keycloak/keyc...
secret_key = b'keycloak' server_url = 'http://keycloak-idp:8080/auth/' admin_username = 'admin' admin_pass = 'admin' realm_name = 'master' client_id = 'keycloak-flask' client_secret = '2da4a9a4-f6f0-48d9-82f6-12012402f03a' ingress_host = 'http://www.google.com/'
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(iname): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {iname}') # Pres...
def print_hi(iname): print(f'Hi, {iname}') print_hi('hi pycharm') def days_to_hour(num_of_days): calc_to_units = 24 name_of_units = 'hours' return f'{num_of_days} days to {name_of_units} are {num_of_days * calc_to_units} {name_of_units}' def validate_user_input(): try: user_input_days = in...
"""Consts for the integration.""" DOMAIN = "sleep_as_android" DEVICE_MACRO: str = "%%%device%%%" DEFAULT_NAME = "SleepAsAndroid" DEFAULT_TOPIC_TEMPLATE = "SleepAsAndroid/%s" % DEVICE_MACRO DEFAULT_QOS = 0 DEFAULT_ALARM_LABEL = "" CONF_ALARMS = "alarms" CONF_ALARM_TIME_FMT = "%H:%M" CONF_ALARM_DATE_FMT = "%Y-%m-%d" C...
"""Consts for the integration.""" domain = 'sleep_as_android' device_macro: str = '%%%device%%%' default_name = 'SleepAsAndroid' default_topic_template = 'SleepAsAndroid/%s' % DEVICE_MACRO default_qos = 0 default_alarm_label = '' conf_alarms = 'alarms' conf_alarm_time_fmt = '%H:%M' conf_alarm_date_fmt = '%Y-%m-%d' conf...
pi=22/7 r=float(input("enter radius of circle")) Area=pi*r*r print("Area of circle:%f",Area)
pi = 22 / 7 r = float(input('enter radius of circle')) area = pi * r * r print('Area of circle:%f', Area)
def upload(task_id, file_id, remote_path): global responses remote_path = remote_path.replace("\\", "") upload = { 'action': "upload", 'file_id': file_id, 'chunk_size': 512000, 'chunk_num': 1, 'full_path': "", 'task_id': task_id, } res = send(upload,...
def upload(task_id, file_id, remote_path): global responses remote_path = remote_path.replace('\\', '') upload = {'action': 'upload', 'file_id': file_id, 'chunk_size': 512000, 'chunk_num': 1, 'full_path': '', 'task_id': task_id} res = send(upload, agent.get_UUID()) res = res['chunk_data'] respon...
#!/usr/bin/env python def constructCDS(features, coordinates): exonCoordinates = [coordinates[featureIndex] for featureIndex in range(len(features)) if features[featureIndex][1] == "e"] cdsMap = {} cdsStart = 1 for exonCoord in exonCoordinates: exonStart, exonEnd = exonCoord cdsEnd = c...
def construct_cds(features, coordinates): exon_coordinates = [coordinates[featureIndex] for feature_index in range(len(features)) if features[featureIndex][1] == 'e'] cds_map = {} cds_start = 1 for exon_coord in exonCoordinates: (exon_start, exon_end) = exonCoord cds_end = cdsStart + (ex...
class CodeParser(): #Parsing variables SPEED = 0 ANGLE = 0 lineNum = 0 #Parsing libraries (or "keywords") PORTS = ["THROTTLE", "TURN"] #Initialize the CodeParser def __init__(self, path): self.SPEED = 0 self.ANGLE = 0 #Open racer file racer = open(path, ...
class Codeparser: speed = 0 angle = 0 line_num = 0 ports = ['THROTTLE', 'TURN'] def __init__(self, path): self.SPEED = 0 self.ANGLE = 0 racer = open(path, 'r') self.code = racer.readlines() racer.close() line = 0 while line < len(self.code): ...
# If we want to find the shortest path or any path between 2 nodes # BFS works better # Breadth-First search needs a Queue class Node: def __init__(self, val): self.val = val self.left = None self.right = None def __str__(self): return "Node: {} Left: {} Right:{}".format(self.v...
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def __str__(self): return 'Node: {} Left: {} Right:{}'.format(self.val, self.left, self.right) def visit(self): print(self.val, end='') def breadth_first_traversal(root): qu...
testcases = int(input().strip()) for test in range(testcases): string = input().strip() length = len(string) half_length = length // 2 if length % 2: print(-1) continue letters1 = [0] * 26 letters2 = [0] * 26 ascii_a = ord('a') ascii_string = [ord(c) - ascii_a for c in...
testcases = int(input().strip()) for test in range(testcases): string = input().strip() length = len(string) half_length = length // 2 if length % 2: print(-1) continue letters1 = [0] * 26 letters2 = [0] * 26 ascii_a = ord('a') ascii_string = [ord(c) - ascii_a for c in st...
w, h, k = list(map(int, input().split())) c=0 for i in range(k): c = c+ ( (h-4*i)*2 +( w - 2-4*i)*2) print(c)
(w, h, k) = list(map(int, input().split())) c = 0 for i in range(k): c = c + ((h - 4 * i) * 2 + (w - 2 - 4 * i) * 2) print(c)
t = int(input()) h = (t // 3600) % 24 m1 = t // 60 % 60 // 10 m2 = t // 60 % 60 % 10 s1 = t % 60 // 10 s2 = t % 10 print(h, ":", m1, m2, ":", s1, s2, sep="")
t = int(input()) h = t // 3600 % 24 m1 = t // 60 % 60 // 10 m2 = t // 60 % 60 % 10 s1 = t % 60 // 10 s2 = t % 10 print(h, ':', m1, m2, ':', s1, s2, sep='')
class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: def sumRootToLeaf(r, s): li, x = [n for n in [r.left, r.right] if n], (s << 1) + r.val return x if not li else sum(sumRootToLeaf(n, x) for n in li) return sumRootToLeaf(root, 0)
class Solution: def sum_root_to_leaf(self, root: TreeNode) -> int: def sum_root_to_leaf(r, s): (li, x) = ([n for n in [r.left, r.right] if n], (s << 1) + r.val) return x if not li else sum((sum_root_to_leaf(n, x) for n in li)) return sum_root_to_leaf(root, 0)
class SymbolTable: def __init__(self): self.table = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, ...
class Symboltable: def __init__(self): self.table = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15, 'SCREEN': 16384, 'KBD': 24576} def add_ent...
""" stormdrain events SD_bounds_updated Bounds have changed. Typically this happens in response to axes limits changing on a plot, or filtering criteria on a dataset changing. SD_reflow_start and SD_reflow_done These events, which often should follow a SD_bounds_updated event, is used to trigger a reflow of dataset...
""" stormdrain events SD_bounds_updated Bounds have changed. Typically this happens in response to axes limits changing on a plot, or filtering criteria on a dataset changing. SD_reflow_start and SD_reflow_done These events, which often should follow a SD_bounds_updated event, is used to trigger a reflow of dataset...
A,B = map(int, input().split()) #A,B = 4, 10 if A > B : print('>') elif A < B : print('<') else: print('==')
(a, b) = map(int, input().split()) if A > B: print('>') elif A < B: print('<') else: print('==')
# @Time: 2022/4/13 11:29 # @Author: chang liu # @Email: chang_liu_tamu@gmail.com # @File:LFU.py class Node: def __init__(self, key=None, val=None): self.val = val self.key = key self.f = 1 self.left = None self.right = None class DLL: def __init__(self): self....
class Node: def __init__(self, key=None, val=None): self.val = val self.key = key self.f = 1 self.left = None self.right = None class Dll: def __init__(self): self.size = 0 self.head = node() self.tail = node() self.head.left = self.tail...
# -*- coding: utf-8 -*- # @Time: 2020/7/16 11:36 # @Author: GraceKoo # @File: interview_7.py # @Desc: https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qr # u=%2Fta%2Fcoding-interviews%2Fquestion-ranking class Solution: def fib(self, N: int) -> int: ...
class Solution: def fib(self, N: int) -> int: if N <= 1: return N f_dict = {0: 0, 1: 1} for i in range(2, N): f_dict[i] = f_dict[i - 1] + f_dict[i - 2] return f_dict[N - 1] so = solution() print(so.fib(4))
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): if matrix: new = [] for rows in matrix: new.append([n ** 2 for n in rows]) return new
def square_matrix_simple(matrix=[]): if matrix: new = [] for rows in matrix: new.append([n ** 2 for n in rows]) return new
# Adaptive Card Design Schema for a sample form. # To learn more about designing and working with buttons and cards, # checkout https://developer.webex.com/docs/api/guides/cards BUSY_CARD_CONTENT = { "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "type": "AdaptiveCard", "version": "1.2", ...
busy_card_content = {'$schema': 'http://adaptivecards.io/schemas/adaptive-card.json', 'type': 'AdaptiveCard', 'version': '1.2', 'body': [{'type': 'ColumnSet', 'columns': [{'type': 'Column', 'width': 1, 'items': [{'type': 'Image', 'url': 'https://i.postimg.cc/2jMv5kqt/AS89975.jpg', 'size': 'Stretch'}]}, {'type': 'Column...
""" This Module is not yet correct!! """ class TypedCollectionCreator(object): """ Class enforcing that the iterable only contains elements of the given type (or subclasses) at initialisation. That is, checks in the __new__ function that only elements of the given dtype are contained in the given seq...
""" This Module is not yet correct!! """ class Typedcollectioncreator(object): """ Class enforcing that the iterable only contains elements of the given type (or subclasses) at initialisation. That is, checks in the __new__ function that only elements of the given dtype are contained in the given seq...
# Map by afffsdd # A map with four corners, with bots spawning in each of them. # flake8: noqa # TODO: Format this file. {'spawn': [(1, 1), (14, 1), (15, 1), (16, 1), (17, 1), (1, 2), (1, 3), (1, 4), (17, 14), (17, 15), (17, 16), (1, 17), (2, 17), (3, 17), (4, 17), (17, 17)], 'obstacle': [(0, 0), (1, 0), (2, 0), (3, 0)...
{'spawn': [(1, 1), (14, 1), (15, 1), (16, 1), (17, 1), (1, 2), (1, 3), (1, 4), (17, 14), (17, 15), (17, 16), (1, 17), (2, 17), (3, 17), (4, 17), (17, 17)], 'obstacle': [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), (15, 0), (16, 0), (17, 0),...
class Node(object): """docstring for Node""" def __init__(self, item, left, right): super(Node, self).__init__() self.item = item self.left = left self.right = right def getChild(self, direction): if (direction > 0): return self.left else: ...
class Node(object): """docstring for Node""" def __init__(self, item, left, right): super(Node, self).__init__() self.item = item self.left = left self.right = right def get_child(self, direction): if direction > 0: return self.left else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def cudasolve(A, b, tol=1e-3, normal=False, regA = 1.0, regI = 0.0): """ Conjugate gradient solver for dense system of linear equations. Ax = b Returns: x = A^(-1)b If the system is normal, then it solves (regA*A'A +regI*I)x= b ...
def cudasolve(A, b, tol=0.001, normal=False, regA=1.0, regI=0.0): """ Conjugate gradient solver for dense system of linear equations. Ax = b Returns: x = A^(-1)b If the system is normal, then it solves (regA*A'A +regI*I)x= b Returns: x = (A'A +reg*I)^(-1)b """ n ...
# MACRO - calculate precision and recall for every class, # then take their weigted sum and calculate ONE f1 score # MICRO - calculate f1 scores for each class and take their weighted sum def f1_score(precision, recall): f = 0 if precision + recall == 0 \ else 2 * precision * recall / (precision + recall) ...
def f1_score(precision, recall): f = 0 if precision + recall == 0 else 2 * precision * recall / (precision + recall) return f def main(k, confusion_matrix): num_samples = [sum(confusion_matrix[idx]) for idx in range(k)] weights = [s / sum(num_samples) for s in num_samples] precisions = [] recal...
""" pyPasswordValidator. Password validator """ __version__ = "0.1.3.1" __author__ = 'Jon Duarte' __credits__ = 'iHeart Media'
""" pyPasswordValidator. Password validator """ __version__ = '0.1.3.1' __author__ = 'Jon Duarte' __credits__ = 'iHeart Media'
name = "harry" print(name[0]) # List names = ["Harry", "Ron", "Hermione"] print(names[0]) # Tuples coordinateX = 10.0 coordinateY = 20.0 coordinate = (10.0,20.0) print(coordinate)
name = 'harry' print(name[0]) names = ['Harry', 'Ron', 'Hermione'] print(names[0]) coordinate_x = 10.0 coordinate_y = 20.0 coordinate = (10.0, 20.0) print(coordinate)
#!/usr/bin/env python print (' ') nome = input('Digite seu nome: ') #Mensagem print (' ') print (f'Seja bem-vindo Sr(a) {nome}, Obrigado por vir!') print (' ')
print(' ') nome = input('Digite seu nome: ') print(' ') print(f'Seja bem-vindo Sr(a) {nome}, Obrigado por vir!') print(' ')
#latin square num=int(input("Enter the number of rows:=")) for i in range(1,num+1): r=i #set the first roew element for j in range(1,num+1): print(r,end='\t') if r==num: r=1 else: r=r+1 print()
num = int(input('Enter the number of rows:=')) for i in range(1, num + 1): r = i for j in range(1, num + 1): print(r, end='\t') if r == num: r = 1 else: r = r + 1 print()
if (isWindVpDefined == 1): evapoTranspiration = evapoTranspirationPenman else: evapoTranspiration = evapoTranspirationPriestlyTaylor
if isWindVpDefined == 1: evapo_transpiration = evapoTranspirationPenman else: evapo_transpiration = evapoTranspirationPriestlyTaylor
#!/usr/bin/env python class ShapeGrid(object): """ Generic shape grid interface. Should be subclassed by specific shapes. """ def __init__(self): pass def create_grid(self, layer, extent, num_across=10): raise NotImplementedError('Provided by each subclass of ShapeGrid.')
class Shapegrid(object): """ Generic shape grid interface. Should be subclassed by specific shapes. """ def __init__(self): pass def create_grid(self, layer, extent, num_across=10): raise not_implemented_error('Provided by each subclass of ShapeGrid.')
# -*- coding: utf-8 -*- """ Created on Sun Jan 10 22:57:00 2021 @author: Dragneel """ #%% Tree structure ''' The following Family Tree will be used P1 -- / \ --- \ / \ P11 P12 + P13 --- ...
""" Created on Sun Jan 10 22:57:00 2021 @author: Dragneel """ '\n The following Family Tree will be used\n P1\n --\n / --- / P11 P12 + P13\n --- ---------\n / | \\ / ...
def add_time(start: str, duration: str, day: str = None) -> str: days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') start_lst = list(map(int, start[:-3].split(':'))) duration_lst = list(map(int, duration.split(':'))) total_min = start_lst[1] + duration_lst[1] extr...
def add_time(start: str, duration: str, day: str=None) -> str: days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') start_lst = list(map(int, start[:-3].split(':'))) duration_lst = list(map(int, duration.split(':'))) total_min = start_lst[1] + duration_lst[1] extra_h...
#! /usr/bin/env python3 # Type of variable: Number a, b = 5, 10 print(a, b) a, b = b, a print(a, b) # Type of variable: List myList = [1, 2, 3, 4, 5] print("Initial Array :", myList) myList[0], myList[1] = myList[1], myList[0] print("Swapped Array :", myList)
(a, b) = (5, 10) print(a, b) (a, b) = (b, a) print(a, b) my_list = [1, 2, 3, 4, 5] print('Initial Array :', myList) (myList[0], myList[1]) = (myList[1], myList[0]) print('Swapped Array :', myList)
def up_egcd(m,n): #Assume m>n if n>m: m,n=n,m if m%n==0: return n else: return up_egcd(n,m%n) print(up_egcd(int(input('Number 1\n')),int(input('Number 2\n'))))
def up_egcd(m, n): if n > m: (m, n) = (n, m) if m % n == 0: return n else: return up_egcd(n, m % n) print(up_egcd(int(input('Number 1\n')), int(input('Number 2\n'))))
class AbstractRecurrentNeuralNetworkBuilder(object): """Build a recurrent neural network according to specified the input/output dimensions and number of unrolled steps. """ DEFAULT_VARIABLE_SCOPE = "recurrent_neural_network" def __init__(self, tensors, mixtur...
class Abstractrecurrentneuralnetworkbuilder(object): """Build a recurrent neural network according to specified the input/output dimensions and number of unrolled steps. """ default_variable_scope = 'recurrent_neural_network' def __init__(self, tensors, mixture_density_output, feature_builder=N...
inp = open('input.txt').read().split(", ") # Reading file coord = (0, 0) # Setting original coordinates p_dir = 0 # Setting original direction (north) seen = set() for instr in inp: dir = instr[0] step = int(instr[1:]) if dir == "R": p_dir = p_dir + 1 if p_dir == 4: p_dir = 0...
inp = open('input.txt').read().split(', ') coord = (0, 0) p_dir = 0 seen = set() for instr in inp: dir = instr[0] step = int(instr[1:]) if dir == 'R': p_dir = p_dir + 1 if p_dir == 4: p_dir = 0 elif dir == 'L': if p_dir == 0: p_dir = 4 p_dir = p_di...
# Problem : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/submissions/ # Ref : https://youtu.be/wuzTpONbd-0 # 2 transactions only class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) ...
class Solution(object): def max_profit(self, prices): """ :type prices: List[int] :rtype: int """ n = len(prices) max_profit_till_today = 0 min_so_far = prices[0] dp_left = [0] * n for i in range(1, n): min_so_far = min(min_so_far,...
def test_it(binbb, repos_cfg): """Test just the first one""" expected_words = ("Fields Values Branch Name Author" " TimeStamp Commit ID Message").split() for account_name, rep_cfg in repos_cfg.items(): for repo_name in rep_cfg.keys(): bbcmd = ["repo", "branch", "-a"...
def test_it(binbb, repos_cfg): """Test just the first one""" expected_words = 'Fields Values Branch Name Author TimeStamp Commit ID Message'.split() for (account_name, rep_cfg) in repos_cfg.items(): for repo_name in rep_cfg.keys(): bbcmd = ['repo', 'branch', '-a', account_name, '-r', rep...
"""Rotate a matrix by 90 degrees.""" def rotate_in_place(matrix): """ Modify and return the original matrix. rotated 90 degrees clockwise in place. """ try: n = len(matrix) m = len(matrix[0]) for i in range(n//2): for j in range(i, m-1-i): ii, j...
"""Rotate a matrix by 90 degrees.""" def rotate_in_place(matrix): """ Modify and return the original matrix. rotated 90 degrees clockwise in place. """ try: n = len(matrix) m = len(matrix[0]) for i in range(n // 2): for j in range(i, m - 1 - i): ...
class Human(object): def __init__(self, world=None, age=20): self.maxAge = 50 self.age = age self.alive = True self.world = world def update(self): self.age += 1 if self.age > self.maxAge: self.alive = False def get_age(self): return sel...
class Human(object): def __init__(self, world=None, age=20): self.maxAge = 50 self.age = age self.alive = True self.world = world def update(self): self.age += 1 if self.age > self.maxAge: self.alive = False def get_age(self): return sel...