content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Cue: def __init__(self): pass def power_to_speed(self, power, ball=None): # Translate a power (0-100) to the ball's velocity. # Ball object passed in in case this depends on ball weight. return power*10 def on_hit(self, ball): # Apply some effect to ball on hi...
class Cue: def __init__(self): pass def power_to_speed(self, power, ball=None): return power * 10 def on_hit(self, ball): pass class Basiccue(Cue): pass
# # PySNMP MIB module UAS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UAS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:28:15 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, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_range_constraint, constraints_union, value_size_constraint) ...
def maior_primo(num): if num < 2: return False else: for n in range(2, num): while num % n == 0: return num - 1 return num
def maior_primo(num): if num < 2: return False else: for n in range(2, num): while num % n == 0: return num - 1 return num
class DragEventArgs(EventArgs): """ Provides data for the System.Windows.Forms.Control.DragDrop,System.Windows.Forms.Control.DragEnter,or System.Windows.Forms.Control.DragOver event. DragEventArgs(data: IDataObject,keyState: int,x: int,y: int,allowedEffect: DragDropEffects,effect: DragDropEffects) """...
class Drageventargs(EventArgs): """ Provides data for the System.Windows.Forms.Control.DragDrop,System.Windows.Forms.Control.DragEnter,or System.Windows.Forms.Control.DragOver event. DragEventArgs(data: IDataObject,keyState: int,x: int,y: int,allowedEffect: DragDropEffects,effect: DragDropEffects) """ @...
""" max dimensions (width & height) of the material if the part is larger than the max dimensions then part must be `pieced` together kerf if our laser beam has a width of 20 mm (kerf - aka the thickness of the blade) and we do not factor this into our calculations (i.e., a kerf value of 0) then we wo...
""" max dimensions (width & height) of the material if the part is larger than the max dimensions then part must be `pieced` together kerf if our laser beam has a width of 20 mm (kerf - aka the thickness of the blade) and we do not factor this into our calculations (i.e., a kerf value of 0) then we wo...
# Demo Python If ... Else - And ''' And The 'and' keyword is a logical operator, and is used to combine conditional statements. ''' # Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True")
""" And The 'and' keyword is a logical operator, and is used to combine conditional statements. """ a = 200 b = 33 c = 500 if a > b and c > a: print('Both conditions are True')
def timesize(t): if t<60: return f"{t:.2f}s" elif t<3600: return f"{t/60:.2f}m" elif t<86400: return f"{t/3600:.2f}h" else: return f"{t/86400:.2f}d"
def timesize(t): if t < 60: return f'{t:.2f}s' elif t < 3600: return f'{t / 60:.2f}m' elif t < 86400: return f'{t / 3600:.2f}h' else: return f'{t / 86400:.2f}d'
# .txt mesh converter def txt_mesh_converter(mesh_filename): # txt mesh converter, returns mesh variables with open(mesh_filename, 'r') as mesh_file: lines = mesh_file.readlines() # remove blank lines lines_list = [] for line in lines: if line.strip(): ...
def txt_mesh_converter(mesh_filename): with open(mesh_filename, 'r') as mesh_file: lines = mesh_file.readlines() lines_list = [] for line in lines: if line.strip(): lines_list.append(line) surfaces_start = lines_list.index('$Surfaces\n') surfaces_end = lines_list.index('$...
getAllObjects = [ { "id": 1, "keyName": "SPREAD", "name": "SPREAD" } ]
get_all_objects = [{'id': 1, 'keyName': 'SPREAD', 'name': 'SPREAD'}]
""" [2017-10-20] Challenge #336 [Hard] Van der Waerden numbers https://www.reddit.com/r/dailyprogrammer/comments/77m6l4/20171020_challenge_336_hard_van_der_waerden/ # Description This one came to me via the always interesting [Data Genetics blog](http://datagenetics.com/blog/august12017/index.html). Van der Waerden'...
""" [2017-10-20] Challenge #336 [Hard] Van der Waerden numbers https://www.reddit.com/r/dailyprogrammer/comments/77m6l4/20171020_challenge_336_hard_van_der_waerden/ # Description This one came to me via the always interesting [Data Genetics blog](http://datagenetics.com/blog/august12017/index.html). Van der Waerden'...
# # PySNMP MIB module CISCO-OPTICAL-MONITOR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OPTICAL-MONITOR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:51:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ...
class MetaDato: def __init__(self, nombreTabla, campos): pass def calcularRegistros(self): pass def getRegistro(self): pass
class Metadato: def __init__(self, nombreTabla, campos): pass def calcular_registros(self): pass def get_registro(self): pass
# day3 - sonar sweeps # def count_bits(bits, pos): ones = sum([int(b[pos]) for b in bits]) zeros = len(bits) - ones return (ones, zeros) def power(bits): width = len(bits[0]) gamma = [] epsilon = [] for i in range(0, width): (ones, zeros) = count_bits(bits, i) print(f"ones...
def count_bits(bits, pos): ones = sum([int(b[pos]) for b in bits]) zeros = len(bits) - ones return (ones, zeros) def power(bits): width = len(bits[0]) gamma = [] epsilon = [] for i in range(0, width): (ones, zeros) = count_bits(bits, i) print(f'ones = {ones} zeros = {zeros}'...
# WARNING: Do not edit by hand, this file was generated by Crank: # # https://github.com/gocardless/crank # class InstalmentSchedule(object): """A thin wrapper around a instalment_schedule, providing easy access to its attributes. Example: instalment_schedule = client.instalment_schedules.get() ...
class Instalmentschedule(object): """A thin wrapper around a instalment_schedule, providing easy access to its attributes. Example: instalment_schedule = client.instalment_schedules.get() instalment_schedule.id """ def __init__(self, attributes, api_response): self.attributes =...
nama = str(input("Masukkan Nama ")) nim = int(input("Masukkan NIM ")) uts = int(input("Masukkan Nilai UTS : ")) uas = int(input("Masukkan Nilai UAS : ")) hitungRataRata = (uts+uas)/2 if int(hitungRataRata) <= 40: nilai = 'E' elif int(hitungRataRata) <= 60: nilai = 'D' elif int(hitungRataRata) <= 70: ni...
nama = str(input('Masukkan Nama ')) nim = int(input('Masukkan NIM ')) uts = int(input('Masukkan Nilai UTS : ')) uas = int(input('Masukkan Nilai UAS : ')) hitung_rata_rata = (uts + uas) / 2 if int(hitungRataRata) <= 40: nilai = 'E' elif int(hitungRataRata) <= 60: nilai = 'D' elif int(hitungRataRata) <= 70: n...
''' Pattern Plus star pattern: Enter number of rows: 5 + + + + +++++++++ + + + + ''' number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+1): if number_rows%2!=0: if row==((number_rows//2)+1) or colu...
""" Pattern Plus star pattern: Enter number of rows: 5 + + + + +++++++++ + + + + """ number_rows = int(input('Enter number of rows: ')) for row in range(1, number_rows + 1): for column in range(1, number_rows + 1): if number_rows % 2 != 0: if row == number_rows //...
class Solution: def maxRotateFunction(self, A: List[int]) -> int: n = len(A) if n <= 1: return 0 if n == 2: return max(A) result = -inf for i in range(n): result = max(result, sum([((j + i) % n) * v for j, v in enumerate(A)])) return result
class Solution: def max_rotate_function(self, A: List[int]) -> int: n = len(A) if n <= 1: return 0 if n == 2: return max(A) result = -inf for i in range(n): result = max(result, sum([(j + i) % n * v for (j, v) in enumerate(A)])) re...
def demo_map(): num_list = list( range(1, 6) ) ## Example_#1: # compute x^2 for each element result = list( map( lambda x:x**2, num_list) ) # [1, 4, 9, 16, 25] print( result ) ## Example_#2: # compute 3x + 1 for each element result = list( map( lambda x:3*x+1, num_list) ) ...
def demo_map(): num_list = list(range(1, 6)) result = list(map(lambda x: x ** 2, num_list)) print(result) result = list(map(lambda x: 3 * x + 1, num_list)) print(result) result = list(map(lambda x: x ** 0.5, num_list)) print(result) str_list = ['apple', 'banana', 'cat', 'dog', 'elephant'...
class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: ans = numBottles // (numExchange - 1) + numBottles return ans if numBottles % (numExchange - 1) else ans - 1
class Solution: def num_water_bottles(self, numBottles: int, numExchange: int) -> int: ans = numBottles // (numExchange - 1) + numBottles return ans if numBottles % (numExchange - 1) else ans - 1
class JouleHeatFraction: """The JouleHeatFraction object defines the fraction of electric energy released as heat. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].jouleHeatFraction import odbMaterial ...
class Jouleheatfraction: """The JouleHeatFraction object defines the fraction of electric energy released as heat. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].jouleHeatFraction import odbMaterial ...
self.description = "Sysupgrade with a set of sync packages replacing a set of local ones" sp1 = pmpkg("pkg2") sp1.replaces = ["pkg1"] sp2 = pmpkg("pkg3") sp2.replaces = ["pkg1"] sp3 = pmpkg("pkg4") sp3.replaces = ["pkg1", "pkg0"] sp4 = pmpkg("pkg5") sp4.replaces = ["pkg0"] for p in sp1, sp2, sp3, sp4: self.addpkg...
self.description = 'Sysupgrade with a set of sync packages replacing a set of local ones' sp1 = pmpkg('pkg2') sp1.replaces = ['pkg1'] sp2 = pmpkg('pkg3') sp2.replaces = ['pkg1'] sp3 = pmpkg('pkg4') sp3.replaces = ['pkg1', 'pkg0'] sp4 = pmpkg('pkg5') sp4.replaces = ['pkg0'] for p in (sp1, sp2, sp3, sp4): self.addpkg...
class NullDisplay: def __init__(self, board=None): pass def show_results(self): pass def draw(self): pass
class Nulldisplay: def __init__(self, board=None): pass def show_results(self): pass def draw(self): pass
n=int(input("How Many Time you Chack the Condition: ")) for i in range(1,n+1): num=int(input("Enter The Number To be Chack Even or Odd: ")) if(num%2==0): print("The Enterd Number is Even") else: print("The Enterd Number is odd")
n = int(input('How Many Time you Chack the Condition: ')) for i in range(1, n + 1): num = int(input('Enter The Number To be Chack Even or Odd: ')) if num % 2 == 0: print('The Enterd Number is Even') else: print('The Enterd Number is odd')
class ShareInstance(): __session = None @classmethod def share(cls, **kwargs): if not cls.__session: cls.__session = cls(**kwargs) return cls.__session # Expand dict class Dict(dict): def get(self, key, default=None, sep='.'): keys = key.split(sep) for i, ke...
class Shareinstance: __session = None @classmethod def share(cls, **kwargs): if not cls.__session: cls.__session = cls(**kwargs) return cls.__session class Dict(dict): def get(self, key, default=None, sep='.'): keys = key.split(sep) for (i, key) in enumerat...
emoji_dict = { "anger": ["\U0001F92C", "data/emoji/emoji_u1f92c.png"], "disgust": ["\U0001F616", "data/emoji/emoji_u1f616.png"], "fear": ["\U0001F633", "data/emoji/emoji_u1f633.png"], "happy": ["\U0001F604", "data/emoji/emoji_u1f604.png"], "neutral": ["\U0001F612", "data/emoji/emoji_u1f612.png"], ...
emoji_dict = {'anger': ['🤬', 'data/emoji/emoji_u1f92c.png'], 'disgust': ['😖', 'data/emoji/emoji_u1f616.png'], 'fear': ['😳', 'data/emoji/emoji_u1f633.png'], 'happy': ['😄', 'data/emoji/emoji_u1f604.png'], 'neutral': ['😒', 'data/emoji/emoji_u1f612.png'], 'sadness': ['😞', 'data/emoji/emoji_u1f61e.png'], 'surprise': [...
# Section 5.16 snippets # Creating a Two-Dimensional List a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]] # Illustrating a Two-Dimensional List # Identifying the Elements in a Two-Dimensional List for row in a: for item in row: print(item, end=' ') print() # How the Nested Loops Execute f...
a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]] for row in a: for item in row: print(item, end=' ') print() for (i, row) in enumerate(a): for (j, item) in enumerate(row): print(f'a[{i}][{j}]={item} ', end=' ') print()
package_name = 'cms_search' name = 'django-cms-search' author = 'Benjamin Wohlwend' author_email = 'piquadrat@gmail.com' description = "An extension to django CMS to provide multilingual Haystack indexes" version = __import__(package_name).__version__ project_url = 'http://github.com/piquadrat/%s' % name license = 'BSD...
package_name = 'cms_search' name = 'django-cms-search' author = 'Benjamin Wohlwend' author_email = 'piquadrat@gmail.com' description = 'An extension to django CMS to provide multilingual Haystack indexes' version = __import__(package_name).__version__ project_url = 'http://github.com/piquadrat/%s' % name license = 'BSD...
# Space: O(1) # Time: O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def addOneRow(self, root, v, d): if d==1: new_node = Tree...
class Solution: def add_one_row(self, root, v, d): if d == 1: new_node = tree_node(v) new_node.left = root return new_node def helper(root, cur_level, required_level, required_val, direction): if root is None and cur_level == required_level: ...
# COSINE FUNCTION def cosine(x) -> float: """ Returns cosine of x radians """ return 0.0
def cosine(x) -> float: """ Returns cosine of x radians """ return 0.0
''' Selection sort is an O(n^2) sorting algorithm. The logic is to find the smallest element in the unsorted portion of the array and swapping it in the right position. In the worst-case it takes n(n+1)/2 accesses. ''' def selsort(A,l,r): ''' Convention is that array elements are indexed from l to r-1.''' ...
""" Selection sort is an O(n^2) sorting algorithm. The logic is to find the smallest element in the unsorted portion of the array and swapping it in the right position. In the worst-case it takes n(n+1)/2 accesses. """ def selsort(A, l, r): """ Convention is that array elements are indexed from l to r-1.""" ...
def dominator(arr): res = 0 if len(arr) == 0: return -1 for x in arr: if arr.count(x) > len(arr) / 2: res = x break else: res = -1 return res
def dominator(arr): res = 0 if len(arr) == 0: return -1 for x in arr: if arr.count(x) > len(arr) / 2: res = x break else: res = -1 return res
def move(instruction, x, y, w_x, w_y): if instruction[0] == 'N': w_y += instruction[1] if instruction[0] == 'S': w_y -= instruction[1] if instruction[0] == 'E': w_x += instruction[1] if instruction[0] == 'W': w_x -= instruction[1] if instruction[0] in ['L', 'R']: ...
def move(instruction, x, y, w_x, w_y): if instruction[0] == 'N': w_y += instruction[1] if instruction[0] == 'S': w_y -= instruction[1] if instruction[0] == 'E': w_x += instruction[1] if instruction[0] == 'W': w_x -= instruction[1] if instruction[0] in ['L', 'R']: ...
DEBUG = True TEMPLATE_DEBUG = True # THIS MUST BE HTTPS DOMAIN_NAME="https://52.34.71.182:8000" #CSRF_COOKIE_SECURE = False #SESSION_COOKIE_SECURE = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'expfactory.db', } } #DATABASES = { # 'default': { # ...
debug = True template_debug = True domain_name = 'https://52.34.71.182:8000' databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'expfactory.db'}} static_root = 'assets/' static_url = '/assets/' media_root = 'static/' media_url = '/static/'
# Writes down all combinations of plates COMBINATIONS = [1.25, 2.5, 5, 10, 25] # 1 kg is 2.20... pounds KILOS_POUNDS_CONVERSION_RATE = 2.20462 # Function that asks for str input def get_input_in_kilos(): return input("Enter weight in kilos: ") # function that converts punds to kilos def convert_kilos_to_pounds(k...
combinations = [1.25, 2.5, 5, 10, 25] kilos_pounds_conversion_rate = 2.20462 def get_input_in_kilos(): return input('Enter weight in kilos: ') def convert_kilos_to_pounds(kilos): return kilos * KILOS_POUNDS_CONVERSION_RATE def break_down_into_combinations(weight, options): combination = [] difference...
class Fila: def __init__(self, maxx): self.limit = maxx self.elementos = [0] * maxx self.ini = -1 self.end = -1 self._size = 0 self.offset = -1 def __len__(self): return self._size def insert(self, elem): if ((self._size) >= self.limi...
class Fila: def __init__(self, maxx): self.limit = maxx self.elementos = [0] * maxx self.ini = -1 self.end = -1 self._size = 0 self.offset = -1 def __len__(self): return self._size def insert(self, elem): if self._size >= self.limit or self....
# O(N^2) def can_make_target1(arr, target): for i in range(len(arr)): for j in range(i, len(arr)): if arr[i] + arr[j] == target: return True return False # O(N) def can_make_target2(arr, target): looking_for = set() for a in arr: if a in looking_for: ...
def can_make_target1(arr, target): for i in range(len(arr)): for j in range(i, len(arr)): if arr[i] + arr[j] == target: return True return False def can_make_target2(arr, target): looking_for = set() for a in arr: if a in looking_for: return True ...
# A somewhat special node as it is designed for use in skip list, in addition to having two pointers \ # it has three (next, previous and down). # This class is used by SortedLinkList, but is somewhat different to a regular link list node. class Node: def __init__(self, value, next=None, down=None, prev=None)...
class Node: def __init__(self, value, next=None, down=None, prev=None): self.value = value self.next = next self.down = down self.prev = prev
expected_output = { 'rib_table': { 'ipv4': { 'num_multicast_tables': 1, 'num_unicast_tables': 3, 'total_multicast_prefixes': 0, ...
expected_output = {'rib_table': {'ipv4': {'num_multicast_tables': 1, 'num_unicast_tables': 3, 'total_multicast_prefixes': 0, 'total_unicast_prefixes': 14}}}
""" Complexities: Runtime O(n log n): 2 sort() executions with O(n log n) each, while iteration with O(n+n) Space O(1) """ def min_platforms(arrivals, departures): """ :param: arrival - list of arrival time :param: departure - list of departure time TODO - complete this method and return the minimum n...
""" Complexities: Runtime O(n log n): 2 sort() executions with O(n log n) each, while iteration with O(n+n) Space O(1) """ def min_platforms(arrivals, departures): """ :param: arrival - list of arrival time :param: departure - list of departure time TODO - complete this method and return the minimum ...
# # @lc app=leetcode id=993 lang=python3 # # [993] Cousins in Binary Tree # # @lc code=start # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isCousins(self, root...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def is_cousins(self, root: TreeNode, x: int, y: int): pre = 0 curval = 0 self.x = x self.y = y self.xdetail = []...
# number one solution def is_ipv4_address(s): """ Return True if 's' is a valid IPv4 address """ # split the string on dots s_split = s.split('.') return len(s_split) == 4 and all(num.isdigit() and 0 <= int(num) < 256 for num in s_split) # my Solution def isIPv4Address(inputString): ...
def is_ipv4_address(s): """ Return True if 's' is a valid IPv4 address """ s_split = s.split('.') return len(s_split) == 4 and all((num.isdigit() and 0 <= int(num) < 256 for num in s_split)) def is_i_pv4_address(inputString): input_string = inputString + '.' print(inputString) start...
class StringParser: def __init__(self): self.parse_trees = [] def register(self,tree): self.parse_trees.append(tree) def parse(self, string): for tree in self.parse_trees: return tree.parse(string)
class Stringparser: def __init__(self): self.parse_trees = [] def register(self, tree): self.parse_trees.append(tree) def parse(self, string): for tree in self.parse_trees: return tree.parse(string)
# -*- coding:utf-8 -*- # https://leetcode.com/problems/unique-paths-ii/description/ class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ if not obstacleGrid or not obstacleGrid[0]: ...
class Solution(object): def unique_paths_with_obstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ if not obstacleGrid or not obstacleGrid[0]: return m = len(obstacleGrid) n = len(obstacleGrid[0]) if obsta...
def merge(pairs): pairs = sorted(pairs) j,tmp = 0, [] while j < len(pairs): a = pairs[j] if j < len(pairs) - 1: b = pairs[j+1] if a[1] == b[0]: a = (a[0], b[1]) j += 1 tmp += [a] j += 1 return tmp print(merge(sorted(set([(1,2),(2,3),(4,5),(5...
def merge(pairs): pairs = sorted(pairs) (j, tmp) = (0, []) while j < len(pairs): a = pairs[j] if j < len(pairs) - 1: b = pairs[j + 1] if a[1] == b[0]: a = (a[0], b[1]) j += 1 tmp += [a] j += 1 return tmp print(merge(...
def corner_move(game): return list(set(game.possible_moves()) & {1, 3, 7, 9}) def center_move(game): return list(set(game.possible_moves()) & {5}) def side_move(game): return list(set(game.possible_moves()) & {2, 4, 6, 8}) def test_if_win_is_possible(game, to_check=None): if to_check is None: ...
def corner_move(game): return list(set(game.possible_moves()) & {1, 3, 7, 9}) def center_move(game): return list(set(game.possible_moves()) & {5}) def side_move(game): return list(set(game.possible_moves()) & {2, 4, 6, 8}) def test_if_win_is_possible(game, to_check=None): if to_check is None: ...
class Solution: def maxProfit(self, prices) -> int: ''' Notice that we can complete as many transactions as we like. Therefore, a greedy rule are easily came out, that we buy it on the low price day which compares with the next day and sell it on the high price day which co...
class Solution: def max_profit(self, prices) -> int: """ Notice that we can complete as many transactions as we like. Therefore, a greedy rule are easily came out, that we buy it on the low price day which compares with the next day and sell it on the high price day which ...
def part1(): values = [i.split(" ") for i in open("input.txt").read().split("\n")] lights = [[False]*50 ,[False]*50,[False]*50,[False]*50,[False]*50,[False]*50] for command in values: if command[0] == "rect": length, height = (int(i) for i in command[1].split("x")) for i in ...
def part1(): values = [i.split(' ') for i in open('input.txt').read().split('\n')] lights = [[False] * 50, [False] * 50, [False] * 50, [False] * 50, [False] * 50, [False] * 50] for command in values: if command[0] == 'rect': (length, height) = (int(i) for i in command[1].split('x')) ...
# https://blog.csdn.net/Violet_ljp/article/details/80556460 # https://www.youtube.com/watch?v=pcKY4hjDrxk # https://github.com/minsuk-heo/problemsolving/tree/master/graph def bfs(graph, start): vertexList, edgeList = graph visitedList = [] queue = [start] adjacencyList = [[] for vertex in vertexList] ...
def bfs(graph, start): (vertex_list, edge_list) = graph visited_list = [] queue = [start] adjacency_list = [[] for vertex in vertexList] for edge in edgeList: adjacencyList[edge[0]].append(edge[1]) while queue: current = queue.pop() for neighbor in adjacencyList[current]:...
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights R...
gb2312_typical_distribution_ratio = 0.9 gb2312_table_size = 3760 gb2312_char_to_freq_order = (1671, 749, 1443, 2364, 3924, 3807, 2330, 3921, 1704, 3463, 2691, 1511, 1515, 572, 3191, 2205, 2361, 224, 2558, 479, 1711, 963, 3162, 440, 4060, 1905, 2966, 2947, 3580, 2647, 3961, 3842, 2204, 869, 4207, 970, 2678, 5626, 2944, ...
# from collections import Counter, defaultdict # class Solution: # def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: # count = Counter(nums) # # print('count: {}'.format(count)) # tmp = nums.copy() #list(set(nums.copy())) # tmp.sort() # # print('tmp...
class Solution: def smaller_numbers_than_current(self, nums: List[int]) -> List[int]: tmp = [0] * (max(nums) + 1) for num in nums: tmp[num] += 1 ans = [] for num in nums: ans.append(sum(tmp[:num])) return ans
#Task https://adventofcode.com/2020/day/2 inputExample = [['2-3','r','rrnr'], ['5-10','n','ltnnnknnvcnnn'], ['7-9','p','jtpptpllpj'], ['2-5','s','slssssszssssssss'], ['16-17','d','dddddddddddddddlp'], ['2-5','q','bbwqqbkmdhqmjhn'], ['7-10','m','qmpgmmsmmmmkmmkj'], ['1-3','a','abcde'], ['4-7','g','vczggdgbgxg...
input_example = [['2-3', 'r', 'rrnr'], ['5-10', 'n', 'ltnnnknnvcnnn'], ['7-9', 'p', 'jtpptpllpj'], ['2-5', 's', 'slssssszssssssss'], ['16-17', 'd', 'dddddddddddddddlp'], ['2-5', 'q', 'bbwqqbkmdhqmjhn'], ['7-10', 'm', 'qmpgmmsmmmmkmmkj'], ['1-3', 'a', 'abcde'], ['4-7', 'g', 'vczggdgbgxgg']] def get_valid_passwords(inpu...
#!/usr/bin/env python # coding: utf-8 class tokenargs(object): '''Wraps builtin list with checks for illegal characters in token arguments.''' # Disallow these characters inside token arguments illegal = '[]:' # Replace simple inputs with illegal characters with their legal equivalents re...
class Tokenargs(object): """Wraps builtin list with checks for illegal characters in token arguments.""" illegal = '[]:' replace = {"':'": '58', "'['": '91', "']'": '93'} def __init__(self, items=None): """Construct a new list of token arguments.""" self.list = list() if items i...
# # PySNMP MIB module SAF-IPRADIO (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SAF-IPRADIO # Produced by pysmi-0.3.4 at Wed May 1 14:59:57 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, 0...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ This module is designed to analysis data """
""" This module is designed to analysis data """
gopen = open('namecheck.txt' , 'w') for i in range(1,54): fopen = open('%d' % i, 'r') for z in range(100): rline = fopen.readline() if rline: rlist = rline.split('$') name = rlist[0].strip() clg = rlist[1].strip() nlist = name.split(' ') if len(nlist)==1: gopen.write('%s, %s \n' % (name,clg)) ...
gopen = open('namecheck.txt', 'w') for i in range(1, 54): fopen = open('%d' % i, 'r') for z in range(100): rline = fopen.readline() if rline: rlist = rline.split('$') name = rlist[0].strip() clg = rlist[1].strip() nlist = name.split(' ') ...
class RectCoordinates: def __init__(self, x, y, w, h): self.startX = int(x) self.startY = int(y) self.w = int(w) self.h = int(h) self.endY = int(y + h) self.endX = int(x + w) def get_frame(self, frame): return frame[self.startY:self.endY, self.startX:self...
class Rectcoordinates: def __init__(self, x, y, w, h): self.startX = int(x) self.startY = int(y) self.w = int(w) self.h = int(h) self.endY = int(y + h) self.endX = int(x + w) def get_frame(self, frame): return frame[self.startY:self.endY, self.startX:sel...
# Reading lines from file and putting from a list to a dict dna = dict() contents = [] for line in open('rosalind_gc.txt', 'r').readlines(): contents.append(line.strip('\n')) if line[0] == '>': header = line[1:].rstrip() dna[header] = '' else: dna[header] = dna.get(header) + line.rst...
dna = dict() contents = [] for line in open('rosalind_gc.txt', 'r').readlines(): contents.append(line.strip('\n')) if line[0] == '>': header = line[1:].rstrip() dna[header] = '' else: dna[header] = dna.get(header) + line.rstrip() greather = ['', 0, ''] for key in dna: gc_qtd = 0 ...
#!/usr/bin/python # Filename: func_default.py def say(message='3',times=1): print (message * times) say(); say(times=11) say('Hello') say('World',5) say(2,4)
def say(message='3', times=1): print(message * times) say() say(times=11) say('Hello') say('World', 5) say(2, 4)
""" Project Euler Problem 45 ======================== Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T[n]=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal P[n]=n(3n-1)/2 1, 5, 12, 22, 35, ... Hexagonal H[n]=n(2n-1) 1, 6, 15, 28, 45, ... It can be verified that T[...
""" Project Euler Problem 45 ======================== Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T[n]=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal P[n]=n(3n-1)/2 1, 5, 12, 22, 35, ... Hexagonal H[n]=n(2n-1) 1, 6, 15, 28, 45, ... It can be verified that T[...
# -*- coding: utf-8 -*- """ Created on Sun Aug 8 12:01:02 2021 @author: Easin """ in1 = input() #print(in1) count = 0 list1 = [] list2 = [] for values in range(len(in1)): if in1[values] >= 'a' and in1[values] <= 'z': list1.append(in1[values]) flag = True for elem in range(len(li...
""" Created on Sun Aug 8 12:01:02 2021 @author: Easin """ in1 = input() count = 0 list1 = [] list2 = [] for values in range(len(in1)): if in1[values] >= 'a' and in1[values] <= 'z': list1.append(in1[values]) flag = True for elem in range(len(list1)): for val in range(elem, len(list1) - 1): if l...
def negate_condition(condition: callable): def _f(context): return not condition(context) return _f def dummy(context: dict) -> dict: return context class Transition: def __init__(self, next_state: object, condition: callable, callback: callable = dummy): self.next_state = next_stat...
def negate_condition(condition: callable): def _f(context): return not condition(context) return _f def dummy(context: dict) -> dict: return context class Transition: def __init__(self, next_state: object, condition: callable, callback: callable=dummy): self.next_state = next_state ...
# python3 def compute_min_number_of_refills(d, m, stops): assert 1 <= d <= 10 ** 5 assert 1 <= m <= 400 assert 1 <= len(stops) <= 300 assert 0 < stops[0] and all(stops[i] < stops[i + 1] for i in range(len(stops) - 1)) and stops[-1] < d count = 0 curr = 0 stops.insert(0, 0) stops.appen...
def compute_min_number_of_refills(d, m, stops): assert 1 <= d <= 10 ** 5 assert 1 <= m <= 400 assert 1 <= len(stops) <= 300 assert 0 < stops[0] and all((stops[i] < stops[i + 1] for i in range(len(stops) - 1))) and (stops[-1] < d) count = 0 curr = 0 stops.insert(0, 0) stops.append(d) ...
"""Decode ASCII-encoded messages""" def decode(coded): """Decode a string of ASCII codes""" return ''.join(map(chr, map(int, coded.split()))) if __name__ == '__main__': print(decode(''' 67 111 109 101 32 105 110 32 97 32 78 101 119 32 89 101 97 114 39 115 32 99 97 112 ...
"""Decode ASCII-encoded messages""" def decode(coded): """Decode a string of ASCII codes""" return ''.join(map(chr, map(int, coded.split()))) if __name__ == '__main__': print(decode('\n 67 111 109 101 32 105\n 110 32 97 32 78 101\n 119 32 89 101 97 114\n 39 115 32 99 97 112\n ...
def applicant_selector(gpa,ps_score,ec_count): message = "This applicant should be rejected." if (gpa >= 3): if (ps_score >= 90): if (ec_count >= 3): message = "This applicant should be accepted." else: message = "This applicant should be given an in-person interview." return messag...
def applicant_selector(gpa, ps_score, ec_count): message = 'This applicant should be rejected.' if gpa >= 3: if ps_score >= 90: if ec_count >= 3: message = 'This applicant should be accepted.' else: message = 'This applicant should be given an in-p...
# lc551.py # LeetCode 551. Student Attendance Record I `E` # acc | 91% | 13' # A~0f27 class Solution: def checkRecord(self, s: str) -> bool: a = 0 l = 0 for c in s: if c == "L": l += 1 if l > 2: return False else:...
class Solution: def check_record(self, s: str) -> bool: a = 0 l = 0 for c in s: if c == 'L': l += 1 if l > 2: return False else: l = 0 if c == 'A': a += 1 ...
inp = input() def palin(inp): if len(inp)==1: return True elif len(inp)==2: return inp[0]==inp[1] else: return inp[0]==inp[-1] and palin(inp[1:-1]) if palin(inp): print('PALINDROME') else: print('NOT PALINDROME')
inp = input() def palin(inp): if len(inp) == 1: return True elif len(inp) == 2: return inp[0] == inp[1] else: return inp[0] == inp[-1] and palin(inp[1:-1]) if palin(inp): print('PALINDROME') else: print('NOT PALINDROME')
def bazel_toolchains_repositories(): org_chromium_clang_mac() org_chromium_clang_linux_x64() org_chromium_sysroot_linux_x64() org_chromium_binutils_linux_x64() org_chromium_libcxx() org_chromium_libcxxabi() def org_chromium_clang_mac(): native.new_http_archive( name = 'org_chromium_...
def bazel_toolchains_repositories(): org_chromium_clang_mac() org_chromium_clang_linux_x64() org_chromium_sysroot_linux_x64() org_chromium_binutils_linux_x64() org_chromium_libcxx() org_chromium_libcxxabi() def org_chromium_clang_mac(): native.new_http_archive(name='org_chromium_clang_mac',...
# This file contains the set of rules of basic # defining the constants DIGITS = '0123456789' # defining the token types TOKEN_INT = 'INT' TOKEN_FLOAT = 'FLOAT' TOKEN_PLUS = 'PLUS' TOKEN_MULTI = 'MUL' TOKEN_MINUS = 'MINUS' TOKEN_DIVIDE = 'DIV' TOKEN_LPAREN = 'LPAREN' # left parenthesis TOKEN_RPAREN = 'RP...
digits = '0123456789' token_int = 'INT' token_float = 'FLOAT' token_plus = 'PLUS' token_multi = 'MUL' token_minus = 'MINUS' token_divide = 'DIV' token_lparen = 'LPAREN' token_rparen = 'RPAREN' class Position: def __init__(self, indx, line, column, file_name, file_txt): self.indx = indx self.line =...
""" Constants for the Desktop Processes integration. """ NAME = "Desktop Processes" DOMAIN = "desktop_processes" IGNORE = "ignore" PRIORITY = "priority" ATTR_CONFIG = "config" VERSION = "0.1.0" STARTUP_MESSAGE = f""" ------------------------------------------------------------------- {NAME} Version: {VERSION} This is...
""" Constants for the Desktop Processes integration. """ name = 'Desktop Processes' domain = 'desktop_processes' ignore = 'ignore' priority = 'priority' attr_config = 'config' version = '0.1.0' startup_message = f'\n-------------------------------------------------------------------\n{NAME}\nVersion: {VERSION}\nThis is...
{ "targets": [{ "target_name": "ui", "include_dirs": ["<(module_root_dir)/src/includes", "<(module_root_dir)"], "sources": [ '<!@(node tools/list-sources.js)' ], "conditions": [ ["OS=='win'", { "libraries": [ "<(module_root_dir)/libui.lib" ] }], ["OS=='linux'", { "cflags": ["-fvi...
{'targets': [{'target_name': 'ui', 'include_dirs': ['<(module_root_dir)/src/includes', '<(module_root_dir)'], 'sources': ['<!@(node tools/list-sources.js)'], 'conditions': [["OS=='win'", {'libraries': ['<(module_root_dir)/libui.lib']}], ["OS=='linux'", {'cflags': ['-fvisibility=hidden', '-std=gnu11'], 'ldflags': ["-Wl,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 25 13:53:05 2017 @author: venusgrape In this problem, you'll create a program that guesses a secret number! The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesse...
""" Created on Sat Feb 25 13:53:05 2017 @author: venusgrape In this problem, you'll create a program that guesses a secret number! The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too hig...
""" Code From: https://github.com/laurentluce/python-algorithms/ The MIT License (MIT) Copyright (c) 2015 Laurent Luce Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, includi...
""" Code From: https://github.com/laurentluce/python-algorithms/ The MIT License (MIT) Copyright (c) 2015 Laurent Luce Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, includi...
class Solution: # Sorting key function (Accepted), O(n log n) time, O(n) space def sortByBits(self, arr: List[int]) -> List[int]: def tup(n): return (bin(n).count('1'), n) return sorted(arr, key=tup) # One Liner (Top Voted), O(n log n) time, O(n) space def sortByBits(self, A...
class Solution: def sort_by_bits(self, arr: List[int]) -> List[int]: def tup(n): return (bin(n).count('1'), n) return sorted(arr, key=tup) def sort_by_bits(self, A): return sorted(A, key=lambda a: (bin(a).count('1'), a))
# # PySNMP MIB module STN-CHASSIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STN-CHASSIS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:03:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) ...
# Python returning values def withdraw_money(current_bal, amount): if(current_bal >= amount): current_bal -= amount return current_bal balance = withdraw_money(100, 20) if (balance >= 50): print(f"The balance is {balance}.") else: print("You need to make a deposit.")
def withdraw_money(current_bal, amount): if current_bal >= amount: current_bal -= amount return current_bal balance = withdraw_money(100, 20) if balance >= 50: print(f'The balance is {balance}.') else: print('You need to make a deposit.')
class Queue: """An implementation of the Queue data strucutre.""" def __init__(self): self._items = [] def __repr__(self): return "pyDS.queue.Queue({})".format(self._items) def __str__(self): return str(self._items) def __len__(self): return len(self._items) ...
class Queue: """An implementation of the Queue data strucutre.""" def __init__(self): self._items = [] def __repr__(self): return 'pyDS.queue.Queue({})'.format(self._items) def __str__(self): return str(self._items) def __len__(self): return len(self._items) ...
# -*- coding: utf-8 -*- """ Created on Fri Sep 16 09:31:26 2016 @author: andre # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Problem Set 2, problem 3 # Use bisection search to make the program faster # The following variables contain values as described below: # balance - the ...
""" Created on Fri Sep 16 09:31:26 2016 @author: andre # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Problem Set 2, problem 3 # Use bisection search to make the program faster # The following variables contain values as described below: # balance - the outstanding balance on t...
while True: n = int(input("Height: ")) width = n if n > 0 and n <= 8: break for num_of_hashes in range(1, n + 1): num_of_spaces = n - num_of_hashes print(" " * num_of_spaces, end="") print("#" * num_of_hashes, end="") print(" ", end="") print("#" * num_of_hashes)
while True: n = int(input('Height: ')) width = n if n > 0 and n <= 8: break for num_of_hashes in range(1, n + 1): num_of_spaces = n - num_of_hashes print(' ' * num_of_spaces, end='') print('#' * num_of_hashes, end='') print(' ', end='') print('#' * num_of_hashes)
class Events: # REPL to USER EVENTS INP = 'inp' OUT = 'out' ERR = 'err' HTML = 'html' EXC = 'exc' PONG = 'pong' PATH = 'path' DONE = 'ended' STARTED = 'started' FORKED = 'forked' # REPL <-> USER EVENTS NOINT = 'noint' # USER to REPL EVENTS WRT = 'wrt' RU...
class Events: inp = 'inp' out = 'out' err = 'err' html = 'html' exc = 'exc' pong = 'pong' path = 'path' done = 'ended' started = 'started' forked = 'forked' noint = 'noint' wrt = 'wrt' run = 'run' ping = 'ping' fork = 'fork' def encode(event, data=''): re...
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the messag...
def test(): assert 'junk_drawer' in __solution__, "Make sure you are naming your object 'junk_drawer'" assert 'drawer_length' in __solution__, "Make sure you are naming your object 'drawer_length'" assert 'cleaned_junk_drawer' in __solution__, "Make sure you are naming your object 'cleaned_junk_drawer'" ...
# Runtime Average-case: Theta(n^2) # Runtime Best-case (already sorted): O(n) # Runtime Worst-case (reserve sorted): Theta(n^2) # In Place: Yes # Stable: Yes def insertion_sort(a): for j in range(1, len(a)): key = a[j] # start with element before and keep going back i = j - 1 whil...
def insertion_sort(a): for j in range(1, len(a)): key = a[j] i = j - 1 while i >= 0 and key < a[i]: a[i + 1] = a[i] i = i - 1 a[i + 1] = key a = [4, 6, 8, 9, 3, 5, 1] insertion_sort(a) print(a)
#!/usr/bin/env python # -*- coding: utf-8 -*- """The module contains a collection of useful algorithms written in python.""" __author__ = 'Md. Imrul Hassan' __email__ = 'mihassan@gmail.com' __version__ = '0.2.1'
"""The module contains a collection of useful algorithms written in python.""" __author__ = 'Md. Imrul Hassan' __email__ = 'mihassan@gmail.com' __version__ = '0.2.1'
# Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if not node: return None ...
class Solution: def clone_graph(self, node): if not node: return None res = undirected_graph_node(node.label) seen = {node.label: res} self.helper(node, res, seen) return res def helper(self, node, answer, seen): seen[answer.label] = answer f...
squares = [1, 4, 9, 16, 25] print(squares) print(squares[0]) #Get first value; remember index offset print(squares[-1]) #Get last value in sequence print(squares[2:4]) #Return slice of list squares.append(54) #Add new value print(squares) squares[3] = 88 #Insert new value print(squares)
squares = [1, 4, 9, 16, 25] print(squares) print(squares[0]) print(squares[-1]) print(squares[2:4]) squares.append(54) print(squares) squares[3] = 88 print(squares)
# ### Problem 3 # Given 2 lists of claim numbers, write the code to merge the 2 lists provided to produce a new list by alternating values between the 2 lists. Once the merge has been completed, print the new list of claim numbers (DO NOT just print the array variable!) # ``` # # Start with these lists # list_of_claim_...
nums1 = [2, 4, 6, 8, 10] nums2 = [1, 3, 5, 7, 9] numall = [] for x in range(0, len(nums1)): numall.append(nums1[x]) numall.append(nums2[x]) print(numall)
class OffsetMissingInIndex(Exception): pass class CouldNotFindOffset(Exception): pass class LogSizeExceeded(Exception): pass
class Offsetmissinginindex(Exception): pass class Couldnotfindoffset(Exception): pass class Logsizeexceeded(Exception): pass
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
"""Test data for Service Management GCP api responses.""" fake_project_id = 'project1' list_consumer_services_page1 = '\n{\n "services": [\n {\n "serviceName": "bigquery-json.googleapis.com",\n "producerProjectId": "google.com:ultra-current-88221"\n },\n {\n "serviceName": "cloudbilling.googleapis.com",\n "p...
print("Welcome to the F.A.T C.A.T program, this program encrypts messages using the reverse cipher method") #Prints whats in the parenteses sentence = input("What do you want to encrypt? ") #Declares a varible and stores what the user inputs final = "" i = len(sentence) -1 while(i != -1): final+= sentence[i]; i...
print('Welcome to the F.A.T C.A.T program, this program encrypts messages using the reverse cipher method') sentence = input('What do you want to encrypt? ') final = '' i = len(sentence) - 1 while i != -1: final += sentence[i] i -= 1 print(final)
def sum_series(generator, n): return sum(generator(i) for i in range(n)) def series(generator, n): return [generator(i) for i in range(n)] def search_bordered_sum_series(generator_fabric, n, left_x, right_x, border, epsilon=0.01**5): left_y = sum_series(generator_fabric(left_x), n) right_y = sum_s...
def sum_series(generator, n): return sum((generator(i) for i in range(n))) def series(generator, n): return [generator(i) for i in range(n)] def search_bordered_sum_series(generator_fabric, n, left_x, right_x, border, epsilon=0.01 ** 5): left_y = sum_series(generator_fabric(left_x), n) right_y = sum_s...
computation_config = { 'Variable': 'GV1', 'From': ['WB API'], 'files': ['GV1_WB.csv'], 'function': lambda df, var: df.groupby(['ISO']).transform(lambda x: x.rolling(5, 1).mean()),#.mean(axis=1), 'sub_variables': [ 'Adjusted net savings, including particulate emission damage (% of GNI)', ...
computation_config = {'Variable': 'GV1', 'From': ['WB API'], 'files': ['GV1_WB.csv'], 'function': lambda df, var: df.groupby(['ISO']).transform(lambda x: x.rolling(5, 1).mean()), 'sub_variables': ['Adjusted net savings, including particulate emission damage (% of GNI)'], 'Description': lambda var: f'{var[0]} 5 years ro...
# DomirScire class Animal: def __init__(self, color, number_of_legs): self.species = self.__class__.__name__ self.color = color self.number_of_legs = number_of_legs def __repr__(self): return f'{self.color} {self.species}, {self.number_of_legs} legs' class Wolf(Animal): de...
class Animal: def __init__(self, color, number_of_legs): self.species = self.__class__.__name__ self.color = color self.number_of_legs = number_of_legs def __repr__(self): return f'{self.color} {self.species}, {self.number_of_legs} legs' class Wolf(Animal): def __init__(s...
TRAIN = False USERS = { 'yuncam':'aBc1to3' }
train = False users = {'yuncam': 'aBc1to3'}
##function 'return_list' goes here def return_list(the_string): new_list = [] the_string = the_string.replace(" ",",") the_string = the_string.split(",") if len(the_string) == 1: return the_string[0] else: for x in range(len(the_string)): new_list.append(the_string[x...
def return_list(the_string): new_list = [] the_string = the_string.replace(' ', ',') the_string = the_string.split(',') if len(the_string) == 1: return the_string[0] else: for x in range(len(the_string)): new_list.append(the_string[x]) return new_list def main():...
""" [E] Given an array, find the average of all contiguous subarrays of size 'K 'in it. Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5 Output: [2.2, 2.8, 2.4, 3.6, 2.8] """ # Brute Force Approach: Time: O(n * k) space: O(1) def find_averages_of_subarrays(K, arr): result = [] for i in range(len(arr)-K+1): # find ...
""" [E] Given an array, find the average of all contiguous subarrays of size 'K 'in it. Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5 Output: [2.2, 2.8, 2.4, 3.6, 2.8] """ def find_averages_of_subarrays(K, arr): result = [] for i in range(len(arr) - K + 1): _sum = 0.0 for j in range(i, i + K): ...
# Maximum Vacation Days # Rules: # 1. You can only travel among N cities, represented by indexes from 0 to N-1. # Initially, you are in the city indexed 0 on Monday. # 2. The cities are connected by flights. The flights are represented as a N*N matrix (not necessary symmetrical), # called flights representing the...
class Solution(object): def max_vacation_days(self, flights, days): """ dp[i][j]: max number of vacation days taken at the end of week j in city i dp[i][j] = -inf no flights to city i = days[i][0] j == 0 and flights[0][i]...
class Option: OPTION_ENABLE = 256 OPTION_TX_ABORT = 1024 OPTION_HIGH_PRIORITY = 2048
class Option: option_enable = 256 option_tx_abort = 1024 option_high_priority = 2048
#BFS or Breadth First Search is a traversal algorithm for a tree or graph, where we start from the root node(for a tree) #And visit all the nodes level by level from left to right. It requires us to keep track of the chiildren of each node we visit #In a queue, so that after traversal through a level is complete, our a...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Bst: def __init__(self): self.root = None self.number_of_nodes = 0 def insert(self, data): new_node = node(data) if self.root == None: self....
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: curr_level = [cloned] while...
class Solution: def get_target_copy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: curr_level = [cloned] while curr_level: next_level = [] for node in curr_level: if node.val == target.val: return node ...
def add(x, y): """add two numbers""" return x + y def subtract(x, y): """subtrct one number from another""" return y - x def mult(x, y): """multiply two numbers""" return x * y
def add(x, y): """add two numbers""" return x + y def subtract(x, y): """subtrct one number from another""" return y - x def mult(x, y): """multiply two numbers""" return x * y
# Demo Python Tuples ''' Create Tuple With One Item To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple. ''' # One item tuple, remember the commma: thistuple = ("apple",) print(type(thistuple)) #NOT a tuple thistuple = ("apple") print(t...
""" Create Tuple With One Item To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple. """ thistuple = ('apple',) print(type(thistuple)) thistuple = 'apple' print(type(thistuple))