text
stringlengths
37
1.41M
''' Created on Apr 22, 2019 @author: Francesca ''' num = input("Enter your mark here:") if num =="4+": print("You got a 98" ) elif num =="4": print("You got a 90" ) elif num =="4-": print("You got a 83" ) elif num =="3+": print("You got a 78" ) elif num =="3": print("You got a 74...
import re import string def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) a = input() a = re.sub(r'[{}," "]'.format(string.punctuation), '', a) a = a.lower() print(is_palindrome(a))
n = int(input()) for i in range(1,2*n): for j in range(1,2*n): if i == j or i+j == 2*n: print('X',end='') else: print('+',end='') print('\n',end='')
def hcf(n1, n2): a = n1 while a%n2: a = a+ n1 b = n1*n2//a return b num1=int(input("")) num2=int(input("")) print(hcf(num1,num2))
""" This module implements various modules of the network. You should fill in code into indicated sections. """ import numpy as np from collections import defaultdict class LinearModule(object): """ Linear module. Applies a linear transformation to the input data. """ def __init__(self, in_features, out_fea...
class Triangle(object): number_sides = 3 def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 def check_angles(self): sum_angles = [self.angle1, self.angle2, self.angle3] if sum(sum_angles) == 180: return True else: return False cl...
import math class MinHeap: def __init__(self, list=[]): self.heap = list self.heap_size = len(list) self.build() def print_heap(self): i=0 while i< self.heap_size: j = min(self.left(i), self.heap_size) while i<j: print(self.heap[...
#### Basics of randomness & simulation ## Poisson random variable # Initialize seed and parameters # Poisson distribution, which is typically used for modeling the average rate at which events occur np.random.seed(123) lam, size_1, size_2 = 5, 3, 1000 # Draw samples & calculate absolute difference between lambda an...
# Libreria principal para hacer la aplicación Web. import streamlit as st # Libreria para manipular datos. import pandas as pd # Libreria para hacer cálculos numéricos import numpy as np import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go from wordcloud import WordC...
def primes(n): """Prints a statement about a number whether it is prime or not, for all the numbers in the range of 2 to n""" if n <= 0: print('Please provide numbers greater than 0') elif n > 0 and n < 2: print(n, 'is not a prime number') elif n == 2: print("2 is a prim...
import math def nums(): print("Numeric operations ") print('2+2 = ', 2+2) print('50 - 5*6 = ', 50 - 5*6) print('17/3 = ', 17/3) print('17//3 = ', 17//3) print('17%3 = ', 17%3) print('2**2 = ', 2**2) print('4**0.5 = ', 4**0.5) print('2**0.5 = ', 2**0.5) length = 17 width =...
# coding: utf-8 # ##### Shambhavi Srivastava # In[294]: import pandas as pd import numpy as np import sklearn.metrics as sm from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import train_test_split import matplotlib import matplotlib.pyplot as plt get_ipython().run_line_ma...
def titulo(msg): print('-'*30) print(f'{msg:^30}') print('-'*30) def soma(a, b): print(f'{a} + {b} = {a+b}') def contador(*val): # * desempacotamento tam = len(val) print(f'O tamanho de {val} = {tam}') def dobrar(lst): for p in range(0, len(lst)): lst[p] *= 2 print(f'Lista...
numeros = [[], []] for c in range(1, 8): num = int(input(f'Digite o {c}° valor: ')) if num % 2 == 0: numeros[0].append(num) else: numeros[1].append(num) numeros[0].sort() numeros[1].sort() print(f'Os valores pares digitados foram: {numeros[0]}') print(f'Os valores ímpares digitados foram: {n...
nome = input('Escreva seu nome completo: ').title().split() print('Seu primeiro nome é', nome[0]) print('Seu último nome é', nome[len(nome)-1])
from time import sleep def contagem(i, f, p): print('~' * 40) if p == 0: # Segunda opção para p == 0 print('passo = 1') p = 1 # end if p < 0: p = -p # p *= -1 print(f'Contagem de {i} até {f} de {p} em {p}') sleep(1) if i <= f: while i <= f: print(...
val = input('Digite algo\n >') print('O tipo primitivo desse valor é', type(val)) print('Possui apenas espaços: ', val.isspace()) print('é numérico: ', val.isnumeric()) print('é alfabético: ', val.isalpha()) print('é alfanumérico: ', val.isalnum()) print('está em maiúsculas: ', val.isupper()) print('está em minúsculas:...
times = ('Flamengo', 'Palmeiras', 'Corinthians', 'Atlético-GO', 'São Paulo', 'Fluminense', 'Atlético-MG', 'Fortaleza', 'Internacional', 'Sport', 'Ceará', 'Grêmio', 'Bahia', 'Santos', 'Chapecoense', 'Bragantino', 'Athletico-PR', 'América-MG', 'Cuiabá', 'Juventude') print('-=-' * 20) print(f'Li...
from random import randint num = randint(1, 10) print('Pensei em um número de 1 à 10, será que adivinhas?') palp = int(input(' >> ')) tent = 1 while palp != num: if num > palp: palp = int(input('Mais... \n >> ')) elif num < palp: palp = int(input('Menos... \n >> ')) tent += 1 print('Adivinh...
print('-'*30) print('Sequência Fibonacci \n') n = int(input('Quantidade de Termos: ')) print('-'*30) t0 = 0 t1 = 1 print('{} -> {}'.format(t0, t1), end='') c = 2 while c < n: t2 = t0 + t1 print(' -> {}'.format(t2), end='') t0 = t1 t1 = t2 c += 1 print(' -> fim')
valores = list() while True: val = int(input('Digite um valor: ')) if val not in valores: valores.append(val) print('Valor adicionado com sucesso...') else: print('* Valores duplicados não são adicionados à lista...') resp = str(input('Quer continuar? [S/N] ')).strip().upper()[...
try: a = float(input('Numerador: ')) b = float(input('Denominador: ')) r = a / b except: print('Infelizmente tivemos um problema :(') else: print(f'O resultado de {a} / {b} é {r:.1f}') finally: print('Volte sempre!') print() # ============================================ try: a = int(input...
## Use % to print every third word in the list list = ['alpha','beta','gamma','delta','epsilon','zeta','eta'] for i, letter in enumerate(list,1): if i % 3 == 0: print(letter)
class Person: # __init__ -- potreban je za inicijalizaciju kalase # svaki argument koji passamo unutra postaje obavezan za stvaranje objekta # argument self stavljamo zato sto on referira na bas taj objekt tipa da age nije univerzalan # nego je vezan za tu osobu nad kojom je pozvan, koju stvara def __init__(sel...
class NearEarthObject(object): """ Object containing data describing a Near Earth Object and it's orbits. # TODO: You may be adding instance methods to NearEarthObject to help you implement search and output data. """ def __init__(self, **kwargs): """ :param kwargs: dict of attribu...
#!/usr/bin/python import os questions = { "strong": "Do ye like yer drinks strong?", "salty": "Do ye like it with a salty tang?", "bitter": "Are ye a lubber who likes it bitter?", "sweet": "Would ye like a bit of sweetness with yer poison?", "fruity": "Are ye one for a fruity finish?" } ingredien...
# https://programmers.co.kr/learn/courses/30/lessons/12901 def solution(a, b): day = ["FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"] month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] count = 0 for i in range(a - 1): count += month[i] count += b return day[count % len(day) - 1...
# https://programmers.co.kr/learn/courses/30/lessons/17680 def solution(cacheSize, cities): if cacheSize == 0: return len(cities) * 5 answer = 0 cache = [] for city in cities: city = city.lower() if city not in cache: if len(cache) == cacheSize: cac...
# https://programmers.co.kr/learn/courses/30/lessons/12903 def solution(arr): answer = [] for i, number in enumerate(arr): if i == 0: answer.append(number) continue if arr[i - 1] != arr[i]: answer.append(number) return answer print(solution([1, 1, 3, ...
# https://programmers.co.kr/learn/courses/30/lessons/12912 def solution(a, b): answer = 0 if a > b: a, b = b, a for number in range(a, b + 1): answer += number return answer print(solution(3, 5)) print(solution(3, 3)) print(solution(5, 3))
#https://programmers.co.kr/learn/courses/30/lessons/12947 def solution(x): result = 0 k = x while k > 0: result += k % 10 k //= 10 if x % result == 0: return True else: return False print(solution(10)) print(solution(12)) print(solution(11)) print(solution(13))
import sys def factorial(number): product = 1 temp = 1 while(temp < (number + 1)): product = product * temp temp = temp + 1 return product number = int(sys.argv[1]) print(factorial(number))
import numpy as np # Import datasets, classifiers and performance metrics from sklearn import datasets, svm, metrics print('Running...') traindata = np.loadtxt('c:\\users\\samarths\\desktop\\the62s\\newtrain620.csv', delimiter = ',', skiprows = 1) nums, attribs1 = np.hsplit(traindata, [1]) binarynums, attribs = np.h...
import random def shouldendgame(): new_game = input("Do you want to play again? (y/n)\n") if new_game == "y": return False elif new_game == "n": return True else: print('Invalid input. Please enter "y" or "n"') return shouldendgame() print("Lets play guess the number!") print("The game will get harder...
# Set up your imports here! from flask import Flask from flask import request app = Flask(__name__) @app.route('/') # Fill this in! def index(): # Create a generic welcome page. return '<h1>Hello Puppers!</h1>' @app.route('/latin/<name>') # Fill this in! def puppylatin(name): # This function will ta...
# this will.... create a truth or dare? # if they pick a truth then the computer gives a statment that might put the human in akward position to answer # if they pick a dare they are told to do some harmless prank at school or on the weekend. # we need advanced data lists/arreays have a function that sets up those l...
def binomial(n, k): if (k == 1 or k == n): return 1 return binomial(n - 1, k) + binomial(n - 1, k - 1) n, k = [int(x) for x in input().split()] print(binomial(n, k))
from tkinter import * def login(): a = inp1.get() b = inp2.get() if a == 'gugas02' and b == "123456": lbl3['text'] = "bem vindo guh" lbl3['fg'] = "blue" else: lbl3['text'] = "Usuário ou senha invalida" lbl3['fg'] = "red" i = Tk() i.title("teste do Tk") lbl1 = Label(i,...
# # # Python 3.6.1 # # Author: Max Jacobsen # # # # Purpose: Create a GUI that allows the user to select a file to check for # newly created and modified files. Allow the user to select a folder to # move these files too. Create a button that initiates the process # # # Please change the file path for your desktop...
# Name: Jordan Strand # Date: June. 04, 2021 # Class: ICS3U1 # Description: This is the final summative, Jordan feels like he's gonna have a bad time # Creating the user input to start the game. print("HELLO, welcome to my game of YOU VS. TRASHMAN. \nIn this game you are tasked with defeating the evil Business tra...
# -*- coding: utf-8 -*- height = 1.75 weight = 80.5 bmi = weight/(height * height) print ('bmi:',bmi) if bmi < 18.5: print ('too thin') elif bmi < 25: print ('normal') elif bmi < 32: print ('too fat') else: print ('very fat')
def read_credentials(path: str) -> (str, str): """ Reads file given at path with format name=value """ with open(path, 'r') as f: user, pw = "", "" for line in f.readlines(): if "user" in line: user = line.split('=')[1].strip() elif "pw" in line: ...
# Get the users choices user1_answer = input("Player1, do you want to choose rock, paper or scissors? ").lower() user2_answer = input("Player2, do you want to choose rock, paper or scissors? ").lower() # Run the algorithm to see who wins if user1_answer == user2_answer: print("It's a tie!") elif user1_answe...
UserEntry = tuple(input("Please enter a list of numbers separated by a comma: ").split(",")) print(UserEntry) for num in UserEntry: num = int(num) if num % 5 == 0: print (num)
import urllib, re, os.path url = "http://www.pythonchallenge.com/pc/def/equality.html" fh = urllib.urlopen(url) in_comment = False chars = "" for line in fh: if in_comment: chars += "".join(re.findall('[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]',line)) elif re.match("<!--",line): in_comment = True else: pass...
#!/usr/bin/env python3 def last_8(some_int): """Return the last 8 digits of an int :param int some_int: the number :rtype: int """ return int(str(some_int)[-8:]) def optimized_fibonacci(f): #covering edge cases when f = 0 or 1 if (f==0): return 0 elif(f==1): return 1...
Comprar = input("indique su compra:") abducir = input("indique su abduccion:") estudiar = input("indique cuanto estudia:") if (jamon = "si") or ((abduccion ="si") and (dia = "J")) or (estudiar = "mucho")): print ("aprobar M03")
""" 날짜 : 2021/04/26 이름 : 김철학 내용 : 파이썬 String 예제 교재 p48 """ # 문자열 더하기 str1 = 'Hello' str2 = 'Python' str3 = str1 + str2 print('str3 :', str3) # 문자열 곱하기 name = '홍길동' print('name * 3 :', name * 3) # 문자열 길이(문자갯수) msg = 'Hello World' print('msg 길이 :', len(msg)) # 문자열 인덱스 print('msg 1번째 문자 :', msg[0]) print('msg 7번째 문자 :...
""" 날짜 : 2021/04/29 이름 : 김철학 내용 : 파이썬 내장함수 교재 p118 """ import math import random import time # 수학관련 # 절대값 r1 = abs(-5) print('r1 :', r1) # 올림값 r2 = math.ceil(1.2) r3 = math.ceil(1.8) print('r2 :', r2) print('r3 :', r3) # 내림값 r4 = math.floor(1.2) r5 = math.floor(1.8) print('r4 :', r4) print('r5 :', r5) # 반올림 r6 = round...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 7 21:20:36 2019 @author: ankit """ ## Building CNN to classify cats and dogs from keras.models import Sequential # To initialize the neural network from keras.layers import Convolution2D # To Convolute the input image from keras.layers import MaxP...
import pandas as pd #Creo un dataset mis_empleados = pd.DataFrame({"nombre": ["Nico", "Estefi", "Jorge", "Pedro", "Jesica", "Hector"], "edad":[33, 44, 29, 45, 37, 28], "sueldo":[40000, 66000, 102222, 32089, 342132, 234343]}) #Agrego una columna con el nuev...
# -*- coding: utf-8 -*- """ Created on Sat May 22 19:44:14 2021 @author: Nico """ #MAXIMO NUMERO EN UNA LISTA PROPIA numero_actual=0 mi_lista=[3,4,213,453,23,534,534354363415] for numero in mi_lista: if numero>numero_actual: numero_actual=numero print("EL MAXIMO NUMERO ES: ", numero_actual)
x=5 y=7 sumar_numeros = lambda x,y : x + y #usando variables print("resultado= ",sumar_numeros(x,y)) #usando numeros enteros print("resultado= ",sumar_numeros(10,7)) print("resultado= ",sumar_numeros( sumar_numeros(1,1),7 ) )
# -*- coding: utf-8 -*- """ Created on Sun Mar 21 18:11:27 2021 @author: la03237 """ #Defino cuantos numeros quiero que tenga la serie cuantosnumerosquiero = 100 #Defino las variables para la formula. Al principio serán 2: 0 y 1 numero1 = 0 numero2 = 1 #Defino variable la cual contendrá el resultado de la suma para...
#DEFINO LA VARIABLE CON EL TIPO DE CAMBIA exchange_rate_ARS = 150 #DEFINO LA FUNCION CON EL PARAMETRO PESOS def conversion(pesos): dolares = pesos/exchange_rate_ARS return dolares #LE PIDO AL USUARIO QUE INGRESE LA CANTIDAD DE PESOS #QUE SERÁ EL PARAMETRO DE LA FUNCION pesos = float(input("INGRESE CANTI...
import random def push(stack,element): stack.append(element) return stack def pop(stack): element = stack.pop() return stack,element def coppare(stack): #pila1=[] #pila2=[] #item=[] y = random.randint(1,len(stack)-1) stack = stack[y:len(stack)]...
''' Computes simple affine cipher ( (a*x + b) % 26 ) ''' Alphabet = ['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'] alpha = int(input("Enter alpha")) beta = int(input("Enter beta")) mess...
''' Takes message and key and encrypts message using provided key in a Vigenere cipher (currently no decrypting function) ''' Alphabet = ('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') def ...
i = 1 while i <= 10: print(i, end=' ', sep='!') i += 1 else: print('Конец цикла while') for _ in range(1, 11): print(_, end=' ') else: print('Конец цикла for')
#CS 2302 Data Structures Fall 2019 MW 10:30 #Sergio Ortiz #Assignment - Lab #2 - Part 2 #Instructor - Olac Fuentes #Teaching Assistant - Anindita Nath #September 20, 2019 #This program implements quicksort non - recursively #as well as select_modified_quick using a while loop class stackRecord(object): d...
#CS 2302 Data Structures Fall 2019 MW 10:30 #Sergio Ortiz #Assignment - Lab #5 #Instructor - Olac Fuentes #Teaching Assistant - Anindita Nath #November 1, 2019 #This program will compare the runtimes between #a Hash Table with Chaining and a Hash Table with #Linear Probing import Sergio_Ortiz_HashC as hc ...
""" Создайте список из всех нечётных чисел от 1 до 100 и передайте его в функцию, которая переставляет его элементы в случайном порядке (например, 99 11 43 19 … 7 91 3 1). Примечание: использовать метод random.shuffle не допускается. def shuffle_list(list_to_shuffle): # no return (shuffles list in place) pass ...
""" Написать функцию решения квадратного уравнения. def solve_quadratic_equation(a, b, c): # returns 2 values: either 2 roots, 1 root and None or 2 Nones """ import math def solve_quadratic_equation (a, b, c) : d = b**2 - 4*a*c #print(d) if d == 0: x = (- b) / (2 * a) return x, None ...
""" Два поезда движутся на скорости V1 и V2 навстречу друг другу. Между ними 10 км. пути. Через 4 км пути первый поезд может свернуть на запасной путь. При заданных скоростях узнать столкнутся ли поезда. def have_trains_crashed(v1, v2): # returns boolean value """ def have_trains_crashed(v1, v2): return 4 / v1 >= ...
""" Написать программу, которая преобразует имя переменной в формате snake_case в формат CamelCase. Для простоты считаем, что имя переменной всегда состоит из 3-х слов. Например: 'employee_first_name' -> 'EmployeeFirstName' """ snake_case = 'employee_first_name' snake_case_lst = snake_case.split('_') print(snake_case_l...
#!/usr/bin/python import Tkinter class SimpleApp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.entry = Tkinter.Entry(self) self.entry.grid(column = 2, ...
def who_wins(a, b): if(a == "R" and b == "S"): print("A Wins") return 1 elif(a == "S" and b == "P"): print("A Wins") return 1 elif(a == "P" and b == "R"): print("A Wins") return 1 elif(a == b): print("DRAW") return 0 else: print("B Wins") return 0 rounds = int(input()) comps = input() play...
## ejemplo ciclo for nombre = str(input("Ingrese su nombre: ")); edad = int(input("Ingrese su edad: ")); edad_lista = []; aux = 0; while aux < edad: aux = aux + 1; edad_lista.append(aux); for i in edad_lista: print(i); ## ejemplo con range lista_range = list(range(10)); print(lista_range[0])...
# -*- coding: utf-8 -*- import datetime import math import random class Solution(): def __init__(self): random.seed(datetime.datetime.now()) def crack(self, prec=3): inside, total, diff = 0, 0, 1 scale = 10 ** (prec) base = int(float('{0:.{prec}f}'.format(math.pi, prec=prec)...
# -*- coding: utf-8 -*- class Solution(): def is_valid(self, board, row): if row in board: return False col = len(board) for occupied_col, occupied_row in enumerate(board): if abs(occupied_row - row) == abs(occupied_col - col): return False ...
# -*- coding: utf-8 -*- class Solution(): def crack(self, nums, word_size=32): target = 0 for i in range(word_size): sum_bits = 0 x = 1 << i for j in range(len(nums)): if nums[j] & x: sum_bits += 1 if sum_bits %...
# -*- coding: utf-8 -*- def break_text(sentence, k): words = sentence.split() broken_text = [] char_count = -1 current_words = [] idx = 0 while idx < len(words): word = words[idx] if len(word) > k: return None if char_count + len(word) + 1 <= k: ...
# -*- coding: utf-8 -*- class Solution: def findMedianSortedArrays(self, nums1, nums2) -> float: half = (len(nums1) + len(nums2)) // 2 if (len(nums1) + len(nums2)) & 0x1 == 0: lhs = find_kth(nums1, nums2, half) rhs = find_kth(nums1, nums2, half + 1) return (lhs +...
#The player decides between two caves, which hold either treasure or certain doom. import random import time def introduction(): print('''Welcome Player. Would you like to play a game? (yes or no)''') decision = input('> ') while True: try: if decision.lower() == 'no' or decision.lower() == ...
""" Link to the question - https://leetcode.com/problems/next-permutation/ """ class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) i = n - 1 while i > 0: if nums[i...
import pygame from math import * import time win = pygame.display.set_mode((400, 600)) running = True t = pygame.time.Clock() fps = 1 def draw_circle(): circle_surface = pygame.Surface((100, 100)) pygame.draw.arc(circle_surface, (0, 0, 255), circle_surface.get_rect(), 0, 2 * pi) win.blit(circle_surface...
list=[1,2,2,3,'a','a'] # a=input("enter the values:") # list.append(a) x=[] for i in list: # for i not in x: if not i in x: x.append(i) print("non duplicate values:") print(x)
# coding=utf-8 print('时尚大方') if True: print'add', 'same line' else: print('adsfsfdfg') # raw_input("按下 enter 键退出,其他任意键显示...\n") ''' 注释 ''' total = 1 +\ 2 + \ 3 print(total) str = 'abcde' print str[-2], str[1:4], str[1:], str * 2 list = [1,2,3,4] print list[:], list * 2, list + [5,6] dict = { 'a': 1, "b": 2 }...
import math import generator # Funguje, jistota def baby_step(g, A, B, p): babystep_count = int(math.ceil(math.sqrt(p - 1))) pole = {} #baby step for i in range(babystep_count): pole[pow(g, i, p)] = i # giant step c = pow(g, babystep_count * (p - 2), p) for j in ...
from Pieces import * from Chessboard import * class Knight(Pieces): """ Represent the pieces of type Knight. """ name = 'Knight' VALUE = 30 def __init__(self, position, color): """ Create a Knight Based on the Piece class. :param position: Position on the chessboard ...
from Tkinter import * root = Tk() root.title("Prime Checker") global numberPrime introText = "Prime Checker. Programmed by David McClarty. Last updated 01/06/2018.\n\ Type your number into the program to see if your number is prime or not.\n\ Press the 'info' button for more information and more cool things this pro...
import random WoordLijst = ["computer", "python", "stoel", "tafel", "jas", "deur", "gordijn", "tapijt", "bloem"] #Dit onderdeel pakt met behulp van random een random woord uit de WoordLijst GeheimWoord = WoordLijst[random.randrange(0, len(WoordLijst))] GeradenLetters = [] levens = 10 #dit onderdeel kijkt of een lette...
# 存在重复 # 给定一个整数数组,判断是否存在重复元素。 # # 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 # # 示例 1: # # 输入: [1,2,3,1] # 输出: true # 示例 2: # # 输入: [1,2,3,4] # 输出: false # 示例 3: # # 输入: [1,1,1,3,3,4,3,2,4,2] # 输出: true class Solution: def containsDuplicate(self, nums): """ :type nums: List[int] :r...
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # # 有效字符串需满足: # # 左括号必须用相同类型的右括号闭合。 # 左括号必须以正确的顺序闭合。 # 注意空字符串可被认为是有效字符串。 # # 示例 1: # # 输入: "()" # 输出: true # 示例 2: # # 输入: "()[]{}" # 输出: true # 示例 3: # # 输入: "(]" # 输出: false # 示例 4: # # 输入: "([)]" # 输出: false # 示例 5: # # 输入: "{[]}" # 输出: true class Solution: def ...
import random, json, os def create_numbers_list(size, min, max, isFloat = False): numbers = [] for i in range(size): if isFloat: numbers.append(min + (random.random() * max)) else: numbers.append(random.randint(min, max)) return numbers def write_to_file(data, filename, location = ''): with open(f"{lo...
def recursive_binary_search(list, target): #returns true or false if target exists in list #list must be sorted for this to work if len(list) == 0: return False middleIndex = len(list) // 2 #get the value at middleIndex middleValue = list[middleIndex] #check if middleValue is target and return mi...
# app/schema/hash.py # Password encryption from passlib.context import CryptContext pwd_ctx = CryptContext(schemes=["bcrypt"], deprecated="auto") class Hash: """Helps to hash and verifying passwords using multiple algorithms.""" @staticmethod def bcrypt(password: str) -> str: """Encrypts the pa...
# !/usr/bin/env python """ Provides the gcd and s, t of Euclidian algorithim for a given m, n The algorithim states that the GCD of 2 numbers is equal to a product of the one of the numbers and a coefficient, s added with the product of the remaining number and a coefficient, t. """ def gcd(m,n,buffer): """Retu...
''' A Convolutional Network implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' from __future__ import print_function import numpy as...
#Sequal DB information ''' This is the file that configures the sqlite DB to store high scores. This file is only run once to construct the SQL DB ''' import sqlite3 database_file = "score_db.db" #You can write raw SQL as a string sql_create_scores_table = ("""CREATE TABLE IF NOT EXISTS high_scores ( ...
import sqlite3 class DictDB(): def __init__(self, filename="devild.db"): self.createDB(filename) def createDB(self, filename="devild.db"): self.conn = sqlite3.connect(filename) self.cur = self.conn.cursor() self.cur.executescript(''' CREATE TABLE IF NOT EXISTS Dict ( ...
s = input() if(len(s) >= 6 and s[2] == s[3] and s[4] == s[5]): print('Yes') else: print('No')
#coding: UTF-8 import sys class Algo: @staticmethod def greatest_common_divisor(x, y): while True: r = x%y if r==0: print(y) break x, y = y, r l = list(map(int, input().split())) X = l[0] Y = l[1] Algo.greatest_common_divisor(X, Y)
import sys N = int(input()) S = input() for s in S: if s == 'Y': print('Four') sys.exit() print('Three')
nums = input().split() a = int( nums[0]) b = int( nums[1]) c = int( nums[2]) if a > b: tmp = a a = b b = tmp if b > c: tmp = b b = c c = tmp if a > b: tmp = a a = b b = tmp print( a, b, c)
import math N=int(input()) a=math.ceil(N/(1.08)) if math.floor(a*1.08)==N: print(a) else: print(':(')
n = int(input()) count = 0 for i in range(n + 1): if i % 2 != 0: count += 1 print(float(count / n))
class Digraph: #入力定義 def __init__(self,vertex=[]): self.vertex=set(vertex) self.edge_number=0 self.vertex_number=len(vertex) self.adjacent_out={v:{} for v in vertex} #出近傍(vが始点) self.adjacent_in={v:{} for v in vertex} #入近傍(vが終点) #頂点の追加 def add_vertex(self,*adder...
input_line = input().split() if int(input_line[0]) + int(input_line[1]) + int(input_line[2]) != 17: print("NO") pass elif input_line[0] == input_line[1] == "5": print("YES") pass elif input_line[1] == input_line[2] == "5": print("YES") pass elif input_line[0] == input_line[2] == "5": print(...
def bubbleSort(n,A): flag = True cnt = 0 while flag: flag = False for j in range(n-1, 0, -1): if A[j-1] > A[j]: A[j-1],A[j] = A[j],A[j-1] cnt += 1 flag = True print(*A) print(cnt) if __name__ == '__main__': N = int(inpu...