content
stringlengths
7
1.05M
while True: print("1. Addition") print("2. Substraction") print("3. Multiplication") print("4. Division") print("5. Exit") choice = input("Your choice: ") print() if choice == "1": first_addend = float(input("First addend: ")) second_addend = float(input("Second adde...
class A: def foo(self): print('in A foo') def hello(self): print('A hello') class B: def bar(self): print('in B bar') def hello(self): print('B hello') class C(B, A): pass # def hello(self): # print('C hello') if __name__ == '__main__': c = C() ...
nota1 = float(input("Digite a 1º nota: ")) nota2 = float(input("Digite a 2º nota: ")) nota3 = float(input("Digite a 3º nota: ")) nota4 = float(input("Digite a 4º nota: ")) media =(nota1+nota2+nota3+nota4)/4 print("A média aritmética é ", media)
print(1 == 2 and 1 == 1) # False print(1 == 1 and 2 == 2) # True print(5 > 2 and True) # True print(False and True) print(False and False) print(True and True)
class Param: """ Param class """ def __init__(self, id=None, name="", type=""): self.id = id self.name = name self.type = type @staticmethod def get_by_name(paramList, paramName): for param in paramList: if param.name == paramName: return param return None
for _ in range(int(input())): n=int(input()) s=list(input()) ans="" for i in s: if i == "U": ans+="D" elif i=="D": ans+="U" else: ans+=i print(ans)
test_board_1 = [ [None, 6, None, None, 4, None, 7, None, None,], [None, 2, None, 1, None, None, None, None, None], [8, None, 5, 2, None, 6, None, 9, 4], [None, None, 1, None, 9, 3, None, None, 7], [4, 3, None, 5, None, 8, None, 2, 9], [5, None, None, 4, 7, Non...
''' Consider a highway of M miles. The task is to place billboards on the highway such that revenue is maximized. The possible sites for billboards are given by number x1 < x2 < ….. < xn-1 < xn, specifying positions in miles measured from one end of the road. If we place a billboard at position xi, we receive a revenue...
a = 0 while(1): a = a+1 if(a%15 == 0): print("FIZZ BUZZ") elif(a%5 == 0): print("BUZZ") elif(a%3 == 0): print("FIZZ") else: print(a)
class Config: BOT_USE = False BOT_TOKEN = '5022399250:AAH4xUY7OgDGHyUlp5_J9DZMhNU8NXgeyh8' # from @botfather APP_ID = 18454593 # from https://my.telegram.org/apps API_HASH = 'b536EkRHLyviZMtSjodB4gByQJwyYxPmBE1x' # from https:...
class Node(object): def __init__(self, value=None, pointer=None): self.value = value self.pointer = pointer class Stack(object): def __init__(self): self.head = None def isEmpty(self): return not bool(self.head) def push(self, item): self.head = Node(item, self.h...
class Solution: def ladderLength(self, beginWord, endWord, wordList): wordList.append(beginWord) m, n = len(wordList[0]), len(wordList) words_inverse = {w:i for i, w in enumerate(wordList)} words_graph = defaultdict(set) alphabet = "abcdefghijklmnopqrstuvwxyz" ...
# Question # 30. Write a program to read a list of ‘n’ integers from the user. Create two new lists, one having all positive numbers and the other having all negative numbers. Print all three lists # Code x = [] n = 5 for e in range(n): a = input(f"int {e}:\n") while not a.replace('+','').replace('-','').isdi...
""" @file @brief This module contains various string useful when a html page has to be produced. It contains the following variables: @var html_header a HTML header to use this way: html_header % (title, author, keywords) @var html_footr a HTML footer """ html_header = ...
DATA = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "name": "Afghanistan" }, "geometry": { "type": "Polygon", "coordinates": [ [ [61.210817, 35.650072], ...
m, n = map(int, input().split()) d = [1]+[0]*99 for i in range(n): d[i+1]+=d[i] d[i+m]=d[i] print (d[n])
INVALID_AMOUNT = -2 INVALID_ACTION = -4 TRANSACTION_NOT_FOUND = -6 ORDER_NOT_FOUND = -5 PREPARE = '0' COMPLETE = '1' A_LACK_OF_MONEY = '-5017' A_LACK_OF_MONEY_CODE = -9 AUTHORIZATION_FAIL = 'AUTHORIZATION_FAIL' AUTHORIZATION_FAIL_CODE = -1 ORDER_FOUND = True
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance # {"feature": "Education", "instances": 127, "metric_value": 0.9989, "depth...
def to_list(arr): """Transform an numpy array into a list with homogeneous element type.""" return arr.astype(type(arr.ravel()[0])).tolist() def to_builtin(arr): """Transform an numpy array into a numpy array with homogeneous element type.""" return arr.astype(type(arr.ravel()[0]))
""" Replace the placeholders below with valid credentials from an active AerisWeather API account. Don't have an active AerisWeather API client account? Accessing the API data requires an active AerisWeather API subscription, and registration of your application or namespace. You can sign up for a free developer acco...
# -*- coding: utf-8 -*- # El code_menu debe ser único y se configurará como un permiso del sistema MENU_DEFAULT = [ {'code_menu': 'acceso_inspeccion_educativa', 'texto_menu': 'Inspección Educativa', 'href': '', 'nivel': 1, 'tipo': 'Accesible', 'pos': 1 }, {'code_menu': 'acceso_tar...
#!/usr/bin/python # -*- coding: utf-8 -*- # Function to rotate each letter with the specified key def BasicRotate(letter, key): # Checks if letter is lowercase if letter.islower(): # As long as letter is lowercase, key is added new = ord(letter) + key ...
class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = f"{first}.{last}@compani.com" def fullname(self): return f"{self.first} {self.last}" emp1 = Employee("john", "smit", 5000) emp2 = Employee("Morramed...
def wrap_data_as_list(data): # Check the type of data if isinstance(data, list): # Return the original list return data elif isinstance(data, tuple): # Convert the tuple to the list and return return list(data) elif isinstance(data, dict): # Wrap the data with lis...
def validate_square(n): if n < 1: raise ValueError('square must be 1 or greater') elif n > 64: raise ValueError('square must be 64 or less') def on_square(n): validate_square(n) return pow(2, n - 1) def total_after(n): validate_square(n) return sum([on_square(i)...
class SCREENSHOT: SC_DATA = b"" def __init__(self): self.generate() def generate(self): obj = io.BytesIO() im = pyscreenshot.grab() im.save(obj, format="PNG") self.SC_DATA = obj.getvalue() def get_data(self): return self.SC_DATA
lista_número = list () while True: valor = int (input ('Digite o núemero: ')) if valor not in lista_número: print ('Adicionado com sucesso!') lista_número.append(valor) else: print ('Valor não adicionado na lista!') while True: stop = str(input('Ainda quer continuar [S ...
""" 040 Ask for a number below 50 and then count down from 50 to that number, making sure you show the number they entered in the output. """ number = int(input("Enter a number please : ")) for i in range(number , 0,-1): print(i)
# by Kami Bigdely # PEP8 - whitespaces and variable names. # This is a guess game. Guess what number the computer has chosen! class Pizza: def __init__ (obj, mybread_type, CHEESE_TYPE, meat_type, pizza_toppings, size): obj.bread_type= mybread_type obj.cheese_type = CHEESE_TYPE obj.meat_type=...
class SDADriver: def InitAI(self): return def UpdateAI(self,SDAData): return (0.4, 0.2, 0.5, 1)
# sorting using custom key employees = [ {'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, {'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, ] # custom functions to get employee info def get_na...
string = "Test String" key = "4381" k_o = key[0] + key[1] k_e = key[2] + key[3] final_op = "" for i in range(0 , len(string)): if(i % 2 == 0): op = ord(string[i]) print(op) xor = hex((int(op)) ^ (int(k_o)) ) final_op.join(str(op)) else: op = ord(string[i]) ...
# -*- coding: utf-8 -*- ''' @author: Gabriele Girelli @contact: gigi.ga90@gmail.com @description: methods for basic nucleic acid sequence management. ''' # CONSTANTS ==================================================================== AB_DNA = ["ACGTRYKMSWBDHVN", "TGCAYRMKSWVHDBN"] AB_RNA = ["ACGURYKMSWBDHVN", "UGCA...
class Cell: # default constructor def __init__(self, value): self._clicked = False self._value = value def get_value(self): return self._value def get_clicked(self): return self._clicked def set_clicked(self, clicked): self._clicked = clicked
"""A tiny English to Spanish dictionary is created, using the Python dictionary type dict. Then the dictionary is used. """ def createDictionary(): '''Returns a tiny Spanish dictionary''' spanish = dict() spanish['hello'] = 'hola' spanish['yes'] = 'si' spanish['one'] = 'uno' spanish['two'] = 'd...
n = int(input('Digite a idade do possível eleitor:')) if n < 16: print('Abaixo de 16 anos') elif n >= 18 and n <= 65: print('Eleitor obrigatório') elif n>=16 and n < 18 or n > 65: print('Eleitor facultativo')
# Finding the smallest number smallest = None print('Before') for value in [9, 24, 12, 57, 6, 32, 2] : if smallest is None : smallest = value elif value < smallest : smallest = value print(smallest, value) print('After', smallest)
aliens=[] #make 30 green aliens for y in range(30): new_alien={'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) #show the first 5 aliens for yy in aliens[:5]: print(yy) print('...') for zzz in aliens[3:9]: for y in aliens[6:9]: if y['color']=='green': y['color']='yellow' y['s...
#Result class constants with ANSI colors ALERT = '\033[91mAlert!\033[0m' WARNING = '\033[93mWarning\033[0m' NOTHING = '\033[92mCheck passed\033[0m' BIG_FILE = 'Big file found' NOT_PLAIN_TEXT = 'File is not plain text' MATCH = 'Match' NOT_MATCH = 'Nothing found' FILETYPE_NOT_ALLOWED = 'Extension not allowed'
while 1: number = input("Type a negabinary number here: ") try: number = int(number) break except ValueError: pass total = 0 loop = 0 for char in str(number)[::-1]: if char == "1": total += (-2) ** loop elif char == "0": pass else: print("You enterned an invalid number") quit() loop += 1 print(t...
dadosJogador = dict() dadosJogador['Nome'] = str(input('Nome do jogador: ')) dadosJogador['Partidas'] = int(input(f'Total de partidas de {dadosJogador["Nome"]}: ')) gols = [] #totGols = 0 for c in range(1, dadosJogador['Partidas'] + 1): gols.append(int(input(f'Quantos gols {dadosJogador["Nome"]} fez na {c}ª partida...
class Solution: def getRow(self, rowIndex: int) -> List[int]: triangle=[] for i in range(rowIndex+1): row=[None for _ in range(i+1)] row[0],row[-1]=1,1 for j in range(1,len(row)-1): row[j]=triangle[i-1][j]+triangle[i-1][j-1] ...
# Change our pairplot to # * plot more samples # * reduce the number of variables to the first three (leave out the group) # * make the plot a bit larger # Optional # * fit linear regression models to the scatter plots # * give each group a different type of marker, use https://matplotlib.org/api/markers_api.html as a...
n = int(input()) a = list(map(int, input().split())) a_sum = [0] for elem in a: a_sum.append(a_sum[-1] + elem) del a_sum[0] # dp_k = (a_k までの移動において一番右端にいるときの相対座標) dp = [0] * (n + 1) pos = 0 farthest = 0 for i in range(1, n + 1): dp[i] = max(dp[i - 1], a_sum[i - 1]) farthest = max(farthest, dp[i] + pos) ...
def helpy(): print('Olá.') print() print('Aqui segue as informações detalhadas sobre cada comando da ferramenta.') print('OBS: No primeiro uso da ferramenta é necessario executar o comando 0 e 1. Uma vez importado os arquivos não sera necessário executar novamente o comando 1, lembre-se de sempre deixar...
class CreateBeam(): def __init__(self,concrete,x,y,z): self.concrete = concrete.concrete_type self.concrete_price = concrete.concrete_price self.x = int(x) self.y = int(y) self.y = int(y) self.volume = x * y * z self.price = self.volume * self.concre...
""" sentry_kavenegar ~~~~~~~~~~~~~ :copyright: (c) 2012 by Amir Asaran. :license: BSD, see LICENSE for more details. """ try: VERSION = __import__('pkg_resources') \ .get_distribution('sentry-kavenegar').version except Exception as e: VERSION = 'unknown'
class MyshowsAPIError(Exception): """Root exception for all errors related to this library""" class APIError(MyshowsAPIError): """An error occurred while performing a request to API""" class ResponseParseError(MyshowsAPIError): """An error occurred while parse a response from API""" class AuthError(My...
N = int(input()) if N%2 == 0: print(1 / 2) else: print((N//2+1) / N)
N_ELEMNT = 10000 CBOW_N_WORDS = 3 SKIPGRAM_N_WORDS = 3 # context = 3 words before, 3 words after the target word MIN_WORD_FREQUENCY = 30 MAX_SEQ_LENGTH = 256 # define it to 0 for no truncature EMBEDDING_DIM = 256 VOCAB_SIZE = 4096 BATCH_SIZE = 64 LANGUAGE = 'french' BUFFER_SIZE = 8192
# Setting to True clearly shows the neat Fibonacci pattern of: # Odd, Odd, Even, O, O, E, O, O, E.... DEBUG = False total = 0 curr = 1 prev = 1 while curr < 4000000: if curr % 2 == 0: if DEBUG: print('adding {}'.format(curr)) total += curr else: if DEBUG: print...
""" coding: utf-8 Created on 29/10/2020 @author: github.com/edrmonteiro From: Codility Lessons """ # MaxNonoverlappingSegments # Find a maximal set of non-overlapping segments. # Located on a line are N segments, numbered from 0 to N − 1, whose positions are given in arrays A and B. For each I (0 ≤ I < N) the posit...
class Node: def __init__(self,value=None): self.value = value self.next = None def __str__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self): node = self.head while n...
a = input().split(" ") l,b = int(a[0]), int(a[1]) y = 0 while( l<=b ) : l=l*3 b=b*2 y+=1 print(y)
""" Programa 028 Área de estudos. data 18.11.2020 (Indefinida) Hs @Autor: Abraão A. Silva """ # Cabeçalho e coleta de informações. print('[Obs: Digite "M" Matutino, "V" Vespertino ou "N" Noturno.]') turno_user = str(input('Turno.: ')).strip().lower() nome_user = str(input('Nome.: ')).strip().title() # Verificamos...
class Folder: def __init__(self, **kwargs): self.folder = { 'rescanIntervalS' : 60, 'copiers' : 0, 'pullerPauseS' : 0, 'autoNormalize' : True, 'id' : kwargs['id'] , 'scanProgressIntervalS' : 0, 'hashers' : 0, 'pullers' : 0, 'invalid' : '', 'label' : kw...
class User: ''' class to creates instances of class User. ''' user_list = [] def save_user(self): ''' save user method that appends objects to our user_list list. ''' User.user_list.append(self) def delete_user(self): ''' method to d...
x=range(1,10,2) print (x) for item in x: print(item,end=",")
op = 'sS' while op not in 'Nn': valor = int(input(f'{"=" * 40}\n' f'{"CAIXA ELETRONICO - BANCO TABAJARA" :^40}\n' f'{"=" * 40}\n' f'Qual valor você deseja sacar: R$')) if valor >= 50: print(f'{valor // 50} nota(s) de R$50,00') ...
""" Module containing exceptions raised in various scenarios during execution of both client and server programs. """ class VariableNotSettableError(Exception): """ Raised when the configuration variable, which is not marked as settable is being set. """ def __init__(self, *args): super(Va...
"""Response decoder: The Strategic Environmental Archaeology Database.""" def occurrences(resp_json, return_obj, options): """Taxa in time and space.""" # from ..elc import ages # Currently SEAD does not support age parameterization # The database also does not include age in the occurrence response...
def contador(i, f, p): # abaixo é a criação de uma docstring """ -> Faz uma contagem e mostra na tela; :param i: início da contagem :param f: fim da contagem :param p: passo da contagem :return: sem retorno """ c = 1 while c <= f: print(f'{c} ', end='') c += p ...
def fizzbuzz(n): """ This function prints integer 1 to N(N included), but print 'Fizz' if an integer is divisible by 3, 'Buzz' if an integer is divisible by 5 and 'FizzBuzz' if an integer is divisible by both 3 and 5 """ for no in range(1,n+1): if no % 3 == 0 and no % 5 == 0: ...
""" 练习1:请排列出2个色子可以组成的所有可能(列表) 色子(1~6) range(1,7) 色子(1~6) 练习2:请排列出3个色子可以组成的所有可能(列表) """ # result = [] # for x in range(1, 7): # for y in range(1, 7): # result.append((x , y)) result = [(x, y) for x in range(1, 7) for y in range(1, 7)] print(result) # result = [] # for x in range(1, 7): #...
# coding: utf-8 ROUTING_VIEWS = [ ("/", "app.IndexController", "foo"), ("/hoge/<id>", "hoge.HogeController", "hoge"), ("/fuga", "template.TemplateController", "fuga") ]
class Solution: def allCellsDistOrder(self, R, C, r0, c0): cells = [[x, y] for x in range(R) for y in range(C)] cells = sorted(cells, key=lambda c: abs(c[0] - r0) + abs(c[1] - c0)) return cells
# Equation checker def is_balanced(equation): parenthesis = ''.join([p for p in equation if p in '(){}[]']) return is_valid(parenthesis) def is_valid(parenthesis): stack = [] for p in parenthesis: if p in '(': stack.append(p) elif p in ')': if stack == []: ...
class crafting: def __init__(self,inv,items): self.inv = inv self.items = items def getCrafts(self): itemsChecked = [] itemAmounts = [] for i in range(len(self.inv.inventory)): if self.inv.inventory[i][0] != None: item = self.inv.inventory[i] ...
class Foo(object): pass @decorator class Bar(object): def foo(self): pass def baz(arg1, arg2): pass foo() | bar()
''' 给定一个正整数 n ,输出外观数列的第 n 项。 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。 你可以将其视作是由递归公式定义的数字字符串序列: countAndSay(1) = "1" countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。 前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 第一项是数字 1 描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11" 描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21" 描述前一项,这...
{ 'targets': [ { 'target_name': 'xwalk_test_base', 'type': 'static_library', 'dependencies': [ # FIXME(tmpsantos): we should depend on runtime # here but it is not really a module yet. '../../../base/base.gyp:base', '../../../base/base.gyp:test_support_base', ...
#Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário #escolher, só que agora utilizando um laço for n = int(input('Digite um número para saber a sua taboada: ')) for c in range(1, 11): print(f'{n} X {c} = {n*c}')
for i in range(5): print("I will not chew gum in class.") repetitions = int(input("How many times should i repeat?")) for i in range(repetitions): print("I will not chew gum in class") def print_about_gum(repetitions): for i in range(repetitions): print("I will not chew gum in class.") def main...
def get_current_channel_planning(mist_session, site_id): uri = "/api/v1/sites/%s/rrm/current" % site_id resp = mist_session.mist_get(uri, site_id=site_id) return resp def get_device_rrm_info(mist_session, site_id, device_id, band): uri = "/api/v1/sites/%s/rrm/current/devices/%s/band/%s" % (site_id, d...
class MovingAverage: def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.__size = size self.__sum = 0 self.__q = deque([]) def next(self, val): """ :type val: int :rtype: float """ ...
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: seen = [False] * len(rooms) seen[0] = True stack = [0] #At the beginning, we have a todo list "stack" of keys to use. #'seen' represents at some point we have entered this room. while stack: ...
# https://open.kattis.com/problems/greetingcard n = int(input()) points = {tuple(map(int, input().split())) for _ in range(n)} neighbor_distances = {(0, 2018), (1118, 1680), (1680, 1118), (2018, 0), (1118, -1680), ...
def make_car(manufacturer_name,model_name,**props): car = { 'manufacturer': manufacturer_name, 'model': model_name, } for prop,value in props.items(): car[prop] = value print(car) car = make_car('subaru', 'outback', color='blue', tow_package=True)
# import pretty_midi # from omnizart.music import app as music_app # from omnizart.drum import app as drum_app # from omnizart.chord import app as chord_app def process(input_audio, model_path=None, output="./"): pass
n = int(input()) p = list(map(int, input().split())) cnt = 0 for i in range(1, n-1): if (p[i-1] <= p[i] <= p[i+1]) or (p[i+1] <= p[i] <= p[i-1]): cnt += 1 print(cnt)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: if B is None: return False if A is None: return False result = Fals...
class fun1: # test testVal = 1 def __init__(self, a): print("class init") self.a = a def __call__(self, x): return x + self.a def __str__(self) -> str: return "Sina changed this function as" def id(self): return 'a=%a' % self.a @classmethod ...
#pj24 foo = '0123456789' def thingamy(foo): foo.sort()
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: return [] ans = [] self.dfs(root...
SURFACE_HARD = 1 SURFACE_CLAY = 2 ADAM_EL_MIHDAWY = 'Adam El Mihdawy' ADAM_MOUNDIR = 'Adam Moundir' ADAM_PAVLASEK = 'Adam Pavlasek' ADHAM_GABER = 'Adham Gabr' ADMIR_KALENDER = 'Admir Kalender' ANDRES_MOLTENI = 'Andres Molteni' ADRIAN_ANDREEV = 'Adrian Andreev' ADRIAN_BODMER = 'Adrian Bodmer' ADRIAN_MANNARINO = 'Adrian...
net_type = 'resnet' #type=str, workers = 4 # type=int, help='number of data loading workers (default: 4)' epochs = 2 # type=int, metavar='N', help='number of total epochs to run' batch_size = 128 #type=int, help='mini-batch size (default: 256)' lr = 0.1 #help='initial learning rate') momentum = 0.9 # help='momentum') w...
class ApiException(Exception): pass class DBConnectionIssue(ApiException): def __str__(self): return "Database Error: %s" % self.message class DBError(ApiException): def __init__(self, *args): # args can have 1 or 2 parameters try: self.errno = args[0] self....
""" On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degrees to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and...
class Tweet: def __init__(self, uuid, name, screen_name, tweet_id, tweet, date_time, retweet_count, favourites_count, link): self.uuid = uuid self.name = name self.screen_name = screen_name self.tweet_id = tweet_id self.tweet = tweet self.date_time = date_time ...
""" Basic hash func """ def my_hashing_func(str, table_size): bytes_representation = str.encode() sum = 0 for byte in bytes_representation: sum += byte return sum % table_size class HashTable: #basic hash template code def __init__(self, capacity): self.capacity = capacity ...
def part1(): x, y = 0, 0 for line in open("in.txt").read().splitlines(): direction, num = line.split() num = int(num) if direction == "forward": x += num elif direction == "down": y += num elif direction == "up": y -= num print(x * ...
""" Write a program that iterates over a large set (from 1 to 10000) of numbers and compute a total running sum. NOTE: 1 + 2 + 3 + ... + N - 1 + N = N(N+1)/2 """ def validate_sum(final_num): total = final_num * (final_num + 1) // 2 return total # def python_summation(a_list): # return sum(a_list) ...
arr = [] for arr_i in range(6): arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] arr.append(arr_t) smax = -9 * 7 for row in range(len(arr) - 2): for column in range(len(arr[row]) - 2): tl = arr[row][column] tc = arr[row][column + 1] tr = arr[row][column + 2] mc = arr[row + 1][column + 1] ...
class LSystem(object): def __init__(self): self.steps = 0 self.axiom = "F" self.rule = "F+F-F" self.startLength = 190.0 self.theta = radians(120.0) self.reset() def reset(self): self.production = self.axiom self.drawLength = self.startLength ...
threshold = 0 today = "2020-06-01" github_tokens = [] clone_all = True delete_after = False FEATURES = ['architecture', 'management' 'community', 'continuous_integration', 'documentation', 'history', 'license', 'unit_test']
class Write_file: """ This class holds: write_file() method """ def write_file(self,input,cwd): """ This method is responsible for writing] given contents into a given file name if no file name is given it creates a file with that name if no contents...
frase = 'Curso em Video Python' print(frase[3:13]) print(frase[1:15]) print(frase[2:18:2]) print(frase[::3]) print(frase.replace('Python','Android')) print(frase.split()) print(len(frase)) print(frase.count('o')) print(frase.upper().split()) print(frase.lower().find('em'))
str_original = 'Hello' bytes_encoded = str_original.encode(encoding='utf-8') print(type(bytes_encoded)) str_decoded = bytes_encoded.decode() print(type(str_decoded)) print('Encoded bytes =', bytes_encoded) print('Decoded String =', str_decoded) print('str_original equals str_decoded =', str_original == str_decoded) ...
def mst_prim(G, w, r): for u in G.V: u.key = float('inf') u.p = None r.key = 0 Q = G.V while len(Q) != 0: u = extract_min(Q) for i in range(n): if G.matrix[u][i] == 1 and i in Q and w(u, i) < v.key: i.p = u i.key = w(u, i)
lr = 0.0001 dropout_rate = 0.5 max_epoch = 3136 #3317 batch_size = 4096 w = 19 u = 9 num_hidden_1 = 512 num_hidden_2 = 512