content
stringlengths
7
1.05M
#!/usr/bin/env python def bubble_search_func(data_list): cnt_num_all = len(data_list) for i in range(cnt_num_all-1): for j in range(1,cnt_num_all-i): if(data_list[j-1]>data_list[j]): data_list[j-1],data_list[j]=data_list[j],data_list[j-1] data_list = [54, 25, 93, 17, 77...
entries = [ { 'env-title': 'atari-enduro', 'score': 207.47, }, { 'env-title': 'atari-space-invaders', 'score': 459.89, }, { 'env-title': 'atari-qbert', 'score': 7184.73, }, { 'env-title': 'atari-seaquest', 'score': 1383.38, ...
class Solution: def diStringMatch(self, S): low,high=0,len(S) ans=[] for i in S: if i=="I": ans.append(low) low+=1 else: ans.append(high) high-=1 return ans +[low]
# 二叉树中序遍历的 生成器写法 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def mid_order(root): if not root: return yield from mid_order(root.left) yield root.val yield from mid_order(root.right)
def factorielle_rec(n: int) -> int: """ Description: Factorielle méthode récursive Paramètres: n: {int} -- Nombre à factorielle Retourne: {int} -- Factorielle de n Exemple: >>> factorielle_rec(100) 9.332622e+157 Pour l'écriture scientif...
def main() -> None: s = input() print(s * (6 // len(s))) if __name__ == "__main__": main()
''' Вводится последовательность из N чисел. Найти произведение и количество положительных среди них чисел ''' proizvedenie = 1 a = input().split(" ") for i in range(0, len(a)): proizvedenie *= int(a[i]) print("Произведение " + str(proizvedenie)) print("Кол-во чисел " + str(len(a)))
# 执行用时 : 348 ms # 内存消耗 : 13 MB # 方案:哈希表 class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # 创建哈希表{value:idx} record = {} # 遍数组 for idx, value in enumerate(nums): ...
"""Voce deve criar uma classe carro que vai assumir dois atributos compostos por duas classes: 1) Motor 2) Direcao O motor terá a responsabilidade de controlar a velocidade. Ele Oferece os seguintes atributos: 1) Atribuo de dado velocidade 2) Método acelerar, que deverá incrementar 1 unidade 3) Médoto freardecrement...
def get_next_target(page): start_link = page.find('<a href=') if start_link == -1: return None,0 else: start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = page[start_quote + 1:end_quote] return url, end_quote
# # @lc app=leetcode id=107 lang=python3 # # [107] Binary Tree Level Order Traversal II # # https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ # # algorithms # Easy (48.66%) # Likes: 1105 # Dislikes: 201 # Total Accepted: 289.3K # Total Submissions: 572.4K # Testcase Example: '[3,9,2...
def test_socfaker_application_status(socfaker_fixture): assert socfaker_fixture.application.status in ['Active', 'Inactive', 'Legacy'] def test_socfaker_application_account_status(socfaker_fixture): assert socfaker_fixture.application.account_status in ['Enabled', 'Disabled'] def test_socfaker_name(socfaker_f...
_base_ = [ '../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/bdd100k_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # model model = dict( bbox_head=dict( num_c...
""" You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array.   Example 1: Input: nums = [1,2,3,4], k = 5 Output: 2 Explanation: Starting with ...
# 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 buildTree(self, inorder, postorder): """ :type preorder: List[int] :type inorder: List[int] :rt...
class InterfaceWriter(object): def __init__(self, output_path): self._output_path_template = output_path + '/_{key}_{subsystem}.i' self._fp = { 'pre': {}, 'post': {}, } def _write(self, key, subsystem, text): subsystem = subsystem.lower() fp = se...
# Format of training prompt defaultPrompt = """I am a Cardiologist. My patient asked me what this means: Input: Normal left ventricular size and systolic function. EF > 55 %. Normal right ventricular size and systolic function. Normal valve structure and function Output: Normal pumping function of the left and right ...
abilities = {1: 'Stench', 2: 'Drizzle', 3: 'Speed Boost', 4: 'Battle Armor', 5: 'Sturdy', 6: 'Damp', 7: 'Limber', 8: 'Sand Veil', 9: 'Static', 10: 'Volt Absorb', 11: 'Water Absorb', 12: 'Oblivious', 13: 'Cloud Nine', 14: 'Compound Eyes', 15: 'Insomnia', 16: 'Color Change', 17: 'Immunity', 18: ...
STRICTDOC_GRAMMAR = r""" Document[noskipws]: '[DOCUMENT]' '\n' // NAME: is deprecated. Both documents and sections now have TITLE:. (('NAME: ' name = /.*$/ '\n') | ('TITLE: ' title = /.*$/ '\n')?) (config = DocumentConfig)? ('\n' grammar = DocumentGrammar)? free_texts *= SpaceThenFreeText section_contents...
li=["a","b","d"] print(li) str="".join(li)#adding the lists value together print(str) str=" ".join(li)#adding the lists value together along with a space print(str) str=",".join(li)#adding the lists value together along with a comma print(str) str="&".join(li)#adding the lists value together along with a & print(st...
def limpar(*args): telaPrincipal = args[0] cursor = args[1] banco10 = args[2] sql_limpa_tableWidget = args[3] telaPrincipal.valorTotal.setText("Valor Total:") telaPrincipal.tableWidget_cadastro.clear() telaPrincipal.desconto.clear() telaPrincipal.acrescimo.clear() sql_limpa_tableW...
consonents = ['sch', 'squ', 'thr', 'qu', 'th', 'sc', 'sh', 'ch', 'st', 'rh'] consonents.extend('bcdfghjklmnpqrstvwxyz') def prefix(word): if word[:2] not in ['xr', 'yt']: for x in consonents: if word.startswith(x): return (x, word[len(x):]) return ('', word) d...
[ [float("NaN"), float("NaN"), 73.55631426, 76.45173763], [float("NaN"), float("NaN"), 71.11031587, 73.6557548], [float("NaN"), float("NaN"), 11.32891221, 9.80444014], [float("NaN"), float("NaN"), 10.27812002, 8.15602626], [float("NaN"), float("NaN"), 21.60703222, 17.9604664], [float("NaN"), flo...
numbers = [float(num) for num in input().split()] nums_dict = {} for el in numbers: if el not in nums_dict: nums_dict[el] = 0 nums_dict[el] += 1 [print(f"{el:.1f} - {occurence} times") for el, occurence in nums_dict.items()]
modules_rules = { "graphlib": (None, (3, 9)), "test.support.socket_helper": (None, (3, 9)), "zoneinfo": (None, (3, 9)), } classes_rules = { "asyncio.BufferedProtocol": (None, (3, 7)), "asyncio.PidfdChildWatcher": (None, (3, 9)), "importlib.abc.Traversable": (None, (3, 9)), "importlib.abc.Tr...
def bolha_curta(self, lista): fim = len(lista) for i in range(fim-1, 0, -1): trocou = False for j in range(i): if lista[j] > lista[j+1]: lista[j], lista[j+1] = lista[j+1], lista[j] trocou = True if trocou== Fal...
a = float(input('digite um numero:')) b = float(input('digite um numero:')) c = float(input('digite um numero:')) if a > b: if a > c: ma = a if b > c: mi = c if c > b: mi = b if b > a: if b > c: ma = b if a > c: mi = c if c > ...
def run(): countries = { 'mexico': 122, 'colombia': 49, 'argentina': 43, 'chile': 18, 'peru': 31 } while True: try: country = input( '¿De que país quieres saber la población?: ').lower() print( f'La p...
""" Common constants for Pipeline. """ AD_FIELD_NAME = 'asof_date' ANNOUNCEMENT_FIELD_NAME = 'announcement_date' CASH_FIELD_NAME = 'cash' CASH_AMOUNT_FIELD_NAME = 'cash_amount' BUYBACK_ANNOUNCEMENT_FIELD_NAME = 'buyback_date' DAYS_SINCE_PREV = 'days_since_prev' DAYS_SINCE_PREV_DIVIDEND_ANNOUNCEMENT = 'days_since_prev_d...
# Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. # Return the n copies of the whole string if the length is less than 2 s = input("Enter a string: ") def copies(string, number): copy = "" for i in range(number): copy += string[0] + strin...
#!/usr/bin/env python3 #https://codeforces.com/problemset/problem/1284/B #记录每个序列是否有上升,如果没有min.max是多少.. #n=1e5,还得避免O(N**2).. #上升情况分解 #情况1: sx+sy中sx或sy本身是上升的 #情况2: sx,sy都不上升,判断四个极值的情况(存在几个上升) #DP..增量计数; f(n+1)=f(n)+X; X=?? # 如果s本身上升,X=(2n+1) # 如果s本身不升,拿s的min/max去一个数据结构去检查(min/max各一个?)..(低于线性..binary search??) # .. def ...
# model settings model = dict( type='Recognizer3D', backbone=dict(type='X3D', frozen_stages = -1, gamma_w=1, gamma_b=2.25, gamma_d=2.2), cls_head=dict( type='X3DHead', in_channels=432, num_classes=400, multi_class=False, spatial_type='avg', dropout_ratio=0.7, ...
#coding:utf-8 # 数据库结构体 class DataBase: url = "" port = 3306 username = "" password = "" database = "" charset = "" # 测试用例信息结构体 class CaseInfo: path = "" case_list = [] # 测试用例结构体 class Case: url = "" db_table = "" case_id = "" method = "" data = {} c...
channels1 = { "#test1": ("@user1", "user2", "user3"), "#test2": ("@user4", "user5", "user6"), "#test3": ("@user7", "user8", "user9") } channels2 = { "#test1": ("@user1", "user2", "user3"), "#test2": ("@user4", "user5", "user6"), "#test3": ("@user7", "...
class BaseAnsiblerException(Exception): message = "Error" def __init__(self, *args, **kwargs) -> None: super().__init__(*args) self.__class__.message = kwargs.get("message", self.message) def __str__(self) -> str: return self.__class__.message class CommandNotFound(BaseAnsiblerEx...
""" Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. """ __author__ = 'Danyang' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution:...
def make_list(element, keep_none=False): """ Turns element into a list of itself if it is not of type list or tuple. """ if element is None and not keep_none: element = [] # Convert none to empty list if not isinstance(element, (list, tuple, set)): element = [element] elif isinstan...
#Evaludador de numero primo #Created by @neriphy numero = input("Ingrese el numero a evaluar: ") divisor = numero - 1 residuo = True while divisor > 1 and residuo == True: if numero%divisor != 0: divisor = divisor - 1 print("Evaluando") residuo = True elif numero%divisor == 0: residuo = False if residu...
# Python programming that returns the weight of the maximum weight path in a triangle def triangle_max_weight(arrs, level=0, index=0): if level == len(arrs) - 1: return arrs[level][index] else: return arrs[level][index] + max( triangle_max_weight(arrs, level + 1, index), triangle_ma...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: ## By passing the case if empty linked list if not he...
def get_span_and_trace(headers): try: trace, span = headers.get("X-Cloud-Trace-Context").split("/") except (ValueError, AttributeError): return None, None span = span.split(";")[0] return span, trace
def trigger(): return """ CREATE OR REPLACE FUNCTION trg_ticket_prioridade() RETURNS TRIGGER AS $$ DECLARE prioridade_grupo smallint; prioridade_subgrupo smallint; BEGIN prioridade_grupo = COALESCE((SELECT prioridade FR...
# CPU: 0.18 s n_rows, _ = map(int, input().split()) common_items = set(input().split()) for _ in range(n_rows - 1): common_items = common_items.intersection(set(input().split())) print(len(common_items)) print(*sorted(common_items), sep="\n")
class APIException(Exception): def __init__(self, message, code=None): self.context = {} if code: self.context['errorCode'] = code super().__init__(message)
lista = [] pess = [] men = 0 mai = 0 while True: pess.append(str(input('Nome:'))) pess.append(float(input('Peso:'))) if len(lista)==0:# se nao cadastrou ninguem ainda mai = men = pess[1]#o maior é o mesmo que o menor e igual pess na posicao 1 que é o peso else: if pess[1] > mai: ...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = 0 l, r = 0, 0 count = dict() while r < len(s): count[s[r]] = count.get(s[r], 0) + 1 while count[s[r]] > 1: count[s[l]] = count[s[l]] - 1 l += 1 ...
class DeviceInterface: # This operation is used to initialize the device instance. Accepts a dictionary that is read in from the device's yaml definition. # This device_config_yaml may contain any number of parameters/fields necessary to initialize/setup the instance for data collection. def initialize(self...
''' mro stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods''' print(__doc__) print('\n'+'-'*35+ 'Method Resolution Order'+'-'*35) class A(object): def dothis(self): print('From A class') class B1(A): de...
def solution(s1, s2): ''' EXPLANATION ------------------------------------------------------------------- I approached this problem by creating two dictionaries, one for each string. These dictionaries are formatted with characters as keys, and counts as values. I then iterate over each string, ...
a = float(input('Введите число: ')) def koren (a): x = 3 k = 0 if (a<0): raise ValueError('Ошибка, введите число, меньшее нуля') while k != (a**0.5): k = 0.5 * (x + a/x) x = k return(k) print('Корень из числа ' + str(a) + ' равен ' + str(koren(a)))
class Node: def __init__(self, data=None, left=None, right=None): self._left = left self._data = data self._right = right @property def left(self): return self._left @left.setter def left(self, left): self._left = left @property def right(self): return self._right @right.setter def right(self, ...
#Faça um programa que pergunte ao usuario o valor do produto, #e mostre o valor final com 5% de desconto. valorProduto = float(input('Qual o valor do produto? R$ ')) desconto = (valorProduto * 5) / 100 vFinal = valorProduto - desconto print('O valor do produto é R${}'.format(valorProduto)) print('O novo valor com o d...
# A resizable list of integers class Vector(object): # Attributes items: [int] = None size: int = 0 # Constructor def __init__(self:"Vector"): self.items = [0] # Returns current capacity def capacity(self:"Vector") -> int: return len(self.items) # Increases capacity of...
''' Arithmetic progression with 10 elements. ''' first_term = int(input('Type the first term of this A.P: ')) reason = int(input('Type the reason of this A.P: ')) last_term = first_term + (50-1)*reason # A.P formula for c in range (first_term, last_term + reason , reason): print(c, end=' ► ')
#!/usr/bin/python3 # File: fizz_buzz.py # Author: Jonathan Belden # Description: Fizz-Buzz Coding Challenge # Reference: https://edabit.com/challenge/WXqH9qvvGkmx4dMvp def evaluate(inputValue): result = None if inputValue % 3 == 0 and inputValue % 5 == 0: result = "FizzBuzz" elif inputValue % 3 ...
class Solution: """ @param A: @return: nothing """ def numFactoredBinaryTrees(self, A): A.sort() MOD = 10 ** 9 + 7 dp = {} for j in range(len(A)): dp[A[j]] = 1 for i in range(j): if A[j] % A[i] == 0: num = A...
def multiplo(a, b): if a % b == 0: return True else: return False print(multiplo(2, 1)) print(multiplo(9, 5)) print(multiplo(81, 9))
class Quadrado: def __init__(self, lado): self.tamanho_lado = lado def mudar_valor_lado(self, novo_lado): lado = novo_lado self.tamanho_lado = novo_lado def retornar_valor_lado(self, retorno): self.tamanho_lado = retorno print(retorno) def calcular_area(self, a...
valores = [] quant = int(input()) for c in range(0, quant): x, y = input().split(' ') x = int(x) y = int(y) maior = menor = soma = 0 if x > y: maior = x menor = y else: maior = y menor = x if maior == menor+1 or maior == menor: valores.append(0) e...
def binary_search(collection, lhs, rhs, value): if rhs > lhs: mid = lhs + (rhs - lhs) // 2 if collection[mid] == value: return mid if collection[mid] > value: return binary_search(collection, lhs, mid-1, value) return binary_search(collection, mid+1, rhs, v...
#Exercício Python 9: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada. n = int(input("Digite um número: ")) i = 0 print("--------------") while i < 10: i += 1 print("{:2} x {:2} = {:2}".format(n, i, n*i)) print("--------------")
click(Pattern("Bameumbrace.png").similar(0.80)) sleep(1) click("3abnb.png") exit(0)
class Rover: def __init__(self,photo,name,date): self.photo = photo self.name = name self.date = date class Articles: def __init__(self,author,title,description,url,poster,time): self.author = author self.title = title self.description = description ...
'''https://leetcode.com/problems/max-consecutive-ones/''' class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: i, j = 0, 0 ans = 0 while j<len(nums): if nums[j]==0: ans = max(ans, j-i) i = j+1 j+=1 return m...
class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: n = len(board) q = collections.deque() q.append(1) visited = set() visited.add(1) step = 0 while q: size = len(q) for _ in range(size): num = q.p...
def mergingLetters(s, t): #edge cases mergedStr = "" firstChar = list(s) secondChar = list(t) for i, ele in enumerate(secondChar): if i < len(firstChar): mergedStr = mergedStr + firstChar[i] print('first pointer', firstChar[i], mergedStr) if i < len(second...
""" 题目: 给定一个 32 位有符号整数,将整数中的数字进行反转。 示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 注意: 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2**31, 2**31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。 """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if ...
# # PySNMP MIB module TIMETRA-SAS-IEEE8021-PAE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-SAS-IEEE8021-PAE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:21:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
x = 0 y = 0 aim = 0 with open('input') as f: for line in f: direction = line.split()[0] magnitude = int(line.split()[1]) if direction == 'forward': x += magnitude y += aim * magnitude elif direction == 'down': aim += magnitude elif directio...
# # PySNMP MIB module PRIVATE-SW0657840-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PRIVATE-SW0657840-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:33:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
class MinDiffList: # def __init__(self): # self.diff = sys.maxint def findMinDiff(self, arr): arr.sort() self.diff = arr[len(arr) - 1] for iter in range(len(arr)): adjacentDiff = abs(arr[iter + 1]) - abs(arr[iter]) if adjacentDiff < self.diff: ...
""" Author: CaptCorpMURICA Project: 100DaysPython File: module1_day06_lists.py Creation Date: 6/2/2019, 8:55 AM Description: Learn the basic of lists in python. """ list_1 = [] list_2 = list() print("List 1 Type: {}\nList 2 Type: {}".format(type(list_1), type(list_2))) ...
class MagicDice: def __init__(self, account, active_key): self.account = account self.active_key = active_key
def countWord(word): count = 0 with open('test.txt') as file: for line in file: if word in line: count += line.count(word) return count word = input('Enter word: ') count = countWord(word) print(word, '- occurence: ', count)
header = """/* Icebreaker and IceSugar RSMB5 project - RV32I for Lattice iCE40 With complete open-source toolchain flow using: -> yosys -> icarus verilog -> icestorm project Tests are written in several languages -> Systemverilog Pure Testbench (Vivado) -> UVM testbench (Vivado) -> PyUvm (Icarus) -> Formal ...
num = int(input()) x = 0 if num == 0: print(1) exit() while num != 0: x +=1 num = num//10 print(x)
class SpecValidator: def __init__(self, type=None, default=None, choices=[], min=None, max=None): self.type = type self.default = default self.choices = choices self.min = min self.max = max
"""FactoryAggregate provider prototype.""" class FactoryAggregate: """FactoryAggregate provider prototype.""" def __init__(self, **factories): """Initialize instance.""" self.factories = factories def __call__(self, factory_name, *args, **kwargs): """Create object.""" ret...
def f(x): #return 1*x**3 + 5*x**2 - 2*x - 24 #return 1*x**4 - 4*x**3 - 2*x**2 + 12*x - 3 return 82*x + 6*x**2 - 0.67*x**3 print(f(2)-f(1)) #print((f(3.5) - f(0.5)) / -3) #print(f(0.5))
# Weird Algorithm # Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one. n = int(input()) print(n, end=" ") while n != 1: if n % 2 == 0: ...
T = int(input()) if T > 100: print('Steam') elif T < 0: print('Ice') else: print('Water')
PSQL_CONNECTION_PARAMS = { 'dbname': 'ifcb', 'user': '******', 'password': '******', 'host': '/var/run/postgresql/' } DATA_DIR = '/mnt/ifcb'
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ tunacell package ============ plotting/defs.py module ~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ DEFAULT_COLORS = ('red', 'blue', 'purple', 'green', 'yellowgreen', 'cyan', 'magenta', 'indigo', 'darkorange', 'pink', 'yellow') colors = DEFAULT_...
class KeyBoardService(): def __init__(self): pass def is_key_pressed(self, *keys): pass def is_key_released(self, *key): pass
#!/usr/bin/env python3 """Switcharoo. Create a function that takes a string and returns a new string with its first and last characters swapped, except under three conditions: If the length of the string is less than two, return "Incompatible.". If the argument is not a string, return "Incompatible.". If the first a...
"""1/1 adventofcode""" with open("input.txt", "r", encoding="UTF-8") as i_file: data = list(map(int, i_file.read().splitlines())) values = ["i" if data[i] > data[i - 1] else "d" for i in range(1, len(data))] print(values.count("i"))
def past(h, m, s): h_ms = h * 3600000 m_ms = m * 60000 s_ms = s * 1000 return h_ms + m_ms + s_ms # Best Practices def past(h, m, s): return (3600*h + 60*m + s) * 1000
# En este problema vamos a resolver el problema de la bandera de Dijkstra. # Tenemos una fila de fichas que cada una puede ser de un único color: roja, verde o azul. Están colocadas en un orden cualquiera # y tenemos que ordenarlas de manera que quede, de izquierda a derecha, los colores ordenados primero en rojo, lue...
# Iteration: Repeat the same procedure until it reaches a end point. # Specify the data to iterate over,what to do to data at every step, and we need to specify when our loop should stop. # Infinite Loop: Bug that may occur when ending condition speicified incorrectly or not specified. spices = [ 'salt', 'pepp...
# coding: utf-8 print(__import__('task_list_dev').tools.get_list())
#Warmup-1 > not_string def not_string(str): if str.startswith('not'): return str else: return "not " + str
num = int(input('Digite um número: ')) print('''Qual será a base de conversão do número {} [1] para "binário" [2] para "octal" [3] para "hexadecimal"'''.format(num)) num1 = int(input('Escolha uma opção: ')) if num1 == 1: print('Você escolheu converter o número {} para binário. O valor é de {}.'.format( num...
''' Docstring with single quotes instead of double quotes. ''' my_str = "not an int"
def selection_sort(input_list): for i in range(len(input_list)): min_index = i for k in range(i, len(input_list)): if input_list[k] < input_list[min_index]: min_index = k input_list[i], input_list[min_index] = input_list[min_index], input_list[i] return inpu...
username = 'user@example.com' password = 'hunter2' # larger = less change of delays if you skip a lot # smaller = more responsive to ups/downs queue_size = 2
""" A list of stopwords to filter out, in addition to those that are already being filtered by the built-in toolkit. """ CustomStopwords = ['alltid', 'fler', 'ta', 'tar', 'sker', 'redan', 'who', 'what', 'gilla', 'big', 'something','fler', 'cv', 'snart', 'minst', 'kunna', '000', 'hr-plus', 'enligt...
# import logging # logging.basicConfig(filename='example.log',level=logging.DEBUG) # logging.debug('This message should go to the log file') # logging.info('So should this') # logging.warning('And this, too ã') class ValidaSmart(): def __init__(self): self._carrega_modulos_externos() def _carrega_mod...
machine_number = 43 user_number = int( raw_input("enter a number: ") ) print( type(user_number) ) if user_number == machine_number: print("Bravo!!!")
def pedir_entero (mensaje,min,max): numero = input(mensaje.format(min,max)) if type(numero)==int: while numero <= min or numero>=max: numero = input("el numero debe estar entre {:d} y {:d} ".format(min,max)) return numero else: return "debes introducir un entero" valido...
test_cases = int(input().strip()) def sum_sub_nums(idx, value): global result if value == K: result += 1 return if value > K or idx >= N: return sum_sub_nums(idx + 1, value) sum_sub_nums(idx + 1, value + nums[idx]) for t in range(1, test_cases + 1): N, K = map(int, i...