blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
e4617c7da4f6dcd3cfcfcad00ca4672e8f891491 | jerede/Desenvolvimento-Python | /ExecicioJorge/Ex01Q1.py | 396 | 3.953125 | 4 | #1) Faça um Programa que peça as 4 notas bimestrais e mostre a média.
print ('Avaliação do Aluno')
nota1 = float(input('Digite a primeira Nota: '))
nota2 = float(input('Digite a segunda Nota: '))
nota3 = float(input('Digite a terceira Nota: '))
nota4 = float(input('Digite a quarta Nota: '))
media = (nota1 + nota2 + nota3 + nota4)/4
print('A sua média é: %s' % media)
|
818d8383004fd4057a5046e41c9088bacbd54758 | marejak023/leibniz-series | /main.py | 2,214 | 3.671875 | 4 | #Author: marejak023
#Contact: marejak023@gmail.com, marejak023.wz.cz
#Date: 06/02/2021
import matplotlib.pyplot as plt
import numpy as np
import math
#code for computing Leibniz series
k = 1 # denominator
s = 0 # sum
# x and y array for storing plot values
y = np.array([])
x = np.array([])
PI_CONST_LINE = np.array([]) # pi contstant for y reference value (set for 15f points from math package)
sum_range = int(input("\nEnter a range: ")) # range for the series
for i in range(sum_range):
# even numbers have + sign
if i % 2 == 0:
s += 4/k
else: # changes + to - sign
s -= 4/k
k += 2
y = np.append(y, s) # adds current value of sum of the series to the y array
PI_CONST_LINE = np.append(PI_CONST_LINE, math.pi) # append math.pi values to PI_CONST_LINE array, so pi y reference value is for every n (sum_range) = math.pi
# stores value in x array (sum_range = n [number of steps])
for i in range(sum_range):
x = np.append(x, i)
error = ((s-math.pi)/math.pi)*100 # Percentage value of error
# printing out computed values
print("\nApproximate value of pi using Liebniz series is: ", "{:.15f}".format(s))
print("Real value using math python constant math.pi is: ", math.pi)
print("Value of error in % is: ", abs(error), "%")
print("\nApproximate value is limited to 15 float digits, so it matches the internal float value of math.pi")
# making plot
# titles & labels
plt.figure().canvas.set_window_title("Pi approximation using Leibniz series")
plt.title(r"$\pi$ approximation using Leibniz series $\frac{\pi}{4}=\sum_{n=0}^{\infty}\frac{(-1)^n}{2n+1}$", y = 1.05) # y is for title positioning on y axis
plt.xlabel(r"n", fontsize = 20) # r is for using mathmode ($$ for entering mathmode, same as LaTeX notation)
plt.ylabel(r"$S_n$", fontsize = 20)
plt.plot(x, y, marker = 'X', mec = "#0085E7", mfc = "#FFF", c = "#0085E7", ls = '--') # plots Leibniz series, mec = marker edge color, mfc = marker face color c = linecolor, ls = linestyle
plt.plot(x, PI_CONST_LINE, ls = '-.', c = "#000") # plots constant line with y value = pi (from math.pi, 15f points) & x value = n (sum_range)
plt.grid(linestyle = '--')
plt.show() # display plot |
9a1b268386b4652bf50af0365892ef7338329727 | ellenfb/EE381 | /Prj_5_HypothesisTesting/Project5_Part2_EllenBurger.py | 933 | 3.6875 | 4 | #header
import matplotlib.pyplot as pmf
import random
p = 0.5 # Probablility of success for original system
n = 18 # Number of trials
Y = [] # Contains binomial RVs
b = [0] * (n+1) # List of n + 1 zeroes
N = 100 # Number of experiments performed
for j in range(N):
# Bernoulli random variable
for i in range(n):
r = random.uniform(0,1)
if r < p:
x = 1
else:
x = 0
Y.append(x)
outcome = sum(Y) # Number of successes from 0 to n
b[outcome] = b[outcome] + 1 # Record of successes for bar plot
Y.clear()
for i in range(n+1):
b[i] = b[i]/N # Probabilities
p = 0
cv = int(input('Enter a choice for the CV.'))
for i in range(cv, 19):
p = p + b[i]
print('For a critical value of', cv, 'the probability of rejecting the old system in favor of a new system that is no better than is', p,'.')
#cv = 13, 1/20 or the 5% rule |
f86364ba2cb64e69ee22736009ae72f4d8bbdfd3 | newmancodes/python_exercises_for_tony | /string_sequences.py | 376 | 3.953125 | 4 | string_values = list(input('Enter a comma separated list of strings: ').split(','))
max_found = ''
for start in range(len(string_values[0])):
for end in range(len(string_values[0][start:])):
look_for = string_values[0][start:start+end+1]
if len(look_for) > len(max_found) and look_for in string_values[1]:
max_found = look_for
print(max_found) |
4ddc77618d10ad035872e94afdb90d41383685f9 | BrianASpencer/CSC310Homework | /Homework-1/Hw1.py | 3,775 | 4.28125 | 4 | # Name: Brian Spencer
# Date: 1/27/19
# Course: CSC 310
# Project: Homework 1
# Function to determine if there is at least one distinct pair of
# elements in an array whose product is odd.
# An array is the only required input.
def isOdds(a):
n = len(a)
for i in range(0, n): #iterate over array twice
for j in range(0, n):
if i != j: #ensures only distinct pairs are checked
if (a[i]*a[j])%2 != 0: #an odd product will result in 1 at this check
return(True)
return(False) #return false after finding no pairs
oddsTest1 = [1,2,4,8,16,32,64,77]
print(isOdds(oddsTest1))
oddsTest2 = [3,0,0,1]
print(isOdds(oddsTest2))
oddsTest3 = [2,6,14,0]
print(isOdds(oddsTest3))
oddsTest4 = [2,2,2,2,1]
print(isOdds(oddsTest4))
class Ham :
x = 0
y = 0
xstr = ""
ystr = ""
#Constructor used for the two inputs and their binary equivalent.
def __init__(self, x, y):
self.x = x
self.y = y
self.xstr = self.dToB(self.x)
self.ystr = self.dToB(self.y)
# Function to convert a decimal number to binary.
# Takes a number as an input.
def dToB (self, n):
s = ""
while n > 0: #While n > 0, add an appropriate character onto a string to convert to binary
if n%2 == 0:
s = "0" + s
else:
s = "1" + s
n = n//2
return s #return string
# Function to find the Hamming Distance between two numbers.
# Requires two strings(part of object) to compare and output difference.
def hamDis (self):
s = self.xstr
t = self.ystr
sl = len(s)
tl = len(t)
n = abs(sl - tl) #determine how much padding the shorter string needs
for i in range (0, n):
if sl < tl: #pad the shorter string with 0's
s = "0" + s
else:
t = "0" + t
cnt = 0
for i in range(0, max(sl, tl)): #counting each difference in characters between strings
if s[i] != t[i]:
cnt += 1
#printing information about each number and then their Hamming Distance
print("x:")
print("dec", self.x)
print("bin", s)
print("y:")
print("dec", self.y)
print("bin", t)
print("Hamming Distance:", cnt)
if __name__ == "__main__":
print("Enter x: ", end= ' ')
x = int(input())
print("Enter y: ", end=' ')
y = int(input())
h = Ham (x, y)
h.hamDis()
words = []
while True: #allows for many inputs
try:
word = input("Enter an input: ")
words.append(word) #add inputs to a list
except EOFError as error:
# Output expected EOFErrors.
for i in range(0, len(words)):
print(words[len(words) - (i+1)]) #once Ctrl+D is inputted, prints out the inputs backwards
break
# Function to output all possible permutations
# of an array of numbers
# Takes an array, zero, and the length of that array as parameters.
def permute(a, l, r):
if l == r-1: #base case, will print once lower and upper bound are the same index
print(a)
else:
for i in range(l, r):
temp = a[l] #these swaps make the starting index for a list with the elements past 'l' to swap
a[l] = a[i]
a[i] = temp
permute(a, l+1, r)
temp = a[l] #undo the swap before
a[l] = a[i]
a[i] = temp
permTest1 = ['z','y','x']
permute(permTest1, 0, len(permTest1))
permTest2 = [0,4,8,6]
permute(permTest1, 0, len(permTest2)) |
6604766302b7fb15c5cb38cea1724f43a7a61f28 | piri07/PythonPractice | /DSA/Bellman.py | 1,328 | 4.03125 | 4 | class Graph:
def __init__(self,vertices):
self.V = vertices
self.graph=[]
def addEdge(self,u,v,w):
self.graph.append([u,v,w])
#prints the solution
def printArr(self,dist):
print("vertex distance from Source")
for i in range(self.V):
print("{0}\t\t{1}".format(i, dist[i]))
# The main function that finds shortest distances from src to all other vertices using Bellman-Ford algorithm. The function also detects negative weight cycle
def BellmanFord(self,src):
#initalize all as infinite except the source node
dist =[float("Inf")]*self.V
dist[src]=0
for i in range(self.V - 1):
for u,v,w in self.graph:
if dist[u] !=float("Inf") and dist[u] + w < dist[v]:
dist[v]= dist[u] + w
for u,v,w in self.graph:
if dist[u]!=float("Inf") and dist[u] + w < dist[v]:
print("graph doesnt containt any negative cycle")
return
self.printArr(dist)
g = Graph(5)
g.addEdge(0, 1, -1)
g.addEdge(0, 2, 4)
g.addEdge(1, 2, 3)
g.addEdge(1, 3, 2)
g.addEdge(1, 4, 2)
g.addEdge(3, 2, 5)
g.addEdge(3, 1, 1)
g.addEdge(4, 3, -3)
# Print the solution
g.BellmanFord(0)
|
7ef715dd78c6282a3a8d337a8ba69c96e4c3607f | piri07/PythonPractice | /DSA/binomialcoeff.py | 1,509 | 3.8125 | 4 | # A Dynamic Programming based Python Program that uses table C[][]
# to calculate the Binomial Coefficient
# Returns value of Binomial Coefficient C(n, k)
def binomialCoef(n, k):
C = [[0 for x in range(k+1)] for x in range(n+1)]
# Calculate value of Binomial Coefficient in bottom up manner
for i in range(n+1):
for j in range(min(i, k)+1):
# Base Cases
if j == 0 or j == i:
C[i][j] = 1
# Calculate value using previously stored values
else:
C[i][j] = C[i-1][j-1] + C[i-1][j]
return C[n][k]
# Driver program to test above function
n = 5
k = 2
print("Value of C[" + str(n) + "][" + str(k) + "] is "
+ str(binomialCoef(n,k)))
#now by using memoization
def binomialCoeffUtil(n, k, dp):
# If value in lookup table then return
if dp[n][k] != -1:
return dp[n][k]
# Store value in a table before return
if k == 0:
dp[n][k] = 1
return dp[n][k]
# Store value in table before return
if k == n:
dp[n][k] = 1
return dp[n][k]
# Save value in lookup table before return
dp[n][k] = (binomialCoeffUtil(n - 1, k - 1, dp) +
binomialCoeffUtil(n - 1, k, dp))
return dp[n][k]
def binomialCoeff(n, k):
# Make a temporary lookup table
dp = [ [ -1 for y in range(k + 1) ]
for x in range(n + 1) ]
return binomialCoeffUtil(n, k, dp)
# Driver code
n = 5
k = 2
print("Value of C(" + str(n) +
", " + str(k) + ") is",
binomialCoeff(n, k))
|
f9886344b8c61878d322680525f4f4afe8220042 | abbi163/MachineLearning_Classification | /KNN Algorithms/CustomerCategory/teleCust_plots.py | 873 | 4.125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('E:\Pythoncode\Coursera\Classification_Algorithms\KNN Algorithms\CustomerCategory/teleCust1000t.csv')
# print(df.head())
# value_counts() function is used to count different value separately in column custcat
# eg.
# 3 281
# 1 266
# 4 236
# 2 217
# count() function counts the number of value in column custcat, or sum of all value_counts(), here 1000
print(df['custcat'].value_counts())
# if sample is from 1 is to 100 , then bin size of 50 implies 50 range of histgram, from [0,2) to [98,100], Last bin include 100
# basically bins are number of class size.
df.hist(column = 'income', bins = 50)
plt.show()
print(df.count())
plt.scatter(df.custcat, df.income, color = 'blue')
plt.xlabel('custcat')
plt.ylabel('income')
plt.show()
|
29809d1ff13e65e1873762eff4292736dc8357aa | jordanyoumbi/Python | /function/function_arg_multiple.py | 531 | 3.703125 | 4 | # function qui prend 2 arguments en parametres
def clean_string(string, change_string):
replacement_string = ""
cleaned_string = string.replace(change_string, replacement_string)
return(cleaned_string)
goal = clean_string("Goal!!!!!!!", "!")
print(goal)
# function qui prend 3 arguments en parametres
def jordan(string_text, a_changer, le_nouveau):
nouveau_text = string_text.replace(a_changer, le_nouveau)
return(nouveau_text)
goal2 = jordan("je suis peut-etre !!!!la et !!!!vous?", "!", "")
print(goal2)
|
b90611898fc38198839e38527a00826a340ff727 | jordanyoumbi/Python | /liste/Comprehension_liste.py | 712 | 4.03125 | 4 | # reduction du calcul à partir de fonction dejà defini
# exemple ci-dessous comment calculer la longueur des elements d' une liste
animals = ["Chien", "Tigre", "Lion", "vache", "Panda"]
animals_lengths = []
for animal in animals:
animals_lengths.append(len(animal))
print(animals_lengths)
# le code ci-dessous fait 4 lignes alors que nous aurons pu le faire plus simplement avec des functions dejà) faite
animals_lengths_2 = [len(animal) for animal in animals]
print(animals_lengths_2)
# les comprehensions de liste sont donc plus compacts
# autres exemple. doublons toute les valeurs d' une liste
prices = [10, 45, 156, 7800]
prices_doubled = [price * 2 for price in prices]
print(prices_doubled)
|
8bf38aa84c4fa743e1e62de5dc82a7e78f59ef4f | jordanyoumbi/Python | /liste/Training_liste.py | 547 | 3.53125 | 4 | # exercice sur les comprehensions de listes
# pourcourir une liste et identifier ses colonnes
name_counts = {}
jules = open("legislators.csv", "r", encoding="utf-8")
legislators = jules.read()
for row in legislators:
gender = row[3]
year = row[7]
if gender =="F" and year > 1950:
name = row [1]
if name in name_counts:
name_counts[name] += 1
else:
name_counts[name] = 1
print (name_counts)
#fonction None
# verifier si la valeur de chaque element d' une liste est differante de None |
b653a7f40d3d18f90733053a18d55b8bac940b39 | jordanyoumbi/Python | /les_dates/time.py | 1,455 | 3.828125 | 4 | # tout d' abord il faut recuperer le mudule time
# l' exemple ci-dessous affiche le nombre de seconde depuis 1970. date à le quelle les comptes ont commencé
import time
current_time = time.time()
print(current_time)
# utilisation de function gmtime() pour connaitre l' heure GMT
current_struct_time = time.gmtime(current_time)
print(current_struct_time)
current_hour = current_struct_time.tm_hour
print(current_hour)
current_year = current_struct_time.tm_year
print(current_year)
# un autre module sur le temps: datetime. ce module est plus efficazce que le module time
import datetime
current_datetime = datetime.datetime.now()
current_year = current_datetime.year
current_month = current_datetime.month
print(current_datetime, current_year, current_month)
# Utilisation d' un nouveau module qui est une function qui favorise aussi les calculs: timedelta
# Comment formater les dates. ici on bveux donner un format au dates: stfrtime
today = datetime.datetime(2017, 6, 16, 10, 14, 23)
print(today)
#stfrtime()
string_today = today.strftime("%b %d %Y")
print(string_today)
#pour faire le chemin inverse c' est à dire remettre le temps sous long format ont utilise: strptime
today_2 = time.strptime(string_today, "%b %d %Y")
print(today_2)
# Utiliser la focntion fromtimestamp() pour convertir un chiffre en temps lisible. c' est une fonction du module datetime
datetime_object = datetime.datetime.fromtimestamp(1440082910.0)
print(datetime_object) |
423d82d0f6248deff3e501763b90eee365757e17 | JimmyLamothe/chess_age | /get_html.py | 1,415 | 3.515625 | 4 | #Used to retrieve HTML page from internet
import sys
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_html(page_address,
basepath = 'html/',
filename = None,
overwrite = False,
module = 'requests'):
print(page_address)
last_slash_index = page_address.rfind('/')
if not filename:
filename = basepath + page_address[last_slash_index + 1:] + '.html'
else:
filename = basepath + filename
if overwrite == False:
try:
with open(filename, 'r') as testfile:
print('File already exists, skipping.')
return True #Only returns if file skipped, otherwise action taken.
except FileNotFoundError:
pass
print('Currently downloading: ' + filename)
if module == 'urlopen':
page = urlopen(page_address)
else:
response = requests.get(page_address)
print(response.status_code)
page = response.text
with open(filename, 'w') as html_file:
html_file.write(page)
return
soup = BeautifulSoup(page, 'html.parser')
with open(filename, 'w') as html_file:
html_file.write(soup.prettify())
#Used to run from terminal
if __name__ == '__main__':
try:
get_html(sys.argv[1])
except IndexError:
print('No address given, exiting')
|
ac5923deb722b5f0925ea302f4f623fdae4f8d0a | KentonJack/LongPlay | /Recommendation.py | 406 | 3.53125 | 4 | def matrix_mul(a, b):
result = [[0] * len(b[0]) for i in range(len(a))]
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
result[i][j] += a[i][k] * b[k][j]
return result
A = [[2, 0, 0]]
i = 0
with open('info/record.txt', 'r') as f:
for line in f.readlines():
A[0][i] = int(line.strip())
i += 1
B = [[0, 0, 1], [0, 1, 0], [1, 1, 0]]
C = matrix_mul(A, B)
print(C)
|
ec8444c4562b05d3fc9fcc47d07e78abbab5077c | beenzino/shingu | /baseball.py | 1,849 | 3.5625 | 4 | c=0
while(c==0):
import random
a = ["0","0","0"]
a[0] = str(random.randint(1,9))
a[1] = a[0]
a[2] = a[0]
while(a[0]==a[1]):
a[1] = str(random.randint(1,9))
while(a[1]==a[2] or a[0]==a[2]):
a[2] = str(random.randint(1,9))
print("야구 게임을 시작합니다, 0을 입력하시면 언제든지 종료 가능합니다")
strike=0
count = 0
while(strike<3):
ab = str(input("3자리 숫자를 입력하세요: "))
if ab == str(0):
count=0
break
elif(len(ab)!=3):
print("3자리로 입력하세요")
continue
elif(ab[0]==ab[1] or ab[1]==ab[2] or ab[0]==ab[2]):
print("숫자는 중복되서는 안 됩니다")
continue
'''elif(ab.isdigit()==False):
print("문자를 입력하면 혼납니다")
continue'''
else:
strike=0
ball=0
for i in range(0,3):
for j in range(0,3):
if(ab[i]==str(a[j]) and i==j):
strike +=1
elif(ab[i]==str(a[j]) and i!=j):
ball +=1
print("Strike : ",strike," Ball : ",ball)
count +=1
if count == 0:
print("게임을 종료합니다")
else:
print(count,"번 만에 맞추셨습니다")
d=0
while(d==0):
abc = input("게임을 한 번더 하시겠습니까? YES/NO: ")
abc2 = abc.lower()
if abc2 == "yes":
print("다시 시작됩니다")
d=1
elif abc2 == "no":
print("게임을 종료합니다")
d=1
c=1
else:
print("YES/NO로 입력해주시기바랍니다")
|
fa930ca9e9bb949afea93e8db3345831fcf7de26 | nhthung/mcgill-uni | /COMP 321 - Programming Challenges/Assignment 3/grid_260793376.py | 2,769 | 3.90625 | 4 | '''
You are on an n×m grid where each square on the grid has a digit on it. From a given square that has digit k on it, a Move consists of jumping exactly k squares in one of the four cardinal directions. A move cannot go beyond the edges of the grid; it does not wrap. What is the minimum number of moves required to get from the top-left corner to the bottom-right corner?
Input
Each input will consist of a single test case. Note that your program may be run multiple times on different inputs. The first line of input contains two space-separated integers n and m (1≤n,m≤500), indicating the size of the grid. It is guaranteed that at least one of n and m is greater than 1.
The next n lines will each consist of m digits, with no spaces, indicating the n×m grid. Each digit is between 0 and 9, inclusive.
The top-left corner of the grid will be the square corresponding to the first character in the first line of the test case. The bottom-right corner of the grid will be the square corresponding to the last character in the last line of the test case.
Output
Output a single integer on a line by itself representing the minimum number of moves required to get from the top-left corner of the grid to the bottom-right. If it isn’t possible, output -1.
Link: https://open.kattis.com/problems/grid
'''
import sys
def grid(g):
'''
Given n x m grid g, e.g.
['0123'
'1234']
Return minimum number of steps needed to reach
bottom-right cell g[n-1][m-1]
'''
n, m = len(g), len(g[0])
# DP table: steps[i][j] = minimum number of steps to cell ij
steps = [[-1]*m for _ in range(n)]
steps[0][0] = 0
# Hashmap/dictionary {row: [col1, col2, ...] storing visited cells
visited = {}
# Function to check if cell ij is visited
def is_visited(i, j):
return steps[i][j] > -1
# Function returning generator of valid moves from cell ij
def moves(i, j):
k = int(g[i][j])
# Move is valid if within bounds and reaches new cell
for r, c in ((i, j+k), (i+k, j), (i, j-k), (i-k, j)):
if 0 <= r < n and 0 <= c < m and not is_visited(r, c):
yield r, c
# Queue storing moves
moves_q = [(0, 0)]
# Make all valid moves
while len(moves_q) > 0:
# Get valid moves from current cell ij
i, j = moves_q.pop(0)
# Make valid moves
for r, c in moves(i, j):
# Enqueue valid move
moves_q.append((r, c))
# Increment step count
steps[r][c] = steps[i][j] + 1
# Return minimum number of steps or -1 if couldn't reach bottom-right cell
return steps[n-1][m-1]
# Extract grid from input
g = [* map(str.strip, sys.stdin)][1:]
print(grid(g)) |
491ffe454bdd5161ea332eb5114561b1a56b8e36 | sacheenanand/pythondatastructures | /ReverseLinkedList.py | 557 | 4.1875 | 4 | __author__ = 'sanand'
# To implement reverse Linked we need 3 nodes(curr, prev and next) we are changing only the pointers here.
class node:
def __init__(self, value, nextNode=None):
self.value = value
self.nextNode = nextNode
class LinkedList:
def __init__(self, head):
self.head = head
def reverse(self):
current = head
prev = None
while True:
next = current.nextNode
current.nextNode = prev
prev = current
current = next
return prev |
04dce36f9f552216ea548da767dbf306fc2de8e9 | mrvbrn/HB_challenges | /medium/code.py | 1,162 | 4.1875 | 4 | """TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work.
You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
"""
class Codec:
def __init__(self):
self.url_to_code={}
self.code_to_url={}
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
letters = string.ascii_letters+string.digits
while longUrl not in self.url_to_code:
code = "".join([random.choice(letters) for _ in range(6)])
if code not in self.code_to_url:
self.url_to_code[longUrl]=code
self.code_to_url[code]=longUrl
return self.url_to_code[longUrl]
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.code_to_url[shortUrl[-6:]]
|
289820dd78f4cf13538bde92149ae03d3e93784c | mrvbrn/HB_challenges | /hard/patternmatch.py | 2,712 | 4.59375 | 5 | """Check if pattern matches.
Given a "pattern string" starting with "a" and including only "a" and "b"
characters, check to see if a provided string matches that pattern.
For example, the pattern "aaba" matches the string "foofoogofoo" but not
"foofoofoodog".
Patterns can only contain a and b and must start with a:
>>> pattern_match("b", "foo")
Traceback (most recent call last):
...
AssertionError: invalid pattern
>>> pattern_match("A", "foo")
Traceback (most recent call last):
...
AssertionError: invalid pattern
>>> pattern_match("abc", "foo")
Traceback (most recent call last):
...
AssertionError: invalid pattern
The pattern can contain only a's:
>>> pattern_match("a", "foo")
True
>>> pattern_match("aa", "foofoo")
True
>>> pattern_match("aa", "foobar")
False
It's possible for a to be zero-length (a='', b='hi'):
>>> pattern_match("abbab", "hihihi")
True
Or b to be zero-length (a='foo', b=''):
>>> pattern_match("aaba", "foofoofoo")
True
Or even for a and b both to be zero-length (a='', b=''):
>>> pattern_match("abab", "")
True
But, more typically, both are non-zero length:
>>> pattern_match("aa", "foodog")
False
>>> pattern_match("aaba" ,"foofoobarfoo")
True
>>> pattern_match("ababab", "foobarfoobarfoobar")
True
Tricky: (a='foo', b='foobar'):
>>> pattern_match("aba" ,"foofoobarfoo")
True
"""
def pattern_match(pattern, astring):
"""Can we make this pattern match this string?"""
# Q&D sanity check on pattern
assert (pattern.replace("a", "").replace("b", "") == ""
and pattern.startswith("a")), "invalid pattern"
count_a = pattern.count("a")
count_b = pattern.count("b")
first_b = pattern.find("b")
for a_length in range(0, len(astring) // count_a + 1):
if count_b:
b_length = (len(astring) - (a_length*count_a)) / float(count_b)
else:
b_length = 0
if int(b_length) != b_length or b_length < 0:
continue
b_start = a_length * first_b
if matches(pattern=pattern,
a=astring[0:a_length],
b=astring[b_start:b_start+int(b_length)],
astring=astring):
return True
return False
def matches(pattern, a, b, astring):
test_string = ""
for p in pattern:
if p == "a":
test_string += a
else:
test_string += b
return test_string == astring
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. WE'RE WELL-MATCHED!\n")
|
d4ad295edf0681aca8be2e4ff2c0c89f46ab306a | mrvbrn/HB_challenges | /hard/active.py | 1,831 | 3.71875 | 4 | """Find window of time when most authors were active.
For example::
>>> data = [
... ('Alice', 1901, 1950),
... ('Bob', 1920, 1960),
... ('Carol', 1908, 1945),
... ('Dave', 1951, 1960),
... ]
>>> most_active(data)
(1920, 1945)
(Alice, Bob, and Carol were all active then).
If there's more than one period, find the earliest::
>>> data = [
... ('Alice', 1901, 1950),
... ('Bob', 1920, 1960),
... ('Carol', 1908, 1945),
... ('Dave', 1951, 1960),
... ('Eve', 1955, 1985),
... ]
>>> most_active(data)
(1920, 1945)
(Alice, Bob, Carol were active 1920-1945. Bob, Dave, and Eve were active 1951-1960.
Since there's a tie, the first was returned)
"""
def most_active(bio_data):
"""Find window of time when most authors were active."""
# finish_date1 = []
# start_date1 = []
# for bio in bio_data:
# finish_date1.append(bio[-1])
# start_date1.append(bio[-2])
# min_finish = min(finish_date1)
# start_date2 = []
# for date in start_date1:
# if date < min_finish:
# start_date2.append(date)
# max_start= max(start_date2)
# return (max_start, min_finish)
century = [0] * 100
for name, start, end in bio_data:
for year in range(start, end+1):
best = 0
in_best = True
start = 0
end = 100
for year, num_activate in enumerate(century):
if num_activate > best:
best = num_activate
in_best = True
start = year
elif num_activate < best and in_best:
end = year - 1
in_best = False
return start + 1900, end + 1900
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YAY!\n") |
d576e6059e0f9f5c12fd8e6954cd50a00666b08d | mrvbrn/HB_challenges | /hard/prefix.py | 10,958 | 3.921875 | 4 | """Example code for modeling tries, and searching them by prefix.
Joel Burton <joel@joelburton.com>
"""
class LetterStack(object):
"""Simple letter-based stack based on a list, useful for tries.
Stacks can be built using a linked list or an array; we'll just
use the built-in Python list-type (array) for this.
>>> s = LetterStack()
>>> s.is_empty()
True
As a convenience, we can pass in a string during instantiation,
and it seeds the stack with those letters:
>>> s = LetterStack("ab")
>>> s.is_empty()
False
We can push and pop things off:
>>> s.push("c")
>>> s.push("d")
>>> s.pop()
'd'
As a convenience, it will construct a word of the letters of the
current stack, from the top:
>>> s.as_word()
'abc'
"""
def __init__(self, initial=""):
"""Create a stack.
If initial is given, add each letter to the stack.
"""
self._stack = list(initial)
def push(self, letter):
"""Add letter to stack.
>>> s = LetterStack()
>>> s.push('a')
Let's make sure it's there:
>>> s.peek()
'a'
"""
self._stack.append(letter)
def pop(self):
"""Remove & return last letter on stack.
>>> s = LetterStack('ab')
>>> s.pop()
'b'
>>> s.pop()
'a'
"""
return self._stack.pop()
def peek(self):
"""Examine most-recent pushed letter.
>>> s = LetterStack('ab')
>>> s.peek()
'b'
This does not change the stack--so we can peek as much as we want:
>>> s.peek()
'b'
Of course, when we pull things off, we'll see the new top:
>>> s.pop() # remove it!
'b'
>>> s.peek()
'a'
"""
return self._stack[-1]
def is_empty(self):
"""Return True/False for if stack is empty.
>>> s = LetterStack()
>>> s.is_empty()
True
>>> s.push('a')
>>> s.is_empty()
False
"""
return not self._stack
def as_word(self):
"""Return stack contents as a word. Does NOT change the stack.
>>> s = LetterStack('abc')
>>> s.as_word()
'abc'
>>> s.push('d')
>>> s.as_word()
'abcd'
"""
return "".join(self._stack)
class TrieNode(object):
"""Node in a trie.
Trie nodes are normal tree nodes -- except they have a method to construct
all words below themselves. To do so, they look for special COMPLETE_WORD
nodes.
"""
# This is just some marker element for "this is the end of a valid word".
#
# We don't care what it really *is* -- we just need it to have a unique
# identity so we can say things like "if some_node is COMPLETE_WORD".
# So, we'll make an instance of object() -- this is a pretty useless thing
# to have, but it *will* have a unique identity, so we can use it for
# comparisons. This is a pretty common Python idiom (some other people
# would make it an instance of an empty dictionary or empty list --
# just because those will have unique identities, too -- but that can
# seem a little less obvious, since empty-lists and empty-dictionaries
# tend to be used more in code for useful things.)
#
# Some people call these kind of markers a "nonce".
COMPLETE_WORD = object()
def __init__(self, letter, children=None):
"""Construct a node from a letter and, optionally, a list of child nodes."""\
self.data = letter
self.children = children or []
def find_child_words(self):
"""Given a find all child words below this node.
For a node without children, this returns nothing:
>>> n = TrieNode('z')
>>> n.find_child_words()
[]
For a node with a child word, return it:
>>> n = TrieNode('t', [TrieNode.COMPLETE_WORD])
>>> n.find_child_words()
['']
For a node with a bunch of child words, return in DFS-order:
a
/---\
c d
/ \ |
e t *
| |
* *
>>> n = TrieNode('a', [TrieNode('c',
... [TrieNode('e', [TrieNode.COMPLETE_WORD]),
... TrieNode('t', [TrieNode.COMPLETE_WORD])]),
... TrieNode('d', [TrieNode.COMPLETE_WORD])])
>>> n.find_child_words()
['ce', 'ct', 'd']
"""
def _find_child_words(node, words, word):
if node is TrieNode.COMPLETE_WORD:
words.append(word.as_word())
return
word.push(node.data)
# Add letters to stack
for n in node.children:
_find_child_words(n, words, word)
# Before we return, pull last letter off stack
if not word.is_empty():
word.pop()
found_words = []
for start_n in self.children:
_find_child_words(start_n, found_words, LetterStack())
return found_words
class Trie(object):
"""A trie is a tree where each node is a letter.
They're often used to construct word trees, as might be used
to find all words starting with a particular prefix.
A path that creates a valid word, like "a"->"c"->"t" will end with a
COMPLETE_WORD node in the children of "t", to show that it is valid.
A path that, by itself, is not a valid word will not (so there will
be no such marker in the list of children of "c", as "ac" is not a word).
For example:
a b
/-----|-----\ / \
* c t a e
/ \ / \ / / \
e t * e t * t
| | | | |
* * * * *
(where * is the "end-of-valid-word" node marker).
This is a trie of "a", "ace", "act", "ate", "bat", "be", "bet".
Note that "b" "ac" and "ba" are not words -- there are no end-of-word nodes
that follow these directly.
"""
def __init__(self, words):
"""Make a trie out of words.
>>> trie = Trie(["a", "ace", "act", "ate", "bat", "be", "bet"])
>>> trie.root.find_child_words()
['a', 'ace', 'act', 'ate', 'bat', 'be', 'bet']
"""
self.root = TrieNode(None)
for word in words:
self.add(word)
def add(self, word):
"""Add word to trie.
Adds word to trie. This creates whatever nodes are needed so there
is a path of letters from the root for this word. It adds a
complete-word marker as a child of the last letter, so it's marked
as a word.
We'll add an test the word 'at', which should add the following to
our trie:
a
|
t
|
*
>>> t = Trie('')
>>> t.add('at')
>>> len(t.root.children)
1
>>> t.root.children[0].data
'a'
>>> len(t.root.children[0].children)
1
>>> t.root.children[0].children[0].data
't'
>>> len(t.root.children[0].children[0].children)
1
>>> t.root.children[0].children[0].children[0] is TrieNode.COMPLETE_WORD
True
If the word is already in our trie, adding it again has no effect:
>>> t.add('at')
>>> len(t.root.children)
1
>>> len(t.root.children[0].children)
1
>>> len(t.root.children[0].children[0].children)
1
"""
node = self.root
for letter in word:
found = False
for child in node.children:
if child is not TrieNode.COMPLETE_WORD and child.data == letter:
found = child
break
if not found:
found = TrieNode(letter)
node.children.append(found)
node = found
if TrieNode.COMPLETE_WORD not in node.children:
# If this word wasn't already in our trie, make sure it's marked
# as a complete word.
node.children.append(TrieNode.COMPLETE_WORD)
def find_prefix_words(self, prefix):
"""Find words with a prefix.
:prefix: string of prefix
- Navigates through the trie for each letter in the prefix
- Returns a list of each word that uses this prefix, making sure
to append the prefix to the returned list of words.
a b
/-----|-----\ / \
* c t a e
/ \ / \ / / \
e t * e t * t
| | | | |
* * * * *
>>> trie = Trie(["a", "ace", "act", "ate", "bat", "be", "bet"])
If we provide an empty string for the prefix, this returns
all child words of the entire trie:
>>> trie.find_prefix_words('')
['a', 'ace', 'act', 'ate', 'bat', 'be', 'bet']
Otherwise, it navigates to the end of that prefix, and finds
all child words:
>>> trie.find_prefix_words('a')
['a', 'ace', 'act', 'ate']
>>> trie.find_prefix_words('ac')
['ace', 'act']
>>> trie.find_prefix_words('ace')
['ace']
(note that they must be valid words; 'ac' does not appear, as it is
not a word -- there's no complete-marker in the children of 'a'->'c')
If the prefix can't be found, it returns no found words:
>>> trie.find_prefix_words('z')
[]
Let's add a node with *no* children:
>>> trie.root.children.append(TrieNode('z'))
That's not very helpful -- this isn't a complete word, and it has no
other children. Some people might even say our trie is no longer valid.
Let's make sure this doesn't break things, though -- it should
truthfully return no-words-with-that-prefix still:
>>> trie.find_prefix_words('z')
[]
"""
# Find prefix
# Get list of suffixes from this point downward. This doesn't
# include the prefix itself -- so four our sample trie, above,
# 'ac' -> [e', 't']
# Return list of words, joining the prefix to each suffix
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED! YOU'RE A TRIE-MASTER!\n")
|
17e7d572d777f3f6706521de99e3b5ca3ee175fc | solaaremu-pelumi/PVT-ML | /pvt_ml/GUI.py | 1,276 | 3.8125 | 4 | """This is the first page in the GUI of the app"""
import tkinter as tk
from tkinter import ttk
class my_frame(tk.Frame):
"""Frame to hold the design"""
def __init__(self,parent,*args,**kwargs):
super().__init__(parent,*args,**kwargs)
#Widgetsgit
use_label=ttk.Label(self, text='Username:')
pass_label=ttk.Label(self, text='Password:')
use_entry=ttk.Entry(self)
pass_entry=ttk.Entry(self,show='*')
enter_button=ttk.Button(self,text="Log in")
#Widget Layout
use_label.grid(row=0,column=0,sticky=tk.W)
use_entry.grid(row=0,column=1,sticky=tk.E)
pass_label.grid(row=1,column=0,sticky=tk.W)
pass_entry.grid(row=1,column=1,sticky=tk.E)
enter_button.grid(row=2,column=1)
class my_application(tk.Tk):
"""Login main applicatin"""
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.title("PVT ML")
self.geometry("220x100")
self.resizable(width=False,height=False)
#Defining the UI
my_frame(self).grid(sticky=tk.W+tk.S+tk.E+tk.N)
if __name__ == "__main__":
app=my_application()
app.mainloop()
|
9c02efad543b57e9b03001eba63001ee10fd9672 | IrinaNizova/5_lang_frequency | /lang_frequency.py | 671 | 3.75 | 4 | from collections import Counter
import argparse
import re
def load_data(filepath):
with open(filepath, "r") as file_object:
return file_object.read()
def count_words(text):
match_patterns = re.findall(r'\b\w{2,25}\b', text.lower())
return Counter(match_patterns)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("file_name", help="write name of json file")
text = load_data(parser.parse_args().file_name)
frequent_words_number = 10
words_dict = count_words(text)
for word, counter in words_dict.most_common(frequent_words_number):
print('{} found {} times'.format(word, counter))
|
322aa3bedd4ce2c7bdf80cd7bca5c5bc1b24b743 | dhruvag02/Pyhton | /distinctPairs.py | 1,030 | 3.5 | 4 | def isNotEmpty(a):
if len(a) == 0:
return True
else:
return False
def binarySearch(a, value):
low = 0
high = len(a) - 1
while low <= high:
mid = (low + high)//2
if a[mid] < value:
low = mid+1
elif a[mid] > value:
high = mid-1
else:
return True
return False
def distinctPairs(n, a, k):
if n == 0:
return 0
a.sort()
print(a)
count = 0
i = 0
while (i < n) or (isNotEmpty(a)):
i = i+1
try:
item = a[0]
except:
return count
value = k-item
if binarySearch(a, value):
a.remove(value)
a.remove(item)
print(a)
count = count + 1
else:
continue
return count
n = 6
a = [1, 18, 13, 6, 10, 9]
k = 19
pairs = distinctPairs(n, a, k)
print(pairs)
OUTPUT
[1, 6, 9, 10, 13, 18]
[6, 9, 10, 13]
[9, 10]
[]
3
|
0228e00df8dec90fd27cadd6bec19d9223071f68 | vibinash/vision | /image_processing/hough_line_transform/hough_lines.py | 1,121 | 3.5 | 4 | import cv2
import numpy as np
# Hough Transform is a popular technique to detect shape, if it can be
# represented in mathematical form
# line:
# Cartesian form: y = mx + b
# Parametric form: p = xcos(theta) + ysin(theta)
# p = perpendicular distance from orgin to line
# theta = angle formed by this perpendicular line and the horizontal axis
img = cv2.imread('../../images/puzzle.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# cv2.HoughLines(binary_img, p accuracies, theta accuracies, threshold -
# min vote to be considered a line)
# returns an array of (p, theta) values
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
for line in lines:
for rho, theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 + 1000*(a))
cv2.line(img, (x1,y1), (x2,y2), (0,0,255), 2)
print 'number of lines found', len(lines)
cv2.imshow('lines found', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
0c39ff499615b06812f118c9b8b79e8997244be1 | kontok/clever_magic | /task_01_04.py | 274 | 3.703125 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x3 = int(input())
y3 = int(input())
a = (x2-x1)**2 + (y2-y1)**2
b = (x3-x2)**2 + (y3-y2)**2
c = (x1-x3)**2 + (y1-y3)**2
if (a == c+b) or (c == a+b) or (b == a+c):
print('yes')
else:
print('no')
|
33de3b08054f3265ae46f52923e0cf7178e6bb5f | kontok/clever_magic | /task_02_01.py | 378 | 3.546875 | 4 | def delete(chars, s):
s=(str(s))
s=s.lower()
for i in chars:
if s.find(i):
s = ''.join(s.split(i))
return s
def is_palindrome(s):
p=True
s = delete(' !?,.\'"', s)
a=0
b=len(s)-1
while a<b:
if s[a] != s[b]:
p=False
a +=1
b -=1
return (p)
|
50bd3576574391666e1c60d9aaea2a27f3da2d18 | Brahma1212/testing123 | /remove-duplicate.py | 125 | 3.859375 | 4 | duplicates=[1,1,2,2,3,3,4,4,5,6,7]
empty=[]
for i in duplicates:
if i not in empty:
empty.append(i)
print(empty)
|
46189e97c45b2babf68350b3e1351eca9da02207 | andreaschiavinato/python_grabber | /examples/example_3.py | 891 | 3.5 | 4 | # The following code uses the sample grabber filter to capture single images from the camera.
# To capture an image, the method grab_frame is called. The image will be retrieved from the callback function passed
# as parameter to the add_sample_grabber method. In this case, the image captured is shown using the function
# imshow of opencv.
from pygrabber.dshow_graph import FilterGraph
import cv2
if __name__ == "__main__":
graph = FilterGraph()
cv2.namedWindow('Image', cv2.WINDOW_NORMAL)
graph.add_video_input_device(0)
graph.add_sample_grabber(lambda image: cv2.imshow("Image", image))
graph.add_null_render()
graph.prepare_preview_graph()
graph.run()
print("Press 'C' or 'c' to grab photo, another key to exit")
while cv2.waitKey(0) in [ord('c'), ord('C')]:
graph.grab_frame()
graph.stop()
cv2.destroyAllWindows()
print("Done") |
ee73f52b7f99cc07cd49b826dbe48450fab2e72f | njustqiyu/deep-learning | /linear_unitQY.py | 1,314 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
#author:qiyu,date:2018/5/2
from perceptronQY import Perceptron
#定义激活函数f
f=lambda x:x
class LinearUnit(Perceptron):
def __init__(self,input_num):
'''初始化线性单元,设置输入参数的个数'''
Perceptron.__init__(self,input_num,f)
def get_training_dataset():
'''
创造5个人的收入数据,作为训练样本
'''
#构造训练数据
#输入的向量列表,每一项都是工作年限
input_vecs=[[5],[3],[8],[1.4],[10.1]]
#期望的输出列表,月薪(标签)
labels=[5500,2300,7600,1800,11400]
return input_vecs,labels
def train_linear_unit():
'''
使用数据训练线性单元
'''
#创建感知器,输入参数的特征数为1(只有工作年限一项)
lu=LinearUnit(1)
#训练:迭代10轮,学习速率为0.01
input_vecs,labels=get_training_dataset()
lu.train(input_vecs,labels,10,0.01)
#返回训练好的线性单元
return lu
if __name__ == '__main__':
'''训练线性单元'''
linear_unit=train_linear_unit()
#打印训练获得的权重
print linear_unit
#测试
print 'Work 3.4 years,monthly salary = %.2f'% linear_unit.predict([3.4])
print 'Work 15 years,monthly salary = %.2f'% linear_unit.predict([15])
print 'Work 30 years,monthly salary = %.2f'% linear_unit.predict([30]) |
238df9849fe555fe2baeeaf331119b9cf41345e8 | wangweihao/PythonCookbook | /search_occur_num_more.py | 380 | 4.09375 | 4 | __author__ = 'wwh'
from collections import Counter
words = [
'look', 'into', 'he', 'she', 'is', 'my',
'you', 'into', 'hi', 'into', 'is', 'look',
'eyes', 'the', 'a'
]
#计数
word_count = Counter(words)
print(word_count)
#运算
word_count += word_count
print(word_count)
#获得出现次数最多的前3个值
top_three = word_count.most_common(3)
print(top_three)
|
082ca8fc38be54f03366478516d9075648c9512f | raufmca/NewRepo | /sumArray.py | 362 | 4.09375 | 4 |
#Sum of arrays function
def sumArray(lst1):
sum=0
for i in lst1:
sum = sum + i
print(f'Sum of list item = ', sum)
s = int(input("Enter the size of array " ))
lst1=[]
while s != 0:
i = int(input("Enter you number = "))
lst1.append(i)
s = s-1
sumArray(lst1)
print('End of program')
print('End of file from orginal location')
|
560459ddf49384a758c3bcfde15517ba99e44077 | shaikharshiya/python_demo | /fizzbuzzD3.py | 278 | 4.15625 | 4 | number=int(input("Enter number"))
for fizzbuzz in range(1,number+1):
if fizzbuzz % 3==0 and fizzbuzz%5==0:
print("Fizz-Buzz")
elif fizzbuzz % 3==0:
print("Fizz")
elif fizzbuzz % 5==0:
print("Buzz")
else:
print(fizzbuzz)
|
27ff13f6f44bc41437cec3ee3f53dd7f3e0b06ce | Columnrunner/day1 | /Day1_YunfeiMao.py | 2,002 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 22:22:10 2019
@author: SHAIL
"""
abcd = ['nintendo','Spain', 1, 2, 3]
print(abcd)
# Ex1 - Select the third element of the list and print it
print(abcd[2])
# Ex2 - Type a nested list with the follwing list elements inside list abcd mentioned above and print it
newlist = [54,76]
print(abcd.append(newlist))
# Ex3 - Print the 1 and the 4 position element in the following list
nestedlist = ["shail", [11,8, 4, 6], ['toronto'],abcd, "abcd"]
print(nestedlist[1],nestedlist[4])
# Ex4 - add the fllowing 2 lists and create list3 and print
list1= [10, 20, 'company', 40, 50, 100]
list2 = [100, 200, 300, 'orange', 400, 500,1000]
list3 = list1 + list2
# Ex 5 - print the lenght of the list3
print(len(list3))
# Ex 6 Add 320 to list 1 and print
list1.append(320)
print(list1)
#Ex 7 - Add parts of list1 & 2 by tking first 4 elements from list1 and last 2 elements from list2
list1[:3] + list2[5:]
#ex 8 check if 99 is in list 1
99 in list1
#ex 9 check if 99 is not in list 1
99 not in list1
# concatenation (+) and replication (*) operators
#ex 10 - CONCATENANTE list 1 and ['cool', 1990]
list1 + ['cool', 1990]
# Ex 11 - triplicate the list 1
list1 * 3
# ex 12 - find min & max of list2
list1.remove("company")
list2.remove("orange")
min(list2)
max(list2)
# append & del
# Ex 13 append 'training' to list 1
list1.append("training")
# Ex 14 delete 2nd position element from list 2
del list2[1]
# Ex 15 - iterate over list1 and print all elements by adding 10 to each element
list1= [10, 65,20, 30,93, 40, 50, 100]
# for x in list1:
for x in list1:
print(x+10)
#Ex 16 sorting
#sort list1 by ascending order
list1.sort()
#sort list1 by reverse order
list1.sort(reverse=True)
list1 = [10,10,20,30,30,40,50]
listU = []
for x in list1:
if x not in listU:
listU.append(x)
|
cc06f8221ea3533918bfc37e2d637945895af013 | 2371406255/PythonLearn | /15_filter.py | 460 | 3.765625 | 4 | #!/usr/bin/env python3
#coding:utf-8
#filter:过滤序列,接收一个函数和一个序列,filter把传入的函数依次作用于每个元素,根据返回True还是False决定保留还是丢弃
#删除掉偶数
def is_odd(n):
return n%2==1
arr = list(filter(is_odd,[1,2,3,4,5,6]))
print(arr)#[1, 3, 5]
#删除掉空字符
def not_empty(s):
return s and s.strip()
arr = list(filter(not_empty,['a','','c',None,' ']))
print(arr)#['a', 'c']
|
814d9846600316450e097ef7ce0cb8f40d45efd1 | 2371406255/PythonLearn | /24_访问限制.py | 1,728 | 4.125 | 4 | #!/usr/bin/env python3
#coding:utf-8
#如果要让内部属性不被外部访问,可以在属性名称前加上两个下划线,这样就变成了私有变量,只能内部访问
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s : %s' % (self.__name, self.__score))
stu = Student('BOBO', 90)
stu.print_score()#BOBO : 90
#此时,已经无法使用stu.__name去访问变量
# print(stu.__name)会报错
#如果外部需要获取name,score,则需要增加get_name和get_score方法
#如果需要外部修改name,score,则需要增加set_name和set_score方法
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_name(self, name):
self.__name = name
def set_score(self, score):
self.__score = score
stu = Student('Angle', 99)
print(stu.get_name())#Angle
print(stu.get_score())#99
stu.set_name('Baby')
stu.set_score(98)
print(stu.get_name())#Baby
print(stu.get_score())#98
#特殊变量是__xx__,特殊变量可以直接访问,不是私有的,所以不能这样命名
#有的私有变量是_name,此时,我们应该按照规定,视为私有变量,不要使用
#__name私有变量实际上是,解释器把__name改成_Student_name,所以可以通过_Student_name来访问
#注意的地方:
stu.__name = 'New Name'
print(stu.__name)#New Name 此时是动态添加__name变量,而不是设置了__name变量
print(stu.get_name())#Baby 本身的私有变量还是没有被改变的
|
7fef85965ad45ea0fb3550725c42c51abb250829 | 2371406255/PythonLearn | /04_条件语句.py | 703 | 4.0625 | 4 | #!/usr/bin/env python3
#coding:utf-8
#条件判断
age = 20
if age > 18:
print('%d岁,成年了!' % age)#20岁,成年了!
#if...else...
if age > 18:
print('成年了')#成年了
else:
print('未成年')
#if...elif...else...
if age < 18:
print('未成年')
elif age > 80:
print('你老了')
else:
print('很年轻')#很年轻
#if简写:判断的值是非零数值,非空字符串,非空list等,就为True
if age: print('True')#True
#input:读取用户输入
age = input('输入年龄:')
#input返回的数据类型是str,需要转换
age = int(age)
if age < 18:
print('未成年')
elif age > 80:
print('你老了')
else:
print('很年轻')
|
e077da7130bb05c4e020527e0f7c8200cddc1daa | 2371406255/PythonLearn | /30_多重继承.py | 739 | 3.671875 | 4 | #!/usr/bin/env python3
#coding:utf-8
#多重继承
class Animal(object):
pass
#大类
class Mammal(Animal):
pass
class Bird(Animal):
pass
#各种动物
class Dog(Mammal):
pass
class Bat(Mammal):
pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
#我们要给动物加上Runnable和Flyable功能
class Runable(object):
def run(self):
print('Running...')
class FlyAble(object):
def fly(self):
print('Flying...')
#如果需要一个runable的动物,就多继承一个
class Dog(Mammal, Runable):
pass
#这样,Dog就同时继承了Mammal和Runable的所有功能
dog = Dog()
dog.run()#Running...
#我们可以把Runable改成runableMixIn,表示是混合,父类是Mammal |
f8732e9e7a5c1f056a3e2a3e6b3d089588a469b2 | Monicasfe/AAB_C | /Automata_comp.py | 2,736 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Automata:
def __init__(self, alphabet, pattern):
self.numstates = len(pattern) + 1
self.alphabet = alphabet
self.transitionTable = {}
self.buildTransitionTable(pattern)
def buildTransitionTable(self, pattern): #o pattern vem como argumento pq não foi guardado no init da classe
""""""
for q in range(self.numstates):#por cada caracter no padrão
for a in self.alphabet:#pelo alfabeto
prefixo = pattern[:q] + a #aqui não precisamos de q-1 pq o q é exclusivo nº final da [] não conta
self.transitionTable[(q,a)] = overlap(prefixo, pattern) #q é o estado onde estou, e a o estado para onde vou
def printAutomata(self):
print ("States: " , self.numstates)
print ("Alphabet: " , self.alphabet)
print ("Transition table:")
for k in self.transitionTable.keys():
print (k[0], ",", k[1], " -> ", self.transitionTable[k])
def nextState(self, current, symbol):
return self.transitionTable[(current, symbol)]
#ou return self.transitionTable.get((current, symbol))
#a diferença entre 1 e outro é que com o get se não houver a chave no dict posso retornar o valor por defeito
#definido por nos tipo get((current, symbol), 5) relacionado com kwargs
def applySeq(self, seq):
q = 0 #iniciador do estado
res = [q]
for c in seq:
q = self.nextState(q, c) #guardamos pq depois o estado terá que comecar neste
res.append(q)
return res
def occurencesPattern(self, text):
q = 0
res = []
#applySeq(text).index(self.numstates) - len(self.pattern)
for aa in range(len(text)):
q = self.nextState(q, text[aa])
if q == self.numstates - 1:
res.append(aa - self.numstates + 2)
#para ter o tamanho da seq pomos 1 e depois para dar a casa em branco pomos outro
return res#retorna a lista com as posições onde ocorrem os padrões
def overlap(s1, s2):
maxov = min(len(s1), len(s2))
for i in range(maxov,0,-1):
if s1[-i:] == s2[:i]:#se o ultimo i igual ao primeiro i retorna i
return i
return 0
def test():
auto = Automata("AC", "ACA")
auto.printAutomata()
print (auto.applySeq("CACAACAA"))
print (auto.occurencesPattern("CACAACAA"))
if __name__ == "__main__":
test()
#States: 4
#Alphabet: AC
#Transition table:
#0 , A -> 1
#0 , C -> 0
#1 , A -> 1
#1 , C -> 2
#2 , A -> 3
#2 , C -> 0
#3 , A -> 1
#3 , C -> 2
#[0, 0, 1, 2, 3, 1, 2, 3, 1]
#[1, 4]
|
1c2ba5b0c957997f88e9d16a6ce8560f70c75ddb | lina1/python-algorithm | /string_duplicate.py | 787 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'lina'
__date__ = '16/4/18'
def get_first_single(string):
# 获取字符串中第一个只出现一次的字符的index
if not string:
return -1
length = len(string)
char_count = dict()
for index in range(0, length):
char = string[index]
# if string.count(char) == 1:
# return index
if char in char_count.keys():
char_count[char] += 1
else:
char_count[char] = 1
index += 1
for index in range(0, length):
char = string[index]
if char_count[char] == 1:
return index
index += 1
return -1
if __name__ == "__main__":
a = "bdldjfsewhnasbl"
print get_first_single(a) |
1b10ddfa348801f4d9a816e35f86f07d84229ac5 | AdinaFakih/python | /sets.py | 214 | 3.6875 | 4 | # myset = set()
# print(myset)
# myset.add(1)
# print(myset)
# myset.add(2)
# print(myset)
# myset.add(2) # No changes will be made
# print(myset)
mylist = [1,1,1,1,1,2,2,2,3,3,3]
print(set(mylist)) |
0911c405b07c6c3166f367c900ef7400800293c9 | viktornordling/adventofcode2020 | /07/solve.py | 1,846 | 3.625 | 4 | from math import prod
import re
import math
import string
def parse_contain(can):
if can.strip() == "no other bags.":
return {'amount': 0, 'bag_name': None}
amount = can.strip().split(" ")[0]
bag_name = " ".join(can.split(" ")[2:-1])
return {'amount': amount, 'bag_name': bag_name}
def rchop(s, suffix):
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s
def parse_rule(line):
bag_name = rchop(line.split("contain")[0].strip()[0:-1], "bag").strip()
can_contain = [parse_contain(can) for can in line.split("contain")[1].split(",")]
return {'bag_name': bag_name, 'rule': can_contain}
# lines = open('easy.txt', 'r').readlines()
lines = open('input.txt', 'r').readlines()
bag_rules = [parse_rule(line) for line in lines]
bag_rule_dict = {bag_rule['bag_name']: bag_rule['rule'] for bag_rule in bag_rules}
bag_to_containable_bags = {}
for bag in bag_rules:
for rule in bag['rule']:
contained_bag = rule['bag_name']
containable_bags = bag_to_containable_bags.get(contained_bag, [])
containing_bag = bag['bag_name']
containable_bags.append(containing_bag)
bag_to_containable_bags[contained_bag] = containable_bags
def count_possible_outer_bags(start_bag):
containable_bags = set(bag_to_containable_bags.get(start_bag, []))
further = set()
for bag in containable_bags:
further |= count_possible_outer_bags(bag)
return containable_bags | further
def count_bags_in(start_bag):
rule = bag_rule_dict.get(start_bag, None)
if rule is None:
return 1
total = 0
for r in rule:
total += int(r['amount']) * count_bags_in(r['bag_name']) + int(r['amount'])
return total
print("Part 1: ", len(count_possible_outer_bags("shiny gold")))
print("Part 2: ", count_bags_in("shiny gold")) |
01bcc3ce85f91b578f96aa2e21c1dc5cfee9efbe | joannachenyijun/yijun-1 | /PythonAlgorithm/464.SortInteger.py | 724 | 3.8125 | 4 | '''Given an integer array, sort it in ascending order. Use quick sort, merge sort, heap sort or any O(nlogn) algorithm.
'''
class solution:
#input array
#return array
def sortIntegers2(self,A):
self.quick(A, 0, len(A) - 1)
def quick(self, A, start, end):
if start >= end:
return
left, right = start, end
pivot = A[(start + end) // 2]
while left <= right:
while left <= right and A[left] < pivot:
left += 1
while left <= right and A[right] > pivot:
right -= 1
if left <= right:
A[left], A[right] = A[right], A[left]
left += 1
right -= 1
self.quick(A,start, right)
self.quick(A,left,end)
x = solution()
print(x.sortIntegers2([1,3,3,4,2,1,3,4,5,6,7,8,6,5,4,2])) |
57ad1e768b53dd85018fbfbece246a9bdb33cb90 | joannachenyijun/yijun-1 | /PythonAlgorithm/159.MinRotatedArray.py | 897 | 3.578125 | 4 | '''Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
Example
Given [4, 5, 6, 7, 0, 1, 2] return 0
Notice
You may assume no duplicate exists in the array.'''
class solution:
#input array
#ouput interger index
def findMin(self,nums):
start = 0
end = len(nums)-1
if not nums:
return -1
while start + 1 < end:
mid = start + (end - start) // 2
if abs(nums[mid] - nums[end]) > abs(nums[mid] - nums[start]):
start = mid
else:
end = mid
if nums[start] < nums[start + 1] and nums[start] < nums[start - 1]:
return nums[start]
elif end == len(nums) - 1 and nums[end] < nums[end - 1]:
return nums[end]
elif nums[end] < nums[end + 1] and nums[end] < nums[end - 1]:
return nums[end]
else:
return nums[mid]
x = solution()
print(x.findMin([2,1])) |
b1643984e4bb2c6f946183ce02a1a3e13a9833ed | manmaha/utilities | /buttons.py | 920 | 3.703125 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
button_pin = 18
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#button_pin is pulled down
#connect the other pin to 3.3v
def button_pressed(button_pin,previous_state):
#returns (button state, previous state)
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
state = GPIO.input(button_pin)
button = previous_state ^ state
print ('state is ', state, ' previous state is ', previous_state, ' button is ', button )
previous_state = button
time.sleep(0.2)
return (button, previous_state)
def button_handler(pin):
roaming = not roaming
pass
#def main():
# previous_state = False
# while True:
# button,previous_state = button_pressed(button_pin,previous_state)
# if button:
# print('Button Pressed')
# time.sleep(0.2)
#put your code here)
if __name__ == "__main__":
main() |
916bca341fe50462c410a72b0031e68ec0f88df0 | ZhiCheng0326/SJTU-Python | /Sum of odd numbers between 2 numbers.py | 278 | 3.828125 | 4 | def main():
i = input("Please enter the initial number:")
f = input("Please enter the last number:")
total = 0
l = []
for a in range(i,f+1):
if a % 2 != 0:
l.append(a)
total += a
print l
print total
main()
|
4902a5355d72e15199c2a517b23b7b992f0620e2 | ZhiCheng0326/SJTU-Python | /Summation series.py | 247 | 3.953125 | 4 | def main():
x = input("Please input a digit:")
list1= []
for i in range(1,x+1):
a = i ** i
list1.append(a)
print list1
for j in list1:
number = str(j)
print number + " " + "+",
main()
|
935e1104e9ab9a31d97e901da8fc42d4f05b8fab | laisdutra/BasicHTTPServer | /HTTPserver.py | 2,594 | 3.515625 | 4 | # UNIVERSIDADE FEDERAL DO RIO GRANDE DO NORTE
# DEPARTAMENTO DE ENGENHARIA DE COMPUTACAO E AUTOMACAO
# DISCIPLINA REDES DE COMPUTADORES (DCA0113)
# AUTOR: PROF. CARLOS M D VIEGAS (viegas 'at' dca.ufrn.br)
#
# SCRIPT: Base de um servidor HTTP
#
# importacao das bibliotecas
import socket
import os
# definicao do host e da porta do servidor
HOST = '' # ip do servidor (em branco)
PORT = 8080 # porta do servidor
# cria o socket com IPv4 (AF_INET) usando TCP (SOCK_STREAM)
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# permite que seja possivel reusar o endereco e porta do servidor caso seja encerrado incorretamente
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# vincula o socket com a porta (faz o "bind" do IP do servidor com a porta)
listen_socket.bind((HOST, PORT))
# "escuta" pedidos na porta do socket do servidor
listen_socket.listen(1)
# imprime que o servidor esta pronto para receber conexoes
print 'Servidor HTTP aguardando conexoes na porta %s ...' % PORT
def abre_pagina(pagina):
f = open(pagina, 'r')
conteudo = f.read()
f.close()
return conteudo
def verifica_protocolo(pedido_cliente):
if len(pedido_cliente) < 3:
return False
elif pedido_cliente[0] == 'GET' and pedido_cliente[1][0] == '/' and pedido_cliente[2] == 'HTTP/1.1':
return True
else:
return False
while True:
# aguarda por novas conexoes
client_connection, client_address = listen_socket.accept()
# o metodo .recv recebe os dados enviados por um cliente atraves do socket
request = client_connection.recv(1024)
# imprime na tela o que o cliente enviou ao servidor
print request
# quebra os dados recebidos em um vetor
request_vector = request.split()
# verifica o protocolo HTTP
if verifica_protocolo(request_vector):
# testa existencia da pgina
if os.path.isfile(request_vector[1][1:]):
http_response = "HTTP/1.1 200 OK\r\n\r\n" + abre_pagina(request_vector[1][1:])
elif request_vector[1] == '/':
http_response = "HTTP/1.1 200 OK\r\n\r\n" + abre_pagina('index.html')
else:
http_response = "HTTP/1.1 404 Not Found\r\n\r\n" + abre_pagina('404.html')
# se no atende ao protocolo
else:
http_response = "HTTP/1.1 400 Bad Request\r\n\r\n" + abre_pagina('400.html')
# servidor retorna o que foi solicitado pelo cliente
client_connection.send(http_response)
# encerra a conexo
client_connection.close()
# encerra o socket do servidor
listen_socket.close()
|
ceaf6bc170ae84ed937891818b47f4c788af181e | yxiao1994/python_leetcode | /PartStack.py | 4,261 | 3.765625 | 4 | class CQueue(object):
# 两个栈实现队列
def __init__(self):
self.s1 = []
self.s2 = []
def appendTail(self, value):
self.s1.append(value)
def deleteHead(self):
if not self.s1 and not self.s2:
return -1
if not self.s2:
while self.s1:
temp = self.s1.pop()
self.s2.append(temp)
val = self.s2.pop()
return val
class MinStack(object):
# 包含最小元素的栈
def __init__(self):
"""
initialize your data structure here.
"""
self.A = []
self.B = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.A.append(x)
if not self.B or x <= self.B[-1]:
self.B.append(x)
def pop(self):
"""
:rtype: None
"""
x = self.A.pop()
if x == self.B[-1]:
self.B.pop()
def top(self):
"""
:rtype: int
"""
return self.A[-1]
def min(self):
"""
:rtype: int
"""
return self.B[-1]
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
栈的压入弹出序列
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack, i = [], 0
for num in pushed:
stack.append(num) # num 入栈
while stack and stack[-1] == popped[i]: # 循环判断与出栈
stack.pop()
i += 1
return not stack
def isValid(self, s):
"""
判断是否有效的括号
:type s: str
:rtype: bool
"""
n = len(s)
if n == 0:
return True
stack = []
for ch in s:
if ch == '(' or ch == '[' or ch == '{':
stack.append(ch)
else:
if len(stack) == 0:
return False
top_ch = stack[-1]
if ch == ')':
if top_ch == '(':
stack.pop()
else:
return False
if ch == ']':
if top_ch == '[':
stack.pop()
else:
return False
if ch == '}':
if top_ch == '{':
stack.pop()
else:
return False
return len(stack) == 0
def largestRectangleArea(self, heights):
"""
柱状图中最大的矩形
:type heights: List[int]
:rtype: int
"""
n = len(heights)
if n == 0:
return 0
left, right = [0] * n, [0] * n
stack = []
for i in range(n):
while stack and heights[stack[-1]] >= heights[i]:
stack.pop()
left[i] = stack[-1] if stack else - 1
stack.append(i)
stack = []
for i in range(n - 1, -1, -1):
while stack and heights[stack[-1]] >= heights[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
max_area = 0
for i in range(n):
max_area = max(max_area, (right[i] - left[i] - 1) * heights[i])
return max_area
def calculate(selg, s):
"""
字符串加减乘除
:type s: str
:rtype: int
"""
n = len(s)
stack = []
sign = '+'
num = 0
for i in range(n):
if s[i] != ' ' and s[i].isdigit():
num = num * 10 + int(s[i])
if i == n - 1 or s[i] in '+-*/':
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop() * num)
else:
stack.append(int(stack.pop() / num))
sign = s[i]
num = 0
return sum(stack)
if __name__ == "__main__":
obj = Solution()
print(obj.calculate('14-3/2')) |
1019833fd62896c78e4b542d4c45335ad989a929 | A7xSV/Algorithms-and-DS | /Codes/Py Docs/For.py | 242 | 3.671875 | 4 | words = ['cat', 'window', 'defenestrate']
for w in words[:]: # Sliced copy of the list is useful when some modification is needed.
if len(w) > 6:
words.insert(0, w)
print words
for i in range(len(words)):
print i, words[i]
|
c21f73253780164661997fa29d873dec5a4803ce | A7xSV/Algorithms-and-DS | /Codes/Py Docs/Zip.py | 424 | 4.4375 | 4 | """ zip()
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
The returned list is truncated in length to the length of the shortest argument sequence. """
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
print x
print y
zipped = zip(x, y)
print zipped
# Unzip
x2, y2 = zip(*zipped)
print x2
print y2
print (x == list(x2)) and (y == list(y2)) |
259d5b4312f1f619e60f7fc91dadc0300c01a036 | Mengziyang-Doing/pandaset-devkit | /python/pandaset/utils.py | 404 | 4.03125 | 4 | #!/usr/bin/env python3
import os
from typing import List
def subdirectories(directory: str) -> List[str]:
"""List all subdirectories of a directory.
Args:
directory: Relative or absolute path
Returns:
List of path strings for every subdirectory in `directory`.
"""
return [d.path for d in os.scandir(directory) if d.is_dir()]
if __name__ == '__main__':
pass
|
5890859ef1e424accf5b5998ad3e1682ac0cd97e | JetSimon/Advent-of-Code-2020 | /Solutions/Day 6/day6.py | 495 | 3.515625 | 4 | inputRead = []
inputFile = open('input.txt', 'r')
currentGroup = []
groups = []
totalCount = 0
for line in inputFile:
stripped = line.rstrip()
if(stripped != ''):
currentGroup.append(stripped)
else:
groups.append(currentGroup)
currentGroup = []
groups.append(currentGroup)
for group in groups:
strGroup = "".join(group)
for question in set(strGroup):
if strGroup.count(question) == len(group):
totalCount+=1
inputFile.close()
print(totalCount) |
6f0fdeba1d1d9b337a375070162007a3422220cd | BruceHi/leetcode | /month6-21/peakIndexInMountainArray.py | 693 | 3.5625 | 4 | # 852. 山脉数组的峰顶索引
from typing import List
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
left, right = 0, len(arr)-1
while left < right:
mid = left + right >> 1
if arr[mid] < arr[mid+1]:
left = mid + 1
else:
right = mid
return left
s = Solution()
arr = [0,1,0]
print(s.peakIndexInMountainArray(arr))
arr = [0,2,1,0]
print(s.peakIndexInMountainArray(arr))
arr = [0,10,5,2]
print(s.peakIndexInMountainArray(arr))
arr = [3,4,5,1]
print(s.peakIndexInMountainArray(arr))
arr = [24,69,100,99,79,78,67,36,26,19]
print(s.peakIndexInMountainArray(arr))
|
df98c08e33dfb75bd906ef7800e17129925c6a9c | BruceHi/leetcode | /month5-21/preorder.py | 2,149 | 3.671875 | 4 | # 589. N 叉树的前序遍历
from typing import List
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
# def preorder(self, root: 'Node') -> List[int]:
# res = []
#
# def dfs(root):
# if not root:
# return
# res.append(root.val)
# for child in root.children:
# if child:
# dfs(child)
# dfs(root)
# return res
# def preorder(self, root: 'Node') -> List[int]:
# if not root:
# return []
# res = [root.val]
# for child in root.children:
# res += self.preorder(child)
# return res
# def preorder(self, root: 'Node') -> List[int]:
# if not root:
# return []
# stack, res = [root], []
# while stack:
# cur = stack.pop()
# res.append(cur.val)
# for child in reversed(cur.children):
# stack.append(child)
# return res
# def preorder(self, root: 'Node') -> List[int]:
# if not root:
# return []
# stack, res = [root], []
# while stack:
# cur = stack.pop()
# res.append(cur.val)
# stack.extend(cur.children[::-1])
# return res
# def preorder(self, root: 'Node') -> List[int]:
# if not root:
# return []
# res = [root.val]
# for node in root.children:
# res.extend(self.preorder(node))
# return res
# # 递归
# def preorder(self, root: 'Node') -> List[int]:
# if not root:
# return []
# res = [root.val]
# for child in root.children:
# res.extend(self.preorder(child))
# return res
# 迭代
def preorder(self, root: 'Node') -> List[int]:
if not root:
return []
stack, res = [root], []
while stack:
cur = stack.pop()
res.append(cur.val)
stack.extend(cur.children[::-1])
return res
|
d6ba381d714589831432f5f17383defa421bd3e7 | BruceHi/leetcode | /binarySearch/findMin.py | 1,827 | 3.75 | 4 | # 153.寻找旋转排序数组中的最小值
from typing import List
class Solution:
# def findMin(self, nums: List[int]) -> int:
# left, right = 0, len(nums) - 1
# while left < right:
# mid = left + right >> 1
# if nums[mid] > nums[right]:
# left = mid + 1
# else:
# right = mid
# return nums[right]
# # # 找到最大值
# def findMin(self, nums: List[int]) -> int:
# left, right = 0, len(nums) - 1
# while left < right:
# mid = left + right + 1 >> 1 # 注意要加 1,回头再看看
# if nums[left] > nums[mid]:
# right = mid - 1
# else:
# left = mid
# return nums[right]
# def findMin(self, nums: List[int]) -> int:
# left, right = 0, len(nums) - 1
# while left < right:
# mid = left + right >> 1
# if nums[mid] > nums[right]:
# left = mid + 1
# else:
# right = mid
# return nums[left]
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums)-1
while left < right:
mid = left + right >> 1
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
s = Solution()
nums = [3,4,5,1,2]
print(s.findMin(nums))
# print(s.findMax(nums))
nums = [4,5,6,7,0,1,2]
print(s.findMin(nums))
# print(s.findMax(nums))
nums = [1, 2, 3]
print(s.findMin(nums))
# print(s.findMax(nums))
# 下面是错误示例,都说了是旋转排序,肯定不能是递减的啊
# nums = [3, 2, 1]
# print(s.findMin(nums))
# print(s.findMax(nums))
nums = [2, 3, 4, 5, 1]
print(s.findMin(nums))
# print(s.findMax(nums))
|
21a6e7728ad52a244c16a0bb06ade976df402d9b | BruceHi/leetcode | /month2/removePalindromeSub.py | 316 | 3.703125 | 4 | # 1332. 删除回文子序列
class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
return 2
obj = Solution()
s = "ababa"
print(obj.removePalindromeSub(s))
s = "abb"
print(obj.removePalindromeSub(s))
s = "baabb"
print(obj.removePalindromeSub(s))
|
2816843a799ef7a0503197684d420325b1a32177 | BruceHi/leetcode | /month9/flatten.py | 1,638 | 3.734375 | 4 | # 430. 扁平化多级双向链表
# Definition for a Node.
import pkg_resources
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
class Solution:
# def flatten(self, head: 'Node') -> 'Node':
# dummy = Node(0, None, head, None)
# cur = head
# while cur:
# if not cur.child:
# cur = cur.next
# else:
# nxt = cur.next
# chead = self.flatten(cur.child)
#
# # 连接前面
# cur.next = chead
# chead.prev = cur
# cur.child = None
#
# # 定位到支链的最后
# while cur.next:
# cur = cur.next
#
# cur.next = nxt
#
# # 若nxt 存在
# if nxt:
# nxt.prev = cur
# cur = cur.next
# return dummy.next
def flatten(self, head: 'Node') -> 'Node':
cur = head
while cur:
if cur.child:
nxt = cur.next
other = self.flatten(cur.child)
# 连接前面
cur.next = other
other.prev = cur
cur.child = None
# 定位到支链的最后
while cur.next:
cur = cur.next
cur.next = nxt
# 若nxt 存在
if nxt:
nxt.prev = cur
cur = cur.next
return head
|
82235a171ec1cca3fe07301f0cb453355e8684e7 | BruceHi/leetcode | /month11/findUnsortedSubarray.py | 1,018 | 3.75 | 4 | # 581. 最短无序连续子数组
from typing import List
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
n = len(nums)
nums_sort = sorted(nums)
left = 0
right = n - 1
while left <= right and nums[left] == nums_sort[left]:
left += 1
while left <= right and nums[right] == nums_sort[right]:
right -= 1
return right-left+1
s = Solution()
nums = [2, 6, 4, 8, 10, 9, 15]
print(s.findUnsortedSubarray(nums))
nums = [1, 2, 3, 4]
print(s.findUnsortedSubarray(nums))
nums = [2, 6, 4, 8, 10, 9, 15, 11, 16]
print(s.findUnsortedSubarray(nums))
nums = [2, 6, 4, 8, 10, 9, 15, 1, 2]
print(s.findUnsortedSubarray(nums))
nums = [1, 4, 7, 2, 9]
print(s.findUnsortedSubarray(nums))
nums = [1, 4, 7, 2, 5]
print(s.findUnsortedSubarray(nums))
nums = [3,2,3,2,4]
print(s.findUnsortedSubarray(nums))
nums = [1, 3, 5, 4, 2]
print(s.findUnsortedSubarray(nums))
nums = [1, 3, 2, 5, 4]
print(s.findUnsortedSubarray(nums)) |
522fd172c04f5766ce643403c640adb9cb4be834 | BruceHi/leetcode | /month3/isSubStructure.py | 2,062 | 3.84375 | 4 | # 剑指offer 26.树的子结构
# 约定空树不是任意一个树的子结构
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 错误,
# def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
# # 空树是相同的,这是判断两个树一模一样的,而不是判断子结构,[10,12,6,8,3,11],[10,12,6,8]
# def is_same(A, B):
# if not A and not B:
# return True
# if not A or not B:
# return False
# return A.val == B.val and is_same(A.left, B.left) and is_same(A.right, B.right)
#
# # bool(A and B) 表明若一个为空,则没有相同的子结构
# return bool(A and B) and (is_same(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B))
# def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
# # A 是否包含 B(B 可以是空树),要从A的根就开始包含
# def recur(A, B):
# if not B: # B 递归完了,就说明包含了。
# return True
# if not A or A.val != B.val:
# return False
# return recur(A.left, B.left) and recur(A.right, B.right)
#
#
# # # 直接这样写,会有 短路现象,直接输出 none,而不是false
# # return B and A and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B))
#
# return bool(A and B) and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B))
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def recur(A, B):
if not B:
return True
if not A or A.val != B.val:
return False
return recur(A.left, B.left) and recur(A.right, B.right)
if not A or not B:
return False
return recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
|
3edc817a68cc1bbf028c1594a2b9b9c78bb4a879 | BruceHi/leetcode | /month1/MaxQueue.py | 1,378 | 4.1875 | 4 | # 剑指 offer 59-2:队列的最大值
from collections import deque
# class MaxQueue:
#
# def __init__(self):
# self.queue = deque()
#
# def max_value(self) -> int:
# if not self.queue:
# return -1
# return max(self.queue)
#
# def push_back(self, value: int) -> None:
# self.queue.append(value)
#
# def pop_front(self) -> int:
# if not self.queue:
# return -1
# return self.queue.popleft()
class MaxQueue:
# 辅助队列,从左到右,非递增数列
def __init__(self):
self.queue = deque()
self.min_queue = deque()
def max_value(self) -> int:
if not self.queue:
return -1
return self.min_queue[0]
def push_back(self, value: int) -> None:
self.queue.append(value)
while self.min_queue and value > self.min_queue[-1]:
self.min_queue.pop()
self.min_queue.append(value)
def pop_front(self) -> int:
if not self.queue:
return -1
val = self.queue.popleft()
if val == self.min_queue[0]:
self.min_queue.popleft()
return val
queue = MaxQueue()
queue.push_back(1)
queue.push_back(2)
print(queue.max_value())
print(queue.pop_front())
print(queue.max_value())
queue = MaxQueue()
print(queue.pop_front())
print(queue.max_value())
|
e3e35e99d841a156463aecf21c7b932b1a5e0071 | BruceHi/leetcode | /month6/topKFrequent.py | 2,258 | 3.546875 | 4 | # 前 K 个高频元素
from typing import List
from collections import Counter
import heapq
class Solution:
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# return sorted(count, key=count.get, reverse=True)[:k]
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# return heapq.nlargest(k, count, key=count.get)
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# return [x for x, _ in count.most_common(k)]
# 时间复杂度为 O(n log k),超过 95%
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# arr = [(val, key) for key, val in count.items()] # 次数,实际值
# queue = arr[:k]
# heapq.heapify(queue)
# for x, y in arr[k:]:
# if x > queue[0][0]:
# heapq.heappushpop(queue, (x, y))
# return [x[1] for x in queue]
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# return [x for x, _ in count.most_common(k)]
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# arr = [(v, key) for key, v in count.items()]
# queue = arr[:k]
# heapq.heapify(queue)
# for key, val in arr[k:]:
# if key > queue[0][0]:
# heapq.heappushpop(queue, (key, val))
# return [x for _, x in queue]
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# counter = Counter(nums)
# return [x[0] for x in counter.most_common(k)]
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = Counter(nums)
arr = [(v, key) for key, v in count.items()]
queue = arr[:k]
heapq.heapify(queue)
for v, key in arr[k:]:
if v > queue[0][0]:
heapq.heappushpop(queue, (v, key))
return [x[1] for x in queue]
s = Solution()
nums = [1,1,1,2,2,3]
k = 2
print(s.topKFrequent(nums, k))
nums = [1]
k = 1
print(s.topKFrequent(nums, k))
nums = [3,0,1,0]
k = 1
print(s.topKFrequent(nums, k))
|
b4c8cd932bf8b315030522c2bd8b3e3a3fe7100d | BruceHi/leetcode | /binarySearch/myPow.py | 2,693 | 3.578125 | 4 | # 剑指 offer 16. 数值的整数次方
class Solution:
# def myPow(self, x: float, n: int) -> float:
# return pow(x, n)
# return x**n
# def myPow(self, x: float, n: int) -> float:
# if n == 1:
# return x
# if n == 0:
# return 1.0
# if n == -1:
# return 1/x
# y = self.myPow(x, n >> 1)
# if n & 1:
# return y * y * x
# return y * y
# def myPow(self, x: float, n: int) -> float:
# res, tmp, m = 1.0, x, n
# n = -n if n < 0 else n
# while n:
# if n & 1:
# res *= tmp
# n >>= 1
# tmp *= tmp
# return res if m >= 0 else 1/res
# def myPow(self, x: float, n: int) -> float:
# res, tmp = 1.0, n
# if n < 0:
# n = -n
# while n:
# if n & 1:
# res *= x
# n >>= 1
# x *= x
# return res if tmp >= 0 else 1/res
# def myPow(self, x: float, n: int) -> float:
# if not n:
# return 1.0
# if n == 1:
# return x
# if n == -1:
# return 1 / x
# y = self.myPow(x, n >> 1)
# if n & 1:
# return y * y * x
# return y * y
# def myPow(self, x: float, n: int) -> float:
# sign = 1 if n > 0 else -1
# n = n if n > 0 else -n
# res = 1.0
# while n:
# if n & 1:
# res *= x
# x *= x
# n >>= 1
# return res if sign == 1 else 1 / res
# def myPow(self, x: float, n: int) -> float:
# sign = 1 if n > 0 else -1
# n = n if n > 0 else -n
# res = 1.0
# while n:
# if n & 1:
# res *= x
# x *= x
# n >>= 1
# return res if sign == 1 else 1 / res
# def myPow(self, x: float, n: int) -> float:
# if n == 0:
# return 1.0
# if n == 1:
# return x
# if n == -1:
# return 1/x
# m = n >> 1
# y = self.myPow(x, m)
# if n & 1:
# return y * y * x
# return y * y
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
if n == 1:
return x
if n == -1:
return 1/x
res = self.myPow(x, n//2)
if n & 1:
return res * res * x
return res * res
s = Solution()
x, n = 2.00000, 10
print(s.myPow(x, n))
x, n = 2.10000, 3
print(s.myPow(x, n))
x, n = 2.00000, -2
print(s.myPow(x, n))
x, n = 2.00000, 0
print(type(s.myPow(x, n)))
|
7e60f4ea5b576cd04c9f088d414e79dc8cbb79e6 | BruceHi/leetcode | /month3/canPermutePalindrome.py | 411 | 3.5625 | 4 | # 面试题 01.04.回文排列
from collections import Counter
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
counter = Counter(s)
count = 0
for val in counter.values():
if val & 1:
count += 1
if count > 1:
return False
return True
obj = Solution()
s = "tactcoa"
print(obj.canPermutePalindrome(s))
|
6df8f4f4784bda17dbf9223283dea24731d96f67 | BruceHi/leetcode | /Array/11rotateImage.py | 1,560 | 3.9375 | 4 | # 将图像顺时针旋转 90 度。
# 观察规律
# def rotate(matrix):
# n = len(matrix)
# matrix.reverse()
#
# for j in range(n): # 提取元素
# temp = [matrix[i][j] for i in range(n)]
# matrix.append(temp)
#
# for i in range(n-1, -1, -1): # 删除元素
# matrix.pop(i)
# def rotate(matrix):
# matrix[:] = map(list, zip(*(matrix[::-1])))
# 先转置再说
# def rotate(matrix):
# matrix[:] = list(map(list, zip(*matrix)))
#
# for lst in matrix:
# lst.reverse()
# def rotate(matrix):
# n = len(matrix)
#
# for i in range(n): # 转置
# for j in range(i+1, n):
# matrix[i][j], matrix[j][i] \
# = matrix[j][i], matrix[i][j]
#
# for i in range(n): # 交换顺序
# matrix[i].reverse()
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
matrix[:] = map(list, zip(*matrix[::-1]))
s = Solution()
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
s.rotate(matrix1)
print(matrix1)
# [
# [1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]
# ]
# 反向列表
# [
# [7, 8, 9],
# [4, 5, 6],
# [1, 2, 3]
# ]
# 竖列提取元素
# [
# [7, 4, 1],
# [8, 5, 2],
# [9, 6, 3]
# ]
matrix1 = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
# [
# [15,13, 2, 5],
# [14, 3, 4, 1],
# [12, 6, 8, 9],
# [16, 7,10,11]
# ]
s.rotate(matrix1)
print(matrix1)
|
1489f4add9c1dbde1a515242fa48023aee640751 | BruceHi/leetcode | /LinkedList/reorderList.py | 3,177 | 3.796875 | 4 | # 143. 重排链表
from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# 中心节点,翻转,拼接
# def reorderList(self, head: ListNode) -> None:
# slow = fast = dummy = ListNode(0)
# dummy.next = head
# while fast and fast.next:
# slow, fast = slow.next, fast.next.next
#
# cur = slow.next
# slow.next = None # 前半段要断开
#
# pre = None
# while cur:
# cur.next, pre, cur = pre, cur, cur.next
#
# l1, l2 = head, pre
# cur = dummy
# while l1 or l2:
# if l1:
# cur.next = l1
# cur = cur.next
# l1 = l1.next
# if l2:
# cur.next = l2
# cur = cur.next
# l2 = l2.next
# def reorderList(self, head: ListNode) -> None:
# if not head:
# return
# slow, fast = head, head
# while fast.next and fast.next.next:
# slow, fast = slow.next, fast.next.next
# cur = slow.next
# slow.next = None
#
# pre = None
# while cur:
# cur.next, pre, cur = pre, cur, cur.next
#
# l1, l2 = head, pre
# while l1 and l2:
# l1.next, l1 = l2, l1.next
# l2.next, l2 = l1, l2.next
# 线性表
# def reorderList(self, head: ListNode) -> None:
# if not head:
# return
# nodes = []
# cur = head
# while cur:
# nodes.append(cur)
# cur = cur.next
#
# cur = ListNode(0)
# i, j = 0, len(nodes) - 1
# while i <= j:
# cur.next = nodes[i]
# cur = cur.next
# cur.next = nodes[j]
# cur = cur.next
# i, j = i+1, j-1
# cur.next = None # 去掉循环
# def reorderList(self, head: ListNode) -> None:
# if not head:
# return
# nodes = []
# cur = head
# while cur:
# nodes.append(cur)
# cur = cur.next
#
# i, j = 0, len(nodes) - 1
# while i < j:
# nodes[i].next = nodes[j]
# i += 1
# if i == j: # 偶数个节点
# break
# nodes[j].next = nodes[i]
# j -= 1
# nodes[i].next = None # 退出循环 i == j
# 递归
def reorderList(self, head: ListNode) -> None:
if not head:
return
cur = head
while cur.next:
cur = cur.next
def generate_link(nums: List[int]) -> ListNode:
head = ListNode(0)
cur = head
for num in nums:
cur.next = ListNode(num)
cur = cur.next
return head.next
def print_link(head: ListNode) -> None:
res, cur = [], head
while cur:
res.append(cur.val)
cur = cur.next
print(res)
s = Solution()
head = generate_link([1, 2, 3, 4])
s.reorderList(head)
print_link(head)
head = generate_link([1, 2, 3, 4, 5])
s.reorderList(head)
print_link(head)
|
2b17dbafcf8729f1d2b274d85c2d1d052e3f7626 | BruceHi/leetcode | /month11/sumNumbers.py | 1,436 | 3.640625 | 4 | # 129. 求根到叶子节点数字之和
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 错误解法:没法定位到叶子节点。
# def sumNumbers(self, root: TreeNode) -> int:
#
# res = []
#
# def dfs(root, num):
# if not root:
# res.append(num)
# return
# if root:
# dfs(root.left, num * 10 + root.val)
# dfs(root.right, num * 10 + root.val)
#
# dfs(root, 0)
# return sum(res) // 2
# def sumNumbers(self, root: TreeNode) -> int:
#
# def dfs(root, pre):
# if not root:
# return 0
# total = pre * 10 + root.val
# if not root.left and not root.right: # 真正遍历到叶子节点
# return total
# else:
# return dfs(root.left, total) + dfs(root.right, total) # 若没有左节点或没有右节点,返回 0.
#
# return dfs(root, 0)
def sumNumbers(self, root: TreeNode) -> int:
def dfs(root, pre):
if not root:
return 0
total = pre * 10 + root.val
if not root.left and not root.right:
return total
return dfs(root.left, total) + dfs(root.right, total)
return dfs(root, 0)
|
58a73d18cba360cbba63a05da587dbd72f93fc85 | BruceHi/leetcode | /DFS/findCircleNum.py | 6,246 | 3.6875 | 4 | # 朋友圈
# 省份数量
from typing import List
# class Solution:
# # 邻接矩阵的深度优先遍历 看不懂
# def findCircleNum(self, M: List[List[int]]) -> int:
# n = len(M)
# visited = [0] * n
#
# # 按照诸如 [1, 2], [2, 3], [3, 5] 等可以标记 1, 2, 3,5 索引处为 1.
# def DFS(i):
# for j in range(n):
# if M[i][j] and not visited[j]:
# visited[j] = 1
# DFS(j)
#
# count = 0
# for i in range(n):
# if not visited[i]:
# DFS(i)
# count += 1
#
# return count
# 并查集
# class UnionFind:
# def __init__(self, M):
# n = len(M)
# self.rank = [1] * n
# self.parent = [i for i in range(n)]
# self.count = n
#
# def find(self, i):
# if self.parent[i] != i:
# self.parent[i] = self.find(self.parent[i])
# return self.parent[i]
#
# def union(self, x, y):
# rootx = self.find(x)
# rooty = self.find(y)
# if rootx != rooty:
# if self.rank[rootx] < self.rank[rooty]:
# self.parent[rootx] = rooty
# else:
# self.parent[rooty] = rootx
# if self.rank[rootx] == self.rank[rooty]:
# self.rank[rootx] += 1
# self.count -= 1
#
#
# class Solution:
# def findCircleNum(self, M: List[List[int]]) -> int:
# uf = UnionFind(M)
# n = len(M)
#
# for i in range(n-1):
# for j in range(i+1, n):
# if M[i][j]:
# uf.union(i, j)
#
# return uf.count
# class Solution:
# # 邻接矩阵的 dfs
# def findCircleNum(self, M: List[List[int]]) -> int:
# n = len(M)
# visited = [0] * n
#
# def dfs(i):
# for j in range(n):
# if M[i][j] and not visited[j]:
# visited[j] = 1
# dfs(j)
#
# count = 0
# for i in range(n):
# if not visited[i]:
# dfs(i)
# count += 1
# return count
# class UnionFind:
# def __init__(self, M):
# n = len(M)
# self.parent = [_ for _ in range(n)]
# self.count = n
#
# def find(self, i):
# if self.parent[i] != i:
# self.parent[i] = self.find(self.parent[i])
# return self.parent[i]
#
# def unoion(self, x, y):
# rootx = self.find(x)
# rooty = self.find(y)
# if rootx != rooty:
# self.parent[rootx] = self.find(rooty)
# self.count -= 1
#
#
# class Solution:
# def findCircleNum(self, M: List[List[int]]) -> int:
# uf = UnionFind(M)
# n = len(M)
#
# for i in range(1, n):
# for j in range(i):
# if M[i][j]:
# uf.unoion(i, j)
# return uf.count
# class Solution:
# def findCircleNum(self, M: List[List[int]]) -> int:
# n = len(M)
#
# def dfs(i, j):
# M[i][j] = 0
# for y in range(n):
# if M[j][y]:
# dfs(j, y)
#
# count = 0
# for i in range(n):
# for j in range(i, n):
# if M[i][j]:
# count += 1
# dfs(i, j)
# return count
#
# class UnionFind:
# def __init__(self, M):
# n = len(M)
# self.parent = list(range(n))
# self.count = n
#
# def find(self, i):
# if self.parent[i] != i:
# self.parent[i] = self.find(self.parent[i])
# return self.parent[i]
#
# def union(self, x, y):
# rootx = self.find(x)
# rooty = self.find(y)
# if rootx != rooty:
# self.parent[rootx] = rooty
# self.count -= 1
#
#
# class Solution:
# def findCircleNum(self, M: List[List[int]]) -> int:
# uf = UnionFind(M)
# n = len(M)
# for i in range(n):
# for j in range(n):
# if M[i][j]:
# uf.union(i, j)
# return uf.count
class UnionFind:
def __init__(self, isConnected):
self.count = len(isConnected)
self.parent = list(range(self.count))
def find(self, i):
if self.parent[i] != i:
self.parent[i] = self.find(self.parent[i])
return self.parent[i]
def union(self, x, y):
rootx, rooty = self.find(x), self.find(y)
if rootx != rooty:
self.parent[rootx] = rooty
self.count -= 1
class Solution:
# def findCircleNum(self, isConnected: List[List[int]]) -> int:
# n = len(isConnected)
# visited = [0] * n
#
# def dfs(i):
# for j in range(n):
# if isConnected[i][j] and not visited[j]:
# visited[j] = 1
# dfs(j)
#
# res = 0
# for i in range(n):
# if not visited[i]:
# dfs(i)
# res += 1
# return res
# def findCircleNum(self, isConnected: List[List[int]]) -> int:
# n = len(isConnected)
#
# def dfs(i, j):
# isConnected[i][j] = 0
# for y in range(n):
# if isConnected[j][y]:
# dfs(j, y)
#
# res = 0
# for i in range(n):
# for j in range(n):
# if isConnected[i][j]:
# res += 1
# dfs(i, j)
# return res
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
uf = UnionFind(isConnected)
for i in range(n-1):
for j in range(i+1, n):
if isConnected[i][j]:
uf.union(i, j)
return uf.count
s = Solution()
m = [[1,1,0],
[1,1,0],
[0,0,1]]
print(s.findCircleNum(m))
m = [[1,0,0,1],
[0,1,1,0],
[0,1,1,1],
[1,0,1,1]]
print(s.findCircleNum(m))
m = [[1,1,0],
[1,1,1],
[0,1,1]]
print(s.findCircleNum(m))
m = [[1,1,1],[1,1,1],[1,1,1]]
print(s.findCircleNum(m))
|
4f311ffb537a9f0fac1386c8860d0647582de4bc | BruceHi/leetcode | /month12/divide.py | 935 | 3.625 | 4 | # 29.两数相除
class Solution:
# def divide(self, dividend: int, divisor: int) -> int:
# res = int(dividend / divisor)
# if -2**31 <= res <= 2**31-1:
# return res
# return 2**31-1
# def divide(self, dividend: int, divisor: int) -> int:
# if dividend * divisor > 0:
# res = dividend // divisor
# else:
# res = -1 * (abs(dividend) // abs(divisor))
# if -2 ** 31 <= res <= 2 ** 31 - 1:
# return res
# return 2 ** 31 - 1
def divide(self, dividend: int, divisor: int) -> int:
res = int(dividend / divisor)
if -2 ** 31 <= res <= 2 ** 31 - 1:
return res
return 2 ** 31 - 1
s = Solution()
dividend = 10
divisor = 3
print(s.divide(dividend, divisor))
dividend = 7
divisor = -3
print(s.divide(dividend, divisor))
dividend = -2147483648
divisor = -1
print(s.divide(dividend, divisor))
|
66138da67a9aa3f230ce9f864d5b55eb38023586 | BruceHi/leetcode | /month11/permute.py | 3,061 | 3.640625 | 4 | # 46. 全排列,没有重复的数字
from typing import List
from itertools import permutations
class Solution:
# 回溯
# def permute(self, nums: List[int]) -> List[List[int]]:
# res = []
# n = len(nums)
#
# def dfs(nums, cur):
# if len(cur) == n:
# res.append(cur)
# return
# for num in nums:
# if num not in cur: # 判断是否存在
# dfs(nums, cur+[num])
#
# dfs(nums, [])
# return res
# 回溯,每次选择好之后就将当前的值删掉。更推荐这个。
# def permute(self, nums: List[int]) -> List[List[int]]:
# res = []
#
# def dfs(nums, cur):
# if not nums:
# res.append(cur)
# return
#
# for i in range(len(nums)):
# dfs(nums[:i]+nums[i+1:], cur+[nums[i]])
#
# dfs(nums, [])
# return res
#
# # 使用内置函数,生成全排列
# def permute(self, nums: List[int]) -> List[List[int]]:
# # permutations(nums) 为迭代器对象
# # return list(permutations(nums))
# return list(map(list, permutations(nums)))
# def permute(self, nums: List[int]) -> List[List[int]]:
# return list(map(list, permutations(nums)))
# def permute(self, nums: List[int]) -> List[List[int]]:
# res = []
# n = len(nums)
#
# def dfs(cur, cur_idx):
# if len(cur) == n:
# res.append(cur)
# return
# for i, num in enumerate(nums):
# if i not in cur_idx:
# dfs(cur+[num], cur_idx | {i})
#
# dfs([], set())
# return res
# def permute(self, nums: List[int]) -> List[List[int]]:
# res = []
#
# def dfs(nums, cur):
# if not nums:
# res.append(cur)
# return
# for i, num in enumerate(nums):
# dfs(nums[:i] + nums[i+1:], cur+[num])
#
# dfs(nums, [])
# return res
# def permute(self, nums: List[int]) -> List[List[int]]:
# res = []
# n = len(nums)
#
# def dfs(i, cur_idx):
# if len(cur_idx) == n:
# res.append([nums[i] for i in cur_idx])
# return
# for j in range(n):
# if j != i and j not in cur_idx:
# dfs(j, cur_idx + [j])
#
# dfs(n, [])
# return res
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def dfs(nums, cur):
if not nums:
res.append(cur)
return
for i, num in enumerate(nums):
dfs(nums[:i] + nums[i+1:], cur + [num])
dfs(nums, [])
return res
s = Solution()
print(s.permute([1,2,3]))
print(s.permute([0, 1]))
print(s.permute([1]))
a = [1]
b = a + [2]
print(id(a))
print(id(b))
a += [2]
print(id(a))
|
584d2d2926aac7acffa0fa5f2ad4ba0d1e6a6278 | BruceHi/leetcode | /month8/rotate.py | 1,231 | 3.84375 | 4 | # 旋转矩阵
from typing import List
class Solution:
# def rotate(self, matrix: List[List[int]]) -> None:
# # matrix.reverse()
# matrix[:] = map(list, zip(*matrix[::-1]))
# def rotate(self, matrix: List[List[int]]) -> None:
# # matrix[::] = zip(*matrix[::-1])
# a = list(zip(matrix[::-1])) # 结果:[([7, 8, 9],), ([4, 5, 6],), ([1, 2, 3],)]
# print(a)
# b = list(zip(*matrix[::-1])) # 结果:[(7, 4, 1), (8, 5, 2), (9, 6, 3)]
# print(b)
# matrix[:] = map(list, zip(*matrix[::-1]))
# def rotate(self, matrix: List[List[int]]) -> None:
# # matrix[:] = [x[::-1] for x in list(map(list, zip(*matrix)))]
# matrix[:] = map(list, zip(*matrix[::-1]))
def rotate(self, matrix: List[List[int]]) -> None:
# matrix[:] = list(map(list, zip(*matrix[::-1])))
matrix[:] = map(list, zip(*matrix[::-1]))
s = Solution()
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
s.rotate(matrix)
print(matrix)
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
s.rotate(matrix)
print(matrix)
# a = {1, 2, 4}
# # a += {5, 6, 7}
# a += 8, 9
# print(a)
a = map(list, ['1', [2], '0'])
print(a)
print(list(a))
|
955c78d571a9435ad73640a015cdaf6f76328a9c | BruceHi/leetcode | /month4/lengthLongestPath.py | 2,861 | 3.59375 | 4 | # 388.文件的最长绝对路径
from collections import defaultdict
class Solution:
# def lengthLongestPath(self, input: str) -> int:
# res = 0
# depth_length_map = {-1: 0}
# # 按照顺序来的,所以不担心新的路径会覆盖原有的
# for line in input.split('\n'):
# depth = line.count('\t')
# # 每行制表符(空格)最后要被去掉
# # 其中 \n 表示一个字符,反斜杠和字符连在一块算一个字符
# depth_length_map[depth] = depth_length_map[depth - 1] + len(line) - depth
# if line.count('.'):
# # 每层都要添加depth个 /
# res = max(res, depth_length_map[depth] + depth)
# return res
# def lengthLongestPath(self, input: str) -> int:
# res = 0
# dic = defaultdict(int)
# for line in input.split('\n'):
# path = line.count('\t')
# dic[path] = dic[path-1] + len(line) - path
# if line.count('.'):
# res = max(res, dic[path] + path)
# return res
# def lengthLongestPath(self, input: str) -> int:
# res = 0
# dic = defaultdict(int)
# for line in input.split('\n'):
# depth = line.count('\t')
# dic[depth] = dic[depth-1] + len(line) - depth
# if line.count('.'):
# res = max(res, dic[depth] + depth)
# return res
# def lengthLongestPath(self, input: str) -> int:
# res = 0
# dic = defaultdict(int)
# for path in input.split('\n'):
# depth = path.count('\t')
# dic[depth] = dic[depth-1] + len(path) - depth
# if path.count('.'):
# res = max(res, dic[depth] + depth)
# return res
# def lengthLongestPath(self, input: str) -> int:
# res = 0
# dic = defaultdict(int)
# for line in input.split('\n'):
# depth = line.count('\t')
# dic[depth] = dic[depth-1] + len(line) - depth
# if '.' in line:
# res = max(res, dic[depth] + depth)
# return res
def lengthLongestPath(self, input: str) -> int:
res = 0
dic = defaultdict(int)
for line in input.split('\n'):
num = line.count('\t')
dic[num] = dic[num-1] + len(line) - num
if '.' in line:
res = max(res, dic[num] + num)
return res
s = Solution()
input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
print(s.lengthLongestPath(input))
input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
print(s.lengthLongestPath(input))
input = "a"
print(s.lengthLongestPath(input))
input = "file1.txt\nfile2.txt\nlongfile.txt"
print(s.lengthLongestPath(input))
|
72739ed175c389d74b8da34435f86a16c99d8fd6 | BruceHi/leetcode | /month6-21/judgeSquareSum.py | 1,127 | 3.65625 | 4 | # 633. 平方数之和
from math import sqrt
class Solution:
# def judgeSquareSum(self, c: int) -> bool:
# nums = [x*x for x in range(int(sqrt(c))+1)]
# set_nums = set(nums)
# for num in nums:
# if c-num in set_nums:
# return True
# return False
# 双指针
# def judgeSquareSum(self, c: int) -> bool:
# left, right = 0, int(sqrt(c))
# while left <= right: # 值可以取相同的
# num = left ** 2 + right ** 2
# if num == c:
# return True
# if num < c:
# left += 1
# else:
# right -= 1
# return False
def judgeSquareSum(self, c: int) -> bool:
nums = set(x*x for x in range(int(sqrt(c))+1))
for num in nums:
if c - num in nums:
return True
return False
s = Solution()
c = 5
print(s.judgeSquareSum(c))
c = 3
print(s.judgeSquareSum(c))
c = 4
print(s.judgeSquareSum(c))
c = 2
print(s.judgeSquareSum(c))
c = 1
print(s.judgeSquareSum(c))
c = 0
print(s.judgeSquareSum(c))
|
ff2dd6d3d7bcf549387843cd90478362d95eb8e6 | BruceHi/leetcode | /month12/isPowerOfThree.py | 1,107 | 4.0625 | 4 | # 326. 3 的幂
from math import log
class Solution:
# # 递归
# def isPowerOfThree(self, n: int) -> bool:
# if n == 1:
# return True
# if not n:
# return False
# if n % 3:
# return False
# return self.isPowerOfThree(n//3)
# 迭代
def isPowerOfThree(self, n: int) -> bool:
if n < 1:
return False
while n % 3 == 0:
n //= 3
return n == 1
# 使用公式,返回 float,将结果 对 1 求余(%1),若原来是整数浮点型(比如:2.0)结果是 0.0,返回 False,否则返回 True
# log 第一个参数不能是 0 或 负数
# 使用 公式错误,比如 243 是 3 的 5 次方,结果返回 4.999999
# def isPowerOfThree(self, n: int) -> bool:
# if n < 1:
# return False
# return not log(n, 3) % 1
s = Solution()
n = 27
print(s.isPowerOfThree(n))
n = 0
print(s.isPowerOfThree(n))
n = 9
print(s.isPowerOfThree(n))
n = 45
print(s.isPowerOfThree(n))
n = 243
print(s.isPowerOfThree(n))
print(log(243, 3))
|
97249980777ff838856e4ff689a4a62047dbcaf5 | BruceHi/leetcode | /month1/trap.py | 1,562 | 3.625 | 4 | # 42. 接雨水
# 与 largestRectangleArea 相似
from typing import List
class Solution:
# 构建递减(包括相同的)栈,遇见大的就弹出去
# def trap(self, height: List[int]) -> int:
# res, stack = 0, []
# for i, num in enumerate(height):
# while stack and num > height[stack[-1]]:
# idx = stack.pop()
# if stack:
# h = min(height[stack[-1]], num) - height[idx]
# res += (i-stack[-1]-1) * h
# stack.append(i)
# return res
# def trap(self, height: List[int]) -> int:
# res = 0
# stack = []
# for i, h in enumerate(height):
# while stack and height[stack[-1]] < h:
# val = height[stack.pop()]
# if stack:
# res += (i-stack[-1]-1) * (min(height[stack[-1]], h) - val)
# stack.append(i)
# return res
def trap(self, height: List[int]) -> int:
res = 0
stack = []
for i, h in enumerate(height):
while stack and height[stack[-1]] < h:
val = height[stack.pop()]
if stack:
res += (i-stack[-1]-1) * (min(height[stack[-1]], h)-val)
stack.append(i)
return res
s = Solution()
height = [1, 0, 2]
print(s.trap(height))
height = [0,1,0,2,1,0,1,3,2,1,2,1]
print(s.trap(height))
height = [4,2,0,3,2,5]
print(s.trap(height))
height = []
print(s.trap(height))
height = [1, 2, 3, 4]
print(s.trap(height))
|
3ea3fe02a309b8b7dd4b48d530d99fdd26257745 | BruceHi/leetcode | /grok/quicksort.py | 7,894 | 3.75 | 4 | # 快速排序(因为快,所以叫这个名字),要求原地排序
# 递归,非原地排序(不太合适)
# def quicksort(nums):
# if len(nums) < 2: # 包括 1 和 0 的情况
# return nums
# pivot = nums[0] # 选取第一个为基线条件,也可以选择最后一个
# less = [i for i in nums[1:] if i <= pivot]
# greater = [i for i in nums[1:] if i > pivot]
# return quicksort(less) + [pivot] + quicksort(greater)
# # 原地排序 选取
# def partition(arr, left, right):
# pivot, j = arr[left], left
# for i in range(left+1, right+1):
# if arr[i] <= pivot: # i 永远是跑得快的,遇见小的,就与 j (右面)前面一位的数交换。注意 = 号。
# j += 1 # j 指向的永远是小于或等于 pivot 的值,而他前面的不是。
# arr[i], arr[j] = arr[j], arr[i]
# arr[left], arr[j] = arr[j], arr[left]
# return j # 分类好数据,并返回分类的位置点
# def partition(arr, left, right):
# pivot, j = arr[left], left+1
# for i in range(left+1, right+1):
# if arr[i] <= pivot:
# arr[i], arr[j] = arr[j], arr[i]
# j += 1
# arr[left], arr[j-1] = arr[j-1], arr[left]
# return j-1 # 分类好数据,并返回分类的位置点
# 原地排序 推荐使用右边的数为基准值
# def partition(arr, left, right): # 选取最右边的数为基准值
# pivot, j = arr[right], left
# for i in range(left, right):
# if arr[i] < pivot: # j 停在了小的地方
# arr[i], arr[j] = arr[j], arr[i] # 然后交换
# j += 1 # j 指向的永远是大于 pivot 的值,即待交换位置。j 停在了大的地方。
# arr[right], arr[j] = arr[j], arr[right]
# return j
#
#
# def quicksort(arr, left=None, right=None):
# # 第一次进行调用的时候,left 和 right 没有进行赋值,要进行特殊处理。
# if left is None:
# left = 0
# if right is None: # 不能写成 not right, 如果 right = 0 时,right 就会被重新赋值为 arr 整个长度(很长) - 1.
# right = len(arr) - 1
# if left < right: # 排序条件
# p = partition(arr, left, right)
# quicksort(arr, left, p-1)
# quicksort(arr, p+1, right)
# return arr
# def quicksort(arr, left=None, right=None):
# if left is None:
# left = 0
# if right is None:
# right = len(arr) - 1
# if left < right:
# p = partition(arr, left, right)
# quicksort(arr, left, p-1)
# quicksort(arr, p+1, right)
# return arr
#
#
# def partition(arr, left, right):
# pivot, j = arr[right], left
# for i in range(left, right):
# if arr[i] < pivot:
# arr[i], arr[j] = arr[j], arr[i]
# j += 1
# arr[j], arr[right] = arr[right], arr[j]
# return j
from typing import List
# def quick_sort(nums: List[int], left=None, right=None) -> List[int]:
# if left is None:
# left = 0
# if right is None:
# right = len(nums) - 1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p-1)
# quick_sort(nums, p+1, right)
# return nums
#
#
# def partition(nums: List[int], left: int, right: int) -> int:
# pivot, j = nums[right], left
# for i in range(left, right):
# if nums[i] < pivot:
# nums[i], nums[j] = nums[j], nums[i]
# j += 1
# nums[j], nums[right] = pivot, nums[j]
# return j
# left, right 都是 int 类型,代表区间
# def quick_sort(nums, left=None, right=None):
# if left is None and right is None:
# left, right = 0, len(nums) - 1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p-1)
# quick_sort(nums, p+1, right)
# return nums
#
#
# def partition(nums, left, right):
# pivot, i = nums[right], left
# for j in range(left, right):
# if nums[j] < pivot:
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[right] = pivot, nums[i]
# return i
# left, right 表示要排序的区间范围
# def quick_sort(nums: List[int], left=None, right=None) -> List[int]:
# if left is None and right is None:
# left, right = 0, len(nums) - 1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p-1)
# quick_sort(nums, p+1, right)
# return nums
#
#
# def partition(nums: List[int], left: int, right: int) -> int:
# pivot, i = nums[right], left
# for j in range(left, right):
# if nums[j] < pivot: # 小于交换
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[right] = pivot, nums[i]
# return i
# def quick_sort(nums: List[int], left: int = None, right: int = None):
# if left is None and right is None:
# left, right = 0, len(nums) - 1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p - 1)
# quick_sort(nums, p + 1, right)
# return nums
#
#
# def partition(nums: List[int], left: int, right: int):
# i, pivot = left, nums[right]
# for j in range(left, right):
# if nums[j] < pivot:
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[right] = pivot, nums[i]
# return i
# def quick_sort(nums, left=None, right=None):
# if left is None and right is None:
# left, right = 0, len(nums) - 1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p-1)
# quick_sort(nums, p+1, right)
# return nums
#
#
# def partition(nums, left, right):
# i, pivot = left, nums[right]
# for j in range(left, right): # left 也要算在内
# if nums[j] < pivot:
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[right] = pivot, nums[i]
# return i
# def quick_sort(nums, left=None, right=None):
# if left is None and right is None:
# left, right = 0, len(nums)-1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p-1)
# quick_sort(nums, p+1, right)
# return nums
#
#
# def partition(nums, left, right):
# pivot, i = nums[right], left
# for j in range(left, right):
# if nums[j] < pivot:
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[right] = pivot, nums[i]
# return i
# def quick_sort(nums, left=None, right=None):
# if left is None and right is None:
# left, right = 0, len(nums) - 1
# if left < right:
# p = partition(nums, left, right)
# quick_sort(nums, left, p-1)
# quick_sort(nums, p+1, right)
# return nums
#
# def partition(nums, left, right):
# i, pivot = left, nums[right]
# for j in range(left, right):
# if nums[j] < pivot:
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[right] = pivot, nums[i]
# return i
def quick_sort(nums, left=None, right=None):
if left is None and right is None:
left, right = 0, len(nums)-1
if left < right:
p = partition(nums, left, right)
quick_sort(nums, left, p-1)
quick_sort(nums, p+1, right)
def partition(nums, left, right):
i, pivot = left, nums[right]
for j in range(left, right):
if nums[j] < pivot:
nums[i], nums[j] = nums[j], nums[i]
i += 1
nums[i], nums[right] = pivot, nums[i]
return i
num = [5, 8, 9, 1, 2]
quick_sort(num)
print(num)
nums = []
quick_sort(nums)
print(nums)
nums = [1]
quick_sort(nums)
print(nums)
nums = [1, 4, 5, 6, 5, 6]
quick_sort(nums)
print(nums)
nums = [2, 7, 4, 1, 0]
quick_sort(nums)
print(nums)
|
652cf776936eb888b53f85cd45390403f8ce28db | BruceHi/leetcode | /month12-21/superPow.py | 1,377 | 3.65625 | 4 | # 372. 超级次方
from typing import List
class Solution:
# 超时
# def superPow(self, a: int, b: List[int]) -> int:
# num = 0
# for n in b:
# num = num * 10 + n
# return a ** num % 1337
# 快速幂 超时
# def superPow(self, a: int, b: List[int]) -> int:
# def power(x, y):
# if y == 0:
# return 1
# if y == 1:
# return x
# tmp = power(x, y // 2)
# if y & 1:
# return tmp * tmp * x
# return tmp * tmp
#
# num = 0
# for n in b:
# num = num * 10 + n
# return power(a, num) % 1337
# 快速幂 + 递归
def superPow(self, a: int, b: List[int]) -> int:
def power(x, y):
if y == 0:
return 1
if y == 1:
return x
tmp = power(x, y // 2)
if y & 1:
return tmp * tmp * x
return tmp * tmp
def dfs(i):
if i == -1:
return 1
return power(dfs(i-1), 10) * power(a, b[i]) % 1337
return dfs(len(b)-1)
s = Solution()
a = 2
b = [3]
print(s.superPow(a, b))
a = 2
b = [1,0]
print(s.superPow(a, b))
a = 1
b = [4,3,3,8,5,2]
print(s.superPow(a, b))
a = 2147483647
b = [2,0,0]
print(s.superPow(a, b))
|
75ab64c2c8fb273d494f53835992c627be34d051 | BruceHi/leetcode | /month3/lemonadeChange.py | 1,529 | 3.78125 | 4 | # 860. 柠檬水找零
from typing import List
class Solution:
# def lemonadeChange(self, bills: List[int]) -> bool:
# count5, count10 = 0, 0
# for bill in bills:
# if bill == 5:
# count5 += 1
# elif bill == 10:
# if count5 == 0:
# return False
# count5, count10 = count5-1, count10+1
# else:
# if count5 == 0:
# return False
# elif count5 <= 2 and count10 == 0:
# return False
# elif count10 >= 1:
# count5, count10 = count5-1, count10-1
# else:
# count5 -= 3
# return True
def lemonadeChange(self, bills: List[int]) -> bool:
count5, count10 = 0, 0
for bill in bills:
if bill == 5:
count5 += 1
elif bill == 10:
count5, count10 = count5-1, count10+1
else:
if count10:
count5, count10 = count5-1, count10-1
else:
count5 -= 3
if count5 < 0:
return False
return True
s = Solution()
bills = [5,5,5,10,20]
print(s.lemonadeChange(bills))
bills = [5,5,10]
print(s.lemonadeChange(bills))
bills = [10,10]
print(s.lemonadeChange(bills))
bills = [5,5,10,10,20]
print(s.lemonadeChange(bills))
bills = [5,5,5,10,5,5,10,20,20,20]
print(s.lemonadeChange(bills))
|
c12a78a64c19a88eeedaca4e54f0bef52715bb43 | BruceHi/leetcode | /DFS/generateParenthesis.py | 5,853 | 3.59375 | 4 | # 括号生成
from typing import List
class Solution:
# # 原始解法,不太好
# def generateParenthesis(self, n: int):
# res = set()
#
# def DFS(s, c, left, right): # s: 当前拼接到的字符串,c:传入的括号
# if len(s) == 2 * n:
# res.add(s)
# return
#
# s += c
# if c == '(':
# left += 1
# else:
# right += 1
#
# if right <= left <= n:
# DFS(s, '(', left, right)
# DFS(s, ')', left, right)
#
# DFS('', '(', 0, 0)
# return list(res)
# 改进
# def generateParenthesis(self, n: int):
# res = []
#
# def DFS(s, left, right):
# if len(s) == 2 * n:
# res.append(s)
# return
#
# if left < n:
# DFS(s+'(', left+1, right)
# if right < left:
# DFS(s+')', left, right+1)
#
# DFS('', 0, 0)
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(cur, left, right):
# if len(cur) == 2 * n:
# res.append(cur)
# return
#
# if right < left:
# dfs(cur + ')', left, right + 1)
# if left < n:
# dfs(cur + '(', left + 1, right)
#
# dfs('(', 1, 0)
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(cur, left, right):
# if right > left:
# return
# if len(cur) == n * 2:
# if left == right:
# res.append(cur)
# return
# dfs(cur+'(', left+1, right)
# dfs(cur+')', left, right+1)
#
# dfs('', 0, 0)
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(cur, left, right):
# if len(cur) == 2 * n:
# res.append(cur)
# return
# if left > right:
# dfs(cur+')', left, right+1)
# if left < n:
# dfs(cur+'(', left+1, right)
#
# dfs('', 0, 0)
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(left, right, cur):
# if left < right:
# return
# if len(cur) == 2 * n:
# if left == n:
# res.append(cur)
# return
# dfs(left+1, right, cur+'(')
# dfs(left, right+1, cur+')')
#
# dfs(0, 0, '')
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(cur, left, right):
# if len(cur) == n * 2:
# res.append(cur)
# return
#
# if left > right:
# dfs(cur+')', left, right+1)
# if left < n:
# dfs(cur+'(', left+1, right)
#
# dfs('', 0, 0)
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(left, right, cur):
# if len(cur) == 2 * n:
# res.append(cur)
# return
# if left < n:
# dfs(left+1, right, cur+'(')
# if right < left:
# dfs(left, right+1, cur+')')
#
# dfs(0, 0, '')
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(left, right, cur):
# if len(cur) == 2 * n:
# if left == right:
# res.append(cur)
# return
# if left < right:
# return
# dfs(left+1, right, cur + '(')
# dfs(left, right+1, cur + ')')
#
# dfs(0, 0, '')
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(left, right, cur):
# if len(cur) == 2 * n:
# res.append(cur)
# return
# if left < n:
# dfs(left+1, right, cur + '(')
# if right < left:
# dfs(left, right+1, cur + ')')
#
# dfs(0, 0, '')
# return res
# def generateParenthesis(self, n: int) -> List[str]:
# res = []
#
# def dfs(left, right, cur):
# if left < right:
# return
# if len(cur) == 2 * n:
# res.append(cur)
# return
# if left < n:
# dfs(left + 1, right, cur + '(')
# dfs(left, right + 1, cur + ')')
#
# dfs(0, 0, '')
# return res
def generateParenthesis(self, n: int) -> List[str]:
res = []
def dfs(left, right, cur):
if len(cur) == 2 * n:
res.append(cur)
return
if left < n:
dfs(left + 1, right, cur + '(')
if right < left:
dfs(left, right + 1, cur + ')')
dfs(0, 0, '')
return res
s = Solution()
print(s.generateParenthesis(1))
print(s.generateParenthesis(2))
print(s.generateParenthesis(3))
a = ["()((()))","(()())()","((()))()","()(())()","(())()()","(((())))","()()()()","(()()())","()(()())","(()(()))","((()()))","((())())","()()(())"]
b = ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"]
for i in b:
if i not in a:
print(i)
break
|
2cf1017d544db7c2389726d4468ca65201788d4f | BruceHi/leetcode | /month3/verifyPostorder.py | 638 | 3.9375 | 4 | # 剑指 offer 33.二叉搜索树的后序遍历序列
from typing import List
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def dfs(left, right):
if left >= right:
return True
root = postorder[right]
mid = left
while postorder[mid] < root:
mid += 1
# 判断后面的是否都比root大
for i in range(mid+1, right):
if postorder[i] <= root:
return False
return dfs(left, mid-1) and dfs(mid, right-1)
return dfs(0, len(postorder)-1)
|
6a4d7784b455c699c8f41eb252a27b9c2a64b77e | BruceHi/leetcode | /month1/checkPossibility.py | 832 | 3.625 | 4 | # 655. 非递减数列
from typing import List
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
changed = False
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
if changed:
return False
changed = True
# 修改后者
if i > 0 and nums[i-1] > nums[i+1]:
nums[i+1] = nums[i]
else:
nums[i] = nums[i+1]
return True
s = Solution()
nums = [4,2,3]
print(s.checkPossibility(nums))
nums = [4,2,1]
print(s.checkPossibility(nums))
nums = [-1,4,2,3]
print(s.checkPossibility(nums))
nums = [-1,1,2,3]
print(s.checkPossibility(nums))
nums = [3,4,2,3]
print(s.checkPossibility(nums))
nums = [3,4,2,5]
print(s.checkPossibility(nums))
|
0e977ce63c8e0e46615d7f90042431e8276ede74 | BruceHi/leetcode | /month3/addDigits.py | 460 | 3.640625 | 4 | # 258. 各位相加
class Solution:
def addDigits(self, num: int) -> int:
def get_nums(num):
res = 0
while num:
res += num % 10
num //= 10
return res
if num < 10:
return num
res = get_nums(num)
while res >= 10:
res = get_nums(res)
return res
s = Solution()
num = 38
print(s.addDigits(num))
num = 0
print(s.addDigits(num)) |
59643b32b20b675745daeb327ef70660e0f1e430 | BruceHi/leetcode | /month12/reverseLeftWords.py | 270 | 3.734375 | 4 | # 剑指 offer 58-2.左旋转字符串
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:] + s[:n]
obj = Solution()
s = "abcdefg"
k = 2
print(obj.reverseLeftWords(s, k))
s = "lrloseumgh"
k = 6
print(obj.reverseLeftWords(s, k))
|
3a44ec0068bcca1af854e071b5a01868d93d679c | BruceHi/leetcode | /month7/searchInsert.py | 908 | 3.796875 | 4 | # 搜索插入位置
from typing import List
import bisect
class Solution:
# def searchInsert(self, nums: List[int], target: int) -> int:
# return bisect.bisect_left(nums, target)
# def searchInsert(self, nums: List[int], target: int) -> int:
# return bisect.bisect_left(nums, target)
def searchInsert(self, nums: List[int], target: int) -> int:
if nums[-1] < target: # 特判,因为后面的 left 取值范围是 [0, len(nums) - 1]
return len(nums)
left, right = 0, len(nums) - 1
while left < right:
mid = left + right >> 1
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left
s = Solution()
print(s.searchInsert([1,3,5,6], 5))
print(s.searchInsert([1,3,5,6], 2))
print(s.searchInsert([1,3,5,6], 7))
print(s.searchInsert([1,3,5,6], 0))
|
c454efbc05cf6d8231e6807312be9d71ccd9cf58 | BruceHi/leetcode | /month12/findNumberIn2DArray.py | 1,823 | 3.84375 | 4 | # 剑指 offer 04. 二维数组中的查找
# 与 240. 搜索二维矩阵 II searchMatrix 一样
from typing import List
class Solution:
# def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# if not matrix:
# return False
# m, n = len(matrix), len(matrix[0])
# i, j = m-1, 0
# # while 0 <= i < m and 0 <= j < n:
# while i >= 0 and j < n: # 不用完整的判定
# if matrix[i][j] < target:
# j += 1
# elif matrix[i][j] > target:
# i -= 1
# else:
# return True
# return False
# def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# if not matrix or not matrix[0]:
# return False
# m, n = len(matrix), len(matrix[0])
# i, j = m-1, 0
# while i >= 0 and j < n:
# if target < matrix[i][j]:
# i -= 1
# elif target > matrix[i][j]:
# j += 1
# else:
# return True
# return False
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
m, n = len(matrix), len(matrix[0])
i, j = m-1, 0
while i >= 0 and j < n:
if matrix[i][j] == target:
return True
if matrix[i][j] < target:
j += 1
else:
i -= 1
return False
s = Solution()
matrix = [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
print(s.findNumberIn2DArray(matrix, target=5))
print(s.findNumberIn2DArray(matrix, target=20))
print(s.findNumberIn2DArray([[]], target=20))
|
a22fb70a8d897b1764f4a1fffd97c6ce72edab55 | BruceHi/leetcode | /other/maxArea.py | 1,892 | 3.625 | 4 | # 盛最多水的容器
# def maxArea(height):
# left = 0
# right = len(height) - 1
# area = 0
# while left < right: # 低的移动,木桶盛水多少取决于最短的那个
# if height[left] >= height[right]:
# area = max(area, height[right] * (right-left))
# right -= 1
# else:
# area = max(area, height[left] * (right - left))
# left += 1
# return area
from typing import List
# def maxArea(height: List[int]) -> int:
# left, right = 0, len(height) - 1
# res = 0
# while left < right:
# if height[left] < height[right]:
# area = (right - left) * height[left]
# left += 1
# else:
# area = (right - left) * height[right]
# right -= 1
# res = max(area, res)
# return res
# def maxArea(height: List[int]) -> int:
# left, right = 0, len(height) - 1
# res = 0
# while left < right:
# area = (right - left) * min(height[left], height[right])
# res = max(area, res)
# if height[left] < height[right]:
# left += 1
# else:
# right -= 1
# return res
# def maxArea(height: List[int]) -> int:
# left, right = 0, len(height) - 1
# res = 0
# while left < right:
# res = max(res, (right-left)*min(height[left], height[right]))
# if height[left] < height[right]:
# left += 1
# else:
# right -= 1
# return res
def maxArea(height: List[int]) -> int:
res = float('-inf')
left, right = 0, len(height)-1
while left < right:
res = max(res, (right-left)*min(height[left], height[right]))
if height[left] < height[right]:
left += 1
else:
right -= 1
return res
h = [1,8,6,2,5,4,8,3,7]
print(maxArea(h))
h = [1,8]
print(maxArea(h)) |
53d86618be06468d738d16539864f2d425fe507b | BruceHi/leetcode | /month8-21/isPrefixString.py | 814 | 3.625 | 4 | from typing import List
class Solution:
# def isPrefixString(self, s: str, words: List[str]) -> bool:
# return ''.join(words).startswith(s)
def isPrefixString(self, s: str, words: List[str]) -> bool:
i = 0
for word in words:
n = len(word)
if s[i:n+i] != word:
return False
i += n
if i == len(s):
return True
return False
obj = Solution()
s = "iloveleetcode"
words = ["i","love","leetcode","apples"]
print(obj.isPrefixString(s, words))
s = "iloveleetcode"
words = ["apples","i","love","leetcode"]
print(obj.isPrefixString(s, words))
s = "a"
words = ["aa","i","love","leetcode"]
print(obj.isPrefixString(s, words))
s = "ccccccccc"
words = ["c","cc"]
print(obj.isPrefixString(s, words))
|
613302288e873e5389c81681278d6898c5510d38 | BruceHi/leetcode | /Array/removeDuplicates.py | 2,968 | 3.59375 | 4 | # 失败
# def removeDuplicates(nums):
# for i in range(len(nums) - 2):
# m = i + 1
# for j in range(m, len(nums)):
# if nums[i] == nums[j]:
# nums.remove(nums[j])
# if nums[-1] == nums[-2]:
# nums.remove(nums[-1])
# 从排序数组中删除重复项
# def removeDuplicates(nums):
# for i in range(len(nums) - 1):
# for j in nums[i+1:]:
# if nums[i] == j:
# nums.remove(j) # 删除第一个与该值相等的匹配项,然后相对关系并没有发生改变。
# # nums.pop(i+1) # 实际上删除后面的也完全可以。
# else:
# break # 用break时,表明只要下一个数字不相等,就退出该次循环。如果去掉的话,要白白遍历到头,因为说了是有序的。
# return len(nums)
#
#
# list1 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
# print(removeDuplicates(list1))
# print(list1)
#
# 成功
# def removeDuplicates(nums):
# i = 0
# while i < len(nums) - 1:
# if nums[i] == nums[i+1]:
# nums.remove(nums[i]) # 去掉前面那个相同的,退出if,下次循环时,还是刚才的那个i.
# else: # 如果去掉了else就变成了死循环
# i += 1
# return len(nums)
# def removeDuplicates(nums):
# if not nums:
# return 0
# slow = 0
# for fast in range(1, len(nums)):
# if nums[slow] != nums[fast]:
# slow += 1
# nums[slow] = nums[fast]
# return slow + 1
from typing import List
# def removeDuplicates(nums: List[int]) -> int:
# if not nums:
# return 0
# i = 0
# for j in range(1, len(nums)):
# if nums[i] != nums[j]:
# i += 1
# nums[i] = nums[j]
# return i + 1
# def removeDuplicates(nums: List[int]) -> int:
# if not nums:
# return 0
# i = 0
# for j, num in enumerate(nums):
# if num != nums[i]:
# i += 1
# nums[i] = num
# return i + 1
# def removeDuplicates(nums: List[int]) -> int:
# if not nums:
# return 0
# i = 0
# for num in nums:
# if num != nums[i]:
# i += 1
# nums[i] = num
# return i + 1
# def removeDuplicates(nums: List[int]) -> int:
# if not nums:
# return 0
# i = 0
# for num in nums:
# if num != nums[i]:
# i += 1
# nums[i] = num
# return i + 1
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
i = 0
for num in nums:
if num != nums[i]:
i += 1
nums[i] = num
return i + 1
s = Solution()
nums = [1,1,2]
print(s.removeDuplicates(nums))
print(nums)
list1 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
print(s.removeDuplicates(list1))
print(list1)
list1 = []
print(s.removeDuplicates(list1))
print(list1)
|
4192e51a0b5c3473206a8dacbb8aa42f7d43b0f6 | BruceHi/leetcode | /month11/hammingDistance.py | 476 | 3.78125 | 4 | # 461.汉明距离
class Solution:
# def hammingDistance(self, x: int, y: int) -> int:
# dist = x ^ y
# res = 0
# while dist:
# res += 1
# dist &= dist - 1
# return res
# def hammingDistance(self, x: int, y: int) -> int:
# return bin(x ^ y).count('1')
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count('1')
s = Solution()
x = 1
y = 4
print(s.hammingDistance(x, y))
|
234bbcfc1eaae78c7f1da50312404d0332b313c6 | BruceHi/leetcode | /month12/runningSum.py | 865 | 3.6875 | 4 | # 1480. 一维数组的动态和
from typing import List
class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# res = [0]
# for num in nums:
# res.append(res[-1] + num)
# return res[1:]
# # 修改 nums 的值,这样是错误的,边运行边解包
# def runningSum(self, nums: List[int]) -> List[int]:
# # 这样错误,在下次使用之前,已经解包了
# for i, num in enumerate(nums[:-1]):
# nums[i+1] += num
# return nums
# 修改 nums 的值
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return nums
s = Solution()
nums = [1,2,3,4]
print(s.runningSum(nums))
nums = [1,1,1,1,1]
print(s.runningSum(nums))
nums = [3,1,2,10,1]
print(s.runningSum(nums))
|
dd0d8ca77f1de34a52a741563d9c5dca0dbcfe40 | BruceHi/leetcode | /Tree/isSameTree.py | 1,147 | 3.84375 | 4 | # 相同的树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 先序遍历
# def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
#
# def preorder(root):
# if not root:
# return '-'
# return str(root.val) + ',' + preorder(root.left) + ',' + preorder(root.right)
#
# return preorder(p) == preorder(q)
# def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
# if not p and not q:
# return True
# elif not p or not q:
# return False
# elif p.val != q.val:
# return False
# return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) \
and self.isSameTree(p.right, q.right)
|
3cf0a3f3c1a9b21735d80f5199ad7699e53ea50e | BruceHi/leetcode | /queue/MyCircularQueue.py | 9,350 | 4.03125 | 4 | # 设计循环队列
# # 这种方法没有达到空间的循环利用,不太好。
# class MyCircularQueue:
#
# def __init__(self, k: int):
# """
# Initialize your data structure here. Set the size of the queue to be k.
# """
# self.queue = [] # 使用可扩展的列表,才不会出现溢出问题,妙啊。
# self.capacity = k # 队列容量(数组长度)
#
# def enQueue(self, value: int) -> bool:
# """
# Insert an element into the circular queue. Return true if the operation is successful.
# """
# if len(self.queue) == self.capacity: # 判断队空还是队满,只需比较容量和队列长度即可
# return False
# self.queue.append(value)
# return True
#
# # 时间复杂度为 O(n),不太好。
# def deQueue(self) -> bool:
# """
# Delete an element from the circular queue. Return true if the operation is successful.
# """
# if not self.queue:
# return False
# self.queue.pop(0)
# return True
#
# def Front(self) -> int:
# """
# Get the front item from the queue.
# """
# if not self.queue:
# return -1
# return self.queue[0]
#
# def Rear(self) -> int:
# """
# Get the last item from the queue.
# """
# if not self.queue:
# return -1
# return self.queue[-1]
#
# def isEmpty(self) -> bool:
# """
# Checks whether the circular queue is empty or not.
# """
# return not self.queue
#
# def isFull(self) -> bool:
# """
# Checks whether the circular queue is full or not.
# """
# return len(self.queue) == self.capacity
#
# def __repr__(self) -> str:
# return str(self.queue)
# 真正的循环队列,时间复杂度都是 O(1)。
# class MyCircularQueue:
#
# def __init__(self, k: int):
# """
# Initialize your data structure here. Set the size of the queue to be k.
# """
# self.queue = [0] * (k + 1) # 要多留一个长度
# self.head = 0
# self.tail = 0
# self.capacity = k + 1 # 后面要多次用到,所以保留了。
#
# def enQueue(self, value: int) -> bool:
# """
# Insert an element into the circular queue. Return true if the operation is successful.
# """
# if self.isFull():
# return False
# self.queue[self.tail] = value
# self.tail = (self.tail + 1) % self.capacity # 往后移一位,再求余
# return True
#
# def deQueue(self) -> bool:
# """
# Delete an element from the circular queue. Return true if the operation is successful.
# """
# if self.isEmpty():
# return False
#
# # 不需要改变值,直接移动指针即可。
# self.head = (self.head + 1) % self.capacity
# return True
#
# def Front(self) -> int:
# """
# Get the front item from the queue.
# """
# if self.isEmpty():
# return -1
# return self.queue[self.head]
#
# def Rear(self) -> int:
# """
# Get the last item from the queue.
# """
# if self.isEmpty():
# return -1
# # + capacity 是为了保证 tail=0 时,可以正常得出结果。
# return self.queue[(self.tail - 1 + self.capacity) % self.capacity]
#
# def isEmpty(self) -> bool:
# """
# Checks whether the circular queue is empty or not.
# """
# return self.head == self.tail
#
# def isFull(self) -> bool:
# """
# Checks whether the circular queue is full or not.
# """
# return (self.tail + 1) % self.capacity == self.head
# class MyCircularQueue:
#
# def __init__(self, k: int):
# self.queue = [0] * (k + 1)
# self.head = 0
# self.tail = 0
# self.capacity = k + 1
#
# def enQueue(self, value: int) -> bool:
# if self.isFull():
# return False
# self.queue[self.tail] = value
# self.tail = (self.tail + 1) % self.capacity
# return True
#
# def deQueue(self) -> bool:
# if self.isEmpty():
# return False
# self.head = (self.head + 1) % self.capacity
# return True
#
# def Front(self) -> int:
# if self.isEmpty():
# return -1
# return self.queue[self.head]
#
# def Rear(self) -> int:
# if self.isEmpty():
# return -1
# return self.queue[self.tail-1]
#
# def isEmpty(self) -> bool:
# return self.tail == self.head
#
# def isFull(self) -> bool:
# return (self.tail + 1) % self.capacity == self.head
# class MyCircularQueue:
#
# def __init__(self, k: int):
# self.nums = (k + 1) * [0]
# self.capacity = k + 1
# self.head = 0
# self.tail = 0
#
#
# def enQueue(self, value: int) -> bool:
# if self.isFull():
# return False
# self.nums[self.tail] = value
# self.tail = (self.tail + 1) % self.capacity
# return True
#
#
# def deQueue(self) -> bool:
# if self.isEmpty():
# return False
# self.head = (self.head + 1) % self.capacity
# return True
#
# def Front(self) -> int:
# if self.isEmpty():
# return -1
# return self.nums[self.head]
#
# def Rear(self) -> int:
# if self.isEmpty():
# return -1
# return self.nums[self.tail - 1]
#
# def isEmpty(self) -> bool:
# return self.head == self.tail
#
# def isFull(self) -> bool:
# return (self.tail + 1) % self.capacity == self.head
# 右进左出
# class MyCircularQueue:
#
# def __init__(self, k: int):
# self.nums = [0] * (k+1)
# self.capacity = k + 1
# self.head = 0
# self.tail = 0
#
# # 右边是尾部
# def enQueue(self, value: int) -> bool:
# if self.isFull():
# return False
# self.nums[self.tail] = value
# self.tail = (self.tail + 1) % self.capacity
# return True
#
# def deQueue(self) -> bool:
# if self.isEmpty():
# return False
# self.head = (self.head + 1) % self.capacity
# return True
#
# def Front(self) -> int:
# if self.isEmpty():
# return -1
# return self.nums[self.head]
#
# def Rear(self) -> int:
# if self.isEmpty():
# return -1
# return self.nums[self.tail-1]
#
# def isEmpty(self) -> bool:
# return self.head == self.tail
#
# def isFull(self) -> bool:
# return (self.tail + 1) % self.capacity == self.head
# class MyCircularQueue:
#
# def __init__(self, k: int):
# self.nums = [0] * (k+1)
# self.capacity = k + 1
# self.head = 0
# self.tail = 0
#
# def enQueue(self, value: int) -> bool:
# if self.isFull():
# return False
# self.nums[self.tail % self.capacity] = value
# self.tail = (self.tail + 1) % self.capacity
# return True
#
#
# def deQueue(self) -> bool:
# if self.isEmpty():
# return False
# self.head = (self.head + 1) % self.capacity
# return True
#
#
# def Front(self) -> int:
# if self.isEmpty():
# return -1
# return self.nums[self.head]
#
#
# def Rear(self) -> int:
# if self.isEmpty():
# return -1
# return self.nums[self.tail-1]
#
#
# def isEmpty(self) -> bool:
# return self.head == self.tail
#
#
# def isFull(self) -> bool:
# return (self.tail + 1) % self.capacity == self.head
# 入队的时候是 tail + 1,即队尾加
class MyCircularQueue:
def __init__(self, k: int):
self.nums = [0] * (k + 1)
self.capacity = k + 1
self.head = 0
self.tail = 0
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self.nums[self.tail] = value
self.tail = (self.tail + 1) % self.capacity
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self.head = (self.head + 1) % self.capacity
return True
def Front(self) -> int:
if self.isEmpty():
return -1
return self.nums[self.head]
def Rear(self) -> int:
if self.isEmpty():
return -1
return self.nums[self.tail-1]
def isEmpty(self) -> bool:
return self.tail == self.head
def isFull(self) -> bool:
return (self.tail + 1) % self.capacity == self.head
if __name__ == "__main__":
q = MyCircularQueue(5)
for i in range(5):
q.enQueue(i)
q.deQueue()
q.deQueue()
q.enQueue(5)
print(q.nums)
circularQueue = MyCircularQueue(3)
print(circularQueue.enQueue(1))
print(circularQueue.enQueue(2))
print(circularQueue.enQueue(3))
print(circularQueue.enQueue(4))
print(circularQueue.Rear())
print(circularQueue.isFull())
print(circularQueue.deQueue())
print(circularQueue.enQueue(4))
print(circularQueue.Rear())
|
93bcc701b30e3b1061d11b8d82c85d464ad920c1 | BruceHi/leetcode | /month8/merge.py | 4,438 | 3.9375 | 4 | # 合并两个有序数组到 nums1
# 面试题 10.01. 合并排序的数组
from typing import List
class Solution:
# 递归
# def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# """
# Do not return anything, modify nums1 in-place instead.
# """
# def merge_two(nums1, nums2):
# if not nums1:
# return nums2
# if not nums2:
# return nums1
# if nums1[0] < nums2[0]:
# return [nums1[0]] + merge_two(nums1[1:], nums2)
# return [nums2[0]] + merge_two(nums1, nums2[1:])
#
# nums = merge_two(nums1[:m], nums2)
# nums1[:m+n] = nums
# 迭代
# def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# tmp = nums1[:m]
# nums1[:] = [] # 必须是切片赋值
# i = j = 0
#
# while i < m and j < n:
# if tmp[i] < nums2[j]:
# nums1.append(tmp[i])
# i += 1
# else:
# nums1.append(nums2[j])
# j += 1
#
# if i < m:
# nums1.extend(tmp[i:])
# if j < n:
# nums1.extend(nums2[j:])
# # 迭代,从前往后遍历,空间复杂度为 O(m),由于要复制一份 nums1[:m]
# def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# nums1_copy = nums1[:m]
# nums1[:] = [] # 必须是切片赋值
# i, j = 0, 0
#
# while i < m and j < n:
# if nums1_copy[i] < nums2[j]:
# nums1.append(nums1_copy[i])
# i += 1
# else:
# nums1.append(nums2[j])
# j += 1
#
# if i < m:
# nums1 += nums1_copy[i:]
# if j < n:
# nums1 += nums2[j:]
# 迭代,从后往前遍历,不占用额外空间,空间复杂度是 O(1)
# 因为切片产生新的对象,大小为 O(j),此时因为 j >= 0 中不知道剩余 j 是多少,按最长的算,
# 时间复杂度应该是 O(n)
# def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# p = m + n - 1
# i, j = m-1, n-1
#
# while i >= 0 and j >= 0:
# if nums1[i] > nums2[j]:
# nums1[p] = nums1[i]
# i -= 1
# else:
# nums1[p] = nums2[j]
# j -= 1
# p -= 1
#
# if j >= 0:
# nums1[:p+1] = nums2[:j+1]
# def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
# k = m + n - 1
# i, j = m-1, n-1
# while i >= 0 and j >= 0:
# if A[i] > B[j]:
# A[k] = A[i]
# i -= 1
# else:
# A[k] = B[j]
# j -= 1
# k -= 1
# print(id(B))
# if j >= 0:
# print(id(B[:j+1]))
# A[:k+1] = B[:j+1]
# 真正的时间复杂度为 O(1) 的情况
# def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
# k = m + n - 1
# i, j = m-1, n-1
# while i >= 0 and j >= 0:
# if A[i] > B[j]:
# A[k] = A[i]
# i -= 1
# else:
# A[k] = B[j]
# j -= 1
# k -= 1
#
# while j >= 0:
# A[j] = B[j]
# j -= 1
# # if j >= 0:
# # for i in range(j+1):
# # A[i] = B[i]
# # A[:j+1] = B[:j+1]
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
i, j = m-1, n-1
k = m + n - 1
while i >= 0 and j >= 0:
if nums1[i] < nums2[j]:
nums1[k] = nums2[j]
j -= 1
else:
nums1[k] = nums1[i]
i -= 1
k -= 1
if j >= 0:
nums1[:j+1] = nums2[:j+1]
s = Solution()
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
s.merge(nums1, m, nums2, n)
print(nums1)
# nums1 = [0]
# m = 0
# nums2 = [1]
# n = 1
# s.merge(nums1, m, nums2, n)
# print(nums1) # 结果是 [1]
nums1 = [1]
m = 1
nums2 = []
n = 0
s.merge(nums1, m, nums2, n)
print(nums1) # 结果是 [1]
nums1 = [4,5,6,0,0,0]
m = 3
nums2 = [1,2,3]
n = 3
s.merge(nums1, m, nums2, n)
print(nums1)
|
281d2dd7982ececea09b887d6b495209e07a3f0e | BruceHi/leetcode | /month6-21/largestOddNumber.py | 342 | 3.5 | 4 | class Solution:
def largestOddNumber(self, num: str) -> str:
for i in range(len(num)-1, -1, -1):
if int(num[i]) & 1:
return num[:i+1]
return ''
s = Solution()
num = "52"
print(s.largestOddNumber(num))
num = "4206"
print(s.largestOddNumber(num))
num = "35427"
print(s.largestOddNumber(num))
|
ad440ed2075442df0c269b2354a57b7ce26b0154 | BruceHi/leetcode | /month11-21/detectCapitalUse.py | 340 | 3.5 | 4 | # 520. 检测大写字母
class Solution:
def detectCapitalUse(self, word: str) -> bool:
# return word in (word.upper(), word.capitalize(), word.lower())
return word.isupper() or word.islower() or word.istitle()
s = Solution()
word = "USA"
print(s.detectCapitalUse(word))
word = "FlaG"
print(s.detectCapitalUse(word))
|
867b0c8bd24505a9b0674e62b0c8ecbe1b719669 | BruceHi/leetcode | /bitOperate/missingNumber.py | 2,038 | 3.59375 | 4 | # 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
from functools import reduce
from operator import ixor
from typing import List
class Solution:
# 数学方法
# def missingNumber(self, nums) -> int:
# n = len(nums)
# return n * (n+1) // 2 - sum(nums)
# 按位异或
# def missingNumber(self, nums) -> int:
# res = len(nums)
# for i, num in enumerate(nums):
# res ^= i ^ num
# return res
#
#
# # n = len(nums)
# # res = 0
# # for i in range(n):
# # res ^= i ^ nums[i]
# # return res ^ n
#
# # return reduce(ixor, nums + list(range(len(nums)+1)))
# 哈希表
# def missingNumber(self, nums) -> int:
# nums = set(nums)
# for i in range(len(nums)+1):
# if i not in nums:
# return i
# def missingNumber(self, nums: List[int]) -> int:
# res = len(nums)
# for i, num in enumerate(nums):
# res ^= i ^ num
# return res
# def missingNumber(self, nums: List[int]) -> int:
# n = len(nums)
# return (n+1) * n // 2 - sum(nums)
# def missingNumber(self, nums: List[int]) -> int:
# nums = set(nums)
# for i in range(len(nums)+1):
# if i not in nums:
# return i
# def missingNumber(self, nums: List[int]) -> int:
# res = len(nums)
# for i, num in enumerate(nums):
# res ^= i ^ num
# return res
# def missingNumber(self, nums: List[int]) -> int:
# res = len(nums)
# for i, num in enumerate(nums):
# res ^= i ^ num
# return res
def missingNumber(self, nums: List[int]) -> int:
res = len(nums)
for i, num in enumerate(nums):
res ^= i ^ num
return res
s = Solution()
nums = [3,0,1]
print(s.missingNumber(nums))
nums = [9,6,4,2,3,5,7,0,1]
print(s.missingNumber(nums))
|
434f6904c35a4608b7e55b68dfdc4f21b78d15c2 | BruceHi/leetcode | /month12/movingCount.py | 2,200 | 3.515625 | 4 | # 剑指 offer 13. 机器人的运动范围
# BFS 广度优先搜索
from collections import deque
class Solution:
# def movingCount(self, m: int, n: int, k: int) -> int:
# def digit_sum(n):
# res = 0
# while n:
# res += n % 10
# n //= 10
# return res
#
# queue = deque([(0, 0)])
# visited = set()
# while queue:
# x, y = queue.popleft()
# if (x, y) not in visited and 0 <= x < m and 0 <= y < n and digit_sum(x) + digit_sum(y) <= k:
# visited.add((x, y))
# queue.append((x+1, y))
# queue.append((x, y+1))
# return len(visited)
# def movingCount(self, m: int, n: int, k: int) -> int:
# def digit_sum(n):
# res = 0
# while n:
# res += n % 10
# n //= 10
# return res
#
# queue = deque([(0, 0)])
# record = set()
# while queue:
# x, y = queue.popleft()
# if 0 <= x < m and 0 <= y < n and (x, y) not in record and digit_sum(x) + digit_sum(y) <= k:
# record.add((x, y))
# queue.append((x+1, y))
# queue.append((x, y+1))
# return len(record)
def movingCount(self, m: int, n: int, k: int) -> int:
def digit_sum(num):
res = 0
while num:
res += num % 10
num //= 10
return res
queue = deque([(0, 0)])
record = set()
while queue:
a, b = queue.popleft()
if (a, b) not in record and 0 <= a < m and 0 <= b < n and digit_sum(a) + digit_sum(b) <= k:
record.add((a, b))
queue.append((a+1, b))
queue.append((a, b+1))
print(queue)
print(record)
return len(record)
s = Solution()
m = 2
n = 3
k = 1
print(s.movingCount(m, n, k))
m = 3
n = 1
k = 0
print(s.movingCount(m, n, k))
m = 1
n = 2
k = 1
print(s.movingCount(m, n, k))
m = 3
n = 2
k = 17
print(s.movingCount(m, n, k))
m = 16
n = 16
k = 2
print(s.movingCount(m, n, k))
|
4512966968955e3d103045f2d9ed9c3125318b49 | BruceHi/leetcode | /month1/search4.py | 771 | 3.828125 | 4 | # 剑指 offer 53-1. 在排序数组中查找数字
from typing import List
import bisect
class Solution:
# def search(self, nums: List[int], target: int) -> int:
# left = bisect.bisect_left(nums, target)
# if left == len(nums) or nums[left] != target:
# return 0
# right = bisect.bisect(nums, target)
# return right - left
def search(self, nums: List[int], target: int) -> int:
left = bisect.bisect_left(nums, target)
if left == len(nums) or nums[left] != target:
return 0
right = bisect.bisect(nums, target)
return right-left
s = Solution()
nums = [5,7,7,8,8,10]
target = 8
print(s.search(nums, target))
nums = [5,7,7,8,8,10]
target = 6
print(s.search(nums, target))
|
d0247f858e0cc158b6152434c53a3c1b84a3d333 | BruceHi/leetcode | /month8/recoverTree.py | 1,495 | 3.625 | 4 | # 恢复二叉搜索树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 递归 只会显式中序遍历
def recoverTree(self, root: TreeNode) -> None:
def inorder(root):
if not root:
return []
return inorder(root.left) + [root] + inorder(root.right)
node_list = inorder(root)
sort_list = sorted(node_list, key=lambda node: node.val)
p, q = [node for i, node in enumerate(node_list) if node.val != sort_list[i].val]
# node1, node2 = [node1 for node1, node2 in zip(node_list, sort_list) if node1.val != node2.val]
p.val, q.val = q.val, p.val
# 错误的代码。
# def recoverTree(self, root: TreeNode) -> None:
# cur = root
# stack = []
# record = float('-inf')
# res = []
#
# while cur or stack:
# while cur:
# stack.append(cur)
# cur = cur.left
# top = stack.pop()
# if not len(res):
# res.append(top)
# if top.val < record:
# res.append(top)
# if len(res) == 3:
# break
# record = top.val
# cur = top.right
#
# if len(res) == 2:
# p, q = res
# else:
# _, p, q = res
# p.val, q.val = q.val, p.val
|
5306cae0d27ec35a00764050f48089cf8d389098 | BruceHi/leetcode | /month8/removeElement.py | 1,086 | 3.75 | 4 | # 移除元素
from typing import List
class Solution:
# def removeElement(self, nums: List[int], val: int) -> int:
# try:
# while True:
# nums.remove(val)
# except ValueError:
# return len(nums)
# def removeElement(self, nums: List[int], val: int) -> int:
# i = 0
# for j in range(len(nums)):
# if nums[j] != val:
# nums[i] = nums[j]
# i += 1
# return i
# def removeElement(self, nums: List[int], val: int) -> int:
# i = 0
# for j, num in enumerate(nums):
# if num != val:
# nums[i] = num
# i += 1
# return i
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
for num in nums:
if num != val:
nums[i] = num
i += 1
return i
s = Solution()
nums = [3,2,2,3]
val = 3
print(s.removeElement(nums, val))
print(nums)
nums = [0,1,2,2,3,0,4,2]
val = 2
print(s.removeElement(nums, val))
print(nums)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.