content
stringlengths
7
1.05M
def merge_sort(arr): if len(arr) <= 1: return mid = len(arr)//2 left = arr[:mid] right = arr[mid:] merge_sort(left) merge_sort(right) merge_two_sorted_lists(left, right, arr) def merge_two_sorted_lists(a, b, arr): len_a = len(a) len_b = len(b) i = j = k = 0 w...
class BotServiceInterface: async def start(self) -> None: raise NotImplementedError async def stop(self) -> None: raise NotImplementedError
T = int(input()) for _ in range(T): N, K, x, y = map(int, input().split()) if(x == y): print(N, N) else: if(x<y): final_cordinates = [[x+N-y, N], [N, N-y+x], [y-x, 0], [0, y-x]] else: final_cordinates = [[N, y+N-x], [y+N-x, N], [0, x-y], [x-y, 0]] resu...
def main(sam1, sam2): # FilterSam1ByReadNamesFromSam2 outsamfile = '.'.join(sam1.split('.')[:-1] + ['RNAReadsConnectedDNAOver300winExtIES', 'sam']) readnames = [] with open(sam2, 'r') as FILE: for line in FILE: if line[0] != '@': readnames.append(line.strip()...
lyrNames = ['admin_0.geom', 'admin_1.geom', 'admin_2.geom', 'admin_3.geom', 'postal_0.geom', 'postal_1.geom', 'postal_2.geom', 'postal_3.geom', 'postal_4.geom', 'postal_5.geom'] root = QgsProject.instance().layerTreeRoot() model = iface.layerTreeView().layerTreeModel() for lyrName in lyrNames: lyr = QgsProject...
class Solution: def peakIndexInMountainArray(self, A): length = len(A) left = 0 right = length - 1 mid = int((right - left + 1) / 2) while not (A[mid - 1] < A[mid] and A[mid] > A[mid + 1]): print(mid, A[mid]) if A[mid] > A[mid - 1]: lef...
dataset = dict( user_file='./datasets/raw/traindata/user_features_data.csv', video_file='./datasets/raw/traindata/video_features_data.csv', # training_behavior_file='./datasets/raw/traindata/history_behavior_light.csv', training_behavior_file='./datasets/raw/traindata/history_behavior_data.csv', tes...
#!/usr/bin/python3 file_to_write = open('converted_csv.txt', 'w+') file_to_convert = open('test-csv.csv', 'r') data = '' with file_to_convert as myfile: data = myfile.read() data = data.replace("\n", ",") data1 = data[0:239].lower() data2 = data[240:479].lower() data3 = data[480:719].lower() data4 = data[720:-...
data = [word.lower() for word in input().split()] odd_dict = {} for word in data: if word in odd_dict: odd_dict[word] += 1 else: odd_dict[word] = 1 for word, value in odd_dict.items(): if odd_dict[word] % 2 != 0: print(word, end=" ")
def readLine(line): return [ int(c) for c in line.split(' ') ] def jump(x, y): # exactly one step of length 1 => exactly one of the numbers even if x % 2 == y % 2 and (x != 0 or y != 0): return 'IMPOSSIBLE' if x == 0: if y == 1: return 'N' if y == -1: ...
usuario = db.define_table("usuario", Field("nome", notnull=True, unique=True), Field("pin"), Field("email"), #auth.signature format="%(nome)s") meetme = db.define_table("meetme", Field("confno", 'id'), Field("starttime", "datetime"), Field("endtime", "datetime"), ...
N, M = map(int,input().split()) for i in range(1,N,2): print('-' * int((M-(3*i))/2) + i*'.|.' + '-' * int((M-(3*i))/2)) print('-' * int((M-7)/2) + "WELCOME" + '-' * int((M-7)/2)) for i in range(N-2,-1,-2): print('-' * int((M - (3 * i)) / 2) + i * '.|.' + '-' * int((M - (3 * i)) / 2))
ambiguous_codes = { "R": {"A", "G"}, "Y": {"C", "T"}, "S": {"G", "C"}, "W": {"A", "T"}, "K": {"G", "T"}, "M": {"A", "C"}, "B": {"C", "G", "T"}, "D": {"A", "G", "T"}, "H": {"A", "C", "T"}, "V": {"A", "C", "G"}, "N": {"A", "C", "G", "T"}, } rev_ambiguous_codes = {"".join(sorte...
"""Faça um Programa para uma loja de tintas. O programa deverá pedir o metros em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00. Infor...
#Escreva um script python que calcule e apresente na tela a média aritmética dos elementos da seguinte matriz: #A = [[1,6,-9],[33,-6,88],[0,23,98]] matriz = [[1,6,-9],[33,-6,88],[0,23,98]] count = 0 soma = 0 for l in range(3): for c in range(3): count += 1 soma += matriz[l][c] media = soma / coun...
MOD = 1000000007 n = int(input()) k = 1 L = [] for i in range(2,n+1): k *= i k %= MOD L.append(k) k2 = 1 for i in range(n-1): k2 *= 2 k2%= MOD print((k - k2 + MOD*MOD)%MOD)
def outer(mynum): def inner(a1): return mynum ** a1 return inner obj1 = outer(6) obj2 = outer(5) print(obj1(2)) print(obj2(3))
salario = float(input("Qual é o salário do funcionário? R$ ")) if salario <= 1250: novo = salario + (salario * 15 / 100) else: novo = salario + (salario * 10 / 100) print("O funcionário que ganhava R${:.2f} passará a ganhar R${:.2f} agora".format(salario, novo))
#!/usr/bin/env python3 def main(): p1 = 0 p2 = 0 try: with open('../input.txt', 'r') as fin: d = fin.read().splitlines() passes = [] for line in d: seat_id = get_seat_id(line) passes.append(seat_id) p1 = seat_id if ...
class Stack(object): def __init__(self, checker=None): self.__stack = [] self.__checker = checker @property def depth(self): return len(self.__stack) @property def empty(self): return self.depth == 0 @property def top(self): return self.__stack[0] ...
# coding:utf-8 try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") print("Give me two numbers, I'll divide them.") print("Print q to exit.") while True: number1 = input("First number: ") if number1 == 'q': break number2 = input("Second number: ") if number2 == ...
#Program to find area and perimeter of a circle radius=int(input("Enter the radius of a circle ")) area=3.14*radius**2 perimeter=2*3.14*radius print("The area of a circle with radius",radius,"is ",area) print("and the perimeter is",perimeter)
def test_activate(vf): vf.run("vf new test") vf.run("vf activate test") out, _ = vf.run("which python") assert out == "{homedir}/.virtualenvs/test/bin/python\n".format(homedir=vf.homedir).encode('utf8')
# Domotique @Lecanois def allume(phrase): talk(phrase) Parse("http://192.168.1.27/lumieres.php") def eteins(phrase): talk(phrase) Parse("http://192.168.1.27/lumiereoffs.php") #RELAY CONTROL TO SHUTDOWN SERVO sleep(0.1) left.pinMode(53, Arduino.OUTPUT) left.pinMode(51, Arduino.OUTPUT) right.pinMode(53, Arduino...
def func2(): pass def func1(n): num = 0 while num < n: yield func2 num += 1 for i in func1(100): i()
input() s = set(map(int,input().split())) for it in range(int(input())): line = input().split() if line[0]=="pop": s.pop() elif line[0]=="remove": s.remove(int(line[1])) else: s.discard(int(line[1])) print(sum(s))
#take 1st minm element put it on the 1st place. #take 2nd minm element put it on the 2nd place. #take nth minm element put it on the nth place. def get_min(L): min=L[0] i=0 idx=i while(i<len(L)): if L[i]<min: min=L[i] idx=i i=i+1 return min,idx #L=[12,13,54,4,4,7] min,idx=get_min(L) def s...
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SYSTRAN Software, Inc. 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/licen...
"""Top-level package for Speech emotion Recognition.""" __author__ = """Hrithik Chourasia""" __email__ = 'hrithik8wel@gmail.com' __version__ = '0.1.0'
''' Common implementation of a Linked List. ''' class Node(): def __init__(self,value,next_pointer): self.value = value self.next = next_pointer class LinkedList(): def __init__(self, head): self.next = None #pointer to the next node self.head_node = Node(hea...
metros = int(input('Digite o valor em metros: ')) print(f'Centímetros: {metros * 100}') print(f'Milímetros: {metros * 1000}')
d_pu = { "Épée en mousse": 5, "Masque Dark Vador": 30, "Hand spinner 3d": 10, "Console Minux": 150, "Lego Footix": 15 } d_stock = { "Masque Dark Vador": 4, "Hand spinner 3d": 10, "Console Minux": 2, "Lego Footix": 5, "Épée en mousse": 10 } def verification(d1, d2): ...
N = int(input()) for k in range(N): S = input() print("Ciencia da Computacao")
#!/usr/bin/env python3 """Make abba. Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi". make_abba('Hi', 'Bye') → 'HiByeByeHi' make_abba('Yo', 'Alice') → 'YoAliceAliceYo' make_abba('What', 'Up') → 'WhatUpUpWhat' source: https://codingba...
largura = float(input('Digite a largura da parede: ')) altura = float(input('Digite a altura da parede: ')) area = largura * altura tinta = area / 2 print('Considerando a largura da parede com {} metros e a altura com {} metros:\nTemos uma area de {} m2 e serão necessario {} litros de tinta para pintá=la'.format(largur...
class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 negative, result = n < 0, 1 n = abs(n) while n > 0: base, p = x, 2 while p < n: base *= base p *= 2 result *= base n -= p // 2 return 1 / result if negative else res...
def install(job): cuisine = job.service.executor.cuisine name = 'mongod_%s' % job.service.name cuisine.apps.mongodb.install(start=True, name=name) def start(job): cuisine = job.service.executor.cuisine name = 'mongod_%s' % job.service.name cuisine.apps.mongodb.start(name) def stop(job): ...
def encode_string(clear_text): cypher = "" for char in clear_text: cypher = cypher + character_encode(char) return cypher def char_to_num(char): return ord(char) def char_to_encoded(char): encoded = char_to_num(char) + 13 if encoded > 122: end_of_alpha = ord('z') be...
# https://www.codewars.com/kata/54ba84be607a92aa900000f1/train/python # An isogram is a word that has no repeating letters, consecutive or # non-consecutive. Implement a function that determines whether a # string that contains only letters is an isogram. Assume the empty # string is an isogram. Ignore letter case. ...
number1 = 7 number2 = 2 print(number1) print(number2) # ARITHMATIC OPERATOR # # + - * / % sumRes = number1 + number2 subRes = number1 - number2 multRes = number1 * number2 diviRes = number1 / number2 restRes = number1 % number2 print(sumRes) print(subRes) print(multRes) print(diviRes) print(restRes) newVa...
""" Class file for the ArmedSwitch class """ class ArmedSwitch(object): """ ArmedSwitch is a boolean switch that must be explicitly re-armed after each time it switches, or else it keeps the same state. """ # __init__: ArmedSwitch initializer def __init__(self, switched=False, armed=True): ...
second=50 def func01(first01): first=10 func02(first01) return def func02(first02): first=20 return if __name__ == '__main__' : #first=30 #func01(first) a=30 b=4.2 c='G' pass
lights = [True for _ in range(5000000)] Q = int(input()) queries = [] for _ in range(Q): queries.append(input().split()) for query in queries: if(query[0]=='1'): lights[int(query[1])] = False elif(query[0]=='2'): pos = int(query[1]) dist = 0 for dist in ran...
# Elevated permissions permitted = [553478921870508061] staff_role = 583646707938623489 # General max_msg_size = 2000 no_react = "❎" yes_react = "✅" # Bot detection massjoin_window = 30 massjoin_amount = 5 massjoin_notif_timeout = 900 massjoin_wizard_timeout = 300 massjoin_default_pfp = True massjoin_min_acc_age = Tr...
def solve(test, printing = False): decrypted = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '?', '(', ')', '!'] ...
# Exercício 036: """Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário, ou então o empréstimo será negado...
""" Provide a djangoapp for XBlock development """ __version__ = '0.5.1'
class Nodo(): def __init__(varClase, nombre, movil, correo): varClase.nombre = nombre varClase.movil = movil varClase.correo = correo varClase.siguiente = None def actualizar(varClase, nombre, movil, correo): varClase.nombre = nombre varClase.movil = m...
class Song: def __init__(self, name): self.name = name self.next = None def next_song(self, song): self.next = song def is_repeating_playlist(self): """ :returns: (bool) True if the playlist is repeating, False if not. """ visited = set() ...
class StorageProcessorCacheDirtySize(object): def read_get(self, name, idx_name, unity_client): return unity_client.get_sp_cache_dirty_size(idx_name) class StorageProcessorCacheDirtySizeColumn(object): def get_idx(self, name, idx, unity_client): return unity_client.get_sps()
# 025 # Ask the user to enter their first name. If the length of their first # name is under five characters, ask them to enter their surname and # join them together (without a space) and display the name in upper # case. If the length of the first name is five or more characters, # display their first name in lower c...
# To actually have your app use this file, you need to RENAME the file to db_credentials.py # You will find details about your CS340 database credentials on Canvas. # the following will be used by the db_connector.py and # in turn by all the Python code in this codebase to interact with the database host =...
{ "12345":{ "condition":{ "Material":["50007747","50335560","425452"], "Filial":["BR19","BR23","BR40"] }, "implication": { "IVAMIRO": ["TESTE"] }, "date": "2019-01-01", "user": "99813554", "description": "this rules was created in order to do somethi...
{ "targets": [ { "target_name": "shm", "sources": [ "shm.cpp" ], "libraries" : [ "-lrt" ] } ] }
def two_list_dictionary(keys, values): """Given keys and values, make dictionary of those. >>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7]) {'x': 9, 'y': 8, 'z': 7} If there are fewer values than keys, remaining keys should have value of None: >>> two_list_dictionary(['a', 'b',...
'''Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário 2 para octal 3 para hexadecimal''' n = int(input('Digite um número inteiro para ser convertido: ')) r = int(input('Escolha uma das seguintes opções de conversão:\n1 - para' ...
if __name__=='__main__': while True: try: s=input().split(' ') a=[] for itm in s: a.append(itm[::-1]) print(*a) except: break
# Released under CC0: # Summary: https://creativecommons.org/publicdomain/zero/1.0/ # Legal Code: https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt win_w, win_h = 1000, 600 rec_x = win_w * 0.9 rec_y = win_h / 2 rec_w = win_w * 0.01 rec_h = win_h * 0.2 r = 10 pos = PVector(win_w * 0.1, win_h / 2) vel = ...
# Service Lane # Calculate the maximum width of the vehicle that can pass through a service lane. # # https://www.hackerrank.com/challenges/service-lane/problem # def serviceLane(width, a, b): # euh? comment dire... print(min(width[a:b + 1])) if __name__ == "__main__": n, t = map(int, input().split()) ...
class Solution: def maxProfit(self, prices): # greedy profit = 0 for i in range(len(prices)-1): tmp = prices[i+1] - prices[i] if tmp > 0: profit += tmp return profit
"""Bot exceptions module.""" class CameraBotError(Exception): pass class ConfigError(Exception): pass class UserAuthError(Exception): pass class HikvisionCamError(Exception): pass class DirectoryWatcherError(Exception): pass class APIError(Exception): pass class APIRequestError(API...
def sum_zero(n): zero_sum_array = [] counter = 1 if n % 2 != 0: zero_sum_array.append(0) n -= 1 while n: zero_sum_array.append(counter) zero_sum_array.append(-counter) counter += 1 n -= 2 return zero_sum_array
""" Desc: Skeleton app to access API's with JWT tokens Author: [marirs,] version: 1.0 """
# Insertion sort def insertion_sort(arr): ''' Sort list using insertion sort. Return number of comparisons made. ''' comparisons = 0 for i in range(1, len(arr)): key = arr[i] j = i-1 while j >= 0 and key < arr[j]: comparisons += 2 arr[j+1] = arr[j...
seat = [] min = 0 max = 5 print(min <= len(seat) < max) # True seat.append('person') seat.append('person') seat.append('person') seat.append('person') seat.append('person') print(min <= len(seat) < max) # False seat.pop() print(min <= len(seat) < max) # True
# -*- coding: utf-8 -*- """ @author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/ """ #This is a summary statistic + database query tool #Define function def SGapDown(s): #Percentage measure of how current high is lower than previous low s['GapDown'] = (s['Low'].shift(1) - s['High'])...
""" 14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". All given inputs are in lowercase letters a-z. """ class Solution: # Runtime: 32 ms, faster than 92.33% of Python3 online submissions for Lo...
# Taken from https://github.com/first20hours/google-10000-english/blob/master/google-10000-english-no-swears.txt # then extracted only words with 5 letters while keeping the order. # fives_popular = [] fives = [ "aahed", "aalii", "aargh", "aaron", "abaca", "abaci", "aback", "abada", ...
# Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks. # Lets say im inserting 1 2 3 to the queue when i remove i have to do 1 2 3 # If I add 1 then all is normal then 2 in a stack would look like 1 2 and pop would go like 2 1 # but if i have two stacks and actively swap them i would h...
############################################################################### # Copyright (c) 2017-2020 Koren Lev (Cisco Systems), # # Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others # # # ...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the ...
#!/usr/bin/python ransac_iters = [1000, 5000] ncc_threshold_s = [0.6, 0.7, 0.8] ncc_threshold_m = [0.6, 0.7, 0.8] #search_wsz = [180, 200, 230] harris_block_sz = [3, 5] harris_k = [0.04, 0.06] harris_thr = [0.00001, 0.000001, 0.0000001] fp_runscript = open("/mnt/ssd/kivan/cv-stereo/scripts/eval_batch/run_batch_vali...
##Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range ##Last Updated : 19 Oct, 2020 ##Given two integers X and Y, the task is to perform the following operations: ## ##Find all prime numbers in the range [X, Y]. ##Generate all numbers possible by combining every pair o...
print("Hello world!") print(1 + 2) print(7 * 6) print() print("The end","Or is it?","Keep watching to learn more about Python",3)
p = int(input()) for i in range(0, p): k, n = map(int, input().split()) days = 0 days += n for j in range(1, n+1): days += j print(k, days)
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 class VDKAuthException(Exception): """ The VDKAuthException is custom exception type following the coding standard for error handling: see the project contributing documentation """ def __init__(self, what, why, consequence, coun...
n,m = map(int,input().split()) price_number = [0 for _ in range(n)] for i in range(n): price_number[i] = list(map(int,input().split())) price_number.sort() price = 0 index = 0 while m > 0: if m >= price_number[index][1]: price += price_number[index][0]*price_number[index][1] m -= price_number...
data = ( 'Xu ', # 0x00 'Ji ', # 0x01 'Mu ', # 0x02 'Chen ', # 0x03 'Xiao ', # 0x04 'Zha ', # 0x05 'Ting ', # 0x06 'Zhen ', # 0x07 'Pei ', # 0x08 'Mei ', # 0x09 'Ling ', # 0x0a 'Qi ', # 0x0b 'Chou ', # 0x0c 'Huo ', # 0x0d 'Sha ', # 0x0e 'Fei ', # 0x0f 'Wen...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 14 21:45:36 2018 @author: owner """ def isPalindrome(x): y = x new = 0 if x.bit_length() > 31 | x < 0: return False while y != 0: remainder = y % 10 new = new * 10 + remainder y = int(y/10) return...
n1 = int(input('Informe um número: ')) n2 = int(input('Informe outro número: ')) s = n1 + n2 # print(s) A soma pode ser demonstrada desse modo ou #print('A soma entre', n1, 'e', n2, 'é igual a', s,'!') # ou da forma mais atual que é utilizando o .format print('O valor da soma de {} e {} é igual a {}!'.format(n1, n2, s...
''' Author : Arnob Mahmud Mail : arnob.tech.me @ gmail.com ''' # 1 + 2 + 3 + ...................... + n num = int(input("Enter the last number : ")) sum = 0 for x in range( 1, num + 1, 1): sum = sum + x print("Sum is :", sum) # 2 + 4 + 6 + ..................... + n num1 = int(input("Enter last value :")...
# Nice Detective! # Don't defect first, but try to figure out oppenent if they have defected def strategy(history, memory): """ :history: 2d numpy array of our and opponent past moves :memory: dict """ num_rounds = history.shape[1] max_defection_threshold = .5 if num_rounds == 0: ...
sq = [i**2 for i in range(0, 11)] # print (sq) pari = [i for i in sq if i%2 == 0] print (pari)
class Process: def __init__(self,name,arrival,burst): self.name = name self.arrival_time = arrival self.burst_time = burst def set_arrival_time(self,time): self.arrival_time = time def get_arrival_time(self): return self.arrival_time def get_burst_time(self): return self.burst_time def set_burst_time(s...
# Exercise 3: Rewrite the guardian code in the above example without two if statements. Instead, use a compound logical expression using the or logical operator with a single if statement. fhand = open('mbox-short-edited.txt') count = 0 for line in fhand: words = line.split() #print('Debug:', words) if len(words) ...
COLUMNS = [ 'TIPO_REGISTRO', 'NRO_FILIACAO_MATRIZ_OU_GRUPO_COMERCIAL', 'QTDE_RESUMOS_VENDAS', 'QTDE_COMPROVANTES_VENDAS', 'TOTAL_BRUTO', 'TOTAL_DESCONTO', 'TOTAL_LIQUIDO' 'VL_BRUTO_PREDATADO', 'DESCONTO_PREDATADO', 'LIQUIDO_PREDATADO', 'TOTAL_REGISTROS_ARQUIVO' ]
mystr = "abcdcba" start = 0 last = len(mystr)-1 flag = False while(start <= last): if(mystr[start] != mystr[last]): flag = True break start = start + 1 last = last - 1 if(flag == True): print("Not a palindrome.") if(flag == False): print("Palindrome.")
# 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 ( a , b ) : m = len ( a ) n = len ( b ) lookup = [ [ 0 ] * ( n + 1 ) for i in range ( m + 1 ) ] for i...
#conversão #conversões ara string bool_string = str(True) print(bool_string) bool_string2 = str(False) print(bool_string2) int_string = str(5) print(int_string) float_string = str(3.14159) #conversões para int string_int = int("2019") print(string_int) bool_int = int(True) print(bool_int) bool_int2 = int(False) prin...
valores = [] while True: n = int(input('Digite um valor: ')) if n not in valores: valores.append(n) print('Valor adicionado com sucesso...') else: print('Valor duplicado! Não vou adicionar...') sair = ' ' while sair not in 'SN': sair = input('Quer continuar? [S/N] ')....
n=int(input()) ans=0 for i in range(1,n+1): ans+=2**i print(ans)
#!python # TBD: children() or children_of() ? # TBD: provide map/filter/fold functions """ type Label = String data JSP = Lit Label | Seq Label [JSP] | Alt Label [JSP] | Rep Label JSP Each node has a uid. * retains identity even if labels change * lists of tuples of nodeid perm...
def solve(n): s1 = n * (n + 1) * (2 * n + 1) // 6 s2 = (n * (n + 1) // 2) ** 2 return s2 - s1 # n = 10 n = 100 print(solve(n))
'''Paths and filenames used by `smartmove` modules. These are not to be changed''' paths = { # Contains datalogger data for each experiment to be analyzed 'tag': 'data_tag', # Contains `.csv` files for field and isotope experiments 'csv': 'data_csv', # Contains data from CTD measurements 'ctd':...
#World size determines how big the world map is. world_size = { "x" : 5, "y" : 5 } currency = "Gold" MAX_MONSTERS = 10000
# CTCI 1.2: Check permutations # Given two strings, write a method to decide if one is a permutation of the other. def isPermutation(s1:str, s2:str)-> bool: l1 = len(s1) l2 = len(s2) if l1 != l2: return False dict = {} # O(n) for c in s1: if c in dict: dict[c] += 1 ...
# Question Link : https://app.codesignal.com/challenge/LPAySw9MQXCi7934W # Level : Hard for beginners # Solution right below :- def minDistTriplet(a, b, c): minDist = 2**31 x,y,z=a.pop(),b.pop(),c.pop() while True: # 'x' should be max(x,y,z) always # 'a' should always points to l...
# string.py sStr1 = 'strchr' sStr2 = 'r' nPos = sStr1.index(sStr2) print(nPos) # 输出字符第一次出现的序号
a = [] for i in range(9): a.append(int(input())) print(max(a)) print(a.index(max(a))+1)
# Code generation format strings for UFC (Unified Form-assembly Code) v. 2.0.5. # This code is released into the public domain. # # The FEniCS Project (http://www.fenicsproject.org/) 2006-2011. finite_element_combined = """\ /// This class defines the interface for a finite element. class %(classname)s: public ufc::f...