From 8ee02c54b7d7e7b70b6830a718b70a481b8a64e5 Mon Sep 17 00:00:00 2001 From: Mavis Date: Mon, 22 Sep 2025 15:07:26 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E8=A7=A3=E9=A1=8C?= =?UTF-8?q?=E7=B7=B4=E7=BF=92=EF=BC=8Cpython=E7=B7=B4=E7=BF=92oop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python/index.py | 17 +++++--- python/leetcode/list/3005.py | 21 +++++++++ python/oop/Animal.py | 40 ++++++++++++++++++ python/oop/Animals.py | 20 --------- python/oop/Behavior.py | 11 +++++ python/oop/Lion.py | 20 ++++++--- python/oop/{Tortoises.py => Tortoise.py} | 20 ++++----- python/oop/__pycache__/Animal.cpython-312.pyc | Bin 0 -> 2028 bytes .../oop/__pycache__/Animals.cpython-312.pyc | Bin 1367 -> 1709 bytes python/oop/__pycache__/Lion.cpython-312.pyc | Bin 939 -> 1362 bytes .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 0 -> 1708 bytes .../oop/__pycache__/Tortoises.cpython-312.pyc | Bin 1788 -> 2094 bytes 12 files changed, 107 insertions(+), 42 deletions(-) create mode 100644 python/leetcode/list/3005.py create mode 100644 python/oop/Animal.py delete mode 100644 python/oop/Animals.py create mode 100644 python/oop/Behavior.py rename python/oop/{Tortoises.py => Tortoise.py} (75%) create mode 100644 python/oop/__pycache__/Animal.cpython-312.pyc create mode 100644 python/oop/__pycache__/Tortoise.cpython-312.pyc diff --git a/python/index.py b/python/index.py index 0c4be74..9703188 100644 --- a/python/index.py +++ b/python/index.py @@ -11,7 +11,7 @@ from operator import le from typing import List import math - +from collections import Counter # from numpy import diff # module @@ -23,16 +23,22 @@ # 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 -greek = Tortoises("福氣","7個月大","veggie","地中海型陸龜") +greek = Tortoise("福氣",7,"veggie","地中海型陸龜") greek.eat() +greek.hibernation() greek.environment() +greek.attack() lion = Lion("獅子","未知","肉食") -lion.environment() +lion.eat() +# lion.attack() + +# print(lion.food) +# lion.environment() # from oop.Fruit import Fruit # from oop.Melon import Melon @@ -296,3 +302,4 @@ def isPrime(element:int): # print(closestPrimes(left,right)) + 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/oop/Animal.py b/python/oop/Animal.py new file mode 100644 index 0000000..2262d10 --- /dev/null +++ b/python/oop/Animal.py @@ -0,0 +1,40 @@ +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..9f11a36 --- /dev/null +++ b/python/oop/Behavior.py @@ -0,0 +1,11 @@ +from abc import ABC, abstractmethod +class Behavior(ABC): + + # abstract + @abstractmethod + def attack(): + pass + + @abstractmethod + def affend(): + pass \ 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/Tortoises.py b/python/oop/Tortoise.py similarity index 75% rename from python/oop/Tortoises.py rename to python/oop/Tortoise.py index bdce47e..8db1a7e 100644 --- a/python/oop/Tortoises.py +++ b/python/oop/Tortoise.py @@ -1,16 +1,12 @@ -from oop.Animals import Animals +from oop.Animal import Animal -class Tortoises(Animals): +class Tortoise(Animal): def __init__(self, name, age, food,speciceType:str): super().__init__(name, age, food) self.speciceType = speciceType - def eat(self): - return super().eat() - - # 覆寫父類別的方法 def environment(self): ''' 環境 @@ -28,8 +24,10 @@ def environment(self): except NameError: print("eror") - def hibernation(self): - ''' - 冬眠 - ''' - print("if it's really cold") \ No newline at end of file + + # 抽象 + def attack(self): + print("衝撞") + + def affend(self): + print("縮") \ 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 0000000000000000000000000000000000000000..c4f9b9b0bfa2fe5149b6b57e231b2a2bfd857375 GIT binary patch literal 2028 zcmbtVO>7%g5PrM+)>%8T3r$)Y1+`8Qi0z?9G{7Z74ImH~UudEDvf6kz^@g<_)@xKp zIhbNfXaf|{)*(&QRH!9Z5QQS~lZJ{r99&S;YK6q1v0a~P;`Y)LGrQ}p>sAPfkv(tb zy?OIyzBlvs*I+O}fPQP16Du4c*HLK^?+VRbAQXv06h1_qjCzX zQt-^HTtBRh`4n29F`vR0NUTfo0T+}m;C?lr2nDk2I*N6J?r+n3asjd1@{Odlq^w&s zB_~yjlMkvE9ZN$n)ZK>z3x73mW5T9B627lY*8m0EFZq^Jrax z6_Fa4pdldh1GBbBP9Tz$P-WdrNV@uts*BX38C4(au+Cs`VW8U>P$ZE~su5k*;1{W$ z`e6Oi_mOy7QD08$ifTkA5MeE@MkaEAaw?KePeh!vc2DFiL6WqTW=hiJCU>$mfoEiP z0LznWecPt#jQ?8iRv3hqwtaA#t_cH8Fd=ad08lVB8?JE>ip2ERrpUMl4J^5I8mdQO z$6GbknuZbVeQl~MF1!9tlLf9NGbG1}G`k&40tgIJ<=DyEhoyS{V*QIV-sB_=YniY` zq5v&FVQ4AS#@3?aX)R@6MTs$j;3k8ogpCkzi&JHDGT`C^ayPDv!1CmlK>VTOeZ~Gy z`;T|e4lS}@cAf27q8I!n{~zI}%RBazLqluAGsZ(;eGf%VF1-30+R^+nV zV5^r|<;YjH`9)97_P}Cw{yk^9Qv5h7vPLh=IkmI}r1liM6WXY1q-0Y|rzSVMskY5M zjP{QJ>r8pL9C~t15bsYAZ_ZBe5D3sTm^ujR1zPSw zzF>u0plu+*i<5l{wtJ{JHBmcprdE9a=ITu4-E){ zbA=A0^_3&n^M`AnT&~P7Rc9~UT%8NwVRlDF&OpTf1!Cc#YDyU`{+8EjtqH_6^Bk}| zX+S*%uL=Xd3j?#p6=4t>>`x)sDzNgv-e3Bzj_kWKvah^%e|i7w<=HJ^NnxMR!{v@{q7`0Uio^icDYnNajE**(Hm!HYKK>%C1P~ehEFz4 z8Nv>_W#On{aM#3EhoF5B^#2T^K6|lt{=6H6fsOotIL5}*lyWx?Tg6*4!pN}4qGAx= zG6_ltt4*BQ2vPpojULMH+UVi=H<`v} z;_LgHW%*!}1F3-$+<*I=y=o_BABC?LCy&MrY!N3uJB)inyCV!cSwC;!_Zc6u3>I{Q WV;JTy^4Kl*2_`uG+HC@Z?fV}Qdf5X2 literal 0 HcmV?d00001 diff --git a/python/oop/__pycache__/Animals.cpython-312.pyc b/python/oop/__pycache__/Animals.cpython-312.pyc index 4935a6c58ec9fc309d0aa9047e763cc36e7776dd..aac4139e093e7916f43d8b968f602c0e04fd4930 100644 GIT binary patch delta 791 zcmaJ;)`O%;YO9+TC-JcDVS6a( z!AqG#y$W8+;@$t?r590xpy0`auo}I1^1WmiHVDn(oA-uGT+=A-%6?!C8d6Y#tH z<7oXQ2lz&0^i_sIb{T^M2q0h`h*+CNyv-SKxD5f{gFu9=FA8m2bTzl~orud*(P-XE z9d9*Gq~|A5n5=IFejzN-JTYY1{rv~m7Q$*^>_LB+Yn#ZcW8CVRuC@Pa$D%4}5LDG1 zTPX26>@m~SJNEi?uBxKykVzYtm?2z{j(W;xn5CZcc~)0_-kF>tr|EIUqPTR@p@fC7 z3!e@9$hrQ(Sdn$*i#IDZD#)wy9^<9BlNyi0VMS`-u)G0@RPYvRG>XUY* z_ea dQAaNzrt2CA#@H8_|IH_6nf=251Gwbo{{WR_kCgxb delta 420 zcmZ3>dz~x#G%qg~0}z{h| diff --git a/python/oop/__pycache__/Lion.cpython-312.pyc b/python/oop/__pycache__/Lion.cpython-312.pyc index 2fa756cde23479441a8d7227236a08a6b4e5ead5..cafddad17f7d192f953a167d9dcf00c67b7912f6 100644 GIT binary patch delta 805 zcmZ`%O^8xa6u#&E`P9^YM$kl%sKpy%W*``dqNZ9jh0LN>xf7oLR zX$?DzEogY7*R*rF^m06#Ag_I-u`!rM<2GxuB#VK`Vp5Hzz=WzElTE40Vu~pvs-}Xd znJS{A#;!w5zsd})u{jS$WA7H|)+$`Ku1LoNE$FH%Je@1HfICsT00f%8~IIWD%OI_&aukW$dQyT)ZDL6HF2KWcZEQxmtVB(Ht=u#eeh@8AJMJo( zd^*SX5kG`r4@)6A885Es(R4mHg_fJ5Gn0s7^!h|I*a+6$ozV0P>6PQ9-+SA)*7*Ts|J2grsZ=s&uDM0I5uwEvsL9c; zm$vo8Lh$Sy&eLDF{-;zd#uH1nk|1JSKh-5o!)bkxj`?-sv@ISa2oZ!Wko{#3nqm=i z+)G~iGy-UWg)qX8DjQ0mPVQ=;26lB&F9BibJ8@A&?0 zATHbW7itkLrG7!10t<;2oqP4b{mysK<2&cx*T^swdx}OQKz9G}T>1h(mNP>8)pEu0 zxbG})Whiq4eJFy3E?7zjj?u-oVX2ZS#57lJgQa)i46V65n414^fCK;U8pA;g51VO{ zxWhg)$WN_{m(bGzhO>JfScs^pFoWDkEjkV2Vk;IS;0i&y#o{8cNN{fC%C%~S%0wF% z@ktBb;)(8Q_u}^I#YnLQiWQImf=A3IO&sZUR<1Tol)7A`(kvdtl=T%ch=&PC!-#fD zy|`>QLxHPpG(|#AWlO|HQQIzf4(ElU=h-&N$qj|v-gH5F7cc=T9WK_Lv|+5EzB!&l zef5VRDfMO1k*SX6Yqff2_UBA=$;<#`)wWdqHL{hOd*T&$S&9n8IG!N*R1xtV*2bEF L$y diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85caad9bc40e26b818ce2e4f827000748d2bf73d GIT binary patch literal 1708 zcmbVNO-vg{6n?Wm#wIvGVp0Odr7a@bq>2xf`lpH(HMCL>T#`$yRx8W9E>6~7XLe0u zWF)sBVpNbKqy$qO;`WdxBCY6OiU@6#b1#XMs%S+|#Wp^b@Kd3j`eyw@kb3HP_2$j{ z{pQV^@o#Q-J>bY~KOBhg0DrMXb%+&as~eeVP(UFXM2Mdd;NSyLxKU7emCU0b8-6Y! zNMebx60sb;(QqW71=+GXDu%H28cHr>NEQ4XHL<14k;sc+kmJrf) z#nxIbSq^Fe!;oczS$DFL+UY^oH=svUpB4z?=PO*hyms%dFQ_Z(`?{v6)EA?Hpo!b@ z#S-R#9`)&Z%vas($ykEAFvL)EO;W|gHfubOWH$w?PWO1-BWG*IlQD9q9y_I#_U^Rs zyR&r*^$;YCRtCdn*XT!N@N}{C3XeY_D-4q)Irpq>#bv%SpMsCO06xNM4Rgc13$T)K zu2#E>5l(|Zo6Op|B)M5o#3Vlp*ZKKMbOICI0wn5Q29x2jM;Fk81or$C$DZ|BnCQ6( zm-w@Akx0&XD>~HM1x8YwTF8GjQd`E`QCZ5S)^C2gzC2Qz&lJBHEiBFFmu?ovzAN3E zi@%BbLUueqcBh!l74J_KQeXeQJhAr6SRp%-pUo9NTPlpF^4VMY>_XXZJvFhmI9axj zxBN%+`&Ti#B*Yt8%?weo3&zu&G9ja<_>w8jhNls~=mjkD`GjPV(GTG{4aR z?cN*Gj5K><6GWGH{KNEnS6VhW!R=i+d?eHLN89m7_#HmJ>N%P@o$1RR%Jt=5f7o{7 zvFDZDCw1ttyX^!|$0iWBceSbIO6Zzw~3XeVkvAb3{e~@ z>_C#UgQ0>kiYu5wlVjtKUo0Fe8H>b$YFAF)#Tqc#lhrtsL6ga^lnp5KV&U9pljar4 z0hvYeK%$rtNGKEu0Lfcyi6te8$=Ou`A^Alm`I*J3#d;7CHIPD1Akn~Zhl95xqnE!( z5Xb|W90E2OP)a^RQWRD*$DSlt6^aWH&Zr zMvci;Y%=)YHC0UMj$R00TLgW85tSxGRS{nQD9V^!2Xp1NP+bO0L@S*r~m)} From 0404cca84b5be05807cd3f13bd2a43e01f78eb58 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 23 Sep 2025 14:47:04 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E8=A7=A3=E9=A1=8C?= =?UTF-8?q?=E3=80=81oop=E7=B7=B4=E7=BF=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/LeetCode/math/165.js | 34 +++ javascript/index.js | 16 ++ python/index.py | 227 +++++++----------- python/leetcode/math/165.py | 31 +++ python/leetcode/string/1980.py | 44 ++++ python/oop/Animal.py | 8 +- python/oop/Behavior.py | 15 +- python/oop/Fruit.py | 28 --- python/oop/Melon.py | 15 -- python/oop/Tortoise.py | 9 +- python/oop/__pycache__/Animal.cpython-312.pyc | Bin 2028 -> 2028 bytes .../oop/__pycache__/Behavior.cpython-312.pyc | Bin 0 -> 388 bytes .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 1708 -> 1923 bytes 13 files changed, 228 insertions(+), 199 deletions(-) create mode 100644 javascript/LeetCode/math/165.js create mode 100644 python/leetcode/math/165.py create mode 100644 python/leetcode/string/1980.py delete mode 100644 python/oop/Fruit.py delete mode 100644 python/oop/Melon.py create mode 100644 python/oop/__pycache__/Behavior.cpython-312.pyc 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/index.js b/javascript/index.js index 67404b1..80a449f 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1028,3 +1028,19 @@ var closetPair = function(arr1,arr2,x) { // [1,30]; // console.log(closetPair(arr1,arr2,x)); +/** + * 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/python/index.py b/python/index.py index 9703188..8419509 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 collections import Counter # from numpy import diff # module @@ -26,32 +23,21 @@ from oop.Animal import Animal from oop.Tortoise import Tortoise from oop.Lion import Lion +from oop.Behavior import move greek = Tortoise("福氣",7,"veggie","地中海型陸龜") greek.eat() greek.hibernation() greek.environment() greek.attack() +greek.affend() -lion = Lion("獅子","未知","肉食") -lion.eat() +# lion = Lion("獅子","未知","肉食") +# lion.eat() # lion.attack() - -# print(lion.food) +# # print(lion.food) # 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() - - ''' 1415. The k-th Lexicographical String of All Happy Strings of Length n @@ -88,135 +74,95 @@ 1 <= n <= 10 1 <= k <= 100 ''' +# def getHappyString(n: int, k: int) -> 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. -''' -# class Solution: -# def findDifferentBinaryString(self, nums: List[str]) -> str: - - -# nums = ["111","011","001"] -# # 101 -# a = Solution() -# print(a.findDifferentBinaryString(nums)) - -class Solution: - ''' - 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(nums: List[int], k: int, multiplier: int) -> List[int]: ''' - 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)) ''' @@ -302,4 +248,3 @@ def isPrime(element:int): # print(closestPrimes(left,right)) - 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 index 2262d10..d831cbd 100644 --- a/python/oop/Animal.py +++ b/python/oop/Animal.py @@ -1,4 +1,7 @@ from abc import ABC, abstractmethod + + +# 抽象類別不能被實體化 class Animal(ABC): def __init__(self,name:str,age:int,food:list[str]): @@ -20,6 +23,7 @@ def hibernation(self): ''' print(f"{self.name}會冬眠嗎") + def get_sick(self): ''' 動物生病,健康值下降 @@ -27,7 +31,6 @@ def get_sick(self): self.__health_level -= 20 print(f"{self.name}的健康值下降了。現在是: {self.__health_level}.") - # abstract方法:所有動物必須具備的 @abstractmethod def attack(self): @@ -37,4 +40,5 @@ def attack(self): @abstractmethod def affend(self): """抽象方法:定義防禦行為""" - pass \ No newline at end of file + pass + \ No newline at end of file diff --git a/python/oop/Behavior.py b/python/oop/Behavior.py index 9f11a36..c27f6ae 100644 --- a/python/oop/Behavior.py +++ b/python/oop/Behavior.py @@ -1,11 +1,6 @@ -from abc import ABC, abstractmethod -class Behavior(ABC): +# 通用涵式 +from oop.Tortoise import Tortoise +from oop.Lion import Lion - # abstract - @abstractmethod - def attack(): - pass - - @abstractmethod - def affend(): - pass \ No newline at end of file +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/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/Tortoise.py b/python/oop/Tortoise.py index 8db1a7e..aedcf2d 100644 --- a/python/oop/Tortoise.py +++ b/python/oop/Tortoise.py @@ -24,10 +24,13 @@ def environment(self): except NameError: print("eror") - + # 繼承、覆寫 + def hibernation(self): + return super().hibernation() + # 抽象 def attack(self): - print("衝撞") + print("咬,但不太會發生") def affend(self): - print("縮") \ No newline at end of file + print("縮進殼內") \ No newline at end of file diff --git a/python/oop/__pycache__/Animal.cpython-312.pyc b/python/oop/__pycache__/Animal.cpython-312.pyc index c4f9b9b0bfa2fe5149b6b57e231b2a2bfd857375..2e798fc24ff5866ba72a1ecdba28ea853849e844 100644 GIT binary patch delta 95 zcmaFE|AwFUG%qg~0}yO;xRmj5BkvbRM)u82Oj3-De3NCFKQW4I7GQ~CWR#wq%esY8 xd9o5)JEO+rRcsB6tdq6bjoJBFStA)g2ux08FBjlYW901!{>lKPiUfcr0szng7i0hc delta 95 zcmaFE|AwFUG%qg~0}!0~d?91kM&2)sj4Yd(n4}mPxhKmqe_|BeEWi@O$S6KJmvsxH x!ek}3c1G37tJoSCnI>zq8?*DUvPLp~5SpCIUM|3-#>m?d{FMPn6$t=M1OWa&7w7;0 diff --git a/python/oop/__pycache__/Behavior.cpython-312.pyc b/python/oop/__pycache__/Behavior.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10f0abec6d5f53423fd022292f30b671ec9b2e50 GIT binary patch literal 388 zcmX|-y-ve05XbKlN2EXn0}L<$TbB9-P=y$nP$#BtRqQIRk~(rjrECmH@C5W3Ds~ng zfenczf{71_4Jl%PiMuN0WZ(Vn?ElH^?8TJvG zz0}M6zEA95LSK|33O-pd$0|ItuCQjJBdo-!vEvwdtBZ@7BwS^&yJ%tTOa&$0M zFh+3(Gib6;+?>w1alihd7`Z23XO?3WnEZ|TOuYioxT%cO8A?FrfgU=`z2{1rC)WknrR+EEee!K*rNa zYu@kad9t_d$&TKqOIAIb)BJqqp665MuVgF|1xf=ckk!SEKtcg*=`FUzl9I&a>?(e^ zy$}HfkUEfJpp6{77x*-;a%jTsQsMzhJm0bIWy7Xt>-IctU0x&y6eyAh>4BO(xr0?k zN*N>o3Vg639eGzdWWi==a!uaLs#On?DUt#aAP*KPfCwcZaf>%TJ~=0`xHvgACnr8$ zlMxbDAd?*+K?MwHh9VHb48+ACYkssad|+W>Ro`Izl>tb7;^JqO`=Y|gs``n8kyYy( z8zZY6*lMsYKTYOaT=|n@*u<Qu?Ud(z|6?Vc$Y!; R3yUJ7Tu0eg1|S7C2>?x8l{WwY delta 380 zcmZqXU&G6LnwOW00SFd+xsZ`NkvEIcY+{9~SPDxELlj#IE0ARGV5ne>;s|EYWSh7* zol$eLD&r(Z&doa*HJBK=CO>4BW8|O2a%Qpsn^FK9(3}?w=RTV>ZzW@q2#^D$K!z7H z0ttm8ejs^^EwQ8|F*&=6KP11XBtNq_RSzN{3sT1kBpMj*aPW3y^zs)8Opai+_G1Q$ zJ>RjeNE%2N$$(U$n3k57nwNrX8dyL9qz++PYA;Wb08mJib8;7(mJ3LtND@SVY%P)p z61RBc?)!lOTfy1aoFVMr Date: Wed, 24 Sep 2025 13:52:46 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E8=A7=A3=E9=A1=8C,oop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/LeetCode/Array/1572.js | 61 +++++++++--------------------- javascript/LeetCode/Array/1980.js | 16 ++++++++ javascript/LeetCode/math/3099.js | 32 ++++++++++++++++ javascript/index.js | 27 +++++++------ javascript/oop.js | 5 +++ javascript/oop/1_basic_literals.js | 32 ---------------- javascript/oop/2_constructor.js | 14 ------- javascript/oop/3_prototypes.js | 16 -------- javascript/oop/4_inheritence.js | 24 ------------ javascript/oop/5_object_create.js | 24 ------------ javascript/oop/6_classes-ES6.js | 25 ------------ javascript/oop/7_subclasses.js | 28 -------------- javascript/oop/Vehicle .js | 15 ++++++++ 13 files changed, 101 insertions(+), 218 deletions(-) create mode 100644 javascript/LeetCode/Array/1980.js create mode 100644 javascript/LeetCode/math/3099.js create mode 100644 javascript/oop.js delete mode 100644 javascript/oop/1_basic_literals.js delete mode 100644 javascript/oop/2_constructor.js delete mode 100644 javascript/oop/3_prototypes.js delete mode 100644 javascript/oop/4_inheritence.js delete mode 100644 javascript/oop/5_object_create.js delete mode 100644 javascript/oop/6_classes-ES6.js delete mode 100644 javascript/oop/7_subclasses.js create mode 100644 javascript/oop/Vehicle .js 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/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/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/index.js b/javascript/index.js index 80a449f..fe5ee65 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1028,19 +1028,24 @@ var closetPair = function(arr1,arr2,x) { // [1,30]; // console.log(closetPair(arr1,arr2,x)); + + + /** - * 1980. Find Unique Binary String + * 166. Fraction to Recurring Decimal * - * @param {string[]} nums + * 參數為分子、分母,以字串資料型態回傳分數 + * 如果小數部分重複,則將重複部分放在括號中。 + * 若有很多個答案,任一回傳 + * + * @param {number} numerator + * @param {number} denominator * @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; +var fractionToDecimal = function(numerator, denominator) { + }; -let nums = ["01","10"]; -// "11" -console.log(findDifferentBinaryString(nums)); \ No newline at end of file +let numerator = 1, denominator = 2; +// "0.5" +// console.log(fractionToDecimal(numerator,denominator)); + 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 From a46aeb7c3142bdd198ece7b1efaccb12c5b08e55 Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 25 Sep 2025 15:22:41 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E7=B7=B4=E7=BF=92js=20=E8=A7=A3=E9=A1=8C?= =?UTF-8?q?=EF=BC=8Coop=E7=B7=B4=E7=BF=92=E5=AF=AB=E7=B9=BC=E6=89=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/LeetCode/math/3602.js | 21 ++++++++++++++++++ javascript/index.js | 4 +--- python/index.py | 1 + python/oop/Testudo_graeca.py | 7 ++++++ python/oop/Tortoise.py | 6 +++++ python/oop/Turtle.py | 6 +++++ .../oop/__pycache__/Behavior.cpython-312.pyc | Bin 388 -> 387 bytes .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 1923 -> 1959 bytes 8 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 javascript/LeetCode/math/3602.js create mode 100644 python/oop/Testudo_graeca.py create mode 100644 python/oop/Turtle.py 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 fe5ee65..f5e9b99 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,9 +1029,6 @@ var closetPair = function(arr1,arr2,x) { // [1,30]; // console.log(closetPair(arr1,arr2,x)); - - - /** * 166. Fraction to Recurring Decimal * diff --git a/python/index.py b/python/index.py index 8419509..67b0d3e 100644 --- a/python/index.py +++ b/python/index.py @@ -31,6 +31,7 @@ greek.environment() greek.attack() greek.affend() +print(greek.specice) # lion = Lion("獅子","未知","肉食") # lion.eat() 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/Tortoise.py b/python/oop/Tortoise.py index aedcf2d..060afa7 100644 --- a/python/oop/Tortoise.py +++ b/python/oop/Tortoise.py @@ -1,8 +1,14 @@ +# 陸龜 from oop.Animal import Animal 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 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__/Behavior.cpython-312.pyc b/python/oop/__pycache__/Behavior.cpython-312.pyc index 10f0abec6d5f53423fd022292f30b671ec9b2e50..95623955ca99c94557a6093088713e6074b87ff5 100644 GIT binary patch delta 190 zcmZo+Zf52^&CAQh00i=mmojoD^16v>GT!0{$uBC&&n!*_vRQmG^YfA!CT6;`uVnZP zQaN$AS3Nh7W(DG6klqG{J1m?Xnpaswia3E>KTXzKJo)(rdN5Opn1Q0VI6y)m!-`md z+#-+(MI0akq^AgE&Myv|-29Z%oK(9aJ|LG7h>Hb)#0O?ZM#iTMigy_#KeI40iWYH# G3Zeiv<&CAQh00ciBE@hNVNGDv=AVPq5q G>i_^%v@LG{ diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc index 41e8aaa56dbfceb4b958eb11abe27cacd69a7bc1..c199dd4747bd237efbb37e4c8b9a7722560d0356 100644 GIT binary patch delta 212 zcmZqXU(U~WnwOW00SMMTy^_JgGLbJc-UY~OXPC~A$`Hkv!Vtxj!WhMz!j#IA#?--( z#+bs~!V|@s!qUPJ#RlfHws1tTr?3I}94YKTlCy)Mf-#CKm_d`{7Dq^aQAvJgacY%7 za6xHNQEG}p$;JbGjEwA?&ohQIG4gCyXAxy&l$&hJx`a__@*~zhM%BrMY!Zyzle^ed zIoOK}Qj;^2Qzx%u^W)I~I_pOZ!vj8r2KUL#>`{!`ljGRM_>~#uI?BE>0I4EDpb7vr CS2h6v delta 212 zcmZ3^-^|ZX)lGfZblWr$)-VTfW%VN7LCW9nc?V@zRc z;fZ2NVQyiFVg>VAS~#NEQdog}_7pZC$4BO~Ko2H7txii~m{WnUS96j(C=gjg@q From 24e73524688adddadbe65d88fff4ceab88e48d14 Mon Sep 17 00:00:00 2001 From: Mavis Date: Fri, 26 Sep 2025 15:23:42 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=88=A5=E7=A8=AE?= =?UTF-8?q?=E8=A7=A3=E9=A1=8C=E6=96=B9=E5=BC=8F=E3=80=82python=20oop=20?= =?UTF-8?q?=E7=B9=BC=E6=89=BF=E3=80=81*args=E5=AD=B8=E7=BF=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/LeetCode/Array/1588.js | 11 +++++++++++ python/index.py | 1 + python/oop/Tortoise.py | 3 +++ .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 1959 -> 2134 bytes 4 files changed, 15 insertions(+) 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/python/index.py b/python/index.py index 67b0d3e..2b0efb1 100644 --- a/python/index.py +++ b/python/index.py @@ -32,6 +32,7 @@ greek.attack() greek.affend() print(greek.specice) +print(greek.avgWeight(7,5)) # lion = Lion("獅子","未知","肉食") # lion.eat() diff --git a/python/oop/Tortoise.py b/python/oop/Tortoise.py index 060afa7..da5b947 100644 --- a/python/oop/Tortoise.py +++ b/python/oop/Tortoise.py @@ -30,6 +30,9 @@ def environment(self): except NameError: print("eror") + def avgWeight(self,*args): + return sum(args) / 2 + # 繼承、覆寫 def hibernation(self): return super().hibernation() diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc index c199dd4747bd237efbb37e4c8b9a7722560d0356..11e71fa8ecdc6c978663e3fd904492ae951ce839 100644 GIT binary patch delta 427 zcmZ3^e@%e*G%qg~0}!mVx|XqbB5xL>*Tf1kjudtvpEHF6 zNOE;BR4_(y2Qz4LZak>W2-aOJ12o}B1H+Te9~r%w7zHNVvMi`)2a0``0}|62N*I9@ z7}PMXhO$!_tGF2$fW|QSy<`H)X)@koE-ua0WGVs*Gu&cHEJ`mf21zI=6bXPtI1|g# z!&5WUGfJw2Lh_4B@-vH5_26QPKqbW>bqx%6_=P5zbaPbBFzl?oz#%g^hgEv=BbG2} zkdi79xYmr!q|~Ck#FEVXJk`m;tVy150=b$zlNYer3dn<0f($KE1rh3#U$E(EvjCaJ`at4G3&RHv27bi`_YW-0tm+$# zzcK)+Pdxmra-WnKS!KU)OtxZoS2F-A1%*hl2$1-|%*e?2ltK0jizcI7N7+|kpvZx3 F1OQNWW~u-H delta 248 zcmca6u$-UwG%qg~0}!lxdL@HpB5xL>%ft#zg${-^#uU~TjwtpNwibpcjudtv$=ShB z!5GCA%%I7!@whT0FFR0Mu?&#-(ZFzL^LIvXCPtpg&MXTiH?T%C%1pk)D#<7}`5WsJ zMy1KK*%I00fGUgRCo{3DOR0i%f~*B<3WlqOGL z*Hd8zGK)2U#E%w+2Yd<*?jKl~Sk*Tee`NqtpSbv0<-Vv)e#!2xrVUiX2vRHpBt9@R XGBVy}kp04<%qZ7U_LTuhfo%Z*z0*1* From 626b1fdbc9b3c2da4a56c9608e0de2507d7c7d87 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 30 Sep 2025 15:24:13 +0800 Subject: [PATCH 6/6] add new solution of 1464 in JS --- javascript/LeetCode/Array/1464.js | 9 +++++++++ javascript/index.js | 3 +-- 2 files changed, 10 insertions(+), 2 deletions(-) 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/index.js b/javascript/index.js index f5e9b99..f00c3fa 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1045,5 +1045,4 @@ var fractionToDecimal = function(numerator, denominator) { }; let numerator = 1, denominator = 2; // "0.5" -// console.log(fractionToDecimal(numerator,denominator)); - +// console.log(fractionToDecimal(numerator,denominator)); \ No newline at end of file