content
stringlengths
7
1.05M
# -*- coding: utf-8 -*- # @Time : 2021/5/24 4:08 PM # @Author: lixiaomeng_someday # @Email : 131xxxx119@163.com # @File : TP_02_remove_duplicates.py """ story: Given an array of sorted numbers, remove all duplicates from it. You should not use any extra space; after removing the duplicates in-place return...
class Person(object): def __init__(self, name, age): self.name = name self.age = age # Ghi đè phương thức __eq__ def __eq__(self, other): return self.name == other.name and self.age == other.age jack1 = Person('Jack', 23) jack2 = Person('Jack', 23) # Gọi tới phương thức __eq__ pr...
class Node: '''each node represents a different dog or cat object They each have a name, a type (cat or dog), and a reference to the next animal in the shelter queue ''' def __init__(self, animal_type, next_node=None): self.animal_type = animal_type self.next = next_node class Inva...
target_x = range(211, 233) target_y = range(-124, -68) # part 1 and 2 x_hits = [] infinite_x_hits = [] for vx in range(1, target_x.stop): pos = 0 i = 0 while pos < target_x.stop and vx > i: pos += vx - i i += 1 if pos in target_x: x_hits.append((vx, i)) if vx == i a...
class Inteligencia: def __init__(self, nomeArquivoIA, arquivosExternos, ambientes, entradas, todosTiposJogadores, preJogos): self.INomeArquivoIA = nomeArquivoIA self.IArquivosExternos = arquivosExternos self.IAmbientes = ambientes self.IEntradas = entradas se...
n = 0 factor = 20 while True: n = n + factor is_divisible = True for i in range(1, factor + 1): if n % i != 0: is_divisible = False break if (is_divisible): break print(n)
line = input().split(" ") n = int(line[0]) # nodes m = int(line[1]) # edges graph = {} def find_lowest_cost_node(costs, processed): lowest_cost_node = None lowest_cost = float("inf") for node, cost in costs.items(): if cost < lowest_cost and node not in processed: lowest_cost_node = ...
class Solution: # @param {string} s # @return {integer} def lengthOfLongestSubstring(self, s): n = len(s) if n <=1: return n start = 0 max_count = 1 c_dict = {s[0]:0} for p in range(1,n): sub = s[start:p] c = s[p] ...
broj = -1 while broj != 0: print("Trenutni broj je " + str(broj)) broj = int(intpu("Unesite novi broj: ")) print("Kraj")
name="Ashwin" def student(): print("Name",name) #accessing in def also student() if name[0]=="A": #accessing in global print("Starts from A") x = 300 def myfunc(): global x x = 200 print(x) myfunc() print(x)
# GENERATED VERSION FILE # TIME: Fri Sep 11 18:59:53 2020 __version__ = '0.3.0+038435e' short_version = '0.3.0'
""" Data types for RAIL File Input/Output """ #from rail.core.data import DataFile #class TextFile(DataFile): # """ # A data file in plain text format. # """ # suffix = "txt" # format = "http://edamontology.org/format_2330" #@classmethod #def read(cls, path): #@classmethod #def writ...
def quick_sort(nums: list) -> list: if len(nums) <= 1: return nums mid = nums[0] return quick_sort([i for i in nums if i < mid]) + [mid] + quick_sort([i for i in nums if i > mid])
# -*- coding: utf-8 -*- """ idfy_rest_client.models.jwt_validation_request This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ class JwtValidationRequest(object): """Implementation of the 'JwtValidationRequest' model. Jwt validation request ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: dummy = ListNode(None) dummy.next = head p = dummy while p.next: ...
# Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps. # Input: n = 3 # Output: 4 # Explantion: # Below are the four ways # 1 step + 1 step + 1 step # 1 step + 2 step # 2 step + 1 step # 3 step def noofWays(n): dp=[0 for i in range(n+1)] dp[0] = 1 dp[1] = 1 dp[2] =...
# -*- coding: utf-8 -*- ftx = { 'apiKey':"your_api_key_here" , 'secret':"your_api_secret_here", }
# The location of the extracted scilab_for_xcos_on_cloud. This can be either # relative to SendLog.py or an absolute path. SCILAB_DIR = '../scilab_for_xcos_on_cloud' # The location to keep the flask session data on server. FLASKSESSIONDIR = '/tmp/flask-sessiondir' # The location to keep the session data on server. SE...
class ApiError(Exception): pass class WrongToken(ApiError): pass class PermissionError(ApiError): pass
def solve(A): T = [None]*len(A) prev = [None]*len( A) for i in range(len(A)): T[i] = 1 prev[i] = -1 for j in range(i): if A[j] < A[i] and T[i] < T[j]+1: T[i] = T[j]+1 return max(T[i] for i in range(len(A))) if __name__ == '_...
# -- coding: UTF-8 class String(object): def __init__(self): super(String, self).__init__() ''' 类名标准化 ''' def class_name_normalize(self, class_name): part_list = [] for item in class_name.split("_"): part_list.append("{}{}".format(item[0].upper(), item[1...
""" A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles. """ def word_search(documents, keyword): # list holds the indices of matching documents indices = [] # ...
while True: numero= int(input("Escribir un numero= ")) if numero%2 == 0: print("El numero es par") else: print("El numero es impar")
# Natural Language Toolkit: code_search_documents def raw(file): contents = open(file).read() contents = re.sub(r'<.*?>', ' ', contents) contents = re.sub('\s+', ' ', contents) return contents def snippet(doc, term): text = ' '*30 + raw(doc) + ' '*30 pos = text.index(term) return text[pos-...
class Solution: def diffWaysToCompute(self, input: str) -> [int]: end = [] op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y} for i in range(len(input)): if input[i] in op.keys(): for left in self.diffWays...
__author__ = ['Tomas Mendez Echenagucia <tmendeze@uw.edu>'] __copyright__ = 'Copyright 2020, Design Machine Group - University of Washington' __license__ = 'MIT License' __email__ = 'tmendeze@uw.edu' __all__ = [ 'Node', ] class Node(object): """ Initialises base Node object. Parameters ...
# Queue in python """ Queue is like people entering in a theatre in queue i.e: add elements at the end, and remove the elements from the start A Queue in python is where you can add or remove elements either side is called `deque` or `double ended queue`. and in the stack, you add and remove from the same end """
def counting_sort(array): """ В первой строке задано количество предметов в гардеробе: n <= 1000000 Во второй строке даётся массив, в котором указан цвет для каждого предмета. Розовый цвет обозначен 0, жёлтый — 1, малиновый – 2. Вывести в строку через пробел цвета предметов в правильном порядке. ...
#PLOTS ################################################## #if(plot_opacity == True): # p_plot = np.linspace(2.0,6.0,21) # a_plot = np.logspace(np.log10(0.001),np.log10(10.),21) # # EXT_plot = EXT(a_plot,p_plot) # ALB_plot = ALB(a_plot,p_plot) # # plt.close() # fig = plt.figure() # ax = fig.ad...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'chromium', 'chromium_android', 'recipe_engine/json', ] def RunSteps(api): api.chromium.set_config('chromium') api.chromium_androi...
def solveQuestion(value): n = -1 total = 0 while total < value: n += 1 total = 4*n*n - 4*n + 1 n = n - 1 minSpiralVal = 4*n*n - 4*n + 1 difference = value - minSpiralVal # if difference is more than n - 1 if difference < n: return n + difference elif d...
input = "()()(()()()(()()((()((()))((()((((()()((((()))()((((())(((((((()(((((((((()(((())(()()(()((()()(()(())(()((((()((()()()((((())((((((()(()(((()())(()((((()))())(())(()(()()))))))))((((((((((((()())()())())(())))(((()()()((((()(((()(()(()()(()(()()(()(((((((())(())(())())))((()())()((((()()((()))(((()()()())))((...
class COLORS: header = "\033[4m" red = "\033[31m" green = "\033[32m" blue = "\033[34m" normal = "\033[0m" def format_verse(reference, text) -> str: return "{blue}{reference}{normal} \n{verse}\n".format( blue=COLORS.blue, reference=reference, normal=COLORS.normal, verse=text ...
class Solution: # @param A : list of integers # @return an integer def solve(self, A): s = set(A) if len(s) == len(A): return -1 for i in A: if A.count(i) > 1: return i else: return -1
# Environment variables ENV_PROJECT_PATH = "PROJECT_PATH" ENV_FLOW_PATH = "FLOW_PATH" ENV_SCRIPT_PATH = "SCRIPT_PATH" ENV_PLATFORM_SCRIPT_PATH = "PLATFORM_SCRIPT_PATH" # Contexts CTX_EXEC = "exec"
print("Привет".find("т")) print("Привет".find("П")) print("Привет".rfind("т")) print("Привет".rfind("П")) print("Привет".index("т")) print("Привет".index("П"))
N, W, H = map(int, input().split()) row, col = [0] * (H + 1), [0] * (W + 1) for _ in range(N): x, y, w = map(int, input().split()) row[max(0, y - w)] += 1 row[min(H, y + w)] -= 1 col[max(0, x - w)] += 1 col[min(W, x + w)] -= 1 for i in range(H): row[i + 1] += row[i] for i in range(W): col[i ...
# Calculates a^b def power(a, b): if b == 0: return 1 b -= 1 return a*power(a, b) x = int(input()) y = int(input()) print(power(x, y))
''' Program Description: Calculate factorial of a given number ''' def calculate_factorial(n): if n == 0: return 1 if n < 0: raise ValueError fact = 1 for x in range(1,n+1): fact *= x return fact print('N = ', end='') try: result = calculate_factorial(int(input())) print('Output =', result) except Val...
class A: def __init__(self): print('base class constructor ') class B(A): def __init__(self): super().__init__() print('child class constructor ') b1=B()
#Incomplete ordering class PartOrdered(object): def __eq__(self, other): return self is other def __ne__(self, other): return self is not other def __hash__(self): return id(self) def __lt__(self, other): return False #Don't blame a sub-class for super-class's sins. ...
config = { "coinbase":{ "Key": "", "Secret": "" }, "twilio":{ "Key": "", "Secret": "", "from": "+12223334444", "to_list": ["+12223334444"], }, "bittrex":{ "Key" : "", "Secret" : "" } }
def getNthFib(n): if(n==1): return 0 elif (n==2): return 1 else: return getNthFib(n-1) + getNthFib(n-2) #End of getNthFib if __name__ == '__main__': print(getNthFib(6))#5 print(getNthFib(7))#8 print(getNthFib(1))#0 print(getNthFib(11))#55 print(getNthFib(18))#15...
# recursive power method # 7. Рекурсивный метод возведения в степень. Разработайте функцию, в # которой рекурсия применяется для возведения числа в степень. Данная # функция должна принимать два аргумента: число, которое будет возведено в # степень, и показатель степени. Исходите из того, что показатель степени # ...
class BadMessageError(Exception): # A bad message is broken in some way that will never be accepted by # the endpoing and as such should be rejected (it will still be logged # and stored so no data is lost) pass class RetryableError(Exception): # A retryable error is apparently transient and may b...
def cents_to_dollars(cents): """ Convert cents to dollars. :param cents: Amount in cents :type cents: int :return: float """ return round(cents / 100.0, 2) def dollars_to_cents(dollars): """ Convert dollars to cents. :param dollars: Amount in dollars :type dollars: float ...
name = "igittigitt" title = "A spec-compliant gitignore parser for Python" version = "v2.0.4" url = "https://github.com/bitranox/igittigitt" author = "Robert Nowotny" author_email = "bitranox@gmail.com" shell_command = "igittigitt" def print_info() -> None: print( """\ Info for igittigitt: A spec-co...
class n_A(flatdata.archive.Archive): _SCHEMA = """namespace n { archive A { } } """ _NAME = "A" _RESOURCES = { "A.archive" : flatdata.archive.ResourceSignature( container=flatdata.resources.RawData, initializer=None, schema=_SCHEMA, is_optional=False,...
for i in range(11): print(i) for i in "pythonの世界へようこそ": print(i)
#! /usr/bin/python # Samples Python/PYgames # Print 'Hi' 10 times for i in range(10): print("Hi") for i in range(5): print("Hello") print ("There") for i in range(5): print("Hello") print("There") for i in range(10): print(i) for i in range(1, 11): print(i) for i in range(10, 0, -1): p...
def draw_z(size, position, target): if size == 1: return (position == target, 1) base_r, base_c = position half_size = size // 2 counter = 0 matched = False if (target[0] >= (base_r + size)) or (target[1] >= (base_c + size)): counter = size ** 2 return (matched, counter...
# # @lc app=leetcode.cn id=174 lang=python3 # # [174] dungeon-game # None # @lc code=end
""" PASSENGERS """ numPassengers = 19423 passenger_arriving = ( (5, 4, 5, 6, 7, 2, 3, 1, 0, 1, 2, 0, 0, 6, 6, 2, 2, 3, 1, 1, 1, 2, 2, 1, 1, 0), # 0 (5, 7, 2, 5, 4, 2, 2, 1, 5, 1, 1, 1, 0, 10, 5, 2, 0, 6, 2, 0, 3, 3, 3, 1, 2, 0), # 1 (3, 6, 7, 3, 4, 4, 0, 1, 2, 0, 0, 1, 0, 5, 2, 7, 2, 4, 3, 1, 2, 1, 5, 0, 0, 0),...
class Solution: def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: answer=0 aliceVisited=[0]*(n+1) bobVisited=[0]*(n+1) aliceSet={} aliceSetNum=1 bobSet={} bobSetNum=1 # Return False if this edge can be deleted. Applies to...
def fibonum(num): if num == 1: return 1 elif num == 2: return 1 else: return fibonum(num - 1) + fibonum(num - 2)
age = int(input('What your age?: ')) if age <= 2: print('Is a baby!') elif age <= 4: print('You are a children!') elif age <= 13: print('You are a kid!') elif age <= 20: print('You are a teenager!') elif age <= 65: print('You are a adult!') else: print('You are a old!')
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Patrón de diseño Visitante """ __author__ = "Sébastien CHAZALLET" __copyright__ = "Copyright 2012" __credits__ = ["Sébastien CHAZALLET", "InsPyration.org", "Ediciones ENI"] __license__ = "GPL" __version__ = "1.0" __maintainer__ = "Sébastien CHAZALLET" __email__ = "seba...
class Student(): def __init__(self): self._name = 'John' self._age = 18 self._grades = [9.5, 5.75, 10] s1 = Student() # Verify if s1 has the attribute 'name': print(hasattr(s1, 'name')) # Sets a new attribute 'average': setattr(s1, "average", sum(s1._grades) / 3) # Gets t...
class Solution: ''' 1. char_freq count and updates the char frequent of current window and updates accordingly as the window moves forward. so it dosen't need to delete the elements when the count become 0. 2. window length - window max_count > windown length - global max_count > k. If window length - most...
'''https://leetcode.com/problems/binary-search/''' class Solution: def search(self, nums: List[int], target: int) -> int: l, h = 0, len(nums)-1 while l<=h: m = (l+h)//2 if nums[m]==target: return m elif nums[m]>target: h = m-1 ...
def bubblesort(array): length = len(array)-1 for i in range(length,0,-1): for j in range(i): if array[j] > array[j+1]: array[j],array[j+1]=array[j+1],array[j]
#!/usr/bin/env python3 # coding: utf-8 def position(T, s): """renvoie la position de la chaine s dans la liste T Si s n'appartient pas à la liste T, la fonction renvoie -1 à la place. T: liste de chaine de caractères s: chaine de caractère résultat: nombre entier """ try: return T...
# -*- coding: utf-8 -*- """ Created on Sat Sep 8 16:04:50 2018 @author: robot """
# Time complexity: O(n^2) # Approach: Fix one and then based on that loop over other numbers. class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return [] nums = sorted(nums) ans = [] for k in range(n): tar...
''' @description 2019/09/14 13:38 ''' # 字典常用方法: # 1.clear:清除字典所有的项。 person1 = {'username': 'zhiliao', 'age': 18, 'weight': 160, 'height': 180} person2 = person1 print(person1) # {'username': 'zhiliao', 'age': 18} print(person2) # {'username': 'zhiliao', 'age': 18} # 使用clear清除了,person1和person2的引用 # person1.clear() #...
''' Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.) Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".) Example 1: Input: "banana" Output...
class Solution(object): def minCostII(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 dp = [[0] * len(costs[0]) for _ in xrange(0, len(costs))] dp[0] = costs[0] for i in xrange(1, len(costs)):...
Friend1 = {"First_name": "Anita", "Last_name": "Sanchez", "Age": 21, "City": "Saltillo"} Friend2 = {"First_name": "Andrea", "Last_name": "De la Fuente", "Age": 21, "City": "Monclova"} Friend3 = {"First_name": "Jorge", "Last_name": "Sanchez", "Age":20, "City": "Saltillo"} amigos = [Friend1, Friend2, Friend3] for i in ...
""" 1518. 换酒问题 小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。 如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。 请你计算 最多 能喝到多少瓶酒。 """ def numWaterBottles(numBottles, numExchange): if numBottles < numExchange: return numBottles # 一共喝了多少 res = numBottles # 剩余空瓶子 empty = numBottles while empty // numExch...
# -*- coding: utf-8 -*- # Aufgaben 6, 7, 20, 21, 24, 30, 34, 39, 38, 41, 43 Bis Dienstag # ----------------- # 41 list in nested loop # ----------------- words = ['attribution', 'confabulation', 'elocution', 'sequoia', 'tenacious', 'unidirectional'] s = sorted(set([''.join([c for c in w if c in 'aeiou']) fo...
def main(): ref = "lunes,martes,miercoles,juevez,viernes,sabado,domindo".split(",") day = int(input("Day: ")) - 1 print(ref[day]) if __name__ == '__main__': main()
file = open('data/day1.txt', 'r') values = [] for line in file.readlines(): values.append(int(line)) counter = 0 i = 3 while i < len(values): if values[i-3] < values [i]: counter = counter + 1 i = i + 1 print(counter)
fun = lambda s : True if len(s) > 5 else False print(fun("sidd")) print(fun("sidddha")) names = ['alka','sidd','lala'] for pos,name in enumerate(names): print(f"{pos} ===> {name}") string = "lala" for pos,name in enumerate(names): if(name == string): print(f"{pos} ===> {name}")
class BinarySearchTree(): def __init__(self): self.root = None def insert(self, data): if self.root: return self.root.insert(data) else: self.root = Node(data) return True def find(self, data): if self.root: return self.root....
# -*- coding: utf-8 -*- """Main module.""" def pluck(dictionary, key): """ Return array. :param dictionary: array :param key: string """ try: ages = [li[key] for li in dictionary] return ages except KeyError as e: raise KeyError(e.message) except TypeError as ...
# An example of function calling another def func_a(): print('A') # func_b() calls system function print() def func_b(): print('B') # func_ab() calls func_a() and func_b() def func_ab(): func_a() func_b() print('Done!') # Main calls func_ab() def main(): func_ab() # Call main() function....
# -*- encoding:utf8 -*- """:: _/_/_/ _/ _/ _/_/ _/ _/ _/_/ _/_/_/ _/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ ...
#Problema 9 res = 0 for a in range(1, 500): for b in range(1, 500): for c in range(1, 500): if (a < b < c) and (a ** 2 + b ** 2 == c ** 2): if a + b + c == 1000: res = a*b*c print(res)
# Rule for building verilator simulations. # # Copyright 2019 Erik Gilling # # Heavily informed from the rules_foreign_cc package at: # https://github.com/bazelbuild/rules_foreign_cc/ # Since verilator uses make to build its output it shares some actions with # @rules_foreign_cc. load("@rules_foreign_cc//tools/build...
class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None @staticmethod def pre_order(root, nodes): if not root: return nodes.append(root.data) Node.pre_order(root.left, nodes) Node.pre_order(root....
class Node(): def __init__(self, data=None,next_node=None): self.data = data self.next_node = next_node def __str__(self): return self.data def get_next(self): return self.next_node def set_new_next(self, new_next): self.next_node = new_next class LinkedList(): def __init_...
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 17:44:54 2020 @author: teja """ ex_str = "God has created the universe so beautiful that the description of it can be represented in lisp." ex_str = ex_str[:-1] print(ex_str) ex_list = list(map(lambda x: x.lower(), ex_str.split())) ex_list.sort(key=lambda x: len(x))...
valid_sequence_dict = { "P1": "complete protein", "F1": "protein fragment", \ "DL": "linear DNA", "DC": "circular DNA", "RL": "linear RNA", \ "RC":"circular RNA", "N3": "transfer RNA", "N1": "other" }
# Marcelo Campos de Medeiros # ADS UNIFIP # REVISÃO DE PYTHON # AULA 18 Variáveis Composta Listas 2° parte---> GUSTAVO GUANABARA ''' A primore o desafio 86 e mostre: 1- Soma de todos os valores pares digitados 2- Soma de todos os valores terceira coluna 3- O maior valor da segunda linha ''' print('='*30) p...
f = open("test.txt") print(f.read())
def fibonacci(N :int)->int: if N==1 or N==2: return 1 else : return fibonacci(N-1)+fibonacci(N-2) def main(): # input N = int(input()) # compute # output print(fibonacci(N)) if __name__ == '__main__': main()
class ConnectedSIPMessage(object): def __init__(self, a_sip_transport_connection, a_sip_message): self.connection = a_sip_transport_connection self.sip_message = a_sip_message @property def raw_string(self): if self.sip_message: return self.sip_message.raw_string ...
# -*- coding: utf-8 -*- class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.queue = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.queue.append(x) def pop(self) -> int:...
# Change to API-tokens CONSUMER_KEY='[TWITTER CONSUMER KEY]' CONSUMER_SECRET='[TWITTER CONSUMER SECRET]' # Change to proper username/password ADMIN_NAME='admin' ADMIN_PW='1234' # Change to proper secrete key e.g. `python3 -c 'import os; print(os.urandom(16))'` SECRET_KEY = b'1234'
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: cs = head cf = head if head == None: return None if cf.next == None: ...
""" This is a module to be used as a reference for building other modules """ def foo(): """docstring for foo""" return 'foo' class Bar(): """docstring for Bar""" def __init__(self, arg): super().__init__() self.arg = arg
def toh(disks, source, destination, helper) -> int: # Number of steps it will take to transfer the disks from one tower to another # Base Case if disks == 1: print("move disk {} from {} -> {}".format(disks, source, destination)) return 1 # only one step needed # Hypothesis steps_t...
# -*- coding: utf-8 -*- """ KM3NeT Data Definitions v2.0.0-9-gbae3720 https://git.km3net.de/common/km3net-dataformat """ # reconstruction data = dict( JPP_RECONSTRUCTION_TYPE=4000, JMUONBEGIN=0, JMUONPREFIT=1, JMUONSIMPLEX=2, JMUONGANDALF=3, JMUONENERGY=4, JMUONSTART=5, JLINEFIT=6, ...
class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: raise Exception("No Available Prices") low = prices[0] # lowest HISTORICAL price profit = 0 for i in range(1, len(prices)): if prices[i] - low > profit: profit = pr...
# Create a calculator function # The function should accept three parameters: # first_number: a numeric value for the math operation # second_number: a numeric value for the math operation # operation: the word 'add' or 'subtract' # the function should return the result of the two numbers added or subtracted # based on...
# Auto generated by web.apps.config module WXMP_TOKEN='laonabuzhai' WXMP_APP_ID='wxadf692dbf276c755' WXMP_APP_KEY='d5d70f3c91578b545de3392c8c758dad ' WXMP_ENCODING_AES_KEY='Y81yOIit1k5GZS9Vhx5L1JCOVaQJc9uXnhvaDVKGq4k' WXMP_MSG_ENCRYPT_METHOD='clear'
# Find this puzzle at: # https://adventofcode.com/2020/day/6 with open('input.txt', 'r') as file: puzzle_input = [i for i in file.read().split('\n\n')] answered = 0 for group in puzzle_input: ques_answered = set() # Add all questions answered to a set. # Duplicates are avoided by using a set. for q...
def test_app_is_created(app): assert app.name == 'joalheria.app' def test_config_is_loaded(config): assert config["DEBUG"] is False
numA = int(input('Digite um número inteiro: ')) numB = int(input('Digite outro número inteiro: ')) numC = float(input('Digite um número real: ')) a = (2 * numA) * (numB / 2) b = (3 * numA) + numC c = numC ** 3 print(f'O produto do dobro de {numA} com metade de6 {numB} é igual a {a}') print(f'A soma do triplo de {numA} ...
database = {"shuttle":9080590855,"barath":638383877,"hannah":6987237898} print("\nGreeting\'s from Vigneshwaram") print("Welcome to phoneBook\n") while True: print("Type EDIT to edit the contact number\n CREATE to create a new contact\n SEARCH to search a specific contact\n DELETE to Delete the con...