content
stringlengths
7
1.05M
""" flask_konch ~~~~~~~~~~~ An improved shell commmand for the Flask CLI. """ __version__ = "2.0.0" __all__ = ["EXTENSION_NAME"] EXTENSION_NAME = "flask-konch"
# https://baike.baidu.com/item/%E5%BF%AB%E9%80%9F%E5%B9%82 # 11 = 2^0 + 2^! + 2^3 # a^11 = a^(2^0) + a^(2^1) + a^(2^3) class Solution: def myPow(self, x: float, n: int) -> float: N = n if N < 0: x = 1/x N = -N ans = 1 current_product = x while N > 0: ...
# time Complexity: O(n^2) # space Complexity: O(1) def bubble_sort(arr): current = 0 next = 1 last_index = len(arr) while last_index >= next: if arr[current] > arr[next]: arr[current], arr[next] = arr[next], arr[current] current += 1 next += 1 if next == ...
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: # Copy / paste from the "fastest" solution. # It's sort of beautiful in its simplicity, if wildly esoteric. # Basically the same thing as the hacky failsafe in my first solution; # compare the number of unique characters...
#Sieve of Eratosthenes #Решето Эратосфена # Оригинал: https://github.com/nquidox/learn2python. Вещание на 8-Bit Tea Party. #предел работы скрипта limit=16; it = 0 #будем считать, что каждый индекс списка является простым числом numbers_list=[True]*limit #и сразу отбросим ноль с единицей numbers_list[0]=False number...
# # PySNMP MIB module APDNSALG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APDNSALG-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:23:12 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
''' /****************************************************************** * * Copyright 2018 Samsung Electronics 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 * * htt...
# -*- coding: utf-8 -*- # 设置订阅人的邮箱 RECEIVER = ['**@**'] # 信息化平台的用户名和密码 USER_ID = "SA****" USER_PWD = "***" # 是否在实习,用于提醒写实习月报,后期建立receiver的字典保存,目前没有必要 IS_INTERNSHIP = True # SMTP服务器信息设置(发件邮箱) # 我用的是163邮箱 # 可以参考:https://blog.csdn.net/qlzy_5418/article/details/86661883 HOST = "smtp.163.com" # SMTP服务器host SENDER = "...
# -*- coding: utf-8 -*- { 'name': "onesphere_mdm", 'summary': """ MOM主数据管理模块 """, 'description': """ Long description of module's purpose """, 'author': "上海文享信息科技有限公司", 'website': "http://www.oneshare.com.cn", # Categories can be used to filter modules in modules list...
hpp = 'AL-Import' # Specify the name of the hpp to print the graph graph_title='EM- Total Impact of the energy maximization scenario on '+ hpp df_em2 = df_em1.groupby(['scenario'])['value'].sum().round(2).reset_index() fig5c = px.bar(df_em2, x='scenario', y='value', text= 'value', color='scenario',barmode='group', ...
class MyModule(): def my_function(): pass def main(): """The main entrypoint for this script Used in the setup.py file """ MyModule.my_function() if __name__ == '__main__': main()
class MessageTypeNotSupported(Exception): pass class MessageDoesNotExist(Exception): pass
# https://www.codechef.com/problems/RAINBOWA for T in range(int(input())): n,l=int(input()),list(map(int,input().split())) print("no") if(set(l)!=set(list(range(1,8))) or l[0]!=1 or l[-1]!=1 or l!=l[::-1]) else print("yes")
# -*- encoding:utf-8 -*- __version__ = (1, 2, 11) __version_str__ = ".".join(map(str, __version__)) __version_core__ = (3, 0, 4)
def to_camel_case(s): return ('' if not s else s[0] + ''.join(c.upper() if s[::-1][i + 1] in '-_' else '' if c in '-_' else c for i, c in enumerate(s[::-1][:-1]))[::-1])
##NIM, Umur, Tinggi = (211080200045, 18, 170) ##print(NIM, Umur, Tinggi) angka_positif = 1,2,3,4,5,6,7,8,9 print(angka_positif)
GOLD = ["7374", "7857", "7990", "8065", "8250"] ANNOTATORS = ["01", "02", "03", "04", "05", "06"] DOC_HEADER = ["order", "doc_id", "assigned", "nr_sens_calculated", "nr_sens", "annotator_1", "annotator_2", "assigned_2"] CYCLE_FILE = "../input/batch_cycles.csv" CYCLE_COL = "cycle" ASSIGNMENT_TXT = "assig...
""" Item 29: Avoid Repeated Work in Comprehensions by Using Assignment Expressions """ stock = { 'nails': 125, 'screws': 35, 'wingnuts': 8, 'washers': 24, } order = ['screws', 'wingnuts', 'clips'] def get_batches(count, size): return count // size result = {} for name in order: count = stock.get(name, 0) ...
""" >>> 'dir/bar.py:2' """
class IntegerField: def __str__(self): return "integer"
class AdministrativeDivision: def __init__(self, level): self.level = level pass class Province(AdministrativeDivision): type = 'Province' area = 0 center = '' def __init__(self, name): self.name = name self.level = 1 def __str__(self): return f"{self.name} {self.type}" pas...
# Binary Tree implemented using python list class BinaryTree: def __init__(self,size) -> None: self.cl=size*[None] self.lastUsedIndex=0 self.maxSize=size def insertNode(self,value): if self.lastUsedIndex+1==self.maxSize: return "BT is full" self.cl[self.last...
num1 = int(input()) count1 = 0 while 1 <= num1 <= 5: if num1 == 5: count1 += 1 num1 = int(input()) print(count1)
# MSCT TAU = 1 TAU_INFINITE = 1e-3 C_PUCT = 5 # A higher value means relying on the prior more. ALPHA = 0.55 # Dirichlet noise的参数 NOISE_EPS = 0.25 SELF_PLAY_SIMULATION_NUM = 400 SELF_PLAY_GAME_NUM = 2 # self-play的游戏次数 FREE_PLAY_SIMULATION_NUM = 400 REPLAY_BUFF_CAPACITY = 50000 # replay_buffer的容量,论文中是存储最近的500000把游戏...
class Label(object): def __eq__(self, other): assert(isinstance(other, Label)) return type(self) == type(other) def __ne__(self, other): assert(isinstance(other, Label)) return type(self) != type(other) def __hash__(self): return hash(self.to_class_str()) def ...
#Function to insert a string in the middle of a string def string_in(): string=str(input("Enter a string :")) mid=len(string)//2 word=str(input("Enter a word to insert in middle :")) new_string=string[:mid]+word+string[mid:] print(new_string) string_in()
# # This file contains "references" to unreferenced code that should be kept and not considered dead code # not_used_but_whitelisted
""" Contains exception classes. """ class KRDictException(Exception): """ Contains information about an API error. This exception is only thrown if the argument passed to the ``raise_api_errors`` parameter is True. - ``message``: The error message associated with the error. - ``error_code``: T...
# Copyright 2018 TNG Technology Consulting GmbH, Unterfoehring, Germany # Licensed under the Apache License, Version 2.0 - see LICENSE.md in project root directory # TODO IT-1: give this function some great functionality def great_function(): pass # TODO: give this function some greater functionality def greate...
class Stats:# pragma: no cover """Abstract class defining the basis of all Stats """ def get_keys(self): """Return the keys of the Stats Returns ------- keys : tuple of strings Key for the Stats """ return () def get...
n = 0 for i in range(999, 100, -1): for j in range(i, 100, -1): x = i * j if x > n: s = str(i * j) if s == s[::-1]: n = i * j print(n)
class DictSerializable: @classmethod def from_dict(cls, data: dict) -> 'DictSerializable': return cls(**data) def to_dict(self) -> dict: return vars(self)
def ticket_printer(lister,number,total): f=open("ticket.txt","w") f.write("本次购物清单如下:\n") f.write("商品编号\t商品名称\t价格\t数量\t小计\n") for (good,num) in zip(lister,number): f.write(str(good.id)+"\t\t"+good.name+"\t\t"+str(good.price)+"\t"+str(num)+"\t"+str(num*good.price)+"\n") f.write("总价: "+str(tota...
known = {} def ack(m, n): if m == 0: return n + 1 if m > 0 and n == 0: return ack(m-1, 1) if m > 0 and n > 0: if (m,n) in known: print('Cache hit') return known[(m, n)] else: known[(m, n)] = ack(m - 1, ack(m , n - 1)) retu...
# # @lc app=leetcode id=450 lang=python3 # # [450] Delete Node in a BST # # @lc code=start # 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 deleteNode(s...
__title__ = 'pairing-functions' __description__ = 'A collection of pairing functions' __url__ = 'https://github.com/ConvertGroupLabs/pairing-functions' __version__ = '0.2.1' __author__ = 'Convert Group Labs' __author_email__ = 'tools@convertgroup.com' __license__ = 'MIT License' __copyright__ = 'Copyright 2020 Convert ...
def deleteMid(head): # check if the list contains 1 or more nodes if head is None or head.next is None: return None #assign pointers to their respective positions prev, i, j = None, head, head while j and j.next: j = j.next.next;# j pointer moves 2 nodes ahead ...
"""Contains ascii-art project related logos.""" # http://patorjk.com/software/taag/#p=display&f=Varsity&t=PnP PNP = r""" _______ _______ |_ __ \ |_ __ \ | |__) |_ .--. | |__) | | ___/[ `.-. | | ___/ _| |_ | | | | _| | |_____| [___||__]|_____| """
N = int(input()) a = N % 1000 if a == 0: print(0) else: print(1000 - a)
# -*- coding: utf-8 -*- f = open("dico.txt", "r") contrasenia = "hola" contador = 0 linea = f.readline() while linea: contador += 1 if linea.strip() == contrasenia.strip(): print('Contrasenia encontrada: ' + linea) print('en ' + str(contador) + ' intentos') break linea = f.readline(...
first = "Murat" last = "Aksoy" name = f"Welcome to pyhton '{last}', {first}" print(name)
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ dic = {} for item in s: if item in dic: dic[item] += 1 else: dic[item] = 1 ans = [0 for x in range(len(dic))] i = 0 ...
AUTHOR="Zawadi Done" DESCRIPTION="This module wil install/update MassDNS" INSTALL_TYPE="GIT" REPOSITORY_LOCATION="https://github.com/blechschmidt/massdns" INSTALL_LOCATION="massdns" DEBIAN="" AFTER_COMMANDS="cd {INSTALL_LOCATION},make,cp bin/massdns /usr/local/bin/" LAUNCHER="massdns"
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): # # Iterative (accepted), Time: O(m + n), Space: O(1) # def insert(self, pos_node, node): # node.next = pos_node.next ...
''' This module declares constants needed for this solution. This is to remove magic numbers ''' CRATER_CHANGE_WHEN_SUNNY = 0.9 CRATER_CHANGE_WHEN_RAINY = 1.2 CRATER_CHANGE_WHEN_WINDY = 0.0 ORBIT1_ORBIT_DISTANCE = 18 ORBIT1_CRATERS_COUNT = 20 ORBIT2_ORBIT_DISTANCE = 20 ORBIT2_CRATERS_COUNT = 10
class Solution: def singleNumber(self, nums: List[int]) -> int: ret = 0 for n in nums: ret ^= n return ret
#! /usr/bin/env python3 """Sort a list and store previous indices of values""" # enumerate is a great but little-known tool for writing nice code l = [4, 2, 3, 5, 1] print("original list: ", l) values, indices = zip(*sorted((a, b) for (b, a) in enumerate(l))) # now values contains the sorted list and indices contai...
#!/usr/bin/env python3 # https://www.urionlinejudge.com.br/judge/en/problems/view/1020 def decompose(total, value): decomposed = total // value return total - decomposed * value, decomposed def main(): DAYS = int(input()) DAYS, YEARS = decompose(DAYS, 365) DAYS, MONTHS = decompose(DAYS, 30)...
''' Creating a very basic module in Python ''' languages = {'Basic', 'QBasic', 'Cobol', 'Pascal', 'Assembly', 'C/C++', 'Java', 'Python', 'Ruby'} values = 10, 50, 60, 11, 98, 75, 65, 32 def add(*args: float) -> float: sum = 0.0 for value in args: sum += value return sum def multiply(*args: float) -> flo...
class person(): def __init__(self,nombre,edad,lugResi): self.name = nombre self.age=edad self.place=lugResi def datos(self): print("Nombre: ", self.name, "\nEdad: ", self.age, "\nResidencia: ", self.place ) class employee(person): def __i...
__author__ = 'roland' class HandlerResponse(object): def __init__(self, content_processed, outside_html_action=None, tester_error_description=None, cookie_jar=None, urllib_request=None, urllib_response=None): """ :param content_processed: bool set to True if a sc...
#Config, Reference, and configure provided in globals cards = Config( hd_audio=Config( match=dict(), name='Auto-%(id)s-%(label)s', restart=-1, input=dict( label="input", subdevice='0', channels=2, buffer_size=512, buffer_count=4, sample_rate=48000, quality=4 ), output=dict(...
# 给定一个二叉树,判断它是否是高度平衡的二叉树。 # # 本题中,一棵高度平衡二叉树定义为: # # 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 # # 示例 1: # # 给定二叉树 [3,9,20,null,null,15,7] # # 3 # / \ # 9 20 # / \ # 15 7 # 返回 true 。 # # 示例 2: # # 给定二叉树 [1,2,2,3,3,null,null,4,4] # # 1 # / \ # 2 2 # / \ # 3 3 # / \ # 4 4 # 返回 fa...
#!/usr/bin/env python3 # Copyright 2018, Rackspace US, Inc. # # 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 applicabl...
def make_bio_dict(tags, start_idx=0): d = dict() i = start_idx for tag in tags: for pre_tag in ['B-', 'I-']: d[pre_tag + tag] = i i += 1 d['O'] = i return d
# -------------------------------------------------# # EXERCICIO 08 # # -------------------------------------------------# # Faça um programa que leia um valor em metros # e exiba convertido em centimetro e milimetros mt = float(input('digite um distancia em metros...:')) mm = mt * 1...
# -*- coding: utf-8 -*- __author__ = "Sergey Aganezov" __email__ = "aganezov(at)cs.jhu.edu" __status__ = "production" version = "1.10" __all__ = ["grimm", "breakpoint_graph", "graphviz", "utils", "edge", "genome", "kbreak", "multicolor", ...
size(200, 200) stroke(0) strokeWidth(10) fill(1, 0.3, 0) polygon((40, 40), (40, 160)) polygon((60, 40), (60, 160), (130, 160)) polygon((100, 40), (160, 160), (160, 40), close=False)
# imdb sortBy functions def sortMoviesBy(movies_names_wl, args): """ This module is used to sortMovies by the dict(arg.sortBy) :param list movies_names_wl: a list of movie_names_with_links movie : [Rank, Link, Title, Year, Rating, Number of Ratings, Runtime, Director] Rank : int L...
# flake8: noqa _base_ = [ './coco.py' ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict(classes=('person',)), val=dict(classes=('person',)), test=dict(classes=('person',)) )
######################################################## # Copyright (c) 2015-2017 by European Commission. # # All Rights Reserved. # ######################################################## extends("BaseKPI.py") """ Expected Unserved Demand (%) ----------------------------- Inde...
x = int(input()) n = int(input()) pool = x for _ in range(n): pool += x - int(input()) print(pool)
def reject_outliers(data, m = 2.): d = np.abs(data - np.median(data)) mdev = np.median(d) s = d/mdev if mdev else 0. return (s < m) def mean_dup(x_): global reject_outliers if 1==len(np.unique(x_.values)): return x_.values[0] else: x = x_....
class MyList: class _Node: __slots__ = ('value', 'next') def __init__(self, value, next=None): self.value = value self.next = next class _NodeIterator: def __init__(self, first): self._next_node = first def __iter__(self): retur...
number = 10 array = '64630 11735 14216 99233 14470 4978 73429 38120 51135 67060' array = list(map(int, array.split())) def find_mean(a): return round(sum(a)/number, 1) def find_median(a): a = sorted(a) if len(a) % 2 == 0: return round((a[number//2 - 1] + a[number//2])/2, 1) else: ret...
""" Entrada O arquivo de entrada contém dois valores inteiros correspondentes ao código e à quantidade de um item conforme tabela acima. Saída O arquivo de saída deve conter a mensagem "Total: R$ " seguido pelo valor a ser pago, com 2 casas após o ponto decimal """ produtos = { 1: {"desc": "Cachorro Quente", "...
velocidade = float(input('Escreva a Velocidade de seu carro:')) if velocidade <=80: print('Tenha um bom dia.Dirija com segurança') else: print('MUTADO.Você passou o limite permitodo que è 80km/h') print('Você agora vai ter que pagar de R${:.2f}!'.format((velocidade - 80 )*7)) print('Tenha um bom dia . D...
class ScrollProperties(object): """ Encapsulates properties related to scrolling. """ def Instance(self): """ This function has been arbitrarily put into the stubs""" return ScrollProperties() @staticmethod def __new__(self,*args): #cannot find CLR constructor """ __new__(cls: type,container: Scrolla...
# -- coding: utf-8 -- # Created by LoginRadius Development Team # Copyright 2019 LoginRadius Inc. All rights reserved. # class MultiFactorAuthenticationApi: def __init__(self, lr_object): """ :param lr_object: this is the reference to the parent LoginRadius object. """ self._lr_ob...
Num1 = int(input('Primeiro número: ')) Num2 = int(input('Segundo número: ')) Num3 = int(input('Terceiro número: ')) Num4 = int(input('Quarto número: ')) Num5 = int(input('Quinto número: ')) Num6 = int(input('Sexto número: ')) lista = [Num1, Num2, Num3, Num4, Num5, Num6] soma = 0 for c in range(0, len(lista)): if (l...
"""Not sure why memory limit exceeded, but this solution works""" class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ def postProcess(combos, s): if combos is None: re...
class IAMPolicies(): def __init__(self, iam): self.client = iam def _marker_handler(self, marker=None, scope='All'): if marker: response = self.client.list_policies( Scope=scope, OnlyAttached=True, PolicyUsageFilter='PermissionsPolicy...
runtime_project='core' editor_project='core-Editor' runtime_project_file='Assembly-CSharp' editor_project_file='Assembly-CSharp-Editor' define='ANDROID' MONO="/Applications/Unity/MonoDevelop.app/Contents/Frameworks/Mono.framework/Versions/Current/bin/mono" MDTOOL="/Applications/Unity/MonoDevelop.app/Contents/MacOS/lib...
L = 0 heatmap = [] while True: try: line = [int(x) for x in input()] # Pad heatmap with 9s heat = [9] + line + [9] L = len(heat) heatmap.extend(heat) except EOFError: break index = 0 # Pad 9s in top and bottom heatmap = heatmap + (L*[9]) bigmap = (L*[9]) + ...
# Copyright 2019 the rules_bison authors. # # 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...
test = { 'name': 'q1_19', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> -1 <= observed_diff_proportion <= 1 True """, 'hidden': False, 'locked': False }, { 'code': r""" >>> # The observed d...
# -*- coding: utf-8 -*- """ ==================================================== Autor: Johann Gordillo Email: jgordillo@ciencias.unam.mx ==================================================== Excepciones personalizadas para el programa. ==================================================== """ class InvalidLocationErr...
def convert(key): if key == " ": return " " elif key == "ক": return "क" elif key == "খ": return "ख" elif key == "গ": return "ग" elif key == "ঘ": return "घ" elif key == "ঙ": return "ङ" elif key == "চ": return "च" elif key == "ছ": ...
""" Problem statement: Write a function to simulate the rock, paper, scissors game between Abigail and Benson. Problem Link: https://edabit.com/challenge/p6uXeD7JC7cmxeD2Z Abigail and Benson are playing Rock, Paper, Scissors. Each game is represented by an array of length 2, where the first element represents what Ab...
# Enter your code for "Hello with attitude" here. name = input("What is your name? ") print("So you call yourself '" + name + "' huh?")
# https://www.codewars.com/kata/59e49b2afc3c494d5d00002a/train/python def sort_vowels(s): if isinstance(s, int) or s == None: return '' vovels = ['a', 'e', 'u', 'i', 'o'] output = [] for letter in s: if vovels.count(letter.lower()) > 0: output.append(f'|{let...
#!/usr/bin/python3 # The MDPs consists of a range of integers 0..stateMax which represent # the states of the MDP, a set of actions. The rewards and transition # probabilities are accessed with some of the functions below defined # for the Python classes that represent MDPs. # # - The __init__ constructor builds the ...
W = int(input()) N, K = map(int, input().split()) dp = [{} for _ in range(K + 1)] dp[0][0] = 0 for _ in range(N): A, B = map(int, input().split()) for i in range(K - 1, -1, -1): for j in dp[i]: if j + A <= W: dp[i + 1].setdefault(j + A, 0) dp[i + 1][j + A] = ...
# This file is part of the DMComm project by BladeSabre. License: MIT. class ProngOutput: """Description of the outputs for the RP2040 prong circuit. :param pin_drive_signal: The first pin to use for signal output. Note that `pin_drive_low=pin_drive_signal+1` due to the rules of PIO. :param pin_weak_pull: The pi...
class RenderInterface(object): def render(self): raise NotImplementedError("Class %s doesn't implement render()" % (self.__class__.__name__)) class ViewportInterface(object): def to_dict(self): raise NotImplementedError("Class %s doesn't implement to_dict()" % (self.__class__.__name__)) d...
num1 = int(input('digite um valor')) num2 = int(input('digite um valor')) s = num1 + num2 print('A soma entre {} e {} vale {}'.format(num1, num2, s))
def modify_phoneme_script_to_create_grapheme_script(original_dataset_path, grapheme_dataset_path): with open(original_dataset_path, 'r', encoding='utf-8-sig') as f: lines = f.readlines() new_lines = [] for line in lines: split_result = line.split('|') wav_path = split_result[0] ...
# Solution def add_one(arr): output = 1; for i in range(len(arr), 0, -1): output = output + arr[i - 1] borrow = output//10 if borrow == 0: arr[i - 1] = output break else: arr[i - 1] = output % 10 output = borrow arr = [borrow] ...
def interpolation_search(arr, key): low = 0 high = len(arr) - 1 while arr[high] != arr[low] and key >= arr[low] and key <= arr[high]: mid = int(low + ((key - arr[low]) * (high - low) / (arr[high] - arr[low]))) if arr[mid] == key: return mid elif arr[mid] < key: ...
# encoding: utf-8 # module Tekla.Structures.Model.History calls itself History # from Tekla.Structures.Model,Version=2017.0.0.0,Culture=neutral,PublicKeyToken=2f04dbe497b71114 # by generator 1.145 # no doc # no imports # no functions # classes class ModelHistory(object): # no doc @staticmethod ...
# dividebyzero.py """Simple exception handling example.""" while True: # attempt to convert and divide values try: number1 = int(input('Enter numerator: ')) number2 = int(input('Enter denominator: ')) result = number1 / number2 except ValueError: # tried to convert non-numeric valu...
try: with open('../../.password/google-maps/api', 'r') as fp: key = fp.readlines() key = ''.join(key) except: # Insert your API key here key = 'AIzaSyDxydKN7Yt54JNmVw9opg9EcibCghjetgw'
#Ex053 Crie um programa que leia uma frase e diga se ela é um palíndromo, desconsiderando os espaços. #Ex: apos a sopa frase = str(input('Digite uma frase: ')).strip().upper() palavras = frase.strip() junto = ''.join(palavras) inverso = '' for letra in range(len(junto)-1,-1,-1): inverso += junto[letra] print(f'O in...
#SOLUTION FOR P20 '''P20 (*) Remove the K'th element from a list. Example: * (remove-at '(a b c d) 2) (A C D)''' my_list = ['a','b','c','d','e'] pos= int(input('Element to remove = ')) if pos <= len(my_list): #CHECK IF INPUT IS IN RANGE my_list.pop(pos-1) #REMOVE THE ELEMENT AT GIVEN INDE...
class PairSet(object): __slots__ = '_data', def __init__(self): self._data = set() def __contains__(self, item): return item in self._data def has(self, a, b): return (a, b) in self._data def add(self, a, b): self._data.add((a, b)) self._data.add((b, a)) ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def count_unival_subtrees(self, root: TreeNode) -> int: self.count = 0 self.is_unival(root) return self.count def is_unival(self, root: TreeNode) -> bool...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def getNth(self, ll...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
def draw_line(tick_length, tick_label=""): line = "-" * tick_length if tick_label: line += " " + tick_label print(line) def draw_interval(center_length): if center_length > 0: draw_interval(center_length - 1) draw_line(center_length) draw_interval(center_length - 1) d...
class TrainConfig(typing.NamedTuple): T: int train_size: int batch_size: int loss_func: typing.Callable class TrainData(typing.NamedTuple): feats: np.ndarray targs: np.ndarray DaRnnNet = collections.namedtuple("DaRnnNet", ["encoder", "decoder", "enc_opt", "dec_opt"])