content
stringlengths
7
1.05M
""" This module demonstrates OVERLOADING the + symbol: -- With numbers as operands, it means addition (as in arithmetic) -- With sequences as operands, it means concatenation, that is, forming a new sequence that stitches together its operands. This module also demonstrates the STR function. Authors...
""" 输入一个正整数判断它是不是素数 """ num = int(input('请输入一个正整数: ')) end = int(num ** 0.5) + 1 is_prime = True for x in range(2, end): if num % x == 0: is_prime = False break if is_prime and num != 1: print(f'{num}是素数') else: print(f'{num}不是素数')
filename = 'full_text_small.txt' def file_write(filename): with open(filename, 'r') as f: n = 0 for line in f: n += 1 if n <= 5: print(line) return(line) file_write(filename)
a = 1 b = 0 c = a & b d = a | b e = a ^ b print(c+d+e) my_list = [[1,2,3,4] for i in range(2)] print(my_list[1][0]) x =2 x = x==x print(x) my_list = [1,2,3] for v in range(len(my_list)): my_list.insert(1, my_list[v]) print(my_list)
n = int(input()) ans = 0 for i in range(n): l, c = map(int, input().split()) if l > c: ans += c else: continue print(ans)
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn_moco.py', '../_base_/datasets/vocdataset_voc0712.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] optimizer = dict(type='SGD', lr=0.02/16, momentum=0.9, weight_decay=0.0001)
_base_ = ['./mswin_par_small_patch4_512x512_160k_ade20k_pretrain_224x224_1K.py'] model = dict( decode_head=dict( mode='seq', )) data = dict(samples_per_gpu=10)
def merge_sort(arr): n = len(arr) if (n >= 2): A = merge_sort(arr[:int(n/2)]) B = merge_sort(arr[int(n/2):]) i = 0 j = 0 for k in range(0, n): if i < int(n/2) and (j == len(B) or A[i] <= B[j]): arr[k] = A[i] i = i + 1 ...
#Задачи на циклы и оператор условия------ #---------------------------------------- ''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' for i in range(1,6): print(i,' 0') ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользовате...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) ...
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( x , y , z ) : if ( not ( y / x ) ) : return y if ( not ( y / z ) ) else z return x if ( not ( x / z...
config = { 'lr': (1.5395901937079718e-05, 4.252664987376195e-05, 9.011700881717918e-05, 0.00026653695086486183), 'target_stepsize': 0.07688144983085089, 'feedback_wd': 5.751527315358352e-07, 'beta1': 0.9, 'beta2': 0.999, 'epsilon': (7.952762675272583e-06, 3.573159556208438e-06, 1.0425400798717413e-08, 2.023264400953111...
# constants related to the matchers # all the types of matches MATCH_TYPE_NONE = 0 MATCH_TYPE_RESET = 1 MATCH_TYPE_NMI = 2 MATCH_TYPE_WAIT_START = 3 MATCH_TYPE_WAIT_END = 4 MATCH_TYPE_BITS = 6 # number of bits required to represent the above (max 8) NUM_MATCHERS = 32 # how many match engines are there? MATCHER_BITS ...
def get_initial(name, force_uppercase=True): if force_uppercase: initial = name[0:1].upper() else: initial = name[0:1].lower() return initial first_name = input('Enter your first name: ') # initial = get_initial(first_name) initial = get_initial(force_uppercase=False, name=first_name) prin...
INPUT_PATH = "./input.txt" input_file = open(INPUT_PATH, "r") lines = input_file.readlines() input_file.close() divided_input = [[[set(x) for x in x.split()] for x in line.split(" | ")] for line in lines] # Part 1 print("Part 1: ", sum([len([x for x in entry[1] if len(x) in [2, 3, 4, 7]]) for entry in divided_input...
#Python Lists mylist = [ "banana", "abacate", "manga"] print(mylist)
# working on final project to combine all the learnt concepts into 1 # problem statement. #The CTO wants to monitor all the computer usage by all engineers. Using Python , # write an automation script that will produce a report when each user logged in and out, # and how long each user used the computers. # writing ...
class RockartExamplesException(Exception): pass class RockartExamplesIndexError(RockartExamplesException, IndexError): pass class RockartExamplesValueError(RockartExamplesException, ValueError): pass
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n") row = int(input("Enter the number of rows: ")) for i in range(1, row+1): for j in range(i): print("*", end=" ") print() for i in range(row+1, 0, -1): for j in range(i): print("*", end=" ") print()
#!/usr/bin/env python3 for hour_offset in range(0, 24, 6): train = open('data/train_b{:02}.csv'.format(hour_offset), 'w', newline='') test = open('data/test_b{:02}.csv'.format(hour_offset), 'w', newline='') data = open('data/data.txt') t = int(next(data)) n, m = tuple(map(int, next(data).split()))...
p = [1,2,3,4,5,6,7,8,9] del p[1:3] print(p[:]) p.remove(8) print(p[:]) print(p.pop()) p.clear() print(p[:]) l=[1,3,4,5,6,7] l.remove(3) print(l[:]) l.sort() print(l[:]) l.reverse() print(l[:]) l.clear() print(l[:])
# Copyright 2017 The Bazel Authors. All rights reserved. # # 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 la...
# -*- coding: utf-8 -*- tentativas = [] posição = 1 n = int(input()) linha = input().split() for i in range(len(linha)): tentativas.append(linha[i]) menor = tentativas[0] for i in range(n): if tentativas[i] < menor: menor = tentativas[i] posição = i + 1 print("{}".format(posição))
# -*- coding: utf-8 -*- CSRF_ENABLED = True SECRET_KEY = "208h3oiushefo9823liukhso8dyfhsdklihf" debug = False
def getLate(): v = Late(**{}) return v class Late(): value = 'late'
formatter = "{} {} {} {}" print(formatter.format(1, 2, 3, 4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(True, False, False, True)) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "I had this thing.", "That you could type up right."...
# Copyright 2014 PDFium authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # Original code from V8, original license was: # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style ...
activate_mse = 1 activate_adaptation_imp = 1 activate_adaptation_d1 = 1 weight_d2 = 1.0 weight_mse = 1.0 refinement = 1 n_epochs_refinement = 10 lambda_regul = [0.01] lambda_regul_s = [0.01] threshold_value = [0.95] compute_variance = False random_seed = [1985] if not compute_variance else [1985, 2184, 51, 12, 465] ...
# encoding: utf-8 # module cv2.xphoto # from /home/davtoh/anaconda3/envs/rrtools/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so # by generator 1.144 # no doc # no imports # Variables with simple values BM3D_STEP1 = 1 BM3D_STEP2 = 2 BM3D_STEPALL = 0 HAAR = 0 INPAINT_SHIFTMAP = 0 __loader__ = None ...
# flopy version file automatically created using...pre-commit.py # created on...March 20, 2018 17:03:11 major = 3 minor = 2 micro = 9 build = 60 commit = 2731 __version__ = '{:d}.{:d}.{:d}'.format(major, minor, micro) __build__ = '{:d}.{:d}.{:d}.{:d}'.format(major, minor, micro, build) __git_commit__ = '{:d}'.format(...
#!/usr/bin/env python3 def main(): with open("dnsservers.txt", "r") as dnsfile: for svr in dnsfile: svr = svr.rstrip('\n') # remove newline char if exists # would exists on all but last line # IF the string svr ends with 'org' if svr.endswith('org'): ...
a, b = map(int, input('').split(' ')) n = int(input('')) ans = 0 for i in range(n): shop = [int(i) for i in input('').split(' ') if abs(int(i)) == a or b] if shop.count(a) > shop.count(-a) and shop.count(b) > shop.count(-b): ans += 1 print(ans)
# Break Statement : greetings = ["Hello","World","!!!"] for x in greetings: print(x) if (x == "World"): break #Breaks the loop when condition matches print() for x in range (0,22,2): if (x == 10): continue #Skips the current iteration when condition matches print(x)...
HOST = '127.0.0.1' USERNAME = 'guest' PASSWORD = 'guest' URI = 'amqp://guest:guest@127.0.0.1:5672/%2F' HTTP_URL = 'http://127.0.0.1:15672'
load("@bazel_skylib//lib:paths.bzl", "paths") def _add_data_impl(ctx): (_, extension) = paths.split_extension(ctx.executable.executable.path) executable = ctx.actions.declare_file( ctx.label.name + extension, ) ctx.actions.symlink( output = executable, target_file = ctx.executab...
# -*- coding: utf-8 -*- """ File Name: missingNumber Author : jing Date: 2020/4/13 0~n-1中缺失的数字 https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof/ """ class Solution: def missingNumber(self, nums: List[int]) -> int: if nums is None or len(nums) == 0: re...
""" """ def words_to_snake_case(s): components = s.split(' ') return '_'.join(x.lower() for x in components)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 功能实现:在字典中查找最小值的键。 解读: 使用min()并将key参数设置为dict.get()来查找并返回给定字典中最小值的键。 """ def key_of_min(d): return min(d, key=d.get) # Examples print(key_of_min({'a': 4, 'b': 0, 'c': 13})) # output: # b
#What will this script produce? #A: 3 a = 1 a = 2 a = 3 print(a)
#addintersert3.py def addInterest(balances, rate): for i in range(len(balances)): balances[i] = balances[i] * (1 + rate) def main(): amounts = [1000, 105, 3500, 739] rate = 0.05 addInterest(amounts, rate) print(amounts) main()
# -*- coding: utf-8 -*- ABBREVIATIONS = [ 'dr', 'jr', 'mr', 'mrs', 'ms', 'msgr', 'prof', 'sr', 'st'] SUB_PAIRS = [ ('M.', 'Monsieur') ] ALL_PUNC = u"?!?!.,¡()[]¿…‥،;:—。,、:\n" TONE_MARKS = u"?!?!" PERIOD_COMMA = u".," COLON = u":"
# INTERNAL_ONLY_PROPERTIES defines the properties in the config that, while settable, should # not be documented for external users. These will generally be used for internal test or only # given to customers when they have been briefed on the side effects of using them. INTERNAL_ONLY_PROPERTIES = { "__module__", ...
# example file for submodule imports def divide_me_by_2(x): return x/2
class Solution: def connect(self, root): nodes = [[root], []] x = 0 while (nodes[0] and nodes[0][0]) or (nodes[1] and nodes[1][0]): for i in range(len(nodes[x])): nodes[x][i].next = None if i == len(nodes[x]) - 1 else nodes[x][i+1] nodes[(1 + x) % ...
CELERY_TIMEZONE = 'Europe/Rome' # The backend used to store task results CELERY_RESULT_BACKEND = 'rpc://' # If set to True, result messages will be persistent. This means the messages will not be lost after a broker restart CELERY_RESULT_PERSISTENT = True CELERY_ACCEPT_CONTENT=['json', 'pickle'] CELERY_TASK_SERIALI...
def checkIfMessagerIsBooster(self, user): """ Function would be called by Robot class :param self: instance from Robot :param user: instance from Discord.User :return: True if user is a booster """ for role in user.roles: if role == self.boostedRole: return True retu...
class InputBroker: """Abstract class responsible for providing raw values when considering scores""" def get_input_value(self, consideration, context): raise NotImplementedError()
# colorcodingfor rows(...) def colornumber(color): if color == 'd': return 0 elif color == 'e': return 1 elif color == 'f': return 2 elif color == 'g': return 3 elif color == 'h': return 4 elif color == 'i': return 5 elif color ==...
class Solution: def isIdealPermutation(self, A): """ :type A: List[int] :rtype: bool """ size, m = len(A), 0 for i in range(size - 2): m = max(m, A[i]) if m > A[i + 2]: return False return True
[ { 'date': '2018-01-01', 'description': "New Year's Day", 'locale': 'en-US', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2018-01-15', 'description': 'Birthday of Martin Luther King, Jr.', 'locale': 'en-US', 'notes': '...
# A function to get the desired metrics while working with multiple model training procedures def print_classification_metrics(y_train, train_pred, y_test, test_pred, return_performance=True): dict_performance = {'Training Accuracy: ': accuracy_score(y_train, train_pred), 'Training f1-score:...
#!/usr/bin/env python def part_one(values: list[int]) -> int: count = sum(values[index] < values[index + 1] for index in range(len(values) - 1)) return count def part_two(values: list[int]) -> int: summed_list = list(sum(three) for three in zip(values, values[1:], values[2:])) count = sum(summed_list...
"""Top-level package for Client 1C for Time Sheet.""" __author__ = """Nick K Sabinin""" __email__ = 'sabnk@optictelecom.ru' __version__ = '0.1.0'
# -*- coding: utf-8 -*- { 'name': "programme_fidelite", 'summary': """ fidelite programme """, 'description': """ programme de fidelité """, 'author': "emmanuel.kissi@progistack.com", 'website': "http://www.yourcompany.com", 'category': 'Uncategorized', 'version':...
# Usage: gunicorn ProductCatalog.wsgi --bind 0.0.0.0:$PORT --config deploy/gunicorn.conf.py # Max number of pending connections. backlog = 1024 # Number of workers spawned for request handling. workers = 1 # Standard type of workers. worker_class = 'sync' # Kill worker if it does not notify the master process in this ...
# NOTE: This objects are used directly in the external-notification-data and vulnerability-service # on the frontend, so be careful with changing their existing keys. PRIORITY_LEVELS = { "Unknown": { "title": "Unknown", "value": "Unknown", "index": 5, "level": "info", "color"...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumEvenGrandparent(self, root): """ :type root: TreeNode :rtype: int """ res = [0] ...
class solution: def findNumbers(self, nums=[]): even = 0 for num in nums: numString = str(num) if len(numString) % 2 == 0: even += 1 return even if __name__ == "__main__": sol = solution() _ = [int(n) for n in input().split()] print(sol.fin...
pressure_arr = [80, 90, 100, 150, 120, 110, 160, 110, 100] sum = 0 for pressure in pressure_arr: sum = pressure + sum length = len(pressure_arr) mean = sum / length print("The mean is", mean)
n = int(input()) families = map(int, input().split()) families = sorted(families) for i in range(len(families)): if(i!=len(families)-1): if(families[i]!=families[i - 1] and families[i]!=families[i + 1]): print(families[i]) break else: print(families[i])
class Solution: def expand(self, S: str) -> List[str]: return sorted(self.dfs(S, [''])) def dfs(self, s, prev): if not s: return prev n = len(s) cur = '' found = False result = [] for i in range(n): if s[i].is...
def translate(data, char, replacement): result = data.replace(char, replacement) print(result) return result def includes(data, string): if string in data: return True return False def start(data, string): counter = 0 is_it = False for char in string: if char == data[cou...
L = 25 with open('input') as f: nums = list(map(int, f.read().split())) # Part 1 for i in range(L, len(nums)): pre = nums[i - L:i] n = nums[i] d = {} for p in pre: if p in d and p != d[p]: break d[n - p] = p else: print(n) break # Part 2 i = 0 j = 2...
class UnexpectedMode(ValueError): def __init__(self, mode: str) -> None: super().__init__( f"Unexpected mode - found '{mode}' but must be 'image' or 'mesh'" )
def area(base, altura): return base*altura/2 base = float(input('Medida de un lado')) altura = float(input('Altura relativa a ese lado')) print(f'El area del triángulo es de {area(base, altura)} unidades')
# -*- coding: utf-8 -*- """ Jaccard Index Implementation @author: AniruddhaMaheshDave """ def jaccard_index(str1, str2, n_gram = 2): """ Computes the Jaccard Index between two strings `str1` and `str2`. #TODO : Write details about Jaccard Index """ if str1 == str2: return 1 len1, len2 = len(str1), len(str2...
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project au...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/lzh/racecar_ws/devel/include;/home/lzh/racecar_ws/src/navigation-melodic-devel/dwa_local_planner/include".split(';') if "/home/lzh/racecar_ws/devel/include;/home/lzh/racecar_ws/src/navigation-mel...
nome = input("Digite seu nome ").strip().lower() confirmacao = 'silva' in nome print(f"Seu nome tem silva {confirmacao}")
# Exercício 2.3 nome = input("olá! Informe seu nome:") print(nome) # Exercício 2.4 a = 3 b = 5 print(2*a + 3*b) # Exercício 2.5 a = 3 b = 7 c = 4 print(a+b+c) # Exercício 2.6 salário = 750 aumento = 0.15 sal_real = (salário+(salário*aumento)) print(sal_real)
# ***************************** # Environment specific settings # ***************************** # DO NOT use "DEBUG = True" in production environments DEBUG = True # DO NOT use Unsecure Secrets in production environments # Generate a safe one with: # python -c "import os; print repr(os.urandom(24));" ...
""" Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: "A" Output: 1 Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701 """ class Solutio...
# coding: utf-8 # # Functions (1) - Creating Functions # In this lesson we're going to learn about functions in Python. Functions are an important tool when programming and their use can be very complex. It's not the aim of this course to teach you how to implement functional programming, instead, this lesson will g...
# This module is from mx/DateTime/LazyModule.py and is # distributed under the terms of the eGenix.com Public License Agreement # https://www.egenix.com/products/eGenix.com-Public-License-1.1.0.pdf """ Helper to enable simple lazy module import. 'Lazy' means the actual import is deferred until an attribute ...
stack = [] stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) print('\nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are poped:') print(stack)
#!/usr/bin/env python # -*- coding':' utf-8 -*- # Hiswelókë's Sindarin dictionary # Compiled, edited and annotated by Didier Willis # https://www.jrrvf.com/hisweloke/sindar/online/sindar/dict-en-sd.html dict_words = { 'abandon':'awartha', 'abandonment':'awarth', 'abhor':'fuia', 'abhorrence':'delos', ...
"""Static values for one way import.""" SUPPORTED_FORMATS = (".svg", ".jpeg", ".jpg", ".png", ".tiff", ".tif") HTML_LINK = '<link rel="{rel}" type="{type}" href="{href}" />' ICON_TYPES = ( {"image_fmt": "ico", "rel": None, "dimensions": (64, 64), "prefix": "favicon"}, {"image_fmt": "png", "rel": "icon", "dim...
def findLongestSubSeq(str): n = len(str) dp = [[0 for k in range(n+1)] for l in range(n+1)] for i in range(1, n+1): for j in range(1, n+1): # If characters match and indices are not same if (str[i-1] == str[j-1] and i != j): dp[i][j] = 1 + dp[i-1][j-1] # If characters do not match else:...
""" [8/8/2012] Challenge #86 [easy] (run-length encoding) https://www.reddit.com/r/dailyprogrammer/comments/xxbbo/882012_challenge_86_easy_runlength_encoding/ Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string and compresses them to a list of pairs of...
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden def swap(values, first, second): value1 = values[first] value2 = values[second] values[first] = value2 values[second] = value1 def swap(values, first, second): tmp = values[first] values[first] = values[s...
@singleton class Database: def __init__(self): print('Loading database')
#!/usr/bin/env python3 def get_case_data(): return [int(i) for i in input().split()] # Using recursive implementation def get_gcd(a, b): return get_gcd(b, a % b) if b != 0 else a def print_number_or_ok_if_equals(number, guess): print("OK" if number == guess else number) number_of_cases = int(input()) for case in...
ACCOUNT_TYPES = [ 'Cuenta de ahorro', 'Cuenta vista', 'Cuenta corriente', 'Cuenta rut', ] BANK_NAMES = [ 'BANCO DE CHILE/EDWARDS CITI', 'BANCO ESTADO', 'SCOTIABANK', 'BCI', 'CORPBANCA', 'BICE', 'HSBC', 'SANTANDER', 'ITAU', 'THE BANK OF TOKYO-MITSUBISHI LTD.', ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: res = defaultdict(list) q = ...
# -*- coding: utf-8 -*- def main(): s = input() mod = '' for i in range(3): if s[i] == '1': mod += '9' elif s[i] == '9': mod += '1' print(mod) if __name__ == '__main__': main()
# Añadimos el template / clase generica class SportInfo: """Mostrar información de un deporte""" def __init__(self, name): print("Estamos creando un objeto") self.name = name def __del__(self): print("Estamos destruyendo un objeto: {}" .format(self.__class__.__name__)...
# HyperLogLog - вероятностная структура данных для подсчёта количества уникальных элементов class HyperLogLog: def __init__(self, size): # size=32 self.buckets = [0] * size def fill_buckets(self, item): bin_hash = self.hash_value(item, length=32) buckets_index = int(str(bin_hash[:5]),...
class Node: def __init__(self,data): self.data=data self.next=None arr=[5,8,20] brr=[4,11,15] #inserting elements in first list list1=Node(arr[0]) root1=list1 for i in arr[1::]: temp=Node(i) list1.next=temp list1=list1.next #inserting elements in second list lis...
# Write your solution for 1.4 here! def is_prime(x): if x > 1: for i in range(2,x): if (x % i) == 0: print(x,"is not a prime number") print(i,"times",x//i,"is",x) else: print(x,"is not a prime number") is_prime(5)
class PluginMount(type): """Generic plugin mount point (= entry point) for pydifact plugins. .. note:: Plugins that have an **__omitted__** attriute are not added to the list! """ # thanks to Marty Alchin! def __init__(cls, name, bases, attrs): if not hasattr(cls, "plugins"): ...
if __name__ == "__main__": print((lambda x,r : [r:=r+1 for i in x.split('\n\n') if all(map(lambda x : x in i,['byr','iyr','eyr','hgt','hcl','ecl','pid']))][-1])(open("i").read(),0)) def main_debug(inp): # 204 inp = inp.split('\n\n') rep = 0 for i in inp: if all(map(lambda x : x in i,['byr','iyr...
def flatten(iterable, result=None): if result == None: result = [] for it in iterable: if type(it) in (list, set, tuple): flatten(it, result) else: result.append(it) return [i for i in result if i is not None]
def palindromo(palavra: str) -> bool: if len(palavra) <= 1: return True primeira_letra = palavra[0] ultima_letra = palavra[-1] if primeira_letra != ultima_letra: return False return palindromo(palavra[1:-1]) nome_do_arquivo = input('Digite o nome do entrada de entrada: ') with open...
def main(): isNumber = False while not isNumber: try: size = int(input('Height: ')) if size > 0 and size <= 8: isNumber = True break except ValueError: isNumber = False build(size, size) def build(size, counter): sp...
#URLs ROOTURL = 'https://www.reuters.com/companies/' FXRATESURL = 'https://www.reuters.com/markets/currencies' #ADDURLs INCSTAT_ANN_URL = '/financials/income-statement-annual/' INCSTAT_QRT_URL = '/financials/income-statement-quarterly/' BS_ANN_URL = '/financials/balance-sheet-annual/' BS_QRT_URL = '/financials/balance...
DEFAULT_PORT = 9000 DEFAULT_SECURE_PORT = 9440 DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES = 50264 DBMS_MIN_REVISION_WITH_TOTAL_ROWS_IN_PROGRESS = 51554 DBMS_MIN_REVISION_WITH_BLOCK_INFO = 51903 # Legacy above. DBMS_MIN_REVISION_WITH_CLIENT_INFO = 54032 DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE = 54058 DBMS_MIN_REVISION_WIT...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ res=0 prev=None for x in prices: res += x-prev if prev!=None and prev<x else 0 prev = x return res
input_file = open("input.txt", "r") entriesArray = input_file.read().split("\n") depth_measure_increase = 0 for i in range(3, len(entriesArray), 1): first_window = int(entriesArray[i-1]) + int(entriesArray[i-2]) + int(entriesArray[i-3]) second_window = int(entriesArray[i]) + int(entriesArray[i-1]) + int(entrie...
# ©2018 The Arizona Board of Regents for and on behalf of Arizona State University and the Laboratory for Energy And Power Solutions, All Rights Reserved. # # Universal Power System Controller # USAID Middle East Water Security Initiative # # Developed by: Nathan Webster # Primary Investigator: Nathan Johnson # # Versi...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ l , r = 0 , len(s)-1 while l<r: s[l] , s[r] = s[r] , s[l] l +=1 r -=1 return s