content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: dummy = ListNode(None) dummy.next = head p = dummy while p.next: ...
class Solution: def delete_duplicates(self, head: ListNode) -> ListNode: dummy = list_node(None) dummy.next = head p = dummy while p.next: cur = p.next nxt = cur.next while nxt and cur.val == nxt.val: cur = cur.next ...
# -*- coding: utf-8 -*- ftx = { 'apiKey':"your_api_key_here" , 'secret':"your_api_secret_here", }
ftx = {'apiKey': 'your_api_key_here', 'secret': 'your_api_secret_here'}
# The location of the extracted scilab_for_xcos_on_cloud. This can be either # relative to SendLog.py or an absolute path. SCILAB_DIR = '../scilab_for_xcos_on_cloud' # The location to keep the flask session data on server. FLASKSESSIONDIR = '/tmp/flask-sessiondir' # The location to keep the session data on server. SE...
scilab_dir = '../scilab_for_xcos_on_cloud' flasksessiondir = '/tmp/flask-sessiondir' sessiondir = '/tmp/sessiondir' xcossourcedir = '' http_server_host = '127.0.0.1' http_server_port = 8001 db_host = '127.0.0.1' db_user = 'scilab' db_pass = '' db_name = 'scilab' db_port = 3306 query_category = "SELECT DISTINCT(loc.id),...
class ApiError(Exception): pass class WrongToken(ApiError): pass class PermissionError(ApiError): pass
class Apierror(Exception): pass class Wrongtoken(ApiError): pass class Permissionerror(ApiError): pass
def solve(A): T = [None]*len(A) prev = [None]*len( A) for i in range(len(A)): T[i] = 1 prev[i] = -1 for j in range(i): if A[j] < A[i] and T[i] < T[j]+1: T[i] = T[j]+1 return max(T[i] for i in range(len(A))) if __name__ == '_...
def solve(A): t = [None] * len(A) prev = [None] * len(A) for i in range(len(A)): T[i] = 1 prev[i] = -1 for j in range(i): if A[j] < A[i] and T[i] < T[j] + 1: T[i] = T[j] + 1 return max((T[i] for i in range(len(A)))) if __name__ == '__main__': a = [...
""" A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles. """ def word_search(documents, keyword): # list holds the indices of matching documents indices = [] # ...
""" A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles. """ def word_search(documents, keyword): indices = [] for (i, doc) in enumerate(documents): tokens ...
while True: numero= int(input("Escribir un numero= ")) if numero%2 == 0: print("El numero es par") else: print("El numero es impar")
while True: numero = int(input('Escribir un numero= ')) if numero % 2 == 0: print('El numero es par') else: print('El numero es impar')
# Natural Language Toolkit: code_search_documents def raw(file): contents = open(file).read() contents = re.sub(r'<.*?>', ' ', contents) contents = re.sub('\s+', ' ', contents) return contents def snippet(doc, term): text = ' '*30 + raw(doc) + ' '*30 pos = text.index(term) return text[pos-...
def raw(file): contents = open(file).read() contents = re.sub('<.*?>', ' ', contents) contents = re.sub('\\s+', ' ', contents) return contents def snippet(doc, term): text = ' ' * 30 + raw(doc) + ' ' * 30 pos = text.index(term) return text[pos - 30:pos + 30] print('Building Index...') files...
class Solution: def diffWaysToCompute(self, input: str) -> [int]: end = [] op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y} for i in range(len(input)): if input[i] in op.keys(): for left in self.diffWays...
class Solution: def diff_ways_to_compute(self, input: str) -> [int]: end = [] op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y} for i in range(len(input)): if input[i] in op.keys(): for left in self.diffWaysToCompute(input[:i]): ...
__author__ = ['Tomas Mendez Echenagucia <tmendeze@uw.edu>'] __copyright__ = 'Copyright 2020, Design Machine Group - University of Washington' __license__ = 'MIT License' __email__ = 'tmendeze@uw.edu' __all__ = [ 'Node', ] class Node(object): """ Initialises base Node object. Parameters ...
__author__ = ['Tomas Mendez Echenagucia <tmendeze@uw.edu>'] __copyright__ = 'Copyright 2020, Design Machine Group - University of Washington' __license__ = 'MIT License' __email__ = 'tmendeze@uw.edu' __all__ = ['Node'] class Node(object): """ Initialises base Node object. Parameters ---------- key : i...
# Queue in python """ Queue is like people entering in a theatre in queue i.e: add elements at the end, and remove the elements from the start A Queue in python is where you can add or remove elements either side is called `deque` or `double ended queue`. and in the stack, you add and remove from the same end """
""" Queue is like people entering in a theatre in queue i.e: add elements at the end, and remove the elements from the start A Queue in python is where you can add or remove elements either side is called `deque` or `double ended queue`. and in the stack, you add and remove from the same end """
#PLOTS ################################################## #if(plot_opacity == True): # p_plot = np.linspace(2.0,6.0,21) # a_plot = np.logspace(np.log10(0.001),np.log10(10.),21) # # EXT_plot = EXT(a_plot,p_plot) # ALB_plot = ALB(a_plot,p_plot) # # plt.close() # fig = plt.figure() # ax = fig.ad...
if plot_sky == True: plt.close() (fig, ax) = plt.subplots(nrows=2, ncols=2, figsize=(15, 12)) fig.subplots_adjust(hspace=0.15, wspace=0.1) plt.suptitle('$\\lambda = %.2f \\ \\mathrm{cm}; \\ i = %.1f \\ \\mathrm{deg}$' % (wl, inc * 180.0 / np.pi)) if intensity_log == True: im = ax[0][0].imsho...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'chromium', 'chromium_android', 'recipe_engine/json', ] def RunSteps(api): api.chromium.set_config('chromium') api.chromium_androi...
deps = ['chromium', 'chromium_android', 'recipe_engine/json'] def run_steps(api): api.chromium.set_config('chromium') api.chromium_android.set_config('main_builder', BUILD_CONFIG='Release') api.chromium_android.run_java_unit_test_suite('test_suite', json_results_file=api.json.output()) def gen_tests(api):...
def solveQuestion(value): n = -1 total = 0 while total < value: n += 1 total = 4*n*n - 4*n + 1 n = n - 1 minSpiralVal = 4*n*n - 4*n + 1 difference = value - minSpiralVal # if difference is more than n - 1 if difference < n: return n + difference elif d...
def solve_question(value): n = -1 total = 0 while total < value: n += 1 total = 4 * n * n - 4 * n + 1 n = n - 1 min_spiral_val = 4 * n * n - 4 * n + 1 difference = value - minSpiralVal if difference < n: return n + difference elif difference == n: return n...
input = "()()(()()()(()()((()((()))((()((((()()((((()))()((((())(((((((()(((((((((()(((())(()()(()((()()(()(())(()((((()((()()()((((())((((((()(()(((()())(()((((()))())(())(()(()()))))))))((((((((((((()())()())())(())))(((()()()((((()(((()(()(()()(()(()()(()(((((((())(())(())())))((()())()((((()()((()))(((()()()())))((...
input = '()()(()()()(()()((()((()))((()((((()()((((()))()((((())(((((((()(((((((((()(((())(()()(()((()()(()(())(()((((()((()()()((((())((((((()(()(((()())(()((((()))())(())(()(()()))))))))((((((((((((()())()())())(())))(((()()()((((()(((()(()(()()(()(()()(()(((((((())(())(())())))((()())()((((()()((()))(((()()()())))((...
class COLORS: header = "\033[4m" red = "\033[31m" green = "\033[32m" blue = "\033[34m" normal = "\033[0m" def format_verse(reference, text) -> str: return "{blue}{reference}{normal} \n{verse}\n".format( blue=COLORS.blue, reference=reference, normal=COLORS.normal, verse=text ...
class Colors: header = '\x1b[4m' red = '\x1b[31m' green = '\x1b[32m' blue = '\x1b[34m' normal = '\x1b[0m' def format_verse(reference, text) -> str: return '{blue}{reference}{normal} \n{verse}\n'.format(blue=COLORS.blue, reference=reference, normal=COLORS.normal, verse=text) def format_referenc...
class Solution: # @param A : list of integers # @return an integer def solve(self, A): s = set(A) if len(s) == len(A): return -1 for i in A: if A.count(i) > 1: return i else: return -1
class Solution: def solve(self, A): s = set(A) if len(s) == len(A): return -1 for i in A: if A.count(i) > 1: return i else: return -1
# Environment variables ENV_PROJECT_PATH = "PROJECT_PATH" ENV_FLOW_PATH = "FLOW_PATH" ENV_SCRIPT_PATH = "SCRIPT_PATH" ENV_PLATFORM_SCRIPT_PATH = "PLATFORM_SCRIPT_PATH" # Contexts CTX_EXEC = "exec"
env_project_path = 'PROJECT_PATH' env_flow_path = 'FLOW_PATH' env_script_path = 'SCRIPT_PATH' env_platform_script_path = 'PLATFORM_SCRIPT_PATH' ctx_exec = 'exec'
N, W, H = map(int, input().split()) row, col = [0] * (H + 1), [0] * (W + 1) for _ in range(N): x, y, w = map(int, input().split()) row[max(0, y - w)] += 1 row[min(H, y + w)] -= 1 col[max(0, x - w)] += 1 col[min(W, x + w)] -= 1 for i in range(H): row[i + 1] += row[i] for i in range(W): col[i ...
(n, w, h) = map(int, input().split()) (row, col) = ([0] * (H + 1), [0] * (W + 1)) for _ in range(N): (x, y, w) = map(int, input().split()) row[max(0, y - w)] += 1 row[min(H, y + w)] -= 1 col[max(0, x - w)] += 1 col[min(W, x + w)] -= 1 for i in range(H): row[i + 1] += row[i] for i in range(W): ...
# Calculates a^b def power(a, b): if b == 0: return 1 b -= 1 return a*power(a, b) x = int(input()) y = int(input()) print(power(x, y))
def power(a, b): if b == 0: return 1 b -= 1 return a * power(a, b) x = int(input()) y = int(input()) print(power(x, y))
''' Program Description: Calculate factorial of a given number ''' def calculate_factorial(n): if n == 0: return 1 if n < 0: raise ValueError fact = 1 for x in range(1,n+1): fact *= x return fact print('N = ', end='') try: result = calculate_factorial(int(input())) print('Output =', result) except Val...
""" Program Description: Calculate factorial of a given number """ def calculate_factorial(n): if n == 0: return 1 if n < 0: raise ValueError fact = 1 for x in range(1, n + 1): fact *= x return fact print('N = ', end='') try: result = calculate_factorial(int(input())) ...
class A: def __init__(self): print('base class constructor ') class B(A): def __init__(self): super().__init__() print('child class constructor ') b1=B()
class A: def __init__(self): print('base class constructor ') class B(A): def __init__(self): super().__init__() print('child class constructor ') b1 = b()
#Incomplete ordering class PartOrdered(object): def __eq__(self, other): return self is other def __ne__(self, other): return self is not other def __hash__(self): return id(self) def __lt__(self, other): return False #Don't blame a sub-class for super-class's sins. ...
class Partordered(object): def __eq__(self, other): return self is other def __ne__(self, other): return self is not other def __hash__(self): return id(self) def __lt__(self, other): return False class Derivedpartordered(PartOrdered): pass
config = { "coinbase":{ "Key": "", "Secret": "" }, "twilio":{ "Key": "", "Secret": "", "from": "+12223334444", "to_list": ["+12223334444"], }, "bittrex":{ "Key" : "", "Secret" : "" } }
config = {'coinbase': {'Key': '', 'Secret': ''}, 'twilio': {'Key': '', 'Secret': '', 'from': '+12223334444', 'to_list': ['+12223334444']}, 'bittrex': {'Key': '', 'Secret': ''}}
def getNthFib(n): if(n==1): return 0 elif (n==2): return 1 else: return getNthFib(n-1) + getNthFib(n-2) #End of getNthFib if __name__ == '__main__': print(getNthFib(6))#5 print(getNthFib(7))#8 print(getNthFib(1))#0 print(getNthFib(11))#55 print(getNthFib(18))#15...
def get_nth_fib(n): if n == 1: return 0 elif n == 2: return 1 else: return get_nth_fib(n - 1) + get_nth_fib(n - 2) if __name__ == '__main__': print(get_nth_fib(6)) print(get_nth_fib(7)) print(get_nth_fib(1)) print(get_nth_fib(11)) print(get_nth_fib(18))
class BadMessageError(Exception): # A bad message is broken in some way that will never be accepted by # the endpoing and as such should be rejected (it will still be logged # and stored so no data is lost) pass class RetryableError(Exception): # A retryable error is apparently transient and may b...
class Badmessageerror(Exception): pass class Retryableerror(Exception): pass class Decrypterror(Exception): pass
def cents_to_dollars(cents): """ Convert cents to dollars. :param cents: Amount in cents :type cents: int :return: float """ return round(cents / 100.0, 2) def dollars_to_cents(dollars): """ Convert dollars to cents. :param dollars: Amount in dollars :type dollars: float ...
def cents_to_dollars(cents): """ Convert cents to dollars. :param cents: Amount in cents :type cents: int :return: float """ return round(cents / 100.0, 2) def dollars_to_cents(dollars): """ Convert dollars to cents. :param dollars: Amount in dollars :type dollars: float ...
name = "igittigitt" title = "A spec-compliant gitignore parser for Python" version = "v2.0.4" url = "https://github.com/bitranox/igittigitt" author = "Robert Nowotny" author_email = "bitranox@gmail.com" shell_command = "igittigitt" def print_info() -> None: print( """\ Info for igittigitt: A spec-co...
name = 'igittigitt' title = 'A spec-compliant gitignore parser for Python' version = 'v2.0.4' url = 'https://github.com/bitranox/igittigitt' author = 'Robert Nowotny' author_email = 'bitranox@gmail.com' shell_command = 'igittigitt' def print_info() -> None: print('\nInfo for igittigitt:\n\n A spec-compliant git...
class n_A(flatdata.archive.Archive): _SCHEMA = """namespace n { archive A { } } """ _NAME = "A" _RESOURCES = { "A.archive" : flatdata.archive.ResourceSignature( container=flatdata.resources.RawData, initializer=None, schema=_SCHEMA, is_optional=False,...
class N_A(flatdata.archive.Archive): _schema = 'namespace n {\narchive A\n{\n}\n}\n\n' _name = 'A' _resources = {'A.archive': flatdata.archive.ResourceSignature(container=flatdata.resources.RawData, initializer=None, schema=_SCHEMA, is_optional=False, doc='Archive signature')} def __init__(self, resour...
#! /usr/bin/python # Samples Python/PYgames # Print 'Hi' 10 times for i in range(10): print("Hi") for i in range(5): print("Hello") print ("There") for i in range(5): print("Hello") print("There") for i in range(10): print(i) for i in range(1, 11): print(i) for i in range(10, 0, -1): p...
for i in range(10): print('Hi') for i in range(5): print('Hello') print('There') for i in range(5): print('Hello') print('There') for i in range(10): print(i) for i in range(1, 11): print(i) for i in range(10, 0, -1): print(i) for i in [2, 6, 4, 2, 6, 7, 4]: print(i) for i in range(3): ...
def draw_z(size, position, target): if size == 1: return (position == target, 1) base_r, base_c = position half_size = size // 2 counter = 0 matched = False if (target[0] >= (base_r + size)) or (target[1] >= (base_c + size)): counter = size ** 2 return (matched, counter...
def draw_z(size, position, target): if size == 1: return (position == target, 1) (base_r, base_c) = position half_size = size // 2 counter = 0 matched = False if target[0] >= base_r + size or target[1] >= base_c + size: counter = size ** 2 return (matched, counter) fo...
# # @lc app=leetcode.cn id=174 lang=python3 # # [174] dungeon-game # None # @lc code=end
None
""" PASSENGERS """ numPassengers = 19423 passenger_arriving = ( (5, 4, 5, 6, 7, 2, 3, 1, 0, 1, 2, 0, 0, 6, 6, 2, 2, 3, 1, 1, 1, 2, 2, 1, 1, 0), # 0 (5, 7, 2, 5, 4, 2, 2, 1, 5, 1, 1, 1, 0, 10, 5, 2, 0, 6, 2, 0, 3, 3, 3, 1, 2, 0), # 1 (3, 6, 7, 3, 4, 4, 0, 1, 2, 0, 0, 1, 0, 5, 2, 7, 2, 4, 3, 1, 2, 1, 5, 0, 0, 0),...
""" PASSENGERS """ num_passengers = 19423 passenger_arriving = ((5, 4, 5, 6, 7, 2, 3, 1, 0, 1, 2, 0, 0, 6, 6, 2, 2, 3, 1, 1, 1, 2, 2, 1, 1, 0), (5, 7, 2, 5, 4, 2, 2, 1, 5, 1, 1, 1, 0, 10, 5, 2, 0, 6, 2, 0, 3, 3, 3, 1, 2, 0), (3, 6, 7, 3, 4, 4, 0, 1, 2, 0, 0, 1, 0, 5, 2, 7, 2, 4, 3, 1, 2, 1, 5, 0, 0, 0), (6, 3, 7, 6, 5,...
class Solution: def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: answer=0 aliceVisited=[0]*(n+1) bobVisited=[0]*(n+1) aliceSet={} aliceSetNum=1 bobSet={} bobSetNum=1 # Return False if this edge can be deleted. Applies to...
class Solution: def max_num_edges_to_remove(self, n: int, edges: List[List[int]]) -> int: answer = 0 alice_visited = [0] * (n + 1) bob_visited = [0] * (n + 1) alice_set = {} alice_set_num = 1 bob_set = {} bob_set_num = 1 def add_edge(edge) -> bool: ...
def fibonum(num): if num == 1: return 1 elif num == 2: return 1 else: return fibonum(num - 1) + fibonum(num - 2)
def fibonum(num): if num == 1: return 1 elif num == 2: return 1 else: return fibonum(num - 1) + fibonum(num - 2)
age = int(input('What your age?: ')) if age <= 2: print('Is a baby!') elif age <= 4: print('You are a children!') elif age <= 13: print('You are a kid!') elif age <= 20: print('You are a teenager!') elif age <= 65: print('You are a adult!') else: print('You are a old!')
age = int(input('What your age?: ')) if age <= 2: print('Is a baby!') elif age <= 4: print('You are a children!') elif age <= 13: print('You are a kid!') elif age <= 20: print('You are a teenager!') elif age <= 65: print('You are a adult!') else: print('You are a old!')
class Student(): def __init__(self): self._name = 'John' self._age = 18 self._grades = [9.5, 5.75, 10] s1 = Student() # Verify if s1 has the attribute 'name': print(hasattr(s1, 'name')) # Sets a new attribute 'average': setattr(s1, "average", sum(s1._grades) / 3) # Gets t...
class Student: def __init__(self): self._name = 'John' self._age = 18 self._grades = [9.5, 5.75, 10] s1 = student() print(hasattr(s1, 'name')) setattr(s1, 'average', sum(s1._grades) / 3) print(f"{getattr(s1, 'average'):4.2f}") delattr(s1, 'age')
class Solution: ''' 1. char_freq count and updates the char frequent of current window and updates accordingly as the window moves forward. so it dosen't need to delete the elements when the count become 0. 2. window length - window max_count > windown length - global max_count > k. If window length - most...
class Solution: """ 1. char_freq count and updates the char frequent of current window and updates accordingly as the window moves forward. so it dosen't need to delete the elements when the count become 0. 2. window length - window max_count > windown length - global max_count > k. If window length - most_...
'''https://leetcode.com/problems/binary-search/''' class Solution: def search(self, nums: List[int], target: int) -> int: l, h = 0, len(nums)-1 while l<=h: m = (l+h)//2 if nums[m]==target: return m elif nums[m]>target: h = m-1 ...
"""https://leetcode.com/problems/binary-search/""" class Solution: def search(self, nums: List[int], target: int) -> int: (l, h) = (0, len(nums) - 1) while l <= h: m = (l + h) // 2 if nums[m] == target: return m elif nums[m] > target: ...
def bubblesort(array): length = len(array)-1 for i in range(length,0,-1): for j in range(i): if array[j] > array[j+1]: array[j],array[j+1]=array[j+1],array[j]
def bubblesort(array): length = len(array) - 1 for i in range(length, 0, -1): for j in range(i): if array[j] > array[j + 1]: (array[j], array[j + 1]) = (array[j + 1], array[j])
# -*- coding: utf-8 -*- """ Created on Sat Sep 8 16:04:50 2018 @author: robot """
""" Created on Sat Sep 8 16:04:50 2018 @author: robot """
# Time complexity: O(n^2) # Approach: Fix one and then based on that loop over other numbers. class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return [] nums = sorted(nums) ans = [] for k in range(n): tar...
class Solution: def three_sum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return [] nums = sorted(nums) ans = [] for k in range(n): target = -nums[k] (i, j) = (k + 1, n - 1) while i < j: s...
''' Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.) Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".) Example 1: Input: "banana" Output...
""" Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.) Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".) Example 1: Input: "banana" Output...
class Solution(object): def minCostII(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 dp = [[0] * len(costs[0]) for _ in xrange(0, len(costs))] dp[0] = costs[0] for i in xrange(1, len(costs)):...
class Solution(object): def min_cost_ii(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 dp = [[0] * len(costs[0]) for _ in xrange(0, len(costs))] dp[0] = costs[0] for i in xrange(1, len(costs)): ...
Friend1 = {"First_name": "Anita", "Last_name": "Sanchez", "Age": 21, "City": "Saltillo"} Friend2 = {"First_name": "Andrea", "Last_name": "De la Fuente", "Age": 21, "City": "Monclova"} Friend3 = {"First_name": "Jorge", "Last_name": "Sanchez", "Age":20, "City": "Saltillo"} amigos = [Friend1, Friend2, Friend3] for i in ...
friend1 = {'First_name': 'Anita', 'Last_name': 'Sanchez', 'Age': 21, 'City': 'Saltillo'} friend2 = {'First_name': 'Andrea', 'Last_name': 'De la Fuente', 'Age': 21, 'City': 'Monclova'} friend3 = {'First_name': 'Jorge', 'Last_name': 'Sanchez', 'Age': 20, 'City': 'Saltillo'} amigos = [Friend1, Friend2, Friend3] for i in r...
# -*- coding: utf-8 -*- # Aufgaben 6, 7, 20, 21, 24, 30, 34, 39, 38, 41, 43 Bis Dienstag # ----------------- # 41 list in nested loop # ----------------- words = ['attribution', 'confabulation', 'elocution', 'sequoia', 'tenacious', 'unidirectional'] s = sorted(set([''.join([c for c in w if c in 'aeiou']) fo...
words = ['attribution', 'confabulation', 'elocution', 'sequoia', 'tenacious', 'unidirectional'] s = sorted(set([''.join([c for c in w if c in 'aeiou']) for w in words])) print('My result: ', sorted(s)) print('Solution: ', ['aiuio', 'eaiou', 'eouio', 'euoia', 'oauaio', 'uiieioa'])
def main(): ref = "lunes,martes,miercoles,juevez,viernes,sabado,domindo".split(",") day = int(input("Day: ")) - 1 print(ref[day]) if __name__ == '__main__': main()
def main(): ref = 'lunes,martes,miercoles,juevez,viernes,sabado,domindo'.split(',') day = int(input('Day: ')) - 1 print(ref[day]) if __name__ == '__main__': main()
file = open('data/day1.txt', 'r') values = [] for line in file.readlines(): values.append(int(line)) counter = 0 i = 3 while i < len(values): if values[i-3] < values [i]: counter = counter + 1 i = i + 1 print(counter)
file = open('data/day1.txt', 'r') values = [] for line in file.readlines(): values.append(int(line)) counter = 0 i = 3 while i < len(values): if values[i - 3] < values[i]: counter = counter + 1 i = i + 1 print(counter)
fun = lambda s : True if len(s) > 5 else False print(fun("sidd")) print(fun("sidddha")) names = ['alka','sidd','lala'] for pos,name in enumerate(names): print(f"{pos} ===> {name}") string = "lala" for pos,name in enumerate(names): if(name == string): print(f"{pos} ===> {name}")
fun = lambda s: True if len(s) > 5 else False print(fun('sidd')) print(fun('sidddha')) names = ['alka', 'sidd', 'lala'] for (pos, name) in enumerate(names): print(f'{pos} ===> {name}') string = 'lala' for (pos, name) in enumerate(names): if name == string: print(f'{pos} ===> {name}')
class BinarySearchTree(): def __init__(self): self.root = None def insert(self, data): if self.root: return self.root.insert(data) else: self.root = Node(data) return True def find(self, data): if self.root: return self.root....
class Binarysearchtree: def __init__(self): self.root = None def insert(self, data): if self.root: return self.root.insert(data) else: self.root = node(data) return True def find(self, data): if self.root: return self.root.fi...
# -*- coding: utf-8 -*- """Main module.""" def pluck(dictionary, key): """ Return array. :param dictionary: array :param key: string """ try: ages = [li[key] for li in dictionary] return ages except KeyError as e: raise KeyError(e.message) except TypeError as ...
"""Main module.""" def pluck(dictionary, key): """ Return array. :param dictionary: array :param key: string """ try: ages = [li[key] for li in dictionary] return ages except KeyError as e: raise key_error(e.message) except TypeError as e: raise type_err...
# An example of function calling another def func_a(): print('A') # func_b() calls system function print() def func_b(): print('B') # func_ab() calls func_a() and func_b() def func_ab(): func_a() func_b() print('Done!') # Main calls func_ab() def main(): func_ab() # Call main() function....
def func_a(): print('A') def func_b(): print('B') def func_ab(): func_a() func_b() print('Done!') def main(): func_ab() main()
# -*- encoding:utf8 -*- """:: _/_/_/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ ...
""":: _/_/_/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _...
#Problema 9 res = 0 for a in range(1, 500): for b in range(1, 500): for c in range(1, 500): if (a < b < c) and (a ** 2 + b ** 2 == c ** 2): if a + b + c == 1000: res = a*b*c print(res)
res = 0 for a in range(1, 500): for b in range(1, 500): for c in range(1, 500): if a < b < c and a ** 2 + b ** 2 == c ** 2: if a + b + c == 1000: res = a * b * c print(res)
# Rule for building verilator simulations. # # Copyright 2019 Erik Gilling # # Heavily informed from the rules_foreign_cc package at: # https://github.com/bazelbuild/rules_foreign_cc/ # Since verilator uses make to build its output it shares some actions with # @rules_foreign_cc. load("@rules_foreign_cc//tools/build...
load('@rules_foreign_cc//tools/build_defs:cc_toolchain_util.bzl', 'get_env_vars') load('@rules_foreign_cc//tools/build_defs:shell_script_helper.bzl', 'os_name') def _verilator_sim_impl(ctx): v_files = ctx.attr._verilator_toolchain.files.to_list() verilator_dir = [f for f in v_files if f.path.endswith('copy_ver...
class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None @staticmethod def pre_order(root, nodes): if not root: return nodes.append(root.data) Node.pre_order(root.left, nodes) Node.pre_order(root....
class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None @staticmethod def pre_order(root, nodes): if not root: return nodes.append(root.data) Node.pre_order(root.left, nodes) Node.pre_order(root.r...
class Node(): def __init__(self, data=None,next_node=None): self.data = data self.next_node = next_node def __str__(self): return self.data def get_next(self): return self.next_node def set_new_next(self, new_next): self.next_node = new_next class LinkedList(): def __init_...
class Node: def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def __str__(self): return self.data def get_next(self): return self.next_node def set_new_next(self, new_next): self.next_node = new_next class Linkedlist: ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 17:44:54 2020 @author: teja """ ex_str = "God has created the universe so beautiful that the description of it can be represented in lisp." ex_str = ex_str[:-1] print(ex_str) ex_list = list(map(lambda x: x.lower(), ex_str.split())) ex_list.sort(key=lambda x: len(x))...
""" Created on Mon Mar 9 17:44:54 2020 @author: teja """ ex_str = 'God has created the universe so beautiful that the description of it can be represented in lisp.' ex_str = ex_str[:-1] print(ex_str) ex_list = list(map(lambda x: x.lower(), ex_str.split())) ex_list.sort(key=lambda x: len(x)) ex_list[0] = ex_list[0].ti...
valid_sequence_dict = { "P1": "complete protein", "F1": "protein fragment", \ "DL": "linear DNA", "DC": "circular DNA", "RL": "linear RNA", \ "RC":"circular RNA", "N3": "transfer RNA", "N1": "other" }
valid_sequence_dict = {'P1': 'complete protein', 'F1': 'protein fragment', 'DL': 'linear DNA', 'DC': 'circular DNA', 'RL': 'linear RNA', 'RC': 'circular RNA', 'N3': 'transfer RNA', 'N1': 'other'}
f = open("test.txt") print(f.read())
f = open('test.txt') print(f.read())
def fibonacci(N :int)->int: if N==1 or N==2: return 1 else : return fibonacci(N-1)+fibonacci(N-2) def main(): # input N = int(input()) # compute # output print(fibonacci(N)) if __name__ == '__main__': main()
def fibonacci(N: int) -> int: if N == 1 or N == 2: return 1 else: return fibonacci(N - 1) + fibonacci(N - 2) def main(): n = int(input()) print(fibonacci(N)) if __name__ == '__main__': main()
class ConnectedSIPMessage(object): def __init__(self, a_sip_transport_connection, a_sip_message): self.connection = a_sip_transport_connection self.sip_message = a_sip_message @property def raw_string(self): if self.sip_message: return self.sip_message.raw_string ...
class Connectedsipmessage(object): def __init__(self, a_sip_transport_connection, a_sip_message): self.connection = a_sip_transport_connection self.sip_message = a_sip_message @property def raw_string(self): if self.sip_message: return self.sip_message.raw_string ...
# -*- coding: utf-8 -*- class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.queue = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.queue.append(x) def pop(self) -> int:...
class Myqueue: def __init__(self): """ Initialize your data structure here. """ self.queue = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.queue.append(x) def pop(self) -> int: """ Remov...
# Change to API-tokens CONSUMER_KEY='[TWITTER CONSUMER KEY]' CONSUMER_SECRET='[TWITTER CONSUMER SECRET]' # Change to proper username/password ADMIN_NAME='admin' ADMIN_PW='1234' # Change to proper secrete key e.g. `python3 -c 'import os; print(os.urandom(16))'` SECRET_KEY = b'1234'
consumer_key = '[TWITTER CONSUMER KEY]' consumer_secret = '[TWITTER CONSUMER SECRET]' admin_name = 'admin' admin_pw = '1234' secret_key = b'1234'
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: cs = head cf = head if head == None: return None if cf.next == None: ...
class Solution: def detect_cycle(self, head: ListNode) -> ListNode: cs = head cf = head if head == None: return None if cf.next == None: return None else: cf = cf.next while cf.next != None and cf != cs: cs = cs.next ...
""" This is a module to be used as a reference for building other modules """ def foo(): """docstring for foo""" return 'foo' class Bar(): """docstring for Bar""" def __init__(self, arg): super().__init__() self.arg = arg
""" This is a module to be used as a reference for building other modules """ def foo(): """docstring for foo""" return 'foo' class Bar: """docstring for Bar""" def __init__(self, arg): super().__init__() self.arg = arg
def toh(disks, source, destination, helper) -> int: # Number of steps it will take to transfer the disks from one tower to another # Base Case if disks == 1: print("move disk {} from {} -> {}".format(disks, source, destination)) return 1 # only one step needed # Hypothesis steps_t...
def toh(disks, source, destination, helper) -> int: if disks == 1: print('move disk {} from {} -> {}'.format(disks, source, destination)) return 1 steps_to_move_remaining_disks__from_src_helper = toh(disks - 1, source, helper, destination) print('move last disk({}) from {} -> {}'.format(disk...
# -*- coding: utf-8 -*- """ KM3NeT Data Definitions v2.0.0-9-gbae3720 https://git.km3net.de/common/km3net-dataformat """ # reconstruction data = dict( JPP_RECONSTRUCTION_TYPE=4000, JMUONBEGIN=0, JMUONPREFIT=1, JMUONSIMPLEX=2, JMUONGANDALF=3, JMUONENERGY=4, JMUONSTART=5, JLINEFIT=6, ...
""" KM3NeT Data Definitions v2.0.0-9-gbae3720 https://git.km3net.de/common/km3net-dataformat """ data = dict(JPP_RECONSTRUCTION_TYPE=4000, JMUONBEGIN=0, JMUONPREFIT=1, JMUONSIMPLEX=2, JMUONGANDALF=3, JMUONENERGY=4, JMUONSTART=5, JLINEFIT=6, JMUONEND=99, JSHOWERBEGIN=100, JSHOWERPREFIT=101, JSHOWERPOSITIONFIT=102, JSHOW...
class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: raise Exception("No Available Prices") low = prices[0] # lowest HISTORICAL price profit = 0 for i in range(1, len(prices)): if prices[i] - low > profit: profit = pr...
class Solution: def max_profit(self, prices: List[int]) -> int: if not prices: raise exception('No Available Prices') low = prices[0] profit = 0 for i in range(1, len(prices)): if prices[i] - low > profit: profit = prices[i] - low ...
# Create a calculator function # The function should accept three parameters: # first_number: a numeric value for the math operation # second_number: a numeric value for the math operation # operation: the word 'add' or 'subtract' # the function should return the result of the two numbers added or subtracted # based on...
def calculator(first_number, second_number, operation): if operation == 'add': answer = first_number + second_number elif operation == 'subtract': answer = first_number - second_number elif operation == 'divide': answer = first_number / second_number return answer first_number = ...
# Auto generated by web.apps.config module WXMP_TOKEN='laonabuzhai' WXMP_APP_ID='wxadf692dbf276c755' WXMP_APP_KEY='d5d70f3c91578b545de3392c8c758dad ' WXMP_ENCODING_AES_KEY='Y81yOIit1k5GZS9Vhx5L1JCOVaQJc9uXnhvaDVKGq4k' WXMP_MSG_ENCRYPT_METHOD='clear'
wxmp_token = 'laonabuzhai' wxmp_app_id = 'wxadf692dbf276c755' wxmp_app_key = 'd5d70f3c91578b545de3392c8c758dad ' wxmp_encoding_aes_key = 'Y81yOIit1k5GZS9Vhx5L1JCOVaQJc9uXnhvaDVKGq4k' wxmp_msg_encrypt_method = 'clear'
# Find this puzzle at: # https://adventofcode.com/2020/day/6 with open('input.txt', 'r') as file: puzzle_input = [i for i in file.read().split('\n\n')] answered = 0 for group in puzzle_input: ques_answered = set() # Add all questions answered to a set. # Duplicates are avoided by using a set. for q...
with open('input.txt', 'r') as file: puzzle_input = [i for i in file.read().split('\n\n')] answered = 0 for group in puzzle_input: ques_answered = set() for question in group.replace('\n', ''): ques_answered.add(question) answered += len(ques_answered) print(answered)
def test_app_is_created(app): assert app.name == 'joalheria.app' def test_config_is_loaded(config): assert config["DEBUG"] is False
def test_app_is_created(app): assert app.name == 'joalheria.app' def test_config_is_loaded(config): assert config['DEBUG'] is False
database = {"shuttle":9080590855,"barath":638383877,"hannah":6987237898} print("\nGreeting\'s from Vigneshwaram") print("Welcome to phoneBook\n") while True: print("Type EDIT to edit the contact number\n CREATE to create a new contact\n SEARCH to search a specific contact\n DELETE to Delete the con...
database = {'shuttle': 9080590855, 'barath': 638383877, 'hannah': 6987237898} print("\nGreeting's from Vigneshwaram") print('Welcome to phoneBook\n') while True: print('Type EDIT to edit the contact number\n CREATE to create a new contact\n SEARCH to search a specific contact\n DELETE to Delete the cont...
#take a user input i = input() print (i) #int i = 23 #float j = 23.5 #bool k = True # char l = 'w' #string m = "word" #input typecasting print("Try to enter an alphabet") value1 = input() value2 = int(value1) print (value2+1) print("Please input integers only") a = int(input()) b = int(input()) #Operator 1 pri...
i = input() print(i) i = 23 j = 23.5 k = True l = 'w' m = 'word' print('Try to enter an alphabet') value1 = input() value2 = int(value1) print(value2 + 1) print('Please input integers only') a = int(input()) b = int(input()) print(a + b) print(a - b) print(a * b) print(a > b) print(a < b) print(a == b) print(a >= b) pr...
class Sensor: """Sensor, measures an amount """ last_measure = -1 def __init__(self, range_min=0, range_max=4095, average_converging_speed=1 / 2): """ constructor. :param range_min: min value of sensor :param range_max: max value of sensor :param average_converging_speed: s...
class Sensor: """Sensor, measures an amount """ last_measure = -1 def __init__(self, range_min=0, range_max=4095, average_converging_speed=1 / 2): """ constructor. :param range_min: min value of sensor :param range_max: max value of sensor :param average_converging_speed: sp...
""" *Line-Direction* Controls the direction of text. """ __all__ = ["LineDirection"] css_syntax = "text-direction" class LineDirection: Name = "Direction" # [TODO} ident? LeftToRight = "ltr" RightToLeft = "rtl"
""" *Line-Direction* Controls the direction of text. """ __all__ = ['LineDirection'] css_syntax = 'text-direction' class Linedirection: name = 'Direction' left_to_right = 'ltr' right_to_left = 'rtl'
def add_native_methods(clazz): def mapAlternativeName__java_io_File__(a0): raise NotImplementedError() clazz.mapAlternativeName__java_io_File__ = staticmethod(mapAlternativeName__java_io_File__)
def add_native_methods(clazz): def map_alternative_name__java_io__file__(a0): raise not_implemented_error() clazz.mapAlternativeName__java_io_File__ = staticmethod(mapAlternativeName__java_io_File__)
class Timings(object): def __init__(self, j): self.raw = j if "blocked" in self.raw: self.blocked = self.raw["blocked"] else: self.blocked = -1 if "dns" in self.raw: self.dns = self.raw["dns"] else: self.dns = -1 if "...
class Timings(object): def __init__(self, j): self.raw = j if 'blocked' in self.raw: self.blocked = self.raw['blocked'] else: self.blocked = -1 if 'dns' in self.raw: self.dns = self.raw['dns'] else: self.dns = -1 if 'co...
# -*- coding: utf-8 -*- __author__ = "Paul Schifferer <dm@sweetrpg.com>" """Constants. """ # argument values DEFAULT_PAGE_SIZE = 50 MAX_PAGE_SIZE = 200 # url parameters PAGE_PARAM = "page[number]" LIMIT_PARAM = "page[size]" SORT_PARAM = 'sort' INCLUDE_PARAM = "include" # type info keys ENDPOINT_PATH = "endpoint_path...
__author__ = 'Paul Schifferer <dm@sweetrpg.com>' 'Constants.\n' default_page_size = 50 max_page_size = 200 page_param = 'page[number]' limit_param = 'page[size]' sort_param = 'sort' include_param = 'include' endpoint_path = 'endpoint_path' api_schema_class = 'api_schema_class' object_class = 'object_class'
def splitscore(file_dir): score = [] Prefix_str = [] f = open(file_dir) for line in f: s =line.split() score.append(float(s[-1])) s = s[0] + ' ' + s[1] + ' ' + s[2] + ' ' Prefix_str.append(s) return score,Prefix_str file_dir1='submission/2019-01-28_15:45:05_fishnet15...
def splitscore(file_dir): score = [] prefix_str = [] f = open(file_dir) for line in f: s = line.split() score.append(float(s[-1])) s = s[0] + ' ' + s[1] + ' ' + s[2] + ' ' Prefix_str.append(s) return (score, Prefix_str) file_dir1 = 'submission/2019-01-28_15:45:05_fish...
layer_info = \ {1: {'B': 1, 'K': 96, 'C': 3, 'OY': 165, 'OX': 165, 'FY': 3, 'FX': 3, 'SY': 2, 'SX': 2, 'SFY': 1, 'SFX': 1, 'PY': 0, 'PX': 0, 'G': 1}, 2: {'B': 1, 'K': 42, 'C': 96, 'OY': 165, 'OX': 165, 'FY': 1, 'FX': 1, 'SY': 1, 'SX': 1, 'SFY': 1, 'SFX': 1, 'PY': 0, 'PX': 0, 'G': 1}, 3: {'B': 1, 'K': 42, 'C': 42, 'O...
layer_info = {1: {'B': 1, 'K': 96, 'C': 3, 'OY': 165, 'OX': 165, 'FY': 3, 'FX': 3, 'SY': 2, 'SX': 2, 'SFY': 1, 'SFX': 1, 'PY': 0, 'PX': 0, 'G': 1}, 2: {'B': 1, 'K': 42, 'C': 96, 'OY': 165, 'OX': 165, 'FY': 1, 'FX': 1, 'SY': 1, 'SX': 1, 'SFY': 1, 'SFX': 1, 'PY': 0, 'PX': 0, 'G': 1}, 3: {'B': 1, 'K': 42, 'C': 42, 'OY': 8...
shelters = ['MNTG1', 'MNTG'] twitter_api_key = 'k5O4owMpAPDcI7LG7y4fue9Fc' twitter_api_secret = 'XXXXX' #Edited out twitter_access_token = '2150117929-qnttvTJW3uvP0QbZr2ZKxaBlrkRPa9FdUUWSxqx' twitter_access_token_secret = 'XXXXX'
shelters = ['MNTG1', 'MNTG'] twitter_api_key = 'k5O4owMpAPDcI7LG7y4fue9Fc' twitter_api_secret = 'XXXXX' twitter_access_token = '2150117929-qnttvTJW3uvP0QbZr2ZKxaBlrkRPa9FdUUWSxqx' twitter_access_token_secret = 'XXXXX'
class LatticeModifier: object = None strength = None vertex_group = None
class Latticemodifier: object = None strength = None vertex_group = None
""" Django LDAP user authentication backend for Python 3. """ __version__ = (0, 11, 2)
""" Django LDAP user authentication backend for Python 3. """ __version__ = (0, 11, 2)
class ModbusException(Exception): def __init__(self, code): codes = { '1': 'Illegal Function', '2': 'Illegal Data Address', '3': 'Illegal Data Value', '4': 'Slave Device Failure', '5': 'Acknowledge', '6': 'Slave Device Busy', ...
class Modbusexception(Exception): def __init__(self, code): codes = {'1': 'Illegal Function', '2': 'Illegal Data Address', '3': 'Illegal Data Value', '4': 'Slave Device Failure', '5': 'Acknowledge', '6': 'Slave Device Busy', '7': 'Negative Acknowledge', '8': 'Memory Parity Error', '10': 'Gateway Path Unava...
'''2. Write a Python program to convert all units of time into seconds.''' def time_conv(ty, tmo, twk, tdy, thr, tmin): yr = 365 * 24 * 60 * 60 * ty mont = 30 * 24 * 60 * 60 *tmo week = 7 * 24 * 60 * 60 * twk days = 24 * 60 * 60 * tdy hrs= 60*60 * thr mins =60* tmin return f"{ty} year ={...
"""2. Write a Python program to convert all units of time into seconds.""" def time_conv(ty, tmo, twk, tdy, thr, tmin): yr = 365 * 24 * 60 * 60 * ty mont = 30 * 24 * 60 * 60 * tmo week = 7 * 24 * 60 * 60 * twk days = 24 * 60 * 60 * tdy hrs = 60 * 60 * thr mins = 60 * tmin return f'{ty} year...
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ stack = root and [root] va...
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ stack = root and [root] ...
## Single ended filter chain element # class FilterElement(object): ## Constructor def __init__(self): self.nextelement = None ##! points at next in chain self.name = "noname" ##! nicename for printing ## Call to input data into the filter def input(self, data, meta=None): r...
class Filterelement(object): def __init__(self): self.nextelement = None self.name = 'noname' def input(self, data, meta=None): return self.down.rxup(data, meta) def output(self, data, meta=None): return self.nextelement.input(data, meta) def tick(self): pass ...
def sequentialSearch(alist, item): pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos += 1 return found if __name__ == '__main__': test_list = [1, 2, 32, 8, 17, 19, 42, 13, 0] print(sequentialSearc...
def sequential_search(alist, item): pos = 0 found = False while pos < len(alist) and (not found): if alist[pos] == item: found = True else: pos += 1 return found if __name__ == '__main__': test_list = [1, 2, 32, 8, 17, 19, 42, 13, 0] print(sequential_searc...
class driven_range: def main(self, inputData): inputData.sort() self.inputData = inputData.copy() return self.generateResult() def convertDigitalToAnalog(self, digitalValueRange, ADC_Sensor_Type): # Formula used to convert Digital to Analog: # # Analog_Val...
class Driven_Range: def main(self, inputData): inputData.sort() self.inputData = inputData.copy() return self.generateResult() def convert_digital_to_analog(self, digitalValueRange, ADC_Sensor_Type): analog_value_range = [] (max_digital_value, scale, offset) = self.sens...
# Given 2 arrays, create a function that let's a user know (true/false) whether these two arrays contain any # common items # For Example: # const array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'i']; # should return false. # ----------- # const array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'x']; ...
def find_common(list_1, list_2): for i in list1: for j in list2: if i == j: print('Common element is :', i) return True return False list1 = ['a', 'b', 'c', 'x'] list2 = ['z', 'y', 'x'] find_common(list1, list2)
# version_info should conform to PEP 386 # (major, minor, micro, alpha/beta/rc/final, #) # (1, 1, 2, 'alpha', 0) => "1.1.2.dev" # (1, 2, 0, 'beta', 2) => "1.2b2" __version_info__ = (0, 1, 0, 'alpha', 0) def _get_version(): # pragma: no cover " Returns a PEP 386-compliant version number from version_info. " a...
__version_info__ = (0, 1, 0, 'alpha', 0) def _get_version(): """ Returns a PEP 386-compliant version number from version_info. """ assert len(__version_info__) == 5 assert __version_info__[3] in ('alpha', 'beta', 'rc', 'final') parts = 2 if __version_info__[2] == 0 else 3 main = '.'.join(map(str, _...
class Options(object): def __init__(self, dry_run=False, unoptimized=False, verbose=False, debug=False): self.dry_run = dry_run self.unoptimized = unoptimized self.verbose = verbose self.debug = debug
class Options(object): def __init__(self, dry_run=False, unoptimized=False, verbose=False, debug=False): self.dry_run = dry_run self.unoptimized = unoptimized self.verbose = verbose self.debug = debug
# Bubble Sort implementation. def bubbleSort(array): for i in range(len(array) - 1, -1, -1): for j in range(i): if array[j] > array[j+1]: array = exchange(array, j, j+1) print(array) return array # Exchange function implementation. def exchange(array, i, j): te...
def bubble_sort(array): for i in range(len(array) - 1, -1, -1): for j in range(i): if array[j] > array[j + 1]: array = exchange(array, j, j + 1) print(array) return array def exchange(array, i, j): temp = array[i] array[i] = array[j] array[j] = temp r...
# -*- coding: utf-8 -*- """ Created on Thu May 2 19:23:43 2019 @author: Lee """
""" Created on Thu May 2 19:23:43 2019 @author: Lee """
words = [word.upper() for word in open('gettysburg.txt').read().split()] theDictionary = {} for word in words: theDictionary[word] = theDictionary.get(word,0) + 1 print(theDictionary)
words = [word.upper() for word in open('gettysburg.txt').read().split()] the_dictionary = {} for word in words: theDictionary[word] = theDictionary.get(word, 0) + 1 print(theDictionary)
#!/usr/bin/env python3 # Small library for generating URLs of visualizations class Constructor(object): """ Constructs Google Static Maps API URLs Constructs requests for the Google Static Maps API by storing substrings of the overall URL which are created by the add_coords function. The generate_url ...
class Constructor(object): """ Constructs Google Static Maps API URLs Constructs requests for the Google Static Maps API by storing substrings of the overall URL which are created by the add_coords function. The generate_url function returns the full, assembled URL. Attributes: parameters:...
class Mobile: def __init__(self, brand, price): print("Inside Constructor") self.brand = brand self.price = price def purchase(self): print("Purchasing a mobile") print("The mobile has brand", self.brand, "and price", self.price) print("Mobile-1") mob1 = Mobile("Apple",...
class Mobile: def __init__(self, brand, price): print('Inside Constructor') self.brand = brand self.price = price def purchase(self): print('Purchasing a mobile') print('The mobile has brand', self.brand, 'and price', self.price) print('Mobile-1') mob1 = mobile('Apple',...
def byte(n): return bytes([n]) def rlp_encode_bytes(x): if len(x) == 1 and x < b'\x80': # For a single byte whose value is in the [0x00, 0x7f] range, # that byte is its own RLP encoding. return x elif len(x) < 56: # Otherwise, if a string is 0-55 bytes long, the RLP encoding # consists of a s...
def byte(n): return bytes([n]) def rlp_encode_bytes(x): if len(x) == 1 and x < b'\x80': return x elif len(x) < 56: return byte(len(x) + 128) + x else: length = to_binary(len(x)) return byte(len(length) + 183) + length + x def rlp_encode_list(xs): sx = b''.join((rlp_...