Posts

Showing posts from August, 2021

[LeetCode] #188. Best Time to Buy and Sell Stock IV

題目 You are given an integer array prices where prices[i] is the price of a given stock on the i th day, and an integer k . Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). 直覺解 構想: 先找出所有可以低買高賣的時機,再從這些時機裡面挑出 k 個。挑選方式:while 迴圈,每圈會減少一個時機,減少方式有兩種,合併兩個相鄰的時機,或移除一個時機。 python 3 實作(失敗): class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: profit = 0 if len(prices) < 2 or k == 0: return profit # find all best time to buy and sell stock start = 0 intervals = [] while start < len(prices): interval = self.find_buy_sell_interval(start, prices) if interval['buy'] is None or interval['sell'] is None: break interval['subtotal'] = prices[interval[

shop_platform - 新增種子資料時報錯

想完成的事 建立 user 的種子資料 遇到的問題,和解決過程 直接在 MySQL workbench 新增資料沒有問題,但是用 flask_seeder 新增資料會報錯。縮小範圍後,發現使用 flask_sqlalchemy 新增資料就會報錯。 錯誤訊息如下: Traceback (most recent call last): File "/Users/flora/.local/share/virtualenvs/shop_platform-9-YKR-2e/lib/python3.9/site-packages/sqlalchemy/orm/relationships.py", line 2744, in _determine_joins self.primaryjoin = join_condition( File "<string>", line 2, in join_condition File "/Users/flora/.local/share/virtualenvs/shop_platform-9-YKR-2e/lib/python3.9/site-packages/sqlalchemy/sql/selectable.py", line 1184, in _join_condition cls._joincond_trim_constraints( File "/Users/flora/.local/share/virtualenvs/shop_platform-9-YKR-2e/lib/python3.9/site-packages/sqlalchemy/sql/selectable.py", line 1305, in _joincond_trim_constraints raise exc.AmbiguousForeignKeysError( sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'user' and 'order'; tables have more tha

shop_platform - Composite Foreign Keys

想要達到的效果: 現有 order_item 這張表。現在要建立 rating table ,並且建立 order_item 和 rating 之間的 one-one relationship。但 order_item 的 primary key 是 composite primary key,同時有兩個 column 都是 primary key。不知道要怎麼在 rating 建立外鍵。 order_item 的程式碼: from app import db from datetime import datetime class OrderItem(db.Model): __tablename__ = 'order_item' order_id = db.Column(db.Integer, db.ForeignKey('order.id'), primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('product.id'), primary_key=True) price = db.Column(db.Integer, nullable=False) quantity = db.Column(db.Integer, nullable=False) insert_time = db.Column(db.DateTime, nullable=False, default=datetime.now) update_time = db.Column(db.DateTime, onupdate=datetime.now, nullable=False, default=datetime.now) order = db.relationship('Order', back_populates='products') product = db.relationship('Product', back_populates='orders') 參考資料 用「sqlalchemy foreign

shop_platform - flask db downgrade 遇到 TypeError

事發經過 發現建立 cart table 時,漏掉 user_id 這個 foreign key,所以幫 user 和 cart 兩張資料表補上 one-one relationship。 class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) display_name = db.Column(db.String(50), unique=True, nullable=False) email = db.Column(db.String(50), unique=True, nullable=False) password = db.Column(db.String(140), nullable=False) cell_phone = db.Column(db.String(20)) address = db.Column(db.String(100)) store_introduction = db.Column(db.String(2000)) role = db.Column(db.String(10), nullable=False, default='user') insert_time = db.Column(db.DateTime, nullable=False, default=datetime.now) update_time = db.Column(db.DateTime, onupdate=datetime.now, nullable=False, default=datetime.now) cart = db.relationship('Cart', back_populates='user', uselist=False) delivery_orders = db.relationship('Order', back_populates='seller') purchase_order = db.relati

[LeetCode] #1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

題目 Given an array nums and an integer target . Return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target . 直覺解 構想: 我把 non-overlapping subarray 理解為「nums 中的每個成員,最多只能用在一個 subarray 裡」(後來才發現不是這個意思⋯⋯做白工啊做白工 orz) 先找出所有 subarray,再過濾出 sum 等於 target 的 non-empty subarray,為了加快查詢速度,把過濾出來的 subarray 轉為 dictionary,key 是數字,value 是數字出現幾次。用 recursion 嘗試所有可能的 non-overlapping subarray 組合,找出 maximum number。 python 3 實作(失敗): class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int: sum_eq_target = [] for array in self.get_subarrays(nums): if array and sum(array) == target: map = {} for item in array: map[item] = map.get(item, 0) + 1 sum_eq_target.append(map) if not sum_eq_target: return 0 nums_map = {} for n in nums: nums_map[n] = nums_map.g

shop_platform - 建立多對多關聯:Association Object

根據 SQLAlchemy 的 Basic Relationship Patterns ,建立多對多關聯有兩種方式: join table 上只有外鍵欄位:使用 association table join table 上除了外鍵,還有其他欄位:使用 association object association object 不同欄位間的關係: class Association (Base):     __tablename__ = 'association'     left_id = Column(ForeignKey(' left.id '), primary_key=True)     right_id = Column(ForeignKey(' right.id '), primary_key=True)     extra_data = Column(String(50))     child = relationship(" Child ", back_populates=" parents ")     parent = relationship(" Parent ", back_populates=" children ") class Parent (Base):     __tablename__ = ' left '     id = Column(Integer, primary_key=True)     children = relationship(" Association ", back_populates=" parent ") class Child (Base):     __tablename__ = ' right '     id = Column(Integer, primary_key=True)     parents = relationship(" Association ", back_populates=" c

shop_platform - flask db init fails: KeyError 'migrate'

試著使用 Flask-Migrate 做 MySQL 的 migration。但是在終端機使用 flask db init 指令時失敗了。 程式碼: common/database.py: from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate db = SQLAlchemy() migrate = Migrate() app.py: import os from flask import Flask from dotenv import load_dotenv from common.database import db, migrate if os.environ.get('FLASK_ENV', '') != 'production': load_dotenv() app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') @app.route('/') def home(): return 'Hello World!' if __name__ == '__main__': db.init_app(app) migrate.init_app(app, db) app.run() 錯誤訊息: File "/Users/flora/.local/share/virtualenvs/shop_platform-9-YKR-2e/bin/flask", line 8, in <module> sys.exit(main()) File "/Users/flora/.local/share/virtualenvs/shop_platform-9-YKR

[LeetCode] #1553. Minimum Number of Days to Eat N Oranges

題目 There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges ( n ) is divisible by 2 then you can eat n/2 oranges. If the number of remaining oranges ( n ) is divisible by 3 then you can eat 2*(n/3) oranges. You can only choose one of the actions per day. Return the minimum number of days to eat n oranges. 直覺解 構想: 每天,看哪個方式可以吃最多橘子,就用那個吃法。但是這題是 Hard,總覺得事情沒有這麼簡單⋯⋯ python 3 實作(失敗): class Solution:     def minDays(self, n: int) -> int:         days = 0         while n > 0:             if n % 3 == 0:                 n = n // 3              elif n % 2 == 0:                 n = n >> 1             else:                 n -= 1             days += 1         return days Submission Detail Wrong Answer Input: 10 Output: 5 Expected: 4 失敗原因 我吃橘子的顆數是:5, 1, 2, 1, 1,花了五天。解答吃橘子的顆數是:1, 6, 2, 1,只花了四天。 並不是簡單的「每天都選三個方