content
stringlengths
7
1.05M
def data_cart(request): total_cart=0 total_items=0 if request.user.is_authenticated and request.session.__contains__('cart'): for key, value in request.session['cart'].items(): if not key == "is_modify" and not key == 'id_update': total_cart = total_...
# int: Minimum number of n-grams occurence to be retained # All Ngrams that occur less than n times are removed # default value: 0 ngram_min_to_be_retained = 0 # real: Minimum ratio n-grams to skip # (will be chosen among the ones that occur rarely) # expressed as a ratio of the cumulated histogram # default value: 0...
customcb = {'_smps_flo': ["#000000", "#000002", "#000004", "#000007", "#000009", "#00000b", "#00000d", "#000010", "#000012", "#000014", "#000016", "#000019", "#00001b", "#00001d", "#00001f", "#000021", "#000024", "#000026", "#000028", "#00002a"...
dados = [] cadastrados = 0 pesado = [] leve = [] nomes_leves = [] nomes_pesados = [] def linha(): print('-' * 80) linha() while True: dados.append(str(input('Nome: ')).capitalize()) dados.append(int(input('Peso: '))) cadastrados += 1 resp = str(input('Quer continuar: ')).upper()[0] if resp == ...
print('#######################') print('###### Exemplo 1 ######') print('#######################') # Exemplo 1 for i in range(5): print('Iterating ', i) print(' ') print('#######################') print('###### Exemplo 2 ######') print('#######################') # Utilizando os itens da lista como indice. smoothi...
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint's name. """ if self.url_prefix is not None: if rule: rule ...
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ NOTES ----- py2app includes all packages in Spyder.app/Contents/Resources/lib/ python<ver>.zip, but some packages have issues when placed there. The following pac...
cont_9 = cont_3 = cont_pares = 0 numeros_pares = "" tupla_numeros = (int(input("Digite o primeiro número: ")), int(input("Digite o segundo número: ")), int(input("Digite o terceiro número: ")), int(input("Digite o quarto número: "))) for c in range(0, 4): if tupla_numeros[c] == 9: cont_...
class ModelSingleton(object): # https://stackoverflow.com/a/6798042 _instances = {} def __new__(class_, *args, **kwargs): if class_ not in class_._instances: class_._instances[class_] = super(ModelSingleton, class_).__new__(class_, *args, **kwargs) return class_._instances[class...
tabuleiro_easy_1 = [ [4, 0, 1, 8, 3, 9, 5, 2, 0], [3, 0, 9, 2, 7, 5, 1, 4, 6], [5, 2, 7, 6, 0, 1, 9, 8, 0], [0, 5, 8, 1, 0, 7, 3, 9, 4], [0, 7, 3, 9, 8, 4, 2, 5, 0], [9, 1, 4, 5, 2, 3, 6, 7, 8], [7, 4, 0, 3, 0, 6, 8, 1, 2], [8, 0, 6, 4, 1, 2, 7, 3, 5], [1, 3, 2, 7, 5, 8, 4, 0, 9...
class Config(object): def __init__(self, vocab_size, max_length): self.vocab_size = vocab_size self.embedding_size = 300 self.hidden_size = 200 self.filters = [3, 4, 5] self.num_filters = 256 self.num_classes = 10 self.max_length = max_length self.num_...
#Mayor de edad mayor=int(input("edad: ")) if(mayor >=18): print("es mator de edad") else: print("es menor de edad")
"""Top-level package for Python Boilerplate.""" __author__ = """Nate Solon""" __email__ = 'nate.solon@gmail.com' __version__ = '0.1.0'
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given a word W and a string S, find all starting indices in S which are anagrams of W. For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4. """ def verify_string_combos(word, string): """ ...
#!/usr/bin/env python3 # implicit None return def say_hi(): print("hey there") # implicit artument return "name" def yell_name(name='Adrienne'): """ this is a doc string also this function returns the arg by default """ print("YO {0} ".format(name.upper())) # scoping def add(num1=0, num2=0...
""" Module for a sudoku Cell with row, column position """ class Cell: """ A Sudoku cell """ def __init__(self, row: int, column: int): """ A Cell at the given row and column :param row: The 1-indexed row of the cell :param column: The 1-indexed column of the cell """ ...
def getBASIC(): list = [] n = input() while True: line = n if n.endswith('END'): list.append(line) return list else: list.append(line) newN = input() n = newN
type_of_flowers = input() count = int(input()) budget = int(input()) prices = { "Roses": 5.00, "Dahlias": 3.80, "Tulips": 2.80, "Narcissus": 3.00, "Gladiolus": 2.50 } price = count * prices[type_of_flowers] if type_of_flowers == "Roses" and count > 80: price -= 0.10 * price elif type_of_flowe...
#170 # Time: O(n) # Space: O(n) # Design and implement a TwoSum class. It should support the following operations: add and find. # # add - Add the number to an internal data structure. # find - Find if there exists any pair of numbers which sum is equal to the value. # # For example, # add(1); add(3); add(5); # ...
def flatten(d: dict, new_d, path=''): for key, value in d.items(): if not isinstance(value, dict): new_d[path + key] = value else: path += f'{key}.' return flatten(d[key], new_d, path=path) return new_d if __name__ == "__main__": d = {"foo": 42, ...
class BotovodException(Exception): pass class AgentException(BotovodException): pass class AgentNotExistException(BotovodException): def __init__(self, name: str): super().__init__(f"Botovod have not '{name}' agent") self.name = name class HandlerNotPassed(BotovodException): def __...
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: tripOccupancy = [0] * 1002 for trip in trips: tripOccupancy[trip[1]] += trip[0] tripOccupancy[trip[2]] -= trip[0] occupancy = 0 for occupancyDelta in tripOccupancy: ...
class Result: def __init__(self, value=None, error=None): self._value = value self._error = error def is_ok(self) -> bool: return self._error is None def is_error(self) -> bool: return self._error is not None @property def value(self): return self._value ...
cv_results = cross_validate( model, X, y, cv=cv, return_estimator=True, return_train_score=True, n_jobs=-1, ) cv_results = pd.DataFrame(cv_results)
# """ # This is Master's API interface. # You should not implement it, or speculate about its implementation # """ #class Master: # def guess(self, word): # """ # :type word: str # :rtype int # """ class Solution: def findSecretWord(self, wordlist, master): n = 0 whil...
class Usercredentials: ''' class to generate new instances of usercredentials ''' user_credential_list = [] #empty list for user creddential def __init__(self,site_name,password): ''' method to define properties of the object ''' self.site_name = site_name ...
"""Fixed and parsed data for testing""" SERIES = { "_links": { "nextepisode": { "href": "http://api.tvmaze.com/episodes/664353"}, "previousepisode": { "href": "http://api.tvmaze.com/episodes/631872"}, "self": { "href": "http://api.tvmaze.com/shows/60"} }, "externals": { "im...
#!/usr/bin/env python def clean_links(text): """Remove brackets around a wikilink, keeping the label instead of the page if it exists. "[[foobar]]" will become "foobar", but "[[foobar|code words]]" will return "code words". Args: text (str): Full text of a Wikipedia article as a single st...
def GetParent(node, parent): if node == parent[node]: return node parent[node] = GetParent(parent[node], parent) return parent[node] def union(u, v, parent, rank): u = GetParent(u, parent) v = GetParent(v, parent) if rank[u] < rank[v]: parent[u] = v elif rank[u] > rank[...
#!/usr/bin/env python3 n, *h = map(int, open(0).read().split()) dp = [0] * n dp[0] = 0 a = abs for i in range(1, n): dp[i] = min(dp[i], dp[i-1] + a(h[i] - h[i-1])) dp[i+1] = min(dp[i+1], dp[i-1] + a(h[i] - h[i-2])) print(dp[n-1])
""" In this Bite you complete the divide_numbers function that takes a numerator and a denominator (the number above and below the line respectively when doing a division). First you try to convert them to ints, if that raises a ValueError you will re-raise it (using raise). To keep things simple we can expect thi...
""" You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't ha...
"""This file defines the unified tensor framework interface required by DeepXDE. The principles of this interface: * There should be as few interfaces as possible. * The interface is used by DeepXDE system so it is more important to have clean definition rather than convenient usage. * Default arguments should be av...
# User input minutes = float(input("Enter the time in minutes: ")) # Program operation hours = minutes/60 # Computer output print("The time in hours is: " + str(hours))
x = 12 y = 3 print(x > y) # True x = "12" y = "3" print(x > y) # ! False / Why it's false ? print(x < y) # ! True # x = 12 # y = "3" # print(x > y) x2 = "45" y2 = "321" print(x2 > y2) # True x2 = "45" y2 = "621" X2_Length = len(x2) Y2_Length = len(y2) print(X2_Length < Y2_Length) # True print( ord('4') ) # 52...
s = """auto 1 break 2 case 3 char 4 const 5 continue 6 default 7 do 8 double 9 else 10 enum 11 extern 12 float 13 for 14 goto 15 if 16 int 17 long 18 register 19 return 20 short 21 signed 22 sizeof 23 static 24 struct 25 switch 26 typedef ...
''' For 35 points, answer the following questions. Create a new folder named file_io and create a new Python file in the folder. Run this 4 line program. Then look in the folder. 1) What did the program do? ''' f = open('workfile.txt', 'w') f.write('Bazarr 10 points\n') f.write('Iko 3 points') f.close() '''Run this ...
# -*- coding: utf-8 -*- def main(): n = int(input()) a = [int(input()) for _ in range(n)][::-1] ans = 0 for i in range(n): p, q = divmod(a[i], 2) ans += p if q == 1: if (i + 1 <= n - 1) and (a[i + 1] >= 1): ans += 1 a...
''' escreva num arquivo texto.txt o conteudo de uma lista de uma vez ''' arquivo = open('texto.txt', 'a') frases = list() frases.append('TreinaWeb \n') frases.append('Python \n') frases.append('Arquivos \n') frases.append('Django \n') arquivo.writelines(frases)
print("Jogo da advinhação") print("******************") numero_secreto = 30 palpite_str = input("Digite o seu palpite: ") palpite = int(palpite_str) maior = palpite > numero_secreto menor = palpite < numero_secreto if palpite == numero_secreto: print("Você acertou!") elif maior: print("Seu palpite ultrapa...
'''Exceptions for my orm''' class ObjectNotInitializedError(Exception): pass class ObjectNotFoundError(Exception): pass
def a(x): # Объявление функции n = 1 # Присваивание переменной n начального значения. while n < len(x): # Задаётся условие для выполнения программы:"Пока порядковый номер элемента меньше количества элементов в списке:" for ...
def download_file(my_socket): print("[+] Downloading file") filename = my_socket.receive_data() my_socket.receive_file(filename)
def return_for_conditions(obj, raise_ex=False, **kwargs): """ Get a function that returns/raises an object and is suitable as a ``side_effect`` for a mock object. Args: obj: The object to return/raise. raise_ex: A boolean indicating if the object should be raised...
# # @lc app=leetcode id=223 lang=python3 # # [223] Rectangle Area # # @lc code=start class Solution: def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: overlap = max(min(C, G) - max(A, E), 0) * max(min(D, H) - max(B, F), 0) total = (A - C) * (B - D) + (E...
gameList = [ 'Riverraid-v0', 'SpaceInvaders-v0', 'StarGunner-v0', 'Pitfall-v0', 'Centipede-v0' ]
class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: n = len(boxes) # dp[i] := min trips to deliver boxes[0..i) and return to the storage dp = [0] * (n + 1) trips = 2 weight = 0 l = 0 for r in range(n): weight += box...
{{AUTO_GENERATED_NOTICE}} CompilerInfo = provider(fields = ["platform", "bsc", "bsb_helper"]) def _rescript_compiler_impl(ctx): return [CompilerInfo( platform = ctx.attr.name, bsc = ctx.file.bsc, bsb_helper = ctx.file.bsb_helper, )] rescript_compiler = rule( implementation = _resc...
''' https://leetcode.com/problems/longest-absolute-file-path/ 388. Longest Absolute File Path Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two s...
# https://leetcode.com/explore/featured/card/fun-with-arrays/521/introduction/3238/ class Solution: def findMaxConsecutiveOnes(self, nums): left = 0 prev = 0 while left < len(nums): counter = 0 if nums[left] == 1: right = left while rig...
# ------------------------------ # 274. H-Index # # Description: # Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. # According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have a...
class Solution(object): def minTimeToVisitAllPoints(self, points): """ :type points: List[List[int]] :rtype: int """ current_pos, time = points[0], 0 for p in points: if current_pos[0] != p[0] or current_pos[1] != p[1]: delta_x = abs(p[0]-c...
# # PySNMP MIB module Nortel-Magellan-Passport-FrameRelayNniTraceMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-FrameRelayNniTraceMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:17:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ...
RSS_PERF_NAME = "rss" FLT_PERF_NAME = "flt" CPU_CLOCK_PERF_NAME = "cpu_clock" TSK_CLOCK_PERF_NAME = "task_clock" SIZE_PERF_NAME = "file_size" EXEC_OVER_HEAD_KEY = 'exec' MEM_USE_OVER_HEAD_KEY = 'mem' FILE_SIZE_OVER_HEAD_KEY = 'size'
LINE_LEN = 25 while True: try: n = int(input()) if n == 0: break surface = [] max_len = 0 for i in range(n): line = str(input()) line = line.strip() l_space = line.find(' ') if l_space == -1: max_len = LINE_LEN else: r_space = line.rfind(' ') ...
fs = None sys = None dataJar = None version = '1.1.0' windows = [] manifest = { 'name': 'Hybrid App Engine', 'version': version, 'description': '轻量级Web桌面应用引擎', 'path': '', 'icon': '', 'width': 800, 'height': 600, 'visible': True, 'resizable': True, 'frameless': False, 'transBackground': False }
f = open('rosalind_motif.txt') a = [] for line in f.readlines(): a.append(line.strip()) dna1, dna2 = a[0], a[1] f.close() def find_motif(dna1, dna2): """Given: Two DNA strings s and t (each of length at most 1 kbp). Return: All locations of t as a substring of s.""" k = len(dna2) indexes = [] for i in range(...
class Solution: def findMin(self, nums: List[int]) -> int: # solution 1 # return min(nums) # solution 2 left = 0 right = len(nums)-1 while left < right: mid = int((left + right)/2) if nums[mid] < nums[right]: right = mid ...
def cyclicQ(ll): da_node = ll sentient = ll poop = ll poop = poop.next.next ll = ll.next while poop != ll and poop is not None and poop.next is not None: poop = poop.next.next ll = ll.next if poop is None or poop.next is None: return None node_in_cycle =...
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 class Trace: '''An object that can cause a trace entry''' def trace(self) -> str: '''Return a representation of the entry for tracing This is use...
WAGTAILSEARCH_BACKENDS = { "default": {"BACKEND": "wagtail.contrib.postgres_search.backend"} }
def key_in_dict_not_empty(key, dictionary): """ """ if key in dictionary: return is_not_empty(dictionary[key]) return False def is_empty(value): """ """ if value is None: return True return value in ['', [], {}] def is_not_empty(value): return not is_empty(value) ...
# https://www.codingame.com/training/easy/1d-spreadsheet def add_dependency(cell, arg_cell, in_deps, out_deps): if cell not in out_deps: out_deps[cell] = set() out_deps[cell].add(arg_cell) if arg_cell not in in_deps: in_deps[arg_cell] = set() in_deps[arg_cell].add(cell) def remove_dependency(cell, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Word: def __init__(self, id, name, image, category=None): self.id = id self.name = name self.image = image self.category = category
def optimal_order(predecessors_map, weight_map): vertices = frozenset(predecessors_map.keys()) # print(vertices) memo_map = {frozenset(): (0, [])} # print(memo_map) return optimal_order_helper(predecessors_map, weight_map, vertices, memo_map) def optimal_order_helper(predecessors_map, weight_map, ...
# Program to implement First Come First Served CPU scheduling algorithm print("First Come First Served scheduling Algorithm") print("============================================\n") headers = ['Processes','Arrival Time','Burst Time','Waiting Time' ,'Turn-Around Time','Completion Time'] # Dictionary to st...
# -*- coding: utf-8 -*- __author__ = 'Sinval Vieira Mendes Neto' __email__ = 'sinvalneto01@gmail.com' __version__ = '0.1.0'
# -*- coding: utf-8 -*- # # This file is part of the SKATestDevice project # # # # Distributed under the terms of the none license. # See LICENSE.txt for more info. """Release information for Python Package""" name = """tangods-skatestdevice""" version = "1.0.0" version_info = version.split(".") description = """A ge...
#--coding:utf-8 -- """ """ class cDBSCAN: """ The major class of the cDBSCAN algorithm, belong to CAO Yaqiang, CHEN Xingwei. """ def __init__(self, mat, eps, minPts): """ @param mat: the raw or normalized [pointId,X,Y] data matrix @type mat : np.array @param eps: The...
# Tuples in python def swap(m, n, k): temp = m m = n n = k k = temp return m, n, k def main(): a = (1, "iPhone 12 Pro Max", 1.8, 1) print(a) print(a[1]) print(a.index(1.8)) print(a.count(1)) b = a + (999, 888) print(b) m = 1 n = 2 k = 3 m, n, k = swap(...
# -*- coding: utf-8 -*- """ *************************************************************************** __init__.py --------------------- Date : August 2014 Copyright : (C) 2014-2016 Boundless, http://boundlessgeo.com **********************************************************...
# O programa le um valor em metros e o exibe convertido em centimetros e milimetros metros = float(input('Entre com a distancia em metros: ')) centimetros = metros * 100 milimetros = metros * 1000 kilometros = metros / 1000.0 print('{} metros e {:.0f} centimetros'.format(metros, centimetros)) print('{} metros e {} m...
try: # TENTA VER SE DÁ CERTO a = int(input('Digite um número: ')) b = int(input('Digite um número: ')) print(f'{a} / {b} = {a / b}') except Exception as erro: # SE DER UM ERRO, RETORNA A VARIÁVEL ERRO COM A INFORMAÇÃO print(f'\033[31mERRO! {erro.__class__}\033[0m') except ValueError: # SE DER UM ERRO...
train_datagen = ImageDataGenerator(rescale=1./255) # rescaling on the fly # Updated to do image augmentation train_datagen = ImageDataGenerator( rescale = 1./255, # recaling rotation_range = 40, # randomly rotate b/w 0 and 40 degrees width_shift_range = 0.2, # shifting the images height_shift_rang...
#!/usr/bin/env python ## # Print a heading. # # @var string text # @return string ## def heading(text): return '-----> ' + text; ## # Print a single line. # # @var string text # @return string ## def line(text): return ' ' + text; ## # Print a single new line. # # @return string ## def nl(): return...
load("@build_bazel_rules_nodejs//:providers.bzl", "run_node") def _create_worker_module_impl(ctx): output_file = ctx.actions.declare_file(ctx.attr.out_file) if (len(ctx.files.worker_file) != 1): fail("Expected a single file but got " + str(ctx.files.worker_file)) cjs = ["--cjs"] if ctx.attr.cjs el...
"""ANSI color codes for the command line output.""" RESET = u"\u001b[0m" BLACK = u"\u001b[30m" RED = u"\u001b[31m" GREEN = u"\u001b[32m" YELLOW = u"\u001b[33m" BLUE = u"\u001b[34m" MAGENTA = u"\u001b[35m" CYAN = u"\u001b[36m" WHITE = u"\u001b[37m" BRIGHT_BLACK = u"\u001b[30;1m" BRIGHT_RED = u"\u001b[31;1m" BRIGHT_GREE...
print('Laboratory work 1.1 measurements of the R-load.') measurements = [] measurements_count = int(input('Enter number of measurements : ')) for cur_measurement_number in range(1, measurements_count+1): print(f'Enter value for measurement {cur_measurement_number} -> ', end='') measurement = float(input()) ...
#tests: depend_extra depend_extra=('pelle',) def synthesis(): pass
### ANSI ''' \033[style; text; backgroundm \033[0;33;44m style - 0 = faz nada, 1 = negrito, 4 = subliando, 7 = inverter configurações text - 30 = branco, 31 = vermelho, 32 = verde, 33 = amarelo, 34 = azul, 35 = roxo, 36 = ciano, 37 = cinza background - 40 = branco, 41 = vermelho, 42 = verde, 43 = amarelo, 44 = azul, 4...
def _capnp_toolchain_gen_impl(ctx): ctx.template( "toolchain/BUILD.bazel", ctx.attr._build_tpl, substitutions = { "{capnp_tool}": str(ctx.attr.capnp_tool), }, ) capnp_toolchain_gen = repository_rule( implementation = _capnp_toolchain_gen_impl, attrs = { ...
expected_output = { 'steering_entries': { 'sgt': { 2057: { 'entry_last_refresh': '10:32:00', 'entry_state': 'COMPLETE', 'peer_name': 'Unknown-2057', 'peer_sgt': '2057-01', 'policy_rbacl_src_list': { ...
contacts = {"John": "01217000111", "Addison": "01217000222", "Jack": "01227000123"} print("contacts: ", contacts) print("Element count: ", len(contacts)) contactsAsString = str(contacts) print("str(contacts): ", contactsAsString) # Một đối tượng đại diện lớp 'dict'. aType = type(contacts) print("type(contacts): "...
''' 给定一个有序数组a = [3,7,8,9],一个二维数组querys = [[2,5], [3,7], [2, 8]], 要求返回对于query中每一项的range,数组在这个范围内的数字个数。 解法一:遍历数组,依次判断数组是否在querys的每个queray的range中并计数,时间复杂度O(n*m)。 解法二:遍历querys,对每个query的start和end在数组中进行二分查找,得到对应位置后再相减。 总结:需要注意边界条件的检查,包括 1. 二分查找的停止条件,是否可能存在死循环。计算middle是否可能溢出(python中不用考虑)。 2. 当整个数组都小于或大于target时...
__author__ = 'Stormpath, Inc.' __copyright__ = 'Copyright 2012-2014 Stormpath, Inc.' __version_info__ = ('1', '3', '1') __version__ = '.'.join(__version_info__) __short_version__ = '.'.join(__version_info__)
J # welcoming the user name = input("What is your name? ") print("Hello, " + name, "It is time to play hangman!") print("Start guessing...") # here we set the secret word = "secret" # creates a variable with an empty value guesses = '' # determine the number of turns turns = 10 while turns > 0: failed = 0 ...
conductores = { 'azambrano': ('Andres Zambrano', 5.6, ('Hyundai', 'Elantra')), 'jojeda': ('Juan Ojeda', 1.1, ('Hyundai', 'Accent')), # ... } def agrega_conductor(conductores, nuevo_conductor): username, nombre, puntaje, (marca, modelo) = nuevo_conductor if username in conductores: ...
""" Implement a class for a Least Recently Used (LRU) Cache. The cache should support inserting key/value paris, retrieving a key's value and retrieving the most recently active key. Each of these methods should run in constant time. When a key/value pair is inserted or a key's value is retrieved, the key in question...
#calculator def add(n1,n2): return n1 +n2 def substract(n1,n2): return n1-n2 def multiply(n1,n2): return n1 * n2 def devide(n1,n2): return n1/n2 operator = { "+": add, "-": substract, "*": multiply, "/": devide, } num1 = float(input("Enter number: ")) op_simbol = input("enter +...
a1 = int(input('Insira o primeiro termo dessa p.a.: ')) r = int(input('Insitra a razão dessa p.a.')) quant = 1 continuar = 10 tot = 1 while continuar != 0: tot += continuar while quant <= tot: an = a1 + r*(quant - 1) quant += 1 print(an) continuar =...
# https://www.codechef.com/problems/SUMPOS for T in range(int(input())): l=sorted(list(map(int,input().split()))) print("NO") if(l[2]!=l[1]+l[0]) else print("YES")
''' Faça um programa q mostre a tabuada de varios numeros 1 de cada vez e só pare se o numero digitado for negativo ''' while True: num = int(input("Diga um numero [digite um negativo para sair]")) if num < 0: print() print("Voce saiu") break for i in range (1,11): print(n...
class LoggerTemplate(): def __init__(self, *args, **kwargs): raise NotImplementedError def update_loss(self, phase, value, step): raise NotImplementedError def update_metric(self, phase, metric, value, step): raise NotImplementedError
var={"car":"volvo", "fruit":"apple"} print(var["fruit"]) for f in var: print("key: " + f + " value: " + var[f]) print() print() var1={"donut":["chocolate","glazed","sprinkled"]} print(var1["donut"][0]) print("My favorite donut flavors are:", end= " ") for f in var1["donut"]: print(f, end=" ") print() print() #Usin...
#Challenge 4: Take a binary tree and reverse it #I decided to create two classes. One to hold the node, and one to act as the Binary Tree. #Node class #Only contains the information for the node. Val is the value of the node, left is the left most value, and right is the right value class Node: def __init__(self, ...
DAOLIPROXY_VENDOR = "OpenStack Foundation" DAOLIPROXY_PRODUCT = "DaoliProxy" DAOLIPROXY_PACKAGE = None # OS distro package version suffix loaded = False class VersionInfo(object): release = "1.el7.centos" version = "2015.1.21" def version_string(self): return self.version def release_string(...
# Space: O(n) # Time: O(n) class Solution: def findUnsortedSubarray(self, nums): length = len(nums) if length <= 1: return 0 stack = [] left, right = length - 1, 0 for i in range(length): while stack and nums[stack[-1]] > nums[i]: left = min(lef...
# encoding: utf-8 # module Autodesk.AutoCAD.DatabaseServices # from D:\Python\ironpython-stubs\release\stubs\Autodesk\AutoCAD\DatabaseServices\__init__.py # by generator 1.145 # no doc # no imports # no functions # no classes # variables with complex values __path__ = [ 'D:\\Python\\ironpython-stubs\\release\\stu...
# coding=utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License")...
f = str ( input( 'Escreva alguma frase:')) print (' Sua frase contém {} letras "as".'.format(f.count('a'))) print (' Ela aparece pela primeira fez na posição {}.'.format(f.find('a'))) print (' E.aparece pela última vez na posição {}.' .format( f.rfind ('a')))