blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d63588c573c00bb82bff49d550579c3cf990dd65 | LordofEchoes/Chess-Dog | /src/Board.py | 11,639 | 3.78125 | 4 | # Board Class
from Pawn import Pawn
from Knight import Knight
from Rook import Rook
from Bishop import Bishop
from King import King
from Queen import Queen
class ChessBoard:
def __init__(self):
self.board = [[" " for y in range(0,8)] for x in range(0,8)]
self.white = list()
self.black = list()
self.graveyard = list()
self.move = 0
self.enpassant = False
self.EPlocation = tuple()
def __eq__(self, other):
return self.board == other.board
def __str__(self):
#print the board
string = "Chess Board:\n a|b|c|d|e|f|g|h|\n"
string += " - - - - - - - - \n"
for y in range(7,-1,-1):
string += str(y+1) + "|"
for x in range(0,8):
string += str(self.board[x][y]) + "|"
string += "\n - - - - - - - -\n"
return string
def setUpBoard(self):
#set up white
self.white = [
Pawn(0,1,True),
Pawn(1,1,True),
Pawn(2,1,True),
Pawn(3,1,True),
Pawn(4,1,True),
Pawn(5,1,True),
Pawn(6,1,True),
Pawn(7,1,True),
Knight(1,0,True),
Knight(6,0,True),
Bishop(2,0,True),
Bishop(5,0,True),
Rook(0,0,True),
Rook(7,0,True),
King(4,0,True),
Queen(3,0,True)]
#set up Black
self.black = [
Pawn(0,6,False),
Pawn(1,6,False),
Pawn(2,6,False),
Pawn(3,6,False),
Pawn(4,6,False),
Pawn(5,6,False),
Pawn(6,6,False),
Pawn(7,6,False),
Knight(1,7,False),
Knight(6,7,False),
Bishop(2,7,False),
Bishop(5,7,False),
Rook(0,7,False),
Rook(7,7,False),
King(4,7,False),
Queen(3,7,False)]
#set up board
for obj in self.white:
# print(obj.x, obj.y)
self.board[obj.x][obj.y] = obj
for obj in self.black:
self.board[obj.x][obj.y] = obj
#check if any Kings are in mate
#True if in check
def checkKing(self, isWhite):
if isWhite:
for obj in self.white:
#found the King
if obj == "K":
#can any piece kill the King?
for enemy in self.black:
# print("enemy", enemy, " x:", enemy.x, " y:", enemy.y)
if enemy != "K" and enemy.validMoves(self, obj.x, obj.y):
return True
return False
#is Black
else:
for obj in self.black:
#found the King
if obj == "K":
#can another piece kill the King
for enemy in self.white:
# print("enemy", enemy, " x:", enemy.x, " y:", enemy.y)
if enemy != "K" and enemy.validMoves(self, obj.x, obj.y):
return True
return False
def movePiece(self, board, start_x, start_y, new_x, new_y):
# print("pre obj:", board[start_x][start_y])
# print("pre nothing:", board[new_x][new_y])
board[start_x][start_y].x = new_x
board[start_x][start_y].y = new_y
board[new_x][new_y] = board[start_x][start_y]
board[start_x][start_y] = " "
# print("post obj:", board[new_x][new_y])
# print("post obj y:", board[new_x][new_y].x, "post obj y:", board[new_x][new_y].y)
# print("post nothing:", board[start_x][start_y])
def performMoveWhite(self, start_x, start_y, new_x, new_y):
temp = self.board
tempblack = self.black
tempyard = self.graveyard
#are they moving a piece
if self.board[start_x][start_y] == " ":
print("not a piece: 1")
return False
#are they moving a white piece
if self.board[start_x][start_y].isWhite == True:
#is the move a castling move
if self.board[start_x][start_y] == "K" and self.checkKing(True):
castle = False
if self.board[start_x][start_y].validMoves(self, new_x, new_y, castle) == True:
if castle == True:
print("attempt castle: 1")
#White King is attempting to castle Queenside
if new_x == 2 and new_y == 0:
print("attempt castle Queen: 1")
#move King
self.movePiece(4,0,3,0)
if self.checkKing(True):
self.board = temp
return False
self.movePiece(4,0,2,0)
#move Rook
self.movePiece(7,0,3,0)
if self.checkKing(True):
self.board = temp
return False
#White King is attempting to castle Kingside
elif new_x == 6 and new_y == 0:
print("attempt castle King: 1")
#move King
self.movePiece(4,0,5,0)
if self.checkKing(True):
self.board = temp
return False
self.movePiece(4,0,6,0)
#move Rook
self.movePiece(0,0,5,0)
if self.checkKing(True):
self.board = temp
return False
#not castling move
if self.board[start_x][start_y].validMoves(self, new_x, new_y) == True:
if self.board[new_x][new_y] != " ":
print("capture move: 1")
#capturing, remove graveyard and pieces accordingly
self.graveyard.append(self.board[new_x][new_y])
self.white.remove(self.board[new_x][new_y])
#implement move
self.movePiece(self.board,start_x,start_y,new_x,new_y)
else:
#only time that capturing piece doesn't move to capture square is enpassant
print(self.board[start_x][start_y] == "P", self.EPlocation == (new_x,new_y-1))
if self.board[start_x][start_y] == "P" and self.EPlocation == (new_x,new_y-1):
print("enpassant capture: 1")
self.graveyard.append(self.board[new_x][new_y-1])
self.white.remove(self.board[new_x][new_y-1])
self.board[new_x][new_y-1] = " "
else:
print("standard move: 1")
self.movePiece(self.board,start_x,start_y,new_x,new_y)
else:
print("not a valid move: 1")
return False
if self.checkKing(True):
print("king in check: 1")
self.board = temp
self.black = tempblack
self.graveyard = tempyard
self.movePiece(self.board,new_x,new_y,start_x,start_y)
return False
else:
#if the newly moved piece isn't a pawn then enpassant is false
if self.board[new_x][new_y] != "P" and abs(new_y-start_y) != 2:
print("enpassant reset: 1")
self.enpassant = False
self.EPlocation = ()
return True
# performs moves but as black
def performMoveBlack(self, start_x, start_y, new_x, new_y):
temp = self.board
tempwhite = self.white
tempyard = self.graveyard
#are they moving a piece
if self.board[start_x][start_y] == " ":
print("not a piece: 2")
return False
#are they moving a black piece
if self.board[start_x][start_y].isWhite == False:
#is the move a castling move
if self.board[start_x][start_y] == "K"and self.checkKing(False):
castle = False
if self.board[start_x][start_y].validMoves(self, new_x, new_y, castle) == True:
if castle == True:
print("attempt castle Queen: 2")
#Black King is attempting to castle Queenside
if new_x == 2 and new_y == 7:
#move King
self.movePiece(4,7,3,7)
if self.checkKing(False):
self.board = temp
return False
self.movePiece(4,7,2,7)
# move Rook
self.movePiece(0,7,3,7)
if self.checkKing(False):
self.board = temp
return False
#White King is attempting to castle Kingside
elif new_x == 6 and new_y == 7:
print("attempt castle King: 2")
# move King
self.movePiece(4,7,5,7)
if self.checkKing(False):
self.board = temp
return False
self.movePiece(4,7,6,7)
# move Rook
self.movePiece(0,7,5,7)
if self.checkKing(False):
self.board = temp
return False
#not castling move
if self.board[start_x][start_y].validMoves(self, new_x, new_y) == True:
if self.board[new_x][new_y] != " ":
print("capture move: 2")
#capturing, remove graveyard and pieces accordingly
self.graveyard.append(self.board[new_x][new_y])
self.white.remove(self.board[new_x][new_y])
#implement move
self.movePiece(self.board,start_x,start_y,new_x,new_y)
else:
#only time that capturing piece doesn't move to capture square is enpassant
if self.board[start_x][start_y] == "P" and self.EPlocation == (new_x,new_y+1):
print("enpassant capture: 2")
self.graveyard.append(self.board[new_x][new_y+1])
self.white.remove(self.board[new_x][new_y+1])
self.board[new_x][new_y+1] = " "
else:
print("standard move: 2")
self.movePiece(self.board,start_x,start_y,new_x,new_y)
else:
print("not a valid move: 2")
return False
if self.checkKing(False):
print("king in check: 2")
self.board = temp
self.white = tempwhite
self.graveyard = tempyard
self.movePiece(self.board,new_x,new_y,start_x,start_y)
return False
else:
#if the newly moved piece isn't a pawn then enpassant is false
if self.board[new_x][new_y] != "P" and self.EPlocation != (new_x,new_y) and abs(new_y-start_y) != 2:
print("enpassant reset: 2")
self.enpassant = False
self.EPlocation = ()
return True
|
2ad2af28bbdf1156a0233b791b67eabc14e6f840 | ShadowHammer/MadProgram | /Mad Program v2/Mad Program v2/Mad_Program.py | 7,119 | 3.65625 | 4 | #!/usr/local/bin/python3
from tkinter import *;
import tkinter as tk;
import os;
x=650
y=600
xStr=str(x)
yStr=str(y)
def main():
#Jeg laver første et vindue der hedder "Window" med titlen Madprogram
exit = False;
window = tk.Tk();
window.title("Madprogram");
window.geometry(xStr+'x'+yStr)
#Her ler jeg en funktion til at lukke programmet, hvis man ønsker det
def lukProgrammet():
global exit;
window.destroy();
exit = True;
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
exitBtn = tk.Button(window, text="X", command = lukProgrammet,bg="red",width=3);
exitBtn.grid(row=0,column=3,sticky="NE");
def dessertBut():
window.destroy();
bagning();
def retterBut():
window.destroy();
retter();
def bagningBut():
window.destroy();
desserter();
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
bagBtn = tk.Button(window, text="Bagning", command = dessertBut);
bagBtn.grid(row=1,column=0,padx=115,sticky="W",pady=120);
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
retBtn = tk.Button(window, text="Retter", command = retterBut);
retBtn.grid(row=1,column=1,sticky="N", pady=120);
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
desBtn = tk.Button(window, text="Desserter", command = bagningBut);
desBtn.grid(row=1,column=2,padx=115,sticky="E");
def enter(event):
rigtigLogin();
def close(event):
lukProgrammet();
window.bind('<Return>', enter);
window.bind('<Escape>', close);
window.mainloop();
def desserter():
window = tk.Tk();
window.title("Dessert");
window.geometry(xStr+'x'+yStr);
def home():
window.destroy();
main();
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
homeBtn = tk.Button(window, text="Tilbage", command = home);
homeBtn.pack();
#Defining option list
strPath=os.path.abspath(os.getcwd()+"/Retter/Desserter"+"/")
OptionList = [ item for item in os.listdir(strPath) if os.path.isdir(os.path.join(strPath, item)) ]
#print (OptionList)
w=Scrollbar(window,orient="vertical");
variable = tk.StringVar(window);
variable.set(OptionList[0]);
opt = tk.OptionMenu(window, variable, *OptionList);
opt.config(width=30, font=('Helvetica', 12));
opt.pack(side="top");
#Labels
ingredienserTekst = tk.Text(window, height=50,font=('Helvetica', 12));
ingredienserTekst.pack(side="top");
#Function
def callback(*args):
ingredienserTekst.configure(state="normal")
ingredienserTekst.delete('1.0',END)
ingredienser=open(strPath+"/"+"{}".format(variable.get())+"/"+"ingredienser.txt",encoding="utf-8");
fremstilling=open(strPath+"/"+"{}".format(variable.get())+"/"+"fremstilling.txt",encoding="utf-8");
ingredienserTekst.insert(END,ingredienser.read()+"\n\nFremstilling:\n\n"+fremstilling.read());
ingredienser.close();
fremstilling.close();
ingredienserTekst.configure(state="disabled")
variable.trace("w", callback);
scrollbar = tk.Scrollbar(window,orient='vertical',command=ingredienserTekst.yview);
scrollbar.pack(side="right")
ingredienserTekst['yscrollcommand'] = scrollbar.set
window.mainloop();
def retter():
window = tk.Tk();
window.title("Retter");
window.geometry(xStr+'x'+yStr)
def home():
window.destroy();
main();
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
homeBtn = tk.Button(window, text="Tilbage", command = home);
homeBtn.pack();
#Defining option list
strPath=os.path.abspath(os.getcwd()+"/Retter/Aftensmad"+"/")
OptionList = [ item for item in os.listdir(strPath) if os.path.isdir(os.path.join(strPath, item)) ]
w=Scrollbar(window,orient="vertical");
variable = tk.StringVar(window);
variable.set(OptionList[0]);
opt = tk.OptionMenu(window, variable, *OptionList);
opt.config(width=30, font=('Helvetica', 12));
opt.pack(side="top");
#Labels
ingredienserTekst = tk.Text(window, font=('Helvetica', 12));
ingredienserTekst.pack(side="top");
#Function
def callback(*args):
ingredienserTekst.configure(state="normal")
ingredienserTekst.delete('1.0',END)
ingredienser=open(strPath+"/"+"{}".format(variable.get())+"/"+"ingredienser.txt",encoding="utf-8");
fremstilling=open(strPath+"/"+"{}".format(variable.get())+"/"+"fremstilling.txt",encoding="utf-8");
ingredienserTekst.insert(END,ingredienser.read()+"\n\nFremstilling:\n\n"+fremstilling.read());
ingredienser.close();
fremstilling.close();
ingredienserTekst.configure(state="disabled")
variable.trace("w", callback);
scrollbar = tk.Scrollbar(window,orient='vertical',command=ingredienserTekst.yview);
scrollbar.pack(side="right")
ingredienserTekst['yscrollcommand'] = scrollbar.set
window.mainloop();
def bagning():
window = tk.Tk();
window.title("Bagning");
window.geometry(xStr+'x'+yStr)
def home():
window.destroy();
main();
#Her er knappen til funktionen "lukProgrammet" til at lukke programmet
homeBtn = tk.Button(window, text="Tilbage", command = home);
homeBtn.pack();
#Defining option list
strPath=os.path.abspath(os.getcwd()+"/Retter/Bagning"+"/")
OptionList = [ item for item in os.listdir(strPath) if os.path.isdir(os.path.join(strPath, item)) ]
w=Scrollbar(window,orient="vertical");
variable = tk.StringVar(window);
variable.set(OptionList[0]);
opt = tk.OptionMenu(window, variable, *OptionList);
opt.config(width=30, font=('Helvetica', 12));
opt.pack(side="top");
#Labels
ingredienserTekst = tk.Text(window, font=('Helvetica', 12));
ingredienserTekst.pack(side="top");
#Function
def callback(*args):
ingredienserTekst.configure(state="normal")
ingredienserTekst.delete('1.0',END)
ingredienser=open(strPath+"/"+"{}".format(variable.get())+"/"+"ingredienser.txt",encoding="utf-8");
fremstilling=open(strPath+"/"+"{}".format(variable.get())+"/"+"fremstilling.txt",encoding="utf-8");
ingredienserTekst.insert(END,ingredienser.read()+"\n\nFremstilling:\n\n"+fremstilling.read());
ingredienser.close();
fremstilling.close();
ingredienserTekst.configure(state="disabled")
variable.trace("w", callback);
scrollbar = tk.Scrollbar(window,orient='vertical',command=ingredienserTekst.yview);
scrollbar.pack(side="right")
ingredienserTekst['yscrollcommand'] = scrollbar.set
window.mainloop();
if __name__ =='__main__' :main();
|
e33cba62b32510844bcffd1b37fb848a956e3db6 | xiaomingxian/python_base | /0.test/约瑟夫.py | 1,252 | 3.5 | 4 | def main():
nums = 41
call = 3
# 参数定义:
peoples = []
for _ in range(nums):
# True定义状态为活
peoples.append(True)
result = []
num = 1
# 主逻辑
while (any(peoples)): # peoples中存在任何True元素
# enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
for index, people in enumerate(peoples):
if people:#如果人存活True
if num == call:
peoples[index] = False
result.append(index + 1) # index是从0开始 但是值是从1开始
# print(index+1)#每轮的出局者
# print(peoples)#每次的队列状态
num = 1 # 找到后就计数归为初始值 接着从上次循环的位置开始计数
else:
num += 1
print('-' * 25)
print('\n总数为%d,报数为%d' % (nums, call))
print('约瑟夫序列为:\n%s\n' % result)
print('-' * 25)
print(any([False]))
pass
if __name__ == '__main__':
main()
|
3348e918fe036839ac9557f91721447a37d9762a | xiaomingxian/python_base | /1.xxm/day12_minweb/4元类/Demo2_自定义元类_函数.py | 798 | 3.859375 | 4 | # coding=utf-8
# 自定义元类---函数
def MyType(lname, fus, params):
# 还可以进行其他 操作 例如python3的类 都继承object 可以遍历 fus 判断元组内有没有object 没有就添加
new_params = {}
for name, value in params.items():
# 过滤魔法/私有属性
if not name.startswith('__'):
new_params[name.upper()] = value
return type(lname, fus, new_params)
# 使用自定义 元类 (将属性key变成大写)
class A(object, metaclass=MyType):
num = 10
def main():
print('------------元类应用------------')
print('---------------------------')
# 源于 type
print(A().__class__)
print(A().__class__.__class__)
# 自定义元类
print(help(A))
if __name__ == '__main__':
main()
|
61ac28fdd39bef0934f08ce87548696201676bb0 | xta/California_School_Dashboard_Rank | /utils/csv_to_json.py | 1,254 | 4.03125 | 4 | # -*- coding: utf-8 -*-
import sys
import csv
import json
'''
Purpose
Convert a CSV to a JSON file
Usage
python3 csv_to_json.py file_in.csv file_out.json json_key
'''
def row_count(file_name):
with open(file_name) as in_file:
return sum(1 for _ in in_file)
if __name__ == '__main__':
assert(len(sys.argv) == 4)
csv_file = open(sys.argv[1], 'r')
json_file = open(sys.argv[2], 'w')
json_key = sys.argv[3]
new_line = '\n'
with open(sys.argv[1]) as csv_document:
# input
reader = csv.reader(csv_document)
field_names = next(reader)
csv_reader = csv.DictReader(csv_file, field_names)
next(csv_reader) # skip header
# count lines (to detect last row)
lines = row_count(sys.argv[1])
assert(lines > 0)
last_line = lines-2 # one for 0 based index, one for header row
# output
json_file.write('{ "' + json_key + '": [' + new_line)
for index, row in enumerate(csv_reader):
json.dump(row, json_file)
if index != last_line:
json_file.write(',' + new_line)
else:
json_file.write(new_line)
json_file.write(']}' + new_line)
|
bca635b61e7def60ba191c76fd712e11a7ff1a54 | zyx528750635/program | /Test.py | 564 | 3.59375 | 4 | # _*_ coding :UTF-8 _*_
# 开发人员 :52875
# 开发时间 :2019/6/11 19:44
# 文件名称 :Test.PY
# 开发工具 :PyCharm
capital = []
lower_case = []
number = []
for i1 in range(48, 58):
capital.append(chr(i1))
for i2 in range(65, 91):
lower_case.append(chr(i2))
for i3 in range(97, 123):
number.append(chr(i3))
print(capital)
print(lower_case)
print(number)
print(','.join(chr(i4) for i4 in range(48, 58)))
print(','.join(chr(i5) for i5 in range(65, 91)))
print(','.join(chr(i6) for i6 in range(97, 123)))
|
7864339b9651c8726e9f41f458d436498809aaed | Xphera/appservicios | /appServicios/utils/Utils/Validators.py | 1,215 | 3.59375 | 4 | import re
from datetime import datetime, date, timedelta
def es_alfanumerico(valor,espacios = False):
"""
Calcula si una cadena de caracteres contine unicamente caracteres alfanumericos.
r"^[A-zñÑáéíóúÁÉÍÓÚ0-9 ]+$"
:param valor: cadena a evaluar
:param espacios: (bool) indica si la cadena puede o no contener espacios
:return: (bool) indicando si la caden cumple o no con la expresion
"""
expr = r"^[A-zñÑáéíóúÁÉÍÓÚ0-9]+$"
if(espacios):
expr = r"^[A-zñÑáéíóúÁÉÍÓÚ0-9 ]+$"
return re.search(expr, valor) is not None
def menor_que_fecha_actual(fecha):
"""
Indica si la fecha suministrada es menor que la fecha actual
:param fecha: fecha a comparar
:return: (bool)
"""
fechaActual = datetime.now().date()
return fecha < fechaActual
def es_numero_telefonico(numero):
'''
Indica si un numero telefonico tiene el formato correcto para colombia, soporta fijos y moviles
6302338
3188725398
+576302338
:param numero:
:return:
'''
expr = r"^\(?(\+57)?\)?[- ]?([1-9])?(3[0-9]{2})?[- ]?[1-9][0-9]{2}[- ]?[0-9]{2}[- ]?[0-9]{2}$"
return re.search(expr, numero) is not None |
f9dda5c9814a797933079ec9e5775f59e63b74e2 | fossabot/experiment_code | /python_tricks/two_nums.py | 756 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# @Author: jerry
# @Date: 2017-09-25 21:40:27
# @Last Modified by: jerry
# @Last Modified time: 2017-09-25 21:45:54
class Solution:
"""
@param numbers : An array of Integer
@param target : target = numbers[index1] + numbers[index2]
@return : [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self,numbers,target):
ret = []
for i in range(len(numbers)):
for j in range(i+1,len(numbers)):
if numbers[i] + numbers[j] == target:
ret.append(i)
ret.append(j)
return ret
if __name__ == '__main__':
a = Solution()
numbers = [98,23,3,4,5]
target = 26
c = a.twoSum(numbers,target)
print c
|
9937bc16eff459c0432af59ac2a956d29b2d0b71 | cayennes/advent | /y2022-python/day02.py | 722 | 3.578125 | 4 | #!/usr/bin/env python3
with open("input/day02.txt") as input:
content = input.readlines()
def translate(item):
return {"A": 1, "B": 2, "C": 3,
"X": 1, "Y": 2, "Z": 3}.get(item)
def parse(lines):
return [[translate(them), translate(me)]
for them, me in [line.split() for line in lines]]
def score (play):
if (play[0] - play[1]) % 3 == 1: # win
return play[1] + 6
if (play[0] - play[1]) % 3 == 2: # loss
return play[1]
return play[1] + 3 # draw
test_input = ["A Y", "B X", "C Z"]
def part1(input):
return sum([score(play) for play in parse(input)])
print("part 1 test (should be 15): ", part1(test_input))
print("part 1: ", part1(content))
|
4a4f0e71027d92fa172f78811993aa1d62e2a6c7 | JuveVR/Homework_5 | /Exercise_2.py | 2,650 | 4.21875 | 4 | #2.1
class RectangularArea:
"""Class for work with square geometric instances """
def __init__(self, side_a, side_b):
"""
Defines to parameters of RectangularArea class. Checks parameters type.
:param side_a: length of side a
:param side_b:length of side a
"""
self.side_a = side_a
self.side_b = side_b
if type(self.side_a) and type(self.side_b) == int or float:
pass
else:
raise Exception("Wrong type, sides should be int or float")
def square(self):
"""
:return: value of square for class instance
"""
return self.side_a * self.side_b
def perimeter(self):
"""
:return: alue of square for class instance
"""
return (self.side_b + self.side_a)*2
#2.2
class Dot:
"""Defines coordinates of the dot on the map"""
def __init__(self, x, y):
"""
:param x: distance from point x to y-axis
:param y: distance from point y to x-axis
"""
self.x = x
self.y = y
def dist_from_zero_version1(self):
"""
:return: the distance on the plain from the dot to the origin
"""
x1 = 0
y1 = 0
d = ((self.x-x1)**2 + (self.y - y1)**2)**0.5
return d
def dist_from_zero_version2(self, x2=0, y2=0):
"""
:param x2: origin of x-axis (by default)
:param y2: origin of y-axis (by default)
:return: :return: the distance on the plain from the dot to the origin
"""
dv2 = ((self.x-x2)**2 + (self.y - y2)**2)**0.5
return dv2
def between_two_dots(self, x3, y3): # I am not sure that this is correct way to solve your exercise
"""
:param x3: distance from point x to y-axis
:param y3: distance from point y to x-axis
:return: the distance on the plain between two dots
"""
d = ((self.x - x3) ** 2 + (self.y - y3) ** 2) ** 0.5
return d
def three_dimensional(self, z): # Maybe I misunderstood the task. My method looks weird
"""
Converts coordinates to three_dimensional system
:param z: distance from point x to xy plane
:return: coordinates of the dot in three_dimensional system
"""
return (self.x, self.y, z)
if __name__ == "__main__":
rect = RectangularArea(10, 12)
print(rect.square())
print(rect.perimeter())
dot1 = Dot(20,20)
print(dot1.dist_from_zero_version1())
print(dot1.dist_from_zero_version2())
print(dot1.between_two_dots(34.4, 45))
print(dot1.three_dimensional(12))
|
63d8370eb3efcfe1cebf11dbd2ffdd7c747b2a37 | SandraAcosta/Clase3 | /hola.py | 396 | 4.03125 | 4 | opc = True
while opc:
print "ingrese un numero"
x = input ()
if x >= 15 and x<=20:
print "estas muy viejo"
elif x>20 and x<=35:
print "eres un adulto contemporaneo"
elif x>35 and x<=150:
print "eres un nio"
else:
print "no creo que seas humano"
ent = raw_input("desea evaluar de nuevo: (s - n) ")
|
b594e98ce3a62764b03ad9b8413425deeb12b452 | skasero/cs491project2 | /perceptron.py | 1,444 | 3.578125 | 4 | #!/usr/bin/python3
import numpy as np
# perceptron_train
# returns the weights and bias for training data
def perceptron_train(X,Y):
# This is used to fix arrays that have 0 as their labels instead of -1
for i in range(0,len(Y)):
if(Y[i] != 1):
Y[i] = -1
index = 0
countToEpoch = 0
epoch = len(Y)
w = [0] * len(X[0]) # Creating a list of [0] * number of features
b = 0 # Starts as 0
# Continue going through all samples until an entire epoch where there was no update.
while(countToEpoch != epoch-1):
a = (np.dot(w,X[index])+b)*Y[index]
# We need to update if a <= 0
if(a <= 0):
w += X[index]*Y[index]
b += Y[index]
countToEpoch = 0
else:
countToEpoch += 1
index += 1
index %= epoch
# print("w: {} b: {}".format(w,b))
return [w.tolist(),b.tolist()]
# perceptron_test
# checks how accurate the weights and bias are for the perceptron by testing on test data
def perceptron_test(X_test, Y_test, w, b):
totalCorrect = 0
totalCount = len(Y_test)
for i in range(0,len(Y_test)):
y = np.dot(w,X_test[i]) + b
y = y[0]
if(y != 0):
y /= abs(y) # this is fix a value such as -3 to a -1 value
if(y == Y_test[i]):
totalCorrect += 1
return totalCorrect/totalCount |
0b0e1f3f55ae4faa409b1fefb704b577aebb6c87 | saicataram/MyWork | /DL-NLP/Assignments/Assignment4/vowel_count.py | 801 | 4.3125 | 4 | """
*************************************************************************************
Author: SK
Date: 30-Apr-2020
Description: Python Assignments for practice;
a. Count no of vowels in the provided string.
*************************************************************************************
"""
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)
str = input("Enter a character: ")
# Function Call
vowel_count(str) |
bd557b8cb881b1a6a0832b347c6855289a7c7cef | saicataram/MyWork | /DL-NLP/Assignments/Assignment4/lengthofStringinList.py | 528 | 4.375 | 4 | """
*************************************************************************************
Author: SK
Date: 30-Apr-2020
Description: Python Assignments for practice;
a. Count length of the string in list provided.
*************************************************************************************
"""
string = ["mahesh","hello","nepal","Hyderabad","mahesh","Delhi", "Amsterdam", "Tokyo"]
index = len(string)
for i in range (0, index):
count_each_word = len(string[i])
print(count_each_word)
|
ef2b6f193874dcd23a1b7bc269f293d7ac18244b | mdettlaff/mdettla | /si/lab07/tautologyCNF.py | 2,405 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
u"""Sprawdzanie czy podana formuła jest tautologią.
Formuła musi być w koniunkcyjnej postaci normalnej (CNF).
Przykład: (p V q) & (~q V r V ~s) & (s V ~t)
"""
class Literal:
u"""Pojedynczy symbol lub jego zaprzeczenie."""
def __init__(self, symbol, negated):
self.symbol = symbol
self.negated = negated
def __str__(self):
if self.negated:
return '~' + self.symbol
else:
return self.symbol
class Formula:
u"""Formuła w postaci CNF."""
def __init__(self, input):
self.CNF = []
self.symbols = set()
input = input.strip().replace(' ', '').\
replace('(', '').replace(')', '')
conjunctions = input.split('&')
for conjunction in conjunctions:
self.CNF.append([])
disjunction = conjunction.split('V')
for literal_str in disjunction:
if literal_str.startswith('~'):
literal = Literal(literal_str[-1], True)
else:
literal = Literal(literal_str[-1], False)
self.CNF[-1].append(literal)
self.symbols.add(literal_str[-1])
def __str__(self):
s = ''
for disjunction in self.CNF:
s += '('
for literal in disjunction:
s += str(literal) + ' V '
s = s[:-3]
s += ') & '
return s[:-3]
def is_tautology(formula):
u"""Sprawdza czy podana w CNF formuła jest tautologią.
Korzystamy z twierdzenia:
Formuła w Koniunkcyjnej Postaci Normalnej jest tautologią <=>
każda alternatywa zawiera kontrarną parę literałów (np. p & ~p).
"""
for disjunction in formula.CNF:
contrary_found = False
for i, literal in enumerate(disjunction):
for j in range(i, len(disjunction)):
if literal.symbol == disjunction[j].symbol:
if literal.negated == (not disjunction[j].negated):
contrary_found = True
if not contrary_found:
return False
return True
if __name__ == '__main__':
print u'Podaj formułę w KPN:'
formula = Formula(raw_input())
print formula
print u'Podana formuła',
print u'jest' if is_tautology(formula) else u'nie jest', u'tautologią.'
|
d4aa13f6bd5d92ad0445200c91042b1b72f8f4cc | lilianaperezdiaz/cspp10 | /unit4/Lperez_rps.py | 2,982 | 4.3125 | 4 | import random
#function name: get_p1_move
# arguments: none
# purpose: present player with options, use input() to get player move
# returns: the player's move as either 'r', 'p', or 's'
def get_p1_move():
move=input("rock, paper, scissors: ")
return move
#function name: get_comp_move():
# arguments: none
# purpose: randomly generates the computer's move,
# either 'r' 'p' or 's'
# returns: the computer's randomly generated move
def get_comp_move():
randy=random.randint(1,3)
if randy==1:
return("rock")
elif randy==2:
return("paper")
elif randy==3:
return("scissors")
return randy
#function name: get_rounds
# arguments: none
# purpose: allows the user to choose a number of rounds from 1 to 9.
# returns: the user-chosen number of rounds
def get_rounds():
rounds=int(input("How many rounds do you want to play 1-9: "))
return rounds
#function name: get_round_winner
# arguments: player move, computer move
# purpose: based on the player and computer's move, determine
# the winner or if it's a tie
# returns: returns a string based on the following:
# "player" if player won
# "comp" if computer won
# "tie" if it's a tie
def get_round_winner(p1move, cmove):
if p1move == cmove:
return("Tie!")
if p1move == "rock" and cmove == "paper":
return("You lose!")
elif p1move == "paper" and cmove == "rock":
return("You win!")
elif p1move == "scissors" and cmove == "rock":
return("You lose!")
elif p1move == "rock" and cmove == "scissors":
return("You win!")
elif p1move == "paper" and cmove == "scissors":
return ("You lose!")
elif p1move == "scissors" and cmove == "paper":
return ("You win!")
#function name: print_score
# arguments: player score, computer score, number of ties
# purpose: prints the scoreboard
# returns: none
def print_score(pscore, cscore, ties):
print("Player score: {}".format(pscore))
print("Computer score: {}".format(cscore))
print("Tie score: {}".format(ties))
#function name: rps
# arguments: none
# purpose: the main game loop. This should be the longest, using
# all the other functions to create RPS
# returns: none
def rps():
pscore=0
cscore=0
ties=0
rounds = get_rounds()
for rounds in range(1, rounds + 1):
p1move = get_p1_move()
randy = get_comp_move()
winner = get_round_winner(p1move, randy)
print ("Computer chose {}".format(randy))
if winner == "You win!":
print("Player won!")
pscore= pscore+1
elif winner =="You lose!":
print("Computer won!")
cscore = cscore +1
else:
print("It's a tie!")
ties = ties+1
print_score(pscore,cscore,ties)
print("_________________________________")
rps() |
17154fa6ddbb3a0604a4f4b9b367e31b8dbed84d | lilianaperezdiaz/cspp10 | /unit1/Lperez_calcCtoF.py | 114 | 3.84375 | 4 | c= input()
c= float(c)
x= c*1.8
f= x+32
print (f)
F_T=str(f)
C_T=str(c)
print (C_T + "c is equal to " + F_T +"F") |
2b48bf8b4c0f65c8a1335b26475981e42c27a040 | ankovachev/SoftUni | /PythonADV/99_temp_problems/05_temp_pronlem.py | 248 | 3.734375 | 4 | a = 8
b = 4
c = a % b
d = a // b
print(f"{a} % {b} = {c}")
print(f"{a} // {b} = {d}")
a = 7
b = 4
c = a % b
d = a // b
print(f"{a} % {b} = {c}")
print(f"{a} // {b} = {d}")
aa = 19
print(aa)
print(type(aa))
bb = str(aa)
print(bb)
print(type(bb)) |
795a6e76b637c347763aa7d308fde8d29d52618d | ankovachev/SoftUni | /PythonADV/99_temp_problems/04_temp_problem.py | 264 | 3.8125 | 4 | import datetime
input_data_string = "8:00:00"
hh, mm, ss = input_data_string.split(":")
hh = int(hh)
mm = int(mm)
ss = int(ss)
a = datetime.datetime(1,1,1,hh,mm,ss)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time()) |
2f3907e4ab5e2741602a168acd996dae25d1942e | huhudaya/leetcode- | /LeetCode/414. 第三大的数.py | 792 | 4.03125 | 4 | '''
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
示例 1:
输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1.
示例 2:
输入: [1, 2]
输出: 2
解释: 第三大的数不存在, 所以返回最大的数 2 .
示例 3:
输入: [2, 2, 3, 1]
输出: 1
解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。
'''
from typing import List
class Solution:
def thirdMax(self, nums: List[int]) -> int:
nums = list(set(nums))
nums.sort()
nums.reverse()
n = len(nums)
if n < 3:
return nums[0]
else:
return nums[2]
|
f1ea2b04d8f79bb038248a7e4e8c2d5ebbba804b | huhudaya/leetcode- | /LeetCode/718. 最长重复子数组(最长公共子串).py | 1,009 | 3.703125 | 4 | # 718. 最长重复子数组.py
"""
给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。
示例 1:
输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出: 3
解释:
长度最长的公共子数组是 [3, 2, 1]。
说明:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
链接:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray
"""
'''
动态规划思路:
1.明确dp数组的含义
2.明确base case
3.找状态转义方程
'''
from typing import List
class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
# 最长公共子串
m, n = len(A), len(B)
# dp[i][j]定义为以i,j结尾的最长子串
dp = [[0] * (n + 1) for _ in range(m + 1)]
res = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
res = max(dp[i][j], res)
return res
|
5bb5db7dcf066421e712866a0a8760a9162bc436 | huhudaya/leetcode- | /LeetCode/220. 存在重复元素 III(滑动窗口)好题.py | 1,389 | 3.578125 | 4 | # 220. 存在重复元素 III.py
'''
给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j
使得 nums [i] 和 nums [j] 的差的绝对值最大为 t
并且 i 和 j 之间的差的绝对值最大为 ķ
示例 1:
输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:
输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false
链接:https://leetcode-cn.com/problems/contains-duplicate-iii
'''
# 利用set,底层是红黑树
from typing import List
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
n = len(nums)
if n <= 1:
return False
record = set() # 定义窗口
# 遍历整个数组
for i in range(n):
if t == 0: # 如果t=0,那么看看窗口内是否有重复元素,有就返回True
if nums[i] in record:
return True
else:
for j in record: # 遍历窗口元素,判断是否有绝对值小于t的情况,有就返回True
if abs(j - nums[i]) <= t:
return True
record.add(nums[i]) # 向集合添加元素
if len(record) > k:
record.remove(nums[i - k]) # 维护长度为k的窗口
return False
|
6c18e8e7ca9ef641685aa5697279647ab2bccfd0 | huhudaya/leetcode- | /程序员面试金典/面试题 08.01. 三步问题.py | 1,142 | 3.546875 | 4 | '''
三步问题。有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶或3阶。实现一种方法,计算小孩有多少种上楼梯的方式。结果可能很大,你需要对结果模1000000007。
示例1:
输入:n = 3
输出:4
说明: 有四种走法
示例2:
输入:n = 5
输出:13
提示:
n范围在[1, 1000000]之间
'''
# 备忘录递归
class Solution:
def waysToStep(self, n: int) -> int:
memo = {}
memo[1] = 1
memo[2] = 3
memo[3] = 4
def dfs(n):
if n in memo:
return memo[n]
res = dfs(n - 1) + dfs(n - 2) + dfs(n - 3)
memo[n] = res
return res
return dfs(n)
class Solution:
def waysToStep(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
dp = [0] * (n + 1)
dp[0] = 0
dp[1] = 1
dp[2] = 2
dp[3] = 4
for i in range(4, n + 1):
dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3]) % 1000000007
return dp[n]
|
b9de7839f4ea1618aa4156a14fd4a6ef5b1820f4 | huhudaya/leetcode- | /程序员面试金典/面试题 17.18. 最短超串.py | 1,429 | 3.546875 | 4 | '''
假设你有两个数组,一个长一个短,短的元素均不相同。
找到长数组中包含短数组所有的元素的最短子数组,其出现顺序无关紧要。
返回最短子数组的左端点和右端点,如有多个满足条件的子数组,返回左端点最小的一个。若不存在,返回空数组。
示例 1:
输入:
big = [7,5,9,0,2,1,3,5,7,9,1,1,5,8,8,9,7]
small = [1,5,9]
输出: [7,10]
示例 2:
输入:
big = [1,2,3]
small = [4]
输出: []
'''
import sys
from typing import List
from collections import defaultdict
class Solution:
def shortestSeq(self, big: List[int], small: List[int]) -> List[int]:
# 滑动窗口
hash = defaultdict(int)
for i in small:
hash[i] += 1
left = 0
m = len(big)
n = len(small)
if n > m:
return []
cnt = 0
max_len = sys.maxsize
res = []
for i in range(m):
hash[big[i]] -= 1
if hash[big[i]] >= 0:
cnt += 1
# 移动左指针,指向第一个有意义的值的索引位置
while left < i and hash[big[left]] < 0:
hash[big[left]] += 1
left += 1
if cnt == n and max_len > i - left + 1:
max_len = i - left + 1
if res == [] or (res and left > res[0]):
res = [left, i]
return res
|
3bd30ee8dd9bab158a29b9b912ad0f4e196d0f4e | huhudaya/leetcode- | /LeetCode/440. 字典序的第K小数字.py | 2,816 | 3.65625 | 4 | '''
给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。
注意:1 ≤ k ≤ n ≤ 109。
示例 :
输入:
n: 13 k: 2
输出:
10
解释:
字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
'''
'''
我们求字典序第k个就是上图前序遍历访问的第k节点!
但是不需要用前序遍历,如果我们能通过数学方法求出节点1和节点2之间需要走几步,减少很多没必要的移动。
其实只需要按层节点个数计算即可,图中节点1和节点2在第二层,因为n = 13,节点1可以移动到节点2(同一层)所以在第二层需要移动1步。
第三层,移动个数就是 (13 - 10 + 1) = 4 (min(13 + 1, 20) - 10)
所以节点1到节点2需要移动 1 + 4 = 5 步
当移动步数小于等于k,说明需要向右节点移动,图中就是节点1移动到节点2。
当移动步数大于k,说明目标值在节点1和节点2之间,我们要向下移动!即从节点1移动到节点10。
'''
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
def cal_steps(n, n1, n2):
step = 0
while n1 <= n:
step += min(n2, n + 1) - n1 # //比如n是195的情况195到100有96个数
n1 *= 10
n2 *= 10
return step
cur = 1
# k -= 1
while k > 0:
# 求同一层移动一个节点所需要的步数
steps = cal_steps(n, cur, cur + 1)
# 如果移动次数<=k,则需要水平移动一次,注意注意,这个k会一直减少!!!!!知道<=0
if steps <= k:
k -= steps
cur += 1
# 否则需要下沉
else:
k -= 1
cur *= 10
return cur - 1
# 自己的版本
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
# 计算水平移动的时候需要移动的步数
def cal_step(n, n1, n2):
step = 0
while n1 <= n:
step += min(n2, n + 1) - n1
n1 *= 10
n2 *= 10
return step
cur = 1
# 因为k多走了一步,所以这里需要提前减1
k -= 1
while k > 0:
# 计算水平移动的时候需要的步数
step = cal_step(n, cur, cur + 1)
# 需要水平移动
if step <= k: # 在另外的子树中
k -= step
# 这里cur每次都+1,最后会多加一个1
cur += 1
# 需要下沉
else: # 在当前子树中
k -= 1
cur *= 10
return cur
print(Solution().findKthNumber(100, 90))
|
2a6f5d9565e734235fa1cc312a3af9a33d5c3eb8 | huhudaya/leetcode- | /剑指offer/面试题40. 最小的k个数.py | 10,029 | 4.03125 | 4 | '''
输入整数数组 arr ,找出其中最小的 k 个数。
例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:
输入:arr = [0,1,2,1], k = 1
输出:[0]
限制:
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
'''
from typing import List
# 排序 O(NlogN)
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
arr.sort()
return arr[:k]
# 堆 O(NlogK)
'''
我们用一个大根堆实时维护数组的前 k 小值。
首先将前 k 个数插入大根堆中,随后从第 k+1 个数开始遍历
如果当前遍历到的数比大根堆的堆顶的数要小,就把堆顶的数弹出,再插入当前遍历到的数
最后将大根堆里的数存入数组返回即可
在下面的代码中,由于 C++ 语言中的堆(即优先队列)为大根堆,我们可以这么做。
而 Python 语言中的对为小根堆,因此我们要对数组中所有的数取其相反数,才能使用小根堆维护前 k 小值。
python中默认是小根堆
'''
import heapq
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
if k == 0:
return list()
hp = [-x for x in arr[:k]]
heapq.heapify(hp)
for i in range(k, len(arr)):
if -hp[0] > arr[i]:
heapq.heappop(hp)
heapq.heappush(hp, -arr[i])
ans = [-x for x in hp]
return ans
# 快排 平均的时间复杂度为O(N)
# 期望为 O(n)
'''
时间复杂度的推导
partition的过程,时间是o(n)。
我们在进行第一次partition的时候需要花费n
第二次partition的时候,数据量减半了,所以只要花费n/2,同理第三次的时候只要花费n/4,以此类推。
而n+n/2+n/4+...显然是小于2n的,所以这个方法的渐进时间只有o(n)
'''
'''
我们可以借鉴快速排序的思想。
我们知道快排的划分函数每次执行完后都能将数组分成两个部分
小于等于分界值 pivot 的元素的都会被放到数组的左边
大于的都会被放到数组的右边,然后返回分界值的下标。
与快速排序不同的是,快速排序会根据分界值的下标递归处理划分的两侧,而这里我们只处理划分的一边。
'''
# 本质其实就是求第K小的数,就是求第K小的数的索引,然后返回前K个元素就可以了
import random
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
n = len(arr)
# 快排的思想
def partition(left, right, target):
index = arr[target]
arr[left], arr[target] = arr[target], arr[left]
# 挖坑法
while left < right:
while left < right and arr[right] >= index:
right -= 1
arr[left] = arr[right]
while left < right and arr[left] <= index:
left += 1
arr[right] = arr[left]
arr[left] = index
return left
def partition1(left, right, target):
index = arr[target]
arr[left], arr[target] = arr[target], arr[left]
k = left
# 指针交换法
while left < right and arr[right] >= target:
right -= 1
while left < right and arr[left] <= target:
left += 1
if left < right:
arr[left], arr[right] = arr[right], arr[left]
arr[left], arr[k] = arr[k], arr[left]
return left
def select(left, right):
# 使用随机快排的方式
pivot = random.randint(left, right)
index = partition(left, right, pivot)
if index > k:
select(left, index - 1)
elif index < k:
select(index + 1, right)
# 直到index = k退出递归
if k == 0:
return []
if k == n:
return arr[:k]
k = k - 1
select(0, n - 1)
return arr[:k + 1]
# 自己的版本
import random
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
# 快速排序
def partition(left, right):
# 随机快排
tmp = random.randint(left, right)
arr[tmp], arr[left] = arr[left], arr[tmp]
target = arr[left]
while left < right:
# 挖坑法
while left < right and arr[right] >= target:
right -= 1
arr[left] = arr[right]
while left < right and arr[left] <= target:
left += 1
arr[right] = arr[left]
arr[right] = target
return left
n = len(arr)
left = 0
right = n - 1
if k == 0:
return []
if k == n:
return arr[:k]
k -= 1
# 错误写法
# index = partition(left, right)
# # 注意,这种写法是非常不好的!!!因为每次循环,并没有实际改变left和right,我们希望的是在每一次遍历完都会更新left和right的值
# while index != k:
# if index < k:
# tmp = partition(index + 1, right)
# elif index > k:
# tmp = partition(left, index - 1)
# index = tmp
# return arr[:k + 1]
#正确写法
# index = partition(left, right)
# # 注意,这种写法是非常不好的!!!因为每次循环,并没有实际改变left和right,我们希望的是在每一次遍历完都会更新left和right的值
# while index != k:
# if index < k:
# left = index + 1
# index = partition(left, right)
# elif index > k:
# right = index - 1
# index = partition(left, right)
# return arr[:k + 1]
while 1:
# 每一次partition都相当于一次排序!
idx = partition(left, right)
if idx == k:
return arr[:k+1]
if idx < k:
left = idx + 1
if idx > k:
right = idx - 1
return arr[:k + 1]
# java
'''
# 小根堆
class Solution {
public int[] smallestK(int[] arr, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(k + 1);
Arrays.stream(arr).forEach(num -> heap.offer(num));
int[] res = new int[k];
int idx = 0;
while (idx < k) res[idx++] = heap.poll();
return res;
}
}
# 大根堆
class Solution {
public int[] smallestK(int[] arr, int k) {
if (k == 0) return new int[0];
PriorityQueue<Integer> heap = new PriorityQueue<>(k + 1, Comparator.comparingInt(item -> -item));
int idx = 0, len = arr.length;
for (; idx < k; ++idx)
heap.offer(arr[idx]);
for (; idx < len; ++idx) {
heap.offer(arr[idx]);
heap.poll();
}
return heap.stream().mapToInt(Integer::valueOf).toArray();
}
}
# lambda
class Solution {
public int[] smallestK(int[] arr, int k) {
return Arrays.stream(arr).sorted().limit(k).toArray();
}
}
# 快排
public int[] smallestK(int[] arr, int k) {
if (k >= arr.length) {
return arr;
}
int low = 0;
int high = arr.length - 1;
while (low < high) {
int pos = partition(arr, low, high);
if (pos == k - 1) {
break;
} else if (pos < k - 1) {
low = pos + 1;
} else {
high = pos - 1;
}
}
int[] dest = new int[k];
System.arraycopy(arr, 0, dest, 0, k);
return dest;
}
private int partition(int[] arr, int low, int high) {
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
# 排序
class Solution {
public int[] smallestK(int[] arr, int k) {
if (arr == null || arr.length == 0) return new int[k];
int[] result = new int[k];
Arrays.sort(arr);
for (int i = 0; i < k; i++) {
result[i] = arr[i];
}
return result;
}
}
# 最小堆
class Solution {
public int[] smallestK(int[] arr, int k) {
if (arr == null || arr.length == 0) return new int[k];
int[] result = new int[k];
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int i : arr) {
queue.offer(i);
}
for (int i = 0; i < k; i++) {
result[i] = queue.poll();
}
return result;
}
}
# 应该使用的大根堆
class Solution {
public int[] smallestK(int[] arr, int k) {
if (arr == null) return arr;
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for (int num : arr) {
if (maxHeap.size() == k) {
if (maxHeap.peek()!=null && num < maxHeap.peek()) {
maxHeap.remove();
maxHeap.offer(num);
}
} else {
//还未满,继续添加元素
maxHeap.offer(num);
}
}
return heap2Array(maxHeap);
}
private int[] heap2Array(PriorityQueue<Integer> maxHeap) {
int[] arr = new int[maxHeap.size()];
List<Integer> list = new ArrayList<>(maxHeap);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
}
''' |
1941b7e762054d1f0b6c674664d2abe0fe5bc52d | huhudaya/leetcode- | /LeetCode/092. 反转链表 II.py | 3,992 | 3.796875 | 4 | # 92. 反转链表 II.py
'''
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 递归,记录使用后继节点
class Solution:
# 递归版本
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# 全局变量
self.successor = None
# 反转前N个节点函数
def reverseN(head, n):
if n == 1:
# 注意一定要注意保存这个后继节点
self.successor = head.next
return head
last = reverseN(head.next, n - 1)
head.next.next = head
head.next = self.successor
return last
if m == 1:
return reverseN(head, n)
head.next = self.reverseBetween(head.next, m - 1, n - 1)
return head
class Solution:
# 非递归版本
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# 重点是找到m前一个pre
cur = head
pre = None
tail = None
cnt = 0
while cur:
cnt += 1
pre = cur if cnt == m - 1 else pre
tail = cur if cnt == n + 1 else tail
cur = cur.next
if m > n or m < 1 or n > cnt:
return head
start = head if pre is None else pre.next
cur = start.next
start.next = tail
# 反转逻辑
while cur != tail:
next = cur.next
cur.next = start
start = cur
cur = next
if pre:
# fuck 我这里写成了"=="。。。。黑人问号脸
pre.next = start
return head
return start
# 简约解法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# 非递归
dummy = ListNode(-1)
dummy.next = head
pre = dummy
# 此时pre指针指向第m - 1个节点
for i in range(m - 1):
pre = pre.next
cur = pre.next
# 保存这个pre
node = pre
pre = None
# 反转m-n 需要转n-m+1次
for i in range(n - m + 1):
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
node.next.next = cur
node.next = pre
return dummy.next
'''
思路二:
用三个指针,进行插入操作
例如:
1->2->3->4->5->NULL, m = 2, n = 4
将节点3插入节点1和节点2之间
变成: 1->3->2->4->5->NULL
再将节点4插入节点1和节点3之间
变成:1->4->3->2->5->NULL
实现翻转的效果!
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
pre = dummy
# 找到翻转链表部分的前一个节点, 1->2->3->4->5->NULL, m = 2, n = 4 指的是 节点值为1
for _ in range(m - 1):
pre = pre.next
# 用 pre, start, tail三指针实现插入操作
# tail 是插入pre,与pre.next的节点
start = pre.next
tail = start.next
for _ in range(n - m):
start.next = tail.next
tail.next = pre.next
pre.next = tail
tail = start.next
return dummy.next
|
abcd521c65b0628df20b5bbbd36d26eae35066ee | huhudaya/leetcode- | /剑指offer/面试题10- II. 青蛙跳台阶问题.py | 805 | 3.515625 | 4 | '''
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
提示:
0 <= n <= 100
注意:本题与主站 509 题相同:https://leetcode-cn.com/problems/fibonacci-number/
链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof
'''
class Solution:
def numWays(self, n: int) -> int:
# dp
if n < 2:
return 1
dp = [0 for i in range(n + 1)]
dp[1] = 1
dp[2] = 2
for i in range(3, n+1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n] % 1000000007 |
bf80f7db8370374e52346a09c1a75fe38e225fbc | huhudaya/leetcode- | /基础算法/归并排序.py | 1,755 | 3.84375 | 4 | # 思路是利用递归 注意递归的三要素
# 一定要有递归结束条件,不断调用自身,不断向递归结束条件靠近
# 核心思想,先递归sort,然后merge,不同于快排,快排是先排序,然后递归子快排
# 谁小移动谁
# 使用递归的时候需要注意一点,当不需要返回值得时候 不需要return,当需要有返回值的时候,一定要设置return
# 归并排序的空间复杂度有点高啊!
# 每次都需要一个子的空间
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2
# 当使用list[:], 此时left和right是两个新开辟的链表
left = alist[0:mid]
right = alist[mid:]
mergeSort(left)
mergeSort(right) # 递归过程
# merge过程
i = 0
j = 0
k = 0 # 用k来表示新的数组 其实可以用一个新的数组,arr_new,但是增加了空间消耗,所以可以使用原数组
# merge的过程
while i < len(left) and j < len(right):
if left[i] < right[j]:
alist[k] = left[i] # 因为数组是可变类型,所以直接对列表进行值修改
i += 1
# print(1)
else:
alist[k] = right[j]
j += 1
k += 1 # 每次k+1
while i < len(left): # 总有一个要越界
alist[k] = left[i]
k += 1
i += 1
while j < len(right):
alist[k] = right[j]
k += 1
j += 1
return alist
list = [6, 1, 23, 4, 234, 1, 2, 5, 2, 4, 1]
list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
list = [-2, 3, 2]
mergeSort(list)
print(list)
list = [1, 2, 3]
list[0] = 2
num = list
print(num)
|
f7343791fa4a35d2c48a604fafe4e4f4f8fa3f81 | huhudaya/leetcode- | /LeetCode/042. 接雨水.py | 3,644 | 3.921875 | 4 | # 42. 接雨水.py
'''
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1]
表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
链接:https://leetcode-cn.com/problems/trapping-rain-water
'''
class Solution:
def trap(self, height) -> int:
# 双指针优化版本
n = len(height)
if n < 1:
return 0
ans = 0
left = 0
right = n - 1
l_max = height[0]
r_max = height[n - 1]
# 每次循环更新一次,所以这里必须<=
while left <= right:
l_max = max(height[left], l_max)
r_max = max(height[right], r_max)
# 谁小移动谁,相当于当前指针所在位置已经计算过了
if l_max < r_max:
ans += l_max - height[left]
left += 1
else:
ans += r_max - height[right]
right -= 1
return ans
'''
# 接雨水
# 暴力法
'''
def trap(heigh):
length = len(heigh)
ans = 0
# 边走边算
# 从第二个到倒数第二个之间计算
for i in range(1, length - 1):
l_max, r_max = heigh[0], heigh[length - 1]
# 找到当前元素右边最高的柱子
for j in range(i, length):
r_max = max(heigh[j], r_max)
# 找到当前元素左边最高柱子
for j in range(i, 0, -1):
l_max = max(heigh[j], l_max)
# 计算当前元素能接的最大水量,同时累加到ans结果中
ans += min(l_max, r_max) - heigh[i]
return ans
#备忘录优化
# 准备两个备忘录,减少重复计算
'''
# 我们开两个数组r_max和l_max充当备忘录
# l_max[i]表示位置 i 左边最高的柱子高度
# r_max[i]表示位置 i 右边最高的柱子高度
'''
def mempTrap(heigh):
if len(heigh) < 1:
return 0
length = len(heigh)
ans = 0
# 准备两个备忘录
l_max, r_max = [0 for i in range(length)], [0 for i in range(length)]
# 当前元素左边最大值
l_max[0] = heigh[0]
# 当前元素右边最大值
r_max[-1] = heigh[-1]
# 计算从i到左右两边的最大值
for i in range(1, length):
r_max[i] = max(heigh[i], r_max[i - 1])
for i in range(length - 1, -1, -1):
l_max[i] = max(heigh[i], l_max[i + 1])
# 计算答案,第一个和最后一个位置不用计算
for i in range(1, length - 1):
ans += min(l_max[i] - r_max[i]) - heigh[i]
return ans
# 双指针
'''
# 边走边算
# l_max是height[0..left]中最高柱子的高度,
# r_max是height[right..end]的最高柱子的高度
# 最后双指针一定会相遇,所以移动一次计算一次
'''
def twoPreTrap(heigh):
if len(heigh) < 1:
return 0
length = len(heigh)
ans = 0
left = 0
right = length - 1
l_max = heigh[0]
r_max = heigh[length - 1]
# 必须保证left到达right,因为每次判断一步
while left <= right:
# 每次循环更新一次
l_max = max(l_max, heigh[left])
r_max = max(r_max, heigh[right])
# 如果l_max < r_max,即只和l_max相关,就和r_max没有关系了,谁小移动谁
if l_max < r_max:
ans += l_max - heigh[left]
left += 1
else:
ans += r_max - heigh[right]
right -= 1
return ans
print(twoPreTrap([1, 6, 1, 5]))
|
a5e08a21655b8bd6f47ceef4513d10131d968845 | huhudaya/leetcode- | /剑指offer/剑指 Offer 39. 数组中出现次数超过一半的数字.py | 761 | 3.734375 | 4 | '''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
'''
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
if nums is None or nums == []:
return -1
n = len(nums)
candidate = nums[0]
cnt = 1
for i in range(1, n):
if nums[i] == candidate:
cnt += 1
else:
cnt -= 1
if cnt == 0:
cnt = 1
candidate = nums[i]
return candidate |
dd9b3784f2eaaf57245fa15eac92bb895a2c69a6 | huhudaya/leetcode- | /LeetCode/004.寻找两个有序数组的中位数.py | 9,067 | 3.71875 | 4 | # 004.寻找两个有序数组的中位数.py
'''
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
'''
# 二分法! O(log(m+n))
from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n = len(nums1)
m = len(nums2)
left = (n + m + 1) // 2
right = (n + m + 2) // 2
return (self.getKth(nums1, 0, n - 1, nums2, 0, m - 1, left) + self.getKth(nums1, 0, n - 1, nums2, 0, m - 1, right)) / 2
def getKth(self, nums1: List[int], start1: int, end1: int, nums2: List[int], start2: int, end2: int, k: int) -> int:
len1 = end1 - start1 + 1
len2 = end2 - start2 + 1
#让 len1 的长度小于 len2,这样就能保证如果有数组空了,一定是 len1
if len1 > len2:
return self.getKth(nums2, start2, end2, nums1, start1, end1, k)
#这里判断nums1数组是否为空,为空时直接取nums2数组即可
if len1 == 0:
return nums2[start2 + k - 1]
if k == 1:
return min(nums1[start1], nums2[start2])
#为什么要减一?是因为在数组中索引是以0开始的
i = start1 + min(len1, k // 2) - 1
j = start2 + min(len2, k // 2) - 1
#谁小抛弃谁的那一部分
if nums1[i] > nums2[j]:
#这个时候统一都降一个维度,求两个数组的第(k-抛弃的那部分的长度)
return self.getKth(nums1, start1, end1, nums2, j + 1, end2, k - (j - start2 + 1))
else:
return self.getKth(nums1, i + 1, end1, nums2, start2, end2, k - (i - start1 + 1))
# 双指针
# 简单粗暴,先将两个数组合并,两个有序数组的合并也是归并排序中的一部分。然后根据奇数,还是偶数,返回中位数。
# 时间复杂度:遍历全部数组 (m+n)(m+n)
# 空间复杂度:开辟了一个数组,保存合并后的两个数组 O(m+n)O(m+n)
'''
解法二
其实,我们不需要将两个数组真的合并,我们只需要找到中位数在哪里就可以了。
开始的思路是写一个循环,然后里边判断是否到了中位数的位置,到了就返回结果,但这里对偶数和奇数的分类会很麻烦。当其中一个数组遍历完后,出了 for 循环对边界的判断也会分几种情况。总体来说,虽然复杂度不影响,但代码会看起来很乱。
首先是怎么将奇数和偶数的情况合并一下。
用 len 表示合并后数组的长度,如果是奇数,我们需要知道第 (len+1)/2 个数就可以了,如果遍历的话需要遍历 int(len/2 ) + 1 次。如果是偶数,我们需要知道第 len/2和 len/2+1 个数,也是需要遍历 len/2+1 次。所以遍历的话,奇数和偶数都是 len/2+1 次。
返回中位数的话,奇数需要最后一次遍历的结果就可以了,偶数需要最后一次和上一次遍历的结果。所以我们用两个变量 left 和 right,right 保存当前循环的结果,在每次循环前将 right 的值赋给 left。这样在最后一次循环的时候,left 将得到 right 的值,也就是上一次循环的结果,接下来 right 更新为最后一次的结果。
循环中该怎么写,什么时候 A 数组后移,什么时候 B 数组后移。用 aStart 和 bStart 分别表示当前指向 A 数组和 B 数组的位置。如果 aStart 还没有到最后并且此时 A 位置的数字小于 B 位置的数组,那么就可以后移了。也就是aStart<m&&A[aStart]< B[bStart]。
但如果 B 数组此刻已经没有数字了,继续取数字 B[ bStart ],则会越界,所以判断下 bStart 是否大于数组长度了,这样 || 后边的就不会执行了,也就不会导致错误了,所以增加为 aStart<m&&(bStart) >= n||A[aStart]<B[bStart]) 。
代码
Java
public double findMedianSortedArrays(int[] A, int[] B) {
int m = A.length;
int n = B.length;
int len = m + n;
int left = -1, right = -1;
int aStart = 0, bStart = 0;
for (int i = 0; i <= len / 2; i++) {
left = right;
if (aStart < m && (bStart >= n || A[aStart] < B[bStart])) {
right = A[aStart++];
} else {
right = B[bStart++];
}
}
if ((len & 1) == 0)
return (left + right) / 2.0;
else
return right;
}
时间复杂度:遍历 len/2+1 次,len=m+n,所以时间复杂度依旧是 O(m+n)O(m+n)。
空间复杂度:我们申请了常数个变量,也就是 m,n,len,left,right,aStart,bStart 以及 i
总共 8 个变量,所以空间复杂度是 O(1)
'''
'''
这道题如果时间复杂度没有限定在 O(log(m+n))O(log(m+n)),我们可以用 O(m+n) 的算法解决,用两个指针分别指向两个数组,比较指针下的元素大小,一共移动次数为 (m+n + 1)/2,便是中位数。
首先,我们理解什么中位数:指的是该数左右个数相等。
比如:odd : [1,| 2 |,3],2 就是这个数组的中位数,左右两边都只要 1 位;
even: [1,| 2, 3 |,4],2,3 就是这个数组的中位数,左右两边 1 位;
那么,现在我们有两个数组:
num1: [a1,a2,a3,...an]
nums2: [b1,b2,b3,...bn]
[nums1[:left1],nums2[:left2] | nums1[left1:], nums2[left2:]]
只要保证左右两边 个数 相同,中位数就在 | 这个边界旁边产生。
如何找边界值,我们可以用二分法,我们先确定 num1 取 m1 个数的左半边,那么 num2 取 m2 = (m+n+1)/2 - m1 的左半边,找到合适的 m1,就用二分法找。
当 [ [a1],[b1,b2,b3] | [a2,..an],[b4,...bn] ]
我们只需要比较 b3 和 a2 的关系的大小,就可以知道这种分法是不是准确的!
例如:我们令:
nums1 = [-1,1,3,5,7,9]
nums2 =[2,4,6,8,10,12,14,16]
当 m1 = 4,m2 = 3 ,它的中位数就是median = (num1[m1] + num2[m2])/2
时间复杂度:O(log(min(m,n)))
对于代码中边界情况,大家需要自己琢磨。
代码:
PythonC++Java
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n1 = len(nums1)
n2 = len(nums2)
if n1 > n2:
return self.findMedianSortedArrays(nums2,nums1)
k = (n1 + n2 + 1)//2
left = 0
right = n1
while left < right :
m1 = left +(right - left)//2
m2 = k - m1
if nums1[m1] < nums2[m2-1]:
left = m1 + 1
else:
right = m1
m1 = left
m2 = k - m1
c1 = max(nums1[m1-1] if m1 > 0 else float("-inf"), nums2[m2-1] if m2 > 0 else float("-inf") )
if (n1 + n2) % 2 == 1:
return c1
c2 = min(nums1[m1] if m1 < n1 else float("inf"), nums2[m2] if m2 <n2 else float("inf"))
return (c1 + c2) / 2
'''
# 双指针
'''
解法二
其实,我们不需要将两个数组真的合并,我们只需要找到中位数在哪里就可以了。
开始的思路是写一个循环,然后里边判断是否到了中位数的位置,到了就返回结果,但这里对偶数和奇数的分类会很麻烦。当其中一个数组遍历完后,出了 for 循环对边界的判断也会分几种情况。总体来说,虽然复杂度不影响,但代码会看起来很乱。
首先是怎么将奇数和偶数的情况合并一下。
用 len 表示合并后数组的长度,如果是奇数,我们需要知道第 (len+1)/2 个数就可以了,如果遍历的话需要遍历 int(len/2 ) + 1 次。如果是偶数,我们需要知道第 len/2和 len/2+1 个数,也是需要遍历 len/2+1 次。所以遍历的话,奇数和偶数都是 len/2+1 次。
返回中位数的话,奇数需要最后一次遍历的结果就可以了,偶数需要最后一次和上一次遍历的结果。所以我们用两个变量 left 和 right,right 保存当前循环的结果,在每次循环前将 right 的值赋给 left。这样在最后一次循环的时候,left 将得到 right 的值,也就是上一次循环的结果,接下来 right 更新为最后一次的结果。
循环中该怎么写,什么时候 A 数组后移,什么时候 B 数组后移。用 aStart 和 bStart 分别表示当前指向 A 数组和 B 数组的位置。如果 aStart 还没有到最后并且此时 A 位置的数字小于 B 位置的数组,那么就可以后移了。也就是aStart<m&&A[aStart]< B[bStart]。
但如果 B 数组此刻已经没有数字了,继续取数字 B[ bStart ],则会越界,所以判断下 bStart 是否大于数组长度了,这样 || 后边的就不会执行了,也就不会导致错误了,所以增加为 aStart<m&&(bStart) >= n||A[aStart]<B[bStart]) 。
'''
|
3d8ea548da4891dd0124ca4f67f366dd64fe1a9a | huhudaya/leetcode- | /程序员面试金典/面试题 03.05. 栈排序.py | 3,190 | 3.734375 | 4 | '''
栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1。
示例1:
输入:
["SortedStack", "push", "push", "peek", "pop", "peek"]
[[], [1], [2], [], [], []]
输出:
[null,null,null,1,null,2]
示例2:
输入:
["SortedStack", "pop", "pop", "push", "pop", "isEmpty"]
[[], [], [], [1], [], []]
输出:
[null,null,null,null,null,true]
说明:
栈中的元素数目在[0, 5000]范围内。
'''
class SortedStack:
def __init__(self):
self.ret = []
def push(self, val: int) -> None:
import bisect
bisect.insort(self.ret, val)
def pop(self) -> None:
try:
self.ret.pop(0)
except:
pass
def peek(self) -> int:
try:
return self.ret[0]
except:
return -1
def isEmpty(self) -> bool:
return self.ret == []
# 两个栈
class SortedStack:
def __init__(self):
self.data = []
self.helper = []
def push(self, val: int) -> None:
if not self.data: # 如果 data 为空,直接将元素添加到data中
self.data.append(val)
else:
# 如果 data 顶的元素比val小,将 data 中比 val 小的元素倒到 helper 中
#然后将 val 放入 data 顶
if self.data[-1] < val:
while self.data and self.data[-1] < val:
self.helper.append(self.data.pop(-1))
self.data.append(val)
# 如果 data 顶的元素等于 val,直接将 val 放在 data 顶
elif self.data[-1] == val:
self.data.append(val)
else:
# 此时的情况为:val < sel.data[-1],需要把 helper 中比 val 大的元素倒到data顶去
# case 1, 如果helper 为空,或者 val 大于等于 helper 顶的元素
# 直接将val 放到 data 顶
if not self.helper or self.helper[-1] <= val:
self.data.append(val)
else:
# case 2, val 小于 helper 的栈顶元素,则把小于 val 的元素倒回 data 中
# 然后把 val 放在 data 栈顶
while self.helper and val < self.helper[-1]:
self.data.append(self.helper.pop())
self.data.append(val)
def pop(self) -> None:
if not self.data:
return -1
# 由于 helper 中会放有较小的元素,
# 首先检查 helper 是否有元素,有的话将其倒入 data 中
# pop data 顶的元素(当前最小值)
while self.helper:
self.data.append(self.helper.pop())
return self.data.pop()
def peek(self) -> int:
if not self.data:
return -1
while self.helper:
self.data.append(self.helper.pop())
return self.data[-1]
def isEmpty(self) -> bool:
return self.data == [] |
67c285419da28e7fbf17626dff2515676dd97875 | huhudaya/leetcode- | /剑指offer/面试题62. 圆圈中最后剩下的数字.py | 8,016 | 3.765625 | 4 | '''
0,1,,n-1这n个数字排成一个圆圈,从数字0开始
每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。
例如,0、1、2、3、4这5个数字组成一个圆圈
从数字0开始每次删除第3个数字
则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。
示例 1:
输入: n = 5, m = 3
输出: 3
示例 2:
输入: n = 10, m = 17
输出: 2
'''
# 约瑟夫环
# Python 默认的递归深度不够,需要手动设置
# 时间和空间复杂度都是O(N)
'''
题目中的要求可以表述为:给定一个长度为 n 的序列,每次向后数 m 个元素并删除,那么最终留下的是第几个元素?
这个问题很难快速给出答案。但是同时也要看到,这个问题似乎有拆分为较小子问题的潜质:
如果我们知道对于一个长度 n - 1 的序列,留下的是第几个元素,那么我们就可以由此计算出长度为 n 的序列的答案。
算法
我们将上述问题建模为函数 f(n, m),该函数的返回值为最终留下的元素的序号。
首先,长度为 n 的序列会先删除第 m % n 个元素,然后剩下一个长度为 n - 1 的序列。
那么,我们可以递归地求解 f(n - 1, m),就可以知道对于剩下的 n - 1 个元素,最终会留下第几个元素,我们设答案为 x = f(n - 1, m)。
由于我们删除了第 m % n 个元素,将序列的长度变为 n - 1。当我们知道了 f(n - 1, m) 对应的答案 x 之后
我们也就可以知道,长度为 n 的序列最后一个删除的元素,应当是从 m % n 开始数的第 x 个元素
因此有 f(n, m) = (m % n + x) % n = (m + x) % n。
'''
# 注意 是每次删除一个人,第一次有8个人的时候,第一轮过去杀死一个还有7个人
# 递推 f(8,3) = (f(7, 3) + 3) % 8
# f(n,m) = (f(n - 1 + m) % n)
import sys
sys.setrecursionlimit(100000)
'''
大体思路:
n个人编号0,1,2,...,n-1,每数m次删掉一个人
假设有函数f(n)表示n个人最终剩下人的编号
n个人删掉1个人后可以看做n-1的状态,不过有自己的编号。
n个人删掉的第一个人的编号是(m-1)%n,那么n个人时删掉第一个人的后面那个人(m-1+1)%n一定是n-1个人时候编号为0的那个人,即n个人时的编号m%n(这个编号是对于n个人来考虑的),n-1个人时编号为i的人就是n个人时(m+i)%n
所以f(n)=(m+f(n-1))%n
f(1)=0,因为1个人时只有一个编号0。
'''
'''
两者序号的关系
我们知道,从 f(n - m) 场景下删除的第一个数的序号是 (m - 1) % n,那么 f(n - 1, m) 场景将使用被删除数字的下一个数,即序号 m % n 作为它的 0 序号。
设 f(n - 1, m) 的结果为 x,x 是从 f(n, m) 场景下序号为 m % n 的数字出发所获得的结果,因此,我们可以得出:m % n + x 是该数字在 f (n, m) 场景下的结果序号。即:
f(n, m) = m % n + x
但由于 m % n + x 可能会超过 n 的范围,所以我们再取一次模:
f(n , m) = (m % n + x) % n = (m + x) % n
将 f(n - 1, m) 代回,得到递推公式:
f(n, m) = (m + f(n - 1, m)) % n
有了递推公式后,想递归就递归,想迭代就迭代咯~
'''
# 一个基本事实,当n-1和n带入函数中得到的都是同一个值,这个值是存好的那个人的编号!
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
# 递归函数的定义为:返回存活的那个人的编号
def f(n, m):
if n == 0:
return 0
# 有n - 1个人的时候,存好的那个人的编号,然后根据那个人的编号进行反推
x = f(n - 1, m)
return (m + x) % n
return f(n, m)
# 数学法 时间O(N),空间O(1)
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
f = 0
for i in range(2, n + 1):
f = (m + f) % i
return f
from collections import deque
# 队列模拟
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
simqueue = deque()
for i in range(n):
simqueue.append(i)
while len(simqueue) > 1:
for i in range(n):
simqueue.append(simqueue.popleft())
# 循环结束后kill一个人
simqueue.popleft()
alive = simqueue.popleft()
return alive
'''
既然约塞夫问题就是用人来举例的,那我们也给每个人一个编号(索引值),每个人用字母代替
下面这个例子是N=8 m=3的例子
我们定义F(n,m)表示最后剩下那个人的索引号,因此我们只关系最后剩下来这个人的索引号的变化情况即可
从8个人开始,每次杀掉一个人,去掉被杀的人,然后把杀掉那个人之后的第一个人作为开头重新编号
第一次C被杀掉,人数变成7,D作为开头,(最终活下来的G的编号从6变成3)
第二次F被杀掉,人数变成6,G作为开头,(最终活下来的G的编号从3变成0)
第三次A被杀掉,人数变成5,B作为开头,(最终活下来的G的编号从0变成3)
以此类推,当只剩一个人时,他的编号必定为0!(重点!)
现在我们知道了G的索引号的变化过程,那么我们反推一下
从N = 7 到N = 8 的过程
如何才能将N = 7 的排列变回到N = 8 呢?
我们先把被杀掉的C补充回来,然后右移m个人,发现溢出了,再把溢出的补充在最前面
神奇了 经过这个操作就恢复了N = 8 的排列了!
'''
'''
class Solution {
public:
int lastRemaining(int n, int m) {
int pos = 0; // 最终活下来那个人的初始位置
for(int i = 2; i <= n; i++){
pos = (pos + m) % i; // 每次循环右移
}
return pos;
}
};
'''
# java链表模拟
'''
class Solution {
public int lastRemaining(int n, int m) {
ArrayList<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(i);
}
int idx = 0;
while (n > 1) {
idx = (idx + m - 1) % n;
list.remove(idx);
n--;
}
return list.get(0);
}
}
'''
'''
首先,记f(n)为游戏结束后最后一个数字的index
那么关键在于找到f(n,start=0)和f(n-1,start=0)的关系
显然,第一次扔出去的元素是(m-1)%n,记作k
那么根据游戏规则f(n,start=0)=f(n-1,start = k+1)。
接下来我们可以看到f(n-1,start = k+1) = (f(n-1,start=0)+k+1)%n。
有了这个中间桥梁,可知f(n,start=0) = (f(n-1,start=0)+k+1)%n = (f(n-1,start=0)+m)%n。
然后从f(1)=0推广过去即可。
这类问题凭空很难找到规律,建议记住f(n) = (f(n-1)+m)%n的大概形式,再去推导会比较有方向。
数学归纳法都是扯淡,都是有了公式强行去归纳,要是不知道递推公式怎么能从n=1,n=2,n=3找到取模规律
'''
'''
最终剩下一个人时的安全位置肯定为0,反推安全位置在人数为n时的编号
人数为1: 0
人数为2: (0+m) % 2
人数为3: ((0+m) % 2 + m) % 3
人数为4: (((0+m) % 2 + m) % 3 + m) % 4
........
迭代推理到n就可以得出答案
如果用dp的方式来思考本题。
状态:还剩i个人的时候,安全人所在的位置编号 reuslt
初始状态:只剩一个人的时候,他的位置肯定是 result = 0
状态方程: i -> i + 1 result = (m + result) % i
'''
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
res = 0
# 最后一轮剩下2个人,所以从2开始反推
for i in range(1, n + 1):
# 核心思路就是只关注活着的人的索引,为什么要余 i 呢?
# 这是因为前一轮的人数少于当前轮,比如第7轮有7个人, 第8轮有8个人
# 因为我们是从前到后推导的,所以要余数保证在当前轮的范围中
res = (res + m) % i
return res
print(Solution().lastRemaining(8, 3))
|
e879ba8849510b693486910878007d6769ba12b8 | huhudaya/leetcode- | /LeetCode/1497. 检查数组对是否可以被 k 整除.py | 1,697 | 3.65625 | 4 | '''
给你一个整数数组 arr 和一个整数 k ,其中数组长度是偶数,值为 n 。
现在需要把数组恰好分成 n / 2 对,以使每对数字的和都能够被 k 整除。
如果存在这样的分法,请返回 True ;否则,返回 False 。
示例 1:
输入:arr = [1,2,3,4,5,10,6,7,8,9], k = 5
输出:true
解释:划分后的数字对为 (1,9),(2,8),(3,7),(4,6) 以及 (5,10)
示例 2:
输入:arr = [1,2,3,4,5,6], k = 7
输出:true
解释:划分后的数字对为 (1,6),(2,5) 以及 (3,4) 。
示例 3:
输入:arr = [1,2,3,4,5,6], k = 10
输出:false
解释:无法在将数组中的数字分为三对的同时满足每对数字和能够被 10 整除的条件。
示例 4:
输入:arr = [-10,10], k = 2
输出:true
示例 5:
输入:arr = [-1,1,-2,2,-3,3,-4,4], k = 3
输出:true
提示:
arr.length == n
1 <= n <= 10^5
n 为偶数
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
'''
# java
# (x + y) // k = 3 ===> (x // k + y // k) = 3 ===>
'''
两个数 x 和 y 的和能被 kk 整除,当且仅当这两个数对 kk 取模的结果 x_kx,k和 y_ky k的和就能被 k 整除。
这里我们规定取模的结果大于等于 0,无论 x 和 y 的正负性。
因此,我们将数组 arr 中的每个数 x 对 k 进行取模,并将得到的余数 x_k,k 进行配对:
'''
'''
class Solution {
public boolean canArrange(int[] arr, int k) {
int[] mod = new int[k];
for(int i : arr){
// 消除负数
mod[(i % k + k) % k]++;
}
for(int i = 1; i < k; i++){
if(mod[i] != mod[k - i]) return false;
}
return mod[0] % 2 == 0 ? true : false;
}
}
'''
|
0dfe73a481072f62172baa987310c7d69e60d68c | huhudaya/leetcode- | /LeetCode/015.三数之和.py | 1,640 | 3.640625 | 4 | # 015三数之和.py
'''
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c
使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
'''
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
length = len(nums)
nums.sort()
result = []
if length < 3 or nums is None:
return []
for i in range(length):
if nums[i] > 0:
break
# 去重,这里应该是continue,不能是break
if i > 0 and nums[i] == nums[i - 1]:
continue
r = length - 1
l = i + 1
while l < r:
_sum = nums[i] + nums[l] + nums[r]
if _sum == 0:
result.append([nums[i], nums[l], nums[r]])
# 小剪枝 去重,注意必须先判断 l < r,否则会出现超出索引
while l < r and nums[l] == nums[l + 1]:
l += 1
# 小剪枝
while l < r and nums[r] == nums[r - 1]:
r -= 1
# 注意这里,每次循环必须移动指针,否则死循环
l += 1
r -= 1
elif _sum < 0:
l += 1
elif _sum > 0:
r -= 1
return result
|
9c6055411762ab85229ee62fe7722f0c069f0cb1 | huhudaya/leetcode- | /LeetCode/117. 填充每个节点的下一个右侧节点指针 II.py | 3,557 | 4.1875 | 4 | '''
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
提示:
树中的节点数小于 6000
-100 <= node.val <= 100
'''
# BFS
def connect(self, root: 'Node') -> 'Node':
from collections import deque
if not root: return root
queue = deque()
queue.appendleft(root)
while queue:
p = None
n = len(queue)
for _ in range(n):
tmp = queue.pop()
if p:
p.next = tmp
p = p.next
else:
p = tmp
if tmp.left:
queue.appendleft(tmp.left)
if tmp.right:
queue.appendleft(tmp.right)
p.next = None
return root
# 迭代方法
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
cur = root
head = None
tail = None
while cur:
while cur:
if cur.left:
if not head:
head = cur.left
tail = cur.left
else:
tail.next = cur.left
tail = tail.next
if cur.right:
if not head:
head = cur.right
tail = cur.right
else:
tail.next = cur.right
tail = tail.next
cur = cur.next
cur = head
head = None
tail = None
return root
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
head = root
while head: # 当前层的头节点
cur = head # 当前层处理节点
pre = head = None # 初始化下一层头节点和前置节点
while cur:
if cur.left:
if not pre: # 若尚未找到下一层前置节点,则同步更新下一层头节点和前置节点
pre = head = cur.left
else: # 已找到下一层前置节点,则将前置节点指向当前子节点,并前移pre
pre.next = cur.left
pre = pre.next
if cur.right:
if not pre:
pre = head = cur.right
else:
pre.next = cur.right
pre = pre.next
cur = cur.next
return root
|
314f6080e1b6184de80b92f5c93aceb064084d81 | huhudaya/leetcode- | /程序员面试金典/面试题 04.08. 首个共同祖先.py | 1,508 | 3.765625 | 4 | '''
设计并实现一个算法,找出二叉树中某两个节点的第一个共同祖先。不得将其他的节点存储在另外的数据结构中。注意:这不一定是二叉搜索树。
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
def dfs(root, p, q):
if root is None:
return None
if root.val == p.val:
return p
if root.val == q.val:
return q
left = dfs(root.left, p, q)
right = dfs(root.right, p, q)
if left is None:
return right
if right is None:
return left
return root
return dfs(root, p, q)
|
cd65bf7314fd8eec1d38d878d90fe5e2706bbcf2 | huhudaya/leetcode- | /LeetCode/1071. 字符串的最大公因子.py | 2,102 | 3.578125 | 4 | '''
对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
示例 1:
输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"
示例 2:
输入:str1 = "ABABAB", str2 = "ABAB"
输出:"AB"
示例 3:
输入:str1 = "LEET", str2 = "CODE"
输出:""
提示:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] 和 str2[i] 为大写英文字母
'''
# 枚举法
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
for i in range(min(len(str1), len(str2)), 0, -1):
if (len(str1) % i) == 0 and (len(str2) % i) == 0:
if str1[: i] * (len(str1) // i) == str1 and str1[: i] * (len(str2) // i) == str2:
return str1[: i]
return ''
# 枚举优化
'''
方法二:枚举优化
思路
注意到一个性质:如果存在一个符合要求的字符串 X
那么也一定存在一个符合要求的字符串 X',它的长度为 str1 和 str2 长度的最大公约数
最大公约数为gcd(x1, x2)
解法2证明:
证:如果存在最大公约串,则其的长度必然等于两母串长度的最大公约数
证明:
反证:如果存在最大公约串sub的长度不等于两串长度的最大公约数gcd ①成立则上述规律不成立
那么gcd必然大于sub长度,否则sub的长度就是gcd,即sub长度小于gcd
如果sub长度小于gcd,而且sub又是公约串
那么sub必然是长度为gcd的串gsub的公约串
那么gsub是比sub更长的公约串
那么gsub才是最大公约串,与①不符
反证不成立,得证
'''
import math
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# gcd算法需要O(logN)
candidate_len = math.gcd(len(str1), len(str2))
candidate = str1[: candidate_len]
if candidate * (len(str1) // candidate_len) == str1 and candidate * (len(str2) // candidate_len) == str2:
return candidate
return '' |
a0cb76c0ab71152237c883438b4bccb4538746a4 | huhudaya/leetcode- | /LeetCode/538. 把二叉搜索树转换为累加树.py | 1,443 | 3.953125 | 4 | '''
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 原始二叉搜索树:
5
/ \
2 13
输出: 转换为累加树:
18
/ \
20 13
注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
# 利用二叉搜索树的中序遍历是有序的性质
if root is None:
return None
self.cur_sum = 0
def dfs(root):
if root is None:
return
# 反向遍历
dfs(root.right)
self.cur_sum = self.cur_sum + root.val
root.val = self.cur_sum
dfs(root.left)
dfs(root)
return root
# go
'''
func convertBST(root *TreeNode) *TreeNode {
sum := 0
var dfs func(*TreeNode)
dfs = func(node *TreeNode) {
if node != nil {
dfs(node.Right)
sum += node.Val
node.Val = sum
dfs(node.Left)
}
}
dfs(root)
return root
}
''' |
dce0e479473783cf9dac90bcc29a51e8bddf7a6c | huhudaya/leetcode- | /LeetCode/504. 七进制数.py | 481 | 3.546875 | 4 | '''
给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100
输出: "202"
示例 2:
输入: -7
输出: "-10"
注意: 输入范围是 [-1e7, 1e7] 。
'''
class Solution:
def convertToBase7(self, num: int) -> str:
res = ''
numAbs = abs(num)
while numAbs >= 7:
res += str(numAbs % 7)
numAbs //= 7
res += str(numAbs)
return res[::-1] if num >= 0 else '-' + res[::-1]
|
dc6f550f530d06980747d5b08c013a4381659075 | huhudaya/leetcode- | /剑指offer/剑指 Offer 58 - II. 左旋转字符串.py | 3,240 | 4.0625 | 4 | '''
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
请定义一个函数实现字符串左旋转操作的功能。
比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
限制:
1 <= k < s.length <= 10000
'''
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:] + s[:n]
# 拼接
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
res = []
for i in range(n, len(s)):
res.append(s[i])
for i in range(n):
res.append(s[i])
return ''.join(res)
# java
'''
class Solution {
public String reverseLeftWords(String s, int n) {
StringBuilder res = new StringBuilder();
for(int i = n; i < s.length(); i++)
res.append(s.charAt(i));
for(int i = 0; i < n; i++)
res.append(s.charAt(i));
return res.toString();
}
}
'''
# 求余
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
res = []
for i in range(n, n + len(s)):
res.append(s[i % len(s)])
return ''.join(res)
# java
'''
class Solution {
public String reverseLeftWords(String s, int n) {
StringBuilder res = new StringBuilder();
for(int i = n; i < n + s.length(); i++)
res.append(s.charAt(i % s.length()));
return res.toString();
}
}
'''
# 方法三:字符串遍历拼接
'''
感谢分享,另外对于Java而言,上述第三种方法还有其他的缺点:
使用+进行字符串拼接时,Java实际上是通过new出一个StringBuilder对象,然后进行append操作,最后通过toString方法返回String对象完成的,会造成内存资源的额外浪费。
所以如果在循环体中,字符串的连接方式,推荐使用StringBuilder的append方法进行扩展,而不要使用+。
不是在循环体中的话,可以使用+,代码更加简洁和可读,如方法一的代码。
'''
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
res = ""
for i in range(n, len(s)):
res += s[i]
for i in range(n):
res += s[i]
return res
'''
class Solution {
public String reverseLeftWords(String s, int n) {
String res = "";
for(int i = n; i < s.length(); i++)
res += s.charAt(i);
for(int i = 0; i < n; i++)
res += s.charAt(i);
return res;
}
}
'''
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
res = ""
for i in range(n, n + len(s)):
res += s[i % len(s)]
return res
'''
class Solution {
public String reverseLeftWords(String s, int n) {
String res = "";
for(int i = n; i < n + s.length(); i++)
res += s.charAt(i % s.length());
return res;
}
}
'''
# java
'''
class Solution {
public String reverseLeftWords(String s, int n) {
if(n == 0) return s;
return s.substring(n)+s.substring(0, n);
}
}
''' |
ec603e4b049f85e770e5a83339158ea03a691e43 | huhudaya/leetcode- | /utils/list2ListNode.py | 279 | 3.625 | 4 | # list转链表
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def list2ListNode(list) -> ListNode:
dummy = ListNode(-1)
pre = dummy
for i in list:
pre.next = ListNode(i)
pre = pre.next
return dummy.next
|
7f854aa0270fbc9ba330f77832100dfa2d7b2268 | huhudaya/leetcode- | /LeetCode周赛/201场(滴滴)/5471. 和为目标值的最大数目不重叠非空子数组数目.py | 2,884 | 3.78125 | 4 | '''
给你一个数组 nums 和一个整数 target 。
请你返回 非空不重叠 子数组的最大数目,且每个子数组中数字和都为 target 。
示例 1:
输入:nums = [1,1,1,1,1], target = 2
输出:2
解释:总共有 2 个不重叠子数组(加粗数字表示) [1,1,1,1,1] ,它们的和为目标值 2 。
示例 2:
输入:nums = [-1,3,5,1,4,2,-9], target = 6
输出:2
解释:总共有 3 个子数组和为 6 。
([5,1], [4,2], [3,5,1,4,2,-9]) 但只有前 2 个是不重叠的。
示例 3:
输入:nums = [-2,6,6,3,5,4,1,2,8], target = 10
输出:3
示例 4:
输入:nums = [0,0,0], target = 0
输出:3
提示:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
0 <= target <= 10^6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
from typing import List
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
s = {0}
cur_sum = 0
ans = 0
for num in nums:
cur_sum += num
if cur_sum - target in s:
s = {0}
cur_sum = 0
ans += 1
else:
s.add(cur_sum)
return ans
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
""" 贪心:从左向右寻找第一个符合要求的子数组,发现后重置,并继续查找
pre记录当前的前缀和,初始为0
mp记录出现过的前缀和,题目要求不重叠,故使用set实现即可,初始只含0
当发现有pre[i] - pre[j] == target (j < i)时,表示发现一个满足要求的子数组
即pre - target in mp
此时应: ans += 1,且初始化 mp 和 pre
否则在mp中记录该前缀和
"""
mp = set([0])
pre = 0 # 前缀和
ans = 0
for n in nums:
pre += n
if pre - target in mp:
ans += 1
mp = set([0])
pre = 0
else:
mp.add(pre)
return ans
# 前缀和+hash+贪心
from collections import defaultdict
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
# 前缀和
pre_sum = 0
cnt = 0
hash = defaultdict(int)
hash[0] = 1
for num in nums:
pre_sum += num
if pre_sum - target in hash:
cnt += 1
# 不能重复,所以贪心选择
hash = defaultdict(int)
hash[0] = 1
pre_sum = 0
else:
hash[pre_sum] += 1
return cnt
|
d5c8375ef4991d2b93e2cf44731cf5c99fc5d0eb | huhudaya/leetcode- | /LeetCode/279. 完全平方数.py | 2,508 | 3.546875 | 4 | '''
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n
你需要让组成和的完全平方数的个数最少
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
'''
class Solution:
def numSquares(self, n: int) -> int:
from collections import deque
deq = deque()
visited = set()
deq.append((n, 0))
while deq:
number, step = deq.popleft()
targets = [number - i * i for i in range(1, int(number ** 0.5) + 1)]
for target in targets:
if target == 0:
return step + 1
if target not in visited:
deq.append((target, step + 1))
visited.add(target)
return 0
# Java
'''
class Solution {
public int numSquares(int n) {
Queue<Integer> queue = new LinkedList<>();
HashSet<Integer> visited = new HashSet<>();
int level = 0;
queue.add(n);
while (!queue.isEmpty()) {
int size = queue.size();
level++; // 开始生成下一层
for (int i = 0; i < size; i++) {
int cur = queue.poll();
//依次减 1, 4, 9... 生成下一层的节点
for (int j = 1; j * j <= cur; j++) {
int next = cur - j * j;
if (next == 0) {
return level;
}
if (!visited.contains(next)) {
queue.offer(next);
visited.add(next);
}
}
}
}
return -1;
}
}
'''
# 自己的版本
from collections import deque
class Solution:
def numSquares(self, n: int) -> int:
# BFS
seen = set()
queue = deque()
queue.append(n)
level = 0
while queue:
size = len(queue)
level += 1
for i in range(size):
cur = queue.popleft()
# 依次减 1, 4, 9... 生成下一层的节点
j = 1
while j ** 2 <= cur:
nxt = cur - j * j
j += 1
if nxt == 0:
return level
if nxt not in seen:
queue.append(nxt)
seen.add(nxt)
return -1 |
9995fc4844044f119540a3ba65fb92a0c0a0c96f | huhudaya/leetcode- | /LeetCode/054. 螺旋矩阵.py | 10,379 | 3.6875 | 4 | # 54. 螺旋矩阵.py
'''
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
链接:https://leetcode-cn.com/problems/spiral-matrix
'''
from typing import List
# 模拟螺旋矩阵的形式
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row_len = len(matrix)
column_len = len(matrix[0])
# 模拟顺时针
row_index = [0, 1, 0, -1]
column_index = [1, 0, -1, 0]
# seen 矩阵很重要 用来缩圈,触壁就拐弯,同时也可以在当单行单列的时候,用seen防止重复添加元素
seen = [[False] * column_len for i in range(row_len)]
res = []
row = 0
column = 0
# direction = 0
di = 0
for i in range(row_len * column_len):
res.append(matrix[row][column])
seen[row][column] = True
# 判断下一个前进的方向
rr = row + row_index[di]
cc = column + column_index[di]
# 在范围且没有被访问过,注意必须是 0 <= rr
if 0 <= rr < row_len and 0 <= cc < column_len and not seen[rr][cc]:
row = rr
column = cc
else:
di = (di + 1) % 4
row = row + row_index[di]
column = column + column_index[di]
return res
# 精简版本
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
while matrix:
res += matrix.pop(0)
matrix = list(map(list, zip(*matrix)))[::-1]
return res
# java
# 根据左上角和右下角
'''
class Solution {
public List < Integer > spiralOrder(int[][] matrix) {
List ans = new ArrayList();
if (matrix.length == 0)
return ans;
int r1 = 0, r2 = matrix.length - 1;
int c1 = 0, c2 = matrix[0].length - 1;
while (r1 <= r2 && c1 <= c2) {
for (int c = c1; c <= c2; c++) ans.add(matrix[r1][c]);
for (int r = r1 + 1; r <= r2; r++) ans.add(matrix[r][c2]);
//这里不判断的话,单行或者单列的时候会多添加数字。为了往左走,往上走
if (r1 < r2 && c1 < c2) {
for (int c = c2 - 1; c > c1; c--) ans.add(matrix[r2][c]);
for (int r = r2; r > r1; r--) ans.add(matrix[r][c1]);
}
r1++;
r2--;
c1++;
c2--;
}
return ans;
}
}
'''
# 按圈遍历
class Solution(object):
def spiralOrder(self, matrix):
def spiral_coords(r1, c1, r2, c2):
for c in range(c1, c2 + 1):
yield r1, c
for r in range(r1 + 1, r2 + 1):
yield r, c2
if r1 < r2 and c1 < c2:
for c in range(c2 - 1, c1, -1):
yield r2, c
for r in range(r2, r1, -1):
yield r, c1
if not matrix:
return []
ans = []
r1, r2 = 0, len(matrix) - 1
c1, c2 = 0, len(matrix[0]) - 1
while r1 <= r2 and c1 <= c2:
for r, c in spiral_coords(r1, c1, r2, c2):
ans.append(matrix[r][c])
r1 += 1
r2 -= 1
c1 += 1
c2 -= 1
return ans
# java 计算圈数
'''
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0)
return list;
int m = matrix.length;
int n = matrix[0].length;
int i = 0;
//统计矩阵从外向内的层数,如果矩阵非空,那么它的层数至少为1层
int count = (Math.min(m, n)+1)/2;
//从外部向内部遍历,逐层打印数据
while(i < count) {
for (int j = i; j < n-i; j++) {
list.add(matrix[i][j]);
}
for (int j = i+1; j < m-i; j++) {
list.add(matrix[j][(n-1)-i]);
}
for (int j = (n-1)-(i+1); j >= i && (m-1-i != i); j--) {
list.add(matrix[(m-1)-i][j]);
}
for (int j = (m-1)-(i+1); j >= i+1 && (n-1-i) != i; j--) {
list.add(matrix[j][i]);
}
i++;
}
return list;
}
'''
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix: return []
m = len(matrix)
n = len(matrix[0])
layer_num = (min(m, n) + 1) // 2 # 总共有多少层
res_list = [] # 保存结果
for lr in range(layer_num):
start = lr # 该层左上角的位置(start, start)
last_col = n - lr - 1 # 该层最后一列的索引
last_row = m - lr - 1 # 该层最后一行的索引
for c in range(start, last_col + 1): # from left to right
res_list.append(matrix[start][c])
for r in range(start + 1, last_row + 1): # from top to bottom
res_list.append(matrix[r][last_col])
if last_row != start and last_col != start:
for c1 in range(last_col - 1, start - 1, -1): # from right to bottom
res_list.append(matrix[last_row][c1])
for r1 in range(last_row - 1, start, -1): # from bottom to top
res_list.append(matrix[r1][start])
return res_list
class Solution:
def spiralOrder(self, matrix):
if not matrix:
return []
m, n = len(matrix), len(matrix[0]) # 行,列
# 1. 横向遍历m,纵向遍历n-1;
# 2. 横向遍历m-1,纵向遍历n-2;
# 3. 横向遍历m-2,纵向遍历n-3;
# 4. 直到有一方向遍历长度为0时终止。
ans = []
judge = 1 # 1为顺序遍历,-1为逆序遍历
i, j = 0, -1 # 初始位置,列为-1,因为代表[0,0]前一个位置
while m > 0 and n > 0:
# 横向遍历
for x in range(n):
j += judge * 1
ans.append(matrix[i][j])
# 纵向遍历
for y in range(m - 1):
i += judge * 1
ans.append(matrix[i][j])
# 每遍历一次,m 和 n 都要减少一次,
m = m - 1
n = n - 1
# 每一轮横向和纵向遍历完之后,需要拐点,即col方向减少,row方向减少
judge *= -1
return ans
# 好方法
# 将已经走过的地方置0,然后拐弯的时候判断一下是不是已经走过了,如果走过了就计算一下新的方向:
def solution(matrix):
r, i, j, di, dj = [], 0, 0, 0, 1
if matrix != []:
m = len(matrix)
n = len(matrix[0])
for _ in range(m * n):
r.append(matrix[i][j])
# 走过了就置为0
matrix[i][j] = 0
# di的初始值是1
if matrix[(i + di) % m][(j + dj) % n] == 0:
di, dj = dj, -di
i += di
j += dj
return r
# solution([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
# 回溯
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# 这里多加一个上的方向
directions = [[-1, 0], [0, 1], [1, 0], [0, -1], [-1, 0]]
if not matrix or not matrix[0]:
return []
m = len(matrix)
n = len(matrix[0])
marked = [[False] * n for i in range(m)]
res = []
def flag(x, y):
return 0 <= x < m and 0 <= y < n and not marked[x][y]
def dfs(matrix, i, j, m, n, marked):
marked[i][j] = True
res.append(matrix[i][j])
start = 1
# 向左 和 向下 都不能使用的话,说明是最左边的那一列,优先搜索 上 即可
if not flag(i, j - 1) and not flag(i + 1, j):
start = 0
for di in range(start, 5):
x = i + directions[di][0]
y = j + directions[di][1]
if 0 <= x < m and 0 <= y < n and not marked[x][y]:
dfs(matrix, x, y, m, n, marked)
dfs(matrix, 0, 0, m, n, marked)
return res
# Solution().spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
# 按圈遍历
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return list()
rows, columns = len(matrix), len(matrix[0])
order = list()
left, right, top, bottom = 0, columns - 1, 0, rows - 1
while left <= right and top <= bottom:
for column in range(left, right + 1):
order.append(matrix[top][column])
for row in range(top + 1, bottom + 1):
order.append(matrix[row][right])
if left < right and top < bottom:
for column in range(right - 1, left, -1):
order.append(matrix[bottom][column])
for row in range(bottom, top, -1):
order.append(matrix[row][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return order
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
res = []
m = len(matrix)
n = len(matrix[0])
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
seen = [[False] * n for _ in range(m)]
row = 0
col = 0
di = 0
# 注意这里需要为m * n + 1
for i in range(m * n + 1):
res.append(matrix[row][col])
# 记录是否已经遍历过
seen[row][col] == True
rr = row + directions[di][0]
cc = col + directions[di][1]
if rr < 0 or rr >= m or cc < 0 or cc >= n or seen[rr][cc]:
di = (di + 1) % 4
row += directions[di][0]
col += directions[di][1]
return res
Solution().spiralOrder([[1,2,3],[4,5,6],[7,8,9]]) |
76d7b8dd3cb5a9d1016b5cad4be16f10eb41f97c | huhudaya/leetcode- | /牛客面经整理/字节跳动题库答案/数组/递增数组,找出和为k的数对.py | 1,603 | 3.671875 | 4 | '''
作者:星__尘
链接:https://www.nowcoder.com/discuss/428158?source_id=profile_create&channel=2002
来源:牛客网
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。
如果有多对数字的和等于s,则输出任意一对即可。
双指针遍历:用头尾两个指针,分别开始遍历,两个数字和大于k时,右指针向前移动,小于k时左指针向后移动。
public class Solution{
public ArrayList findPair(int[] nums,int k){
int n = nums.length;
int i = 0;
int j = n - 1;
ArrayList<Integer> list = new ArrayList<>();
while(i < j){
if(nums[i] + nums[j] < k){
i++;
}else if(num[i] + nums[j] > k){
j--;
}else{
list.add(nums[i]);
list.add(nums[j]);
}
}
return list;
}
}
'''
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 因为已经排好序,直接双指针
n = len(nums)
left = 0
right = n - 1
res = []
# 最大值都比target小,剪枝
right_max = nums[right] + nums[right - 1]
if right_max < target:
return res
while left < right:
tmp = nums[left] + nums[right]
if tmp == target:
return [nums[left], nums[right]]
elif tmp < target:
left += 1
else:
right -= 1
return res |
072ff1b85f48cd538b30a2b5ec538e66d8b852e9 | huhudaya/leetcode- | /剑指offer/剑指 Offer 41. 数据流中的中位数.py | 5,140 | 3.96875 | 4 | '''
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
示例 1:
输入:
["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"]
[[],[1],[2],[],[3],[]]
输出:[null,null,null,1.50000,null,2.00000]
示例 2:
输入:
["MedianFinder","addNum","findMedian","addNum","findMedian"]
[[],[2],[],[3],[]]
输出:[null,null,2.00000,null,2.50000]
限制:
最多会对 addNum、findMedia进行 50000 次调用。
注意:本题与主站 295 题相同:https://leetcode-cn.com/problems/find-median-from-data-stream/
'''
# 核心思想,最小栈即右边的堆中的数据有可能会比左边的多一个
import heapq
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.max_heap = []
self.min_heap = []
self.cnt = 0
def addNum(self, num: int) -> None:
# 偶数个
if not (self.cnt & 1):
heapq.heappush(self.max_heap, -num)
heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap))
else:
heapq.heappush(self.min_heap, num)
heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap))
self.cnt += 1
def findMedian(self) -> float:
# 奇数个
if self.cnt & 1:
return self.min_heap[0]
else:
return (self.min_heap[0] + -self.max_heap[0]) / 2
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
# 二分
import bisect
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.nums = []
self.cnt = 0
def addNum(self, num: int) -> None:
bisect.insort(self.nums, num)
self.cnt += 1
def findMedian(self) -> float:
# 奇数
if self.cnt & 1:
return self.nums[self.cnt // 2]
else:
mid = self.cnt // 2
return (self.nums[mid - 1] + self.nums[mid]) / 2
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
# Java
'''
class MedianFinder {
Queue<Integer> maxHeap, minHeap;
int cnt = 0;
/** initialize your data structure here. */
public MedianFinder() {
maxHeap = new PriorityQueue<>();
minHeap = new PriorityQueue<>((x, y) -> y - x);
}
public void addNum(int num) {
// 奇数
if ((cnt & 1) == 1){
minHeap.add(num);
maxHeap.add(minHeap.poll());
}else{
maxHeap.add(num);
minHeap.add(maxHeap.poll());
}
cnt += 1;
}
public double findMedian() {
// 奇数
if((cnt & 1) == 1){
return minHeap.peek();
}else{
return (minHeap.peek() + maxHeap.peek()) / 2.0;
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
'''
'''
import java.util.PriorityQueue;
public class MedianFinder {
/**
* 当前大顶堆和小顶堆的元素个数之和
*/
private int count;
private PriorityQueue<Integer> maxheap;
private PriorityQueue<Integer> minheap;
/**
* initialize your data structure here.
*/
public MedianFinder() {
count = 0;
maxheap = new PriorityQueue<>((x, y) -> y - x);
minheap = new PriorityQueue<>();
}
public void addNum(int num) {
count += 1;
maxheap.offer(num);
minheap.add(maxheap.poll());
// 如果两个堆合起来的元素个数是奇数,小顶堆要拿出堆顶元素给大顶堆
if ((count & 1) != 0) {
maxheap.add(minheap.poll());
}
}
public double findMedian() {
if ((count & 1) == 0) {
// 如果两个堆合起来的元素个数是偶数,数据流的中位数就是各自堆顶元素的平均值
return (double) (maxheap.peek() + minheap.peek()) / 2;
} else {
// 如果两个堆合起来的元素个数是奇数,数据流的中位数大顶堆的堆顶元素
return (double) maxheap.peek();
}
}
}
作者:liweiwei1419
链接:https://leetcode-cn.com/problems/find-median-from-data-stream/solution/you-xian-dui-lie-python-dai-ma-java-dai-ma-by-liwe/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
''' |
33ace2008b854afdf395976fd086d9945f07450a | huhudaya/leetcode- | /牛客企业真题/网易/网易2019实习生招聘编程题集合/安置路灯.py | 1,374 | 3.734375 | 4 | '''
链接:https://www.nowcoder.com/questionTerminal/3a3577b9d3294fb7845b96a9cd2e099c?answerType=1&f=discussion
来源:牛客网
小Q正在给一条长度为n的道路设计路灯安置方案。
为了让问题更简单,小Q把道路视为n个方格,需要照亮的地方用'.'表示, 不需要照亮的障碍物格子用'X'表示。
小Q现在要在道路上设置一些路灯, 对于安置在pos位置的路灯, 这盏路灯可以照亮pos - 1, pos, pos + 1这三个位置。
小Q希望能安置尽量少的路灯照亮所有'.'区域, 希望你能帮他计算一下最少需要多少盏路灯。
输入描述:
输入的第一行包含一个正整数t(1 <= t <= 1000), 表示测试用例数
接下来每两行一个测试数据, 第一行一个正整数n(1 <= n <= 1000),表示道路的长度。
第二行一个字符串s表示道路的构造,只包含'.'和'X'。
输出描述:
对于每个测试用例, 输出一个正整数表示最少需要多少盏路灯。
示例1
输入
2
3
.X.
11
...XX....XX
输出
1
3
'''
# 让灯尽量覆盖到更大的地方 —— 即若i处要照亮的话,那么在i+1处放灯可以照得更远。
#
# 如果第i个位置为'.',则计数器加一,i+=3
def calc(path):
cnt, i = 0, 0
while i<len(path):
if path[i]=='.':
cnt += 1
i += 3
else:
i +=1
return cnt |
fb6746416698011bcc91af0d1cf07739cc1bc2ec | huhudaya/leetcode- | /剑指offer/剑指 Offer 45. 把数组排成最小的数.py | 2,536 | 3.625 | 4 | '''
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例 1:
输入: [10,2]
输出: "102"
示例 2:
输入: [3,30,34,5,9]
输出: "3033459"
'''
# 内置排序
# 相当于一个排序的过程,先两两排序??好像是这样?
from typing import List
import functools
# lambda
class Solution:
def minNumber(self, nums: List[int]) -> str:
def sort_rule(x, y):
a, b = x + y, y + x
return b > a
strs = [str(num) for num in nums]
strs.sort(key=functools.cmp_to_key(sort_rule))
return ''.join(strs)
# java
'''
class Solution {
public String minNumber(int[] nums) {
List<String> list = new ArrayList<>();
for (int num : nums) {
list.add(String.valueOf(num));
}
list.sort((o1, o2) -> (o1 + o2).compareTo(o2 + o1));
return String.join("", list);
}
}
'''
from typing import List
class Solution:
def minNumber(self, nums: List[int]) -> str:
def cmp_(a, b):
return int(str(a) + str(b)) <= int(str(b) + str(a))
def partition(left: int, right: int):
privot = right
small = left - 1
for index in range(left, right):
# if nums[index]<nums[privot]:
if cmp_(nums[index], nums[privot]):
small += 1
nums[small], nums[index] = nums[index], nums[small]
nums[small + 1], nums[privot] = nums[privot], nums[small + 1]
return small + 1
def q_sort(l: int, r: int):
if l >= r:
return nums
p = partition(l, r)
q_sort(l, p - 1)
q_sort(p, r)
return nums
q_sort(0, len(nums) - 1)
return "".join([str(x) for x in nums])
from typing import List
class Solution:
def largestNumber(self, nums: List[int]) -> str:
# 放一个快排搁着
def fast_sort(strs):
if len(strs) <= 1:
return strs
less, greater = [], []
p = strs.pop()
for i in strs:
if i + p < p + i:
less.append(i)
else:
greater.append(i)
return fast_sort(less) + [p] + fast_sort(greater)
strs = [str(num) for num in nums]
res = fast_sort(strs)
if res[0] == "0":
return "0"
return ''.join(res)
|
fa15fe01923ab0a9292aa47f6ed9cb085b0584e9 | huhudaya/leetcode- | /LeetCode/1200. 最小绝对差.py | 1,882 | 3.828125 | 4 | '''
给你个整数数组 arr,其中每个元素都 不相同。
请你找到所有具有最小绝对差的元素对,并且按升序的顺序返回。
示例 1:
输入:arr = [4,2,1,3]
输出:[[1,2],[2,3],[3,4]]
示例 2:
输入:arr = [1,3,6,10,15]
输出:[[1,3]]
示例 3:
输入:arr = [3,8,-10,23,19,-4,-14,27]
输出:[[-14,-10],[19,23],[23,27]]
提示:
2 <= arr.length <= 10^5
-10^6 <= arr[i] <= 10^6
'''
from typing import List
import sys
# 使用hash
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
# 使用hash
n = len(arr)
arr.sort()
hash = {}
min_diff = sys.maxsize
for i in range(n - 1):
diff = abs(arr[i] - arr[i + 1])
if diff not in hash:
hash[diff] = []
hash[diff].append([arr[i], arr[i + 1]])
min_diff = min(min_diff, diff)
return hash[min_diff]
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
mindiff = arr[1] - arr[0]
res = [[arr[0], arr[1]]]
for i in range(2, len(arr)):
curdiff = arr[i] - arr[i - 1]
if curdiff < mindiff:
res = [[arr[i - 1], arr[i]]]
mindiff = curdiff
elif curdiff == mindiff:
res.append([arr[i - 1], arr[i]])
return res
from collections import defaultdict
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
min_map = defaultdict(list)
arry_min_val = float("inf")
for i in range(len(arr) - 1):
min_val = abs(arr[i + 1] - arr[i])
arry_min_val = min(min_val, arry_min_val)
min_map[min_val].append([arr[i], arr[i + 1]])
return min_map[arry_min_val]
|
4b901a26128fa2ff67e3971ec306183b1b159ebf | huhudaya/leetcode- | /LeetCode/101. 对称二叉树.py | 4,076 | 3.890625 | 4 | '''
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
'''
'''
做递归思考三步:
递归的函数要干什么?
函数的作用是判断传入的两个树是否镜像。
输入:TreeNode left, TreeNode right
输出:是:true,不是:false
递归停止的条件是什么?
左节点和右节点都为空 -> 倒底了都长得一样 ->true
左节点为空的时候右节点不为空,或反之 -> 长得不一样-> false
左右节点值不相等 -> 长得不一样 -> false
从某层到下一层的关系是什么?
要想两棵树镜像,那么一棵树左边的左边要和二棵树右边的右边镜像,一棵树左边的右边要和二棵树右边的左边镜像
调用递归函数传入左左和右右
调用递归函数传入左右和右左
只有左左和右右镜像且左右和右左镜像的时候,我们才能说这两棵树是镜像的
调用递归函数,我们想知道它的左右孩子是否镜像,传入的值是root的左孩子和右孩子。这之前记得判个root==null。
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
# 递归
def check(left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
return left.val == right.val and check(left.left, right.right) and check(left.right, right.left, )
return check(root, root)
# 递归Java
'''
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
}
}
'''
# 迭代Java
'''
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode u, TreeNode v) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(u);
q.offer(v);
while (!q.isEmpty()) {
u = q.poll();
v = q.poll();
if (u == null && v == null) {
continue;
}
if ((u == null || v == null) || (u.val != v.val)) {
return false;
}
q.offer(u.left);
q.offer(v.right);
q.offer(u.right);
q.offer(v.left);
}
return true;
}
}
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
def dfs(left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
return left.val == right.val and dfs(left.right, right.left) and dfs(left.left, right.right)
return dfs(root.left, root.right)
# Java
'''
class Solution {
public boolean isSymmetric(TreeNode root) {
if (null == root) return true;
return helper(root.left, root.right);
}
private boolean helper(TreeNode left, TreeNode right){
if (null == left && null == right) return true;
if (null == left || null == right) return false;
return left.val == right.val && helper(left.left, right.right) && helper(left.right, right.left);
}
}
'''
|
def253879ce7208634a63076445b344ae983e547 | huhudaya/leetcode- | /LeetCode/445. 两数相加 II.py | 1,371 | 3.875 | 4 | '''
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。
将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
stack1 = []
stack2 = []
dummy = ListNode(-1)
#
def push_stack(p, stack):
while p:
stack.append(p.val)
p = p.next
push_stack(l1, stack1)
push_stack(l2, stack2)
# 记录进位
carry = 0
while stack1 or stack2 or carry:
tmp1, tmp2 = 0, 0
if stack1:
tmp1 = stack1.pop()
if stack2:
tmp2 = stack2.pop()
carry, mod = divmod(tmp1 + tmp2 + carry, 10)
# 头插法
new_node = ListNode(mod)
new_node.next = dummy.next
dummy.next = new_node
return dummy.next
|
12ac1e40db76d866ae6ce392be1291f44c9d4748 | huhudaya/leetcode- | /剑指offer/面试题06. 从尾到头打印链表.py | 1,155 | 3.71875 | 4 | '''
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
'''
# 递归&回溯
from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if head == None:
return []
res = []
self.helper(head, res)
return res
def helper(self, node, res):
if node is None:
return
# 应该先判断下一个结点是否为空,如果不为空,则递归调用,在回溯的时候,才添加到结果中
if node.next:
self.helper(node.next, res)
# 回溯时添加
res.append(node.val)
# 迭代&栈
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
p = head
stack = []
while p:
stack.append(p.val)
p = p.next
return stack[::-1]
|
a871052cb0a76ba2973b821eaf388d6eb969edb7 | huhudaya/leetcode- | /LeetCode/263. 丑数.py | 1,391 | 3.9375 | 4 | '''
编写一个程序判断给定的数是否为丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例 1:
输入: 6
输出: true
解释: 6 = 2 × 3
示例 2:
输入: 8
输出: true
解释: 8 = 2 × 2 × 2
示例 3:
输入: 14
输出: false
解释: 14 不是丑数,因为它包含了另外一个质因数 7。
说明:
1 是丑数。
输入不会超过 32 位有符号整数的范围: [−231, 231 − 1]。
通过次数37,727提交次数76,492
'''
'''
根据定义, 任何一个丑叔都可以写成 n = 2^i * 3^j * 5^k
(i,j,k都是幂,输入法不太方便写成指数,三个数都为0的时候,为丑数1的情况)
于是我们按照2,3,5 的顺序依次循环除,
当除到不是当前因数的倍数时,进行下一个因素的整数
这样,最后剩下的数为1则为丑数
'''
# 递归
class Solution:
def isUgly(self, num: int) -> bool:
if num == 0:
return False
if num == 1:
return True
if num % 2 == 0:
return self.isUgly(num // 2)
if num % 3 == 0:
return self.isUgly(num // 3)
if num % 5 == 0:
return self.isUgly(num // 5)
return False
# 迭代
class Solution:
def isUgly(self, num: int) -> bool:
for p in 2, 3, 5:
while num % p == 0 < num:
num //= p
return num == 1
|
ffdbd0d3408efb44a6b75cc3a038fa0fbc78bd85 | huhudaya/leetcode- | /LeetCode/121.买卖股票的最佳时机.py | 2,564 | 3.546875 | 4 | '''
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
'''
'''
如果反过来想,固定卖出时间 sell,向前穷举买入时间 buy,寻找 prices[buy] 最小的那天
是不是也能达到相同的效果?是的,而且这种思路可以减少一个 for 循环
'''
# 暴力法
'''
res = 0
for buy in range(len(price)):
for sell in range(buy + 1, len(price)):
res = max(res, price[sell] - price[buy])
return res
'''
import sys
from typing import List
class Solution:
def maxProfit1(self, prices: List[int]) -> int:
if not prices:
return 0
# 固定卖出的时间,用一个for循环,然后与卖出时间之前的最小值比较!
# 思想其实就是单调栈的思想
res = 0
cur_min = prices[0]
n = len(prices)
# 卖出时间必须从 1 开始,因为第一条肯定不能卖啊,还没买怎么卖
for i in range(1, n):
cur_min = min(cur_min, prices[i])
res = max(res, prices[i] - cur_min)
return res
# 状态转移动态规划
# https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484508&idx=1&sn=42cae6e7c5ccab1f156a83ea65b00b78&chksm=9bd7fa54aca07342d12ae149dac3dfa76dc42bcdd55df2c71e78f92dedbbcbdb36dec56ac13b&scene=21#wechat_redirect
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
# dp
n = len(prices)
# 我们这里特殊处理一下,dp[0][0],dp[0][1]表示base case即第0天
dp = [[0, 0] for i in range(n + 1)]
# dp[-1][1]无法表示,我们需要另外想办法解决这个case
# base case
dp[0][0] = 0
dp[0][1] = -sys.maxsize
for i in range(1, n + 1):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i - 1]) # 卖出,所以需要加
dp[i][1] = max(dp[i - 1][1], -prices[i - 1]) # 买入,所以需要减
return dp[n][0]
|
ff64f836ab3076c4dbf89494e50f92205ecdbd60 | huhudaya/leetcode- | /剑指offer/剑指 Offer 59 - I. 滑动窗口的最大值.py | 1,605 | 3.828125 | 4 | '''
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
提示:
你可以假设 k 总是有效的,在输入数组不为空的情况下,1 ≤ k ≤ 输入数组的大小。
注意:本题与主站 239 题相同:https://leetcode-cn.com/problems/sliding-window-maximum/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
from collections import deque
from typing import List
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# 单调队列
qMax = deque()
n = len(nums)
res = []
# i作为右指针(写指针)
for i in range(n):
while qMax and nums[qMax[-1]] <= nums[i]:
qMax.pop()
# 注意这里放的是下标
qMax.append(i)
# 判断队列的头部是否出队
if i >= k and qMax[0] == i - k:
qMax.popleft()
if i >= k - 1:
res.append(nums[qMax[0]])
return res |
8695f8eef8d0a52cc0c53b3d1a5ba2671663b3d6 | huhudaya/leetcode- | /LeetCode/227. 基本计算器 II.py | 3,242 | 4 | 4 | '''
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
示例 1:
输入: "3+2*2"
输出: 7
示例 2:
输入: " 3/2 "
输出: 1
示例 3:
输入: " 3+5 / 2 "
输出: 5
说明:
你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。
'''
'''
那么,为什么说处理括号没有看起来那么难呢,因为括号具有递归性质。我们拿字符串3*(4-5/2)-6举例:
calculate(3*(4-5/2)-6)
= 3 * calculate(4-5/2) - 6
= 3 * 2 - 6
= 0
可以脑补一下,无论多少层括号嵌套,通过 calculate 函数递归调用自己,都可以将括号中的算式化简成一个数字。换句话说,括号包含的算式,我们直接视为一个数字就行了。
现在的问题是,递归的开始条件和结束条件是什么?遇到(开始递归,遇到)结束递归:
'''
from typing import List
def calculate(s: str) -> int:
def helper(s: List) -> int:
stack = []
sign = '+'
num = 0
while len(s) > 0:
c = s.pop(0)
if c.isdigit():
num = 10 * num + int(c)
# 遇到左括号开始递归计算 num
if c == '(':
num = helper(s)
# 当c不是数字或者遍历到了尽头,就执行入栈的操作
if (not c.isdigit() and c != ' ') or len(s) == 0:
if sign == '+': ...
elif sign == '-': ...
elif sign == '*': ...
elif sign == '/': ...
num = 0
sign = c
# 遇到右括号返回递归结果
if c == ')':
break
return sum(stack)
return helper(list(s))
# 自己的版本,注意需要使用deque,否则自带的list的效率很低
from collections import deque
class Solution:
def calculate(self, s: str) -> int:
s = deque(s)
def helper(s) -> int:
stack = []
sign = "+"
num = 0
while len(s) > 0:
# 注意这里是pop(0)!!!!,pop最左边的数据
c = s.popleft()
if c.isdigit():
num = num * 10 + int(c)
# 当c不是数字或者遍历到了尽头,就执行入栈的操作,注意,这里必须是if,因为
if (not c.isdigit() and c != ' ') or len(s) == 0:
# 判断之前的sign标志位
if sign == "+":
stack.append(num)
elif sign == "-":
stack.append(-num)
# 如果遇见乘除法,需要弹出栈顶的元素先进行一次运算操作
elif sign == "*":
stack.append(stack.pop() * num)
# stack[-1] = stack[-1] * num
elif sign == "/":
stack[-1] = int(stack[-1] / float(num))
num = 0
sign = c
return sum(stack)
return helper(s)
print(Solution().calculate("14-3/2")) |
b41b72cd3745377db2e1c6368d835ace44d49a15 | huhudaya/leetcode- | /LeetCode/098. 验证二叉搜索树.py | 3,106 | 3.96875 | 4 | # 098. 验证二叉搜索树.py
'''
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 递归 中序遍历的方式
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
res = []
def helper(root):
if not root:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res == sorted(res) and len(set(res)) == len(res)
# 中序遍历迭代的方式 迭代
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack = []
p = root
pre = None
while p or stack:
while p:
stack.append(p)
p = p.left
p = stack.pop()
if pre and p.val <= pre.val:
return False
pre = p
p = p.right
return True
# 递归中序遍历+剪枝
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# 使用一个变量存储上一个值
self.pre = None
def dfs(root):
if root is None:
return True
# 中序遍历
if dfs(root.left) is False:
return False
# 这个时候是中序遍历!!
if self.pre and root.val <= self.pre.val:
return False
# 否则更新pre
self.pre = root
return dfs(root.right)
return dfs(root)
# 自己版本的递归
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# 递归
self.pre = None
def dfs(root):
if root is None:
return True
left = dfs(root.left)
if self.pre and root.val <= self.pre.val:
return False
self.pre = root
right = dfs(root.right)
return left and right
return dfs(root)
# 最大最小值
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def isBST(root, min_val, max_val):
if root == None:
return True
# print(root.val)
if root.val >= max_val or root.val <= min_val:
return False
return isBST(root.left, min_val, root.val) and isBST(root.right, root.val, max_val)
return isBST(root, float("-inf"), float("inf"))
|
d717960b2780b50a21f2ce7e1a586d08c2937f38 | huhudaya/leetcode- | /LeetCode/212. 单词搜索 II.py | 2,593 | 4.21875 | 4 | '''
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。
同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:
你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。
什么样的数据结构可以有效地执行这样的操作?
散列表是否可行?为什么? 前缀树如何?
如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。
'''
from typing import List
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
# trie树
root = {}
for word in words:
trie = root
for i in word:
trie = trie.setdefault(i, {})
trie["end"] = "1"
m = len(board)
n = len(board[0])
directions = [[-1, 0], [1, 0], [0, 1], [0, -1]]
marked = [[False] * n for i in range(m)]
res = []
def dfs(i, j, trie, path):
# 剪枝
if board[i][j] not in trie:
return
trie = trie[board[i][j]]
if "end" in trie and trie["end"] == "1":
res.append(path)
# 防止重复加入
trie["end"] = "0"
# 注意,这个marked不能在最上面使用,否则直接return了,就不能回溯了
marked[i][j] = True
for di in directions:
row = i + di[0]
col = j + di[1]
if not (row >= 0 and row < m and col >= 0 and col < n):
continue
if marked[row][col] is True:
continue
dfs(row, col, trie, path + board[row][col])
marked[i][j] = False
for i in range(m):
for j in range(n):
dfs(i, j, root, board[i][j])
return res
Solution().findWords([["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]],["oath","pea","eat","rain"]) |
3b7e11f98e9c3d65a5aacf43f3b2ca6bbb932d86 | aljohn0422/implementation-practices-in-python | /structure/hash_table.py | 788 | 3.578125 | 4 | class HashTable:
def __init__(self):
self.table = [[] for _ in range(8)]
def __len__(self):
return len(self.table)
def _hash(self, key):
return key % len(self)
def put(self, key: int, value: int):
k = self._hash(key)
for i in self.table[k]:
if i[0] == key:
i[1] = value
return
self.table[k].append([key, value])
def get(self, key):
k = self._hash(key)
for i in self.table[k]:
if i[0] == key:
return i[1]
return None
def resize(self, new_size):
old_table = self.table
self.table = [[] for _ in range(new_size)]
for i in old_table:
for j in i:
self.put(j[0], j[1])
|
be3762d1ea5c2b35419f3f5474966d03ac6fd935 | sdeck51/ECE440 | /socketlab/client.py | 491 | 3.5 | 4 | from socket import *
import sys
print
# Create a TCP/IP socket
client = socket(AF_INET, SOCK_STREAM)
#Connect the socket to the port on the server given by the caller
server_address = (sys.argv[1],((int)(sys.argv[2])))
client.connect(server_address)
target = "GET " + sys.argv[3]
print "Request: ",target
client.send(target)
indata = client.recv(1024)
if not indata:
quit()
print "From Server: ", indata
indata = client.recv(2048)
if not indata:
quit()
print "From Server: ", indata
|
c5d224a3d63d0d67bc7a48fecec156cca41cdcf7 | Lundgren/ud120-intro-ml | /datasets_questions/explore_enron_data.py | 2,138 | 3.578125 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import pickle
import math
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
def print_it():
for x in enron_data:
print (x)
for y in enron_data[x]:
print (y,':',enron_data[x][y])
#print_it()
print "persons:", len(enron_data)
print "features:", len(enron_data["SKILLING JEFFREY K"])
pois = 0
for n in enron_data:
if enron_data[n]["poi"] == 1:
pois = pois + 1
print "nbr of poi:", pois
print "stock value James Prentice:", enron_data["PRENTICE JAMES"]["total_stock_value"]
print "Wesley Colwell sent mail to pois:", enron_data["COLWELL WESLEY"]["from_this_person_to_poi"], "times"
print "Jeffrey K Skilling exercised stock:", enron_data["SKILLING JEFFREY K"]["exercised_stock_options"]
print "money for Lay:", enron_data["LAY KENNETH L"]["total_payments"], ", Skilling:", enron_data["SKILLING JEFFREY K"]["total_payments"], " & Fastow:", enron_data["FASTOW ANDREW S"]["total_payments"]
salary = 0
email = 0
for n in enron_data:
if not enron_data[n]["salary"] == "NaN":
salary = salary + 1
if not enron_data[n]["email_address"] == "NaN":
email = email + 1
print "nbr of salary:", salary, ", email: ", email
total_pay = 0
for n in enron_data:
if enron_data[n]["total_payments"] == "NaN":
total_pay = total_pay + 1
print "% not salary:", (total_pay * 100 / len(enron_data)), ", ", total_pay
total_pay_pois = 0
for n in enron_data:
if enron_data[n]["poi"] == 1:
if enron_data[n]["total_payments"] == "NaN":
total_pay_pois = total_pay_pois + 1
print "% not salary & poi:", (total_pay_pois * 100 / pois) |
85b9813120fefce2862cf92ee43f5918752dcef3 | shalinc/Facebook-Community-Detection-and-Link-Prediction | /FBCommunityDetectionAndLinkPrediction.py | 17,194 | 3.75 | 4 | # coding: utf-8
#
# In this assignment, we'll implement community detection and link prediction algorithms using Facebook "like" data.
# The file `edges.txt.gz` indicates like relationships between facebook users. This was collected using snowball sampling: beginning with the user "Bill Gates", I crawled all the people he "likes", then, for each newly discovered user, I crawled all the people they liked.
# We'll cluster the resulting graph into communities, as well as recommend friends for Bill Gates.
#
from collections import Counter, defaultdict, deque
import copy
import math
import networkx as nx
import urllib.request
## Community Detection
def bfs(graph, root, max_depth):
"""
Perform breadth-first search to compute the shortest paths from a root node to all
other nodes in the graph. To reduce running time, the max_depth parameter ends
the search after the specified depth.
E.g., if max_depth=2, only paths of length 2 or less will be considered.
This means that nodes greather than max_depth distance from the root will not
appear in the result.
Params:
graph.......A networkx Graph
root........The root node in the search graph (a string). We are computing
shortest paths from this node to all others.
max_depth...An integer representing the maximum depth to search.
Returns:
node2distances...dict from each node to the length of the shortest path from
the root node
node2num_paths...dict from each node to the number of shortest paths from the
root node that pass through this node.
node2parents.....dict from each node to the list of its parents in the search
tree
"""
###TODO
node2distance = defaultdict(int)
node2parent = defaultdict(list)
node2num_path = defaultdict(int)
visted_nodes = []
queue = deque()
#initially for root node
queue.append(root)
visted_nodes.append(root)
#print("Nodes in QUEUE", queue)
#finding the shortest path node2distance
while queue:
#pop from queue the node and visit its neighbors
#print("Nodes in QUEUE", queue)
parent = queue.popleft()
node_neighbors = sorted(graph.neighbors(parent))
for neighbor in node_neighbors:
#finding the shortest distances
if not neighbor in visted_nodes:
if (node2distance[parent]) < max_depth:
#mark the neighbor visted and add in queue
queue.append(neighbor)
visted_nodes.append(neighbor)
#print("Nodes in QUEUE", queue)
#Calculate the distance
node2distance[neighbor] = node2distance[parent] + 1
#finding the parents for the nodes node2parent
if (node2distance[parent]) < max_depth:
if node2distance[neighbor] == node2distance[parent] + 1:
#store the path
node2parent[neighbor].append(parent)
node2num_path[neighbor] += 1
node2num_path[root] = 1
# for node, depth in node2distance.items():
# if depth > 0:
# for node_parent, depth_parent in node2distance.items():
# if depth_parent == (depth - 1) and node in graph.neighbors(node_parent):
# node2parent[node].append(node_parent)
#finding the number of shortest path from root to nodes
# for node, parent in node2parent.items():
# node2num_path[node] = len(parent)
#print(sorted(node2distance.items()))
#print(sorted(node2parent.items()))
#print(sorted(node2num_path.items()))
return node2distance, node2num_path, node2parent
def bottom_up(root, node2distances, node2num_paths, node2parents):
"""
Compute the final step of the Girvan-Newman algorithm.
The third and final step is to calculate for each edge e the sum
over all nodes Y of the fraction of shortest paths from the root
X to Y that go through e.
Params:
root.............The root node in the search graph (a string). We are computing
shortest paths from this node to all others.
node2distances...dict from each node to the length of the shortest path from
the root node
node2num_paths...dict from each node to the number of shortest paths from the
root node that pass through this node.
node2parents.....dict from each node to the list of its parents in the search
tree
Returns:
A dict mapping edges to credit value. Each key is a tuple of two strings
representing an edge (e.g., ('A', 'B')).
"""
###TODO
temp_dict = defaultdict(int)
result = defaultdict(int)
for node, paths in sorted(node2num_paths.items()):
temp_dict[node] = 1/paths
#print(temp_dict.items())
#print(sorted(node2parents.items(),key=lambda x: x[1]))
for node, _ in sorted(node2distances.items(),key=lambda x: -x[1]):
parents = node2parents[node]
for parent in parents:
temp_dict[parent] += temp_dict[node]
#print("Parent =",parent,temp_dict[parent], " Child =",children, temp_dict[children])
#temp_parent,temp_children = parent, children
#sort_val = sorted([temp_parent,temp_children])
#result[(sort_val[0], sort_val[1])] = temp_dict[children]
#temp_val = temp_dict[node]
result[tuple(sorted([parent, node]))] = temp_dict[node]
#print(sorted(temp_dict.items()))
#print(sorted(result.items()))
return result
def approximate_betweenness(graph, max_depth):
"""
Compute the approximate betweenness of each edge, using max_depth to reduce
computation time in breadth-first search.
Params:
graph.......A networkx Graph
max_depth...An integer representing the maximum depth to search.
Returns:
A dict mapping edges to betweenness.
"""
###TODO
approx_betweenness = defaultdict(int)
for node in graph.nodes():
#print(node)
node2distances, node2num_paths, node2parents = bfs(graph, node, max_depth)
result = bottom_up(node, node2distances, node2num_paths, node2parents)
for pair, betweenness in result.items():
approx_betweenness[pair] += betweenness/2
#print(sorted(approx_betweenness.items()))
return approx_betweenness
def partition_girvan_newman(graph, max_depth):
"""
Used approximate_betweenness implementation to partition a graph.
Computed the approximate betweenness of all edges, and removed
them until multiple comonents are created.
Params:
graph.......A networkx Graph
max_depth...An integer representing the maximum depth to search.
Returns:
A list of networkx Graph objects, one per partition.
"""
###TODO
approx_betweeness = approximate_betweenness(graph,max_depth)
components = [val for val in nx.connected_component_subgraphs(graph)]
#print(list(components[0]))
#print(approx_betweeness)
#print("Components: ", len(components))
count_remove = 0
updatedGraph = graph.copy()
while len(components) == 1:
#print(list(component) for component in components)
edge_to_remove = sorted(approx_betweeness.items(),key= lambda x: (-x[1],x[0]))[count_remove][0]
#print(edge_to_remove)
#print("Edges: ",graph.number_of_edges())
updatedGraph.remove_edge(*edge_to_remove)
count_remove+=1
#print("Edges: ",graph.number_of_edges())
components = [val for val in nx.connected_component_subgraphs(updatedGraph)]
#print(list(components[0]))
# for component in components:
# print(list(component))
# #print(val)
return components
def get_subgraph(graph, min_degree):
"""
Return a subgraph containing nodes whose degree is
greater than or equal to min_degree.
We'll use this in the main method to prune the original graph.
Params:
graph........a networkx graph
min_degree...degree threshold
Returns:
a networkx graph, filtered as defined above.
"""
###TODO
"""Intially considering the entire graph as Subgraph,
then removing the nodes which don't satisfy min_degree criteria
"""
subgraph = graph.copy()
for node, degree in graph.degree().items():
if degree < min_degree:
subgraph.remove_node(node)
return subgraph
""""
Compute the normalized cut for each discovered cluster.
I've broken this down into the three next methods.
"""
def volume(nodes, graph):
"""
Compute the volume for a list of nodes, which
is the number of edges in `graph` with at least one end in
nodes.
Params:
nodes...a list of strings for the nodes to compute the volume of.
graph...a networkx graph
"""
###TODO
volume_calc = 0
for edge1, edge2 in graph.edges():
if (edge1 in nodes) or (edge2 in nodes):
volume_calc+=1
return volume_calc
def cut(S, T, graph):
"""
Compute the cut-set of the cut (S,T), which is
the set of edges that have one endpoint in S and
the other in T.
Params:
S.......set of nodes in first subset
T.......set of nodes in second subset
graph...networkx graph
Returns:
An int representing the cut-set.
"""
###TODO
cut_set = 0
for edge1, edge2 in graph.edges():
if ((edge1 in S) and (edge2 in T)) or ((edge1 in T) and (edge2 in S)):
cut_set += 1
return cut_set
def norm_cut(S, T, graph):
"""
The normalized cut value for the cut S/T.
Params:
S.......set of nodes in first subset
T.......set of nodes in second subset
graph...networkx graph
Returns:
An float representing the normalized cut value
"""
###TODO
#print("Volume",volume(S,graph),"Volume 2", volume(T,graph), "Cut",cut(S,T,graph),sep="\n")
norm_cut_calc = (cut(S, T,graph)/volume(S,graph)) + (cut(S,T,graph)/volume(T,graph))
return norm_cut_calc
def score_max_depths(graph, max_depths):
"""
In order to assess the quality of the approximate partitioning method
we've developed, we will run it with different values for max_depth
and see how it affects the norm_cut score of the resulting partitions.
Recall that smaller norm_cut scores correspond to better partitions.
Params:
graph........a networkx Graph
max_depths...a list of ints for the max_depth values to be passed
to calls to partition_girvan_newman
Returns:
A list of (int, float) tuples representing the max_depth and the
norm_cut value obtained by the partitions returned by
partition_girvan_newman. See Log.txt for an example.
"""
###TODO
norm_cuts = []
# plt.figure()
# nx.draw_networkx(graph)
# plt.show()
#original_graph = graph.copy()
for max_depth in max_depths:
components = partition_girvan_newman(graph, max_depth)
#print(len(components[0]), len(components[1]))
original_graph = graph.copy()
norm_cuts.append((max_depth,float(norm_cut(components[0],components[1],original_graph))))
return norm_cuts
## Link prediction
# Next, we'll consider the link prediction problem. In particular,
# we will remove 5 of the accounts that Bill Gates likes and
# compute our accuracy at recovering those links.
def make_training_graph(graph, test_node, n):
"""
To make a training graph, we need to remove n edges from the graph.
we'll assume there is a test_node for which we will
remove some edges. Remove the edges to the first n neighbors of
test_node, where the neighbors are sorted alphabetically.
Params:
graph.......a networkx Graph
test_node...a string representing one node in the graph whose
edges will be removed.
n...........the number of edges to remove.
Returns:
A *new* networkx Graph with n edges removed.
"""
###TODO
newGraph = graph.copy()
neighbors = sorted(newGraph.neighbors(test_node))[:n]
for neighbor in neighbors:
newGraph.remove_edge(test_node,neighbor)
return newGraph
def jaccard(graph, node, k):
"""
Compute the k highest scoring edges to add to this node based on
the Jaccard similarity measure.
Params:
graph....a networkx graph
node.....a node in the graph (a string) to recommend links for.
k........the number of links to recommend.
Returns:
A list of tuples in descending order of score representing the
recommended new edges. Ties are broken by
alphabetical order of the terminal node in the edge.
"""
###TODO
#train_graph = make_training_graph(graph,node,k)
all_neighbors = set(graph.neighbors(node))
scores = []
for n_node in graph.nodes():
#no edge exists and node is not similar to itself
if not graph.has_edge(node, n_node) and node!= n_node:
node_neighbors = set(graph.neighbors(n_node))
scores.append(((str(node),str(n_node)), 1. * len(all_neighbors & node_neighbors) / len(all_neighbors | node_neighbors)))
return sorted(scores, key=lambda x: (-x[1],x[0][1]))[0:k]
# One limitation of Jaccard is that it only has non-zero values for nodes two hops away.
#
# Implement a new link prediction function that computes the similarity between two nodes $x$ and $y$ as follows:
#
# $$
# s(x,y) = \beta^i n_{x,y,i}
# $$
#
# where
# - $\beta \in [0,1]$ is a user-provided parameter
# - $i$ is the length of the shortest path from $x$ to $y$
# - $n_{x,y,i}$ is the number of shortest paths between $x$ and $y$ with length $i$
def path_score(graph, root, k, beta):
"""
Compute a new link prediction scoring function based on the shortest
paths between two nodes.
Params:
graph....a networkx graph
root.....a node in the graph (a string) to recommend links for.
k........the number of links to recommend.
beta.....the beta parameter in the equation above.
Returns:
A list of tuples in descending order of score. Ties are broken by
alphabetical order of the terminal node in the edge.
"""
###TODO
node2distances, node2num_paths, node2parents = bfs(graph, root, math.inf)
return sorted([((root,node),(beta**node2distances[node]) * node2num_paths[node])
for node in graph.nodes() if not graph.has_edge(node, root) and node!= root], key=lambda x: (-x[1],x[0][1]))[:k]
def evaluate(predicted_edges, graph):
"""
Return the fraction of the predicted edges that exist in the graph.
Args:
predicted_edges...a list of edges (tuples) that are predicted to
exist in this graph
graph.............a networkx Graph
Returns:
The fraction of edges in predicted_edges that exist in the graph.
"""
###TODO
predict_right = 0
for predicted_edge in predicted_edges:
if graph.has_edge(*predicted_edge):
predict_right+=1
return predict_right/len(predicted_edges)
def read_graph():
""" Read 'edges.txt.gz' into a networkx **undirected** graph.
Returns:
A networkx undirected graph.
"""
return nx.read_edgelist('edges.txt.gz', delimiter='\t')
def main():
graph = read_graph()
print('graph has %d nodes and %d edges' %
(graph.order(), graph.number_of_edges()))
subgraph = get_subgraph(graph, 2)
print('subgraph has %d nodes and %d edges' %
(subgraph.order(), subgraph.number_of_edges()))
#MYCALLs
#a,b,c=bfs(example_graph(),'E',5)
#bottom_up('E',a,b,c)
#approximate_betweenness(example_graph(), 2)
#partition_girvan_newman(example_graph(), 5)
#volume(['A','B','C'], example_graph())
#norm_cut(['A', 'B', 'C'], ['D', 'E', 'F', 'G'],example_graph())
print('norm_cut scores by max_depth:')
print(score_max_depths(subgraph, range(1,5)))
clusters = partition_girvan_newman(subgraph, 3)
print('first partition: cluster 1 has %d nodes and cluster 2 has %d nodes' %
(clusters[0].order(), clusters[1].order()))
print('cluster 2 nodes:')
print(clusters[1].nodes())
test_node = 'Bill Gates'
train_graph = make_training_graph(subgraph, test_node, 5)
print('train_graph has %d nodes and %d edges' %
(train_graph.order(), train_graph.number_of_edges()))
jaccard_scores = jaccard(train_graph, test_node, 5)
print('\ntop jaccard scores for Bill Gates:')
print(jaccard_scores)
print('jaccard accuracy=%g' %
evaluate([x[0] for x in jaccard_scores], subgraph))
path_scores = path_score(train_graph, test_node, k=5, beta=.1)
print('\ntop path scores for Bill Gates for beta=.1:')
print(path_scores)
print('path accuracy for beta .1=%g' %
evaluate([x[0] for x in path_scores], subgraph))
if __name__ == '__main__':
main() |
97a8acae73ec9910ccb864c9d55e3af9812099b3 | ManskeTierling/crud_python_mysql | /programa.py | 535 | 3.84375 | 4 | from funcao import add, delete, read
while True:
print('======== BANCO DE DADOS ========')
nome = str(input('Nome: '))
sobrenome = str(input('Sobrenome: '))
cpf = input('CPF: ')
email = input('E-mail: ')
telefone = int(input('Telefone: '))
print('''======== OPÇÕES ========
1. Adicionar
2. Deletar
3. Ler''')
opcao = int(input('Opção: '))
if opcao == 1:
add(nome, sobrenome, cpf, email, telefone)
elif opcao == 2:
delete(cpf)
elif opcao == 3:
read(cpf)
|
7919a0df0d90864e041d2d0653f4979a42a7bdd5 | MaattiiP/basics-exe2-py | /ej-12-pr2.py | 677 | 3.59375 | 4 | #-*- coding: utf-8 -*-
"""
dominoInfinite: No recibe argumentos --> No devuelve valores
Pide al usuario ingresar la cantidad de fichas a generar
Imprime en pantalla las fichas
"""
def dominoInfinite ():
print ("Muestra en pantalla las fichas de domino")
cantFichas = int(input("Ingrese el número de las fichas: "))
domUp = 0
domDown = 0
for x in range (0, cantFichas + 1):
if domDown < domUp:
domUp = 0
domDown = domDown + 1
while domDown >= domUp:
print ("[" + str (domDown) + " | " + str(domUp) + "]", end = "\n")
domUp = domUp + 1
dominoInfinite()
|
4a79f1684dde29b3840959b65988c53ba523b03c | kchatr/sudoku-solver | /sudoku-solver.py | 4,529 | 4.03125 | 4 | '''
Representation of a traditional 9x9 sudoku board
A1 A2 A3| A4 A5 A6| A7 A8 A9
B1 B2 B3| B4 B5 B6| B7 B8 B9
C1 C2 C3| C4 C5 C6| C7 C8 C9
---------+---------+---------
D1 D2 D3| D4 D5 D6| D7 D8 D9
E1 E2 E3| E4 E5 E6| E7 E8 E9
F1 F2 F3| F4 F5 F6| F7 F8 F9
---------+---------+---------
G1 G2 G3| G4 G5 G6| G7 G8 G9
H1 H2 H3| H4 H5 H6| H7 H8 H9
I1 I2 I3| I4 I5 I6| I7 I8 I9
'''
digits = "123456789" #the possible digits that can go in every square
rows = "ABCDEFGHI" #the rows of the grid
colmns = digits #the columns of the grid
def cross_product(A,B):
'''
Returns the coordinate of a square
'''
return [a + b for a in A for b in B]
'''
Equivlalent to:
list = []
for a in rows:
for b in clmns:
list.append(a + b)
'''
squares = cross_product(rows, colmns) #generates all the squares from A1 to I9
list_of_units = ([cross_product(rows, c) for c in colmns] +
[cross_product(r, colmns) for r in rows] +
[cross_product(rws, cols) for rws in ("ABC", "DEF", "HGI") for cols in ("123", "456", "789")])
#shows all the units of a given square (rows, columns, and same box)
units = dict((s, [u for u in list_of_units if s in u]) for s in squares) #lists the units in a dictionary pairing with the square
peers = dict((s, set(sum(units[s],[])) - set([s])) for s in squares) #lists the peers of a square in a dictionary
def eliminate(values, sqr, dgt):
'''
Eliminates a digit(dgt) from the values of sqr (values[s]). When the values are <=2 this change is propagated.
'''
if dgt not in values[sqr]:
return values #other have already been eliminated
values[sqr] = values[sqr].replace(dgt, " ")
if len(values[sqr]) == 0:
return False #no values left - CONTRADICTION
elif len(values[sqr]) == 1:
d2 = values[sqr]
if not all(elimate(values, sqr2, dgt2) for sqr2 in peers[sqr]):
return False
for u in units[sqr]:
dplaces = [sqr for sqr in u if dgt in values[sqr]]
if len(dplaces) == 0:
return False
elif len(dplaces) == 1:
if not assign_values(values, dplaces[0], dgt):
return False
return values
def assign_values(values, sqr, dgts):
'''
sqr is the square we are assigning a digit (dgts) to. Dgts is the digit that will be assigned to square sqr.
All other values are eliminated from the dictionary holding the values for sqr, and this change is propagated.
'''
remaining_values = values[sqr].replace(dgts, " ")
if all(eliminate(values, sqr, dgts2) for dgts2 in remaining_values):
return values
else:
return False
def values(grid):
'''
Converts the grid to a dictionary of {Square: Char} with empty squares containing a value of 0.
'''
chars = [c for c in grid if c in digits or c in "0"]
assert len(chars) == 81 #raises assertion error if not 9x9 grid
return dict(zip(squares,chars))
def parse_grid(grid):
'''
Converts the grid to a dictionary mapping each square to a list of its possible values.
'''
square_values = dict((s, digits) for s in squares)
for s, d in values(grid).items():
if d in digits and not assign_values(square_values, s, d):
return False #if the digit d cannot be assigned to square s
return square_values
def display(values):
'''
Displays the sudoku grid with the given values
'''
width = max(len(values[s]) for s in squares) + 1
line = "+".join(["-" * (width * 3)] * 3)
for r in rows:
print("".join(values[r + c].center(width) + ("|" if c in "36" else "") for c in colmns))
if(r in "CF"):
print(line)
print()
def search(values):
'''
Using Depth-First Search (DFS) attempt to solve for every unit by starting with the
squares with the lowest possible values.
'''
if values is False:
return False
if all(len(values[s]) == 1 for s in squares):
return values #puzzle is solved
n, s = min((len(values[s]), s) for s in squares is len(values[s]) > 1)
return some(search(assign_values(values.copy()), s, d) for d in values[s])
def some(seq):
'''
Cheks if attempt solves puzzle
'''
for element in seq:
if element:
return element
return False
def solve_sudoku(grid):
'''
Solves the inputted sudoku puzzle.
'''
return search(parse_grid(grid))
|
287660ee7a1580903b9815b83106e8a5bd6e0c20 | 5folddesign/100daysofpython | /day_002/day_004/climbing_record_v4.py | 2,228 | 4.15625 | 4 | #python3
#climbing_record.py is a script to record the grades, and perceived rate of exertion during an indoor rock climbing session.
# I want this script to record: the number of the climb, wall type, grade of climb, perceived rate of exertion on my body, perceived rate of exertion on my heart, and the date and time of the climbing session. I then want all of this information to be added to a .csv file
import csv
#import the datetime library.
csvFile = open('/Users/laptop/github/100daysofpython/day_004/climbinglog.csv','a',newline='')
csvWriter = csv.writer(csvFile,delimiter=',',lineterminator='\n\n')
#add functions for each question.
climb_number =''
wall_type = ''
grade = ''
pre_heart = ''
pre_body = ''
def climbNumber():
global climb_number
climb_number = input("What number route is this? \n > ")
answer_string = str(climb_number)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
climbNumber()
def wallType():
global wall_type
wall_type = input("What type of wall was the route on? \n >")
if str.isalpha(wall_type):
pass
else:
print("You entered a number, you must enter a word. Try again. ")
wallType()
def grade():
global grade
grade = input("What was the grade of the route? \n >")
answer_string = str(grade)
if answer_string:
pass
else:
print("You must enter a number. Try again. ")
grade()
def preBody():
global pre_body
pre_body = input("On a scale of 1-10, how difficult did this route feel on your body? \n >")
answer_string = str(pre_body)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
preBody()
def preHeart():
global pre_heart
pre_heart = input("On a scale of 1-10, how difficult did this route feel on your heart? \n >")
answer_string = str(pre_heart)
if str.isnumeric(answer_string):
pass
else:
print("You must enter a number. Try again. ")
preHeart()
climbNumber()
wallType()
grade()
preBody()
preHeart()
csvWriter.writerow([climb_number,wall_type,grade,pre_body,pre_heart])
|
6367b485bbbeb065dc379fa1164072db6bac22e4 | risbudveru/machine-learning-deep-learning | /Machine Learning A-Z/Part 2 - Regression/Section 4 - Simple Linear Regression/Simple linear reg Created.py | 1,590 | 4.3125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
#X is matrix of independent variables
#Y is matrix of Dependent variables
#We predict Y on basis of X
dataset = pd.read_csv('Salary_data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
#Random_state = 0 indicates no randomized factors in algorithm
#Fitting Simple linear regression to Training set
from sklearn.linear_model import LinearRegression
#This class will help us to build models
regresor = LinearRegression() #Here we created a machine
regresor.fit(X_train, y_train) #Machine has learnt
#Now, We'll predict future values based on test set
#y_pred is predicted salary vector
y_pred = regresor.predict(X_test)
#Visualization of Trainning set data
plt.scatter(X_train, y_train, color='red') #Make scatter plot of real value
plt.plot(X_train, regresor.predict(X_train), color='blue') #Plot Predictions
plt.title('Salary vs Exprience(Training Set)')
plt.xlabel('Exprience(Years)')
plt.ylabel('Salary')
plt.show
#Visualization of Test set data
plt.scatter(X_test, y_test, color='red') #Make scatter plot of real value
plt.plot(X_train, regresor.predict(X_train), color='blue') #Plot Predictions
plt.title('Salary vs Exprience(Training Set)')
plt.xlabel('Exprience(Years)')
plt.ylabel('Salary')
plt.show
|
2af39a5f4a74ed28d2b963356e18cc9916f31b6c | Patrick-Akbar/cellular-automata-classification | /Grid.py | 7,249 | 3.875 | 4 | import pygame
#Grid object used to analyse and display the results of an automaton
class Grid:
def __init__(self, k, data):
#Input data is a nested list (technically a list of strings, but strings are lists of characters in Python, and the Grid object treats it like an ordinary list)
self.data = data
self.k = k
self.size = (len(data), len(data[0]))
#This generator produces all the colours that will be needed, which is dependent on the number of states
self.colours = [tuple([int(255 * (1-(i/(k-1)))) for j in range(3)]) for i in range(k)]
#__sub__ is a python magic method which is called whenever a Grid object is subtracted from another Grid object
def __sub__(self, other):
#Error handling - this isn't an issue in the main code since __sub__ is only used following get_background, but it could crop up if someone other program imports a Grid object
if self.size != other.size:
raise ValueError("Grid sizes do not match")
elif self.k != other.k:
raise ValueError("Grid colours do not match")
new_data = []
#We want to apply the second grid as a subtraction mask, so we simply subtract the value of each cell modulo k to get the new value
for i in range(self.size[0]):
self_row = self.data[i]
other_row = other.data[i]
new_row = ""
for j in range(self.size[1]):
new_row += str((int(self_row[j])-int(other_row[j]))%self.k)
new_data.append(new_row)
#Although this returns a new Grid, using -= to assign on subtraction also uses the __sub__ method
return Grid(self.k, new_data)
#__eq__ is another magic method to compare equality
def __eq__(self, other):
return (self.data == other.data)
def draw(self):
#Reverse size to get width then height, which is what pygame uses
image = pygame.Surface(self.size[::-1])
#Draw each cell as a one-pixel rectangle
for i in range(self.size[0]):
row = self.data[i]
for j in range(self.size[1]):
pygame.draw.rect(image, self.colours[int(row[j])], (j, i, 1, 1))
return(image)
#get_slice returns a grid containing the cells found within the requested rectangle
def get_slice(self, position, size):
x,y = position
w,h = size
slice_data = []
for i in range(h):
row = self.data[y+i]
slice_data.append(row[x:x+w])
return Grid(self.k, slice_data)
#get_background calculates the background pattern of the grid using the leftmost cells and returns a grid full of just that using the static method "regular"
def get_background(self):
bg_data = self.get_slice((0,0),(1, self.k*2)).data
initial_data = ""
pattern = ""
for i in range(0,self.k):
initial_data += (bg_data[i][0])
if not bg_data[self.k+i][0] in pattern:
pattern += bg_data[self.k+i][0]
return Grid.regular(self.k, initial_data, pattern, self.size)
#Returns the first cell found from each direction on the requested row
def find_edges(self, row_number):
#Use -1,-1 to represent no edges
edges = [-1,-1]
row = self.data[row_number]
#reverse_row is used to check from both directions simultaneously
reverse_row = row[::-1]
for i in range(len(row)):
if row[i] != "0" and edges[0] == -1:
edges[0] = i
if reverse_row[i] != "0" and edges[1] == -1:
edges[1] = i
if edges[0] != -1 and edges[1] != -1:
break
return tuple(edges)
#Finds the number of connected cells of the same state from a given point, up to a provided maximum
def fill(self, start_at, fill_cutoff):
#First get the state we are looking for, and add the first cell to cells_to_check
fill_colour = self.data[start_at[1]][start_at[0]]
cells_to_check = [start_at]
cells_in = []
cells_out = []
#The program performs a bredth-first search with additional constraints, as explained below
#cells_to_check is the list of cells to be explored, cells_in is the list of cells which have been explored,
#and cells_out is the list of cells which will never be added. By storing this we can save time on checking cells multiple times
while len(cells_to_check) != 0 and len(cells_in) < fill_cutoff: #cells_in is capped to avoid long wait times. This is accounted for in the main program
x,y = cells_to_check[0]
#Only directly adjacent cells are checked - no diagonals
next_cells = [(x+1,y), (x,y+1),(x-1,y),(x,y-1)]
for cell in next_cells:
#If we have already seen the cell in any capacity, skip it
if cell in cells_in + cells_out + cells_to_check:
continue
#If the cell is off the grid, skip it
if cell[0] >= self.size[1] or cell[0]<0 or cell[1] >= self.size[0] or cell[1] < 0:
continue
#If the cell is of the wrong state, skip it on all future runs
if self.data[cell[1]][cell[0]] != fill_colour:
cells_out.append(cell)
continue
else:
#We check to see if the cell has a same-state neighbour parallel to the direction we are checking in.
#This prevents the algorithm from following a long thin path, instead focusing on wide open spaces
#The exact check is different depending on if the x or y values of this cell match the ones of the cell currently being explored
if cell[0] != x:
if (cell[1] + 1 < self.size[0] and self.data[cell[1] + 1][cell[0]] == fill_colour) or (cell[1] - 1 >= 0 and self.data[cell[1] - 1][cell[0]] == fill_colour):
cells_to_check.append(cell)
elif cell[1] != y:
if (cell[0] + 1 < self.size[1] and self.data[cell[1]][cell[0] + 1] == fill_colour) or (cell[0] - 1 >= 0 and self.data[cell[1]][cell[0] - 1] == fill_colour):
cells_to_check.append(cell)
#We remove the cell currently being explored from cells_to_check and add it to cells_in
cells_in.append(cells_to_check.pop(0))
return (fill_colour, cells_in)
#Returns a Grid object which has uniform states on each step. The first few steps contain the states of initial_data, and every step after that is a loop of pattern
@staticmethod
def regular(k, initial_data, pattern, size):
l,w = size #l=length, w=width
if len(initial_data) > l:
raise ValueError("Initial data longer than length")
data = []
for c in initial_data:
data.append(c*w)
for i in range(l-len(initial_data)):
data.append(pattern[i%len(pattern)]*w)
return Grid(k, data)
|
9c82f1f5345319c662956dfdc74772e7500859eb | aishwaryaiyer22/Leetcode-Problems | /binary_tree/bin_tree_to_dll.py | 592 | 3.515625 | 4 | class Node :
def __init__(self, key):
self.left = null
self.right = null
self.key = key
def listify(Node root):
if root is None:
return (None, None)
(left_first, left_last) = listify(root.left)
(right_first, right_last) = listify(root.right)
first = last = root
if left_last:
left_last.right = root
root.left = left_last
first = left_first
if right_first:
right_first.left = root
root.right = right_first
last = right_last
return (first, last)
|
8e34c6ba21a8ee19cb1f3281ebdf704a9c729064 | gammay/nltk_building_blocks | /nltk_building_blocks/01_nltk_tokenize.py | 609 | 3.859375 | 4 | text = "Computers don't speak English. So, we've to learn C, C++, ,C#, Java, Python and the like! Yay!"
from nltk.tokenize import sent_tokenize
sentences = sent_tokenize(text)
print(len(sentences), 'sentence(s): ', sentences)
from nltk.tokenize import word_tokenize
words = word_tokenize(text)
print(len(words), 'word(s): ', words)
text = "I love nltk.org"
from nltk.tokenize import sent_tokenize
sentences = sent_tokenize(text)
print(len(sentences), 'sentence(s): ', sentences)
from nltk.tokenize import word_tokenize
words = word_tokenize(text)
print(len(words), 'word(s): ', words)
|
a336bcd22bf55b68efd3208717461f207984f6e3 | renan09/Assignments | /Python/PythonAssignments/Assign6/MainmathsNew.py | 657 | 4 | 4 | #6. Implement a child class called mathnew and
# parent classes as sqroot, addition, subtraction, multiplication and division.
# Use the super () function to inherit the parent methods.
from addition import addition
from multiplication import multiplication
from substraction import substraction
from division import division
from sqroot import sqroot
class mathsnew(addition,substraction,multiplication,division,sqroot):
def calValues(self):
super().findAddition(8,9)
super().findSubstraction(8,7)
super().findMultiply(9,9)
super().findDivision(9,9)
super().findSqroot(16)
math = mathsnew()
math.calValues() |
84c9145c5802f5f1b2c2e70b8e2038b573220bd5 | renan09/Assignments | /Python/PythonAssignments/Assign8/fibonacci2.py | 489 | 4.15625 | 4 | # A simple generator for Fibonacci Numbers
def fib(limit):
# Initialize first two Fibonacci Numbers
a, b = 0, 1
# One by one yield next Fibonacci Number
while a < limit:
yield a
#print("a : ",a)
a, b = b, a + b
#print("a,b :",a," : ",b)
# Create a generator object
x = fib(5)
# Iterating over the generator object using for
# in loop.
print("\nUsing for in loop")
for i in fib(55):
print("\t\t Series :",i) |
6bf37dd7d6c725e8f636d765e7a21f11695e5b86 | knimini/python-szkolenia | /tut2/zagadnienia.py | 1,448 | 3.671875 | 4 | 'generatory wyjatki list comperhensions klasy'
'''
List comperhension
'''
l = []
for i in range(5):
l.append(i**2)
l = [x**2 for x in range(5)]
zdanie = 'Chciałbym aby te zdanie było w uppercase'
nowe_zdanie = ''
for slowo in zdanie.split():
nowe_zdanie += slowo.upper() + ' '
nowe_zdanie = ' '.join(slowo.upper() for slowo in zdanie.split())
'''
stworzyć listę kolejnych potęg 2
'''
'''
Exceptions
'''
try:
10/0
except ZeroDivisionError:
print('Nie można dzielić przez 0')
def divide(a, b):
try:
print(a/b)
except TypeError as e:
print(e)
'''
input: [1, 2, 3]
output: [1, 3, 5]
input: [a, b, c]
output: ['', 'b', 'cc']
'''
def iterating_list(seq):
try:
return [int(item) + it for it, item in enumerate(seq)]
except ValueError:
return [item * it for it, item in enumerate(seq)]
'''
Generators
'''
def simple_gen(n):
for i in range(n):
yield i
my_gen = simple_gen(5)
print(next(my_gen))
for val in my_gen:
print(val)
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
'''
Classes
overide magic methods
inheritance
'''
class Vehicle:
def do_sound(self):
print(self.sound)
class Car(Vehicle):
sound = 'wrum wrum'
def __init__(self, color):
self.color = color
class Motorcycle(Vehicle):
sound = 'brum brum'
def __init__(self, color):
self.color = color
|
20aeb42d6e83f5d770210661e6b91687d8e5aceb | knimini/python-szkolenia | /tut2/live.py | 627 | 3.5 | 4 | from PIL import Image
im = Image.open('eye.jpg')
im.show()
img2 = im.copy()
width, height = img2.size
img3 = im.copy()
width2, height2 = img3.size
def change_pixels(width, height, img, fun):
for i in range(width):
for j in range(height):
val = img.getpixel((i,j))
new_val = fun(val)
img.putpixel((i, j), new_val)
def grey_px(px):
new_px = int(sum(px)/3)
return (new_px, new_px, new_px)
def inverted_px(px):
return tuple(map(lambda x: 255-x, px))
change_pixels(width, height, img2, grey_px)
change_pixels(width, height, img3, inverted_px)
img2.show()
img3.show()
|
7f5d6dfb709196cd256775f299bc97360c3cf742 | knimini/python-szkolenia | /tut1/dict_comprehensions.py | 248 | 3.84375 | 4 | # generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.
d=dict()
for i in range(1,21):
d[i]=i**2
for (k,v) in d.items():
print (v)
#
d = {k:k**2 for k in range(1,21)}
print(d)
|
92f047b095d3baca823813e530dfec6433708230 | HappySusan2016/blueberry-berry-development | /scripts/fix_scaff13.py | 999 | 3.78125 | 4 | """
Created on July 21, 2020
Author: Jiali
This script is used to flip the sequences
Usage: python fix_scaff13.py <input_fasta.fa> <int> <output.fasta>
"""
import argparse
parser=argparse.ArgumentParser(description="takes a location to break the sequences and flip the two parts")
parser.add_argument("-i", help="input fasta")
parser.add_argument("-loc", help="break location [integer]", type=int)
parser.add_argument("-o", help="output file")
args = parser.parse_args()
newfasta=open(args.o,'w')
from Bio.Seq import Seq
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
# read the fasta file and get the sequence
fasta = SeqIO.parse(open(args.i), "fasta")
for fasta_seq in fasta:
seq = fasta_seq.seq
first_part = seq[0:args.loc]
second_part = seq[args.loc:]
new_seq = second_part + first_part
# save the header and new sequences into a seq record
new_record = SeqRecord(seq = new_seq, id = fasta_seq.id, description="")
SeqIO.write(new_record, newfasta, "fasta") |
b54367b39a36de6fd5b12c82a2f0f056417af979 | Alopezm5/CORRECTO-2 | /.history/leccion_20210910224928.py | 430 | 3.78125 | 4 | from datetime import date
class Calculos:
def antiguedad(self,fecha):
hoy=date.today()
if hoy<fecha:
return -1
else:
anio=fecha.year
mes=fecha.month
dia=fecha.day
aa=0
while fecha<hoy:
aa=1
fecha=date(anio+aa,mes,dia)
return aa
cal = Calculos()
print(cal.antiguedad(date(1971, 6, 9)))
|
19f81e94e74490c234194513b23c2ed309501cc7 | BarbosaKO/trabalhos-da-faculdade | /4-Semestre/Complexidade_de_algoritmos/Lista_Exercicios/oDesafioDoMonge.py | 232 | 3.640625 | 4 | def func_Secreta(a):
if a == 0:
return 10
elif a == 1:
return 11
elif a == 2:
return 27
else:
return func_Secreta(a-2)-func_Secreta(a-3)
while True:
try:
print(func_Secreta(int(input())))
except:
break |
0d9361c9c0986457fc8746620131d8f0ba1d4bcd | sudhakumari2/dictionary | /question8dic.py | 295 | 3.859375 | 4 | # question number 8
students=[]
marks=[]
i=1
while i<=10:
student=input("enter sudent name")
students.append(student)
j=1
while j<=1:
num=int(input("enter marks"))
marks.append(num)
j+=1
i+=1
dictionary = dict(zip(students, marks))
print(dictionary)
|
79099101426b667a5e9ebb94cd6d845d14510d67 | leobalestra/pyhton-jogo-aprendendo-logica-fatec | /Jogo1.py | 1,579 | 3.5625 | 4 | # Leonardo Balestra
from random import randint
min = 0
max = 500
x = -5
N = []
qtd = 0
print("\n************************************************************************")
print("**** Jogo 1 - Aprendendo Lógica em Python - FATEC-SP - Prof. Banin ****")
print("************************************************************************")
print("************************************************************************")
print("***************** Descubra o número que estou pensando *****************")
print("************************************************************************")
while min > x or x > max:
x = int(input("\nDigite um número entre 0 e 500: "))
y = randint(min,max)
if x == y:
qtd = qtd + 1
N.append(x)
else:
while x != y:
if min <= x and x <= max:
if x > y:
qtd = qtd + 1
N.append(x)
print("O número é menor!")
x = int(input("Tente novamente (Seu número anterior foi %d): " %(x)))
else:
qtd = qtd + 1
N.append(x)
print("O número é maior!")
x = int(input("Tente novamente (Seu número anterior foi %d): " %(x)))
else:
print("O número deve estar entre %d e %d!" %(min,max))
x = int(input("Tente novamente (Seu número anterior foi %d): " %(x)))
qtd = qtd + 1
N.append(x)
print("\nParabéns!! O numero correto é %d!" %y)
print("\nHouve %d tentativas, foram elas:\n" %(qtd))
print(N)
|
f841df5254e7753090d9c4e6dfc96e931e35b4a4 | lovely7261/loop_question | /oil.py | 485 | 3.6875 | 4 | #i=1
#while(i<=5):
# print(i)
#i=i+1
# j=5
# while(j>=1):
# j=j-1
# print(j,end=" ")
#print()
#i=0
#while(i<6):
# i=i+1
# print(i," ")
#j=1
#hile(i<5):
#j=j-1
# print(j, end=" ")
# j=j+1
#print( )
#i=1
#while (i<=10):
#i=i*10
#print(i)
#num=int(input("enter the number"))
#while(num<10):
# num=num+1
#print(num)
i=1
while(i<5):
print(i)
i=i+1
j=5
while(j>=1):
print(j,end=" ")
j=j-1 |
4072264b3f46fcddd7e80a9fba54f1a2989d5832 | lovely7261/loop_question | /lovelypy/if-elis.py | 84 | 3.78125 | 4 | a=10
b=90
if a<b:
print("a is less then")
else:
print("b is less then ") |
329452b90db7dbd9bfe28cf736dd0ec7e450cfad | lovely7261/loop_question | /asciinumbers.py | 178 | 3.671875 | 4 | asciiNumber = 65
for i in range(0, 7):
for j in range(0, i + 2):
character = chr(asciiNumber)
print(character, end=' ')
asciiNumber +=1
print(" ") |
8fa278a0adcf19426d8b40a82aa53992b685341a | itssekhar/Pythonpractice | /oddandeven.py | 515 | 4.125 | 4 | num=int(input("enter a numer:"))
res=num%2
if(res>0):
print("odd number")
else:
print("even number")
""" Using function"""
def Number(n):
res=n%2
if res>0:
return "odd"
else:
return "even"
Number(2)
"""Using main function for to find an even and odd number """
def tofindoddoreven(n):
if n%2 == 0 :
print("even number")
elif n%2!=0:
print("odd number")
if __name__ == "__main__":
n = int(input("Enter n number:"))
tofindoddoreven(n) |
8d94d4003ca9643269ccdff48e8f8aa5d18b478c | JayRuiz/Python_example | /token_ex.py | 270 | 3.796875 | 4 |
input = 'Jay, Kim, 1971, 10, 17, male'
tokens = input.split(',')
firstName = tokens[0]
lastName = tokens[1]
birthDate = (int(tokens[2]), int(tokens[3]), int(tokens[4]))
isMale = (tokens[5] == 'male')
print 'Howday!', firstName, lastName
print 'Birthday', birthDate
|
ae0a94e2ffe6ca2cc64b67a4e0ec5c26d72beae0 | s3nt1n3lz21/myRaspberryPiProjects | /buttonMultiLED/ButtonLightWater.py | 4,231 | 3.84375 | 4 | ########################################################################
# Filename : ButtonLightWater.py
# Description : Button To Control Display Of A 10 LED Bar Graph
# Author : Neil Smith
# First Created : 14/07/2019
# Last Modification : 18/07/2019
########################################################################
import RPi.GPIO as GPIO
import time
class ButtonMultiLED:
#buttonPin = 7 # The pin of the button
#LEDPins = [0,1,2,3,4,5,6,8,9,10] # The pins of the LEDs
#multiLEDPin = 21 # The pin of the multiLED
#multiLEDState = 'off' # The state of the multiLED
#currentLEDPin = 0 # The pin of the LED currently on
#currentLEDNumber = 0 # The LED number that is currently on
#lastLEDChangeTime = datetime.datetime.now() # The time at which the LEDs last changed
#LEDDelayTime = 300 # The time to wait before turning on the next LED
#LEDDirection = 1 # Direction of LEDs. 1 for right, 0 for left.
def __init__(self, LEDDelayTime = 300, LEDDirection = 1):
print('Initialising...')
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
self.LEDDelayTime = LEDDelayTime
self.LEDDirection = LEDDirection
self.buttonPin = 4
self.LEDPins = [21,20,16,12,25,24,23,18,26,19]
self.multiLEDPin = 5
self.multiLEDState = 'off'
self.currentLEDNumber = 0
self.currentLEDPin = 21
for pin in self.LEDPins:
print(pin)
GPIO.setup(pin, GPIO.OUT) # Set the mode of all the LED pins to be outputs
GPIO.output(pin, GPIO.HIGH) # Turn all the LEDs off
GPIO.setup(self.buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set the mode of the button pin to be an input, and set it to be initially released
GPIO.setup(self.multiLEDPin, GPIO.OUT) # Set the mode of the multiLED pin to be an output
GPIO.output(self.multiLEDPin, GPIO.HIGH) # Turn off the multiLED
GPIO.add_event_detect(self.buttonPin,GPIO.BOTH,callback = self.buttonChanged,bouncetime=50) # Call the buttonChanged method on change of button state
def run(self):
self.lastLEDChangeTime = time.time()*1000
print('Starting the program...')
while(1):
#time.sleep(1)
rising = GPIO.input(self.buttonPin)
#print(rising)
if (self.multiLEDState == 'on'): # If the multiLED is on
if (self.timeToChangeLEDs() == True): # If its time to change the LEDs
self.changeLEDs() # Turn on the next LED
# Check whether its time to change the LEDs
def timeToChangeLEDs(self):
change = False
currentTime = time.time()*1000
if (currentTime > self.lastLEDChangeTime + self.LEDDelayTime):
change = True
return change
# Turn on the next LED
def changeLEDs(self):
self.lastLEDChangeTime = time.time()*1000
# Turn off the current LED
GPIO.output(self.currentLEDPin, GPIO.HIGH)
if (self.LEDDirection == 1): # If LEDs going right
# If another LED to the right
if (self.currentLEDNumber < len(self.LEDPins) - 1):
self.currentLEDNumber = self.currentLEDNumber + 1
self.currentLEDPin = self.LEDPins[self.currentLEDNumber]
GPIO.output(self.currentLEDPin, GPIO.LOW)
# No more LEDs to the right, set the leftmost to on
else:
self.currentLEDNumber = 0;
self.currentLEDPin = self.LEDPins[self.currentLEDNumber]
GPIO.output(self.currentLEDPin, GPIO.LOW)
# Turn the nth LED on
def ledOn(self,n):
GPIO.output(n, GPIO.LOW)
# Turn the nth LED off
def ledOff(self,n):
GPIO.output(n, GPIO.HIGH)
# Turn on/off the multiLED based on button state
def buttonChanged(self,_):
print('Button has changed!')
rising = GPIO.input(self.buttonPin)
if rising:
self.buttonPressed()
else:
self.buttonReleased()
# When the button is released, turn off the multiLED
def buttonReleased(self):
self.multiLEDState = 'off'
GPIO.output(self.multiLEDPin, GPIO.LOW)
print('MultiLED turned off!')
# When the button is pressed, turn on the multiLED
def buttonPressed(self):
self.multiLEDState = 'on'
GPIO.output(self.multiLEDPin, GPIO.HIGH)
print('MultiLED turned on!')
# Turn off all the LEDs and release resources
def destroy(self):
for pin in ledPins:
GPIO.output(pin, GPIO.HIGH)
GPIO.cleanup()
if __name__ == "__main__":
myClass = ButtonMultiLED(300, 1)
try:
myClass.run()
except KeyboardInterrupt:
myClass.destroy()
|
7559742af5047e836ba22d3c8f6717aa7e9308c0 | zaego123/onedrive-public | /py_learn/def_gerator/def_genrator.py | 5,591 | 3.875 | 4 | 通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。
我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢?
如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值:
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
我们讲过,generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。
当然,上面这种不断调用next(g)实在是太变态了,正确的方法是使用for循环,因为generator也是可迭代对象:
>>> g = (x * x for x in range(10))
>>> for n in g:
... print(n)
...
0
1
4
9
16
25
36
49
64
81
所以,我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。
generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。
比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
注意,赋值语句:
a, b = b, a + b
相当于:
t = (b, a + b) # t是一个tuple
a = t[0]
b = t[1]
但不必显式写出临时变量t就可以赋值。
上面的函数可以输出斐波那契数列的前N个数:
>>> fib(6)
1
1
2
3
5
8
'done'
仔细观察,可以看出,fib函数实际上是定义了斐波拉契数列的推算规则,可以从第一个元素开始,推算出后续任意的元素,这种逻辑其实非常类似generator。
也就是说,上面的函数和generator仅一步之遥。要把fib函数变成generator,只需要把print(b)改为yield b就可以了:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
这就是定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:
>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>
这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
举个简单的例子,定义一个generator,依次返回数字1,3,5:
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值:
>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
可以看到,odd不是普通函数,而是generator,在执行过程中,遇到yield就中断,下次又继续执行。执行3次yield后,已经没有yield可以执行了,所以,第4次调用next(o)就报错。
回到fib的例子,我们在循环过程中不断调用yield,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。
同样的,把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代:
>>> for n in fib(6):
... print(n)
...
1
1
2
3
5
8
但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:
>>> g = fib(6)
>>> while True:
... try:
... x = next(g)
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e.value)
... break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done
关于如何捕获错误,后面的错误处理还会详细讲解。
|
b81c2a8c1f52ea5077b70a41950bba9e5282a400 | zaego123/onedrive-public | /py_learn/slice-iter-etc.py | 2,884 | 3.90625 | 4 | #slice切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[0,3]
#记住倒数第一个元素的索引是-1。
前10个数,每两个取一个:
>>> L[:10:2]
[0, 2, 4, 6, 8]
所有数,每5个取一个:
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
字符串'xxx'也可以看成是一种list,每个元素就是一个字符。
#迭代
只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
b
c
只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
c
b
如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
#列表生成式
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
还可以使用两层循环,可以生成全排列:
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现:
>>> import os # 导入os模块,模块的概念后面讲到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']
for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
... print(k, '=', v)
...
y = B
x = A
z = C
因此,列表生成式也可以使用两个变量来生成list:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
>>> [i*j for i,j in l.items()]
[6, 20]
最后把一个list中所有的字符串变成小写:(using function)
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
|
8c8bdde3a57ec94e2ae2ce4d52366a95be422ea0 | sasschaps/learning | /python/random.py | 176 | 3.6875 | 4 | def bob():
print "Hello Sarah"
print "Hello Sarah"
print "Hello Sarah"
def sum(a, b):
c = 23
if c > b:
return c - 100
else:
return a + b
bob()
print sum(13, 107)
|
be1a6beb03d6f54c3f3d42882c84031cd415dc83 | shaversj/100-days-of-code-r2 | /days/27/longest-lines-py/longest_lines.py | 675 | 4.25 | 4 | def find_longest_lines(file):
# Write a program which reads a file and prints to stdout the specified number of the longest lines
# that are sorted based on their length in descending order.
results = []
num_of_results = 0
with open(file) as f:
num_of_results = int(f.readline())
for line in f.readlines():
line = line.strip()
results.append([line, len(line)])
sorted_results = sorted(results, reverse=True, key=lambda x: x[1])
for num in range(0, num_of_results):
print(sorted_results[num][0])
find_longest_lines("input_file.txt")
# 2
# Hello World
# CodeEval
# Quick Fox
# A
# San Francisco
|
049c5f71fc8d8203517c0e7991288da1662c134f | shaversj/100-days-of-code-r2 | /days/30/flavius-josephus/flavius-josephus-py.py | 1,058 | 3.953125 | 4 | def flavius_josephus(num_of_people, nth_person):
people = create_list_of_people(num_of_people)
# https://stackoverflow.com/questions/12444979/josephus-problem-using-list-in-python
nth_person -= 1 # pop automatically skips the dead guy
idx = nth_person
while len(people) > 1:
print(people.pop(idx)) # kill prisoner at idx
idx = (idx + nth_person) % len(people)
print('survivor: ', people[0])
def josephus(num_of_people, nth_person):
from collections import deque
# https://stackoverflow.com/questions/12444979/josephus-problem-using-list-in-python
list_of_people = create_list_of_people(num_of_people)
people = deque(list_of_people)
deaths = []
while len(people) > 0:
people.rotate(-nth_person)
deaths.append(people.pop())
return " ".join(str(death) for death in deaths)
def create_list_of_people(num):
list_of_people = []
for number in range(0, num):
list_of_people.append(number)
return list_of_people
#flavius_josephus(5, 2)
josephus(5, 2)
|
f99e68cfa634143883bfce882bc3b399bf1f1fcf | shaversj/100-days-of-code-r2 | /days/08/llist-py/llist.py | 862 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
new_node = Node(data)
node = self.head
# Get to the last node
previous = None
while node is not None:
node = node.next
if node is None:
previous.next = new_node
previous = node
def print_list(self):
node = self.head
while node:
print(f"{node.data} ->", end=" ")
node = node.next
print("None")
ll = LinkedList()
first_node = Node("A")
second_node = Node("B")
third_node = Node("C")
first_node.next = second_node
second_node.next = third_node
ll.head = first_node
ll.print_list()
ll.add("D")
ll.add("E")
ll.print_list()
|
96d5b125384cd37755b0025d9699bd6b656b601c | shaversj/100-days-of-code-r2 | /days/39/rotation-py/solution.py | 760 | 3.875 | 4 | def is_rotation(word, rotated_word):
from collections import deque
d = deque(word)
count = 0
while count != len(word):
d.rotate(1)
print(d)
if "".join(d) == rotated_word:
return True
else:
count += 1
return False
# print(is_rotation("Hello", "lloHe"))
# print(is_rotation("Basefont", "tBasefon"))
def rotate_left(data, k):
# [10, 20, 30]
# rotate to the right by 1: [20, 30, 10]
l = len(data)
for i in range(0, k):
temp = data[0]
print(i)
for num in range(0, l - 1):
#print(num)
data[num] = data[num + 1]
print(data)
data[l - 1] = temp
return data
print(rotate_left([10, 20, 30], 1))
|
f09add834a1e9f6dcc740d80a079c249d3e9cde4 | DiwakarBasnet/OpenCV | /Vehicles and Pedestrians/detect_in_image.py | 1,069 | 3.6875 | 4 | import cv2
# create opencv image
img = cv2.imread('highway.png')
#img = cv2.imread('pedestrian.jpg')
# Pre-trained classifier
car_tracker_file = 'cars.xml'
pedestrian_tracker_file = 'full_body.xml'
# create classifier
car_tracker = cv2.CascadeClassifier(car_tracker_file)
pedestrian_tracker = cv2.CascadeClassifier(pedestrian_tracker_file)
# Convert to grayscale
black_n_white = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#Detect cars and pedestrians
cars = car_tracker.detectMultiScale(black_n_white)
pedestrians = pedestrian_tracker.detectMultiScale(black_n_white)
# Draw rectangles around the cars
for (x, y, w, h) in cars:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
# Draw rectangles around the pedestrians
for (x, y, w, h) in pedestrians:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 255), 2)
# Display the image with the cars and pedestrians spotted
cv2.imshow('Car and Pedestrians detector', img)
# Image is shown until a key is pressed
cv2.waitKey() |
97c33a577ecada5c7ed5d493230f6fbed1b16c85 | GR-python/solved-problems | /askisi5.py | 1,577 | 3.703125 | 4 | """
Να γραφεί πρόγραμμα, το οποίο διαβάζει από το πληκτρολόγιο Π
μονοψήφιους θετικούς ακεραίους αριθμούς και εκτυπώνει τους αριθμούς και το πλήθος εμφάνισής τους
κατά αύξουσα σειρά πλήθους εμφανίσεων (όπου Π τα 2 τελευταία ψηφία του ΑΜ σας).
"""
def repetition(p):
a=[0,1,2,3,4,5,6,7,8,9]
b=[0]*10
while sum(b)<p:
try:
num=int(input('Dose arithmo apo 0-9 : '))
if num in a:
b[a.index(num)]+=1
else:
print('Ο αριθμός πρέπει να είναι μεταξύ 0-9')
except:
pass
for i in sorted(zip(a,b), key=lambda item:item[1]):
print(i)
"""
Να γραφεί πρόγραμμα, το οποίο διαβάζει από το πληκτρολόγιο ακεραίους αριθμούς
και εκτυπώνει τους αριθμούς και το πλήθος εμφάνισής τους
κατά φθίνουσα σειρά πλήθους εμφανίσεων.
"""
def repetition2():
a=[]
b=[]
while True:
try:
num=int(input('Δώσε τον {}ο ακέραιο (-1 για έξοδο): '.format(sum(b)+1)))
if num==-1:
break
if num in a:
b[a.index(num)]+=1
else:
a.append(num)
b.append(0)
b[a.index(num)]+=1
except:
pass
c=list(zip(a,b))
for i in sorted(c, key=lambda item:item[1], reverse=True):
print(i)
|
949df4a00dae19b12ba6a155c341e4082d162129 | wslxko/LeetCode | /hot100/number2.py | 1,064 | 3.78125 | 4 | '''
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def findDisappearedNumbers(self, nums):
new_nums = []
end_nums = []
for num in range(len(nums)):
new_nums.append(num+1)
for i in new_nums:
if i not in nums:
end_nums.append(i)
return end_nums
if __name__ == '__main__':
s = [4, 3, 2, 7, 8, 2, 3, 1]
a = Solution()
print(a.findDisappearedNumbers(s))
|
1b674c9fc4380e20bd33d2e1d67cafbb3560e85a | wslxko/LeetCode | /tencentSelect/number30在排序数组中查找元素的第一个和最后一个位置.py | 1,260 | 3.796875 | 4 | '''
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def searchRange(self, nums, target):
copyNums = nums.copy()
result = []
if target in copyNums:
for i in copyNums:
if i == target:
index = copyNums.index(target)
result.append(index)
copyNums[index] = 'z'
if len(result) == 2:
return result
else:
del result[1:-1]
return result
return [-1, -1]
if __name__ == "__main__":
a = Solution()
nums = [5, 9, 7, 8, 8, 10]
print(a.searchRange(nums, 8))
|
891c3407ec43e164c92155019f8ca7de69b8f687 | wslxko/LeetCode | /tencentSelect/number28下一个排列.py | 1,052 | 3.828125 | 4 | '''
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-permutation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
import itertools
class Solution:
def nextPermutation(self, nums):
nums = tuple(nums)
allNums = sorted(list(set(itertools.permutations(nums, 3))), reverse=False)
index = allNums.index(nums)
if index != len(allNums) - 1:
return allNums[index + 1]
return allNums[0]
if __name__ == "__main__":
a = Solution()
nums = [3,2,1]
print(a.nextPermutation(nums))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.