text
stringlengths
37
1.41M
def DisplayOptions(options): for i in range(len(options)): print("{} - {}".format(i+1, options[i])) choice = input(" Select option above or press enter to exit: ") return choice choice='x' options = ['load data', "export data", 'analyze & predict'] while choice: choice = DisplayOptions(optio...
# -*- encoding: utf-8 -*- """ 迭代器 http://anandology.com/python-practice-book/iterators.html http://nvie.com/posts/iterators-vs-generators/ 迭代器一定是可迭代的, """ from collections import Iterable, Iterator class yrange(object): """迭代器,yrange的对象既是可迭代的也是迭代器""" def __init__(self, n): self.n = n self.i ...
# -*- encoding: utf-8 -*- """ context manager """ from contextlib import contextmanager class SimpleFileCloser(object): def __init__(self, name, mode): self.name = name self.mode = mode def __enter__(self): """打开并返回文件""" print "opening file" self._file = open(self.na...
# -*-encoding: utf-8 -*- """ 后缀表达式求值 从左向右扫描表达式:遇到操作数入栈; 遇到操作符,弹出最近的两个操作数进行运算,然后将结果入栈; 当最后一个操作符被处理后u,栈中只剩一个值,就是后缀表达式的值 """ from datastructure.stack import Stack def do_math(operator, operand1, operand2): if not (operator and operand1 and operand2): raise ValueError("invalid operator") if operator == ...
# encoding: utf-8 import random """查找无序数组中的中位数""" from quick_sort import partition def find_mid_number(number_list): len_number = len(number_list) low, high = 0, len_number - 1 mid_index = len_number / 2 while high > low: j = partition(number_list, low, high) if j == mid_index: ...
# encoding: utf-8 class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ x = "{0:b}".format(x) y = "{0:b}".format(y) print x, y if len(x) > len(y): y = ''.join(['0' for _ in...
# encoding: utf-8 import random """ 二叉堆 https://www.cs.cmu.edu/~adamchik/15-121/lectures/Binary%20Heaps/heaps.html """ class Heap(object): """""" def __init__(self): self._heaplist = [0] self._currentsize = 0 def insert(self, val): self._heaplist.append(val) self._curren...
# 2. Find: # 1. The number of men with a PhD # 2. The number of women with a PhD import numpy as np import pandas as pd df_salary_gender = pd.read_csv("SalaryGender.csv") mens_phd = df_salary_gender.query("Gender == 1 and PhD == 1") womens_phd = df_salary_gender.query("Gender == 0 and PhD == 1") print("The number o...
# 4. Calculate the total number of people who have a PhD degree from SalaryGender CSV file. import pandas as pd csv_data = pd.read_csv('SalaryGender.csv') # filter data from rows people_phd = csv_data.query("PhD == 1") print("Total number of people with PhD degree" + str(len(people_phd)))
# 14. Create a randommatrix and Compute a matrix rank import numpy as np np_array = np.random.random(16).reshape(2, 2, 2, 2) print(np_array) array = np.array([4, 2, 7, 1]) temp = array.argsort() ranks = np.empty_like(temp) ranks[temp] = np.arange(len(array)) print(ranks)
# 1. Find the highest rated movie in the“Quest” story type. import pandas as pd df = pd.read_csv('HollywoodMovies.csv') highest_rate = df[df["Story"] == "Quest"]["RottenTomatoes"].max() highest_rated_movies = df[df["RottenTomatoes"] == highest_rate] print(highest_rated_movies)
import pandas as pd import matplotlib as plt df = pd.read_csv("BigMartSalesData.csv") df_grouped_year = df.query("Year == 2011").filter( ["Month", "Amount"]).groupby(["Month"], as_index=False).sum() # Plot Total Sales Per Month for Year 2011 as Bar Chart. x = df_grouped_year["Month"] y = df_grouped_year["Amount"...
# 3. Use SalaryGender CSV file. # Store the “Age” and “PhD” columns in one DataFrame and delete the data of all people who don’t have a PhD # https://medium.com/dunder-data/selecting-subsets-of-data-in-pandas-6fcd0170be9c # 3. Use SalaryGender CSV file. Store the “Age” and “PhD” columns in one DataFrame # and delete ...
import pandas as pd import matplotlib as plt df = pd.read_csv("BigMartSalesData.csv") df_grouped_year = df.query("Year == 2011").filter( ["Month", "Amount"]).groupby(["Month"], as_index=False).sum() # Plot Total Sales Per Month for Year 2011. x = df_grouped_year["Month"] y = df_grouped_year["Amount"] plt.plot(x...
# 10. By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. given_list = [12, 24, 35, 70, 88, 120, 155] del_index = [0, 4, 5] # Method 1 - Traditional ######################## # removing index from highest to lowest otherwise...
def matches(keyPresses, codes): result = [] for (i,code) in enumerate(codes): keyInd = 0 codeInd = 0 matched = True while keyInd < len(keyPresses): tmpChar = keyPresses[keyInd] tmpKeyCount = 0 tmpCodeCount = 0 while keyInd < len(key...
def getResult(a,op,b): result = 0 if op=='+': result = a+b elif op=='*': result = a*b else: return [-1,-1] return [result%256, result/256] print getResult(200,'+',3) print getResult(200,'+',0) print getResult(200,'+',56) print getResult(255,'+',0) print getResult(255,'+',255)...
def maxWait(arrival, service): readyToService = [] result = [] for (i,arr) in enumerate(arrival): if i == 0: readyToService.append(0) result.append(0) continue tmp1 = readyToService[i-1] + service[i-1] tmp = arrival[i-1] + service[i-1] if t...
name = 'giuseppe rosa' print(name.title()) print(name.upper()) print(name.lower()) print("---------------------") first_name = "giuseppe" last_name = "rosa" full_name = first_name + " " + last_name print(full_name) print('Hello, ' + full_name.title()) # \n gera tabulacao # \t quebra a linha print("----------------...
rivers = { 'nilo': 'egito', 'amazonas': 'brasil', 'ganges': 'india' } for river, country in rivers.items(): print('O {} percorre pelo(a) {}'.format(river.title(), country.title())) for river in rivers.keys(): print(river.title()) for country in rivers.values(): print(country.title())
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: print("Sorry, the file '{}' was not found!".format(filename)) else: # conta o numero aproximado de palavras no arquivo words = contents.split() num_words = len(words) print("The f...
comidas = ('macarrao', 'lasanha', 'feijoada', 'hamburguer', 'bolo') print('\nO cardapio é: ') for comida in comidas: print(comida.title()) comidas = ('peixe', 'carne de boi', 'saladas diversas', 'mouse', 'sorvete') print('\nO novo cardapio é: ') for comida in comidas: print(comida.title())
car = ['bmw', 'audi', 'toyota', 'subaru'] print(car) car.sort() print(car) car.sort(reverse=True) print(car) car = ['bmw', 'audi', 'toyota', 'subaru'] print('\nA lista original') print(car) print('\nA lista em ordem') print(sorted(car)) print('\nA lista em ordem novamente') print(car) print('\n A ordem reversa d...
r = input('Digite seu nome ') while r != "0": with open('guest_book.txt', 'a') as file_object: file_object.write("{}\n".format(r)) print("\nOlá, {}".format(r.title())) file_object.close() r = input('Digite seu nome ')
"""The owner of a store wants a program to track products. Create a product class to fill the requirements.""" class Product(object): def __init__(self, price, name, weight, brand, cost, status = 'for sale'): self.price = price self.name = name self.weight = weight self.brand = brand self.cost = ...
import requests # Set the request parameters url = 'https://pokeapi.co/api/v2/pokemon/1' # Fetch url print "Fetching url.." # Do the HTTP get request response = requests.get(url, verify=True) #Verify is check SSL certificate # Error handling # Check for HTTP codes other than 200 if response.status_code != 200: ...
"""docstring""" # Function definition is here def Mult(start, end, step): """will print numbers in range""" for i in range(start, end + 1, step): print i Mult(1, 1000, 2) Mult(5, 1000000, 5) # Function definition is here def Sum(list): """will print the sum of the passed in list's values""" sum = ...
class MathDojo(object): def __init__(self): self.result = 0 def add(self, *argv): for val in argv: if isinstance(val, (int, float, long, complex)): self.result += val else: for each in val: self.result += each return self def subtract(self, *argv): for val in...
"""will print out stars or first letter of strings a given number of times""" def stars(arr): for el in arr: if isinstance(el, str): print "".join(map(str, [el[0].lower()] * len(el))) else: print "".join(map(str, ['*'] * el)) x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] stars(x)
import turtle # the distance we want the pointer to travel each time DIST = 100 for y in range(0, 50): turtle.right(-20*y) turtle.forward(DIST) # for y in range(0,150): # turtle.circle(y*80) # turtle.forward(DIST)
# int a = 1 # print(a) # string b = "labas pasauli" # print(b) # float c = 1.5 # print(c) # booleans d = True e = False # none f = None vardas = "Benas" pavarde = "Jak" # =========================== x = 2 y = 3 print(x+y) print(f"{vardas} {pavarde}") # 3 kabutės = multiline komentaras - pradzioje 3 ir gale 3 ...
from flask import Flask, jsonify, request app = Flask(__name__) stores = [ {'name': 'my store', 'items': [{'name': 'shoes', 'price': 15.99}] } ] @app.route('/') # http://www.google.com/ def home(): return ("hello world") @app.route('/store', methods=['POST']) def create_store...
from random import randint # Generates a number from 1 through 10 inclusive random_number = randint(1, 10) guesses_left = 3 # Start your game! while guesses_left > 0: guess = int(raw_input ("What is your guess: ")) print "Your current guess is: " + str(guess) if guess == random_number: print "y...
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import sys import time # De tilfeldig generete testene er like for hver gang du kjører koden. # Hvis du vil ha andre tilfeldig genererte tester, så endre dette nummeret. random.seed(123) def find_maximum(x): n = len(x) if n == 1: return x[0...
#!/usr/bin/python3 # coding=utf-8 from queue import SimpleQueue class Node: def __init__(self, i, j): self.children = [None for _ in range(4)] self.parent = None self.pos = (i, j) def child(self, d, i, j): self.children[d] = Node(i, j) self.children[d].parent = self dr...
numbers = [] def getOffset(input=[], task=1): if task == 1: return 1 elif task == 2: return len(input) // 2 def main(): input = open('input.txt', 'r').read().rstrip() for index, char in enumerate(input): current = int(char) offset = getOffset(input, task=2) i =...
import random from datetime import datetime def ymd(): today = datetime.today() if today.hour < 12: day = today.day - 1 else: day = today.day return today.year, today.month, day def get_day8(day=None) -> str: ''' :return: something like '20200502' ''' if not day: ...
import random def generate_response(user_input): responses = [ "How interesting!", "Thanks for telling me!", "Fascinating!", "You don't say!" ] return random.choice(responses) def joke_response(): j_responses = [ "Why did it get so hot in stadium? There were no fans", "What did the tra...
import pandas as pd from numpy import * def compute_error(c,m,data): totalerror=0 for i in range(0,len(data)): x = data[i,0] y = data[i,1] totalerror += (y - (m * x + c)) ** 2 return totalerror/float(len(data)) def step_gradient(c,m,data,lr): c_gradient=0 m_gradient=0 N=float(len(data)) for i in range(0,le...
## guessing game with if, while, var and all previous knowledge ## using secret until with get it right secret_word = "Awana_Academy" ## this is the secret word guess = "" guess_count = 0## counter var guess_limit = 3 ## limit var out_of_guesses = False ### prompt the user to enter a word until they guess it c...
friends = ["ken", "yamo" , "Alex"] ## set list to a set of value [] means we are storing bunch of values print(friends) ## print list with index element 0 - 1 - 2 friends[1] = "bernard" print(friends[1])## value is going to b updated ## list can b very usefull to modify value in a data collection in python ...
## antes do exercício, só mais uma função: ## para transformarmos um número em String, usamos o método str(), ## e dentro dele colocamos o que converteremos ## Crie um código que peça nome, sobrenome, altura, e peso, e em seguida ## dê um print() no terminal, dizendo: ## 'NOME SOBRENOME tem um imc de IMC, logo está no...
## veremos aqui como funciona a estrutura condicional If ## agora ficaremos mais objetivos ## porém, antes de vermos como funciona um if, precisamos saber ## o que são valores booleanos. ## Resumindo: verdadeiro e falso. Estes são nossos valores. ## Em Python, são True e False. ## agora veremos quais são os operador...
from datetime import date, timedelta, datetime class Clock(): def __init__(self, date_time=''): self.__date_time = date_time def get_current_time(self): now = datetime.now() # now.strftime("%Y-%m-%dT%H:%M:%S") return now def calculate_time_diff(self, time2): time_1...
number_Array = list(map(int, input().split(' '))) previous_Number = number_Array[0] for index in range(1, 8, 1): if number_Array[index] < previous_Number: break if index == 7: print("ascending") exit() previous_Number = number_Array[index] previous_Number = number_Array[0] for index...
def solve(): sentence = list(map(str, input().split(' '))) max_Count = sentence.__len__() string_Count = 0 for count in range(0, max_Count): if sentence[count] is not '': string_Count += 1 print(string_Count) solve()
''' 주어진 수가 1, 2인 경우에는 1을 출력하게 한다. 이 부분은 피보나치의 첫 부분과 같다. 주어진 수가 1, 2가 아닌 경우에는 피보나치 수열을 계산하는 방식으로 결과값을 도출 후 출력하게 하는 함수이다. ''' def solution(number): result = 0 if number == 1 or number == 2: result = 1 else: previous1 = 1 previous2 = 1 for count in range(3, number+1, 1): ...
def solve(): number_Of_Integers = int(input()) number_Arrays = list(map(int, input().split(' '))) number_Of_Find_Integers = int(input()) find_Integers = list(map(int, input().split(' '))) for count in range(number_Of_Integers): temp = False for find_Count in range(number_Of_Find_Inte...
first_Num = int(input()) second_Num = int(input()) third_Num = int(input()) mul_Result = first_Num * second_Num * third_Num # Int를 String으로 변환하고 map(int, )함수를 쓰면 문자 하나씩 int로 형변환 하여 list타입으로 만든 후 변수에 저장 numbers= list(map(int, str(mul_Result))) numbers_Length = numbers.__len__() numbers_Count = [0 for col in range(10)] ...
"""29. WAP to find the second largest number of a list of numbers. Take the elements of list as input from the user.""" list5= list(input('list5 : ')) list5.sort() print('Second Largest digit :',list5[-2]) """30. WAP to rotate the elements of a list so that the element at the first index moves to the second index, th...
class Solution: def reverse(self, x: int) -> int: if x > 0: result = int(str(x)[::-1]) if result > 2**31-1:return 0 return result if x < 0: result = int(str(x*-1)[::-1])*-1 if result < (-1)*(2**31):return 0 ...
""" Function that takes in parameter ch and returns a boolean value for whether ch is a consonant or not """ def consonant(ch): # complete this function so it returns True iff `ch` is a consonant letter if len(ch) > 1: return False if ch == "b" or ch == "c" or ch == "d" or ch == "f" or ch == "...
""" Basic idioms for python learning """ import time def check_error(ls): if not isinstance(ls, list): raise TypeError("ls is not of type list") i = 0 while i < len(ls): if not isinstance(ls[i], str): raise TypeError("{}-th element of ls is not string".format(i)) i+=1 ...
""" Function that takes in a list and mimics Python's enumerate function and returns a list of tuples with each tuple containing the (index, element) of each element in ls """ def my_enum(ls): if type(ls) != list or len(ls) < 1: print("Wrong parameter type or list is empty") return ret_lis...
import sys import os try: filename = sys.argv[1] if not os.path.exists(filename): raise ValueError("File does not exist in directory") except IndexError as e: raise Exception("Filename was not passed to the program") except ValueError as e: raise Exception(e) try: mode = 'r' # 'w', 'a' ...
# # Lab1Ejercicio1.py # # DESCRIPCION: Programa que calcula el área de un circunferencia, # si se le proporciona el valor del radio, a traves de la formula, # Area = Radio*Radio*3,1416 # Dicho resultado es almacenado en Area. # # Autor: # Br. Jose Barrera # # Ultima modificacion: 16/01/2018 # # VARIABLES: # R: int ...
""" Lab03ejercicio2.py DESCRIPCION:Dado un entero positivo n dice si el entero es primo.\ Un número n es primo si sólo es divisible por 1 y n.\ Además, el programa imprime los divisores de n (distintos de 1 y n)\ a medida que consigue un divisor. Finalmente, se imprime si n es primo o no. Autor: Br. Jose Barrer...
#Print all permutations of the list. #This function runs through list and swaps number def permute(nums, ind): if ind >= len(nums): print(nums) else: i = ind while i < len(nums): swap(nums, i, ind) permute(nums, ind + 1) swap(nums, i, ind) ...
''' Input: ["acabcddd","bcbdbcbd","baddbadb","cbdddcac","aacbcccd","ccccddda","cababaab","addcaccd"] Output: [] dict = {'a': 2, 'c': 2, 'b':1, 'd':3} check 2nd word dict1 = {'b': 4, 'c': 2, 'd': 2} compare and take minimums: dict1 = {'b': 1, 'c': 2, } Build - compare - take min vals dict1= {'b': 3, 'a': 2, 'd': 3}...
#Question: Given a LinkedList, print it in reverse. class Node: def __init__(self, dataval): self.nextval = None self.dataval = dataval class LinkedList: def __init__(self): self.headval = None def makeList(linkedL, list): for ind in range(len(list)): if linkedL.headv...
''' str1 = "abcdef" str2 = "azced" {'d to c': 'Conversion', 'f to d': 'Conversion', 'b': 'Deleted', 'c to z': 'Conversion'} ''' def minimumEditDistance(str1, str2): #print(len(str1), len(str2)) matrix = [[0 for x in range(len(str1) + 1)] for y in range(len(str2)+1)] #printMatrix(matrix) matrix = init...
from random import randint import random def generate(): result="" while True: words = ("anything", "something", "easy", "difficult", "answer") words1=("sagar","keerthi","samhith","akshara","ravi","archana","dinesh") x=random.choice(words) y=random.choice(words1) numbers=randint(10000,99999) result=x+"-"+...
def to_rna(word): RNA="" x=['A','C','G','T'] nucleotides = {'A': 'U', 'C': 'G', 'G': 'C', 'T': 'A'} for letter in word: if(letter not in x): return"" else: RNA+=nucleotides[letter] return RNA print to_rna("ACGTGGTCTTAA")
# str = input("请输入:") # print("你输入的内容是: ", str) import os fo = open("hello.py0000", "a+") print(fo.name) print(fo.mode) print(fo.closed) print(fo.encoding.title()) print(fo.write("122\n1099jmbnmbnmbnmjjjjjjjjjjj212123------------------------")) print(fo.seek(0, 0)) print("read" + fo.read()) fo.close() ...
dict = {"name":"YINHENG", "age": 24, 2018: False} print(dict["name"]) print(dict["age"]) print(dict[2018]) dict["name"] = "Hello" dict["contry"] = "CHN" print(dict["name"]) print(dict["age"]) print(dict[2018]) print(dict["contry"]) del dict["contry"] print(dict["name"]) print(dict["age"]) print(d...
class People: __weight = 65 def __init__(self, name, age, work): self.name = name self.age = age self.work = work print("People init") def say_hello(self): print("hello, i am %s, i am %d years old, my job is %s, weight %s" %(self.name, self.age, self.wo...
# x = int(input("number1: ")) y = int(input("number2: ")) print(x+y)
# -*- coding: utf-8 -*- """ Created on Sun May 13 07:30:06 2018 @author: bgossage """ import threading """ * The WorkerThread provides the means for an * object of a given type to do work of a given type in * parallel. A WorkerThread is constructed using a callable * object and a WorkPile providing the work. The ...
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # utility.py - Helper functions def userChoice(options): madeValidChoice = False print(" -=-= Choose One =-=- ") for i in range(len(options)): print("[{}] : {}".format(i+1, options[i])) while not madeValidChoice: # TODO: parse safely to handle ...
""" 文件的打开 #1.打开open() f = open('test.txt', 'w') #2.读写操作write() f.write('helloworld') #3.关闭close() f = open('test.txt','r') f.close() f = open('1.txt','w') f.write('bbb') f.close() f = open('2.txt', 'a') f.write('xyz') f.close() f = open('test.txt', 'r') print(f.read()) f.close() f = open('test.txt', 'r') content =...
#需求:尝试打开test.txt(r),如果文件不存在,以只写方式打开(w) """ try: 可能发生错误的代码 except: 发生错误时执行的代码 try: f = open('test.txt', 'r') except: f = open('test.txt', 'w') try: print(num) except NameError: print('有错误NameError') import time try: f= open('test.txt') try: while True: content = f.read...
#用户输入目标文件 old_name = input('请输入您要备份的文件名') #规划备份文件的名字 #2.1提取后缀 index = old_name.rfind('.')#查找 #2.2组织新名字 new_name = old_name[:index] + '[备份]' + old_name[index:]#切片 #3备份文件写入数据 #3.1打开原文件与备份文件 old_f = open(old_name, 'rb') new_f = open(new_name, 'wb') #3.2如果不确定目标文件大小,循环读取写入 while True: con = old_f.read(1024)#1024代表读...
#Eliminar de una lista de palabras las palabras que se encuentren en una segunda #lista. Imprimir la lista original, la lista de palabras a eliminar y la lista resultante. import time import sys def eliminar_palabras_clave(lista,lista_clave,lista_nueva): for i in range(len(lista)): for j in ra...
# Desarrollar una función que reciba tres números enteros positivos y verifique si # corresponden a una fecha gregoriana válida (día, mes, año). Devolver True o False # según la fecha sea correcta o no. Realizar también un programa para verificar el # comportamiento de la función. # Año biciesto # p: Es divisible ...
# Trabajo Práctico 4: Cadenas de caracteres # 1. Desarrollar una función que determine si una cadena de caracteres es capicúa, sin # utilizar cadenas auxiliares. Escribir además un programa que permita verificar su # funcionamiento def cad_capicua(cad): largo = len(cad) flag = False mitad = largo / 2 #pri...
#Escribir funciones para: #a. Recibir una lista como parámetro y devolver True si la misma contiene algún #elemento repetido. La función no debe modificar la lista. #b. Generar una lista de 50 números aleatorios del 1 al 100 y comprobar con la #función anterior si existen elementos duplicados. Devolver True o False...
# Andy Wang # Bubble Sort def bubbleSort(bubbleList): n=len(bubbleList) NoMoreSwaps=False while not NoMoreSwaps: NoMoreSwaps=True for i in range(n-1): if bubbleList[i]>bubbleList[i+1]: NoMoreSwaps=False bubbleList[i],bubbleList[i+1]=bubbleList[i+1]...
#Andy Wang Queue nullPtr = -1 ##node initialisation class listNode: def __init__(self): self.value = "" self.nextPtr = nullPtr ##list functions class List(): ##list initialisation def __init__(self): self.freePtr = 0 self.startPtr = nullPtr self.endPtr = nullPtr s...
import numpy def gaussJordan(m): #creamos una matriz, un vector lleno de ceros, y el vector solucion con la misma cantidad de zeros matrix = numpy.zeros((m,m)) vector = numpy.zeros((m)) x = numpy.zeros((m)) #se llena la matriz y el vector for r in range(0, m): for c in range(0, m): ...
import numpy def matrizTranspuesta(): # se solicita al usuario el numero de columnas de las matrices col = int(input("NUMERO DE FILAS:")) # se solicita al usuario el numero de filas de las matrices row = int(input("NUMERO DE COLUMNAS:")) # Se declara la primer matriz con el num de filas y columnas dados...
# A simple python3 script to check for Proth number # first we Check if number is a power of two def isPowerOfTwo(n): return (n and (not(n & (n - 1)))) # then we check if the number is Proth def isProth(n): k = 1 while(k < (n//k)): if(n % k == 0): if(isPowerOfTwo(n//k)): ...
import imdb ia = imdb.IMDb() def findCompany(movie): # Find the companies that produce the given movie # getting the movie name movieName = movie['title'] # get the list of companies of the movie companies = movie.data['production companies'] if len(companies) == 0: print("IMDBot: There...
# Given a non-empty binary tree, find the maximum path sum. # For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. # Example 1: # Input: [1,2,3...
'''一个强密码应满足以下所有条件: 由至少6个,至多20个字符组成。 至少包含一个小写字母,一个大写字母,和一个数字。 同一字符不能连续出现三次 (比如 "...aaa..." 是不允许的, 但是 "...aa...a..." 是可以的)。 编写函数 strongPasswordChecker(s),s 代表输入字符串,如果 s 已经符合强密码条件,则返回0;否则返回要将 s 修改为满足强密码条件的字符串所需要进行修改的最小步数。 插入、删除、替换任一字符都算作一次修改。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/strong-password-checker 著...
'''峰值元素是指其值大于左右相邻值的元素。 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 你可以假设 nums[-1] = nums[n] = -∞。 示例 1: 输入: nums = [1,2,3,1] 输出: 2 解释: 3 是峰值元素,你的函数应该返回其索引 2。 示例 2: 输入: nums = [1,2,1,3,5,6,4] 输出: 1 或 5 解释: 你的函数可以返回索引 1,其峰值元素为 2;   或者返回索引 5, 其峰值元素为 6。 说明: 你的解法应该是 O(logN...
'''实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。 调用 next() 将返回二叉搜索树中的下一个最小的数。   示例: BSTIterator iterator = new BSTIterator(root); iterator.next(); // 返回 3 iterator.next(); // 返回 7 iterator.hasNext(); // 返回 true iterator.next(); // 返回 9 iterator.hasNext(); // 返回 true iterator.next(); // 返回 15 iterator.hasNext(); /...
'''Under a grammar given below, strings can represent a set of lowercase words. Let's use R(expr) to denote the set of words the expression represents. Grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a c...
'''In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in...
'''Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not modify the values in the list's nodes, only nodes itself may be changed. Example 1: Given 1->2->3->4, reorder it to 1->4->2->3. Example 2: Given 1->2->3->4->5, reorder it to 1->5->2->4->3. ''' # Definition for sing...
'''(这是一个 交互式问题 ) 给你一个 山脉数组 mountainArr,请你返回能够使得 mountainArr.get(index) 等于 target 最小 的下标 index 值。 如果不存在这样的下标 index,就请返回 -1。 所谓山脉数组,即数组 A 假如是一个山脉数组的话,需要满足如下条件: 首先,A.length >= 3 其次,在 0 < i < A.length - 1 条件下,存在 i 使得: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[A.length - 1] 你将 不能直接访问该山脉数组,必须通过 Moun...
#参考链接 https://blog.csdn.net/niushuai666/article/details/6662911 ''' 简单理解题意就是有很多点 给你一定量的连接 最后问有多少个独立的连通图。 解题思路就是并查集 参考上面的链接,很有趣可以加深理解。 用pre[]数组记录每个节点的上一级,如果两个节点拥有最终的上级,那么说明是同一个连通图的。 如果需要连接的两个点不在同一个连通图中,便通过使他们最终上级一样的方式连通他们。 同时可以通过路径压缩算法优化。 ''' class Solution: def union(self,n,s): ''' n:节点总个数 ...
# Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. # Example 1: # Input: num1 = "2", num2 = "3" # Output: "6" # Example 2: # Input: num1 = "123", num2 = "456" # Output: "56088" # Note: # The length of both num1 and num2 is < 110...
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its zigzag level order trave...
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. # Example: # Input: # [ # 1->4->5, # 1->3->4, # 2->6 # ] # Output: 1->1->2->3->4->4->5->6 ## http://www.cnblogs.com/grandyang/p/4606710.html # Definition for singly-linked list. class ListNode: def __init_...
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # Now consider if some obstacles are added to...
# Given a collection of numbers that might contain duplicates, return all possible unique permutations. # Example: # Input: [1,1,2] # Output: # [ # [1,1,2], # [1,2,1], # [2,1,1] # ] class Solution: def permuteUnique(self, nums): out = [] temp = [] nums.sort() def helper(nums...
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. # Your algorithm's runtime complexity must be in the order of O(log n). # If the target is not found in the array, return [-1, -1]. # Example 1: # Input: nums = [5,7,7,8,8,10], target = 8 # Ou...
# https://adventofcode.com/2018/day/6 def dist(a,b): return abs(b[0]-a[0]) + abs(b[1]-a[1]) def find_single_closest(x,y, points): closest_points = [] closest_dist = -1 for p in range(len(points)): d = dist(points[p], (x,y)) if d < closest_dist or closest_dist == -1: closest...
# -*- coding: utf-8 -*- import numpy as np def softmax(x): """Compute softmax values for each sets of scores in x.""" pass # TODO: Compute and return softmax(x) x = np.array(x) x = np.exp(x) x.astype('float32') if x.ndim == 1: sumcol = sum(x) for i in range(x.size): ...
generator = (x*x for x in range(3)) for x in generator: print x def yieldfuc(): for x in range(3): yield x*x mygener = yieldfuc() print mygener for i in mygener: print i