text
stringlengths
37
1.41M
class Solution(object): def removeElement(self, nums, val): j=0 for i in nums: if i!=val: nums[j]=i j+=1 return j s=Solution() a=[1] b=s.removeElement(a,3) print b,a
from collections import defaultdict class ClosedList: def __init__(self): self.data_dict = defaultdict(list) def insert(self, item): self.data_dict[hash(item)].append(item) def __contains__(self, item): items = self.data_dict[hash(item)] if items: return ite...
# CTI-110 # P4HW2 # Adam Klover # 06/30/18 total = 0 userNumber = float(input("Enter a number")) while userNumber > -1: total = total + userNumber userNumber = float(input("Enter a number")) print("The total is:",total)
# This project I will convert feet into inches # 07/06/18 # CTI-110 P5T2_FeetToInches # Adam Klover INCHES_PER_FOOT = 12 def main(): feet = int(input('Enter a number in feet: ')) print(feet, 'equals', feet_to_inches(feet), "inches.") def feet_to_inches(feet): return feet * INCHES_PER_FOOT...
import math from functools import reduce from itertools import combinations, chain from typing import List, Tuple, Set, Optional, Iterable, Dict Coord = Tuple[int, int] class Sudoku: def __init__(self, grid: List[List[int]]): size = len(grid) box_size = int(math.sqrt(size)) assert size =...
import math a = float(input('a:')) b = float(input('b:')) c = float(input('c:')) d = (b**2) - (4*a*c) if d >= 0: print("有两个解:") x1 = (-b-math.sqrt(d))/(2*a) x2 = (-b+math.sqrt(d))/(2*a) print("x1=",x1,"\t","x2=",x2) else: print("此方程没有解")
title = input("Enter a book title: ") author = input("Enter the author's name: ") pub_year = int(input("Enter the year that the book was published: ")) pages = int(input("Enter the number of pages in the book: \n")) age = 2019 - pub_year if age < 10: print("This book is younger than ten years old.\n") else: pri...
from nltk import WordNetLemmatizer from nltk.corpus import stopwords import re from bs4 import BeautifulSoup def review_to_words(raw_review, need_to_lemmatize=False): # Function to convert a raw review to a string of words # optional lemmatization # meaningful_words = review_to_wordlist(raw_review) ...
# Guessing game # What are the rules? # Write a program that plays a guessing game with the user # The user will think of a number and the program has to guess it # Range of possible numbers in between 1 and 100 # Program prints out rules at start # Player says "low" "h...
from random import randint cards = {0 : 'Ace', 1 :'King', 2 : 'Queen', 3 : 'Jack', 4 : '10', 5 : '9'} values = {'Ace' : 0, 'King' : 1, 'Queen' : 2, 'Jack' : 3, '10' : 4, '9' : 5} def play(): numbers_1 = [randint(0, 5) for _ in range(5)] numbers_1 = sorted(numbers_1) roll_1 = [cards[i] for i in numbers_1] ...
# Import dependencies import os import csv from collections import Counter # Point to reader file to import poll_read_file = os.path.join('Resources/election_data.csv') with open(poll_read_file, encoding="utf8") as poll_data: poll_reader = csv.reader(poll_data, delimiter=',') poll_header = next(poll_reader)...
# -*- coding: UTF-8 -*- for num in range(2): print (num) for a in range(1,10): print (a) for i in range(1,10,2): print (i) for letter in "python": if letter == "n": break print("当前字母为",letter)
""" 属性案例 创建Student类,描述学生类 学生具有Student.name属性 但是name格式不统一 """ class Student(): def __init__(self,name,age): self.name = name self.age = age self.setname(name) def des(self): print("Hi!My name is {0}".format(self.name)) def setname(self,name): self.name = name.upper()...
lado= input("Digite o valor correspondente ao lado de um quadrado:") perímetro= int(lado) * 4 área= int(lado)** 2 print("perímetro:",perímetro,"- área:",área)
class Triangulo: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def semelhantes(self, triangulo): lista1 = [self.a, self.b, self.c] lista2 = [triangulo.a, triangulo.b, triangulo.c] lista1_ord = sorted(lista1) lista2_ord = sorted(lista2) ...
l = int(input("digite a largura: ")) a = int(input("digite a altura: ")) linha = 1 coluna = 1 while coluna <= a: while linha <= l: print("#", end = "") linha = linha + 1 print() linha = 1 coluna = coluna + 1
num= int(input("Digite o número: ")) if num % 5 == 0: print ("Buzz") else: print (num)
num= int(input("Digite o número: ")) if num % 3 == 0: print ("Fizz") else: print (num)
#!/usr/bin/python firstname=raw_input("Enter the first name") Secondname=raw_input("Enter the second name") print (Secondname+ " "+ firstname)
#!/usr/bin/python #def bmi(a, b): # c = a/(pow(b, 2)) # print (c) #return c #height = input("Enter the height: ") #Weight = input("Enter the waight: ") #result = bmi(Weight, height) #print (result) def calculate_BMI(new_weight, new_height): new_bmi = new_weight/(pow(new_height, 2)) return new_bmi weigh...
from random import randint sim_ou_nao = input('''Olá, sou seu computador! Acabei de pensar em um número entre 1 e 10, quer tentar adivinhar qual é? ''').lower().strip() if sim_ou_nao == 'sim' or sim_ou_nao == 's': computador = randint(1, 10) acertou = False palpites = 0 while not acertou: jo...
num = int(input('Digite um nmero: ')) print(f'Analisando o valor {num}, seu antecessor {num - 1} e seu sucessor {num + 1}')
from random import shuffle a = input('Diga o nome do primeiro aluno: ') b = input('Diga o nome do segundo aluno: ') c = input('Diga o nome do terceiro aluno: ') d = input('Diga o nome do quarto aluno: ') alunos = [a, b, c, d] shuffle(alunos) print(f'A ordem sorteada é') print(alunos)
print('-'*150) galera = [] dados = [] a = contador = 0 q = int(input('''Quantas pessoas você quer cadastrar? (Se não sabe ainda, digite 0) ''')) if q == 0: x = 'sim' while x == 'sim' or x == 's': print('-' * 25) dados.append(input('Nome: ')) dados.append(int(input('Peso: '))) gal...
def fatorial(a, show=False): """-> CALCULA O FATORIAL DE UM NÚMERO :param a: O número a ser calculado :param show: (opcional) Mostra ou não a conta :return: O valor fatorial de a""" numero = a fatorial = 1 while numero != 1: fatorial *= numero numero = numero - 1 if s...
a = int(input('Digite um número: ')) b = int(input('Digite outro número: ')) if a > b: print('O primeiro número é maior que o segundo.') elif a < b: print('O primeiro número é menor que o segundo.') elif a == b: print('Os dois números tem o mesmo valor.')
from modulos_e_pacotes import modulo_moeda n = int(input('Digite um número: ')) print(f'O dobro de {n} é {modulo_moeda.dobrar(n)}') print(f'Aumentando em 10%, temos {modulo_moeda.aumentar(n, 10)}') print(f'Diminuindo em 13%, temos {modulo_moeda.diminuir(n, 13)}') print(f'A metade de {n} é {modulo_moeda.metade(n)}') #o ...
a = (int(input('Diga um número: '))) print('A sua tabuada de multiplicação é: ') print(a, 'x 1 =', (a*1)) print(a, 'x 2 =', (a*2)) print(a, 'x 3 =', (a*3)) print(a, 'x 4 =', (a*4)) print(a, 'x 5 =', (a*5)) print(a, 'x 6 =', (a*6)) print(a, 'x 7 =', (a*7)) print(a, 'x 8 =', (a*8)) print(a, 'x 9 =', (a*9)) print(a, 'x ...
qtd_maiores = 0 qtd_homens = 0 novinhas = 0 while True: print('-' * 20) nome = input('Nome: ').strip() sexo = input('Sexo: [M/F] ').strip().upper() idade = int(input('Idade: ')) if sexo == 'M' or sexo == 'MASCULINO' or sexo == 'MAS': qtd_homens += 1 elif (sexo == 'F' or sexo == 'FEMINI...
def printada(): print('') txt = input('Quer que eu printe o quê? ').strip() print('') print('=' * len(txt)) print(txt) print('=' * len(txt)) print('') a = int(input('Quantas vezes você deseja printar algo? ')) for x in range(a): printada()
from random import choice a = input('Diga o nome do primeiro aluno: ') b = input('Diga o nome do segundo aluno: ') c = input('Diga o nome do terceiro aluno: ') d = input('Diga o nome do quarto aluno: ') alunos = [a, b, c, d] sorteado = choice(alunos) print(f'O aluno sorteado é {sorteado}')
a = [input(f'Digite um valor para a posição {i}: ') for i in range(0, 5)] posmax = [] posmin = [] for pos, valor in enumerate(a): if valor == max(a): posmax.append(pos) elif valor == min(a): posmin.append(pos) print(f'O maior valor foi {max(a)}, e está na posição {posmax}.') print(f'O menor valo...
import random import time a = ['cara', 'coroa'] b = random.choice(a) print('Seja bem-vindo ao jogo cara ou coroa! ') print('Eu, o computador, irei jogar uma moeda virtual para o alto.') print('Você tentará adivinhar se caiu cara ou coroa.') y = input('Preparado? ') if y == 'sim': time.sleep(1) print('*Jogando a...
def notas(*num, Sit): """-> Analisa a nota e situação de um aluno :param num: uma ou mais notas do aluno (aceita várias) :param sit: opcional, indica se deve ou não mostrar a situação do aluno :return: dicionário com as notas (e talvez a situação) do aluno""" resultado = {'Total': len(num), 'Maior':...
x = (int(input('Insira um valor entre 0 e 10: ')), int(input('Insira outro valor entre 0 e 10: ')), int(input('Insira mais um valor entre 0 e 10: ')), int(input('Insira o último valor entre 0 e 10: '))) if x.count(9) == 1: print(f'O número 9 apareceu 1 vez.') elif x.count(9) == 0: print(f'O número 9...
a = input('Digite um número de 0 a 9999: ') print('Milhar:', a[0]) print('Centena:', a[1]) print('Dezena:', a[2]) print('Unidade:', a[3])
a = ('Flamengo', 'Palmeiras', 'Santos', 'Grêmio', 'São Paulo', 'Athlético', 'Internacional', 'Corinthians', 'Bahia', 'Goiás') print(f'Os times são: {a}') print(f'Os cinco primeiros colocados do Brasileirão são: {a[0:5]}.') print(f'Os últimos cinco colocados do Brasileirão são: {a[-5:]}.') print(f'Ordem alfabética: {sor...
a = [] x = 'sim' while x == 'sim' or x == 's': a.append(int(input('Digite um número: '))) sim = input('Quer continuar? [S/N] ').strip().lower() y = int(input('Qual número você quer saber se está dentro da lista? ')) if y in a: print(f'O número {y} está dentro sim!') else: print(f'O número {y} não está n...
num = int(input('Digite um número qualquer: ')) if num % 2 == 0: # se o resto da divisão num / 2 for igual a 0... print('O número é par.') else: print('O número é ímpar.') #começando a usar o %
from flask import Flask # importing Flask class from flask app = Flask(__name__) # name is a variable that stores the module name. we pass it to the Flask class # as an argument to create our flask server. other things it will configure it self. @app.route('/') # app.route is a decorater that tells the func...
#-*- coding: utf-8 -*- def r13(char): if (char >= 'a' and char <= 'z') or ( char >= 'A' and char <= 'Z'): if char.isupper() == False: if ord(char) + 13 > ord('z'): return chr(ord(char) - 13) else: return chr(ord(char) + 13) else: ...
def minimo(lista): """Essa funcao recebe uma lista como parametro e retorna o menor numero contido nela. A lista pode ter qualquer tipo de objeto. Exemplo: >>> minimo([3, 2, 1]) 1 """ menor = lista[0] for elemento in lista[1:]: if elemento < menor: menor = elemento ...
quantia_inicial = float(raw_input('Qual a quantia inicial? ')) quantia_mensal = float(raw_input('Qual a quantia mensal? ')) meses = int(raw_input('Quantos meses? ')) taxa = float(raw_input('Qual a taxa mensal? (em %) ')) multiplicador_mensal = 1 + (taxa / 100) montante = quantia_inicial nome_meses = ['janeiro', 'feve...
import os # Read file paragraph_one = os.path.join('paragraph_1.txt') # Initialize with open(paragraph_one, newline='') as file: #print(file.read()) print('Paragraph Analysis') print('============================') text = file.read() words = text.split(' ') word_count = len(words) p...
import random CHARACTER = "ABCDEFGHIJKLMNOPQRSTabcdefghijklmnopqrst123456789!@#$%^&*_-+~|:?" A_Password = input("Amout of password do you need : ") A_Password = int(A_Password) L_Password = int(input("enter the length of password : ")) p = 1 while A_Password: P_string = " " x = L_Password w...
import sqlite3 #To add table def add_table_to_db(): conn = sqlite3.connect('wz.db') print ("Opened database successfully") conn.execute('''CREATE TABLE NEWCOINDETAIL(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , NEW_COIN_DETAIL INT NOT NULL);''') print("added new table") conn.close...
""" La función map nos permite aplicar una función sobre cada uno de los elementos de una colección(listas,tuplas,etc,...). Haremos uso de esta función siempre que tengamos la necesidad de transformar el valor de cada elemento en otro. """ def doblar(numero): return numero*2 numeros = [2, 5, 10, 23, 50, 33]...
""" Un operario registra la producción de muebles de oficina que logra de lunes a sábado. Elaborar un algoritmo que nos diga si el operario recibe incentivos o no, sabiendo que el promedio de producción mínima es de 20 unidades a la semana. Tambien debe impirmir la producción semanal de muebles. """ print('\n') de...
numero_actual = 1 conteo_par = 0 conteo_impar = 0 suma_par = 0 suma_impar = 0 n = float(input(" Digite un número: ")) while numero_actual <= n: if numero_actual % 2 == 0: suma_par = suma_par + numero_actual conteo_par = conteo_par + 1 else: suma_impar = suma_impar + numero_actual ...
""" Función que regresa la persona cuya edad es mayor, dentro de una población de N personas -La función recibe una lista de diccionarios como parametro que contiene la población, las llaves del diccionario son 'nombre', 'edad' -En caso de que existan edades iguales regresar la primera...
''' CONDicional doble Estructura Algorítmica de la condicional doble Si <condición> entonces Acción(es) sino Accion(es) Fin - Si Determinar si un alumino aprueba o reprueba una asignatura, aprueba si el promedio de tres calififcaciones es mayor o igual a 3, en caso contrario...
# Pasando información a través de diccionarios ''' Los diccionarios ofrecen la posibilidad de empaquetar o encapsular varias varibles para facilitar el envio de parámetros. ''' # Encapsulamiento con Diccionario # Ejemplo2 def sumaVentas(dicVentas): sumatoria = 0 sumatoria += dicVentas['venta1'] sumatoria ...
for i in range(0, 10, 2): print("Estamoes en la iteracción " + str(i))
"""1. Introducir 10 números y sumar solo los números pares. Imprimir la sumatoria""" total = 0 for i in range(10): nuevoNumero = int(input("Inroduce un numero: ")) if nuevoNumero % 2 == 0: total += 1 print("Has introducido", total, "pares")
# Funciones de orden superior ''' Creamos la función crear_funcion. Esta función tiene la capacidad de crear nuevas funciones a partir del valor del parámetro. ''' # Envoltura de funciones def crear_funcion(operador): if operador == '+': def suma(valor1=0, valor2=0): return valor1 + valor2 ...
# Leer 2 números diferentes e indicar cuál es mayor # def cual_es_mayor(a, b): if (a > b) : return a else: return b #La aplicación inicia aquí a=int(input("Digite Número 1: ")) b=int(input("Digite Número 2: ")) respuesta = cual_es_mayor(a, b) print("El numero mayor es: ", respuesta)
""" Diseñar un algoritmo que imprima el número del artículo, código, precio y precio con descuento. Si el artículo tiene código 01, el descuento es del 10%, Si el artículo es diferente el descuento es del 20% (solo existen dos artículos). ALGORITMO Inicio precio, precio_desc: Real LEER nom_articulo, codigo,...
''' . . . . . . . . . . . . . . . . . . . . . . . . << >< >< >< << . . < >< ><< ><<< >< ><< . . << >< > >< >< >< >< . . << >< >< ><<<<<>< >< . . << >< ><< ><< >< ><< . . << ><><< ...
''' Implementation of Random Forest Algorithm based on Decision Trees and giving option of simple Bagged Trees. ''' import decisiontree as dt import random as rdm import numpy as np import math import cla_util as util #Sample from the given set data points def boots_trap(X, y, sample_size=None): samples = len(X)...
from tree import Node class SuffixTree: def __init__(self, text): self.__text = text + '$' self.__root = RootNode(self) self.__has_leaf_count = False @property def root(self): return self.__root @property def text_length(self): return len(self.__text) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import zipfile __arthur__ = "张俊鹏" # Cat vs. Dog Image Classification # Exercise 1: Building a Convnet from Scratch # Estimated completion time: 20 minutes # # In this exercise, we will build a classifier model from scratch that is able to distinguish dogs from...
""" Patrick Danford Lab 4, Rotate array Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. """ array1 = input("Enter a number: ") array2 = input("Enter another number: ") array3 = input("Enter yet another number: ") arra...
import random fortune = ['yes', 'no', 'perhaps', 'maybe', 'uncertain', 'the square root of pi', 'answer the question yourself', 'find the answer within your heart', 'never', 'that is funny', 'I do not know', ' I do not care', 'unfortunately', 'who knows?', 'when pigs fly'] print 'Ask me a question' option = random.choi...
#3.1.1-1.py """ File :timing.py Prints the running times for problem sizs that double. using a single loop. """ import time problemSize = 10000000 print("%12s%26s" % ("Problem Size", "Seconds")) for count in range(5): start = time.time() #the start of rhe algorithm work = 1 for x in range(problemSize): work +...
import random import os import subprocess GameLoop = True user_input = 'null' user_choice = 'null' cpu_choice = 'null' while True: print("1. Rock\n2. Paper\n3. Scissors") user_input = input() user_input = int(user_input) if user_input > 3 or user_input < 1: print("Please Enter a Valid Option!")...
"""My shelve. This module is used to save the workspace (all variables). And you can load these variables whenever you need them. """ import shelve import types def save_workspace(filename, names_of_spaces_to_save, dict_of_values_to_save): """Save the workspace. Args: filename (str): location to sa...
# this is the modified version of Number guessing game and also it takes any random no as winning # number. also it takes input frm user till user guesses the right number,also prints the no of # attempts user has done to guess #first we'll study about DRY principle of coding # Don't Repeat Yourself (dec lines of co...
import re N=int(input()) for _ in range(N): Phone_number=str(input()) pattern=re.compile(r'[789]\d{9}$') if pattern.search(Phone_number): print("YES") else: print("NO")
''' Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → Falses ''' def has22(nums): #We can exit as soon as we find a 2, 2 situation. #There will be a return statement inside the loop # 0 1 2...
''' QUESTON: The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. sleep_in(False, False) → True sleep_in(True, False) → False sleep_in(False, True) → True ''' def sleep_in(week...
x = "cat" #change this to different type if type(x) is float: print("IT IS A FLOAT"); elif type(x) is str: print("IT IS A STRING");
''' Given a string, return a new string where the first and last chars have been exchanged. front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' ''' def front_back(str): #Genearl Comment: This question is tricky so make sure you understand #what is happening. I STRONGlY suggest you ma...
''' Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "". first_two('Hello') → 'He' first_two('abcdefg') → 'ab' first_two('ab') → 'ab' '...
''' Given 2 arrays of ints, a and b, return True if they have the same first element or they have the same last element. Both arrays will be length 1 or more. common_end([1, 2, 3], [7, 3]) → True common_end([1, 2, 3], [7, 3, 2]) → False common_end([1, 2, 3], [1, 3]) → True ''' def common_end(a, b): #Approach 1...
# -*- coding: utf-8 -*- """ This module provides classes implementing game boards for Chutes & Ladders. """ __author__ = 'Hans Ekkehard Plesser' __email__ = 'hans.ekkehard.plesser@nmbu.no' class Board(object): """ Represents game board. This class provides a board of 90 squares (Egmont Libor AS, Oslo, ...
# -*- coding: utf-8 -*- ''' Implements a bacteria model. ''' import random class Bacteria: """Bacteria which die and multiply with fixed probabilities.""" # These parameters are defined at the class level p_death = 0.1 #: probability of death per cycle p_divide = 0.2 #: probability of cell divis...
# -*- coding: utf-8 -*- """ Implements a complete simulation. """ import numpy as np import random from .laboratory import Lab from .bacteria import Bacteria class Sim: """Define and perform a simulation.""" def __init__(self, n_dishes, n_a, n_b, seed, p_dth=0.1, p_div=0.1): """ Parameters ...
''' Brief illustration of re-plotting vs data-updating. @author: plesser ''' import matplotlib.pyplot as plt import numpy as np def replot(n_steps): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(0, n_steps) ax.set_ylim(0, 1) data = [] for _ in range(n_steps): data.app...
import random import math # generate prime numbers up to a given number so that encryption is random # within given list of primes def prime(value): p = [] c = [] for i in range(2, value+1): if i not in c: p.append(i) for j in range(i*i, value+1, i): c.appe...
# Homework1: Favorite Song song_title = "Raise your voice" artist = "F-killer" # F-killer means Fan killer. Formed for the special episode of Running man members_1 = "Kim Joong kook" members_2 = "Gummy" members_3 = "Haha" # I can also represent the members using this code: member1, member2, member3 = "Kim J...
class BMI: def __init__(self,name,age,weight,height): self.name = name self.age = int(age) self.weight = int(weight) self.height = float(height) self.BMI = float(self.weight/(self.height*self.height)) def say(self): print("{n}的BMI是{p}".format(n=self.name,p...
import sys import os from cv2 import cv2 import pose_estimator if __name__ == "__main__": if len(sys.argv) > 1: FILE_NAME = sys.argv[1] else: FILE_NAME = input("Input the file name of the image to analyse: ") #Check that the specified image exists. file_path = 'content/' + FILE_NAME ...
print("This is an example of print function") print("We're going to do store") print('he said "Hi".') print('we\'re going to the store') #Escape character print("Hi " + "there!") #Concatenation print("Hi", "there!") #Use comma to concatenate adding space print("Hi", 5) #print("Hi"+5) #Cannot convert 'int' object...
def simple_addition(num1, num2): answer = num1 + num2 print("The addition of", num1, "and", num2, "is", answer) print(answer) simple_addition(5,3) simple_addition(num2=5, num1=3)
__author__ = 'Shayan Fazeli' __email__ = 'shayan@cs.ucla.edu' import os from typing import Tuple def separate_path_and_file(filepath: str) -> Tuple[str]: """ This method simply separates the path and filename. Parameters ---------- filepath: `str`, required The filepath ending in file nam...
########################################### # DESCRIPTION: # Counts the number of lines and chars in the text file # # Example: # countlines.py file.txt ########################################### from sys import argv script, file_name = argv def count_lines(file_name): with open(file_name, "r") as f: l...
import ds from ds import * if __name__=="__main__": lst=[] while True: z=input("Enter a Number To append:") if z=="q": break lst.append(float(z)) print(lst) l=MergeSort.MergeSort(lst) l.sort() print(lst)
import ds from ds import * if __name__ =="__main__": ob=Queue.Queue() while True: print("1.Enter a number into Queue") print("2.Remove a number from Queue") print("3.Exit") t=int(input("Enter your choice")) if t==1: n=int(input("Enter the number")) ...
# Lee Farretta's movie project # version 1.0 # November 16, 2016 # # In this file, we define the class Movie. This class definition is used as the # data structure for the movies table and the movies website. Here we import # webbrowser and use show_trailer in order to launch the trailer_youtube when the # website is ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Print message 'Hello, world!'.mv :Author: LAL npacxx <npacxx@lal.in2p3.fr> :Date: February 2016 """ import sys # By convention, a function name must contain only lowercase characters and _. # string=None defines a default value for string and makes it optional. def ...
''' 상근날드 https://www.acmicpc.net/problem/5543 ''' minBuger = 987654321 minDrink = 987654321 for i in range(0, 5): if i < 3: temp = int(input()) minBuger = min(minBuger, temp) else: temp = int(input()) minDrink = min(minDrink, temp) print(minBuger + minDrink - 50)
# 전화번호 목록 # https://programmers.co.kr/learn/courses/30/lessons/42577 def solution(phone_book): answer = True for i in range(len(phone_book)): for j in range(len(phone_book)): if i == j : continue if phone_book[i].startswith(phone_book[j]): answer =...
""" 보석과 돌 파이썬 다운 방식 stone for stone in stones ['a', 'A', 'A', 'b', 'b', 'b', 'b'] stone in jewels for stone in stones [True, True, True, False, False, False, False] """ class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum(stone in jewels for ston...
""" 배열의 K번째 큰 요소 정렬을 이용한 풀이 """ import heapq from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return sorted(nums, reverse=True)[k-1]
""" 역순 연결 리스트 0. 데이터 출력 """ from typing import Optional # 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]: def ...
""" 페어의 노드 스왑 https://leetcode.com/problems/swap-nodes-in-pairs/description/ 1. 값만 교환 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head: Optional[ListNode]) -> Op...
""" 큐를 이용한 스택 구현 push(x) pop() 스택의 첫 번째 요소를 삭제한다. top() : 스택의 첫 번째 요소를 가져온다. empty() : 스택이 비어 있는지 여부를 리턴한다. 데크를 사용하여 퍈하게 구현하였다. 큐를 두개써서 구현하는 1 2 3 4 push(1) q : 1 재정렬 0번 : 1 push(2) queue : 1 2 재정렬 1번 : 2 1 push(3) queue : 2 1 3 재정렬 2번 : 3 2 1 """ impor...
""" 페어의 노드 스왑 https://leetcode.com/problems/swap-nodes-in-pairs/description/ 1. 값만 교환 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: Optional[ListNode])...
""" 2D 행렬 검색 2 https://leetcode.com/problems/search-a-2d-matrix-ii/ 첫 행의 맨 뒤에서 탐색 """ from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: # 예외 처리 if not matrix: return False # 첫 행의 맨 뒤 row = 0 ...
""" 704. Binary Search https://leetcode.com/problems/binary-search/ 이진 검색 모듈 """ import bisect from typing import List class Solution: def search(self, nums: List[int], target: int) -> int: index = bisect.bisect_left(nums, target) if index < len(nums) and nums[index] == target: ...