diff --git a/javascript/LeetCode/Array/1464.js b/javascript/LeetCode/Array/1464.js index 9ca22bc..7bf4e7b 100644 --- a/javascript/LeetCode/Array/1464.js +++ b/javascript/LeetCode/Array/1464.js @@ -59,6 +59,15 @@ var maxProduct = function (nums) { return (lastNumber - 1) * (secondLastNumber - 1); + // solution 2. + // 取得第一、第二大value,並將該陣列做切割…只取前兩個 + // let sortNums = nums.sort((a,b) => b - a).slice(0,2); + // // 第一大元素 + // let i = sortNums[0]; + // // 第二大元素 + // let j = sortNums[1]; + // return (i - 1) * (j - 1); + }; const nums = [1, 5, 4, 5]; // return 16 diff --git a/javascript/LeetCode/Array/1572.js b/javascript/LeetCode/Array/1572.js index cdde1c5..89db497 100644 --- a/javascript/LeetCode/Array/1572.js +++ b/javascript/LeetCode/Array/1572.js @@ -1,52 +1,25 @@ -// 1572. Matrix Diagonal Sum -// return the sum of the matrix diagonals. 返回正方形中對角線的總和 -// sum X => -// primary: 1 + 5 + 9 -// secondary: 3 + 5 + 7 - -// 1. 是二維陣列 -// 2. 判斷陣列length是奇數或偶數,共有幾個二維陣列 -// 3. -// a.第一個二維陣列:找該array中位於第0個位置和最後一個位置的值,之後其他二維陣列則取往後移一個位置的值 -// b.最後一個二維陣列:找該array中位於第0個位置和最後一個位置的值 - -// 二維陣列 -// 判斷陣列length是奇數或偶數,共有幾個二維陣列 -// ==> 找第一個和最後一個二維陣列中,第0個位置和最後一個位置的值 -// 其他二維陣列則取往後移一個位置的值 - -/* -Input: mat = [[1,2,3], - [4,5,6], - [7,8,9]] -Output: 25 -Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 -Notice that element mat[1][1] = 5 is counted only once. -*/ - /** + * 1572. Matrix Diagonal Sum + * * @param {number[][]} mat * @return {number} */ -var diagonalSum = function (mat) { - +var diagonalSum = function(mat) { + // 二維陣列,裡面的陣列是奇數的,取該陣列偶數index值;裡面陣列是偶數的,取該陣列奇數index值 let result = 0; - let j = mat[0].length - 1; - for (let i = 0; i < mat.length; i++, j--) { - if (i !== j) { - result += mat[i][j]; - } - result += mat[i][i]; - - // $result += (i != j) ? mat[i][j] : mat[i][i]; - // let end = endTime(start); - // console.log(end); + let len = mat.length; + let mid = Math.floor(len / 2 ); + for (let i = 0; i < len; i++) { + result += mat[i][i]; + result += mat[len - 1 - i][i]; + } + if (len % 2 != 0) { + result -= mat[mid][mid]; } return result; }; -const arr = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] -]; -console.log(diagonalSum(arr)); \ No newline at end of file +let mat = [[1,2,3],[4,5,6],[7,8,9]]; +// Output: 25 +// Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 +// Notice that element mat[1][1] = 5 is counted only once. +console.log(diagonalSum(mat)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/1588.js b/javascript/LeetCode/Array/1588.js index d8c519d..425ed64 100644 --- a/javascript/LeetCode/Array/1588.js +++ b/javascript/LeetCode/Array/1588.js @@ -69,6 +69,17 @@ var sumOddLengthSubarrays = function (arr) { } } return count; + + // solution 2. + // let ans = 0; + // for(let i = 0;i < arr.length;++i) { + // let currentSum = 0; + // for(let j = i;j < arr.length;++j) { + // currentSum += arr[j]; + // ans += (j - i + 1) % 2 === 1 ? currentSum : 0; + // } + // } + // return ans; }; const arr = [1, 4, 2, 5, 3]; console.log(sumOddLengthSubarrays(arr)); diff --git a/javascript/LeetCode/Array/1980.js b/javascript/LeetCode/Array/1980.js new file mode 100644 index 0000000..6653c9b --- /dev/null +++ b/javascript/LeetCode/Array/1980.js @@ -0,0 +1,16 @@ +/** + * 1980. Find Unique Binary String + * + * @param {string[]} nums + * @return {string} + */ +var findDifferentBinaryString = function(nums) { + let res = ""; + for(let i = 0;i < nums.length;i++) { + res += (nums[i][i] === '0' ? '1' : '0'); + } + return res; +}; +let nums = ["01","10"]; +// "11" +// console.log(findDifferentBinaryString(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/math/165.js b/javascript/LeetCode/math/165.js new file mode 100644 index 0000000..48823b7 --- /dev/null +++ b/javascript/LeetCode/math/165.js @@ -0,0 +1,34 @@ +/** + * 165. Compare Version Numbers + * + * 參數為兩個字串,其內含有".",將參數依據"."拆成左右兩部份,從左到右比較每個部份大小。 + * + * If version1 < version2, return -1. + * If version1 > version2, return 1. + * Otherwise, return 0. + * + * 若部份的前面有0,則忽略0,取整數 + * + * @param {string} version1 + * @param {string} version2 + * @return {number} + */ +var compareVersion = function(version1, version2) { + let splitV1 = version1.split("."),splitV2 = version2.split("."); + let length = Math.max(splitV1.length, splitV2.length); + for(let i = 0;i < length;i++) { + let num1 = parseInt(splitV1[i]) || 0; + let num2 = parseInt(splitV2[i]) || 0; + + if(num1 === num2){ + continue; + } + return num1 > num2 ? 1 : -1; + } + return 0; +}; +// let version1 = "1.2", version2 = "1.10" +// -1 +let version1 = "1.01", version2 = "1.001"; +// 0 +console.log(compareVersion(version1,version2)) \ No newline at end of file diff --git a/javascript/LeetCode/math/3099.js b/javascript/LeetCode/math/3099.js new file mode 100644 index 0000000..281d65d --- /dev/null +++ b/javascript/LeetCode/math/3099.js @@ -0,0 +1,32 @@ +/** + * 3099. Harshad Number + * + * Harshad:能被其各位數字之和整除 + * 如果 x 是Harshad,則傳回 x 各位數字總和;否則,回傳 -1。 + * @param {number} x + * @return {number} + */ +var sumOfTheDigitsOfHarshadNumber = function(x) { + // let split = x.toString().split(""); + // let sum = 0; + // for(let i = 0;i < split.length;i++) { + // sum+=parseInt(split[i]); + // } + // if(x % sum === 0){ + // return sum; + // } + // return -1; + + // solution 2. + let ans = 0; + let temp = x; + while(temp > 0){ + // 取尾數 + ans += temp % 10; + temp = Math.floor(temp / 10); + } + return x % ans === 0 ? ans : -1; +}; +let x = 18; +// 9 +console.log(sumOfTheDigitsOfHarshadNumber(x)); \ No newline at end of file diff --git a/javascript/LeetCode/math/3602.js b/javascript/LeetCode/math/3602.js new file mode 100644 index 0000000..b123505 --- /dev/null +++ b/javascript/LeetCode/math/3602.js @@ -0,0 +1,21 @@ +/** + * 3602. Hexadecimal and Hexatrigesimal Conversion + * + * hexadecimal = base 16,使用數字0 - 9和大寫A - F代表0 - 15 + * hexatrigesimal = base 16,使用數字0 - 9和大寫A - Z代表0 - 35 + * 取得hexadecimal的n的二次方(n * 2)和hexatrigesimal的n的三次方(n * 3)串連 + * @param {number} n + * @return {string} + */ +var concatHex36 = function(n) { + return ((n ** 2).toString(16) + (n ** 3).toString(36)).toUpperCase(); +}; +let n = 36 +/** + * Output: "5101000" +n2 = 36 * 36 = 1296. In hexadecimal, it converts to (5 * 162) + (1 * 16) + 0 = 1296, which corresponds to "510". +n3 = 36 * 36 * 36 = 46656. In hexatrigesimal, it converts to (1 * 363) + (0 * 362) + (0 * 36) + 0 = 46656, which corresponds to "1000". +Concatenating both results gives "510" + "1000" = "5101000". + * +*/ +console.log(concatHex36(n)); \ No newline at end of file diff --git a/javascript/index.js b/javascript/index.js index 67404b1..f00c3fa 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1,4 +1,5 @@ // debugger +import { format } from 'node:path'; import {ExecutionTimer} from './time.js'; import assert from 'node:assert/strict'; @@ -1028,3 +1029,20 @@ var closetPair = function(arr1,arr2,x) { // [1,30]; // console.log(closetPair(arr1,arr2,x)); +/** + * 166. Fraction to Recurring Decimal + * + * 參數為分子、分母,以字串資料型態回傳分數 + * 如果小數部分重複,則將重複部分放在括號中。 + * 若有很多個答案,任一回傳 + * + * @param {number} numerator + * @param {number} denominator + * @return {string} + */ +var fractionToDecimal = function(numerator, denominator) { + +}; +let numerator = 1, denominator = 2; +// "0.5" +// console.log(fractionToDecimal(numerator,denominator)); \ No newline at end of file diff --git a/javascript/oop.js b/javascript/oop.js new file mode 100644 index 0000000..2078348 --- /dev/null +++ b/javascript/oop.js @@ -0,0 +1,5 @@ +// 具名匯出 (Named Export),使用{},匯出多個獨立的功能 +import { Vehicle } from "./oop/Vehicle.js "; + +car = new Vehicle("Ford","Kuga"); +console.log(car.startEngine()) \ No newline at end of file diff --git a/javascript/oop/1_basic_literals.js b/javascript/oop/1_basic_literals.js deleted file mode 100644 index 11078c6..0000000 --- a/javascript/oop/1_basic_literals.js +++ /dev/null @@ -1,32 +0,0 @@ -// 都一樣能達到同樣目的,卻得重複寫好幾次 -const book = { - title: 'Harry Poter', - author: 'JK.Rowling', - year: '1997', - getSumary: function () { - return `${this.title} was written by ${this.author} in ${this.year}.`; - }, - getBookAge: function () { - const years = new Date().getFullYear() - this.year; - return `${this.title} is ${years} old.`; - } -} - -const book2 = { - title: 'The Rock from the Sky', - author: 'Klassen, Jon', - year: '2021', - getSumary: function () { - return `${this.title} was written by ${this.author} in ${this.year}.`; - }, - getBookAge: function () { - const years = new Date().getFullYear() - this.year; - return `${this.title} is ${years} old.`; - } -} -// Instantiate an Obj. -console.log(book.title); -console.log(book.getBookAge()); - -console.log(book2.title); -console.log(book2.getBookAge()); diff --git a/javascript/oop/2_constructor.js b/javascript/oop/2_constructor.js deleted file mode 100644 index af059a9..0000000 --- a/javascript/oop/2_constructor.js +++ /dev/null @@ -1,14 +0,0 @@ -// Constructor -function Book(title, author, year) { - this.title = title; - this.author = author; - this.year = year; - - this.getSummary = function () { - return `${this.title} was written by ${this.author} in ${this.year}.`; - } -} - -// Instantiate an Obj. -const book1 = new Book('Daughter of the Deep', 'Rick Riordan', '2021'); -console.log(book1.getSummary()); \ No newline at end of file diff --git a/javascript/oop/3_prototypes.js b/javascript/oop/3_prototypes.js deleted file mode 100644 index 90e09fc..0000000 --- a/javascript/oop/3_prototypes.js +++ /dev/null @@ -1,16 +0,0 @@ -function Book(title, author, year) { - this.title = title; - this.author = author; - this.year = year; -} -Book.prototype.getSummary = function () { - return `${this.title} was written by ${this.author} in ${this.year}.`; -} -Book.prototype.getBookAge = function () { - const years = new Date().getFullYear() - this.year; - return `${this.title} is ${years} old.`; -} - -// Instantiate an Obj. -const book1 = new Book('Daughter of the Deep', 'Rick Riordan', '2021'); -console.log(book1.getSummary()); \ No newline at end of file diff --git a/javascript/oop/4_inheritence.js b/javascript/oop/4_inheritence.js deleted file mode 100644 index aee9392..0000000 --- a/javascript/oop/4_inheritence.js +++ /dev/null @@ -1,24 +0,0 @@ -function Book(title, author, year) { - this.title = title; - this.author = author; - this.year = year; -} -Book.prototype.getSummary = function () { - return `${this.title} was written by ${this.author} in ${this.year}.`; -} - -// Magazine constructor. -function Magazine(title, author, year, month) { - Book.call(this, title, author, year); - this.month = month; -} - -// Inherit Prototype -Magazine.prototype = Object.create(Book.prototype); - -// Use Magazine Constructor. -Magazine.prototype.constuctor = Magazine; - -// Instantiate an Magazine Obj. -const mag = new Magazine('Vogue', 'Eugenia de la Torriente', '1892', 'Dec.'); -console.log(mag.getSummary()); \ No newline at end of file diff --git a/javascript/oop/5_object_create.js b/javascript/oop/5_object_create.js deleted file mode 100644 index d31216e..0000000 --- a/javascript/oop/5_object_create.js +++ /dev/null @@ -1,24 +0,0 @@ -// Object of protos -const bookProtos = { - getSummary: function () { - return `${this.title} was written by ${this.author} in ${this.year}.`; - }, - getAge: function () { - const years = new Date().getFullYear() - this.year; - return `${this.title} is ${years} old.`; - } -} - -// Create Object. -// way 1. -// const book1 = Object.create(bookProtos); -// book1.title = 'Daughter of the Deep'; -// book1.author = 'Rick Riordan'; -// book1.year = '2021'; -// way 2. -const book1 = Object.create(bookProtos, { - title: { value: 'Daughter of the Deep' }, - author: { value: 'Rick Riordan' }, - year: { value: '2021' } -}); -console.log(book1); \ No newline at end of file diff --git a/javascript/oop/6_classes-ES6.js b/javascript/oop/6_classes-ES6.js deleted file mode 100644 index 6437cac..0000000 --- a/javascript/oop/6_classes-ES6.js +++ /dev/null @@ -1,25 +0,0 @@ -// 這一個OOP寫法和PHP物件導向比較類似,但其實是JS ES6語法糖的用法 -class Book { - constructor(title, author, year) { - this.title = title; - this.author = author; - this.year = year; - } - - getSummary() { - return `${this.title} was written by ${this.author} in ${this.year}.`; - } - - getBookAge() { - const years = new Date().getFullYear() - this.year; - return `${this.title} is ${years} old.`; - } - - static topSale() { - return 'Harray Potter'; - } -} -// Instantiate an Obj. -const book1 = new Book('Daughter of the Deep', 'Rick Riordan', '2021'); -console.log(book1.getBookAge()); -console.log(Book.topSale()); \ No newline at end of file diff --git a/javascript/oop/7_subclasses.js b/javascript/oop/7_subclasses.js deleted file mode 100644 index 2daec69..0000000 --- a/javascript/oop/7_subclasses.js +++ /dev/null @@ -1,28 +0,0 @@ -class Book { - constructor(title, author, year) { - this.title = title; - this.author = author; - this.year = year; - } - - getSummary() { - return `${this.title} was written by ${this.author} in ${this.year}.`; - } - - getBookAge() { - const years = new Date().getFullYear() - this.year; - return `${this.title} is ${years} old.`; - } -} - -// Magazie subclass -class Magazine extends Book { - constructor(title, author, year, month) { - super(title, author, year); - this.month = month; - } -} - -// Instantiate Obj. -const mag = new Book('Vogue', 'Eugenia de la Torriente', '1892'); -console.log(mag.getBookAge()); \ No newline at end of file diff --git a/javascript/oop/Vehicle .js b/javascript/oop/Vehicle .js new file mode 100644 index 0000000..925d9df --- /dev/null +++ b/javascript/oop/Vehicle .js @@ -0,0 +1,15 @@ +export class Vehicle { + /** + * + * @param {string} brand + * @param {string} type + */ + constructor(brand,type){ + this.brand = brand; + this.type = type; + } + + startEngine(){ + console.log(`This car is a ${this.brand} ${this.model}.`); + } +} \ No newline at end of file diff --git a/python/index.py b/python/index.py index 0c4be74..2b0efb1 100644 --- a/python/index.py +++ b/python/index.py @@ -8,10 +8,7 @@ python -V """ from math import sqrt -from operator import le from typing import List -import math - # from numpy import diff # module @@ -23,28 +20,25 @@ # oop # from file name(module) import the class. -from oop.Animals import Animals -from oop.Tortoises import Tortoises +from oop.Animal import Animal +from oop.Tortoise import Tortoise from oop.Lion import Lion +from oop.Behavior import move -greek = Tortoises("福氣","7個月大","veggie","地中海型陸龜") +greek = Tortoise("福氣",7,"veggie","地中海型陸龜") greek.eat() +greek.hibernation() greek.environment() +greek.attack() +greek.affend() +print(greek.specice) +print(greek.avgWeight(7,5)) -lion = Lion("獅子","未知","肉食") -lion.environment() - -# from oop.Fruit import Fruit -# from oop.Melon import Melon -# fruits = Fruit("Apple",3,5) -# print("價格:",f"{fruits.calculate()}") - -# fruits.make_watering() - -# v = Melon("西瓜",65,10,30) -# v.make_seedling() -# v.palnt() - +# lion = Lion("獅子","未知","肉食") +# lion.eat() +# lion.attack() +# # print(lion.food) +# lion.environment() ''' 1415. The k-th Lexicographical String of All Happy Strings of Length n @@ -82,135 +76,95 @@ 1 <= n <= 10 1 <= k <= 100 ''' - -''' -1980. Find Unique Binary String - -Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them. - -Hints: -1. We can convert the given strings into base 10 integers. -2. Can we use recursion to generate all possible strings? - -Example 1: -Input: nums = ["01","10"] -Output: "11" -Explanation: "11" does not appear in nums. "00" would also be correct. - -Example 2: - -Input: nums = ["00","01"] -Output: "11" -Explanation: "11" does not appear in nums. "10" would also be correct. - -Example 3: -Input: nums = ["111","011","001"] -Output: "101" -Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct. - - -Constraints: -n == nums.length -1 <= n <= 16 -nums[i].length == n -nums[i] is either '0' or '1'. -All the strings of nums are unique. -''' -# class Solution: -# def findDifferentBinaryString(self, nums: List[str]) -> str: +# def getHappyString(n: int, k: int) -> str: -# nums = ["111","011","001"] -# # 101 -# a = Solution() -# print(a.findDifferentBinaryString(nums)) -class Solution: +def getFinalState(nums: List[int], k: int, multiplier: int) -> List[int]: ''' - 3264. Final Array State After K Multiplication Operations I - - You are given an integer array nums, an integer k, and an integer multiplier. - You need to perform k operations on nums. In each operation: - Find the minimum value x in nums. If there are multiple occurrences of the minimum value, select the one that appears first. - Replace the selected minimum value x with x * multiplier. - Return an integer array denoting the final state of nums after performing all k operations. - - Hints: - 1. Maintain sorted pairs (nums[index], index) in a priority queue. - 2. Simulate the operation k times. - - Example 1: - Input: nums = [2,1,3,5,6], k = 5, multiplier = 2 - Output: [8,4,6,5,6] - Explanation: - Operation Result - After operation 1 [2, 2, 3, 5, 6] - After operation 2 [4, 2, 3, 5, 6] - After operation 3 [4, 4, 3, 5, 6] - After operation 4 [4, 4, 6, 5, 6] - After operation 5 [8, 4, 6, 5, 6] - - Example 2: - Input: nums = [1,2], k = 3, multiplier = 4 - Output: [16,8] - Explanation: - Operation Result - After operation 1 [4, 2] - After operation 2 [4, 8] - After operation 3 [16, 8] - - - Constraints: - 1 <= nums.length <= 100 - 1 <= nums[i] <= 100 - 1 <= k <= 10 - 1 <= multiplier <= 5 - - 3個參數:int array nums.int k & int multiplier - 需在nums上操作K次,每次找出nums中最小值X,若有重複多個最小值出現,則取第一個出現的 - 將X汰換成 X * multiplier - 回傳在操作K次上述步驟後的num - ''' - def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: - # solution 1 - # for _ in range(k): - # minIndex = 0 - # for i in range(len(nums)): - # if nums[i] < nums[minIndex]: - # minIndex =i - # nums[minIndex] *= multiplier - # return nums - - # Solution 2. - # for _ in range(k): - # x = nums.index(min(nums)) - # nums[x] *= multiplier - # return nums - - op = 0 - while op < k: - x = min(nums) - j = 0 - for i in range(len(nums)): - if nums[i] < x: - x = nums[i] - j = i - - op+=1 - nums[j] *= multiplier - - # while(op < k): - # min = newNums[0] - # newNums.remove(min) - # newNums.append(min * multiplier) - # op+=1 - return nums + 3264. Final Array State After K Multiplication Operations I + + You are given an integer array nums, an integer k, and an integer multiplier. + You need to perform k operations on nums. In each operation: + Find the minimum value x in nums. If there are multiple occurrences of the minimum value, select the one that appears first. + Replace the selected minimum value x with x * multiplier. + Return an integer array denoting the final state of nums after performing all k operations. + + Hints: + 1. Maintain sorted pairs (nums[index], index) in a priority queue. + 2. Simulate the operation k times. + + Example 1: + Input: nums = [2,1,3,5,6], k = 5, multiplier = 2 + Output: [8,4,6,5,6] + Explanation: + Operation Result + After operation 1 [2, 2, 3, 5, 6] + After operation 2 [4, 2, 3, 5, 6] + After operation 3 [4, 4, 3, 5, 6] + After operation 4 [4, 4, 6, 5, 6] + After operation 5 [8, 4, 6, 5, 6] + + Example 2: + Input: nums = [1,2], k = 3, multiplier = 4 + Output: [16,8] + Explanation: + Operation Result + After operation 1 [4, 2] + After operation 2 [4, 8] + After operation 3 [16, 8] + + + Constraints: + 1 <= nums.length <= 100 + 1 <= nums[i] <= 100 + 1 <= k <= 10 + 1 <= multiplier <= 5 + + 3個參數:int array nums.int k & int multiplier + 需在nums上操作K次,每次找出nums中最小值X,若有重複多個最小值出現,則取第一個出現的 + 將X汰換成 X * multiplier + 回傳在操作K次上述步驟後的num + ''' + + # solution 1 + # for _ in range(k): + # minIndex = 0 + # for i in range(len(nums)): + # if nums[i] < nums[minIndex]: + # minIndex =i + # nums[minIndex] *= multiplier + # return nums + + # Solution 2. + # for _ in range(k): + # x = nums.index(min(nums)) + # nums[x] *= multiplier + # return nums + + op = 0 + while op < k: + x = min(nums) + j = 0 + for i in range(len(nums)): + if nums[i] < x: + x = nums[i] + j = i + + op+=1 + nums[j] *= multiplier + + # while(op < k): + # min = newNums[0] + # newNums.remove(min) + # newNums.append(min * multiplier) + # op+=1 + return nums # nums = [2,1,3,5,6] # k = 5 # multiplier = 2 # [8,4,6,5,6] -# a = Solution() -# print(a.getFinalState(nums,k,multiplier)) +# print(getFinalState(nums,k,multiplier)) ''' diff --git a/python/leetcode/list/3005.py b/python/leetcode/list/3005.py new file mode 100644 index 0000000..3f2e847 --- /dev/null +++ b/python/leetcode/list/3005.py @@ -0,0 +1,21 @@ +from typing import List +from collections import Counter + +def maxFrequencyElements(nums: List[int]) -> int: + ''' + 3005. Count Elements With Maximum Frequency + + 計算每個元素出現的次數,找出最大出現次數的為何,若value符合最大出現次數,則加總該次數 + ''' + ans = 0 + occurences = Counter(nums) + # 取得Counter後的最大value + maxValue = max(occurences.values()) + for item, count in occurences.items(): + if count == maxValue: + ans += count + + return ans +nums = [1,2,2,3,1,4] +# 4 +print(maxFrequencyElements(nums)) \ No newline at end of file diff --git a/python/leetcode/math/165.py b/python/leetcode/math/165.py new file mode 100644 index 0000000..7c33062 --- /dev/null +++ b/python/leetcode/math/165.py @@ -0,0 +1,31 @@ +def compareVersion(version1: str, version2: str) -> int: + ''' + 165. Compare Version Numbers + 參數為兩個字串,其內含有".",將參數依據"."拆成左右兩部份,從左到右比較每個部份大小。 + + If version1 < version2, return -1. + If version1 > version2, return 1. + Otherwise, return 0. + + 若部份的前面有0,則忽略0,取整數 + ''' + v1 = version1.split(".") + v2 = version2.split(".") + length = max(len(v1),len(v2)) + + for i in range(length): + num1 = int(v1[i]) if i < len(v1) else 0 + num2 = int(v2[i]) if i < len(v2) else 0 + + if num1 == num2: + continue + + return 1 if num1 > num2 else -1 + return 0 + +# version1 = "1.2" +# version2 = "1.10" +# -1 +version1 = "1.0" +version2 = "1.0.0.0" +print(compareVersion(version1,version2)) \ No newline at end of file diff --git a/python/leetcode/string/1980.py b/python/leetcode/string/1980.py new file mode 100644 index 0000000..9c0df49 --- /dev/null +++ b/python/leetcode/string/1980.py @@ -0,0 +1,44 @@ +from typing import List + +def findDifferentBinaryString(nums: List[str]) -> str: + ''' + 1980. Find Unique Binary String + + Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them. + + Hints: + 1. We can convert the given strings into base 10 integers. + 2. Can we use recursion to generate all possible strings? + + Example 1: + Input: nums = ["01","10"] + Output: "11" + Explanation: "11" does not appear in nums. "00" would also be correct. + + Example 2: + + Input: nums = ["00","01"] + Output: "11" + Explanation: "11" does not appear in nums. "10" would also be correct. + + Example 3: + Input: nums = ["111","011","001"] + Output: "101" + Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct. + + + Constraints: + n == nums.length + 1 <= n <= 16 + nums[i].length == n + nums[i] is either '0' or '1'. + All the strings of nums are unique. + ''' + res = "" + for i in range(len(nums)): + res += '1' if nums[i][i] == '0' else '0' + return res + +nums = ["111","011","001"] +# 101 +print(findDifferentBinaryString(nums)) \ No newline at end of file diff --git a/python/oop/Animal.py b/python/oop/Animal.py new file mode 100644 index 0000000..d831cbd --- /dev/null +++ b/python/oop/Animal.py @@ -0,0 +1,44 @@ +from abc import ABC, abstractmethod + + +# 抽象類別不能被實體化 +class Animal(ABC): + + def __init__(self,name:str,age:int,food:list[str]): + self.name = name + self.age = age + self.food = food + self.__health_level = 100 # 私有屬性 + + # methods + def eat(self): + ''' + 動物進食 + ''' + print(f"{self.name} is {''.join(self.food)}") + + def hibernation(self): + ''' + 冬眠 + ''' + print(f"{self.name}會冬眠嗎") + + + def get_sick(self): + ''' + 動物生病,健康值下降 + ''' + self.__health_level -= 20 + print(f"{self.name}的健康值下降了。現在是: {self.__health_level}.") + + # abstract方法:所有動物必須具備的 + @abstractmethod + def attack(self): + """抽象方法:定義攻擊行為""" + pass + + @abstractmethod + def affend(self): + """抽象方法:定義防禦行為""" + pass + \ No newline at end of file diff --git a/python/oop/Animals.py b/python/oop/Animals.py deleted file mode 100644 index b217be2..0000000 --- a/python/oop/Animals.py +++ /dev/null @@ -1,20 +0,0 @@ -class Animals: - - def __init__(self,name:str,age:str,food:list[str]): - self.name = name - self.age = age - self.food = food - self.__health_level = 100 # 這是私有屬性 - - # methods - def eat(self): - print(f"{self.name}","is",f"{self.food}") - - def environment(self): - print("依據不同物種來評估適合的環境") - - def get_sick(self): - self.__health_level -= 20 - print(f"{self.name} 的健康值下降了。") - - \ No newline at end of file diff --git a/python/oop/Behavior.py b/python/oop/Behavior.py new file mode 100644 index 0000000..c27f6ae --- /dev/null +++ b/python/oop/Behavior.py @@ -0,0 +1,6 @@ +# 通用涵式 +from oop.Tortoise import Tortoise +from oop.Lion import Lion + +def move(): + print("jofidjf") \ No newline at end of file diff --git a/python/oop/Fruit.py b/python/oop/Fruit.py deleted file mode 100644 index d926c26..0000000 --- a/python/oop/Fruit.py +++ /dev/null @@ -1,28 +0,0 @@ -import math - -class Fruit: - - def __init__(self,name:str,price:int,quantity:int): - ''' - 等同於PHP __construct() - ''' - self.name = name - self.price = price - self.quantity = quantity - - - # methods - def calculate(self): - ''' - 計算總價 - - 優惠: - 滿3送1 - ''' - return self.price * (self.quantity - math.floor(self.quantity / 3)) - - def make_seedling(self): - print("Make seedling.") - - def make_watering(self): - print("Make watering") \ No newline at end of file diff --git a/python/oop/Lion.py b/python/oop/Lion.py index 68ed66f..5673a76 100644 --- a/python/oop/Lion.py +++ b/python/oop/Lion.py @@ -1,11 +1,19 @@ -from oop.Animals import Animals +from oop.Animal import Animal -class Lion(Animals): +class Lion(Animal): def __init__(self, name, age, food): super().__init__(name, age, food) - - def eat(self): - return super().eat() def environment(self): - print("溫暖") \ No newline at end of file + print("溫暖") + + # 覆寫父類別的方法 + def eat(self): + print(f"{self.name} 正在快速撕咬 {''.join(self.food)}。") + + # abstract + def affend(self): + print("同攻擊") + + def attack(self): + print("咬抓") \ No newline at end of file diff --git a/python/oop/Melon.py b/python/oop/Melon.py deleted file mode 100644 index 191b418..0000000 --- a/python/oop/Melon.py +++ /dev/null @@ -1,15 +0,0 @@ -from oop.Fruit import Fruit - -class Melon(Fruit): - - def __init__(self, name, price, quantity,seed): - super().__init__(name, price, quantity) - self.seed = seed - - - # over write - def make_seedling(self): - print("make melon seed") - - def palnt(self): - print("plants") \ No newline at end of file diff --git a/python/oop/Testudo_graeca.py b/python/oop/Testudo_graeca.py new file mode 100644 index 0000000..c28eff5 --- /dev/null +++ b/python/oop/Testudo_graeca.py @@ -0,0 +1,7 @@ +# 歐洲陸龜 +from oop.Tortoise import Tortoise + +# 繼承自父類別(Tortoise),可以把該類別想成是孫子(Multilevel Inheritance),它的上一輩是Single Inheritance +class Testudo_graeca(Tortoise): + def __init__(self, name, age, food, speciceType): + super().__init__(name, age, food, speciceType) \ No newline at end of file diff --git a/python/oop/Tortoises.py b/python/oop/Tortoise.py similarity index 61% rename from python/oop/Tortoises.py rename to python/oop/Tortoise.py index bdce47e..da5b947 100644 --- a/python/oop/Tortoises.py +++ b/python/oop/Tortoise.py @@ -1,16 +1,18 @@ -from oop.Animals import Animals +# 陸龜 +from oop.Animal import Animal -class Tortoises(Animals): +class Tortoise(Animal): + + # class variable + # a property of the class itself. + specice = "Spurred tortoise" def __init__(self, name, age, food,speciceType:str): + # instance variable.Unique to each instance super().__init__(name, age, food) self.speciceType = speciceType - def eat(self): - return super().eat() - - # 覆寫父類別的方法 def environment(self): ''' 環境 @@ -28,8 +30,16 @@ def environment(self): except NameError: print("eror") + def avgWeight(self,*args): + return sum(args) / 2 + + # 繼承、覆寫 def hibernation(self): - ''' - 冬眠 - ''' - print("if it's really cold") \ No newline at end of file + return super().hibernation() + + # 抽象 + def attack(self): + print("咬,但不太會發生") + + def affend(self): + print("縮進殼內") \ No newline at end of file diff --git a/python/oop/Turtle.py b/python/oop/Turtle.py new file mode 100644 index 0000000..558c3ea --- /dev/null +++ b/python/oop/Turtle.py @@ -0,0 +1,6 @@ +# 澤龜 +from oop.Animal import Animal + +class Turtle(Animal): + def __init__(self, name, age, food): + super().__init__(name, age, food) \ No newline at end of file diff --git a/python/oop/__pycache__/Animal.cpython-312.pyc b/python/oop/__pycache__/Animal.cpython-312.pyc new file mode 100644 index 0000000..2e798fc Binary files /dev/null and b/python/oop/__pycache__/Animal.cpython-312.pyc differ diff --git a/python/oop/__pycache__/Animals.cpython-312.pyc b/python/oop/__pycache__/Animals.cpython-312.pyc index 4935a6c..aac4139 100644 Binary files a/python/oop/__pycache__/Animals.cpython-312.pyc and b/python/oop/__pycache__/Animals.cpython-312.pyc differ diff --git a/python/oop/__pycache__/Behavior.cpython-312.pyc b/python/oop/__pycache__/Behavior.cpython-312.pyc new file mode 100644 index 0000000..9562395 Binary files /dev/null and b/python/oop/__pycache__/Behavior.cpython-312.pyc differ diff --git a/python/oop/__pycache__/Lion.cpython-312.pyc b/python/oop/__pycache__/Lion.cpython-312.pyc index 2fa756c..cafddad 100644 Binary files a/python/oop/__pycache__/Lion.cpython-312.pyc and b/python/oop/__pycache__/Lion.cpython-312.pyc differ diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc new file mode 100644 index 0000000..11e71fa Binary files /dev/null and b/python/oop/__pycache__/Tortoise.cpython-312.pyc differ diff --git a/python/oop/__pycache__/Tortoises.cpython-312.pyc b/python/oop/__pycache__/Tortoises.cpython-312.pyc index e97dcef..ab980c6 100644 Binary files a/python/oop/__pycache__/Tortoises.cpython-312.pyc and b/python/oop/__pycache__/Tortoises.cpython-312.pyc differ