text
stringlengths 37
1.41M
|
---|
from header import *
#the flow of this algorithm is designed as follow:
#1.prepare the Bell state
#2.implement the algorithm according to Nielsen and L.Chuang
def teleportation():
c = Circuit(True)
#store the unknow quantum state, the aim of this algorithm is teleporting the state of AliceQ to BobQ
AliceQ = Qubit()
#the two qubit is entanglement with each other
AliceQ2 = Qubit()
BobQ = Qubit()
H(AliceQ2)
CNOT(AliceQ2,BobQ)
CNOT(AliceQ,AliceQ2)
H(AliceQ)
CNOT(AliceQ2,BobQ)
#######Control-Z#########
H(BobQ)
CNOT(AliceQ,BobQ)
H(BobQ)
#########################
BobQ = M(BobQ)
c.execute(1024) |
from tkinter import *
root = Tk()
root.title("Tic Tac Toe - Two Player Game")
player=True
status=None
count=0
class TicTacToe:
def __init__(self,master):
frame=Frame(master)
menu1 = Menu(root)
root.config(menu=menu1)
subMenu = Menu(menu1)
menu1.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New... ", command=self.refreshWindow)
subMenu.add_separator()
subMenu.add_command(label="Exit...", command=root.quit)
self.B1 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B1))
self.B2 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B2))
self.B3 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B3))
self.B4 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B4))
self.B5 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B5))
self.B6 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B6))
self.B7 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B7))
self.B8 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B8))
self.B9 = Button(frame, width=10, height=5, bg="white", command= lambda: self.swapturn(self.B9))
self.B1.grid(row=0, column=0)
self.B2.grid(row=0, column=1)
self.B3.grid(row=0, column=2)
self.B4.grid(row=1, column=0)
self.B5.grid(row=1, column=1)
self.B6.grid(row=1, column=2)
self.B7.grid(row=2, column=0)
self.B8.grid(row=2, column=1)
self.B9.grid(row=2, column=2)
frame.pack()
def swapturn(self,b):
global player
global status
global count
if (player):
statusBar['text'] = "TURN: Player 2 "
count += 1
player = False
b.config(text="X", state=DISABLED, bg="yellow")
else:
statusBar['text'] = "TURN: Player 1 "
count += 1
player = True
b.config(text="O", state=DISABLED, bg="cyan")
if (self.B1['text'] == self.B2['text'] == self.B3['text'] == "X" or self.B4['text'] == self.B5['text'] == self.B6['text'] == "X" or self.B7[
'text'] ==
self.B8['text'] == self.B9['text'] == "X" or
self.B1['text'] == self.B4['text'] == self.B7['text'] == "X" or self.B2['text'] == self.B5['text'] == self.B8['text'] == "X" or self.B3[
'text'] == self.B6['text'] == self.B9['text'] == "X" or
self.B1['text'] == self.B5['text'] == self.B9['text'] == "X" or self.B3['text'] == self.B5['text'] == self.B7['text'] == "X"):
status = "win"
statusBar['text'] = "Player 1 Won..."
statusBar['bg'] = "lightgreen"
print("player one is wiinner")
if (self.B1['text'] == self.B2['text'] == self.B3['text'] == "O" or self.B4['text'] == self.B5['text'] == self.B6['text'] == "O" or self.B7[
'text'] ==
self.B8['text'] == self.B9['text'] == "O" or
self.B1['text'] == self.B4['text'] == self.B7['text'] == "O" or self.B2['text'] == self.B5['text'] == self.B8['text'] == "O" or self.B3[
'text'] == self.B6['text'] == self.B9['text'] == "O" or
self.B1['text'] == self.B5['text'] == self.B9['text'] == "O" or self.B3['text'] == self.B5['text'] == self.B7['text'] == "O"):
print("player two is wiinner")
statusBar['text'] = "Player 2 Won..."
statusBar['bg'] = "lightgreen"
status = "win"
if (status == "win"):
self.B1['state'] = self.B2['state'] = self.B3['state'] = self.B4['state'] = self.B5['state'] = self.B6['state'] = self.B7['state'] = self.B8[
'state'] = self.B9['state'] = DISABLED
return
if (count == 9):
print("game Draw...")
statusBar['text'] = "Game Draw...."
statusBar['bg']="orange"
def refreshWindow(self):
self.B1.config(text="", state=NORMAL, bg="white")
self.B2.config(text="", state=NORMAL, bg="white")
self.B3.config(text="", state=NORMAL, bg="white")
self.B4.config(text="", state=NORMAL, bg="white")
self.B5.config(text="", state=NORMAL, bg="white")
self.B6.config(text="", state=NORMAL, bg="white")
self.B7.config(text="", state=NORMAL, bg="white")
self.B8.config(text="", state=NORMAL, bg="white")
self.B9.config(text="", state=NORMAL, bg="white")
global status
global player
global count
player=True
status=None
count=0
statusBar['text']="TURN: Player 1"
statusBar['bg']="white"
statusBar = Label(root, text="TURN: Player 1", bd=1, height=5, relief=SUNKEN, anchor=W)
statusBar.pack(side=BOTTOM, fill=X)
obj = TicTacToe(root)
root.mainloop() |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
class AVL:
def getHeight(self, root):
if not root:
return 0
return root.height
def insert(self, root, key):
# Step 1 - Perform normal BST
if not root:
return TreeNode(key)
elif key < root.val:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
return root
def preorder(self, root):
if root:
print(root.val)
self.preorder(root.left)
self.preorder(root.right)
obj = AVL()
root = None
root = obj.insert(root, 1)
root = obj.insert(root, 2)
root = obj.insert(root, 3)
(obj.preorder(root)) |
#These are the enemy classes (includes boss)
from random import randrange
class enemy:
#creates enemy character
def __init__(self):
self.hpp = 35
self.aep = 15
self.mapp = 3.0
self.rapp = 1.0
self.lp = 1
#allows access to and setting of enemy's stats
def getHP(self):
return int(self.hpp)
def setHP(self, x):
self.hpp = self.hpp + x
return self.hpp
def getAE(self):
return int(self.aep)
def setAE(self, x):
self.aep = self.aep + x
return self.aep
def getMelee(self):
return self.mapp
def getRange(self):
return self.rapp
def getLuck(self):
return self.lp
def attacked(self):
#If the enemy is attacked, the enemy's hit points decrease
self.hpp = self.hpp - randrange(1,8)
return print(self.hpp)
def edied(self):
#If the enemy's hit points = 0, the enemy is dead
if self.hpp <= 0:
return True
class boss:
def __init__(self):
self.hpp = 120
self.aep = 20
self.mapp = 5.0
self.rapp = 2.0
self.lp = 2.0
#allows access to and setting of boss's stats
def getHP(self):
return int(self.hpp)
def setHP(self, x):
self.hpp = self.hpp + x
return self.hpp
def getAE(self):
return int(self.aep)
def setAE(self, x):
self.aep = self.aep + x
return self.aep
def getMelee(self):
return self.mapp
def getRange(self):
return self.rapp
def getLuck(self):
return self.lp
def attacked(self):
#If the enemy is attacked, the enemy's hit points decrease
self.hpp = self.hpp - randrange(1,11)
return print(self.hpp)
def edied(self):
#If the enemy's hit points = 0, the enemy is dead
if self.hpp <= 0:
return True
|
from random import randint, shuffle
from munkres import Munkres, print_matrix
# mentors: [a,b,c,d]
# mentees: [z,q,w,y]
# votes: [mentorId,mentorId,mentorId,mentorId,mentorId] <<< per mentee
nMentee = i = 20
nMentor = nMentee
maxSelectedMentors = 3
matrix = []
while i > -1:
i -= 1
entry = [1, 2, 3]
if nMentor > maxSelectedMentors:
rand = [5] * (nMentor - maxSelectedMentors)
entry.extend(rand)
shuffle(entry)
print(f'Current mentee entry: {entry}')
matrix.append(entry)
# matrix = [[1,4,5,2,5, 5, 1, 2], # this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# #1,4,5,2, this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# #1,4,5,2, this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [5, 5, 1, 21,4,5,2,], # this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# #1,4,5,2, this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# #1,4,5,2, this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [5, 5, 1, 21,4,5,2,], # this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# #1,4,5,2, this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2],
# #1,4,5,2, this means mentee#1 selected c and d. fill the rest of the set with 5 for other possible mentors. this makes our matrix nx4
# [1,4,5,2,5, 5, 1, 2],
# [1,4,5,2,5, 5, 1, 2]
# ]
print(matrix)
def calc(input_matrix):
m = Munkres()
indexes = m.compute(input_matrix)
print_matrix(input_matrix, msg='Lowest cost through this matrix:')
total = 0
print_matrix(indexes, msg='indexes:')
for row, column in indexes:
value = input_matrix[row][column]
total += value
print(f'({row}, {column}) -> {value}')
print(f'total cost: {total}')
return indexes
def diff(in1, in2):
# found = in1[in2[:, 1], :]
diff = remove_keys(in1, in2[:, 1])
print("found for:")
print(matrix)
# print(found)
def remove_keys(d, keys):
to_remove = set(keys)
filtered_keys = d.keys() - to_remove
filtered_values = map(d.get, filtered_keys)
return dict(zip(filtered_keys, filtered_values))
k = 1
while k > 0:
current_matrix = matrix[k, :]
result = calc(matrix)
diff(matrix, result)
|
import math
from fractions import Fraction
import itertools
def next(top,root,plus):
newbottom = root-plus**2
if newbottom%top==0:
newbottom,top = newbottom/top,1
else:
print "wtf!"
plusser = int(float(top)*(math.sqrt(root) -plus)/newbottom)
return (plusser,(newbottom,root,-plus-plusser*newbottom))
def rootseq(n):
first = int(math.sqrt(n))
yield first
seqtuple = (1,n,-first)
while 1:
nextres,seqtuple = next(*seqtuple)
yield nextres
def fracseq(seq,times):
total = Fraction(seq.next())
if times>1:
return total + Fraction(1,fracseq(seq,times-1))
return total
def lowestx(d):
i = 1
while 1:
frac = rootconverge(d,i)
x,y=frac.numerator,frac.denominator
if x**2 - d*(y**2) == 1:
return x
i+=1
def rootconverge(root,n):
return fracseq(rootseq(root),n)
def isroot(n):
root = n**(1.0/2)
return abs(root-int(root))<.0000001
highest = 0
highd = 0
for i in range(2,1001):
if not isroot(i):
res = lowestx(i)
if res>highest:
highest = res
highd = i
print highd,highest
|
def split_into_2(array):
length = len(array)
result = []
flag = False
if length % 2 != 0:
last_array = [array.pop()]
flag = True
i = 0
while i < length - 1:
if array[i] < array[i + 1]:
result.append([array[i], array[i + 1]])
else:
result.append([array[i + 1], array[i]])
i += 2
if flag:
result.append(last_array)
return result
def merge_sort(array1, array2):
index1, index2 = 0, 0
result_array = []
length1, length2 = len(array1), len(array2)
while index1 + index2 <= length1 + length2 - 1:
# num1, num2 = array1[index1], array2[index2]
if index1 == length1 and index2 < length2:
result_array.append(array2[index2])
index2 += 1
elif index2 == length2 and index1 < length1:
result_array.append(array1[index1])
index1 += 1
else:
# print(index1, index2)
if array1[index1] < array2[index2]:
result_array.append(array1[index1])
index1 += 1
else:
result_array.append(array2[index2])
index2 += 1
return result_array
def sort(array):
split_array = split_into_2(array)
print(split_array)
while len(split_array) > 1:
temp_array = []
for i in range(0, len(split_array) - 1, 2):
temp_array.append(merge_sort(split_array[i], split_array[i + 1]))
if len(split_array) % 2 != 0:
temp_array.append(split_array[-1])
split_array = temp_array
print(split_array)
if __name__ == "__main__":
array = [1, 5, 21, 2, 3, 6, 17, 4, 9, 542, 123, 6]
sort(array)
|
def is_string_int(s):
"""
This function takes in the parameter s as a string and returns True
if s can be safely converted to an int. It returns False otherwise.
"""
pass
def is_string_float(s):
"""
This function takes in the parameter s as a string and returns True
if s can be safely converted to a float. It returns False otherwise.
"""
pass
user_input = raw_input("What string do you want to know about? ")
|
import copy
#Get an array initialized, 15x15
def make_board():
"""
A board is a list of lists of dictionaries.
board[r][c] is the dictionary representing the square at row r and column c
A dictionary representing a square can have:
* A key 'letter' that contains a single letter that is played at that square.
"""
board = []
for i in range(15):
row = []
for j in range(15):
row.append({})
board.append(row)
return board
def play_letter(letter, board, position):
"""
Takes the given letter and board, and checks if the position on the board
can accept that letter.
If so, modifies the board to have that letter on it.
If not, raises an error.
"""
row, column = position
square = board[row][column]
if 'letter' in square:
if letter != square['letter']:
raise Exception('You tried to play %s, but the board contained %s' %
(letter, square['letter']))
else:
square['letter'] = letter
def print_board(board):
"""
Print a board so that each row is on its own line.
An empty space is represented by '.'
A played letter is represented by that letter
"""
for row in board:
for square in row:
if 'letter' in square:
print square['letter'],
else:
print '.',
print
HORIZONTAL, VERTICAL = ("horizontal", "vertical")
def play_word(board, word, position, orientation):
"""
board: Board to place the word on. See above.
word: the string word to play
position: a tuple of coordinates (row, column) for the initial letter of the
word to play.
orientation: either "horizontal" or "vertical"
raises an error if the coordinates for the word don't fall within the board.
raises an error if the word conflicts with letters already on the board.
returns a new board with the new word on it, as well as all the words
already on the board.
"""
#make the new board
board = copy.deepcopy(board)
#for every letter in the word to add
# find its coordinates
# check to see if it conflicts
# if the square is empty, play on it
# If the square is occupied, report any conflicts, but otherwise leave alone
row, column = position
for l in word:
play_letter(l, board, (row, column))
if orientation == HORIZONTAL:
column += 1
elif orientation == VERTICAL:
row += 1
return board
def read_board(str_board):
"""Takes in a string in the form of a grid of letters
Returns a board in the format described above."""
board = make_board();
lines = str_board.splitlines()
for row, line in enumerate(lines):
for col, letter in enumerate(line):
if letter.isalpha():
play_letter(letter, board, (row, col))
return board
|
# chapter 8 exercise
# create a function that will return a string of the type of data passed
def checkType(var):
var = str(var)
if(var.isalpha()):
return 'alpha'
elif(var.isdigit()):
return 'number'
elif(var.isalnum()):
return 'aphanum'
else:
return 'unknown'
var = input('input something:\n')
print(checkType(var))
|
#chapter 4 exercise
#create fibonacci sequence and stop at the first number greater than 100
#Fn = Fn-2+Fn-1, inital values F0=0 and F1=1
Fn = 0
F0 = 0
F1 = 1
check = False
while True:
Fn = F0 + F1
F1 = F0
F0 = Fn
if(Fn > 100):
check = True
#print('check true')
else:
check = False
print(Fn)
if(check == True):
#print('break')
break
|
# Store input
# create var name number_map
number_map = []
height, width = map(int, input().split()) # first line
for line in height:
# map lines
number_map.append(list(map(int, input().split())))
T = int(input()) # number of test cases
nodes = {}
# For each test case
for i in range(T):
start_x, start_y, end_x, end_y = map(int, input().split())
start_digit = number_map[start_x-1][start_y-1]
end_digit = number_map[start_x-1][start_y-1]
# If the digits of the end points are different, print 'neither' and break
if start_digit != end_digit:
print('neither')
# If the digits are the same, then check if they are connected
# If the endpoints were visited in a single test case before, that means they are connected (ignore for now)
elif findPath():
# If 1, then we are discarding binary (checking if 'decimal')
if start_digit == 1:
print('decimal')
# If 0, then we are discarding decimal (checking if 'binary')
elif start_digit == 0:
print('binary')
else print('neither')
def findPath():
connection_found = False
# TODO Write algorithm here
return connection_found
|
```
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
```
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dic,tmp = {},set()
for i,c in enumerate(s):
if c not in dic:
if t[i] in tmp:
return False
dic[c] = t[i]
tmp.add(t[i])
else:
if dic[c] !=t[i]:
return False
return True
|
```
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
```
### soution 1: heap
class Solution:
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m,n = len(matrix), len(matrix[0])
p = [(matrix[0][0], 0, 0)]
res = 0
for _ in range(k):
res, i, j = heapq.heappop(p)
if j==0 and i+1<m:
heapq.heappush(p,(matrix[i+1][j],i+1,j))
if j+1<n:
heapq.heappush(p,(matrix[i][j+1],i,j+1))
return res
### solution 2: binary search
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
l = matrix[0][0]
m = len(matrix)
n = len(matrix[0])
h = matrix[m-1][n-1]
while l<h:
mid = (l+h)//2
count = 0
j = n-1
i = 0
while j>=0 and i<m:
if matrix[i][j]<=mid:
count+=(j+1)
i+=1
else:
j-=1
if count<k:
l = mid+1
else:
h = mid
return l |
```
You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make.
Example 1:
Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: "AAABBC"
Output: 188
Note:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
```
class Solution(object):
def numTilePossibilities(self, tiles):
"""
:type tiles: str
:rtype: int
"""
def backtrack(s,visited,curr,res):
if curr not in res and curr !="":
res.add(curr)
for i in range(len(s)):
if visited[i]== False:
visited[i] = True
curr+=s[i]
backtrack(s,visited,curr,res)
curr = curr[:-1]
visited[i] = False
res = set()
curr = ""
visited = [False]*len(tiles)
backtrack(tiles,visited,curr,res)
return len(res) |
```
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Output: false
```
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
maps = {("0","0"),("1","1"),("6","9"),("8","8"),("9","6")}
i = 0
j = len(num)-1
while i <= j:
if (num[i],num[j]) not in maps:
return False
i+=1
j-=1
return True |
```
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
```
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l,r = 0, len(nums)-1
while l<r:
mid1 = (l+r)//2
mid2 = mid1+1
if nums[mid1]<nums[mid2]:
l = mid2
else:
r = mid1
return l |
```
Given an input string , reverse the string word by word.
Example:
Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
```
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
start,end = 0 ,len(s)-1
while start<end:
tmp = s[start]
s[start] = s[end]
s[end] = tmp
start+=1
end-=1
start = end = 0
for i in range(len(s)):
if s[i] != " ":
end = i
else:
s[start:end+1] = s[start:end+1][::-1]
start = end = i+1
s[start:end+1] = s[start:end+1][::-1]
|
age=int(input("Enter your age"))
print("sex? (M or F)")
sex=input("Enter your sex")
print("Married? (Y or N)")
married=input("Enter your status")
if sex=="F" and age>=20 and age<=60:
print("Work in Urban area only")
elif sex=="M" and age>=20 and age<=40:
print("Work anywhere")
elif sex=="M" and age>40 and age<=60:
print("Urban areas only")
else:
print("ERROR")
|
alienColor=input("Enter color")
if alienColor=="green":
print("earn 5 points ")
elif alienColor!="green":
print("earn 10 points") |
name=input("Enter you name: ")
password=input("Enter your password: ")
if name=="tejuchoudhary":
if password=="TEJU12":
print("Successful Login")
else:
print(name,password,"You have entered incorrect password or name")
name1=input("Enter you name: ")
if name=="tejuchoudhary":
password=input("Enter your password: ")
if password=="TEJU12":
print("Successful Login")
else:
print("wrong password entered")
else:
print("Again entered wrong name")
else:
print("Wrong details entered")
|
"""Given the array of integers nums, you will choose two
different indices i and j of
that array. Return the maximum
value of (nums[i]-1)*(nums[j]-1)."""
class Solution:
def maxProduct(self, nums: List[int]) -> int:
nums.sort()
max_product = (nums[-1] -1) * (nums[-2] -1)
return max_product |
# while True:
# try:
# miles = input('请输入英里数:')
# km = int(miles) * 1.609344
# print(f'等于{km}公里')
# except ValueError:
# print('你输入了非数字字符')
# try:
# choice = input('输入你的选择:')
# if choice == '1':
# 100/0
# else:
# [][2]
# except ZeroDivisionError:
# print ('出现 ZeroDivisionError')
# except IndexError :
# print ('出现 IndexError ')
import traceback
def level_3():
print ('进入 level_3')
a = [0]
b = a[1]
print ('离开 level_3')
def level_2():
print ('进入 level_2')
level_3()
print ('离开 level_2')
def level_1():
print ('进入 level_1')
level_2()
print ('离开 level_1')
try:
level_1()
except :
print(f'未知异常:{traceback.format_exc()}')
print('程序正常退出') |
def methode_rectanglesdr(a, b, n):
integrale = 0.0
hauteur = float(b-a)/n
for k in range(n+1):
integrale += (hauteur * k + a)**2
integrale = integrale * hauteur
return integrale
print "Rectangle droit pour x**2 avec n = 10 : "
print methode_rectanglesdr(0, 1, 10)
|
from pandas import read_csv
from matplotlib import pyplot
# Display the time series plots/graphs
def display(file, type):
series = read_csv(file, encoding="ISO-8859-1", header=0, index_col=0, parse_dates=True, squeeze=True)
# Loads the dataset and print the first 5 rows
if type == "table":
print(series.head())
# Time Series Line Plot
elif type == "line_plot":
series.plot()
# Time Series Dot Plot (Modified Line Plot where style of line is black dots)
elif type == "dot_plot":
series.plot(style='k.')
# Time Series Dashed Line Plot (Modified Line Plot where style of line is dashed lines)
elif type == "dashed_line_plot":
series.plot(style='k-')
# Time Series Histogram where sentiment values are grouped into bins and the vertical axis is the frequency of each sentiment
elif type == "histogram":
series.hist()
pyplot.show()
files = ['Project6500.csv', 'reuters_data.csv']
types = ["table", "line_plot", "dot_plot", "dashed_line_plot", "histogram"]
for file in files:
for type in types:
display(file, type)
|
'''
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum 3-tree by the given 2-array and output the root node of this 3-tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def constructMaximumBinaryTree(nums):
if not nums: return None
val = max(nums)
idx = nums.index(val)
root = TreeNode(val)
root.left = constructMaximumBinaryTree(nums[:idx])
root.right = constructMaximumBinaryTree(nums[idx + 1:])
return root |
#coding=utf-8
'''
Given a singly 1-linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
'''
#如果让头部节点在"归"的过程中,配合递归时逆向行驶的节点,做相向的移动,有两种方式:
#1. "递"结束之后,返回头部,每次"归"时,返回节点next
#2. 在递归函数之外,定义一个头部节点lnode,每次"归"时,lnode移动到next
def isPalindrome_recursive(head):
def helper(node, ret):
if not node: return head
newHead = helper(node.next, ret)
if not newHead or newHead.val != node.val:
ret[0] = False
return None
return newHead.next
ret = [True]
helper(head, ret)
return ret[0]
def isPalindrome(head):
l = []
while head:
l.append(head.val)
head = head.next
return l == l[::-1] |
#coding=utf-8
'''
Given a string text, we are allowed to swap two of the characters in the string.
Find the length of the longest substring with repeated characters.
Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'.
Then, the longest repeated character substring is "aaa", which its length is 3.
'''
import collections
def maxRepOpt1(text):
"""
:type text: str
:rtype: int
"""
# 细节上处理的不好,导致程序写不出来
# 区分处理 连续性的substring 和 间隔性的substring
# 在一个流程中处理兼容两种情况,会有很大困难
def getLongest(v):
#prev前一个连续区间的长度,curr当前连续区间的长度
prev, curr = 0, 1
sum_res = 0
# 主流程处理艺术:处理主干case
for i in range(len(v) - 1):
if v[i + 1] - v[i] <= 1:
curr += 1
else:
if v[i + 1] - v[i] == 2:
prev = curr
else:
prev = 0
curr = 1
sum_res = max(sum_res, prev + curr)
#除了corner case(整个v区间都是连续),对其他情况下的长度需要补充空缺的1
if sum_res < len(v):
sum_res += 1
return sum_res
cdict = collections.defaultdict(list)
for i, c in enumerate(text):
cdict[c].append(i)
ans = 1
for k, arr in cdict.items():
ans = max(ans, getLongest(arr))
return ans |
#coding=utf-8
'''
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children.
The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node.
If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
'''
def connect_recursive(root):
"""
:type root: Node
:rtype: Node
"""
if not root: return None
if root.left:
root.left.next = root.right
root.right.next = None
#here is lightspot!
if root.next:
root.right.next = root.next.left
connect_recursive(root.left)
connect_recursive(root.right)
return root
#nice!!
def connect_iterative(root):
ret = root
while root and root.left:
next = root.left
while root:
root.left.next = root.right
#same as recursive's lightspot
root.right.next = root.next and root.next.left
root = root.next
root = next
return ret |
'''
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
'''
def lengthOfLIS_dp(nums):
if not nums: return 0
N = len(nums)
dp = [1] * N
for i in range(1, N):
for j in range(i - 1, -1, -1):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
def lengthOfLIS(nums):
dp = []
ret = 0
for n in nums:
N = len(dp)
l,r = 0,N-1
while l<r:
mid = (l+r)/2
if dp[mid] < n:
l = mid+1
elif dp[mid] == n:
l = mid
break
else:
r = mid
if N==0 or (l == N-1 and dp[l] < n):
dp.append(n)
ret += 1
else:
dp[l] = n
return ret
nums = [1,3,2]
print lengthOfLIS(nums)
|
#coding=utf-8
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
'''
#如果不把什么时候返回/结束定清楚,很容易出错
def jump(nums):
"""
:type nums: List[int]
:rtype: int
"""
step = 0
i = 0
while i < len(nums) - 1:
step += 1
#如果以i为起点就能跳到last index,就直接返回,不用寻找它后面最佳的候选
if i + nums[i] >= len(nums) - 1:
return step
#以J为起点能够跳的最远的那个J,为下一个最佳候选
for j in range(i + 1, i + nums[i] + 1):
#如果能够跳到last index,就直接返回,避免越界和冗余的计算
if j + nums[j] >= len(nums) - 1:
return step + 1
if j + nums[j] > i + nums[i]:
i = j
return step
def jump_concise(nums):
res = 0
i = 0
while i < len(nums)-1:
res += 1
if i+nums[i] >= len(nums)-1: break
right = i+nums[i]
j = i+1
while j <= right:
if j+nums[j] >= i+nums[i]:
i = j
j += 1
return res |
'''
Given an 2-array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
'''
#1.use python api
#2.one pass , by recording dict[target-curN] = curIdx,
# judge if curN in dict and get mapping idx
import collections
def twoSum_api(nums, target):
counter1 = collections.Counter(nums)
for i,n in enumerate(nums):
if (target-n != n and counter1[target-n] == 1)\
or (target-n == n and counter1[target-n] > 1):
return [i, nums.index(target - n,i+1)]
#elegant solution
def twoSum(nums, target):
hist = {}
for i, n in enumerate(nums):
idx = hist.get(n,-1)
if idx != -1: return [idx, i]
hist[target-n] = i
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target)) |
#coding=utf-8
'''
Equations are given in the format A / B = k, where A and B are variables represented as strings,
and k is a real number (floating point number).
Given some queries, return the answers. If the answer does not exist, return -1.0.
'''
import collections
def calcEquation(equations, values, queries):
G = collections.defaultdict(dict)
for (x,y), v in zip(equations, values):
G[x][y] = v
G[y][x] = 1/v
def dfs(start, end, path, paths):
if start == end and start in G:
paths[0] = path
return
if start in seen:
return
seen.add(start)
for node in G[start]:
dfs(node, end, path*G[start][node], paths)
ret = []
for x, y in queries:
paths, seen = [-1.0], set()
dfs(x, y, 1.0, paths)
ret.append(paths[0])
return ret
#利用并查集,将所有equations中的pair,都计算它的分子、分母和根节点的除法结果
# 最后,以根节点为中间纽带,判断queries的分子分母分别和根节点的关系,从而得到他两之间的除值
def calcEquation_unionfind(equations, values, queries):
parent = dict()
#一般的 并查集find 直接将结果赋给parent
#这个 需要得到返回的值,在返回值上做累积计算,再做赋值
def find(x):
p, xr = parent.setdefault(x, (x, 1.0))
if p != x:
r, pr = find(p)
parent[x] = r, pr * xr
return parent[x]
def union(x, y, load):
(px, rx), (py, ry) = find(x), find(y)
if not load:
return rx / ry if px == py else -1.0
if px != py:
#注意分子分母不要颠倒
parent[px] = (py, ry / rx * load)
for (x, y), v in zip(equations, values):
union(x, y, v)
#如果if 带 else,就把判断放在for 之前,否则放在for之后
return [union(x, y, 0) if x in parent and y in parent else -1.0 for x, y in queries]
equations = [ ["a", "b"], ["b", "c"] ]
values = [2.0, 3.0]
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]
print(calcEquation_unionfind(equations, values, queries)) |
#coding=utf-8
'''
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
'''
#用part == part[::-1]判断回文,没必要单独写函数
#注意审题,不是返回每个回文子串的集合,而是回文子串列表构成的集合
#对当前输入列表(字符串)进行切片,作为下一层的递归输入
def partition(s):
def helper(s, comb, ret):
if not s:
ret.append(comb)
return
for i in range(1, len(s) + 1):
subs = s[:i]
if subs == subs[::-1]:
helper(s[i:], comb + [subs], ret)
ret = []
helper(s, [], ret)
return ret
s = "aab"
print(partition(s)) |
def longestCommonPrefix(strs):
if not strs: return ""
if len(strs) == 1: return strs[0]
prefix = ""
strs.sort()
for i,j in zip(strs[0], strs[-1]):
if i == j: prefix += i
else: break
return prefix
strs = ["alower","flow","flight"]
print longestCommonPrefix(strs) |
def searchInsert(nums, target):
cnt = len(nums)
lo,hi = 0, cnt-1
while lo < hi:
mid = (lo+hi)/2
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid+1
else:
hi = mid
return lo+1 if cnt>0 and nums[lo] < target else lo
nums = [1]
target = 1
print(searchInsert(nums, target)) |
'''
1. Hashmap provides Insert and Delete in average constant time, although has problems with GetRandom.
The idea of GetRandom is to choose a random index and then to retrieve an element with that index.
There is no indexes in hashmap, and hence to get true random value, one has first to convert hashmap
keys in a list, that would take linear time.
2. Array List has indexes and could provide Insert and GetRandom in average constant time, though has problems with Delete.
To delete a value at arbitrary index takes linear time.
The solution here is to always delete the last value:
I.Swap the element to delete with the last one.
II.Pop the last element out.
'''
#hashmap + list
#hashmap key:num value:num index in list
#list [num0, num1, ... ]
import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = {}
self.list = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val not in self.dict:
self.dict[val] = len(self.list)
self.list.append(val)
return True
return False
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.dict:
lastIdx, dstIdx = len(self.list) - 1, self.dict[val]
self.dict[self.list[lastIdx]] = dstIdx
self.list[lastIdx], self.list[dstIdx] = self.list[dstIdx], self.list[lastIdx]
self.list.pop()
del self.dict[val]
return True
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.list)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom() |
def maxSubArray(nums):
"""
:type nums: List[int]
:rtype: int
"""
maxsum = cursum = nums[0]
for num in nums[1:]:
cursum = max(cursum + num, num)
maxsum = max(maxsum, cursum)
return maxsum |
#coding=utf-8
'''
Reverse a singly 1-linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A 1-linked list can be reversed either iteratively or recursively.
Could you implement both?
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def reverseList_4step(head):
prev, cur = None, head,
while cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
#只是reverse, 只需return.如果是返回最深的那个端点,就按照下面的方式返回。
# 注意到p是逐层向上返回,中间没有对返回的p做任何额外处理
def reverseList_recursion(head):
if not head or not head.next:
return head
p = reverseList_recursion(head.next)
head.next.next = head
head.next = None
return p
|
'''
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
'''
# Let's use three pointers i2,i3,i5 ,to mark the last ugly number which was multiplied by 2, 3 and 5, correspondingly.
def nthUglyNumber(n):
nums = [1,]
i2,i3,i5 = 0,0,0
for i in range(1,n):
ugly = min(nums[i2]*2, nums[i3]*3, nums[i5]*5)
nums.append(ugly)
#when ugly == 6, i2 and i3 must move forward both, so judge three case independent.
if ugly == nums[i2]*2:
i2 += 1
if ugly == nums[i3]*3:
i3 += 1
if ugly == nums[i5]*5:
i5 += 1
return nums[-1]
n = 2
print(nthUglyNumber(n))
|
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hist = {}
for i, num in enumerate(nums):
j = hist.get(target - num, -1)
if j >= 0:
return [j, i]
hist[num] = i |
'''
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers.
Return the maximum product you can get.
'''
def integerBreak(n):
dp = [i-1 for i in range(n+1)]
for i in range(2,n+1):
for j in range(1,i):
dp[i] = max(dp[i], dp[j]*dp[i-j], j*(i-j), dp[j]*(i-j))
return dp[-1]
print(integerBreak(2))
|
'''
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing 2-array A of positive integers forming a sequence,
find the length of the longest fibonacci-like subsequence of A.
If one does not exist, return 0.
'''
import collections
def lenLongestFibSubseq(A):
N = len(A)
dp = [[2] * (N + 1) for _ in range(N + 1)]
numdict = collections.defaultdict(lambda: N + 2)
for idx, n in enumerate(A):
numdict[n] = idx + 1
ans = 0
for i in range(1, N + 1):
for j in range(i - 1, 1, -1):
idx = numdict[A[i - 1] - A[j - 1]]
if idx < j:
dp[j][i] = dp[idx][j] + 1
ans = max(ans, dp[j][i])
return ans
def lenLongestFibSubseq_fast(A):
index = {x:i for i,x in enumerate(A)}
longest = collections.defaultdict(lambda :2)
ans = 0
for i,n in enumerate(A):
for j in range(i-1,0,-1):
k = index.get(A[i]-A[j], None)
if k is not None and k<j:
longest[j,i] = longest[k,j]+1
ans = max(ans, longest[j,i])
return ans
A = [1,2,3]
print(lenLongestFibSubseq_fast(A))
|
#coding=utf-8
'''
Implement a basic calculator to evaluate a simple expression 5-string.
The expression 5-string may contain open ( and closing parentheses ),
the plus + or minus sign -, non-negative integers and empty spaces .
The expression 5-string contains only non-negative integers, +, -, *, / operators ,
open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
All intermediate results will be in the range of [-2147483648, 2147483647].
Some examples:
"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12
'''
#4-stack:
# 1.遇到数字字符,就累积到num;
# 2.遇到'(',让前面的那个operator字符入栈,op='+',num=0
# 3.遇到'+-*/)',就将它前面的num以及num前面的operator一起,
# 3.1 去更新栈;
# 3.1.1 如果operator是+-,就让num带上符号,入栈
# 3.1.2 如果operator是*/,它们计算优先级高,栈顶元素出栈,operator, num,三者一起计算新的值,再入栈
# 3.2 如果是 ')',就连续叠加stack栈顶(弹出)元素,直至栈顶元素不是数字(为'('前面的operator)
# 4.最后将operator,num去更新栈
#KEY:
# 1.operator 和 num的更新时机(operator 是 num前面的运算符)
# 2.stack存放待运算的数字和'('之间的operator,每个数字有正负号,便于统一做加法
# 3.update(op, num),用于更新栈顶元素
# 3.最后循环结束之后,需要将最后的operator 和 num,去更新stack栈顶元素
def calculate(s):
"""
:type s: str
:rtype: int
"""
def update(op, num):
if op == '+':
stack.append(num)
elif op == '-':
stack.append(-num)
elif op == '*':
stack.append(stack.pop()*num)
elif op == '/':
stack.append(int(float(stack.pop())/num))
stack = []
op, num = '+', 0
for c in s:
if c.isdigit():
num = num*10+int(c)
elif c in "+-*/)":
update(op, num)
if c == ')':
num = 0
while isinstance(stack[-1], int):
num += stack.pop()
update(stack.pop(), num)
num, op = 0, c
elif c == '(':
stack.append(op)
num,op = 0,'+'
update(op, num)
return sum(stack)
#s = "-1+4*3/3/3"
s= " ( 2+6 * 3+5- (3*14/7+2)*5)+3 "
print(calculate(s))
|
#coding=utf-8
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
'''
# https://leetcode.com/problems/jump-game/solution/
#Memory Limit Exceeded
def canJump_MLE(nums):
def jump(idx):
if memo[idx] != UNKNOWN:
return memo[idx] == GOOD
furthestJump = min(N - 1, idx + nums[idx])
for pos in range(idx + 1, furthestJump + 1):
if jump(pos):
memo[idx] = GOOD
return True
memo[idx] = BAD
return False
N = len(nums)
GOOD, BAD, UNKNOWN = 0, 1, 2
memo = [UNKNOWN] * N
memo[-1] = GOOD
return jump(0)
def canJump_greedy_nograce(nums):
"""
:type nums: List[int]
:rtype: bool
"""
# 每个点能覆盖范围内,选一个能到达最远处的点,作为下一个跳点
jumpPt = 0
while jumpPt < len(nums) - 1:
nextPt = curIdx = jumpPt
while curIdx < len(nums) and nextPt < len(nums) and curIdx <= nextPt + nums[nextPt]:
nextPt = max(nextPt, curIdx + nums[curIdx])
curIdx += 1
if nextPt <= jumpPt:
return False
jumpPt = nextPt
return True
def canJump_greedy_grace(nums):
N = len(nums)
lastpos = N - 1
for i in range(N - 1, -1, -1):
if i + nums[i] >= lastpos:
lastpos = i
return lastpos == 0
|
#coding=utf-8
#Binary tree could be constructed from preorder/postorder and inorder traversal.
#Inorder traversal of BST is an array sorted in the ascending order: inorder = sorted(preorder).
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""
Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def postorder(root):
return postorder(root.left) + postorder(root.right) + [root.val] if root else []
return ' '.join(map(str, postorder(root)))
def deserialize(self, data):
"""
Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def helper(inorder, postorder):
if not inorder: return None
val = postorder[-1]
idx = inorder.index(val)
root = TreeNode(val)
root.left = helper(inorder[:idx], postorder[:idx])
# 起始是正索引,终止是负索引的用法是OK的
root.right = helper(inorder[idx + 1:], postorder[idx:-1])
return root
postdata = [int(x) for x in data.split(' ') if x]
indata = sorted(postdata)
return helper(indata, postdata)
|
'''
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
'''
def longestOnes(A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
start = end = oneCnt = 0
N = len(A)
maxLen = 0
while end < N:
oneCnt += A[end]
end += 1
if end - start - oneCnt <= K:
maxLen = max(maxLen, end - start)
else:
oneCnt -= A[start]
start += 1
return maxLen
# [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1] |
#coding=utf-8
'''
Given an 2-array A of non-negative integers, the 2-array is squareful if for every pair of adjacent elements,
their sum is a perfect square.
Return the number of permutations of A that are squareful.
Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
'''
import collections
def numSquarefulPerms_noGrace(A):
graph = collections.defaultdict(list)
count = collections.Counter(A)
for x in count:
for y in count:
if int((x + y) ** .5 + 0.5) ** 2 == x + y:
graph[x].append(y)
N = len(A)
def dfs(i, path, ret):
count[i] -= 1 #相比 在line 35前后加上计数的增减,计数放在这里的好处,是不用再外面line 40前后也加这样一对
if len(path) == N:
ret[0] += 1
else:
for child in graph[i]:
if count[child] == 0: continue
dfs(child, path+[child], ret)
count[i] += 1
ret = [0]
for node,n in count.items():
dfs(node, [node], ret)
return ret[0]
#这种固定的总元素个数,全部遍历,最后有多少种可能的code pattern:
#1.可能的话,用counter对每种元素计数,应对初始数组可能有重复元素
#2.为了dfs完毕,透出计数结果,只在if else 之外,做一次返回ans。if 内结束该次遍历 返回1;esle内ans置0,将递归返回的值,累加到ans
#3.遍历过程中,入栈时数目减1 出栈时数目加1,在dfs函数体内进行.
#4.对多个元素的计算,汇总成一个结果返回,为了简洁,可以考虑用sum() 或者 filter() ,返回总数或者列表
def numSquarefulPerms_Grace(A):
graph = collections.defaultdict(list)
count = collections.Counter(A)
for x in count:
for y in count:
if int((x + y) ** .5 + 0.5) ** 2 == x + y:
graph[x].append(y)
def dfs(x, todo):
count[x] -= 1
if todo == 0:
ans = 1
else:
ans = 0
for y in graph[x]:
if count[y]:
ans += dfs(y, todo-1)
count[x] += 1
return ans
return sum(dfs(i, len(A)-1) for i in graph)
A = [1,8,17]
print(numSquarefulPerms_Grace(A)) |
#coding=utf-8
'''
You are driving a vehicle that has capacity empty seats initially available for passengers.
The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip:
the number of passengers that must be picked up, and the locations to pick them up and drop them off.
The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1
trips = [[4,5,6],[6,4,7],[4,3,5],[2,3,5]]
capacity = 13
Output: True
'''
import heapq
def carPooling_greedy_byHeap(trips, capacity):
trips.sort(key=lambda x: x[1])
curCapSum, cur = 0, []
for cap, s, e in trips:
while cur and cur[0][0] <= s:
curCapSum -= cur[0][1]
heapq.heappop(cur)
heapq.heappush(cur, [e, cap])
curCapSum += cap
if curCapSum > capacity: return False
return True
def carPooling(trips, capacity):
pairs = []
for trip in trips:
pairs += [trip[1],trip[0]],
pairs += [trip[2], -trip[0]],
#x:(x[0],x[1]) 很关键,对x[0]比较,还要对x[1]比较,防止在同一地点既有上又有下的情况
pairs = sorted(pairs, key=lambda x:(x[0],x[1]))
total = 0
for item in pairs:
total += item[1]
if total > capacity:
return False
return total == 0
trips = [[4,5,6],[6,4,7],[4,3,5],[2,3,5]]
capacity = 13
print(carPooling(trips, capacity)) |
#coding=utf-8
'''
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative.
The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative.
In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences,the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence.
A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence,
leaving the remaining elements in their original order.
Example 1:
Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
'''
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = 1
delta = 0
for i in range(1, len(nums)):
#处理对算法主流程的干扰
if (nums[i] == nums[i - 1]): continue
#<= 而不是 <,统一头部两个元素的处理逻辑
if (nums[i] - nums[i - 1]) * delta <= 0:
length += 1
delta = nums[i] - nums[i - 1]
return length |
def findMin(nums):
cnt = len(nums)
left, right = 0, cnt-1
if cnt == 1:
return nums[0]
if nums[0] < nums[-1]:
return nums[0]
if (cnt ==2 and nums[0]>nums[1]) or (cnt > 2 and nums[0] > nums[1] and nums[1]>nums[2]):
return nums[-1]
while left < right:
mid = (left+right)//2
if mid == left:
return nums[right]
if nums[mid] == nums[left]:
if nums[left] <= nums[left+1]:
left += 1
else:
return nums[left+1]
elif nums[mid] > nums[left]:
left = mid
else:
right = mid
nums = [5,5,6,7,1,2,2]
print(findMin(nums)) |
#coding=utf-8
'''
There is a new alien language which uses the latin alphabet.
However, the order among letters are unknown to you.
You receive a list of non-empty words from the dictionary,
where words are sorted lexicographically by the rules of this new language.
Derive the order of letters in this language.
Example 1:
Input:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
Output: "wertf"
'''
#1. adjacent list + indegree
#2. topo sort
import collections
def alienOrder(words):
chars = set("".join(words))
indegree = {c:0 for c in chars}
#adjacent list:
letters = collections.defaultdict(set)
for f, b in zip(words[:-1], words[1:]):
fl, bl = len(f), len(b)
minlen = min(fl, bl)
#["wrtkj","wrt"] 这种case,应该为invalid,需要单独判断
if f[:minlen] == b[:minlen] and fl > bl: return ""
for i in range(0, minlen):
#特别容易错,此处如果不做判断,会导致相同的pair重复判断,indegree的计算出现错误
if b[i] in letters[f[i]]:
break
if (f[i] != b[i]):
letters[f[i]].add(b[i])
indegree[b[i]] += 1
break
#initialize indegree:
deque = collections.deque()
for k,v in indegree.items():
if v == 0: deque.append(k)
#topo sort
ans = []
while deque:
p = deque.popleft()
ans.append(p)
for c in letters[p]:
indegree[c] -= 1
if indegree[c] == 0:
deque.append(c)
return "".join(ans) if len(ans) == len(chars) else ""
words = ["ab","b"]
#words = ["wrt","wrf","er","ett","rftt","te"]
print(alienOrder(words)) |
'''
Find the kth largest element in an unsorted 2-array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 <= k <= 2-array's length.
'''
#nlogn
def findKthLargest_sort(nums, k):
nums.sort(reverse=True)
return nums[k - 1]
#nlogk
import heapq
def findKthLargest_heap(nums, k):
heap = nums[:k]
heapq.heapify(heap)
for num in nums[k:]:
if num>heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, num)
return heap[0]
def findKthLargest_concise(nums, k):
return heapq.nlargest(k, nums)[-1]
nums = [3,2,1,5,6,4]
k = 2
print(findKthLargest_heap(nums, k)) |
'''
Given an 2-array nums, there is a sliding window of size k which is moving from the very
left of the 2-array to the very right. You can only see the k numbers in the window.
Each time the sliding window moves right by one position. Return the max sliding window.
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
'''
# Keep indexes of good candidates in deque d. The indexes in d are from the current window,
# they're increasing, and their corresponding nums are decreasing.
# Then the first deque element is the index of the largest window value
#deque在窗口中的妙用,保持队列中的元素从头到尾是递减,即新来的元素淘汰掉队列尾部小于它的元素,最后新元素入队列
import collections
def maxSlidingWindow(nums, k):
deq = collections.deque()
out = []
for i,n in enumerate(nums):
while deq and nums[deq[-1]]<n:
deq.pop()
deq += i,
if deq[0] == i-k:
deq.popleft()
if i>=k-1:
out += nums[deq[0]],
return out
nums = [1,3,-1,-3,5,3,6,7]
k = 8
print(maxSlidingWindow(nums, k)) |
'''
1081. Smallest Subsequence of Distinct Characters
Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once.
Example 1:
Input: "cdadabcc"
Output: "adbc"
'''
def smallestSubsequence(text):
stack = []
for i, c in enumerate(text):
if c in stack: continue
while stack and c < stack[-1] and stack[-1] in text[i:]:
stack.pop()
stack += c,
return "".join(stack)
'''
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once.
You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input: "bcabc"
Output: "abc"
Example 2:
Input: "cbacdcbc"
Output: "acdb"
'''
# Greedy - Solving with Stack
#At each stage in our iteration through the string, we greedily keep what's on the stack as small as possible.
#Greedy problem is hard to find the trick
def removeDuplicateLetters(s):
"""
:type s: str
:rtype: str
"""
stack = []
for i, c in enumerate(s):
#key point: stack里是升序, c在stack里就不管,交给后面的字符来对stack进行处理
if c in stack: continue
while stack and c < stack[-1] and stack[-1] in s[i:]:
stack.pop()
stack += c,
return "".join(stack) |
#coding=utf-8
'''
We have a sequence of books: the i-th book has thickness books[i][0] and height books[i][1].
We want to place these books in order onto bookcase shelves that have total width shelf_width.
We choose some of the books to place on this shelf (such that the sum of their thickness is <= shelf_width),
then build another level of shelf of the bookcase so that the total height of the bookcase has increased
by the maximum height of the books we just put down. We repeat this process until there are no more books to place.
Note again that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf,
the third book on the second shelf, and the fourth and fifth book on the last shelf.
Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.
'''
#lightspot: 阶段没有重新组织划分,还是以原始books数组的每个元素为阶段
# 但是在当前阶段dp[i],推演books[i]加入后能获得最小总体高度时,能够推演到最远的那个j,是受限的,
# 受制于[j..i]累积宽度 不能超过规定的shelft-width。
# 这里给出的启示是:设定的限制条件,可能只是限制了当前dp[i],向低位推演的条件范围,不影响一般性质的阶段划分和状态转移
import sys
def minHeightShelves(books, shelf_width):
N = len(books)
# dp[i] min height after place (i-1)th book
dp = [0] + [float("inf")] * N
for i in range(1, N + 1):
levelHight, width_left = 0, shelf_width
j = i
while j > 0:
width_left -= books[j - 1][0]
if width_left < 0:
break
levelHight = max(levelHight, books[j - 1][1])
dp[i] = min(dp[i], dp[j - 1] + levelHight)
j -= 1
return dp[-1]
shelf_width = 10
#books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]]
books = [[7,3],[8,7],[2,7],[2,5]]
print(minHeightShelves(books, shelf_width))
|
'''
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
For each house i, we can either build a well inside it directly with cost wells[i],
or pipe in water from another well to it.
The costs to lay pipes between houses are given by the 2-array pipes,
where each pipes[i] = [house1, house2, cost] represents the cost to connect house1 and house2 together using a pipe.
Connections are bidirectional.
Find the minimum total cost to supply water to all houses.
Example 1:
Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
Output: 3
Explanation:
The image shows the costs of connecting houses using pipes.
The best strategy is to build a well in the first house with cost 1 and
connect the other houses to it with cost 2 so the total cost is 3.
'''
#we model this problem as a graph problem
#Add a virtual node, connect it to houses with edges weighted by the costs to build wells in these houses.
#The problem is now reduced to a Minimum Spanning Tree problem.
#union find (Kruskal)
class unionFind(object):
def __init__(self, n):
self.parent = range(n+1)
def find(self, i):
if i != self.parent[i]:
self.parent[i] = self.find(self.parent[i])
return self.parent[i]
def union(self, i, j):
ri, rj = self.find(i), self.find(j)
if ri == rj:
return False
else:
self.parent[ri] = rj
return True
def minCostToSupplyWater(n, wells, pipes):
p = [(c, f, t) for f, t, c in pipes]
w = [(c, 0, i) for i, c in enumerate(wells, 1)]
uf = unionFind(n)
ans, edgeCnt = 0, 0
for c, f, t in sorted(p+w):
if edgeCnt >= n: break
if uf.union(f, t):
ans += c
return ans |
#enconding: utf-8
def fact(n):
if n < 0:
return None
mul = 1
for i in range(1,n+1):
mul *= i
return mul
print(fact(-1))
print(fact(0))
print(fact(5)) |
# 构建基本的二叉树
class Node:
def __init__(self, elem):
self.elem = elem
self.lchild = None
self.rchild = None
# list_1 = [1,2,3]
# list_2 = [1,2,3]
# A, B, C = [ Node(i) for i in list_1 ]
# A.lchild, A.rchild = B, C
# D, E, F = [ Node(i) for i in list_2 ]
# D.lchild, D.rchild = E, F
class Tree:
def __init__(self):
self.root = None
def add(self, elem):
node = Node(elem)
if self.root is None:
self.root = node
else:
q = [self.root]
while True:
pop_node = q.pop(0)
if pop_node.lchild is None:
pop_node.lchild = node
return
elif pop_node.rchild is None:
pop_node.rchild = node
return
else:
q.append(pop_node.lchild)
q.append(pop_node.rchild)
def traverse(self):
if self.root is None:
return None
q = [self.root]
res = [self.root.elem]
while q != []:
pop_node = q.pop(0)
if pop_node.lchild is not None:
q.append(pop_node.lchild)
res.append(pop_node.lchild.elem)
if pop_node.rchild is not None:
q.append(pop_node.rchild)
res.append(pop_node.rchild.elem)
return res
def preorder(self, root):
if root is None:
return []
result = [root.elem]
left_elem = self.preorder(root.lchild)
right_elem = self.preorder(root.rchild)
return result + left_elem + right_elem
def inorder(self, root):
if root is None:
return []
result = [root.elem]
left_elem = self.inorder(root.lchild)
right_elem = self.inorder(root.rchild)
return left_elem + result + right_elem
def postorder(self, root):
if root is None:
return []
result = [root.elem]
left_elem = self.postorder(root.lchild)
right_elem = self.postorder(root.rchild)
return left_elem + right_elem + result
tree = Tree()
for i in range(10):
tree.add(i)
print(tree.traverse())
print(tree.preorder(tree.root))
print(tree.inorder(tree.root))
print(tree.postorder(tree.root))
|
# encoding: utf-8
# 选择排序 时间复杂度O(n^2) 空间复杂度 O(1) 不稳定
def selection_sort(arr):
"""选择排序
:param arr:需要排序的列表
:return: 排序完成的列表
"""
length = len(arr)
for i in range(length - 1):
minIndex = i
for j in range(i + 1, length):
if arr[j] < arr[minIndex]:
minIndex = j
arr[i], arr[minIndex] = arr[minIndex], arr[i]
return arr
lis = [1, 5, 2, 0, 3]
print(selection_sort(lis))
|
# 实现 strStr() 函数。
# 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
# 示例 1:
# 输入: haystack = "hello", needle = "ll"
# 输出: 2
# 示例 2:
# 输入: haystack = "aaaaa", needle = "bba"
# 输出: -1
# 说明:
# 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
# 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
# 核心思想:先判断找不找的到,找的到的话就直接切割,切完了判断一个切的字符多长
def test(haystack, needle):
if needle == "":
return 0
return len(haystack.split(needle)[0]) if needle in haystack else -1
haystack = "hello"
needle = "ll"
print(test(haystack, needle))
|
# 核心思路
# 建立两个指针,一个从开始指一个,另一个指下一个,一样就弹出第二个,不一样就递增
# 反思一下 这么简单的想法,为什么我就没想到???
def test(nums):
pre = 1
while pre < len(nums):
if nums[pre-1] == nums[pre]:
nums.pop(pre)
else:
pre = pre + 1
return len(nums)
nums = [0,0,1,1,1,2,2,3,3,4]
print(test(nums))
|
import csv
with open('data.csv', encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader)
print(header)
for i in reader:
print(i)
|
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
# 示例 1:
# 输入: 123
# 输出: 321
# 示例 2:
# 输入: -123
# 输出: -321
# 示例 3:
# 输入: 120
# 输出: 21
# 注意:
# 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
def test(x):
if x > 0:
a = int(str(x)[::-1])
return a if a < 2**31 - 1 else 0
elif x < 0:
b = int(str(x)[:1] + str(int(str(x)[:0:-1])))
return b if b > -2**31 else 0
else:
return 0
x = -120
print(test(x))
# 注意看题啊!!
|
# 编写一个函数来查找字符串数组中的最长公共前缀。
# 如果不存在公共前缀,返回空字符串 ""。
# 示例 1:
# 输入: ["flower","flow","flight"]
# 输出: "fl"
# 示例 2:
# 输入: ["dog","racecar","car"]
# 输出: ""
# 解释: 输入不存在公共前缀。
# 说明:
# 所有输入只包含小写字母 a-z 。
# 注意看题 前缀!!!,随便比两个就行
# 利用python的max()和min(),在Python里字符串是可以比较的,按照ascII值排,举例abb, aba,abac,最大为abb,最小为aba。所以只需要比较最大最小的公共前缀就是整个数组的公共前缀
def longestCommonPrefix(strs):
if not strs:
return ""
str_min = min(strs)
str_max = max(strs)
for idx,val in enumerate(str_min):
print(idx,val)
if val != str_max[idx]:
return str_max[:idx]
return str_min
strs = ["fl","fl","fl"]
print(longestCommonPrefix(strs))
|
# enconding: utf-8
def test(n):
if 1 <= n <= 10**5:
Product = 1
Sum = 0
while(n):
Product *= n % 10
Sum += n % 10
n //= 10
return Product - Sum
n = 234
print(test(n))
|
#enconding: utf-8
def key(n):
return n
def key2(n):
return n[1]
def key3(n):
return n['age']
def bubble(l,key):
length = len(l)
for j in range(length - 1):
for i in range(length - 1):
if key(l[i]) > key(l[i+1]):
l[i+1],l[i] = l[i],l[i+1]
l1 = [5,4,3]
bubble(l1,key)
print(l1)
l2 = [(1, 6), (2, 5), (3, 6)]
bubble(l2, key2)
print(l2)
l3 = [{'age': 60}, {'age': 70}]
bubble(l3, key3)
print(l3)
|
# encoding: utf-8
import queue
def quick_queue_sort(array):
work_queue = queue.Queue()
quick_data = QuickData(0, len(arr) - 1, arr)
work_queue.put(quick_data)
while work_queue.qsize() > 0:
data = work_queue.get_nowait()
i = data.head
j = data.tail
compare = array[data.head]
if j > i:
while j > i:
while j > i and array[j] >= compare:
j -= j
array[i] = array[j]
while j > i and array[i] <= compare:
i += i
array[j] = array[i]
array[i] = compare
work_queue.put(QuickData(data.head, i - 1, array))
work_queue.put(QuickData(i + 1, data.tail, array))
class QuickData:
def __init__(self, head, tail, array):
self.head = head
self.tail = tail
self.array = array
if __name__ == '__main__':
arr = [1, 8, 9, 121, 122, 5, 8, 4, 9, 1, 6, 45, 9, 125, 6546, 16546]
quick_queue_sort(arr)
print(arr)
|
#enconding;utf-8
num1 = [1,2,3,4,5,6,7,8,9]
num2 = [1,2,7,8,11,1230]
result = []
for num in num1:
if num in num2 and num not in result:
result.append(num)
# result.append(num)
print(result)
|
#Written By Collin Lakeland
#Program to solve a quadratic in standard form
#Completed on December 20th, 2013
from __future__ import division #division module makes it so the division operator doesn't round the quotient
import cmath #cmath module allows for complex solutions
import sys
class Quadratic():
def __init__(self, argv):
self.a = int()
self.b = int()
self.c = int()
#user input
self.coeffs = sys.argv
#print len(self.coeffs) Debugging
def more_than_three_coefficients(self):
if len(self.coeffs) > 4:
print "Usage: You must give three coefficents, even if those coefficients are zero, your equation must be of degree 2 or lower and in standard form."
sys.exit()
def less_than_three_coefficients(self):
if len(self.coeffs) < 4:
print "Usage: You must give three coefficients, even if those coefficents are zero, your equation must be of degree 2 or lower and in standard form."
sys.exit()
def three_coefficients(self):
if len(self.coeffs) == 4:
self.a = int(self.coeffs[1])
self.b = int(self.coeffs[2])
self.c = int(self.coeffs[3])
#Tests for specific triplets of coeffcients, which normally give a ZeroDivisonError or some other sort of error.
def coefficient_type_testing(self):
if self.a == 0 and self.b != 0:
#print "condition true" Debugging
self.x = -self.c/self.b
self.x2 = -self.c/self.b
elif self.a == 0 and self.b == 0 and self.c == 0:
print self.c,"= 0"
sys.exit(0)
elif self.a == 0 and self.b == 0:
print self.c, "will never equal 0"
sys.exit(0)
else:
#print "condition false" Debugging
#Root creation
self.x = (-self.b + cmath.sqrt((self.b**2)-4*self.a*self.c))/(2*self.a) #First root
self.x2 = (-self.b - cmath.sqrt((self.b**2)-4*self.a*self.c))/(2*self.a) #Second Root
#Tests to see what type of roots there are and prints them accordingly.
def root_type_testing(self, x, x2):
if x == x2 and x.imag == 0 and x == -0.0: #Double, real root
x = 0.0
print "Your solution is: x =", x
elif x == x2 and x.imag == 0:
print "Your solution is: x =", x.real
elif x.imag == 0 and x2.imag == 0: #Distinct real roots
print "Your solutions are: x =", x.real, "and x =", x2.real
elif x == x2:
print "Your solution is: x = ", x #Double, complex root
print "Note that j = i = (-1)^1/2"
else:
print "Your solutions are: x =", x, "and x =", x2 #Distinct, complex root
print "Note that j = i = (-1)^1/2"
solverObject = Quadratic(sys.argv[1:])
solverObject.more_than_three_coefficients()
solverObject.less_than_three_coefficients()
solverObject.three_coefficients()
solverObject.coefficient_type_testing()
solverObject.root_type_testing(solverObject.x, solverObject.x2)
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return str(self.val)
def inorderTraversal(root: TreeNode):
if not root:
return []
visited = set()
stack = [root]
ans = []
while len(stack) > 0:
node = stack[-1]
visited.add(node)
if node.left and node.left not in visited:
stack.append(node.left)
else:
ans.append(stack.pop().val)
if node.right and node.right not in visited:
stack.append(node.right)
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
inorderTraversal(root)
|
def check_n(ch):
return ord(ch) >= ord('1') and ord(ch) <= ord('9')
class Solution:
def isValidSudoku(self, board) -> bool:
for i in range(9):
row_set = set()
for j in range(9):
ch = board[i][j]
if ch == ".": continue
if not check_n(ch): return False
if ch in row_set: return False
row_set.add(ch)
for j in range(9):
col_set = set()
for i in range(9):
ch = board[i][j]
if ch == ".": continue
if ch in col_set: return False
col_set.add(ch)
for i in range(3):
for j in range(3):
cell_set = set()
for l in range(i * 3, (i + 1) * 3):
for m in range(j * 3, (j + 1) * 3):
ch = board[l][m]
if ch == ".": continue
if ch in cell_set: return False
cell_set.add(ch)
return True
board = [["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]]
s = Solution()
print(s.isValidSudoku(board))
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def buildTree_helper(start_inor, end_inor, preorder_dict, inorder_dict, preorder, inorder):
if start_inor >= end_inor:
return None
root = TreeNode(preorder[buildTree_helper.preor_idx])
inor_idx = inorder_dict[root.val]
buildTree_helper.preor_idx += 1
if start_inor + 1 == end_inor:
return root
root.left = buildTree_helper(start_inor, inor_idx, preorder_dict, inorder_dict, preorder, inorder)
root.right = buildTree_helper(inor_idx + 1, end_inor, preorder_dict, inorder_dict, preorder,
inorder)
return root
def buildTree(preorder, inorder) -> TreeNode:
if not inorder:
return None
if len(inorder) == 1:
return TreeNode(inorder[0])
preorder_dict = {v: i for i, v in enumerate(preorder)}
inorder_dict = {v: i for i, v in enumerate(inorder)}
buildTree_helper.preor_idx = 0
return buildTree_helper(0, len(inorder), preorder_dict, inorder_dict, preorder, inorder)
buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
|
from typing import List
from collections import deque
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
m = len(board)
n = len(board[0])
if board[click[0]][click[1]] == "M":
board[click[0]][click[1]] = "X"
return board
def get_neighbors(i, j):
res = []
for k in range(i - 1, i + 2):
for l in range(j - 1, j + 2):
if (k == i and l == j) or k < 0 or l < 0 or k > m - 1 or l > n - 1:
continue
res.append([k, l])
return res
queue = deque([click])
while queue:
L = len(queue)
for _ in range(L):
i, j = queue.popleft()
if board[i][j] != "E":
continue
bomb_count = 0
neighbors = get_neighbors(i, j)
for k, l in neighbors:
if board[k][l] == "M":
bomb_count += 1
board[i][j] = str(bomb_count) if bomb_count else "B"
if board[i][j] == "B":
for k, l in neighbors:
if board[k][l] == "E":
queue.append([k, l])
return board
s = Solution() |
import turtle
turtle.shape('classic')
def drawRect(side):
turtle.pendown()
turtle.color('red', 'yellow')
turtle.begin_fill()
for i in range(4):
turtle.forward(10 + int(side))
turtle.left(90)
turtle.penup()
turtle.goto(-side*0.5, -side*0.5)
for i in range(10,50,10):
drawRect(i)
turtle.color('red', 'yellow')
turtle.begin_fill()
while True:
turtle.forward(200)
turtle.left(170)
if abs(turtle.pos()) < 1:
break
end_fill()
done()
|
a = int(input("Primeiro valor: "))
b = int(input("Segundo valor: "))
if a > b :
print ("O primeiro numero é maior!")
if b > a :
print ("O segundo numero é maior!")
if a == b :
print ("Os numeros são iguais")
idade = int(input("Digite a ideia de seu carro: "))
if idade <= 3:
print ("Seu carro é novo!")
if idade > 3:
print ("Seu carro é velho!") |
#!/usr/bin/python
num1 = 1
num2 = 2
print num1 + num2
print num1 - num2
print num1 * num2
print num1 / num2
print num1 % num2
num1 = num1 + 2
print num1
print "Hello Wold"
# feita validacao
prog = raw_input("Qual a melhor linguagem de programacao: ")
if prog == "python":
print "Voce acertou"
else:
print "Voce errou"
nome = raw_input("Digite seu nome: ")
idade = input("Digite sua idade: ")
print "Seu nome e: "+nome+" e sua idade e: ",idade
print "Seu nome e: "+nome+" e sua idade e: "+str(idade)
print "Seu nome e: %s e sua idade e %s"%(nome,idade)
|
#!/usr/bin/python
def func1():
print "Entrou na funcao 1"
def func2():
print "Entrou na funcao 2"
def func3():
print "Entrou na funcao 3"
def switch(x):
dict_func = {1:func1,2:func2,3:func3}
dict_func[x]()
# podemos fazer assim:
# switch(1)
# ou assim:
x = input("Digite um valor de 1 a 3: ")
switch(x)
# ou com if
# if x == 1:
# func1()
#elif x == 2:
# func2()
#elif x == 3:
# func3()
#else:
# print "Funcao errada"
|
#!/usr/bin/python
## uso o import sys para o sys.exit() no sair do programa
import sys
## mais sobre funcoes
nome = ""
senha = ""
def cadastrar_usuario():
# buscar uma variavel global
global nome
global senha
nome = raw_input("Digite o login do novo usuario: ")
senha = raw_input("Digite a senha do novo usuario: ")
print "Usuario cadastrado com sucesso"
def acessar_sistema():
global nome
global senha
print "Sistema acessado"
login = raw_input("Digite seu usuario: ")
passwd = raw_input("Digite sua senha: ")
if nome == login and senha == passwd:
print "Autenticado com Sucesso! \n Seja bem vindo %s"%nome
else:
print "Acesso Negado"
def sair_sistema():
print "Saindo do sistema..."
sys.exit()
def menu():
print "\
1 - Cadastrar Usuario \n\
2 - Acessar Sistema \n\
3 - Sair do Sistema \n"
opcao = input("Digite a opcao desejada: ")
return opcao
def switch(x):
dict_options = {1:cadastrar_usuario,2:acessar_sistema,3:sair_sistema}
dict_options[x]()
if __name__ == '__main__':
while True:
switch(menu())
|
custos = []
custo = str(input("Digite o nome do custo: "))
valor = str(input("Digite o valor: "))
custos['custo'] = 'valor'
print(custos)
|
# Considere a empresa de telefonia Tchau.
# Abaixo de 200 minutos, a empresa cobra R$ 0,20 por minuto.
# Entre 200 a 400 minutos, o preço é R$ 0,18. Acima de 400 minutos o preço por
# minutos o preço por minuto é R$ 0,15.
# Calcule sua conta de telefone.
a = 0.20
b = 0.18
c = 0.15
valor = int(input("Quantos minutos voce usuou da sua conta: "))
if valor < 200:
print ("Sua conta abaixo de 200 minutos é de : %6.2f" % (valor * a))
if valor >= 200 and valor < 400 :
valor = valor * b
print ("Sua conta entre 200 a 400 minutos é de: %2.f" %valor)
if valor >= 400:
valor = valor * c
print ("Sua conta maior que 400 minutos é de: %2.f" %valor)
|
# 汉诺塔
"""
Hanoi(A,C,n):
if n = 1 then move(A,C) //将最大的盘子移动到C上
else Hanoi(A,B,n-1) //以C为中间柱,将n-1 个盘子移动到B上
move(A,C) //将当前最大的盘子移动到C上
Hanoi(B,C,n-1) //以A为中间柱,将n-1 个 盘子移动到C上
"""
# ----------------实现-----------------
def Hanoi(A,C,B,n): #开始 结束 中间柱
if n == 1:
print(A,"-->",C)
else:
Hanoi(A,B,C,n-1) #//以C为中间柱,将n-1 个盘子移动到B上
print(A, "-->", C)
Hanoi(B,C,A,n-1)
if __name__ == '__main__':
Hanoi("A","B","C",3)
|
with open("Day10Input.txt") as file:
read_data = file.read()
input_list = read_data.split('\n')
input_numbers_list = [int(i) for i in input_list]
input_numbers_list.append(0)
input_numbers_list.append((max(input_numbers_list) + 3))
input_numbers_set = set(input_numbers_list)
set_sorted = sorted(input_numbers_set)
def calculate_differences(sorted_numbers_set):
count_one_difference = 0
count_two_difference = 0
count_three_difference = 0
for i in range(1, len(sorted_numbers_set)):
difference = sorted_numbers_set[i] - sorted_numbers_set[i-1]
if difference == 1:
count_one_difference += 1
if difference == 2:
count_two_difference += 1
if difference == 3:
count_three_difference += 1
return count_one_difference * count_three_difference
print(calculate_differences(set_sorted))
|
def make_prime_generator():
n= 2
def primes():
nonlocal n
found_prime = False
while not found_prime:
n += 1
found_prime = True
for i in range(2,n):
if n % i == 0:
found_prime = False
return n
return primes
|
# CS 61A Fall 2014
# Name: Kevin L. Chen
# Login: cs61a-sj
def interval(a, b):
"""Construct an interval from a to b."""
"*** YOUR CODE HERE ***"
if type(a) != int or type(b) != int:
return [a,b]
return range(a,b+1)
def lower_bound(x):
"""Return the lower bound of interval x."""
"*** YOUR CODE HERE ***"
return x[0]
def upper_bound(x):
"""Return the upper bound of interval x."""
"*** YOUR CODE HERE ***"
return x[-1]
def str_interval(x):
"""Return a string representation of interval x.
>>> str_interval(interval(-1, 2))
'-1 to 2'
"""
return '{0} to {1}'.format(lower_bound(x), upper_bound(x))
def add_interval(x, y):
"""Return an interval that contains the sum of any value in interval x and
any value in interval y.
>>> str_interval(add_interval(interval(-1, 2), interval(4, 8)))
'3 to 10'
"""
lower = lower_bound(x) + lower_bound(y)
upper = upper_bound(x) + upper_bound(y)
return interval(lower, upper)
def mul_interval(x, y):
"""Return the interval that contains the product of any value in x and any
value in y.
>>> str_interval(mul_interval(interval(-1, 2), interval(4, 8)))
'-8 to 16'
"""
p1 = lower_bound(x) * lower_bound(y)
p2 = lower_bound(x) * upper_bound(y)
p3 = upper_bound(x) * lower_bound(y)
p4 = upper_bound(x) * upper_bound(y)
return interval(min(p1, p2, p3, p4), max(p1, p2, p3, p4))
def div_interval(x, y):
"""Return the interval that contains the quotient of any value in x divided
by any value in y.
Division is implemented as the multiplication of x by the reciprocal of y.
>>> str_interval(div_interval(interval(-1, 2), interval(4, 8)))
'-0.25 to 0.5'
"""
"*** YOUR CODE HERE ***"
assert 0 not in y , "y cannot span 0"
reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))
return mul_interval(x, reciprocal_y)
def sub_interval(x, y):
"""Return the interval that contains the difference between any value in x
and any value in y.
>>> str_interval(sub_interval(interval(-1, 2), interval(4, 8)))
'-9 to -2'
"""
"*** YOUR CODE HERE ***"
lower = lower_bound(x) - lower_bound(y)
lower1 = upper_bound(x) - lower_bound(y)
lower2 = lower_bound(x) - upper_bound(y)
lower3 = upper_bound(x) - upper_bound(y)
lower = min(lower, lower1, lower2, lower3)
upper = max(lower, lower1, lower2, lower3)
return interval(lower, upper)
def par1(r1, r2):
return div_interval(mul_interval(r1, r2), add_interval(r1, r2))
def par2(r1, r2):
one = interval(1, 1)
rep_r1 = div_interval(one, r1)
rep_r2 = div_interval(one, r2)
return div_interval(one, add_interval(rep_r1, rep_r2))
# These two intervals give different results for parallel resistors:
"*** YOUR CODE HERE ***"
r1 = interval(499,501)
r2 = interval(498,502)
def multiple_references_explanation():
return """The mulitple reference problem says that if the same interval is called many times,
then there will be more error than if you called the interval fewer times. The error
from the interval compounds when the interval is called multiple times. This is why
par2 is more accurate than par1."""
from math import sqrt
def quadratic(x, a, b, c):
"""Return the interval that is the range of the quadratic defined by
coefficients a, b, and c, for domain interval x.
>>> str_interval(quadratic(interval(0, 2), -2, 3, -1))
'-3 to 0.125'
>>> str_interval(quadratic(interval(1, 3), 2, -3, 1))
'0 to 10'
"""
"*** YOUR CODE HERE ***"
extreme = b*b/(4*a) + c - b*b/(2*a)
if a > 0:
if (-b + sqrt(b*b - 4*a*(c-extreme)))/(2*a) < lower_bound(x) or (-b - sqrt(b*b - 4*a*(c-extreme)))/(2*a) < lower_bound(x):
t = lower_bound(x)
return interval(a*t*t+b*t+c,max(a*t*t+b*t+c for t in x))
else:
return interval(b*b/(4*a) + c - b*b/(2*a), max(a*t*t+b*t+c for t in x))
else:
if (-b + sqrt(b*b - 4*a*(c-extreme)))/(2*a) > upper_bound(x) or (-b - sqrt(b*b - 4*a*(c-extreme)))/(2*a) > upper_bound(x):
t = upper_bound(x)
return interval(min(a*t*t+b*t+c for t in x),a*t*t+b*t+c)
else:
return interval(min(a*t*t+b*t+c for t in x),b*b/(4*a) + c - b*b/(2*a))
# def polynomial(x, c):
# """Return the interval that is the range of the polynomial defined by
# coefficients c, for domain interval x.
# >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2]))
# '-3 to 0.125'
# >>> str_interval(polynomial(interval(1, 3), [1, -3, 2]))
# '0 to 10'
# >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3]))
# '18.0 to 23.0'
# """
# "*** YOUR CODE HERE ***"
|
#
# @lc app=leetcode id=67 lang=python3
#
# [67] Add Binary
#
# https://leetcode.com/problems/add-binary/description/
#
# algorithms
# Easy (38.13%)
# Total Accepted: 281K
# Total Submissions: 736.8K
# Testcase Example: '"11"\n"1"'
#
# Given two binary strings, return their sum (also a binary string).
#
# The input strings are both non-empty and contains only characters 1 or 0.
#
# Example 1:
#
#
# Input: a = "11", b = "1"
# Output: "100"
#
# Example 2:
#
#
# Input: a = "1010", b = "1011"
# Output: "10101"
#
#
class Solution:
def addBinary1(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, 2))[2:]
def addBinary(self, a: str, b: str) -> str:
if len(a) < len(b):
temp = b
b = a
a = temp
b = '0' * (len(a) - len(b)) + str(b)
jinwei = False
re = ''
for i,j in zip(a[::-1], b[::-1]):
temp = int(i) + int(j)
if jinwei:
temp += 1
if temp > 1:
jinwei = True
re += str(temp - 2)
else:
jinwei = False
re += str(temp)
if jinwei:
re += '1'
return re[::-1]
if __name__ == "__main__":
s = Solution()
print(s.addBinary('11', '1'))
|
from typing import *
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
nums = list(range(1, k+1)) + [n + 1]
output, j = [], 0
while j < k:
output.append(nums[:k])
j = 0
while j < k and nums[j + 1] == nums[j] + 1:
nums[j] = j + 1
j += 1
nums[j] += 1
return output
s = Solution()
print(s.combine(4, 3))
s = {'aa':'b'}
print(s.pop('aa')) |
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# t = sorted(nums1[:m]+nums2)
# for i in range(len(t)):
# nums1[i] = t[i]
j = 0
for i in range(n):
num = nums2[i]
while nums1[j] <= num and j < m + i:
j += 1
nums1.insert(j, num)
j += 1
nums1.pop(-1)
|
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# This is basically a binary search
# Transfer to 2D array
arr = []
for i in matrix:
for j in i:
arr.append(j)
l, r = 0 , len(arr)
if r==1 and arr[0]==target:
return True
if r==1 and arr[0]!=target:
return False
if r==0:
return
while l + 1 < r:
mid = (l+r) // 2
if arr[mid] > target:
r = mid
elif arr[mid] < target:
l = mid
else:
return True
return arr[l]==target
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Do in order traversal. The in order traversal is monotonically increase
# O(1) Space, can not use iterative method or recursive solution, both use space
# class Solution(object):
# first = TreeNode(None)
# second = TreeNode(None)
# prev = TreeNode(None)
# def recoverTree(self, root):
# """
# :type root: TreeNode
# :rtype: None Do not return anything, modify root in-place instead.
# """
# # Recursion Method
# if root is None:
# return
# def helper(self, curr):
# if curr is None:
# return
# helper(curr.left)
# if prev is not None and prev.val >= curr.val:
# # have mistake first is the prev node, second is the curr node
# Morris Traversal O(1) solution
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
first = TreeNode(None)
second = TreeNode(None)
prev = TreeNode(-float('inf'))
firstTime = True
# Recursion Method
while root is not None:
if root.left is not None:
temp = root.left
while temp.right is not None and temp.right is not root:
temp = temp.right
if temp.right is None:
temp.right = root
root = root.left
else:
temp.right = None
if prev.val > root.val and firstTime:
first = prev
firstTime = False
if prev.val > root.val and not firstTime:
second = root
prev = root
root = root.left
else:
# visit root.val
if prev.val > root.val and firstTime:
first = prev
firstTime = False
if prev.val > root.val and not firstTime:
second = root
prev = root
root = root.right
# Now we can swap
if first is not None and second is not None:
val = first.val
first.val = second.val
second.val = val
class Solution(object):
def recoverTree(self, root):
"""
Do not return anything, modify root in-place instead.
"""
point = root
last = None # last point
big = None
small = None
while point:
if point.left is None:
# visit
if last and last.val > point.val:
if big is None:
big = last
small = point
last = point
# end visit
point = point.right
else:
pre = point.left
while pre.right and pre.right is not point:
pre = pre.right
if pre.right is None:
pre.right = point
point = point.left
else:
pre.right = None
# visit
if last and last.val > point.val:
if big is None:
big = last
small = point
last = point
# end visit
point = point.right
big.val, small.val = small.val, big.val |
string = 'aabbcddcef'
def delete_char(string):
try:
print(string[0] == string[0+1])
for i in range(len(string)):
if(string[i] == string[i+1]):
print(string)
string = string[:i] + string[i+2:]
return True, string
except IndexError:
print('DONE')
return False, string
t = delete_char(string)
while t:
t, string = delete_char(string)
print(string) |
class Solution:
# Solution 1, similar to find the pivot solution
def find_pivot(self, nums):
if len(nums) <= 2:
return nums.index(min(nums))
left, right = 0, len(nums) - 1
while right > left:
if right - left == 1:
return nums.index(min(nums[left:right+1]))
mid = (left + right) // 2
if nums[mid] < nums[right]: # Pivot is in mid to right
right = mid
else:
left = mid
# print(nums[left], nums[right], left, right)
return -1
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
idx = self.find_pivot(nums)
return nums[idx]
# Solution 2
def findMin2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo, hi = 0, len(nums)-1
while lo < hi - 1:
m = (lo+hi)//2
if nums[m] <= nums[hi]:
hi = m
elif nums[lo] <= nums[m]:
lo = m
return min(nums[lo], nums[hi]) |
import os
import csv
from operator import itemgetter
months = 0
revenue = 0
changeinmonth = []
monthChanges = []
csvpath = os.path.join('..', 'Resources', 'budget_data.csv')
#budget_data
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# read CSV file & load into list
CSVlist = list(csvreader)
#Total Months
months = len(CSVlist) - 1
# loop through range 1 to number of items in list
for row in range(1, len(CSVlist)):
#Total Revenue
revenue = revenue + int(CSVlist[row][1])
# loop through range 1 to number of items in list less one
for row in range(1, len(CSVlist)-1):
# First Month of Revenue
month1 = int(CSVlist[row][1])
# Next Month of Revenue
month2 = int(CSVlist[row+1][1])
# Append the result of Month 2 - Month 1 to "Change in Month" List
delta = month2-month1
changeinmonth.append(delta)
# declaring successor month to variable
monthName = CSVlist[row+1][0]
# declaring dictionary of month and delta
monthData = { "month" : monthName, "delta" : delta}
# Append dictionary to list
monthChanges.append(monthData)
# The average change in "Profit/Losses" between months over the entire period
avemonth = round(sum(changeinmonth)/(months-1), 2)
# sort the list of dictionary by the property 'delta'
monthChanges = sorted(monthChanges, key=itemgetter('delta'))
first = monthChanges[0]
last = monthChanges[-1]
print("Financial Analysis")
print("--------------------------")
print ("Total Months:", months)
print ("Total Revenue: $" + str(revenue))
print ("Average Revenue Change: $" + str(avemonth))
print ("Greatest Increase in Profits: " + last["month"] + "($" + str(last["delta"]) + ")")
print ("Greatest Decrease in Profits: " + first["month"] + "($" + str(first["delta"]) + ")")
# Set variable for output file
output_file = os.path.join("pybank.csv")
with open(output_file, 'w') as csvfile:
csvfile.writelines('Financial Analysis \n------------------------- \nTotal Months: ' + str(months) +
'\nTotal Revenue: $' + str(revenue) + '\nAverage Revenue Change: $' + str(avemonth) +
'\nGreatest Increase in Profits: ' + last["month"] + " ($" + str(last["delta"]) + ")" +
'\nGreatest Decrease in Profits: ' + first["month"] + " ($" + str(first["delta"]) + ")" )
|
import turtle as t
scale = 100
def move_to(x, y):
t.penup()
t.goto(x, y)
t.pendown()
def draw_kiyeok(xs = 1):
x,y = t.pos()
t.pendown()
t.setheading(0)
t.forward(scale * xs)
t.right(100)
t.forward(scale / 2)
move_to(x, y)
def draw_nieun(xs = 1):
x, y = t.pos()
t.pendown()
t.setheading(270)
t.forward(scale / 2)
t.left(90)
t.forward(scale * xs)
move_to(x, y)
def draw_digeut(xs = 1):
x, y = t.pos()
t.setheading(180)
t.penup()
t.backward(scale * xs)
t.pendown()
t.forward(scale * xs)
t.left(90)
t.forward(scale / 2)
t.left(90)
t.forward(scale * xs)
move_to(x, y)
def draw_rieul(xs = 1):
x, y = t.pos()
t.pendown()
t.setheading(0)
t.forward(scale * xs)
t.right(90)
t.forward(scale / 3)
t.right(90)
t.forward(scale * xs)
t.left(90)
t.forward(scale / 3)
t.left(90)
t.forward(scale * xs)
move_to(x, y)
def draw_mieum(xs = 1):
x, y = t.pos()
t.pendown()
t.setheading(0)
t.forward(scale * xs)
t.right(90)
t.forward(scale / 2)
t.right(90)
t.forward(scale * xs)
t.right(90)
t.forward(scale / 2)
move_to(x, y)
def draw_bieup(xs = 1):
x, y = t.pos()
t.pendown()
t.setheading(270)
t.forward(scale * 0.6)
t.left(90)
t.forward(scale * xs)
t.left(90)
t.forward(scale * 0.6)
t.backward(scale * 0.2)
t.left(90)
t.forward(scale * xs)
move_to(x, y)
def draw_siot(xs = 1):
x, y = t.pos()
y2 = y - scale * 0.6
move_to(x, y2)
t.goto(x + scale * xs / 2, y)
t.goto(x + scale * xs, y2)
move_to(x, y)
def draw_ieung(xs = 1):
x, y = t.pos()
move_to(x + scale * xs * 0.5, y - scale * 0.8)
t.setheading(0)
t.circle(scale * 0.4)
move_to(x, y)
def draw_jieut(xs = 1):
x, y = t.pos()
t.pendown()
t.setheading(0)
t.forward(scale * xs)
y2 = y - scale * 0.6
move_to(x, y2)
t.goto(x + scale * xs * 0.5, y)
t.goto(x + scale * xs, y2)
move_to(x, y)
def draw_chieut(xs = 1):
x, y = t.pos()
y1 = y - scale * 0.2
move_to(x, y1)
t.pendown()
t.setheading(0)
t.forward(scale * xs)
y2 = y - scale * 0.6
move_to(x, y2)
t.goto(x + scale * xs * 0.5, y1)
t.setheading(90)
t.forward(scale * 0.2)
t.backward(scale * 0.2)
t.goto(x + scale * xs, y2)
move_to(x, y)
def draw_kieuk(xs = 1):
x,y = t.pos()
t.pendown()
t.setheading(0)
t.forward(scale * xs)
t.right(100)
t.forward(scale / 2)
t.penup()
t.backward(scale / 4)
t.pendown()
_, y2 = t.pos()
t.setheading(180)
t.goto(x, y2)
move_to(x, y)
def draw_tieut(xs = 1):
x, y = t.pos()
t.setheading(180)
t.penup()
t.backward(scale * xs)
t.pendown()
t.forward(scale * xs)
t.left(90)
t.forward(scale * 0.6)
t.left(90)
t.forward(scale * xs)
y2 = y - scale * 0.3
move_to(x, y2)
t.forward(scale * xs)
move_to(x, y)
def draw_pieup(xs = 1):
x, y = t.pos()
x1 = x + scale * xs * 0.3
x2 = x + scale * xs * 0.7
y2 = y - scale * 0.6
t.pendown()
t.setheading(0)
t.forward(scale * xs)
move_to(x, y2)
t.forward(scale * xs)
move_to(x1, y)
t.goto(x1, y2)
move_to(x2, y)
t.goto(x2, y2)
move_to(x, y)
def draw_hieut(xs = 1):
x, y = t.pos()
t.penup()
t.setheading(0)
t.forward(scale * xs * 0.4)
t.pendown()
t.forward(scale * xs * 0.2)
move_to(x + scale * xs * 0.2, y - scale * 0.1)
t.forward(scale * xs * 0.6)
move_to(x + scale * xs * 0.5, y - scale * 0.8)
t.circle(scale * 0.3)
move_to(x, y)
def draw_double(cons1, cons2):
x, y = t.pos()
cons1(0.5)
t.setheading(0)
t.penup()
t.forward(scale * 0.6)
cons2(0.5)
move_to(x, y)
def draw_dbl_kiyeok():
draw_double(draw_kiyeok, draw_kiyeok)
def draw_dbl_digeut():
draw_double(draw_digeut, draw_digeut)
def draw_dbl_bieup():
draw_double(draw_bieup, draw_bieup)
def draw_dbl_siot():
draw_double(draw_siot, draw_siot)
def draw_dbl_jieut():
draw_double(draw_jieut, draw_jieut)
def draw_kiyeok_siot():
draw_double(draw_kiyeok, draw_siot)
def draw_nieun_jieut():
draw_double(draw_nieun, draw_jieut)
def draw_nieun_hieot():
draw_double(draw_nieun, draw_hieut)
def draw_rieul_kiyeok():
draw_double(draw_rieul, draw_kiyeok)
def draw_rieul_mieum():
draw_double(draw_rieul, draw_mieum)
def draw_rieul_bieup():
draw_double(draw_rieul, draw_bieup)
def draw_rieul_siot():
draw_double(draw_rieul, draw_siot)
def draw_rieul_tieut():
draw_double(draw_rieul, draw_tieut)
def draw_rieul_pieup():
draw_double(draw_rieul, draw_pieup)
def draw_rieul_hieut():
draw_double(draw_rieul, draw_hieut)
def draw_bieup_siot():
draw_double(draw_bieup, draw_siot)
def draw_a():
x, y = t.pos()
x2 = x + scale * 1.5
move_to(x2, y)
t.goto(x2, y - scale)
t.setheading(0)
move_to(x2, y - scale * 0.5)
t.forward(scale * 0.2)
move_to(x, y)
def draw_ya():
x, y = t.pos()
x2 = x + scale * 1.5
move_to(x2, y)
t.goto(x2, y - scale)
t.setheading(0)
move_to(x2, y - scale * 0.4)
t.forward(scale * 0.2)
move_to(x2, y - scale * 0.6)
t.forward(scale * 0.2)
move_to(x, y)
def draw_eo():
x, y = t.pos()
x2 = x + scale * 1.5
move_to(x2, y)
t.goto(x2, y - scale)
t.setheading(180)
move_to(x2, y - scale * 0.5)
t.forward(scale * 0.2)
move_to(x, y)
def draw_yeo():
x, y = t.pos()
x2 = x + scale * 1.5
move_to(x2, y)
t.goto(x2, y - scale)
t.setheading(180)
move_to(x2, y - scale * 0.4)
t.forward(scale * 0.2)
move_to(x2, y - scale * 0.6)
t.forward(scale * 0.2)
move_to(x, y)
def draw_o():
x, y = t.pos()
y2 = y - scale * 1.15
move_to(x, y2)
t.setheading(0)
t.forward(scale)
t.backward(scale * 0.5)
t.left(90)
t.forward(scale * 0.2)
move_to(x, y)
def draw_yo():
x, y = t.pos()
y2 = y - scale * 1.15
move_to(x, y2)
t.setheading(0)
t.forward(scale)
t.backward(scale * 0.6)
t.left(90)
t.forward(scale * 0.2)
move_to(x + scale * 0.6, y2)
t.forward(scale * 0.2)
move_to(x, y)
def draw_u():
x, y = t.pos()
y2 = y - scale * 1.15
move_to(x, y2)
t.setheading(0)
t.forward(scale)
t.backward(scale * 0.5)
t.right(90)
t.forward(scale * 0.2)
move_to(x, y)
def draw_yu():
x, y = t.pos()
y2 = y - scale * 1.15
move_to(x, y2)
t.setheading(0)
t.forward(scale)
t.backward(scale * 0.6)
t.right(90)
t.forward(scale * 0.2)
move_to(x + scale * 0.6, y2)
t.forward(scale * 0.2)
move_to(x, y)
def draw_eu():
x, y = t.pos()
y2 = y - scale * 1.25
move_to(x, y2)
t.setheading(0)
t.forward(scale)
move_to(x, y)
def draw_i():
x, y = t.pos()
x2 = x + scale * 1.5
move_to(x2, y)
t.goto(x2, y - scale)
move_to(x, y)
def draw_ae():
draw_a()
t.setheading(0)
t.penup()
t.forward(scale * 0.2)
draw_i()
def draw_yae():
draw_ya()
t.setheading(0)
t.penup()
t.forward(scale * 0.2)
draw_i()
def draw_e():
draw_eo()
t.setheading(0)
t.penup()
t.forward(scale * 0.1)
draw_i()
def draw_ye():
draw_yeo()
t.setheading(0)
t.penup()
t.forward(scale * 0.1)
draw_i()
def draw_wa():
draw_o()
draw_a()
def draw_wae():
draw_o()
draw_ae()
def draw_oi():
draw_o()
draw_i()
def draw_weo():
draw_u()
draw_eo()
def draw_we():
draw_u()
draw_e()
def draw_wi():
draw_u()
draw_i()
def draw_eui():
draw_eu()
draw_i()
def draw_final(func = None):
x, y = t.pos()
if func != None:
move_to(x, y - scale * 1.5)
func()
move_to(x + scale * 2, y)
chosung = [
draw_kiyeok, draw_dbl_kiyeok, draw_nieun, draw_digeut,
draw_dbl_digeut, draw_rieul, draw_mieum, draw_bieup,
draw_dbl_bieup, draw_siot, draw_dbl_siot, draw_ieung,
draw_jieut, draw_dbl_jieut, draw_chieut, draw_kieuk,
draw_tieut, draw_pieup, draw_hieut
]
joongsung = [
draw_a, draw_ae, draw_ya, draw_yae,
draw_eo, draw_e, draw_yeo, draw_ye,
draw_o, draw_wa, draw_wae, draw_oi,
draw_yo, draw_u, draw_weo, draw_we,
draw_wi, draw_yu, draw_eu, draw_eui,
draw_i
]
jongsung = [
None, draw_kiyeok, draw_dbl_kiyeok, draw_kiyeok_siot,
draw_nieun, draw_nieun_jieut, draw_nieun_hieot,
draw_digeut, draw_rieul,
draw_rieul_kiyeok, draw_rieul_mieum, draw_rieul_bieup, draw_rieul_siot,
draw_rieul_tieut, draw_rieul_pieup, draw_rieul_hieut,
draw_mieum, draw_bieup, draw_bieup_siot,
draw_siot, draw_dbl_siot, draw_ieung, draw_jieut, draw_chieut,
draw_kieuk, draw_tieut, draw_pieup, draw_hieut
]
def draw_ustr(str):
ox,oy = t.pos()
for ch in str:
char = ord(ch)
if char >= 0xAC00 and char <= 0xDCAF:
order = char - 0xAC00
cho = order // (21 * 28)
joong = order % (21 * 28) // 28
jong = order % 28
chosung[cho]()
joongsung[joong]()
draw_final(jongsung[jong])
elif char == 0x0A:
oy -= 3 * scale
move_to(ox, oy)
else:
x,y = t.pos()
move_to(x + scale, y) |
import ctypes
def make_array(size):
return (size * ctypes.py_object)()
arr = make_array(5)
# for i in range(5):
# arr[i] = i*i
arr = [None]*5
print(arr[2])
# for i in range(5):
# print(arr[i])
# class Node:
# def __init__(self, val):
# self.value = val
# self.rightChild = None
# self.leftChild = None
#
# def __str__(self):
# node_str = "Node has the value : " + str(self.value)
#
# if self.rightChild:
# node_str += "\nRight Child: " + str(self.rightChild.value)
#
# if self.leftChild:
# node_str += "\nLeft Child: " + str(self.leftChild.value)
# return node_str
#
# class BST:
#
# def __init__(self):
# self.root = None
#
# def addNode(self,val):
#
# if self.root == None:
# self.root = Node(val)
# return
#
# self._addNode(self.root,val)
#
# def _addNode(self,root,val): # <-------------- Recursive traversal
# if root == None:
# return Node(val)
#
# if val > root.value:
# if not root.rightChild:
# root.rightChild = self._addNode(root.rightChild,val)
# else:
# self._addNode(root.rightChild, val)
#
# elif val < root.value:
# if not root.leftChild:
# root.leftChild = self._addNode(root.leftChild,val)
# else:
# self._addNode(root.leftChild, val)
#
#
# def printBST(self):
# if not self.root:
# return
# self._printBST(self.root)
#
# def _printBST(self,root): # <-------------- Recursive traversal
# if root:
# print(str(root.value))
# self._printBST(root.leftChild)
#
# self._printBST(root.rightChild)
#
# def getNodeCount(root,count,nodes):
# if root:
# nodes[count] = root
# count += 1
# count = getNodeCount(root.leftChild,count,nodes)
# count = getNodeCount(root.rightChild,count,nodes)
# return count
#
#
# tree = BST()
# tree.addNode(10)
# tree.addNode(9)
# tree.addNode(3)
# tree.addNode(4)
# tree.addNode(5)
# tree.addNode(7)
# tree.addNode(6)
# tree.addNode(1)
# tree.addNode(20)
# tree.addNode(30)
# tree.addNode(40)
#
# nodes = []
# count = getNodeCount(tree.root,0,nodes)
# print(count, nodes) |
class Node:
def __init__(self,val):
self.value = val
self.next = None
def __str__(self):
return "value : %d" % self.value
node = Node(1)
node.next = Node(5)
node.next.next = Node(3)
node.next.next.next = Node(2)
node.next.next.next.next = Node(4)
node.next.next.next.next.next = Node(7)
node.next.next.next.next.next.next = Node(9)
def findMthElement(node,m):
# Edge Case
if node is None:
return
# Preserving the head
head = node
curr = head
prev = None
counter = 0
# Approach 1 => Find Length of LinkedList , 'l' and then calculate 'm' th element, and then traverse again 'l-m' elements to find the node
# This is O(n) + O(n) = O(2n) approach, might be inefficient for really long linkedList
# We can have better approach
# Approach 2 => Have 2 pointers. One following the other m nodes behind.
#
while curr:
if counter == m:
prev = head
if counter > m:
prev = prev.next
curr = curr.next
counter += 1
if not prev:
return None
return prev
print(findMthElement(node,7))
|
def partition(slist, low , high):
if low < high:
i = (low - 1)
pivot = slist[high]
for j in range(low,high):
if slist[j] <= pivot:
i+= 1
slist[i],slist[j] = slist[j],slist[i]
slist[i+1],slist[high] = slist[high],slist[i+1]
return (i+1)
def quicksort(slist,low,high):
if low < high:
pi = partition(slist,low,high)
quicksort(slist,low,pi-1)
quicksort(slist,pi+1,high)
def sortString(s):
slist = []
n = 0
for i in s:
slist.append(ord(i))
n += 1
quicksort(slist,0,n-1)
for i in range(n):
slist[i] = chr(slist[i])
return "".join(slist)
name = "Rahulisgreat"
sorted_name = sortString(name)
print(sorted_name == "".join(sorted(name)))
|
# Assignment 4
# Hangman Plus
# Anthony Swift
import random
WORDS = ( "PYTHON", "ESTIMATE", "DIFFICULT", "ANSWER", "XYLOPHONE", \
"UNNECESSARY", "ADEQUATE", "FEASIBLE", "CHARACTER", \
"CONGRATULATIONS", "SEQUENCE", "POSITION", "PROGRAM" )
MAX_WRONG = 6;
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []
def displayScaffold(wrong):
#Displays appropriate scaffold based on how many guesses the player has got wrong
if wrong == 0:
print("""
----------
|/ |
|
|
|
|
---
""")
if wrong == 1:
print("""
----------
|/ |
| 0
|
|
|
---
""")
if wrong == 2:
print("""
----------
|/ |
| 0
| |
|
|
---
""")
if wrong == 3:
print("""
----------
|/ |
| 0
| /|
|
|
---
""")
if wrong == 4:
print("""
----------
|/ |
| 0
| /|/
|
|
---
""")
if wrong == 5:
print("""
----------
|/ |
| 0
| /|/
| /
|
---
""")
if wrong == 6:
print("""
----------
|/ |
| 0
| /|/
| / /
|
---
""")
print("\nWelcome to Hangman.")
displayScaffold(wrong)
print("\nYou have", MAX_WRONG, "wrong attempts to guess the word.")
while wrong < MAX_WRONG and so_far != word:
print("\n", so_far, "\n")
guess=input("Enter a letter: ")
guess=guess.upper()
while guess in used:
print("\nYou have already guessed this letter\a", guess)
guess=input("Enter a letter: ")
guess=guess.upper()
used.append(guess)
if guess in word:
print("\nYes,", guess, "is in the word.")
displayScaffold(wrong)
new=""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
else:
print("\nSorry,", guess, "isn't in the word.\a")
wrong += 1
left = MAX_WRONG - wrong
displayScaffold(wrong)
print("\nYou have", left, "guesses left.")
if wrong == MAX_WRONG:
print("\nYou've been hanged!\a")
else:
print("\nYou guessed it!\a")
print("\nThe word was", word)
|
# -*- coning:utf-8 -*-
# 迭代器
class Fib():
def __init__(self):
self.a, self.b = 0, 1
# 实现了__iter__方法的对象是可迭代的
def __iter__(self):
return self
# 实现了__next__()方法的对象是迭代器
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 100:
raise StopIteration()
return self.a # 返回下一个值
class Student(object):
"""
learn class objects
"""
# 类变量
describe = 'say hello...'
# 属性限制。表示类只能绑定__slots__中含有的属性。对继承的子类不起作用
__slots__ = ['name', '_age', '_city']
def __init__(self, name, age, city): # self 参数代表示例,使用时自动传入
# 实例变量
self.name = name # greet在__slots__中
self._age = age
self._city = city
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if isinstance(value, int):
self._age = value
else:
raise ValueError('must be an integer!')
@property
def city(self): # 只读属性
return self._city
s1 = Student('Bill', 17, 'shanghai')
# s1.age = '16' # ValueError: must be an integer!
# s1.city = 'beijing' # AttributeError: can't set attribute
print(s1.name, s1.age, s1.city)
class A(object):
def __init__(self, name):
self.name = name
print(A('Bill'))
class A(object):
def __init__(self, name):
self.name = name
# 调试使用
# def __repr__(self):
# return 'College'
# print打印显示
def __str__(self):
return 'College'
print(A('Bill'))
# __getattr__:动态的处理属性
class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
print(Chain().status.list.time.mp4) # .status、list、time、mp4 实例属性
# __call__:可以对示例直接进行调用
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self):
print('My name is %s.' % self.name)
s = Student('Bill')
s()
# 枚举类
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
# type()动态创建类
# type() 函数可以返回一个类型或变量的类型,又可以创建出新的类型。
# Hello 是一个class,它的类型就是type,
# s 是一个实例,它的类型就是‘class Student’
class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name)
h = Hello()
print(type(Hello)) # <class 'type'>
print(type(h)) # <class '__main__.Hello'>
# type 动态创建类需要三个参数:
# a. class 名称
# b. 继承的父类,tuple单元素写法
# c. class的方法名称与函数绑定
def fn(self, name='world'):
print('Hello, %s.' % name)
Hello = type('Hello', (object,), dict(hello=fn))
h = Hello()
h.hello()
# metaclass():元类
# 太屌,,稍后学 |
# -*- coding:utf-8 -*-
"""
可迭代对象(Iterable):只要定义了__iter__()方法,我们就说该对象是可迭代对象,并且可迭代对象能提供迭代器。
a. 集合数据类型,如list、tuple、dict、set、str等;
b. 是generator,包括生成器和带yield的generator function。
迭代器、迭代对象 :实现了__next__()或者next()(python2)方法的称为迭代器,迭代器仅仅在迭代到某个元素时才计算该元素,
而在这之前或之后,元素可以不存在或者被销毁,因此只占用固定的内存。
'for' 语法糖:
在for循环中,Python将自动调用工厂函数iter()获得迭代器,自动调用next()获取元素,还完成了检查StopIteration异常的工作。
"""
# from collections import Iterable, Iterator
# 可迭代的
class MyRange(object):
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self): # 这个可迭代对象的的迭代对象就是它自身。这会导致一个问题,无法重复迭代,
return self
def __next__(self):
if self.idx < self.n:
val = self.idx
self.idx += 1
return val
else:
raise StopIteration()
m = MyRange(3)
for i in m:
print(i)
# 第二次执行时,无法迭代
for i in m:
print(i)
## 为什么使用迭代器?
# 代码1
# 直接在函数fab(max)中用print打印会导致函数的可复用性变差,因为fab返回None。其他函数无法获得fab函数返回的数列。
def fab(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
# 代码2
# 代码2满足了可复用性的需求,但是占用了内存空间。
def fab(max):
L = []
n, a, b = 0, 0, 1
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
# 代码3,定义并使用迭代器
# Fabs 类通过 next() 不断返回数列的下一个数,内存占用始终为常数
class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
for key in Fab(5):
print(key)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.