content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# # WAP to accept a number and display all the factors which are prime ( prime factors) user_Inp = int(input("Enter number: ")) for i in range(1, user_Inp+1): c = 0 if(user_Inp % i == 0): for j in range(1, i+1): if(i % j == 0): c += 1 if(c <= 2): print(i, ...
user__inp = int(input('Enter number: ')) for i in range(1, user_Inp + 1): c = 0 if user_Inp % i == 0: for j in range(1, i + 1): if i % j == 0: c += 1 if c <= 2: print(i, end=' ')
N, K = list(map(int, input().split(' '))) cnt = 0 while True: if N == 1: break; if N % K == 0: N /= K else: N -= 1 cnt += 1 print(cnt)
(n, k) = list(map(int, input().split(' '))) cnt = 0 while True: if N == 1: break if N % K == 0: n /= K else: n -= 1 cnt += 1 print(cnt)
# -*- coding: utf-8 -*- """ Created on Thu Mar 1 13:29:53 2018 @author: jel2 """ def xval(x,y,g,mdl,params): M=pd.DataFrame(g).join(y,how='outer').join(x,how='outer') # Y=np.array(M[list(y)]) #### if Y is two columns with one binary column then treat it as survival data # if(len(Y.shape)>1):...
""" Created on Thu Mar 1 13:29:53 2018 @author: jel2 """ def xval(x, y, g, mdl, params): m = pd.DataFrame(g).join(y, how='outer').join(x, how='outer') M['xVal'] = 0 for i in set(M.grp): ll = M.grp == i mod = ls_reg(M.loc[~ll, :].drop(['grp', 'xVal'], axis=1), params) M.loc[ll, 'xV...
class Solution: def nextLargerNodes(self, head: ListNode) -> List[int]: st = [] res = [] while head: while st and st[-1][1] < head.val: idx, v = st.pop() res[idx] = head.val st.append((len(res), head.val)) res.append(0) ...
class Solution: def next_larger_nodes(self, head: ListNode) -> List[int]: st = [] res = [] while head: while st and st[-1][1] < head.val: (idx, v) = st.pop() res[idx] = head.val st.append((len(res), head.val)) res.append(0)...
def find_matches(match_info, results): for target_match_info, obj in results: if target_match_info.equals(match_info): yield target_match_info, obj
def find_matches(match_info, results): for (target_match_info, obj) in results: if target_match_info.equals(match_info): yield (target_match_info, obj)
def test(): print('testing basic math ops') assert 1+1 == 2 assert 10-1 == 9 assert 10 / 2 == 5 assert int(100.9) == 100 print('testing bitwise ops') print(100 ^ 0xd008) assert 100 ^ 0xd008 == 53356 print( 100 & 199 ) assert (100 & 199) == 68 ## TODO fixme print('TODO fix `100 & 199 == 68`') assert 10...
def test(): print('testing basic math ops') assert 1 + 1 == 2 assert 10 - 1 == 9 assert 10 / 2 == 5 assert int(100.9) == 100 print('testing bitwise ops') print(100 ^ 53256) assert 100 ^ 53256 == 53356 print(100 & 199) assert 100 & 199 == 68 print('TODO fix `100 & 199 == 68`')...
phrase = 'Coding For All' phrase = phrase.split() abrv = phrase[0][0] + phrase[1][0] + phrase[2][0] print(abrv)
phrase = 'Coding For All' phrase = phrase.split() abrv = phrase[0][0] + phrase[1][0] + phrase[2][0] print(abrv)
def increment(a): return a+1 def decrement(a): return a-1
def increment(a): return a + 1 def decrement(a): return a - 1
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- """Molecule to atoms.""" def get_sub_molecule(molecule: list, atom: str) -> list: molecule_copy = molecule[molecule.index(atom) + 1:] sub_molecule = [] count_parent = 1 for el in molecule_copy: if el in "([{": count_parent += 1 ...
"""Molecule to atoms.""" def get_sub_molecule(molecule: list, atom: str) -> list: molecule_copy = molecule[molecule.index(atom) + 1:] sub_molecule = [] count_parent = 1 for el in molecule_copy: if el in '([{': count_parent += 1 elif el in ')]}': count_parent -= 1...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int ...
class Solution(object): def path_sum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: int """ count = self.preOrder(root, sum, {0: 1}, 0) return count def pre_order(self, root, sum, hash_map, pre_sum): if not root: re...
class Referee: def __init__(self, json_referee_info: dict) -> None: self.id = json_referee_info.get("id") self.bonuses = json_referee_info.get("bonuses") self.bonuses_total = json_referee_info.get("bonuses_total") self.email = json_referee_info.get("email") class Referrals: de...
class Referee: def __init__(self, json_referee_info: dict) -> None: self.id = json_referee_info.get('id') self.bonuses = json_referee_info.get('bonuses') self.bonuses_total = json_referee_info.get('bonuses_total') self.email = json_referee_info.get('email') class Referrals: de...
def find_the_max_sum_of_subarray(arr, K): # Input: [2, 1, 5, 1, 3, 2], k=3 # Output: 9 start_index = 0 sum_index = 0 target_sum = 0 for index, value in enumerate(arr): sum_index += value if index >= K-1: if sum_index > target_sum: target_sum = s...
def find_the_max_sum_of_subarray(arr, K): start_index = 0 sum_index = 0 target_sum = 0 for (index, value) in enumerate(arr): sum_index += value if index >= K - 1: if sum_index > target_sum: target_sum = sum_index sum_index -= arr[start_index] ...
def addDynamic(): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/addDynamic.html ----------------------------------------- addDynamic is undoable, NOT queryable, and NOT editable. Makes the "object" specified as second argument the source of an existing field or emitter specified...
def add_dynamic(): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/addDynamic.html ----------------------------------------- addDynamic is undoable, NOT queryable, and NOT editable. Makes the "object" specified as second argument the source of an existing field or emitter specifie...
for i in range(10000000): str_i = str(i) s1 = 'ABCDEFH' + str_i s2 = '123456789' + str_i result = '' x = 0 if len(s1) < len(s2): while x < len(s1): result += s1[x] + s2[x] x += 1 result += s2[x:] else: while x < len(s2): result += s...
for i in range(10000000): str_i = str(i) s1 = 'ABCDEFH' + str_i s2 = '123456789' + str_i result = '' x = 0 if len(s1) < len(s2): while x < len(s1): result += s1[x] + s2[x] x += 1 result += s2[x:] else: while x < len(s2): result += s...
class parent: counter=10 hit=15 def __init__(self): print("Parent class initialized.") def SetCounter(self, num): self.counter= num class child(parent): # child is the child class of Parent def __init__(self): print("Child class being initialized.") def SetHit(self, num2): self.hit=num2 c= child() print...
class Parent: counter = 10 hit = 15 def __init__(self): print('Parent class initialized.') def set_counter(self, num): self.counter = num class Child(parent): def __init__(self): print('Child class being initialized.') def set_hit(self, num2): self.hit = num2...
class Node: def __init__(self, data=None , next_ref=None): self.data = data self.next = next_ref class Stack: def __init__(self, data=None): self.__top= None self.__size = 0 if data: node = Node(data) self.__top = node self.__size = 1 def push(self, data): node = Node(data,self.__top) self...
class Node: def __init__(self, data=None, next_ref=None): self.data = data self.next = next_ref class Stack: def __init__(self, data=None): self.__top = None self.__size = 0 if data: node = node(data) self.__top = node self.__size = ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode) -> ListNode: value = 0 currentNode = head while currentNode!=None : node = currentNode while node.next!=None: ...
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def reverse_between(self, head: ListNode) -> ListNode: value = 0 current_node = head while currentNode != None: node = currentNode while node.next != None: ...
__title__ = 'ki' __version__ = '1.1.0' __author__ = 'Joshua Scott & Caleb Pina' __description__ = 'Python bindings and extensions for libki'
__title__ = 'ki' __version__ = '1.1.0' __author__ = 'Joshua Scott & Caleb Pina' __description__ = 'Python bindings and extensions for libki'
# filename : Graph.py # ------------------------------------------------------------------------------------ class Graph: def __init__(self, number_of_vertex, number_of_edges, is_directed = False, is_weighted = False): self.number_of_vertices = number_of_vertex self.number_of_edges = number_...
class Graph: def __init__(self, number_of_vertex, number_of_edges, is_directed=False, is_weighted=False): self.number_of_vertices = number_of_vertex self.number_of_edges = number_of_edges self.is_directed = is_directed self.is_weighted = is_weighted self.graph_list = [[] for...
""" Authors ------- Dr. Randal J. Barnes Department of Civil, Environmental, and Geo- Engineering University of Minnesota Richard Soule Source Water Protection Minnesota Department of Health Version ------- 06 May 2020 """ PROJECTNAME = 'Carlos example' TARGET = 0 NPATHS = 500 DURATION...
""" Authors ------- Dr. Randal J. Barnes Department of Civil, Environmental, and Geo- Engineering University of Minnesota Richard Soule Source Water Protection Minnesota Department of Health Version ------- 06 May 2020 """ projectname = 'Carlos example' target = 0 npaths = 500 duration =...
""" Stack data structure is optimized for quick appends (push) and removal of the last node (pop) """ class Node: """Node is a simple data structure holding information""" def __init__(self, value, node): self.__value = value self.__next = node @property def value(self): """Re...
""" Stack data structure is optimized for quick appends (push) and removal of the last node (pop) """ class Node: """Node is a simple data structure holding information""" def __init__(self, value, node): self.__value = value self.__next = node @property def value(self): """Re...
""" Module cannot be called tool_shed, because this conflicts with lib/tool_shed also at top level of path. """
""" Module cannot be called tool_shed, because this conflicts with lib/tool_shed also at top level of path. """
# -*- coding: utf-8 -*- """ Unit test package for utils. """
""" Unit test package for utils. """
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software 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 Unle...
""" Copyright 2015 SmartBear Software 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 applicable law or agreed...
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ n_s = len(s) n_star = 0 seg = [] i = len(p) - 1 while i > -1: if p[i] == '*': n_star += 1 seg.i...
class Solution(object): def is_match(self, s, p): """ :type s: str :type p: str :rtype: bool """ n_s = len(s) n_star = 0 seg = [] i = len(p) - 1 while i > -1: if p[i] == '*': n_star += 1 seg....
class SimulationNotFinished(Exception): def __init__(self, keyword): super().__init__( "Run simulation first before using `{}` method.".format(keyword) ) class DailyReturnsNotRegistered(Exception): def __init__(self): super().__init__("Daily returns data have not yet regist...
class Simulationnotfinished(Exception): def __init__(self, keyword): super().__init__('Run simulation first before using `{}` method.'.format(keyword)) class Dailyreturnsnotregistered(Exception): def __init__(self): super().__init__('Daily returns data have not yet registered.')
""" SOLUTIONS ROBUST ARE ON GITHUB RAFFSON (OPLEIDER) """ mood = input("What is your mood? :") mood = mood.lower() if mood == "happy": print("It is great to see you happy!") elif mood == "nervous": print("Take a deep breath 3 times.") elif mood == "sad": print("Cheer up, mate!") elif mood == "excited": ...
""" SOLUTIONS ROBUST ARE ON GITHUB RAFFSON (OPLEIDER) """ mood = input('What is your mood? :') mood = mood.lower() if mood == 'happy': print('It is great to see you happy!') elif mood == 'nervous': print('Take a deep breath 3 times.') elif mood == 'sad': print('Cheer up, mate!') elif mood == 'excited': ...
class FilterGroupController: def __init__(self, filterGroups): self.filterGroups = filterGroups def sendCoT(self, CoT): pass def addUser(self, clientInformation): pass def removeUser(self, clientInformation): pass
class Filtergroupcontroller: def __init__(self, filterGroups): self.filterGroups = filterGroups def send_co_t(self, CoT): pass def add_user(self, clientInformation): pass def remove_user(self, clientInformation): pass
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: prefix, n, res, left = [0 for _ in range(len(A) + 1)], len(A) + 1, 0, 0 for i in range(1, n): prefix[i] = prefix[i - 1] + A[i - 1] for i in range(L + M, n): left = max(left, prefix[i - ...
class Solution: def max_sum_two_no_overlap(self, A: List[int], L: int, M: int) -> int: (prefix, n, res, left) = ([0 for _ in range(len(A) + 1)], len(A) + 1, 0, 0) for i in range(1, n): prefix[i] = prefix[i - 1] + A[i - 1] for i in range(L + M, n): left = max(left, pr...
numbers = """ 123.456,789|012,345+678 901 """ print(numbers.split()) print(numbers.split(",")) separators = ".,|+ " op = "".join(char if char not in separators else " " for char in numbers).split() print(op)
numbers = '\n123.456,789|012,345+678 901\n' print(numbers.split()) print(numbers.split(',')) separators = '.,|+ ' op = ''.join((char if char not in separators else ' ' for char in numbers)).split() print(op)
valores = input().split() valores = list(map(int,valores)) A, B = valores if (B%A == 0) or (A%B == 0): print('Sao Multiplos') else: print('Nao sao Multiplos')
valores = input().split() valores = list(map(int, valores)) (a, b) = valores if B % A == 0 or A % B == 0: print('Sao Multiplos') else: print('Nao sao Multiplos')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ extract statistics from github repos """ __version__ = "1.0" name = "github_stats"
""" extract statistics from github repos """ __version__ = '1.0' name = 'github_stats'
def search(str, lst, size): for i in range(0, size): if lst[i] == str: return i return -1 print(search("a", ["a", "b", "c"], 3)) print(search("b", ["a", "b", "c"], 3)) print(search("c", ["a", "b", "c"], 3)) print(search("d", ["a", "b", "c"], 3))
def search(str, lst, size): for i in range(0, size): if lst[i] == str: return i return -1 print(search('a', ['a', 'b', 'c'], 3)) print(search('b', ['a', 'b', 'c'], 3)) print(search('c', ['a', 'b', 'c'], 3)) print(search('d', ['a', 'b', 'c'], 3))
class Renderer: def __init__(self): self.render_queue = Queue() """ the renderer stores all of the shapes and renders them on the screen inside the view the render_queue [node] -> [node] -> [node] """
class Renderer: def __init__(self): self.render_queue = queue() '\n the renderer stores all of the shapes\n and renders them on the screen inside the view\n\n\n the render_queue\n [node] -> [node] -> [node]\n'
#!/usr/bin/env python3 def divisor(n): num = 0 i = 1 while i * i <= n: if n % i == 0: num += 2 i += 1 if i * i == n: num -= 1 return num def main(): i = 1 sum = 0 while True: sum = divisor(i*(i+1)/2) if sum >= 500: pr...
def divisor(n): num = 0 i = 1 while i * i <= n: if n % i == 0: num += 2 i += 1 if i * i == n: num -= 1 return num def main(): i = 1 sum = 0 while True: sum = divisor(i * (i + 1) / 2) if sum >= 500: print((sum, i * (i + 1) /...
# Individuals Script Runs Y = True N = False topics_run = Y groups_run = Y events_and_members_run = Y events_run = Y members_run = Y rsvps_run = Y # Topics searches by keyword query # topics = ['innovation'] topics = ['startups','entrepreneurship','innovation'] topics_per_page=20 # topics_offset=0 n/a # How many t...
y = True n = False topics_run = Y groups_run = Y events_and_members_run = Y events_run = Y members_run = Y rsvps_run = Y topics = ['startups', 'entrepreneurship', 'innovation'] topics_per_page = 20 topic_order = 'ASC' topic_limit = 100 groups_order = 'DESC' groups_limit = 1000 groups_per_page = 200 groups_offset = 0 ev...
class A: def __init__(self, a): self.a = a a = A(0) b = a print(b.a) b = A(5) print(a.a) print(b.a)
class A: def __init__(self, a): self.a = a a = a(0) b = a print(b.a) b = a(5) print(a.a) print(b.a)
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() i, j, boats = 0, len(people) - 1, 0 while i <= j: boats += 1 if people[i] + people[j] <= limit: i += 1 j -= 1 return boats
class Solution: def num_rescue_boats(self, people: List[int], limit: int) -> int: people.sort() (i, j, boats) = (0, len(people) - 1, 0) while i <= j: boats += 1 if people[i] + people[j] <= limit: i += 1 j -= 1 return boats
class Solution: def findTheDifference(self, s: str, t: str) -> str: count = Counter(s) for i, c in enumerate(t): count[c] -= 1 if count[c] == -1: return c
class Solution: def find_the_difference(self, s: str, t: str) -> str: count = counter(s) for (i, c) in enumerate(t): count[c] -= 1 if count[c] == -1: return c
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 1 00:49:46 2019 """ # simple binary detection script config = { ## model 'num_classes': 1, 'classes': ['background', 'car',], 'img_size': 416, ## train 'weight_decay': 0.0001, 'image...
""" Created on Mon Jul 1 00:49:46 2019 """ config = {'num_classes': 1, 'classes': ['background', 'car'], 'img_size': 416, 'weight_decay': 0.0001, 'images_root': './data/images', 'train_path': './data/train.txt', 'test_path': './data/test.txt', 'ckpt_name': 'checkpoint.pth', 'alpha': 0.25, 'gamma': 2.0, 'conf_thres': ...
class Solution(object): def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ P = set() for n in nums: P = {(m+n) % k if k else m+n for m in P} if 0 in P: return True P.add(n) return False
class Solution(object): def check_subarray_sum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ p = set() for n in nums: p = {(m + n) % k if k else m + n for m in P} if 0 in P: return True P.add(n) re...
#!/usr/bin/env python class Empire(dict): ''' Methods for updating/viewing Empirees ''' def __init__(self, Empire_dict): super(Empire, self).__init__() self.update(Empire_dict)
class Empire(dict): """ Methods for updating/viewing Empirees """ def __init__(self, Empire_dict): super(Empire, self).__init__() self.update(Empire_dict)
class ParserError(Exception): pass class ReceiptNotFound(ParserError): pass
class Parsererror(Exception): pass class Receiptnotfound(ParserError): pass
text = input().split(", ") valid_names = "" for word in text: if 3 <= len(word) <= 16: if word.isalnum() or "-" in word or "_" in word: valid_names = word print(valid_names)
text = input().split(', ') valid_names = '' for word in text: if 3 <= len(word) <= 16: if word.isalnum() or '-' in word or '_' in word: valid_names = word print(valid_names)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) == 0: return 0 temp = dict() i = 0 max_dis = 0 for k in range(len(s)): if s[k] in temp: i = max(temp[s[k]] + 1, i) temp[s[k]] = k max_d...
class Solution: def length_of_longest_substring(self, s: str) -> int: if len(s) == 0: return 0 temp = dict() i = 0 max_dis = 0 for k in range(len(s)): if s[k] in temp: i = max(temp[s[k]] + 1, i) temp[s[k]] = k m...
""" Write Number in Expanded Form You will be given a number and you will need to return it as a string in Expanded Form. For example: expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2' expanded_form(70304) # Should return '70000 + 300 + 4' NOTE: All numbers will be whole numbers g...
""" Write Number in Expanded Form You will be given a number and you will need to return it as a string in Expanded Form. For example: expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2' expanded_form(70304) # Should return '70000 + 300 + 4' NOTE: All numbers will be whole numbers g...
#!/usr/bin/env python3 sum = 0 prod = 1 for i in range(1,11): sum += i prod *= i print('sum: %d' % sum) print('prod: %d' % prod)
sum = 0 prod = 1 for i in range(1, 11): sum += i prod *= i print('sum: %d' % sum) print('prod: %d' % prod)
# my name is abhishek. all are comments # print("hie") # ijko """ file = module in python """ ''' data type int,float,string,boolean,none- says particular datatype as it doe not have value actually false data structure - list, dictionary. ''' # everything in python is call by reference, what is done after delete a f...
""" file = module in python """ '\ndata type int,float,string,boolean,none- says particular datatype as it doe not have value actually false\ndata structure - list, dictionary.\n'
#No job instantiation, just an interface that could be implemented with a priority queue or map. class Executor(): def __init__(self, IP, port): self.server_info = (IP, port) #server stores info of jobs in centralized location, so should manage encoding def submit(self, job_name, siz...
class Executor: def __init__(self, IP, port): self.server_info = (IP, port) def submit(self, job_name, size, priority=1, retries=0, send_data=True): new_future = future(function_name, self.server_info) self.server_info return new_future def shutdown(self, wait=True): ...
#!/usr/bin/env python3 """Super class for all malwares. """ class Malware: """Defines the lifetime of the malware's domains. The lifetime is expressed in seconds. 0 means that the malware doesn't implement a DGA. Returns: The lifetime of the malware's domains. """ @classmethod def domainsLifetime(...
"""Super class for all malwares. """ class Malware: """Defines the lifetime of the malware's domains. The lifetime is expressed in seconds. 0 means that the malware doesn't implement a DGA. Returns: The lifetime of the malware's domains. """ @classmethod def domains_lifetime(self): ...
""" Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. Example: Input: text = "nlaebolko" Output: 1 Examp...
""" Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. Example: Input: text = "nlaebolko" Output: 1 Examp...
def block_width(block): try: return block.index('\n') except ValueError: return len(block) def stack_str_blocks(blocks): """Takes a list of multiline strings, and stacks them horizontally. For example, given 'aaa\naaa' and 'bbbb\nbbbb', it returns 'aaa bbbb\naaa bbbb'. As in: ...
def block_width(block): try: return block.index('\n') except ValueError: return len(block) def stack_str_blocks(blocks): """Takes a list of multiline strings, and stacks them horizontally. For example, given 'aaa aaa' and 'bbbb bbbb', it returns 'aaa bbbb aaa bbbb'. As in: 'a...
# -*- coding: utf-8 -*- """Top-level package for pistis.""" __author__ = """Michael Benjamin Hall""" __email__ = 'mbhall88@gmail.com' __version__ = '0.1.0'
"""Top-level package for pistis.""" __author__ = 'Michael Benjamin Hall' __email__ = 'mbhall88@gmail.com' __version__ = '0.1.0'
def binary_search(target, num_list): if not target: raise Exception if not num_list: raise Exception left, right = 0, len(num_list)-1 mid = left + (right - left)//2 while left <= right: mid = left + (right - left)//2 if num_list[mid] == target: return T...
def binary_search(target, num_list): if not target: raise Exception if not num_list: raise Exception (left, right) = (0, len(num_list) - 1) mid = left + (right - left) // 2 while left <= right: mid = left + (right - left) // 2 if num_list[mid] == target: r...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : __init__.py @Time : 2022/2/1 6:51 @Author : Tim Chen @Version : 0.0.1 @Contact : cscomicanimation@gmail.com @License : MIT @Desc : None """ # here put the import lib
""" @File : __init__.py @Time : 2022/2/1 6:51 @Author : Tim Chen @Version : 0.0.1 @Contact : cscomicanimation@gmail.com @License : MIT @Desc : None """
def rotateMatrixby90(ipMat, size): opMat = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): opMat[j][i] = ipMat[i][j] return opMat def reverseMatrix(ipMat, size): opMat = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j i...
def rotate_matrixby90(ipMat, size): op_mat = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): opMat[j][i] = ipMat[i][j] return opMat def reverse_matrix(ipMat, size): op_mat = [[0 for i in range(size)] for j in range(size)] for i in rang...
""" Based on C code from: http://nlp.cs.nyu.edu/evalb/ """ def bracketing(ts): buf = range((len(ts)+1)/2 + 1) buf = list(reversed(zip(buf[:-1], buf[1:]))) stack = [] ret = [] for t in ts: if t == 0: stack.append(buf.pop()) elif t == 1: R, L = stack.pop(), st...
""" Based on C code from: http://nlp.cs.nyu.edu/evalb/ """ def bracketing(ts): buf = range((len(ts) + 1) / 2 + 1) buf = list(reversed(zip(buf[:-1], buf[1:]))) stack = [] ret = [] for t in ts: if t == 0: stack.append(buf.pop()) elif t == 1: (r, l) = (stack.pop...
#!/usr/bin/env python #Modify once acccording to your setup WORKSPACE = "/Users/Gautam/AndroidStudioProjects/AndroidGPSTracking" #Modify the below lines for each project PROJECT_NAME = "AndroidGPSTracking" #Modify if using DB DB_NAME = "mainTuple" TABLE_NAME = "footRecords" MAIN_ACTIVITY = "TrackActivity" #DO NOT MO...
workspace = '/Users/Gautam/AndroidStudioProjects/AndroidGPSTracking' project_name = 'AndroidGPSTracking' db_name = 'mainTuple' table_name = 'footRecords' main_activity = 'TrackActivity' prefix = 'com.example.gpstracking'
class Solution(object): def removeKdigits(self, num, k): if len(num) <= k: return "0" ret = [] for i in range(len(num)): while k > 0 and ret and ret[-1] > num[i]: ret.pop() k-=1 ret.append(num[i]) while k >...
class Solution(object): def remove_kdigits(self, num, k): if len(num) <= k: return '0' ret = [] for i in range(len(num)): while k > 0 and ret and (ret[-1] > num[i]): ret.pop() k -= 1 ret.append(num[i]) while k > 0 a...
class TooShort(Exception): pass class Stale(Exception): pass class Incomplete(Exception): pass class Boring(Exception): pass
class Tooshort(Exception): pass class Stale(Exception): pass class Incomplete(Exception): pass class Boring(Exception): pass
class BasePipeline(object): """Main end-point to run the pipeline processes""" def __init__(self, config): self.config = config def initialize_data(self): """ Initialize dataset: loading, preprocess metadata""" raise NotImplementedError def extract_feature(self): raise...
class Basepipeline(object): """Main end-point to run the pipeline processes""" def __init__(self, config): self.config = config def initialize_data(self): """ Initialize dataset: loading, preprocess metadata""" raise NotImplementedError def extract_feature(self): raise...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class ExampleData(object): def __init__( self, question: str = None, is_multi_select: bool = False, option1: str = None, option2: str = None, option3: str = None, ): ...
class Exampledata(object): def __init__(self, question: str=None, is_multi_select: bool=False, option1: str=None, option2: str=None, option3: str=None): self.question = question self.is_multi_select = is_multi_select self.option1 = option1 self.option2 = option2 self.option3...
# # PySNMP MIB module CISCO-CEF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CEF-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:53:12 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) ...
"""Utilities for speech recognition.""" class TranscriptMap(object): """An abstract class representing a map from transcripts to labels. All other datasets should subclass it. All subclasses should override ``trans2label``. """ def trans2label(self, transcript): """Convert a transcript t...
"""Utilities for speech recognition.""" class Transcriptmap(object): """An abstract class representing a map from transcripts to labels. All other datasets should subclass it. All subclasses should override ``trans2label``. """ def trans2label(self, transcript): """Convert a transcript to...
arr = [[1, 2, 3, 12], [4, 5, 6, 45], [7, 8, 9, 78]] x = 3 print("start") w = len(arr) h = len(arr[0]) i = 0 j = 0 while i < w and j < h and arr[i][j] < x: ib = i ie = w - 1 i2 = -1 while ib < ie: i2n = (ie - ib) // 2 if i2 == i2n: break i2 = i2n print("i2 ", i2, ib, ie) if arr[i2...
arr = [[1, 2, 3, 12], [4, 5, 6, 45], [7, 8, 9, 78]] x = 3 print('start') w = len(arr) h = len(arr[0]) i = 0 j = 0 while i < w and j < h and (arr[i][j] < x): ib = i ie = w - 1 i2 = -1 while ib < ie: i2n = (ie - ib) // 2 if i2 == i2n: break i2 = i2n print('i2 ',...
""" Copyright 2016 Pawel Bartusiak 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 applicable law or agreed to in writing, softwar...
""" Copyright 2016 Pawel Bartusiak 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 applicable law or agreed to in writing, softwar...
"""Skinny, measuring nudity and skin percentage in images. This module measures the skin coefficient of images in order to determine if the people in it are nude or not. Example: The module is a twistd plugin so it can be run by:: $ twistd -n skinny Flags: --port -p (int): Port number for the plugin...
"""Skinny, measuring nudity and skin percentage in images. This module measures the skin coefficient of images in order to determine if the people in it are nude or not. Example: The module is a twistd plugin so it can be run by:: $ twistd -n skinny Flags: --port -p (int): Port number for the plugin...
''' Min Depth of Binary Tree Asked in: Facebook, Amazon https://www.interviewbit.com/problems/min-depth-of-binary-tree/ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. NOTE : The path has to end on a lea...
""" Min Depth of Binary Tree Asked in: Facebook, Amazon https://www.interviewbit.com/problems/min-depth-of-binary-tree/ Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. NOTE : The path has to end on a lea...
def selection_sort(nums): # This value of i corresponds to how many values were sorted for i in range(len(nums)): # We assume that the first item of the unsorted segment is the smallest lowest_value_index = i # This loop iterates over the unsorted items for j in range(i + 1, len(...
def selection_sort(nums): for i in range(len(nums)): lowest_value_index = i for j in range(i + 1, len(nums)): if nums[j] < nums[lowest_value_index]: lowest_value_index = j (nums[i], nums[lowest_value_index]) = (nums[lowest_value_index], nums[i]) random_list_of_num...
# Q: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000, Find the product abc. def main(): print (find_abc(1000)) # We do this in a function to avoid ...
def main(): print(find_abc(1000)) def find_abc(total): for a in range(1, total - 2): for b in range(a, total - 2): c = total - a - b if a * a + b * b == c * c: return a * b * c if __name__ == '__main__': main()
annual_salary = float(input('Enter your annual salary: ')) portion_saved = float(input('Enter the percent of your salary to save, as a ' 'decimal: ')) total_cost = float(input('Enter cost of your dream home: ')) portion_down_payment = 0.25 current_savings = 0 r = 0.04 months = 0 portion_mon...
annual_salary = float(input('Enter your annual salary: ')) portion_saved = float(input('Enter the percent of your salary to save, as a decimal: ')) total_cost = float(input('Enter cost of your dream home: ')) portion_down_payment = 0.25 current_savings = 0 r = 0.04 months = 0 portion_monthly_salary = portion_saved * an...
def greet(name): get_greet = f"Hi, {name}" return get_greet greeting = greet("Ahmed") print(greeting)
def greet(name): get_greet = f'Hi, {name}' return get_greet greeting = greet('Ahmed') print(greeting)
def submission_choice(assignment, user_id, subs): """ If a student has multiple submissions, interactively prompt the user to choose one """ # If they have multiple submissions, make them choose if len(subs) > 1: print("{0} submissions found for {1}, choose one:\n" .forma...
def submission_choice(assignment, user_id, subs): """ If a student has multiple submissions, interactively prompt the user to choose one """ if len(subs) > 1: print('{0} submissions found for {1}, choose one:\n'.format(len(subs), user_id)) i = 1 print('Index\tCreated') ...
def removeElement(nums, val): newArray = [n for n in nums if n != val] print(newArray) print(len(newArray))
def remove_element(nums, val): new_array = [n for n in nums if n != val] print(newArray) print(len(newArray))
class Node: # Constructor to create a new node def __init__(self, data): self.data = data # Pointer to data self.next = None # Initialize next as null def deleteNode(head, position): if head is None: return head elif position == 0: return head.next prev_node ...
class Node: def __init__(self, data): self.data = data self.next = None def delete_node(head, position): if head is None: return head elif position == 0: return head.next prev_node = head current_node = head current_position = 0 while current_position < posi...
# -*- coding: utf-8 -*- L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] print(L[0][0]) print(L[1][1]) print(L[2][2]) sum = 0 for x in range(101): sum = sum + x print(sum) sum1 = 0 n = 99 while n>0: sum1 = sum1 + n n = n -2 print(sum1...
l = [['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa']] print(L[0][0]) print(L[1][1]) print(L[2][2]) sum = 0 for x in range(101): sum = sum + x print(sum) sum1 = 0 n = 99 while n > 0: sum1 = sum1 + n n = n - 2 print(sum1) l = ['Bart', 'Lisa', 'Adam'] for name in L...
ori_file = '/home/unaguo/hanson/data/landmark/WFLW191104/train_data/300W_LP.txt' save_file = '/home/unaguo/hanson/data/landmark/WFLW191104/train_data/300W_LP1.txt' lable = '0' ori_lines = [] with open(ori_file, 'r')as f: ori_lines = f.readlines() with open(save_file, 'w')as f: for line in ori_lines: l...
ori_file = '/home/unaguo/hanson/data/landmark/WFLW191104/train_data/300W_LP.txt' save_file = '/home/unaguo/hanson/data/landmark/WFLW191104/train_data/300W_LP1.txt' lable = '0' ori_lines = [] with open(ori_file, 'r') as f: ori_lines = f.readlines() with open(save_file, 'w') as f: for line in ori_lines: l...
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================== # # File name: test_console_outputs # Author: threeheadedknight@protonmail.com # Date created: 30.06.2018 17:36 # Python Version: 3.7 # # ====================================================== # https://www.c...
sample_output_linux_syntax_1 = '\neth0 Link encap:Ethernet HWaddr 09:00:12:90:e3:e5\n inet addr:192.168.1.29 Bcast:192.168.1.255 Mask:255.255.255.0\n inet6 addr: fe80::a00:27ff:fe70:e3f5/64 Scope:Link\n UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1\n RX packets:54071 erro...
"""Defines the `graalvm_native_image_cc_library` macro, which is a helper macro for declaring a `graalvm_native_image_library` rule and wraping its outputs in appropriate rules from `@rules_cc`. """ load( "@dwtj_rules_java//experimental/graalvm:rules/graalvm_native_image_library/defs.bzl", "graalvm_native_imag...
"""Defines the `graalvm_native_image_cc_library` macro, which is a helper macro for declaring a `graalvm_native_image_library` rule and wraping its outputs in appropriate rules from `@rules_cc`. """ load('@dwtj_rules_java//experimental/graalvm:rules/graalvm_native_image_library/defs.bzl', 'graalvm_native_image_library'...
""" Scripts to parse and convert LAMMPS log files. """ class LogFileReader: def __init__(self, filename): """ Attributes ---------- runs : List of the run objects Todo ---- rigid bodies not implemented ridig body integrator m...
""" Scripts to parse and convert LAMMPS log files. """ class Logfilereader: def __init__(self, filename): """ Attributes ---------- runs : List of the run objects Todo ---- rigid bodies not implemented ridig body integrator ...
class QueryParams: def _append_query_list(query_list, key, values): if isinstance(values, list): for value in values: QueryParams._append_query_list(query_list, key, value) elif isinstance(values, bool): if values == True: QueryParams._...
class Queryparams: def _append_query_list(query_list, key, values): if isinstance(values, list): for value in values: QueryParams._append_query_list(query_list, key, value) elif isinstance(values, bool): if values == True: QueryParams._append_...
def partition(arr, low, high): i = low -1 pivot = arr[high] for j in range(low, high): if arr[j] < pivot: i+=1 arr[i], arr[j] =arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return i+1 def quicksort(arr, low,high): if low < high: pi = partition(...
def partition(arr, low, high): i = low - 1 pivot = arr[high] for j in range(low, high): if arr[j] < pivot: i += 1 (arr[i], arr[j]) = (arr[j], arr[i]) (arr[i + 1], arr[high]) = (arr[high], arr[i + 1]) return i + 1 def quicksort(arr, low, high): if low < high: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-07-07 12:07:46 # @Author : Lewis Tian (taseikyo@gmail.com) # @Link : github.com/taseikyo # @Version : Python3.7 # https://projecteuler.net/problem=1 def main(): return sum([i for i in range(1, 1000) if (i % 3 == 0) or (i % 5 == 0)]) if __name_...
def main(): return sum([i for i in range(1, 1000) if i % 3 == 0 or i % 5 == 0]) if __name__ == '__main__': print(main())
def get_landscape(region): """Takes the region and returns the correct landscape name Args: region (str): a AWS region name, such as 'eu-west-1' Returns: String """ return { 'us-east-1': 'na', 'eu-central-1': 'eu', 'eu-west-1': 'uk' }.get(region, 'eu') ...
def get_landscape(region): """Takes the region and returns the correct landscape name Args: region (str): a AWS region name, such as 'eu-west-1' Returns: String """ return {'us-east-1': 'na', 'eu-central-1': 'eu', 'eu-west-1': 'uk'}.get(region, 'eu') def get_environment(env): ...
def line(a, b): def para(x): return a * x + b return para def count(x=0): def incre(): nonlocal x x += 1 return x return incre def my_avg(): data = list() def add(num): data.append(num) return sum(data)/len(data) return add if __name__ =...
def line(a, b): def para(x): return a * x + b return para def count(x=0): def incre(): nonlocal x x += 1 return x return incre def my_avg(): data = list() def add(num): data.append(num) return sum(data) / len(data) return add if __name__ =...
class Solution: def monotoneIncreasingDigits(self, n: int) -> int: if n < 10: return n break_point = None digits = [int(el) for el in str(n)] for i in range(len(digits) - 1): if digits[i] > digits[i + 1]: break_point = i break ...
class Solution: def monotone_increasing_digits(self, n: int) -> int: if n < 10: return n break_point = None digits = [int(el) for el in str(n)] for i in range(len(digits) - 1): if digits[i] > digits[i + 1]: break_point = i brea...
"""Class for handling strings""" def str2bin(msg): """Convert a binary string into a 16 bit binary message.""" assert isinstance(msg, bytes), 'must give a byte obj' return ''.join([bin(c)[2:].zfill(16) for c in msg]).encode() def bin2str(binary): """Convert biary 16 bit binary message into a string ...
"""Class for handling strings""" def str2bin(msg): """Convert a binary string into a 16 bit binary message.""" assert isinstance(msg, bytes), 'must give a byte obj' return ''.join([bin(c)[2:].zfill(16) for c in msg]).encode() def bin2str(binary): """Convert biary 16 bit binary message into a string of...
begin = """#include "riscv_test.h" RVTEST_CODE_BEGIN """ middle = """ RVTEST_PASS RVTEST_CODE_END .data RVTEST_DATA_BEGIN""" end = """RVTEST_DATA_END""" put_str = """la a1, str{} jal put_str la a1, str_crlf jal put_str """ dot_string = '''str{}: .string "{:x}"''' num = 10 print(begin) for i in range(num): ...
begin = '#include "riscv_test.h"\nRVTEST_CODE_BEGIN\n' middle = '\nRVTEST_PASS\n\nRVTEST_CODE_END\n\n.data\nRVTEST_DATA_BEGIN' end = 'RVTEST_DATA_END' put_str = 'la a1, str{}\njal put_str\nla a1, str_crlf\njal put_str\n' dot_string = 'str{}:\n .string "{:x}"' num = 10 print(begin) for i in range(num): print(put_...
crypt_words = input().split() for word in crypt_words: first_number = "" second_part = "" for letter in word: if 48 <= ord(letter) <= 57: first_number += letter else: second_part += letter first_letter = chr(int(first_number)) half = first_letter + second_par...
crypt_words = input().split() for word in crypt_words: first_number = '' second_part = '' for letter in word: if 48 <= ord(letter) <= 57: first_number += letter else: second_part += letter first_letter = chr(int(first_number)) half = first_letter + second_part...
class ExportBase: """ Base class to be inherited from other modules to export from the online model. It just provides that in writeLine of LineContainer Module always an event handler function is called """ def __init__(self): self.switch = 0 self.path = '' self.avoidPreset =...
class Exportbase: """ Base class to be inherited from other modules to export from the online model. It just provides that in writeLine of LineContainer Module always an event handler function is called """ def __init__(self): self.switch = 0 self.path = '' self.avoidPreset ...
PDAC_MODES = { "debug" : { "session-id" : "debug", "sources" : { "audio" : { "active" : False }, "video" : { "active" : True }, "heartrate" : { "active" : False }, }, "inference" : None, "transform" : False, "sinks" : { ...
pdac_modes = {'debug': {'session-id': 'debug', 'sources': {'audio': {'active': False}, 'video': {'active': True}, 'heartrate': {'active': False}}, 'inference': None, 'transform': False, 'sinks': {'rstp': {'active': True}, 'file': {'active': False}, 'window': {'active': False}}}, 'rtsp-only': {'session-id': 'live', 'sou...
# error lib? def typeError(expected, value): raise TypeError('expected \n |> %s \n but found \n |> %s' % (expected, type(value)))
def type_error(expected, value): raise type_error('expected \n |> %s \n but found \n |> %s' % (expected, type(value)))
n = int(input()) ar = list(map(int, input().split())) print(ar.count(max(ar)))
n = int(input()) ar = list(map(int, input().split())) print(ar.count(max(ar)))
def main(): name = "John Doe" age = 40 print("The user's name is", name, "and his/her age is", age, end=".\n") print("Next year he/she will be", age+1, "years old.", end="\n\n") print("The characters of the user's name are:") for i in range(len(name)): print(name[i].upper(), end=" ")...
def main(): name = 'John Doe' age = 40 print("The user's name is", name, 'and his/her age is', age, end='.\n') print('Next year he/she will be', age + 1, 'years old.', end='\n\n') print("The characters of the user's name are:") for i in range(len(name)): print(name[i].upper(), end=' ') ...
a = input() b = int(input()) def calculate_price(product, qty): PRICE_LIST = { "coffee": 1.50, "water": 1.00, "coke": 1.40, "snacks": 2.00 } return '{:.2f}'.format(PRICE_LIST[product] * qty) print(calculate_price(a, b))
a = input() b = int(input()) def calculate_price(product, qty): price_list = {'coffee': 1.5, 'water': 1.0, 'coke': 1.4, 'snacks': 2.0} return '{:.2f}'.format(PRICE_LIST[product] * qty) print(calculate_price(a, b))
class JsonRPCError(Exception): def __init__(self, request_id, code, message, data, is_notification=False): super().__init__(message) self.request_id = request_id self.code = code self.message = message self.data = data self.is_notification = is_notification def f...
class Jsonrpcerror(Exception): def __init__(self, request_id, code, message, data, is_notification=False): super().__init__(message) self.request_id = request_id self.code = code self.message = message self.data = data self.is_notification = is_notification def ...
# # Sets (kopas) # # unordered # # unique items # # use: get rid of duplicates, membership testing # # https://docs.python.org/3/tutorial/datastructures.html#sets # # https://realpython.com/python-sets/ # chars = set("abracadabra") # you pass an iterable to set(iterablehere) # print(chars) # print(len(chars)) # print...
numbers = set(range(12)) print(numbers) n3_7 = set(range(3, 8)) print(n3_7) n5_9 = set(range(5, 10)) print(n5_9) print(n3_7 | n5_9) print(n3_7.union(n5_9)) n3_9 = n3_7 | n5_9 print(n3_9) n5_7 = n3_7 & n5_9 print(n3_7.intersection(n5_9)) print(n5_7) n3_4 = n3_7 - n5_9 print(n3_4) n8_9 = n5_9 - n3_7 print(n8_9, n5_9.diff...
def menu(): """ Handles the displaying of the main menu """ print('// Main Menu: ') print('1. Teams') print('2. Players') print('0. Exit') def teams_menu(): """ Handles the displaying of the teams menu """ print('// Teams Menu: ') print('1. Display basic team info') print('2. Displa...
def menu(): """ Handles the displaying of the main menu """ print('// Main Menu: ') print('1. Teams') print('2. Players') print('0. Exit') def teams_menu(): """ Handles the displaying of the teams menu """ print('// Teams Menu: ') print('1. Display basic team info') print("2. Displa...
class Skill: def __init__(self, skill_data: dict): self.id = skill_data['id'] self.name = skill_data['skill_name'] self.explain = skill_data['explain'] self.en_explain = skill_data['explain_en'] self.skill_type = skill_data['skill_type'] self.judge_type = skill_data[...
class Skill: def __init__(self, skill_data: dict): self.id = skill_data['id'] self.name = skill_data['skill_name'] self.explain = skill_data['explain'] self.en_explain = skill_data['explain_en'] self.skill_type = skill_data['skill_type'] self.judge_type = skill_data[...
#!/usr/bin/env python # -*- coding: utf-8 -*- spinMultiplicity = 2 energy = { 'BMK/cbsb7': GaussianLog('CH3bmk.log'), 'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('CH3bmk_f12.out'), } frequencies = GaussianLog('CH3bmkfreq.log') rotors = []
spin_multiplicity = 2 energy = {'BMK/cbsb7': gaussian_log('CH3bmk.log'), 'CCSD(T)-F12/cc-pVTZ-F12': molpro_log('CH3bmk_f12.out')} frequencies = gaussian_log('CH3bmkfreq.log') rotors = []