content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# These are local default variables for development # In deployment on Heroku's systems, these variables are changed DEBUG = True SECRET_KEY = "super_secret_key" LILLINK_REDIS_URL = "redis://localhost:6379/0"
debug = True secret_key = 'super_secret_key' lillink_redis_url = 'redis://localhost:6379/0'
numeroA = int(input('Digite um numero...')) outroNumero = int(input('Digite outro numero')) sum = numeroA + outroNumero print('A soma de {} e {} eh igual a {}' .format(numeroA, outroNumero, sum))
numero_a = int(input('Digite um numero...')) outro_numero = int(input('Digite outro numero')) sum = numeroA + outroNumero print('A soma de {} e {} eh igual a {}'.format(numeroA, outroNumero, sum))
file = open('2021\D8\input.txt','r').read().splitlines() s = [] mapcode = { 'a':'', 'b':'', 'c':'', 'd':'', 'e':'', 'f':'', 'g':'' } wirecode = { 0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:'' } numcode = { 0:'abcefg', 1:'cf', 2:'ac...
file = open('2021\\D8\\input.txt', 'r').read().splitlines() s = [] mapcode = {'a': '', 'b': '', 'c': '', 'd': '', 'e': '', 'f': '', 'g': ''} wirecode = {0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: ''} numcode = {0: 'abcefg', 1: 'cf', 2: 'acdeg', 3: 'acdfg', 4: 'bcdf', 5: 'abdfg', 6: 'abdefg', 7: '...
#!/usr/bin/env python # -*- coding: utf-8 -*- n = list(map(int, input().split())) def slove1(): ans, tmp = 0, -1 lmax,rmax = [0]*len(n), [0]*len(n) for i in range(1, len(n)): tmp = max(tmp, n[i-1]) lmax[i] = tmp tmp = -1 for i in range(len(n)-2, -1, -1): tmp = max(tmp, n[i+...
n = list(map(int, input().split())) def slove1(): (ans, tmp) = (0, -1) (lmax, rmax) = ([0] * len(n), [0] * len(n)) for i in range(1, len(n)): tmp = max(tmp, n[i - 1]) lmax[i] = tmp tmp = -1 for i in range(len(n) - 2, -1, -1): tmp = max(tmp, n[i + 1]) rmax[i] = tmp ...
# listFunctions.py # Contains basic list manipulation functions # J. Hassler Thurston # 26 November 2013 (Adapted from Mathematica code written in 2010/2011) # Python 2.7.6 # returns a running sum of the elements in ls def cumulativeSum(ls): total = 0 answer = [] for i in ls: total += i ...
def cumulative_sum(ls): total = 0 answer = [] for i in ls: total += i answer.append(total) return answer def cumulative_sum_zero(ls): total = 0 answer = [0] for i in ls: total += i answer.append(total) return answer
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: binary_list = [] current = head while current: ...
class Solution: def get_decimal_value(self, head: ListNode) -> int: binary_list = [] current = head while current: binary_list.append(str(current.val)) current = current.next return int(''.join(binary_list), 2)
_item_fullname_='Bio.Seq.Seq' def is_biopython_Seq(item): item_fullname = item.__class__.__module__+'.'+item.__class__.__name__ return _item_fullname_==item_fullname
_item_fullname_ = 'Bio.Seq.Seq' def is_biopython__seq(item): item_fullname = item.__class__.__module__ + '.' + item.__class__.__name__ return _item_fullname_ == item_fullname
def ci(A, l, r, k): while r-l > 1: mid = (l + (r-l))//2 if A[mid] >= k: r=mid else: l=mid return r def longestSubsequence(a,n): t = [0 for _ in range(n+1)] l=0 t[0] = a[0] l=1 for i in range(1, n): if a[i] < t[0]: t[0] = a[...
def ci(A, l, r, k): while r - l > 1: mid = (l + (r - l)) // 2 if A[mid] >= k: r = mid else: l = mid return r def longest_subsequence(a, n): t = [0 for _ in range(n + 1)] l = 0 t[0] = a[0] l = 1 for i in range(1, n): if a[i] < t[0]: ...
passmark=0 # declaring variables defer=0 fail=0 all=0 def all(): try: #this won't let strings to pass while True: passmark=int(input("Enter the Pass mark :")) # getting the user's passmark if passmark == 0 or passmark == 20 or passmark == 40 or passmark == ...
passmark = 0 defer = 0 fail = 0 all = 0 def all(): try: while True: passmark = int(input('Enter the Pass mark :')) if passmark == 0 or passmark == 20 or passmark == 40 or (passmark == 60) or (passmark == 80) or (passmark == 100) or (passmark == 120): while True: ...
def extract(graph): ''' Generate a dictionary from a NetworkX Graph. The key is the index (primary node identifier) of the node in the graph. The value is a dict with index, label (original node identifier), room (a node attribute from the source data), and a list of neighbors (by graph index v...
def extract(graph): """ Generate a dictionary from a NetworkX Graph. The key is the index (primary node identifier) of the node in the graph. The value is a dict with index, label (original node identifier), room (a node attribute from the source data), and a list of neighbors (by graph index v...
def dobra_lista(lista): nova_lista = [] for valor in lista: novo_elemento = 2 * valor nova_lista.append(novo_elemento) return nova_lista #---------------------------------------------------------------- numeros = [3, 6, 10] numeros_emdobro = dobra_lista(numeros) print(numeros) print(numeros...
def dobra_lista(lista): nova_lista = [] for valor in lista: novo_elemento = 2 * valor nova_lista.append(novo_elemento) return nova_lista numeros = [3, 6, 10] numeros_emdobro = dobra_lista(numeros) print(numeros) print(numeros_emdobro)
def test_length(devnetwork, chain): assert len(chain) == 1 chain.mine(4) assert len(chain) == 5 def test_length_after_revert(devnetwork, chain): chain.mine(4) chain.snapshot() chain.mine(20) assert len(chain) == 25 chain.revert() assert len(chain) == 5 def test_getitem_negative_...
def test_length(devnetwork, chain): assert len(chain) == 1 chain.mine(4) assert len(chain) == 5 def test_length_after_revert(devnetwork, chain): chain.mine(4) chain.snapshot() chain.mine(20) assert len(chain) == 25 chain.revert() assert len(chain) == 5 def test_getitem_negative_ind...
class Node: __slots__ = ['key','value','prev','next'] def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity): self.capacity = capacity self.size = 0 self.mapp...
class Node: __slots__ = ['key', 'value', 'prev', 'next'] def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class Lrucache: def __init__(self, capacity): self.capacity = capacity self.size = 0 self.ma...
#!/usr/bin/env python3 # https://abc067.contest.atcoder.jp/tasks/arc078_a n = int(input()) a = [int(x) for x in input().split()] s = sum(a) b = a[0] m = abs(s - 2 * b) for i in range(1, n - 1): b += a[i] m = min(m, abs(s - 2 * b)) print(m)
n = int(input()) a = [int(x) for x in input().split()] s = sum(a) b = a[0] m = abs(s - 2 * b) for i in range(1, n - 1): b += a[i] m = min(m, abs(s - 2 * b)) print(m)
# SPDX-License-Identifier: MIT # # keys.py - includes Discord bot token # # Copyright (c) 2019 Joe Dai. TOKEN = ''
token = ''
model = Model() i1 = Input("input", "TENSOR_FLOAT32", "{3,4,2}") perms = Parameter("perms", "TENSOR_INT32", "{3}", [1, 0, 2]) output = Output("output", "TENSOR_FLOAT32", "{4,3,2}") model = model.Operation("TRANSPOSE", i1, perms).To(output) # Example 1. Input in operand 0, input0 = {i1: # input 0 [0, 1, 2, 3...
model = model() i1 = input('input', 'TENSOR_FLOAT32', '{3,4,2}') perms = parameter('perms', 'TENSOR_INT32', '{3}', [1, 0, 2]) output = output('output', 'TENSOR_FLOAT32', '{4,3,2}') model = model.Operation('TRANSPOSE', i1, perms).To(output) input0 = {i1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,...
description = 'TOF counter devices' group = 'lowlevel' tango_base = 'tango://cpci3.toftof.frm2:10000/' devices = dict( timer = device('nicos.devices.entangle.TimerChannel', description = 'The TOFTOF timer', tangodevice = tango_base + 'toftof/det/timer', fmtstr = '%.1f', visibility...
description = 'TOF counter devices' group = 'lowlevel' tango_base = 'tango://cpci3.toftof.frm2:10000/' devices = dict(timer=device('nicos.devices.entangle.TimerChannel', description='The TOFTOF timer', tangodevice=tango_base + 'toftof/det/timer', fmtstr='%.1f', visibility=()), monitor=device('nicos.devices.entangle.Cou...
def colorify(s, color): color_map = { "grey": "\033[90m", "red": "\033[91m", "green": "\033[92m", "yellow": "\033[93m", "purple": "\033[94m", "pink": "\033[95m", "blue": "\033[96m", } return color_map[color] + s + "\033[0m" def underline(s): ret...
def colorify(s, color): color_map = {'grey': '\x1b[90m', 'red': '\x1b[91m', 'green': '\x1b[92m', 'yellow': '\x1b[93m', 'purple': '\x1b[94m', 'pink': '\x1b[95m', 'blue': '\x1b[96m'} return color_map[color] + s + '\x1b[0m' def underline(s): return '\x1b[4m' + s + '\x1b[0m'
class ItemAlreadyStored(Exception): pass class ItemNotStored(Exception): pass
class Itemalreadystored(Exception): pass class Itemnotstored(Exception): pass
_base_="../base-chexpert-chest_xray_kids-config.py" # epoch related total_iters=5000 checkpoint_config = dict(interval=total_iters) model = dict( pretrained='work_dirs/hpt-pretrain/resisc/moco_v2_800ep_basetrain/50000-iters/moco_v2_800ep_basetrain-resisc_50000it.pth', backbone=dict( norm_train=True, frozen_...
_base_ = '../base-chexpert-chest_xray_kids-config.py' total_iters = 5000 checkpoint_config = dict(interval=total_iters) model = dict(pretrained='work_dirs/hpt-pretrain/resisc/moco_v2_800ep_basetrain/50000-iters/moco_v2_800ep_basetrain-resisc_50000it.pth', backbone=dict(norm_train=True, frozen_stages=4)) optimizer = dic...
# # Copyright 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 applicable law or agreed to in writing, so...
dict_datamodel_tag = {'Alerts': ['alert'], 'Authentication': ['authentication'], 'Authentication_Default_Authentication': ['default', 'authentication'], 'Authentication_Insecure_Authentication': ['authentication', 'insecure'], 'Authentication_Insecure_Authentication.2': ['authentication', 'cleartext'], 'Authentication_...
# Python - 3.6.0 Test.describe('thirt') Test.it('Basic tests') Test.assert_equals(thirt(8529), 79) Test.assert_equals(thirt(85299258), 31) Test.assert_equals(thirt(5634), 57) Test.assert_equals(thirt(1111111111), 71) Test.assert_equals(thirt(987654321), 30)
Test.describe('thirt') Test.it('Basic tests') Test.assert_equals(thirt(8529), 79) Test.assert_equals(thirt(85299258), 31) Test.assert_equals(thirt(5634), 57) Test.assert_equals(thirt(1111111111), 71) Test.assert_equals(thirt(987654321), 30)
class HistMovementManager: def __init__(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def make_screen(self, board): if self.cur_board != -1 and self.boards_hist[self.cur_board] == board: return self.boards_hist.append(board) self.c...
class Histmovementmanager: def __init__(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def make_screen(self, board): if self.cur_board != -1 and self.boards_hist[self.cur_board] == board: return self.boards_hist.append(board) self.c...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- __all__ = [ "functions", "dbcontent", "sqlite_helper", "global_variable" ]
__all__ = ['functions', 'dbcontent', 'sqlite_helper', 'global_variable']
float_type = type(1.0) int_type = type(1) string_type = type('') date_type = 'iso8601' unicode_type = type(u'') bool_type = type(True) map_type = type({}) seq_type = type([]) tuple_type = type(()) def is_string(obj): t = type(obj) return t is string_type or t is unicode_type def is_int(obj): return type(o...
float_type = type(1.0) int_type = type(1) string_type = type('') date_type = 'iso8601' unicode_type = type(u'') bool_type = type(True) map_type = type({}) seq_type = type([]) tuple_type = type(()) def is_string(obj): t = type(obj) return t is string_type or t is unicode_type def is_int(obj): return type(o...
class Field(object): sql_type = None py_type = None def __init__(self, name=None, value=None, pk=None, unique=None, not_null=None): self.name = name self.pk = pk self.unique = unique self.not_null = not_null self.value = value def set_name(self, name): ...
class Field(object): sql_type = None py_type = None def __init__(self, name=None, value=None, pk=None, unique=None, not_null=None): self.name = name self.pk = pk self.unique = unique self.not_null = not_null self.value = value def set_name(self, name): s...
# cypher.py - encrypt and decrypt messages def cypher(message, key): result = "" for ch in message: ch = chr(ord(ch) ^ key) result += ch return result def run(): plaintext = input("message? ") key = input("hex number for key? ") key = int(key, 16) cyphertext = cypher(plain...
def cypher(message, key): result = '' for ch in message: ch = chr(ord(ch) ^ key) result += ch return result def run(): plaintext = input('message? ') key = input('hex number for key? ') key = int(key, 16) cyphertext = cypher(plaintext, key) print(cyphertext)
__all__ = [ 'q1_itertools_product', 'q2_itertools_permutations', 'q3_itertools_combinations', 'q4_itertools_combinations_with_replacement', 'q5_compress_the_string', 'q6_iterables_and_iterators', 'q7_maximize_it' ]
__all__ = ['q1_itertools_product', 'q2_itertools_permutations', 'q3_itertools_combinations', 'q4_itertools_combinations_with_replacement', 'q5_compress_the_string', 'q6_iterables_and_iterators', 'q7_maximize_it']
# This file is part of LibCSS. # Licensed under the MIT License, # http://www.opensource.org/licenses/mit-license.php # Copyright 2017 Lucas Neves <lcneves@gmail.com> # Configuration of CSS values. # The tuples in this set will be unpacked as arguments to the CSSValue # class. # Args: see docstring for class CSSValue ...
values = {('length', 'css_fixed', 4, '0', 'unit', 'css_unit', 5, 'CSS_UNIT_PX'), ('integer', 'int32_t', 4, '0'), ('fixed', 'css_fixed', 4, '0'), ('color', 'css_color', 4, '0'), ('string', 'lwc_string*'), ('string_arr', 'lwc_string**'), ('counter_arr', 'css_computed_counter*'), ('content_item', 'css_computed_content_ite...
class CSharpReference(): def __init__(self,): self.reference_object = None self.line_in_file = -1 self.file_name = ''
class Csharpreference: def __init__(self): self.reference_object = None self.line_in_file = -1 self.file_name = ''
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (20, 0, 4, "custom") __version__ = ".".join([str(v) for v in version_info]) SERVER = "gunicorn" SERVER_SOFTWARE = "%s/%s" % (SERVER, __version__)
version_info = (20, 0, 4, 'custom') __version__ = '.'.join([str(v) for v in version_info]) server = 'gunicorn' server_software = '%s/%s' % (SERVER, __version__)
''' 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and ...
""" 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and ...
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], ...
norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict(type='EncoderDecoder', pretrained=None, backbone=dict(type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], patch_sizes=[7, 3, 3, 3], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_...
# how to create a function def greet(): print("Hello") print("welcome, Edgar") greet() # prints greet() # prints(2) greet() # prints(3) # arguments and parameters def greet(name): # name is a parameter print('hello') print('welcome, ', name) greet('Edgar') # Edgar is the argument # return def greet(n...
def greet(): print('Hello') print('welcome, Edgar') greet() greet() greet() def greet(name): print('hello') print('welcome, ', name) greet('Edgar') def greet(name): if name == 'Edgar': return else: print('hello') print('welcome, ', name) greet('Edgar') def greet(name):...
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
exe = "tester.exe" toolchain = "msvc" # optional link_pool_depth = 1 # optional builddir = { "gnu" : "build" , "msvc" : "build" , "clang" : "build" } includes = { "gnu" : [ "-I." ] , "msvc" : [ "/I." ] , "clang" : [ "-I." ] } defines = { "gnu" : [ "-DEXAMPLE=1" ] , "msvc" : [ "/DEX...
exe = 'tester.exe' toolchain = 'msvc' link_pool_depth = 1 builddir = {'gnu': 'build', 'msvc': 'build', 'clang': 'build'} includes = {'gnu': ['-I.'], 'msvc': ['/I.'], 'clang': ['-I.']} defines = {'gnu': ['-DEXAMPLE=1'], 'msvc': ['/DEXAMPLE=1'], 'clang': ['-DEXAMPLE=1']} cflags = {'gnu': ['-O2', '-g'], 'msvc': ['/O2'], '...
# Problem: https://www.hackerrank.com/challenges/alphabet-rangoli/problem def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) string, width , side_l, side_str = alorder[:size], (size-1)*4+1, [], '' # top half for i in range(size-1): ...
def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) (string, width, side_l, side_str) = (alorder[:size], (size - 1) * 4 + 1, [], '') for i in range(size - 1): print((side_str + '-' + string[size - 1 - i] + '-' + side_str[::-1]).center(w...
# Cooling Settings cool_circuit = \ {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2],...
cool_circuit = {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [4, 0], [...
class Solution: # @param {integer} n # @param {integer} k # @return {string} def getPermutation(self, n, k): nums = [i+1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1,n): facts[i] = i*facts[i-1] k = k-1 res = ...
class Solution: def get_permutation(self, n, k): nums = [i + 1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1, n): facts[i] = i * facts[i - 1] k = k - 1 res = [] for i in range(n, 0, -1): idx = k / fac...
# Python 3 compatibility (no longer includes `basestring`): try: basestring except NameError: basestring = str class Item(object): '''Common logic shared across all kinds of objects.''' class UnknownAttributeError(ValueError): def __init__(self, attributes): super(Item.UnknownAttr...
try: basestring except NameError: basestring = str class Item(object): """Common logic shared across all kinds of objects.""" class Unknownattributeerror(ValueError): def __init__(self, attributes): super(Item.UnknownAttributeError, self).__init__('Unknown attributes: {0}'.format(...
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, "") for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, '') for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0,1,2,3,4,5] def add1(t): return t+1 print(list(map(lambda x: x+1,c))) print(ft_map(lambda x: x+1,c))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0, 1, 2, 3, 4, 5] def add1(t): return t + 1 print(list(map(lambda x: x + 1, c))) print(ft_map(lambda x: x + 1, c))
#!/bin/python2.7 #CLASS PARA VERIFICAR OS GRUPOS DE CONFLITO class ScdGrupoConflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False ...
class Scdgrupoconflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False self.solucao = str('') class...
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
entrada = int(input()) #resultado = entrada % 2 #comp = 10 % 2 i = 1 while i <= entrada: if i % 2 != 0: print(i) i+= 1
entrada = int(input()) i = 1 while i <= entrada: if i % 2 != 0: print(i) i += 1
class ModaError(Exception): pass class ModaTimeoutError(ModaError): pass class ModaCannotInteractError(ModaError): pass
class Modaerror(Exception): pass class Modatimeouterror(ModaError): pass class Modacannotinteracterror(ModaError): pass
def recurse(a,i): if i == len(a)-1: print(a[i]) return else: recurse(a,i+1) print(a[i]) recurse([1,2,3,4,5],0)
def recurse(a, i): if i == len(a) - 1: print(a[i]) return else: recurse(a, i + 1) print(a[i]) recurse([1, 2, 3, 4, 5], 0)
# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem # Trial division def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': n, nums = int(input()), [] ...
def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': (n, nums) = (int(input()), []) for i in range(n): nums.append(int(input())) for num in nums: print('Pr...
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bu...
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bu...
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: ...
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: ...
k=1 suma=(k**2+1)/k cont=0 while cont<1000: cont+=suma print(k) k+=1 suma=(k**2+1)/k
k = 1 suma = (k ** 2 + 1) / k cont = 0 while cont < 1000: cont += suma print(k) k += 1 suma = (k ** 2 + 1) / k
# Copyright 2017-2021 object_database Authors # # 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 ...
class Sortwrapper: def __init__(self, x): self.x = x def __lt__(self, other): try: if type(self.x) in (int, float) and type(other.x) in (int, float): return self.x < other.x if type(self.x) is type(other.x): return self.x < other.x ...
# encoding=utf8 # coding=UTF-8 #pastaArquivoCsv = "/home/00937325465/familiai/acompanhaig/arquivos/csv/" #pastaArquivoCsvProc = "/home/00937325465/familiai/acompanhaig/arquivos/csv/processados/" #pastaArquivoZip = "/home/00937325465/familiai/acompanhaig/arquivos/zip/" #pastaArquivoZipProc = "/home/00937325465/famili...
pasta_arquivo_csv = '/home/ubuntu/workspace/public/python/input/csv/' pasta_arquivo_csv_proc = '/home/ubuntu/workspace/public/python/input/csv/processados/' pasta_arquivo_zip = '/home/ubuntu/workspace/public/python/input/zip/' pasta_arquivo_zip_proc = '/home/ubuntu/workspace/public/python/input/zip/processados/' pasta_...
def slices(number, n): initial, res = 0, [] if n > len(number) or n == 0: raise ValueError("Desired slices greater than number length") elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(number)...
def slices(number, n): (initial, res) = (0, []) if n > len(number) or n == 0: raise value_error('Desired slices greater than number length') elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(nu...
# # PySNMP MIB module HUAWEI-LswSMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-LswSMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:34:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ...
INPUTS = [ ['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03'], ] OUTPUTS = [ ['Select', False], ['Signal Only', ''], ['C...
inputs = [['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03']] outputs = [['Select', False], ['Signal Only', ''], ['Coolant Flood', ...
n=int(input()) d=2 i = 0 while n>d : if n%d==0 : i+=1 print ("divisible by",d, "and count",i) else: print ("not divisible by this number",d) d+=1
n = int(input()) d = 2 i = 0 while n > d: if n % d == 0: i += 1 print('divisible by', d, 'and count', i) else: print('not divisible by this number', d) d += 1
# -*- encoding: utf-8 -*- EPILOG = 'Docker Hub in your terminal' DESCRIPTION = 'Access docker hub from your terminal' HELPMSGS = { 'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly re...
epilog = 'Docker Hub in your terminal' description = 'Access docker hub from your terminal' helpmsgs = {'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly results in %(choices)s formats', '...
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if (adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]): v = ord(S[i]) - ord('A') elif (adj[v][ord(S[i]) - ord('A') + 5] or ...
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]: v = ord(S[i]) - ord('A') elif adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('...
# Create a program that reads a positive integer N as input and prints on the console a rhombus with size n: def generate_pyramid(size: int, inverted: bool = False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] d...
def generate_pyramid(size: int, inverted: bool=False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] def generate_rhombus(size: int) -> list: retval = generate_pyramid(size) retval.extend(generate_pyramid(siz...
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ # Write a program that has a user guess your name, but they only get 3 # chances to do so until the program quits. print("Try to guess my name!") count = 1 name = "guileherme" guess = input("What is my name? ") while count < 3 and guess.lower() != name: # . lower allows th...
print('Try to guess my name!') count = 1 name = 'guileherme' guess = input('What is my name? ') while count < 3 and guess.lower() != name: print('You are wrong!') guess = input('What is my name? ') count = count + 1 if guess.lower() != name: print('You are wrong!') print('You ran out of chances.') e...
def minimumDistances(a): min_distance = -1 length = len(a) for number in range(0, length-1): for another_number in range(number+1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: min...
def minimum_distances(a): min_distance = -1 length = len(a) for number in range(0, length - 1): for another_number in range(number + 1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: ...
# -*- coding: utf-8 -*- # # ax_spines.py # # Copyright 2017 Sebastian Spreizer # The MIT License def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(a...
def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_...
''' https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s ''' b = input() count = 0 buf = "0" zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == "0": zeros.append(count) else: ones.append(count) ...
""" https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s """ b = input() count = 0 buf = '0' zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == '0': zeros.append(count) else: ones.append(count) co...
#This program calculates how many tiles you #need when tiling a floor (in m2) length = float(input("Enter room length:")) width = float(input("Enter room width:")) area = length * width needed = area * 1.05 print("You need", needed, "tiles in squared metres")
length = float(input('Enter room length:')) width = float(input('Enter room width:')) area = length * width needed = area * 1.05 print('You need', needed, 'tiles in squared metres')
# # PySNMP MIB module ZYXEL-CLUSTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CLUSTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ...
# import math # def squareRoot(a): # return round(math.sqrt(float(a)),9) def squareRoot(a): return round(float(a)**(1/2),8)
def square_root(a): return round(float(a) ** (1 / 2), 8)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None ...
class Solution: def remove_elements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None dummy_head = current_node = list_node() dummyHead.next = head while currentNode.next: if currentNode.next.val == val: ...
# 2021 April 16. Surrendered entirely. # 2-d dp. # text1 = "abcba", text2 = "abcbcba" # At any two positions i, j in t1 and t2, if 1) t1[i] == t2[j] # then the length of common subsequence count should increment by 1 and # we then check from t1[i+1] and t2[j+1]. If 2) t1[i] != t2[j], then we # should keep on finding...
class Solution: def longest_common_subsequence(self, text1: str, text2: str) -> int: (rows, cols) = (len(text1) + 1, len(text2) + 1) dp = [[0 for _ in range(COLS)] for _ in range(ROWS)] for row in range(ROWS - 2, -1, -1): for col in range(COLS - 2, -1, -1): if te...
class BaseSensor(): def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(s...
class Basesensor: def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(se...
def time_in_range(data, bg_range=(4.0, 7.0)): # data[0] is the time values - assume they are equally spaced, so we can ignore values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values...
def time_in_range(data, bg_range=(4.0, 7.0)): values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values) def estimated_hba1c(data): return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.5...
def maior_primo(x) -> object: for maior in reversed(range(1,x+1)): if all(maior%n!=0 for n in range(2,maior)): return maior
def maior_primo(x) -> object: for maior in reversed(range(1, x + 1)): if all((maior % n != 0 for n in range(2, maior))): return maior
USER_CREATED = "user_created" USER_ADDED = "user_added_to_request" USER_REMOVED = "user_removed_from_request" USER_PERM_CHANGED = "user_permissions_changed" USER_STATUS_CHANGED = "user_status_changed" # user, admin, super USER_INFO_EDITED = "user_information_edited" REQUESTER_INFO_EDITED = "requester_information_edite...
user_created = 'user_created' user_added = 'user_added_to_request' user_removed = 'user_removed_from_request' user_perm_changed = 'user_permissions_changed' user_status_changed = 'user_status_changed' user_info_edited = 'user_information_edited' requester_info_edited = 'requester_information_edited' req_created = 'requ...
# Find the sum of the numbers 8, 9, 10 # Var declarations num1 = 8 num2 = 9 num3 = 10 # Code sum = num1 + num2 + num3 # Result print(sum)
num1 = 8 num2 = 9 num3 = 10 sum = num1 + num2 + num3 print(sum)
# Write your make_spoonerism function here: def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a,b) + word1[1:] d = word2[0].replace(b,a) + word2[1:] e = c + ' ' + d return e # Uncomment these function calls to test your function: print(make_spoonerism("Codecademy", "Learn"...
def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a, b) + word1[1:] d = word2[0].replace(b, a) + word2[1:] e = c + ' ' + d return e print(make_spoonerism('Codecademy', 'Learn')) print(make_spoonerism('Hello', 'world!')) print(make_spoonerism('a', 'b'))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"trace_log": "01_convert_time_log.ipynb", "format_value": "01_convert_time_log.ipynb", "strip_extra_EnmacClientTime_elements": "01_convert_time_log.ipynb", "unix_time_milliseconds":...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'trace_log': '01_convert_time_log.ipynb', 'format_value': '01_convert_time_log.ipynb', 'strip_extra_EnmacClientTime_elements': '01_convert_time_log.ipynb', 'unix_time_milliseconds': '01_convert_time_log.ipynb', 'parse_dt': '01_convert_time_log.ipynb...
#Planetary database #Source for planetary data, and some of the data on #the moons, is http://nssdc.gsfc.nasa.gov/planetary/factsheet/ class Planet: ''' A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius ...
class Planet: """ A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius of planet (m) P.g = Surface gravitational acceleration (m/s**2) P.L = Annual mean solar constant (current) (W/m**2...
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
def getKey(dictionary, svalue): for key, value in dictionary.items(): if value == svalue: return key # def hasKey(dictionary, key): # if key in dictionary: # return True # return False
def get_key(dictionary, svalue): for (key, value) in dictionary.items(): if value == svalue: return key
# https://www.codewars.com/kata/529872bdd0f550a06b00026e/ ''' Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has...
""" Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has more than five digits. Adapted from Project Euler. """ ...
@auth.route('/login', methods=['GET', 'POST']) # define login page path def login(): # define login page fucntion if request.method=='GET': # if the request is a GET we return the login page return render_template('login.html') else: # if the request is POST the we check if the user exist ...
@auth.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False user = U...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_norm_stats": "00_utils.ipynb", "draw_rect": "00_utils.ipynb", "convert_cords": "00_utils.ipynb", "resize": "00_utils.ipynb", "noise": "00_utils.ipynb", "get_p...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'get_norm_stats': '00_utils.ipynb', 'draw_rect': '00_utils.ipynb', 'convert_cords': '00_utils.ipynb', 'resize': '00_utils.ipynb', 'noise': '00_utils.ipynb', 'get_prompt_points': '00_utils.ipynb', 'yolo_to_coco': '00_utils.ipynb', 'PTBDataset': '01_d...
class OutcomeInfo: '''Details for individual outcomes of a Market.''' def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): '''Market Outcome ID Returns int ''' return...
class Outcomeinfo: """Details for individual outcomes of a Market.""" def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): """Market Outcome ID Re...
''' @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 ''' LETTERS = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else...
""" @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 """ letters = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '') ...
def cpu_bound(n): return sum(i * i for i in range(n)) if __name__ == "__main__": n = int(input()) res = cpu_bound(n) print(res)
def cpu_bound(n): return sum((i * i for i in range(n))) if __name__ == '__main__': n = int(input()) res = cpu_bound(n) print(res)
# Implement a queue using two stacks. Recall that a queue is a FIFO # (first-in, first-out) data structure with the following methods: enqueue, # which inserts an element into the queue, and dequeue, which removes it. class Queue: def __init__(self): self.ins = [] self.out = [] de...
class Queue: def __init__(self): self.ins = [] self.out = [] def enqueue(self, value): self.ins.append(value) def dequeue(self): if not self.out: while self.ins: self.out.append(self.ins.pop()) return self.out.pop() if __name__ == '__mai...
MOCK_DATA = [ { "symbol": "sy1", "companyName": "cn1", "exchange": "ex1", "industry": "in1", "website": "ws1", "description": "dc1", "CEO": "ceo1", "issueType": "is1", "sector": "sc1", }, { "symbol": "sy2", "companyName"...
mock_data = [{'symbol': 'sy1', 'companyName': 'cn1', 'exchange': 'ex1', 'industry': 'in1', 'website': 'ws1', 'description': 'dc1', 'CEO': 'ceo1', 'issueType': 'is1', 'sector': 'sc1'}, {'symbol': 'sy2', 'companyName': 'cn2', 'exchange': 'ex2', 'industry': 'in2', 'website': 'ws2', 'description': 'dc2', 'CEO': 'ceo2', 'is...
# Only used for PyTorch open source BUCK build # @lint-ignore-every BUCKRESTRICTEDSYNTAX def is_arvr_mode(): if read_config("pt", "is_oss", "0") == "0": fail("This file is for open source pytorch build. Do not use it in fbsource!") return False
def is_arvr_mode(): if read_config('pt', 'is_oss', '0') == '0': fail('This file is for open source pytorch build. Do not use it in fbsource!') return False
# Diffusion 2D nx = 20 # number of elements ny = nx # number of nodes mx = nx + 1 my = ny + 1 # initial values iv = {} for j in range(int(0.2*my), int(0.3*my)): for i in range(int(0.5*mx), int(0.8*mx)): index = j*mx + i iv[index] = 1.0 print("iv: ",iv) config = { "solverStructureDiagramFile": "so...
nx = 20 ny = nx mx = nx + 1 my = ny + 1 iv = {} for j in range(int(0.2 * my), int(0.3 * my)): for i in range(int(0.5 * mx), int(0.8 * mx)): index = j * mx + i iv[index] = 1.0 print('iv: ', iv) config = {'solverStructureDiagramFile': 'solver_structure.txt', 'logFormat': 'csv', 'scenarioName': 'diffus...
__title__ = 'lightwood' __package_name__ = 'mindsdb' __version__ = '0.14.1' __description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects." __email__ = "jorge@mindsdb.com" __author__ = 'MindsDB Inc' __github__ = 'https://github.com/mindsdb/...
__title__ = 'lightwood' __package_name__ = 'mindsdb' __version__ = '0.14.1' __description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects." __email__ = 'jorge@mindsdb.com' __author__ = 'MindsDB Inc' __github__ = 'https://github.com/mindsdb/...
# Problem: input: an unsorted array A[lo..hi]; | output: the (left) median of the given array # Source: SCU COEN279 DAA HW3 Q3 # Author: Shreyas Padhye # Algorithm: Decrease-Conquer class solution(): def left_median(self, A): if len(A) == 1 or len(A) == 2: return A[0] else: ...
class Solution: def left_median(self, A): if len(A) == 1 or len(A) == 2: return A[0] else: median = self.left_median(A[:-1]) if len(A[:-1]) % 2 == 0: if median > A[-1]: return median else: me...
def get_belief(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = []...
def get_belief(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = [] ...
''' Created on 2016-01-13 @author: Wu Wenxiang (wuwenxiang.sh@gmail.com) ''' DEBUG = False
""" Created on 2016-01-13 @author: Wu Wenxiang (wuwenxiang.sh@gmail.com) """ debug = False
description = 'Helmholtz field coil' group = 'optional' includes = ['alias_B'] tango_base = 'tango://phys.kws1.frm2:10000/kws1/' devices = dict( I_helmholtz = device('nicos.devices.entangle.PowerSupply', description = 'Current in coils', tangodevice = tango_base + 'gesupply/ps2', unit = ...
description = 'Helmholtz field coil' group = 'optional' includes = ['alias_B'] tango_base = 'tango://phys.kws1.frm2:10000/kws1/' devices = dict(I_helmholtz=device('nicos.devices.entangle.PowerSupply', description='Current in coils', tangodevice=tango_base + 'gesupply/ps2', unit='A', fmtstr='%.2f'), B_helmholtz=device('...
# Test checked class SymbolTable(object): def __init__(self): self._symbols = \ { \ 'SP':0, 'LCL':1, 'ARG':2, 'THIS':3, 'THAT':4, \ 'R0':0, 'R1':1, 'R2':2, 'R3':3, 'R4':4, 'R5':5, 'R6':6, 'R7':7, \ 'R8':8, 'R9':9, 'R10':10, 'R11':11, 'R12':12, 'R13':13, 'R14'...
class Symboltable(object): def __init__(self): self._symbols = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15, 'SCREEN': 16384, 'KBD': 24576} ...
# File: question3.py # Author: David Lechner # Date: 11/19/2019 '''Ask some questions about goats''' # REVIEW: We write `NUM_GOATS` in all caps because it is a constant. We set it # once at the begining of the program and don't change after that. NUM_GOATS = 10 # This is how many goats I have # REVIEW: The input()...
"""Ask some questions about goats""" num_goats = 10 answer = int(input('How many goats do you see?')) if answer < NUM_GOATS: print('Some of your goats are missing!') if answer == NUM_GOATS: print('All of the goats are there.') if answer > NUM_GOATS: print('You have extra goats!')
# lec6.4-removeDups.py # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Lecture 6, video 4 # Demonstrates performing operations on lists # Demonstrates how changing a list while iterating over it creates # unintended problems def removeDups(L1, L2): for e1 in L1: if e1 ...
def remove_dups(L1, L2): for e1 in L1: if e1 in L2: L1.remove(e1) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remove_dups(L1, L2) print(L1) def remove_dups_better(L1, L2): l1_start = L1[:] for e1 in L1Start: if e1 in L2: L1.remove(e1) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remo...
def compareTriplets(a, b): result = [] aliceScore =0 bobScore = 0 for Alice, Bob in zip(a, b): if Alice > Bob: aliceScore +=1 continue if Bob > Alice: bobScore +=1 continue if Alice == Bob: continue result....
def compare_triplets(a, b): result = [] alice_score = 0 bob_score = 0 for (alice, bob) in zip(a, b): if Alice > Bob: alice_score += 1 continue if Bob > Alice: bob_score += 1 continue if Alice == Bob: continue result....
#file extension '''n = input("enter file name with extension:") f_ext = n.split('.') x = f_ext[-1] print(x) #sum n = input("enter one number:") temp = n temp1 = temp+temp temp2 = temp+temp+temp val = int(n)+int(temp1)+int(temp2) print(val) #Multiline comment print("a string that you \"don\'t\" have to escape \n This...
"""n = input("enter file name with extension:") f_ext = n.split('.') x = f_ext[-1] print(x) #sum n = input("enter one number:") temp = n temp1 = temp+temp temp2 = temp+temp+temp val = int(n)+int(temp1)+int(temp2) print(val) #Multiline comment print("a string that you "don't" have to escape This is a ....... mult...