content
stringlengths
7
1.05M
class Solution: def largestBSTSubtree(self, root: TreeNode) -> int: return self._post_order(root)[0] def _post_order(self, root): if not root: return 0, True, None, None if not root.left and not root.right: return 1, True, root.val, root.val ln, l...
# print function range value for value in range(1, 5): print(value) numbers = list(range(1, 6)) print(numbers) even_numbers = list(range(2, 11)) print(even_numbers)
def is_odd(n): return n % 2 == 1 def is_weird(n): if is_odd(n): return True else: # n is even if 2 <= n <= 5: return False elif 6 <= n <= 20: return True elif 20 < n: return False n = int(input()) if (is_weird(n)): print("W...
class calculos(): def __init__(self): self.funcoes = { "soma": self.soma, "subtracao": self.subtracao, "multiplicacao": self.multiplicacao, "divisao": self.divisao, "quadrado": self.quadrado, "raiz_quadrada": self.raiz_quadrada, ...
# Print the list created by using list comprehension names = ['George', 'Harry', 'Weasely', 'Ron', 'Potter', 'Hermione'] best_list = [name for name in names if len(name) >= 6] print(best_list) # Range Objects # Create a range object that goes from 0 to 5 nums = range(6) print(type(nums)) # Convert nums to a list nums...
# -*- coding:utf-8 -*- def read_files(path): file = open(path, 'r+') str_ = file.read() print(str_) file.close()
#!/usr/bin/python3 """ 4-main """ MRUCache = __import__('4-mru_cache').MRUCache my_cache = MRUCache() my_cache.put("A", "Hello") my_cache.put("B", "World") my_cache.put("C", "Holberton") my_cache.put("D", "School") my_cache.print_cache() print(my_cache.get("B")) my_cache.put("E", "Battery") my_cache.print_cache() my_c...
class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ def change(i): if i == '0': return '1' return '0' l = '' print(bin(num)[2:]) for i in bin(num)[2:]: l...
print("Em que ano você nasceu?") nascimento = input() nascimento = int(nascimento) print("Para qual ano você quer saber sua idade?") idadequalquer = input() idadequalquer = int(idadequalquer) idadefinal = idadequalquer - nascimento print( "No ano ", idadequalquer , "você terá", idadefinal, "anos!")
nome = input('Digite seu nome completo: ') print('Nome em letras maiúsculas: {}' .format(nome.upper().strip())) print('Nome em letras minúsculas: {}' .format(nome.lower().strip())) print('Total de letras: {}' .format(len((nome.replace(" ", ""))))) nome_s = nome.split() print('O primeiro nome tem {} letras.' .format(len...
for a in range (2,21): if a > 1: for i in range(2,a): if (a % i) == 0: break else: print(a)
#!/usr/bin/env python3 # Simple data processing, extraction of GPGGA and GPRMC entries # Source filename FILENAME = "../data/GNSS_34_2020-02-23_16-20-44.txt" # Output filename OUTFILE = "../output/track.nmea" if __name__ == "__main__": outfile = open(OUTFILE, 'w') with open(FILENAME, 'r') as f: for...
# 60 # Faça um programa que leia um número qualquer e mostre o seu fatorial. # Exemplo: 5! = 5 x 4 x 3 x 2 x 1 = 120 num = int(input('Digite um número para calcular seu Fatorial: ')) c = num fat = 1 # # Form 1 - using Math # from math import factorial # f = factorial(num) # print("O fatorial de {} é {}".format(num,...
registry = {} def unmarshal(typestr, x): try: unmarshaller = registry[typestr] except KeyError: raise TypeError("No unmarshaller registered for '{}'".format(typestr)) return unmarshaller(x) def register(typestr, unmarshaller): if typestr in registry: raise NameError( ...
""" 1201_pull_up_method.py 范例 有两个子类,它们之中各有一个函数做了相同的事情。这个例子在 12.3 和 12.8 也有引用。 """ class Party: """契约或争论的)当事人,一方""" @property def annual_cost(self): return self.monthly_cost * 12 @property def monthly_cost(self): raise RuntimeError("SubclassResponsibilityError") class Employee(...
def play(n=None): if n is None: while True: try: n = int(input('Input the grid size: ')) except ValueError: print('Invalid input') continue if n <= 0: print('Invalid input') continue ...
def get_rate(numbers, is_o2): nb_bits = len(numbers[0]) assert all([len(n) == nb_bits for n in numbers]) current_numbers = [n for n in numbers] i = 0 while len(current_numbers) > 1: nb_ones = sum([elem[i] == '1' for elem in current_numbers]) nb_zeros = sum([elem[i] ==...
# Returns the sum of all multipliers of x for numbers from 1 to end. def sumOfMultipliers(end, x): n = end / x return (n * (n + 1) / 2) * x end = 999 # below 1000 x = 3 y = 5 # We have to subtract one sum of the multipliers of x * y because these multipliers take part in both of the sums of the multipliers of x an...
def cmdissue(toissue, activesession): ssh_stdin, ssh_stdout, ssh_stderr = activesession.exec_command(toissue) return ssh_stdout.read().decode('UTF-8') def commands_list(sshsession, commands): for x in commands: ## call our imported function and save the value returned resp = cmdissue(x, ...
List1 = [] List2 = [] List3 = [] List4 = [] List5 = [13,31,2,19,96] statusList1 = 0 while statusList1 < 13: inputList1 = str(input("Masukkan hewan bersayap : ")) statusList1 += 1 List1.append(inputList1) print() statusList2 = 0 while statusList2 < 5: inputList2 = str(input("Masukkan hewan berkaki 2 : ")...
"""curso = "Curso de Python" res = "Python" not in curso #imprime <FALSE> se existir o valor dentro da variável print(res)""" texto="Curso de Python" palavra ="python" res =palavra.upper()in texto.upper()#deixa a procura por palavras grande e texto grande resposta <True> print(res)
class dataStore: dataList=[] symbolList=[] optionList=[] def __init__(self): self.dataList=[] self.symbolList=[] self.optionList=[] def reset(self): self.dataList=[] self.symbolList=[] ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @author jsbxyyx # @since 1.0 class MessageType(object): TYPE_GLOBAL_BEGIN = 1 TYPE_GLOBAL_BEGIN_RESULT = 2 TYPE_GLOBAL_COMMIT = 7 TYPE_GLOBAL_COMMIT_RESULT = 8 TYPE_GLOBAL_ROLLBACK = 9 TYPE_GLOBAL_ROLLBACK_RESULT = 10 TYPE_GLOBAL_STATUS...
def scoreOfParentheses(S): total = 0 cur = 0 for i in range(len(S)): if S[i] == "(": cur += 1 elif S[i] == ")": cur -= 1 if S[i-1] == "(": total += 2**cur return total print(scoreOfParentheses("()")) # 1 print(scoreOfP...
c = input().split() W, H, x, y, r = int(c[0]), int(c[1]), int(c[2]), int(c[3]), int(c[4]) if r <= x <= W - r and r <= y <= H - r: print("Yes") else: print("No")
# -*- coding: utf-8 -*- numeros = [] for x in range(100): numeros.append(int(input())) print(max(numeros)) print(numeros.index(max(numeros))+1)
# Python Program to Differentiate Between type() and isinstance() class Polygon: def sides_no(self): pass class Triangle(Polygon): def area(self): pass obj_polygon = Polygon() obj_triangle = Triangle() print(type(obj_triangle) == Triangle) # true print(type(obj_triangle) == Polygon) #...
preço = float(input('O produto custava: R$')) novo = preço - (preço * 15 / 100) print('o produto custava {:.2f} na promoção com desconto de 5% ele custará: {:.2f}'.format(preço, novo)) #Para calcular a porcetagem é preciso motiplicar o valor do produto x o valor do desconto e dividir por 100.# #O resultado dubtrair pe...
s1 = (2, 1.3, 'love', 5.6, 9, 12, False) s2 = [True, 5, 'smile'] print('s1=',s1) print('s1[:5]=',s1[:5]) print('s1[2:]=',s1[2:]) print('s1[0:5:2]=',s1[0:5:2]) print('s1[2:0:-1]=',s1[2:0:-1]) print('s1[-1]=',s1[-1]) print('s1[-3]=',s1[-3])
r = requests.get('https://api.github.com/user', auth=('user', 'pass')) r.status_code # -> 200 r.headers['content-type'] # -> 'application/json; charset=utf8' r.encoding # -> 'utf-8' r.text # -> u'{"type":"User"...' r.json() # -> {u'private_gists': 419, u'total_private_repos': 77, ...}
class AttachedFile: def __init__(self, original_name: str, tmp_file_path: str, need_content_analysis: bool, uid: str) -> None: """ Holds information about attached files. :param original_name: Name of the file from which the attachments are extracted :param tmp_file_path: path to th...
class Joint: def __init__(self, name, min_angle: float, max_angle: float): self.name = name self.min_angle = min_angle self.max_angle = max_angle
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: wordSet = set(wordDict) # Converted to set for O(1) # table to map a string to its corresponding words break # {string: [['word1', 'word2'...], ['word3', 'word4', ...]]} mem = defaultdict(list) ...
# # PySNMP MIB module SONOMASYSTEMS-SONOMA-ATM-E3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-ATM-E3-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:09:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
def shift(a): last = a[-1] a.insert(0, last) a.pop() return a def f(a,b): a = list(a) b = list(b) for i in range(len(a)): a = shift(a) if a == b: return True return False f('abcde', 'abced')
def extractBinggoCorp(item): """ # Binggo & Corp Translations """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Jiang Ye' in item['title'] and 'Chapter' in item['title']: return buildReleaseMessageWithType(...
class BaloneyInterpreter(object): def __init__(self, prog): self.prog = prog def run(self): self.vars = {} # All variables self.lists = {} # List variables self.error = 0 # Indicates program error self.stat = list(self.prog) # Ord...
#!/bin/python3 def plus_minus(array): ratio_positive = round(sum(i > 0 for i in array) / len(array), 6) ratio_negative = round(sum(i < 0 for i in array) / len(array), 6) ratio_zero = round(sum(i == 0 for i in array) / len(array), 6) return ratio_positive, ratio_negative, ratio_zero def test_plus_min...
""" Dictionary examples. The intention is that you would use the code in the functions rather than the functions themselves. """ def create_dict(): """ Create a new dictionary. Example from: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict >>> a = dict(one=1, two=2, three=3) >>> b = {'one': ...
# Heap # CLRS Chapter 6 Page 152, 154, 157, 163, 164 # For CPython's implementation see: # https://hg.python.org/cpython/file/2.7/Lib/heapq.py def max_heapify(heap, node): left = _left(node) right = _right(node) largest = node if left < size(heap) and heap[largest] < heap[left]: largest = le...
def ascii(arg): pass def filter(pred, iterable): pass def hex(arg): pass def map(func, *iterables): pass def oct(arg): pass
n = int(input('Escreva um numero inteiro: ')) resto = n % 2 if resto == 0: print('O seu numero é par!') else: print('O seu numero é impar!')
galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]] print(galera[0]) print(galera[0][0]) print(galera[2][1]) for p in galera: print(p) for p in galera: print(p[0]) for p in galera: print(p[1]) for p in galera: print(f'{p[0]} tem {p[1]} anos de idade!')
#!/usr/bin/python3 '''General Class which is used for all the class ''' class GeneralSeller: def __init__(self,mechant_i): pass def start_product(self): pass class WishSeller(GeneralSeller): ''' ''' class AmazonSeller(GeneralSeller): pass class AlibabaSeller(GeneralSeller): pa...
# Python使用被称为异常的特殊对象来管理程序执行期间发生的错误. # 每当发生让Python不知所措的错误时, 它都会创建一个异常对象. # 如果你编写了处理该异常的代码, 程序将继续运行; # 如果你未对异常进行处理, 程序将停止, 并显示一个traceback, 其中包含有关异常的报告. # 处理ZeroDivisionError异常 try: print(5 / 0) except ZeroDivisionError: print('除数不能为零.') # else代码块 # try-except后包含else代码块, 依赖于try代码块成功执行的代码都应放到else代码块中 print...
upTo = int(input()) res = 0 for i in range(upTo): res += i print(res)
class Solution(object): def intersect(self, nums1, nums2): nums1_counter = collections.Counter(nums1) nums2_counter = collections.Counter(nums2) result = [] for k in nums1_counter.keys(): if k in nums2_counter: result.extend([k] * min(nums...
class CandidateViewer: def __init__(self, df): self.df = df def show_candidates(self): best_players_selections = ['2 players', '3 players', '4 players', '5 or more players'] weight_selections = [(1, 1.4), (1.5, 1.9), (1.9, 2.5), (2.5, 3.1), (3.1, 4)] cols = ['title', 'year', 'w...
def main(): q = int(input()) pre = [ 3, 5, 13, 37, 61, 73, 157, 193, 277, 313, 397, 421, 457, 541, 613, 661, 673, 733, 757, 877, 997, 1093, 1153, 1201, 1213, 1237, 1321, 1381, 1453, 1621, 1657, 1753, 1873, 1933, 1993, 2017, 2137, 2341, 2473, 2557, 2593, 2797, 2857, 2917, 3061, 3217, 3253, 3313, ...
#!/usr/bin/env python # -*- coding:UTF-8 -*- # # @AUTHOR: Rabbir # @FILE: /root/GitHub/rab_steam_packages/module/info.py # @DATE: 2021/05/21 Fri # @TIME: 16:46:52 # # @DESCRIPTION: Steam 账户信息模块 """ @description: Steam 账户信息类 ------- @param: ------- @return: """ class r_steam_info(): pass
# pkg.mod # descr # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: timestamp # # Copyright (C) 2013 Bengfort.com # For license information, see LICENSE.txt # # ID: __init__.py [] benjamin@bengfort.com $ """ """ ########################################################################## ## Imports ##...
class FileListing: dictionary: dict def __init__(self, dictionary: dict): self.dictionary = dictionary def __eq__(self, other): return self.dictionary == other.dictionary def __repr__(self): return {'dictionary': self.dictionary} @property def tenant(self): re...
# Builds #T# Table of contents #C# Compiling to bytecode #C# Building a project to binary #T# Beginning of content #C# Compiling to bytecode # |------------------------------------------------------------- #T# Python code is compiled from .py source code files, to .pyc bytecode files #T# in the operating syste...
def get_profile(name, age: int, *sports, **awards): if type(age) != int: raise ValueError if len(sports) > 5: raise ValueError if sports and not awards: sports = sorted(list(sports)) return {'name': name, 'age': age, 'sports': sports} if not sports and award...
a = int(input("a= ")) b = int(input("b= ")) c = int(input("c= ")) if a == 0: if b != 0: print("La solution est", -c / b) else: if c == 0: print("INF") else: print("Aucune solution") else: delta = (b ** 2) - 4 * a * c if delta > 0: print( ...
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 6 Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ def run(): N = 100 return sum(i for i in range(N+1))**2 - sum(i**2 for i in range(N+1)) if __name__ == "__main__": print(run())
# -- # Copyright (c) 2008-2021 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. # -- class SessionError(LookupError): def name(self): return self.__class__.__name__ # ...
class Solution: def checkIfExist(self, arr: List[int]) -> bool: s = set() for v in arr: if v * 2 in s or (v % 2 == 0 and v / 2 in s): return True s.add(v) return False
n = int(input("Dame un numero entero: ")) def factorial( n ): if n == 1: return n else: #llamada recursiva return n * factorial( n - 1 ) print("El factorial de: ",n,"es", factorial(n))
#!/bin/python3 rd = open("06.input", "r") fullSum = 0 validLetters = {"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" } while True: letters = {} count = 0 while True: line = rd.readline().strip() if not li...
''' done ''' ipAddress = '127.0.0.1' port = 21 name = "Pustakalupi" pi = 3.14 #tidak ada constant dalam Python 3 print("ipAddress bertipe :", type(ipAddress)) print("port bertipe :", type(port)) print("name bertipe :", type(name)) print("pi bertipe :", type(pi)) print(pi) del pi print(pi)
class Originator: _state = None class Memento: def __init__(self, state): self._state = state def setState(self, state): self._state = state def getState(self): return self._state def __init__(self, state = None): self._state = state ...
# please excuse me, I'm a C# and Rust developer with only minor Python experience :D # let's give it a go though! MAP = { 'a': "100000", 'n': "101110", 'b': "110000", 'o': "101010", 'c': "100100", 'p': "111100", 'd': "100110", 'q': "111110", 'e': "100010", 'r': "111010", 'f': "110100", 's': "01...
class _Node: """Private class to create a nodes for the tree""" def __init__(self, value): self.value = value self.left = None self.right = None self.next = None class Queue: """class Queue which implements Queue data structure with its common methods""" def __init__(s...
""" 252. Meeting Rooms Easy Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. Example 1: Input: intervals = [[0,30],[5,10],[15,20]] Output: false Example 2: Input: intervals = [[7,10],[2,4]] Output: true Constraints: 0 <= intervals....
# Desafio066: Desafio criar um programa que leia varios numeros de o valor total digitado e pare quando digitado 999. nu = int (0) controle = int(0) print('Se precisar sair digite 999') while True: nu = int(input('Digite um numero ')) if nu == 999: break controle = controle + nu print(controle)
__author__ = 'tony petrov' DEFAULT_SOCIAL_MEDIA_CYCLE = 3600 # 1 hour since most social media websites have a 1 hour timeout # tasks TASK_EXPLORE = 0 TASK_BULK_RETRIEVE = 1 TASK_FETCH_LISTS = 2 TASK_FETCH_USER = 3 TASK_UPDATE_WALL = 4 TASK_FETCH_STREAM = 5 TASK_GET_DASHBOARD = 6 TASK_GET_TAGGED = 7 TASK_GET_BLOG_POST...
class Professor: def __init__(self, nome): self.__nome = nome #conceito de encapusulamento self.__salaDeAula = None def nome(self): return self.__nome def salaDeAula(self, sala): self.__salaDeAula = sala def EmAula(self): return 'Em aula' class Sala: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def init(): pass def servers(): return {}
def processArray(l2): loss=[];mloss=0 for i in range(0,len(l2)): loss.append(l2[i][0]-l2[i][len(l2[i])-1]) if(len(loss)>0): mloss=loss.index(max(loss)) print(len(l2[mloss])) l=[] while True: a=int(input()) if(a<0): break l.append(a) ans=[] i=0 while(i<len(l)): k=l[i] tmp=[...
class Solution: def hammingWeight(self, n: int) -> int: n = bin(n)[2:] str_n = str(n) return str_n.count("1")
print('{:=^40}'.format(' lojas guanabara ')) p=float(input(' preço do produto')) print(p) print('escolha a opção de pagamento') pag=int(input('''[1] á vista com cheque/dinheiro; [2] á vista no cartão; [3] 2x no cartão; [4] 3x ou mais no cartão; ''')) print(pag) if pag == 1: print('valor á pagar R$ {} com 10% de d...
def coordinate_input(): x, y = input("X, Y Coordinates ==> ").strip().split(",") return float(x), float(y) def main(): coordinates = [] print("Type the coordinates in order; it means A,B,C...") while True: try: point = coordinate_input() coordinates.append(point) ...
''' Exemplo 1 c = 1 while c < 11: print(c) c += 1 print('Fim') ''' '''eXEMPLO 2 n = 1 while n!= 0: n = int(input('Digite um valor: ')) print('Fim') ''' ''' Exemplo 3 r = 'S' while r == 'S': n = int(input('Digite um valor: ')) r = str(input('Quer continuar? [S/N] ')).upper() print('Fim')''' ''' Exem...
#!/home/user/code/Django-Sample/django_venv/bin/python2.7 # EASY-INSTALL-SCRIPT: 'Django==1.11.3','django-admin.py' __requires__ = 'Django==1.11.3' __import__('pkg_resources').run_script('Django==1.11.3', 'django-admin.py')
def LB2idx(lev, band, nlevs, nbands): ''' convert level and band to dictionary index ''' # reset band to match matlab version band += (nbands-1) if band > nbands-1: band = band - nbands if lev == 0: idx = 0 elif lev == nlevs-1: # (Nlevels - ends)*Nbands + ends -1 (becaus...
print("+="*10, "TABUADA", "+="*10) while True: n = int(input("Você quer ver a tabuada de que número? 0 (zero) encerra o programa: ")) print("--"*5) if n == 0: break for c in range(1, 11): print(f"{n} x {c} = {n*c}") print("--"*5) print("Programa encerrado.")
# https://www.hackerrank.com/challenges/s10-standard-deviation/problem # Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input().strip()) all1 = [int(i) for i in input().strip().split()] u = sum(all1) / n v = sum(((i - u) ** 2) for i in all1)/n sd = v ** 0.5 print("{0:0.1f}".forma...
context_mapping = { "schema": "http://www.w3.org/2001/XMLSchema#", "brick": "http://brickschema.org/schema/1.0.3/Brick#", "brickFrame": "http://brickschema.org/schema/1.0.3/BrickFrame#", "BUDO-M": "https://git.rwth-aachen.de/EBC/Team_BA/misc/Machine-Learning/tree/MA_fst-bll/building_ml_p...
peso = float(input('Qual é o seu peso (KG) ? ')) altura = float(input('Qual e sua altura (M) ? ')) imc = peso / (altura ** 2) print('O IMC dessa pessoa é de {:.2f} '.format(imc)) if imc < 18.5: print('você está abaixo do peso normal') elif imc > 18.5 and imc <= 25: print('Você está no peso odeal ') elif imc > 2...
"""Relaydomains app constants.""" PERMISSIONS = { "Resellers": [ ("relaydomains", "relaydomain", "add_relaydomain"), ("relaydomains", "relaydomain", "change_relaydomain"), ("relaydomains", "relaydomain", "delete_relaydomain"), ("relaydomains", "service", "add_service"), ("re...
"""Defines error messages and functions.""" _BAD_NAME = "Bad name '{name}'." _BAD_LITERAL = "Bad literal '{literal}'." _NOT_IMPLEMENTED = "Not implemented:" class CheckError(Exception): def __init__(self, message): self.message = message def bad_name(name): _error(_BAD_NAME, name=name) def bad_...
OBJECT( 'VALUE', attributes = [ A( 'ANY', 'value' ), ] )
# Reading Error Messages # Read the Python code and the resulting traceback below, # and answer the following questions: # How many levels does the traceback have? # What is the function name where the error occurred? # On which line number in this function did the error occur? # What is the type of error? # What is...
""" This is a config file that will be used to generate the .piwall file """ # Network information master_ip = "0.0.0.0" # Wall.py for PiWall configs = { 'walls': { 'wall_name': { 'name': 'wall_name', 'height': '270', 'width': '1080', 'master_ip': '0.0.0.0' ...
def cons(a, b): def pair(f): return f(a, b) return pair def car(pair): return pair((lambda a, b: a)) def cdr(pair): return pair((lambda a, b: a))
"""Sub-module of the package.""" def hello_world(): """Print "Hello World".""" print("Hello World")
# Testing site base_url = 'http://localhost:80/demo' # Login account admin_auth_data = {'name': 'admin', 'password': 'admin'} login_url = base_url + '/api/auth' header = dict()
def add(x,y): '''Add two nos''' return x+y def subtract(x,y): '''Subtract two nos''' return y-x
""" Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa". Given "abcd", return "dcbabcd". """ __author__ = 'Daniel' class Solutio...
def word2features(sent, i): word = sent[i][0] postag = sent[i][1] features = [ 'bias', 'word.lower=' + word.lower(), 'word[-3:]=' + word[-3:], 'word[-2:]=' + word[-2:], 'word.isupper=%s' % word.isupper(), 'word.istitle=%s' % word.istitle(), 'word.isdigit=%s' % word.isdigit(), 'postag=' + postag, 'p...
words_single = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] words_teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] words_tens = ['','ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety...
#!/usr/bin/env python3 """ By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10,001st prime number? https://projecteuler.net/problem=7 """
def ping(): """Always returns 'pong'.""" return 'pong' def cowsay(): return r""" ___________________ < Hello Resource Hub! > =================== \ \ ^__^ (oo)\_______ ...
def same_wind(history, **kwargs): """Set the tropopause wind at their previous values for the new state :param history: Current history of state :type history: :class:`History` object """ assert history.size > 1 previous_state = history.state_list[-2] current_state = history.state_list[...
def test_Compare(): a: bool a = 5 > 4 a = 5 <= 4 a = 5 < 4 a = 5.6 >= 5.59999 a = 3.3 == 3.3 a = 3.3 != 3.4 a = complex(3, 4) == complex(3., 4.)
def spaces(n, i): countSpace= n-i spaces = " "*countSpace return spaces def staircase(n): for i in range(1, n+1): cadena = spaces(n,i) steps = "#"*i cadena = cadena+steps print(cadena) if __name__ == "__main__": tamanio = int(input("Ingresa el numero de esc...
#!/usr/bin/python2.4 # # Copyright 2011 Google 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/licenses/LICENSE-2.0 # # Unless required...
''' QUESTION: 344. Reverse String Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable a...
{ "targets":[ { "target_name":"stp", "sources":["calc_grid.cc"] } ] }