content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python # -*- coding: utf-8 -*- def read_version(CMakeLists): version = [] with open(CMakeLists, 'r') as fp: for row in fp: if len(version) == 3: break if 'RSGD_MAJOR' in row: version.append(row.split('RSGD_MAJOR')[-1]) elif 'RSGD_MINOR' in row: version.append(ro...
def read_version(CMakeLists): version = [] with open(CMakeLists, 'r') as fp: for row in fp: if len(version) == 3: break if 'RSGD_MAJOR' in row: version.append(row.split('RSGD_MAJOR')[-1]) elif 'RSGD_MINOR' in row: versio...
""" File: a_to_z.py Prompts the user for a file name, then outputs each of the unique words from the file in alphabetical order """ unique = [] input_filename = input('Enter the input file name: ') print() with open(input_filename, "r") as f: lines = f.readlines() for line in lines: words = line.split...
""" File: a_to_z.py Prompts the user for a file name, then outputs each of the unique words from the file in alphabetical order """ unique = [] input_filename = input('Enter the input file name: ') print() with open(input_filename, 'r') as f: lines = f.readlines() for line in lines: words = line.split()...
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_op = ('<...
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ['cmp_op', 'hasconst', 'hasname', 'hasjrel', 'hasjabs', 'haslocal', 'hascompare', 'hasfree', 'opname', 'opmap', 'HAVE_ARGUMENT', 'EXTENDED_ARG'] cmp_op = ('<', '<=', '==', '!=', '>',...
Experiment(description='Testing the pure linear kernel', data_dir='../data/tsdlr/', max_depth=10, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=2, jitter_sd=0.1, max_jobs=500, ...
experiment(description='Testing the pure linear kernel', data_dir='../data/tsdlr/', max_depth=10, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=2, jitter_sd=0.1, max_jobs=500, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2013-10-01-pure-lin/', iters=25...
class FuzzyPaletteInvalidRepresentation(Exception): """ An Exception indicating that not enough classes have been provided to represent the fuzzy sets. """ def __init__(self, provided_labels: int, needed_labels: int): super().__init__(f"{needed_labels} labels are needed to represent the selecte...
class Fuzzypaletteinvalidrepresentation(Exception): """ An Exception indicating that not enough classes have been provided to represent the fuzzy sets. """ def __init__(self, provided_labels: int, needed_labels: int): super().__init__(f'{needed_labels} labels are needed to represent the selecte...
class Observer: def update(self, obj, *args, **kwargs): raise NotImplemented class Observable: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(obser...
class Observer: def update(self, obj, *args, **kwargs): raise NotImplemented class Observable: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(obse...
def my_func(): result = 3 * 2 return result print(my_func()) def format_name(f_name, l_name): """Take first and last name and format it and returns title version""" name = '' name += f_name.title() name += ' ' name += l_name.title() return name print(format_name('eddie', 'wang'))
def my_func(): result = 3 * 2 return result print(my_func()) def format_name(f_name, l_name): """Take first and last name and format it and returns title version""" name = '' name += f_name.title() name += ' ' name += l_name.title() return name print(format_name('eddie', 'wang'))
class ConstraintDeduplicatorMixin(object): def __init__(self, *args, **kwargs): super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs) self._constraint_hashes = set() def _blank_copy(self, c): super(ConstraintDeduplicatorMixin, self)._blank_copy(c) c._constraint_hash...
class Constraintdeduplicatormixin(object): def __init__(self, *args, **kwargs): super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs) self._constraint_hashes = set() def _blank_copy(self, c): super(ConstraintDeduplicatorMixin, self)._blank_copy(c) c._constraint_has...
def chainResult(num): while num != 1 and num != 89: s = str(num) num = 0 for c in s: num += int(c) * int(c) return num count = 0 for num in range(1,10000000): if chainResult(num) == 89: count += 1 print(count)
def chain_result(num): while num != 1 and num != 89: s = str(num) num = 0 for c in s: num += int(c) * int(c) return num count = 0 for num in range(1, 10000000): if chain_result(num) == 89: count += 1 print(count)
""" Time: O(N) Space: O(1) Keep updating the minimum element (`min1`) and the second minimum element (`min2`). When a new element comes up there are 3 possibilities. 0. Equals to min1 or min2 => do nothing. 1. Smaller than min1 => update min1. 2. Larger than min1 and smaller than min2 => update min2. 3. Larger than mi...
""" Time: O(N) Space: O(1) Keep updating the minimum element (`min1`) and the second minimum element (`min2`). When a new element comes up there are 3 possibilities. 0. Equals to min1 or min2 => do nothing. 1. Smaller than min1 => update min1. 2. Larger than min1 and smaller than min2 => update min2. 3. Larger than mi...
""" Created on 12.02.2010 @author: jupp """ def compute_similarity(lattice): similarity_index = {} for c1 in lattice: for c2 in lattice: if not (c1.concept_id in similarity_index and c2.concept_id in similarity_index[c1.concept_id]): if c1.concept_id not in similarity_...
""" Created on 12.02.2010 @author: jupp """ def compute_similarity(lattice): similarity_index = {} for c1 in lattice: for c2 in lattice: if not (c1.concept_id in similarity_index and c2.concept_id in similarity_index[c1.concept_id]): if c1.concept_id not in similarity_index...
""" ccextractor-web | forms.py Author : Saurabh Shrivastava Email : saurabh.shrivastava54+ccextractorweb[at]gmail.com Link : https://github.com/saurabhshri """
""" ccextractor-web | forms.py Author : Saurabh Shrivastava Email : saurabh.shrivastava54+ccextractorweb[at]gmail.com Link : https://github.com/saurabhshri """
def solution(board, moves): basket = [] answer = 0 for move in moves: for row in board: if row[move - 1] != 0: basket.append(row[move - 1]) row[move - 1] = 0 if len(basket) >= 2 and basket[-1] == basket[-2]: basket.pop(...
def solution(board, moves): basket = [] answer = 0 for move in moves: for row in board: if row[move - 1] != 0: basket.append(row[move - 1]) row[move - 1] = 0 if len(basket) >= 2 and basket[-1] == basket[-2]: basket.pop()...
class Const: board_width = 19 board_height = 19 n_in_row = 5 # n to win! train_core = "keras" check_freq = 10 # auto save current model check_freq_best = 500 # auto save best model
class Const: board_width = 19 board_height = 19 n_in_row = 5 train_core = 'keras' check_freq = 10 check_freq_best = 500
# -*- coding: utf-8 -*- # Copyright 2019 Julian Betz # # 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 l...
class Language: """Resources of a specific language. Stores information about the language and provides methods for text analysis that are tailored to that language. """ _languages = dict() def __init__(self, code, name, *, loader, tokenizer, extractor, parallel_extractor): if...
def insertion_sort(lst): """ Sorts list using insertion sort :param lst: list of unsorted elements :return comp: number of comparisons """ comp = 0 for i in range(1, len(lst)): key = lst[i] j = i - 1 cur_comp = 0 while j >= 0 and key < lst[j]: lst[...
def insertion_sort(lst): """ Sorts list using insertion sort :param lst: list of unsorted elements :return comp: number of comparisons """ comp = 0 for i in range(1, len(lst)): key = lst[i] j = i - 1 cur_comp = 0 while j >= 0 and key < lst[j]: lst[...
# Financial events the contract logs Transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value}) Buy: __log__({_buyer: indexed(address), _buy_order: currency_value}) Sell: __log__({_seller: indexed(address), _sell_order: currency_value}) Pay: __log__({_vendor: indexed(address), _amount: ...
transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value}) buy: __log__({_buyer: indexed(address), _buy_order: currency_value}) sell: __log__({_seller: indexed(address), _sell_order: currency_value}) pay: __log__({_vendor: indexed(address), _amount: wei_value}) company: public(address) ...
n = int(input("Enter the number of of rows: ")) for i in range(1,n+1): for j in range(1,i+1): print(j,end="") print()
n = int(input('Enter the number of of rows: ')) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end='') print()
def verify_format(_, res): return res def format_index(body): # pragma: no cover """Format index data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'id': body['id'].split('/', 1)[-1], 'fields': body['fields'] } ...
def verify_format(_, res): return res def format_index(body): """Format index data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'id': body['id'].split('/', 1)[-1], 'fields': body['fields']} if 'type' in body: result['type'] ...
# exc. 9.1.2 def file_options(file_name, task): if task == 'sort': edit_file = open(file_name, 'r') file_list = edit_file.read().split(' ') print(sorted(file_list)) edit_file.close() elif task == 'rev': edit_file = open(file_name, 'r') for line in edit_file: print(line[::-1]) edit_file....
def file_options(file_name, task): if task == 'sort': edit_file = open(file_name, 'r') file_list = edit_file.read().split(' ') print(sorted(file_list)) edit_file.close() elif task == 'rev': edit_file = open(file_name, 'r') for line in edit_file: print(...
# Singly Linked List class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(node.valu...
class Node: def __init__(self, value): self.value = value self.next = None class Linkedlist: def __init__(self): self.head = None def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(node.value) node ...
# -*- coding: utf-8 -*- """Top-level package for pyqmc.""" __author__ = """Maxime Godin""" __email__ = 'maximegodin@polytechnique.org' __version__ = '0.1.0'
"""Top-level package for pyqmc.""" __author__ = 'Maxime Godin' __email__ = 'maximegodin@polytechnique.org' __version__ = '0.1.0'
# Fibonacci Sequence: 0 1 1 2 3 5 8 13 ... def fibonacci(num): if num == 1: return 0 if num == 2: return 1 return fibonacci(num-1) + fibonacci(num-2) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5))
def fibonacci(num): if num == 1: return 0 if num == 2: return 1 return fibonacci(num - 1) + fibonacci(num - 2) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5))
cities = [ 'Sao Paulo', 'Rio de Janeiro', 'Salvador', 'Fortaleza', 'Belo Horizonte', 'Brasilia', 'Curitiba', 'Manaus', 'Recife', 'Belem', 'Porto Alegre', 'Goiania', 'Guarulhos', 'Campinas', 'Nova Iguacu', 'Maceio', 'Sao Luis', 'Duque de Caxias', ...
cities = ['Sao Paulo', 'Rio de Janeiro', 'Salvador', 'Fortaleza', 'Belo Horizonte', 'Brasilia', 'Curitiba', 'Manaus', 'Recife', 'Belem', 'Porto Alegre', 'Goiania', 'Guarulhos', 'Campinas', 'Nova Iguacu', 'Maceio', 'Sao Luis', 'Duque de Caxias', 'Natal', 'Teresina', 'Sao Bernardo do Campo', 'Campo Grande', 'Jaboatao', '...
##############class##################### class Board: """ This class defines the board object used in the game""" ##############constructeur################## def __init__(self): #self.boardTab = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] self.boardDic = {"A1":[0,"A2"],"A2":[0,"A3"],"A3":[0,"A4"...
class Board: """ This class defines the board object used in the game""" def __init__(self): self.boardDic = {'A1': [0, 'A2'], 'A2': [0, 'A3'], 'A3': [0, 'A4'], 'A4': [0, 'C1'], 'A5': [0, 'A6', 'C8'], 'A6': [0, 'Safe', 'A5'], 'B5': [0, 'B6', 'C8'], 'B6': [0, 'Safe', 'B5'], 'B1': [0, 'B2'], 'B2': [0, 'B...
__all__ = ('BaseIDGenerationStrategy', ) class BaseIDGenerationStrategy: def get_next_id(self, instance): raise NotImplementedError
__all__ = ('BaseIDGenerationStrategy',) class Baseidgenerationstrategy: def get_next_id(self, instance): raise NotImplementedError
# coding=utf-8 n, m = map(int, input().split()) s = [ list(str(input())) for _ in range(n) ] add = [[1, 0],[-1, 0],[0, 1],[0, -1]] ans = 'Yes' for i in range(n): for j in range(m): if s[i][j] == '.': continue mid = False for k in range(4): ii = i + add[k][0] jj = j ...
(n, m) = map(int, input().split()) s = [list(str(input())) for _ in range(n)] add = [[1, 0], [-1, 0], [0, 1], [0, -1]] ans = 'Yes' for i in range(n): for j in range(m): if s[i][j] == '.': continue mid = False for k in range(4): ii = i + add[k][0] jj = j + ...
orbits = dict() with open('input.txt') as f: for line in f: center, satellite = line.strip().split(")") orbits[satellite] = center def calc_distance_to_com(orbs, sat): dist = 1 cent = orbs[sat] while cent != "COM": cent = orbs[cent] dist += 1 return dist def find_ro...
orbits = dict() with open('input.txt') as f: for line in f: (center, satellite) = line.strip().split(')') orbits[satellite] = center def calc_distance_to_com(orbs, sat): dist = 1 cent = orbs[sat] while cent != 'COM': cent = orbs[cent] dist += 1 return dist def find_...
class ParseError(Exception) : """Super class for exception classes used in Parsers package. """ def __init__(self, file='', msg=''): self.file = str(file) self.msg = str(msg) def __str__(self): if self.msg : s = self.msg + ': ' else : s = '' ...
class Parseerror(Exception): """Super class for exception classes used in Parsers package. """ def __init__(self, file='', msg=''): self.file = str(file) self.msg = str(msg) def __str__(self): if self.msg: s = self.msg + ': ' else: s = '' ...
# Commonly used java test dependencies def java_test_repositories(): native.maven_jar( name = "junit", artifact = "junit:junit:4.12", sha1 = "2973d150c0dc1fefe998f834810d68f278ea58ec", ) native.maven_jar( name = "hamcrest_core", artifact = "org.hamcrest:hamcrest-core:1.3", sha1 = "42a25dc...
def java_test_repositories(): native.maven_jar(name='junit', artifact='junit:junit:4.12', sha1='2973d150c0dc1fefe998f834810d68f278ea58ec') native.maven_jar(name='hamcrest_core', artifact='org.hamcrest:hamcrest-core:1.3', sha1='42a25dc3219429f0e5d060061f71acb49bf010a0') native.maven_jar(name='org_mockito_moc...
# # PySNMP MIB module CISCO-VLAN-BRIDGING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-BRIDGING-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ...
def run(): # nombre = input('Escribe tu nombre: ') # for letra in nombre: # print(letra) frase = input('Escribe una frase: ') for c in frase: print(c.upper()) if __name__ == '__main__': run()
def run(): frase = input('Escribe una frase: ') for c in frase: print(c.upper()) if __name__ == '__main__': run()
def choose6(n,k): #computes nCk, the number of combinations n choose k result = 1 for i in range(n): result*=(i+1) for i in range(k): result/=(i+1) for i in range(n-k): result/=(i+1) return result
def choose6(n, k): result = 1 for i in range(n): result *= i + 1 for i in range(k): result /= i + 1 for i in range(n - k): result /= i + 1 return result
class ResultSet(list): """A list like object that holds results from a Unsplash API query.""" class Model(object): def __init__(self, **kwargs): self._repr_values = ["id"] @classmethod def parse(cls, data): """Parse a JSON object into a model instance.""" raise NotImplement...
class Resultset(list): """A list like object that holds results from a Unsplash API query.""" class Model(object): def __init__(self, **kwargs): self._repr_values = ['id'] @classmethod def parse(cls, data): """Parse a JSON object into a model instance.""" raise NotImplementedE...
class Rect(object): def __init__(self, cx, cy, width, height, confidence): self.cx = cx self.cy = cy self.width = width self.height = height self.confidence = confidence self.true_confidence = confidence def overlaps(self, other): if abs(self.cx - other.c...
class Rect(object): def __init__(self, cx, cy, width, height, confidence): self.cx = cx self.cy = cy self.width = width self.height = height self.confidence = confidence self.true_confidence = confidence def overlaps(self, other): if abs(self.cx - other....
class Transformer: def __init__(self, name, allegiance, strength, intelligence, speed, endurance, rank, courage, firepower, skill): """Initialization function for a Transformer.""" self.name = name self.allegiance = allegiance self.strength = strength self.intelligence = inte...
class Transformer: def __init__(self, name, allegiance, strength, intelligence, speed, endurance, rank, courage, firepower, skill): """Initialization function for a Transformer.""" self.name = name self.allegiance = allegiance self.strength = strength self.intelligence = int...
def main(request, response): headers = [("Content-Type", "text/plain")] command = request.GET.first("cmd").lower(); test_id = request.GET.first("id") header = request.GET.first("header") if command == "put": request.server.stash.put(test_id, request.headers.get(header, "")) elif command...
def main(request, response): headers = [('Content-Type', 'text/plain')] command = request.GET.first('cmd').lower() test_id = request.GET.first('id') header = request.GET.first('header') if command == 'put': request.server.stash.put(test_id, request.headers.get(header, '')) elif command =...
no_steps = 359 pos = 0 lst = [0] for x in range(1, 50000001): pos += no_steps pos %= len(lst) lst.insert(pos+1, x) pos += 1 print(lst[lst.index(0)+1])
no_steps = 359 pos = 0 lst = [0] for x in range(1, 50000001): pos += no_steps pos %= len(lst) lst.insert(pos + 1, x) pos += 1 print(lst[lst.index(0) + 1])
#!/usr/bin/env python # AUTHOR: jo # DATE: 2019-08-12 # DESCRIPTION: Tuse homework assignment #1. def partitionOnZeroSumAndMax(row): # Ex. Passing in [1,1,0,1] returns [2,0,1]. # max([2,0,1]) -> 2 localSums = [0] for val in row: if val != 0: localSums.append(localSums.pop() + val) ...
def partition_on_zero_sum_and_max(row): local_sums = [0] for val in row: if val != 0: localSums.append(localSums.pop() + val) else: localSums.append(0) return max(localSums) def get_distance_and_max(matrix): matrix_distance = [[None for row in range(len(matrix))]...
#!/usr/bin/env python2 def main(): n = input('') for i in range(0, n): rows = input('') matrix = [] for j in range(0, rows): matrix.append([int(x) for x in raw_input('').split()]) print(weight(matrix, 0, 0)) def weight(matrix, i, j): #print('weight called with',...
def main(): n = input('') for i in range(0, n): rows = input('') matrix = [] for j in range(0, rows): matrix.append([int(x) for x in raw_input('').split()]) print(weight(matrix, 0, 0)) def weight(matrix, i, j): if i < len(matrix) - 1: return matrix[i][j] ...
"""This module consist of API Groups. All the REST APIs are divided into several groups 1) Access 2) General 3) Organization 4) Service 5) Service Action Each group has a set of APIs with their own models and schemas. """
"""This module consist of API Groups. All the REST APIs are divided into several groups 1) Access 2) General 3) Organization 4) Service 5) Service Action Each group has a set of APIs with their own models and schemas. """
codon_protein = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCG": "Serine", "UCC": "Serine", "UCA": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", ...
codon_protein = {'AUG': 'Methionine', 'UUU': 'Phenylalanine', 'UUC': 'Phenylalanine', 'UUA': 'Leucine', 'UUG': 'Leucine', 'UCU': 'Serine', 'UCG': 'Serine', 'UCC': 'Serine', 'UCA': 'Serine', 'UAU': 'Tyrosine', 'UAC': 'Tyrosine', 'UGU': 'Cysteine', 'UGC': 'Cysteine', 'UGG': 'Tryptophan', 'UAA': None, 'UAG': None, 'UGA': ...
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other # Hatchet Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: MIT __version_info__ = ("2022", "1", "0") __version__ = ".".join(__version_info__)
__version_info__ = ('2022', '1', '0') __version__ = '.'.join(__version_info__)
# Time: O(n) # Space: O(1) class Solution(object): # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s <= root.val <= b: # Keep searching since ro...
class Solution(object): def lowest_common_ancestor(self, root, p, q): (s, b) = sorted([p.val, q.val]) while not s <= root.val <= b: root = root.left if s <= root.val else root.right return root
n = int(input()) nsum = 0 for i in range(1, n+1): nsum += i if nsum == 1: print('BOWWOW') elif nsum <= 3: print('WANWAN') else: for i in range(2, n+1): if n % i == 0: print('BOWWOW') break else: print('WANWAN')
n = int(input()) nsum = 0 for i in range(1, n + 1): nsum += i if nsum == 1: print('BOWWOW') elif nsum <= 3: print('WANWAN') else: for i in range(2, n + 1): if n % i == 0: print('BOWWOW') break else: print('WANWAN')
#!/usr/bin/env python3 def find_array_intersection(A, B): ai = 0 bi = 0 ret = [] while ai < len(A) and bi < len(B): if A[ai] < B[bi]: ai += 1 elif A[ai] > B[bi]: bi += 1 else: ret.append(A[ai]) v = A[ai] while ai < len(...
def find_array_intersection(A, B): ai = 0 bi = 0 ret = [] while ai < len(A) and bi < len(B): if A[ai] < B[bi]: ai += 1 elif A[ai] > B[bi]: bi += 1 else: ret.append(A[ai]) v = A[ai] while ai < len(A) and A[ai] == v: ...
""" --- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own. It seems like...
""" --- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own. It seems like...
def do_stuff(fn, lhs, rhs): return fn(lhs, rhs) def add(lhs, rhs): return lhs + rhs def multiply(lhs, rhs): return lhs * rhs def exponent(lhs, rhs): return lhs ** rhs print(do_stuff(add, 2, 3)) print(do_stuff(multiply, 2, 3)) print(do_stuff(exponent, 2, 3))
def do_stuff(fn, lhs, rhs): return fn(lhs, rhs) def add(lhs, rhs): return lhs + rhs def multiply(lhs, rhs): return lhs * rhs def exponent(lhs, rhs): return lhs ** rhs print(do_stuff(add, 2, 3)) print(do_stuff(multiply, 2, 3)) print(do_stuff(exponent, 2, 3))
# A tuple operates like a list but it's initial values can't be modified # Tuples are declared using the () # Use case examples of using Tuple - Dates of the week, Months of the Year, Hours of the clock # we can create a tuple like this... monthsOfTheYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug...
months_of_the_year = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') print(monthsOfTheYear) print(monthsOfTheYear[0]) print(monthsOfTheYear[:3]) my_tuple = ('Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun') print(len(myTuple)) print(sorted(myTuple)) names = ['John', 'Lamin', 'Vicky...
# class Solution: # def lengthOfLIS(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # O(n^2) complexity # if not nums: # return 0 # n = len(nums) # aux = [1] * n # for i in range(n): # for j in range(i): ...
class Solution: def length_of_lis(self, nums): """ O(nlogn) Binary Search+Greedy """ def binary_search(arr, target): """ find the position of this num """ low = 0 high = len(arr) while low < high: ...
def solve(array): even = [] odd = [] for i in range(len(array)): if array[i] % 2 == 0: even.append(i) else: odd.append(i) if even: return f"1\n{even[-1] + 1}" if len(odd) > 1: return f"2\n{odd[-1] + 1} {odd[-2] + 1}" else: retur...
def solve(array): even = [] odd = [] for i in range(len(array)): if array[i] % 2 == 0: even.append(i) else: odd.append(i) if even: return f'1\n{even[-1] + 1}' if len(odd) > 1: return f'2\n{odd[-1] + 1} {odd[-2] + 1}' else: return '-...
# These constants can be set by the external UI-layer process, don't change them manually is_ui_process = False execution_id = '' task_id = '' executable_name = 'insomniac' do_location_permission_dialog_checks = True # no need in these checks if location permission is denied beforehand def callback(profile_name): ...
is_ui_process = False execution_id = '' task_id = '' executable_name = 'insomniac' do_location_permission_dialog_checks = True def callback(profile_name): pass hardban_detected_callback = callback softban_detected_callback = callback def is_insomniac(): return execution_id == ''
defaults = ''' const vec4 light = vec4(4.0, 3.0, 10.0, 0.0); const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0); const mat4 mvp = mat4( -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972, 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617...
defaults = '\n const vec4 light = vec4(4.0, 3.0, 10.0, 0.0);\n const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0);\n const mat4 mvp = mat4(\n -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972,\n 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057...
class OutOfService(Exception): def __init__(self,Note:str=""): pass class InternalError(Exception): def __init__(self,Note:str=""): pass class NothingFoundError(Exception): def __init__(self,Note:str=""): pass class DummyError(Exception): def __init__(self,Note:str=""):...
class Outofservice(Exception): def __init__(self, Note: str=''): pass class Internalerror(Exception): def __init__(self, Note: str=''): pass class Nothingfounderror(Exception): def __init__(self, Note: str=''): pass class Dummyerror(Exception): def __init__(self, Note: str...
"""Cayley 2020, Problem 20""" def is_divisible(n, d): return (n % d) == 0 def solutions(): a = range(1, 101) b = range(101, 206) return [(m, n) for m in a for n in b if is_divisible(3**m + 7**n, 10)] s = solutions() a = len(s) print(f'Answer = {a}')
"""Cayley 2020, Problem 20""" def is_divisible(n, d): return n % d == 0 def solutions(): a = range(1, 101) b = range(101, 206) return [(m, n) for m in a for n in b if is_divisible(3 ** m + 7 ** n, 10)] s = solutions() a = len(s) print(f'Answer = {a}')
a = [1, 4, 5, 7, 19, 24] b = [4, 6, 7, 18, 24, 134] i = 0 j = 0 ans = [] while i < len(a) and j < len(b): if a[i] == b[j]: ans.append(a[i]) i += 1 j += 1 elif a[i] < b[j]: i += 1 else: j += 1 print(*ans)
a = [1, 4, 5, 7, 19, 24] b = [4, 6, 7, 18, 24, 134] i = 0 j = 0 ans = [] while i < len(a) and j < len(b): if a[i] == b[j]: ans.append(a[i]) i += 1 j += 1 elif a[i] < b[j]: i += 1 else: j += 1 print(*ans)
class Node: def __init__(self, value): self.value = value self.next = None class Queue(object): def __init__(self, size): self.queue = [] self.size = size def enqueue(self, value): '''This function adds an value to the rear end of the queue ''' if(self.isFull() !...
class Node: def __init__(self, value): self.value = value self.next = None class Queue(object): def __init__(self, size): self.queue = [] self.size = size def enqueue(self, value): """This function adds an value to the rear end of the queue """ if self.isF...
bill_board = list(map(int, input().split())) tarp = list(map(int, input().split())) xOverlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0) yOverlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0) if xOverlap == 0 or yOverlap == 0: print((bill_board[2] - bill_boar...
bill_board = list(map(int, input().split())) tarp = list(map(int, input().split())) x_overlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0) y_overlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0) if xOverlap == 0 or yOverlap == 0: print((bill_board[2] - bill_board[0]) * (...
""" --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes firs...
""" --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes firs...
''' Edges in a block diagram computational graph. The edges themselves don't have direction, but the ports that they attach to may. ''' class WireConnection: pass class NamedConnection(WireConnection): def __init__(self, target_uid: int, target_port: str): self.target_uid = target_uid self.t...
""" Edges in a block diagram computational graph. The edges themselves don't have direction, but the ports that they attach to may. """ class Wireconnection: pass class Namedconnection(WireConnection): def __init__(self, target_uid: int, target_port: str): self.target_uid = target_uid self.ta...
RADIO_ENABLED = ":white_check_mark: **Radio enabled**" RADIO_DISABLED = ":x: **Radio disabled**" SKIPPED = ":fast_forward: **Skipped** :thumbsup:" NO_MATCH = ":x: **No matches**" SEARCHING = ":trumpet: **Searching** :mag_right:" PAUSE = "**Paused** :pause_button:" STOP = "**Stopped** :stop_button:" LOOP_ENABLED =...
radio_enabled = ':white_check_mark: **Radio enabled**' radio_disabled = ':x: **Radio disabled**' skipped = ':fast_forward: **Skipped** :thumbsup:' no_match = ':x: **No matches**' searching = ':trumpet: **Searching** :mag_right:' pause = '**Paused** :pause_button:' stop = '**Stopped** :stop_button:' loop_enabled = '**Lo...
def leiaInt(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except (KeyboardInterrupt): print('Entrada interromepida pelo usuario') return 0 else: ...
def leia_int(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except KeyboardInterrupt: print('Entrada interromepida pelo usuario') return 0 ...
#leia um numero inteiro e #imprima a soma do sucessor de seu triplo com #o antecessor de seu dobro num=int(input("Informe um numero: ")) valor=((num*3)+1)+((num*2)-1) print(f"A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}")
num = int(input('Informe um numero: ')) valor = num * 3 + 1 + (num * 2 - 1) print(f'A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}')
""" [Weekly #22] Machine Learning https://www.reddit.com/r/dailyprogrammer/comments/3206mk/weekly_22_machine_learning/ # [](#WeeklyIcon) Asimov would be proud! [Machine learning](http://en.wikipedia.org/wiki/Machine_learning) is a diverse field spanning from optimization and data classification, to computer vision an...
""" [Weekly #22] Machine Learning https://www.reddit.com/r/dailyprogrammer/comments/3206mk/weekly_22_machine_learning/ # [](#WeeklyIcon) Asimov would be proud! [Machine learning](http://en.wikipedia.org/wiki/Machine_learning) is a diverse field spanning from optimization and data classification, to computer vision an...
input = open('input.txt', 'r').read().split("\n") depths = list(map(lambda s: int(s), input)) increases = 0; for i in range(1, len(depths)): if depths[i-2] + depths[i-1] + depths[i] > depths[i-3] + depths[i-2] + depths[i-1]: increases += 1 print(increases)
input = open('input.txt', 'r').read().split('\n') depths = list(map(lambda s: int(s), input)) increases = 0 for i in range(1, len(depths)): if depths[i - 2] + depths[i - 1] + depths[i] > depths[i - 3] + depths[i - 2] + depths[i - 1]: increases += 1 print(increases)
#!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merg...
class Heightmapinterface(object): def __init__(self, image, width, depth, scale, height_scale, pixel_is_tuple=False): self.height_map_image = image self.scale = scale self.height_scale = height_scale self.width = width self.depth = depth self.x_offset = 0 sel...
class NasmPackage (Package): def __init__ (self): Package.__init__ (self, 'nasm', '2.10.07', sources = [ 'http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz' ]) NasmPackage ()
class Nasmpackage(Package): def __init__(self): Package.__init__(self, 'nasm', '2.10.07', sources=['http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz']) nasm_package()
''' Description: Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree ...
""" Description: Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree ...
number_of_drugs = 5 max_id = 1<<5 string_length = len("{0:#b}".format(max_id-1)) -2 EC50_for_0 = 0.75 EC50_for_1 = 1.3 f = lambda x: EC50_for_0 if x=='0' else EC50_for_1 print("[\n", end="") for x in range(0,max_id): gene_string = ("{0:0"+str(string_length)+"b}").format(x) ec50 = list(map(f, list(gene_strin...
number_of_drugs = 5 max_id = 1 << 5 string_length = len('{0:#b}'.format(max_id - 1)) - 2 ec50_for_0 = 0.75 ec50_for_1 = 1.3 f = lambda x: EC50_for_0 if x == '0' else EC50_for_1 print('[\n', end='') for x in range(0, max_id): gene_string = ('{0:0' + str(string_length) + 'b}').format(x) ec50 = list(map(f, list(ge...
input1='389125467' input2='496138527' lowest=1 highest=1000000 class Node: def __init__(self, val, next_node=None): self.val=val self.next=next_node cups=list(input2) cups=list(map(int,cups)) lookup_table={} prev=None # form linked list from the end node to beginning node for i in range(len(cups)...
input1 = '389125467' input2 = '496138527' lowest = 1 highest = 1000000 class Node: def __init__(self, val, next_node=None): self.val = val self.next = next_node cups = list(input2) cups = list(map(int, cups)) lookup_table = {} prev = None for i in range(len(cups) - 1, -1, -1): new = node(cups[...
def counting_sort(arr): k = max(arr) count = [0] * k + [0] for x in arr: count[x] += 1 for i in range(1, len(count)): count[i] = count[i] + count[i-1] output = [0] * len(arr) for x in arr: output[count[x]-1] = x yield output, count[x]-1 count[x] -= 1 ...
def counting_sort(arr): k = max(arr) count = [0] * k + [0] for x in arr: count[x] += 1 for i in range(1, len(count)): count[i] = count[i] + count[i - 1] output = [0] * len(arr) for x in arr: output[count[x] - 1] = x yield (output, count[x] - 1) count[x] -=...
number = int(input()) if 100 <= number <= 200 or number == 0: pass else: print('invalid')
number = int(input()) if 100 <= number <= 200 or number == 0: pass else: print('invalid')
def nth(test, items): if test > 0: test -= 1 else: test = 0 for i, v in enumerate(items): if i == test: return v
def nth(test, items): if test > 0: test -= 1 else: test = 0 for (i, v) in enumerate(items): if i == test: return v
# Combinations class Solution: def combine(self, n, k): ans = [] def helper(choices, start, count, ans): if count == k: # cloning the list here ans.append(list(choices)) return for i in range(start, n + 1): ch...
class Solution: def combine(self, n, k): ans = [] def helper(choices, start, count, ans): if count == k: ans.append(list(choices)) return for i in range(start, n + 1): choices[count] = i helper(choices, i + 1, ...
class PyTime: def printTime(self,input): time_in_string = str(input) length = len(time_in_string) if length == 3: hour,minute1,minute2 = time_in_string hours = "0" + hour minutes = minute1 + minute2 converted_time = self.calculate...
class Pytime: def print_time(self, input): time_in_string = str(input) length = len(time_in_string) if length == 3: (hour, minute1, minute2) = time_in_string hours = '0' + hour minutes = minute1 + minute2 converted_time = self.calculateTime(ho...
# create sets names = {'anonymous','tazri','farha'}; extra_name = {'tazri','farha','troy'}; name_list = {'solus','xenon','neon'}; name_tuple = ('helium','hydrogen'); print("names : ",names); # add focasa in names print("add 'focasa' than set : "); names.add("focasa"); print(names); # update method print("\n\nadd ext...
names = {'anonymous', 'tazri', 'farha'} extra_name = {'tazri', 'farha', 'troy'} name_list = {'solus', 'xenon', 'neon'} name_tuple = ('helium', 'hydrogen') print('names : ', names) print("add 'focasa' than set : ") names.add('focasa') print(names) print('\n\nadd extra_name in set with update method : ') names.update(ext...
#! /usr/bin/python3.6 def create_spa_workbench(document): """ :param document: :return: workbench com object """ return document.GetWorkbench("SPAWorkbench")
def create_spa_workbench(document): """ :param document: :return: workbench com object """ return document.GetWorkbench('SPAWorkbench')
user = int(input("ENTER NUMBER OF STUDENTS IN CLASS : ")) i = 1 marks = [] absent = [] # mark = marks.copy() print("FOR ABSENT STUDENTS TYPE -1 AS MARKS") for j in range(user): student = int(input("ENTER MARKS OF STUDENT {} : ".format(i))) if student == -1: absent.append(i) else: ...
user = int(input('ENTER NUMBER OF STUDENTS IN CLASS : ')) i = 1 marks = [] absent = [] print('FOR ABSENT STUDENTS TYPE -1 AS MARKS') for j in range(user): student = int(input('ENTER MARKS OF STUDENT {} : '.format(i))) if student == -1: absent.append(i) else: marks.append(student) i += 1...
def sum_func(num1,num2 =30,num3=40): return num1 + num2 + num3 print(sum_func(10)) print(sum_func(10,20)) print(sum_func(10,20,30))
def sum_func(num1, num2=30, num3=40): return num1 + num2 + num3 print(sum_func(10)) print(sum_func(10, 20)) print(sum_func(10, 20, 30))
#!/usr/bin/env python # -*- config : utf-8 -*- 'help' class Report(object): """ You can wirte the report has created into a html file. """ def __init__(self, headtitle, content): self.headtitle = 'Bat''s' + headtitle self.content = content def replace(self): self.cont...
"""help""" class Report(object): """ You can wirte the report has created into a html file. """ def __init__(self, headtitle, content): self.headtitle = 'Bats' + headtitle self.content = content def replace(self): self.content = self.content.replace('\n', '<br>') s...
def variableName(name): str_name = [i for i in str(name)] non_acc_chars = [ " ", ">", "<", ":", "-", "|", ".", ",", "!", "[", "]", "'", "/", "@", "#", "&", "%", "?", ...
def variable_name(name): str_name = [i for i in str(name)] non_acc_chars = [' ', '>', '<', ':', '-', '|', '.', ',', '!', '[', ']', "'", '/', '@', '#', '&', '%', '?', '*'] if str_name[0] in str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): return False for j in range(len(str_name)): if str_name[j] in ...
class Vector2d( object, ISerializable, IEquatable[Vector2d], IComparable[Vector2d], IComparable, IEpsilonComparable[Vector2d], ): """ Represents the two components of a vector in two-dimensional space, using System.Double-precision floating point numbers. Vector2d(x...
class Vector2D(object, ISerializable, IEquatable[Vector2d], IComparable[Vector2d], IComparable, IEpsilonComparable[Vector2d]): """ Represents the two components of a vector in two-dimensional space, using System.Double-precision floating point numbers. Vector2d(x: float,y: float) """ def compare_to...
def palindrome(num): return str(num) == str(num)[::-1] # Bots are software programs that combine requests # top Returns a reference to the top most element of the stack def largest(bot, top): z = 0 for i in range(top, bot, -1): for j in range(top, bot, -1): if palindrome(i ...
def palindrome(num): return str(num) == str(num)[::-1] def largest(bot, top): z = 0 for i in range(top, bot, -1): for j in range(top, bot, -1): if palindrome(i * j): if i * j > z: z = i * j return z print(largest(100, 999))
# # Copyright (c) 2020 Xilinx, Inc. All rights reserved. # SPDX-License-Identifier: MIT # plnx_package_boot = True # Generate Package Boot Images
plnx_package_boot = True
# # PySNMP MIB module AGG-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGG-TRAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:15:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
(dev_name, mate_host, unknown_device_trap_contents, pep_name, old_file, reason, result, mate_port, file, sb_producer_port, port, sn_name, host, my_host, minutes, new_file, sb_producer_host, my_port) = mibBuilder.importSymbols('AGGREGATED-EXT-MIB', 'devName', 'mateHost', 'unknownDeviceTrapContents', 'pepName', 'oldFile'...
nums = [int(input()) for _ in range(int(input()))] nums_count = [nums.count(a) for a in nums] min_count, max_count - min(nums_count), max(nums_count) min_num, max_num = 0, 0 a, b = 0, 0 for i in range(len(nums)): if nums_count[i] > b: max_num = nums[i] elif nums_count[i] == b: if nums[i] > max_num: max_num...
nums = [int(input()) for _ in range(int(input()))] nums_count = [nums.count(a) for a in nums] (min_count, max_count - min(nums_count), max(nums_count)) (min_num, max_num) = (0, 0) (a, b) = (0, 0) for i in range(len(nums)): if nums_count[i] > b: max_num = nums[i] elif nums_count[i] == b: if nums[...
# File: phishtank_consts.py # # Copyright (c) 2016-2021 Splunk Inc. # # 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 a...
phishtank_domain = 'http://www.phishtank.com' phishtank_api_domain = 'https://checkurl.phishtank.com/checkurl/' phishtank_app_key = 'app_key' phishtank_msg_query_url = 'Querying URL: {query_url}' phishtank_msg_connecting = 'Polling Phishtank site ...' phishtank_service_succ_msg = 'Phishtank Service successfully execute...
# -*- coding: utf-8 -*- { 'name': 'Events', 'category': 'Website/Website', 'sequence': 166, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': "", 'depends': ['website', 'website_partner', 'website_mail', 'event'], 'data': [ ...
{'name': 'Events', 'category': 'Website/Website', 'sequence': 166, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': '', 'depends': ['website', 'website_partner', 'website_mail', 'event'], 'data': ['data/event_data.xml', 'views/res_config_settings_views.xml', 'view...
Ds = [1, 1.2, 1.5, 2, 4] file_name = "f.csv" f = open(file_name, 'r') for depth in Ds: print('\n\n DEALING WITH ALL D = ', depth-1) DATA['below_depth'] = (depth - 1) * HEIGHT for angle in range(2,90,1): if angle %5 ==0: continue if angle >= 50 and angle <=60: continue f.close...
ds = [1, 1.2, 1.5, 2, 4] file_name = 'f.csv' f = open(file_name, 'r') for depth in Ds: print('\n\n DEALING WITH ALL D = ', depth - 1) DATA['below_depth'] = (depth - 1) * HEIGHT for angle in range(2, 90, 1): if angle % 5 == 0: continue if angle >= 50 and angle <= 60: c...
class Db(): def __init__(self, section, host, wiki): self.section = section self.host = host self.wiki = wiki
class Db: def __init__(self, section, host, wiki): self.section = section self.host = host self.wiki = wiki
"""Classes for handling geometry. Geometric objects (see :class:`GeometricObject`) are usually used in :class:`~ihm.restraint.GeometricRestraint` objects. """ class Center(object): """Define the center of a geometric object in Cartesian space. :param float x: x coordinate :param float y: y co...
"""Classes for handling geometry. Geometric objects (see :class:`GeometricObject`) are usually used in :class:`~ihm.restraint.GeometricRestraint` objects. """ class Center(object): """Define the center of a geometric object in Cartesian space. :param float x: x coordinate :param float y: y co...
# a dp method class Solution: def longestPalindrome(self, s: str) -> str: size = len(s) if size < 2: return s dp = [[False for _ in range(size)] for _ in range(size)] maxLen = 1 start = 0 for i in range(size): dp[i][i] = True ...
class Solution: def longest_palindrome(self, s: str) -> str: size = len(s) if size < 2: return s dp = [[False for _ in range(size)] for _ in range(size)] max_len = 1 start = 0 for i in range(size): dp[i][i] = True for j in range(1, siz...
""" Use the Eratoshenes Algorithm to generate first 1229 prime numbers. """ max = 10000 smax = 100 # sqrt(10000) lst = [] # number list, all True (is prime) at first for i in range(max + 1): # initialization lst.append(True) for i in range(2, smax + 1): # Eratoshenes Algorithm sieve = 2 * i while sieve...
""" Use the Eratoshenes Algorithm to generate first 1229 prime numbers. """ max = 10000 smax = 100 lst = [] for i in range(max + 1): lst.append(True) for i in range(2, smax + 1): sieve = 2 * i while sieve <= max: lst[sieve] = False sieve += i for i in range(2, max + 1): if lst[i] == True...
#Votes Voter0 = int(input("Vote:")) Voter1 = int(input("Vote:")) Voter2 = int(input("Vote:")) #Count def count_votes(): #Accounts voter0_account = 0 voter1_account = 0 voter2_account = 0 #Total total = Voter0 + Voter1 + Voter2 #Return if total > 1: voter2_account =+ 1 ...
voter0 = int(input('Vote:')) voter1 = int(input('Vote:')) voter2 = int(input('Vote:')) def count_votes(): voter0_account = 0 voter1_account = 0 voter2_account = 0 total = Voter0 + Voter1 + Voter2 if total > 1: voter2_account = +1 print(voter2_account) else: print(voter2_...
otra_coordenada=(0, 1) new=otra_coordenada.x print(new)
otra_coordenada = (0, 1) new = otra_coordenada.x print(new)
#!/usr/bin/env python # coding: utf-8 # Given two arrays, write a function to compute their intersection. # # Example 1: # # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2] # Example 2: # # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # In[1]: def intersection(nums1, nums2): return list(...
def intersection(nums1, nums2): return list(set(nums1) & set(nums2)) print(intersection([4, 9, 5], [9, 4, 9, 8, 4])) def intersection(nums1, nums2): stack = [] for i in nums1: if i not in stack and i in nums2: stack.append(i) return stack print(intersection([4, 9, 5], [9, 4, 9, 8, 4...
s = 0 for c in range(0, 6): n = int(input('Digite numero inteiro: ')) if n%2==0: s += n print(f'A soma dos valores par e {s}')
s = 0 for c in range(0, 6): n = int(input('Digite numero inteiro: ')) if n % 2 == 0: s += n print(f'A soma dos valores par e {s}')
#stringCaps.py msg = "john nash" print(msg) # ALL CAPS msg_upper = msg.upper() print(msg_upper) # First Letter Of Each Word Capitalized msg_title = msg.title() print(msg_title)
msg = 'john nash' print(msg) msg_upper = msg.upper() print(msg_upper) msg_title = msg.title() print(msg_title)
def create_500M_file(name): native.genrule( name = name + "_target", outs = [name], output_to_bindir = 1, cmd = "truncate -s 500M $@", )
def create_500_m_file(name): native.genrule(name=name + '_target', outs=[name], output_to_bindir=1, cmd='truncate -s 500M $@')
hotels = pois[pois['fclass']=='hotel'] citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze() cityhotels = hotels[hotels.within(citylondon)] [fig,ax] = plt.subplots(1, figsize=(12, 8)) base = boroughs.plot(color='lightblue', edgecolor='black',ax=ax); cityhotels.plot(ax=ax, marker='o', co...
hotels = pois[pois['fclass'] == 'hotel'] citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze() cityhotels = hotels[hotels.within(citylondon)] [fig, ax] = plt.subplots(1, figsize=(12, 8)) base = boroughs.plot(color='lightblue', edgecolor='black', ax=ax) cityhotels.plot(ax=ax, marker='o', ...