Re: [闲聊] 自学练习

楼主: erimow (Erimo)   2024-08-11 12:26:28
※ 引述《erimow (阿欧伊)》之铭言:
: Write a function called "factorPrime" that takes an integer as input, and
: returns the prime factorization of the input.
: factorPrime(120); # returns "2 x 2 x 2 x 3 x 5"
: 想了大概45分钟
: 修修改改
: 屁都没有
: 转头睡大觉
: 明天再来
早上起来去超市边买边想
想不出来
我一开始的想法是,我先找出所有这个数字会有的因子
再从因子里面挑出是质数的部分,并从最小的质数2开始除
一直重复到2不能除,然后在用下一个质数去除,除到不能除
但这个想法太暴力了,而且我自己写了几行真的写不出来
只好看答案
def factorPrime(n):
answer = str(n) + "="
# if n cannot be divided by 2
# then n cannot be divided any mulitples of 2
p = 2
while p <= n:
if n % p == 0:
answer += str(p) + "x"
n = n / p
else:
p += 1
return answer[: len(answer) - 1]
我的理解是
首先设一个answer,后面的str(n)+"=" 这行应该只是为了美观
就是最后会变成120=2*2*2*3*5而已
第2第3行感觉是我一开始想法的具体且简洁可行的方式
他将2设成第一个拿来被除的质数,所以当n不能再被2整除
n也不能被任何2的倍数整除
所以当p<=n的时候,如果n%p可以整除
answer就加上这个str(p)+"x"
然后n变成n/=p
如果没办法被2整除,p就+1
全部跑完一轮就是答案了
Write a function called "intersection" that takes 2 lists, and returns an list
of elements that are in the intersection of 2 list.
这题我的答案gpt说超级没效率
不过他说是对的
def intersection(lst1, lst2):
result = []
index_lst1 = 0
index_lst2 = 0
for i in range(0, len(lst1)):
for j in range(0, len(lst2)):
# print(lst1[i])
if lst1[i] == lst2[j] and lst1[i] not in result:
# print(lst1[i])
# print(lst2[j])
result.append(lst1[i])
# index_lst2 += 1
# result.append(lst1[index_lst1])
# index_lst2 += 1
return result
print(intersection([1, 3, 4, 6, 10], [5, 11, 4, 3, 100, 144, 0]))
print(intersection([1, 3, 3, 3, 4, 6, 10], [5, 11, 4, 3, 100, 144, 0]))
# returns [3, 4]
index_lst1 = 0
index_lst2 = 0
这两行是一开始想法的痕迹,后来没用到
我本来是想用上次解007那题的方式
从lst1[0]开始,去对照lst2的每一个数字
当有重复就记录下来,但不知道为啥写不出来
所以就笨方法
设i和j,去把两个lst所有数字比较一次,一样就记录下来
然后去重,已经在result里的就不再记就可以
#Write a function called "flatten" that flattens an list.
flatten([1, [[], 2, [0, [1]], [3]], [1, 3, [3], [4, [1]], [2]]]);
# returns [1, 2, 0, 1, 3, 1, 3, 3, 4, 1, 2
一个大lst里面有3个中lst
3个中lst里面又有两个有4个小lst
所以我要做的事应该是用力往深处抽插,插到数字按顺序拔出来,一个一个排好就可以
目前卡在插进去了抽不出来,先写研究所要的东西==
这自学比较没压力
作者: SecondRun (雨夜琴声)   2024-08-11 12:30:00
那解答看起来也挺烂的
楼主: erimow (Erimo)   2024-08-11 12:32:00
因为他要写给初学者看吧 初学者用解答==
作者: Smallsh (Smallsh)   2024-08-11 12:32:00
大师
楼主: erimow (Erimo)   2024-08-11 12:33:00
写得太好我才真的看不懂

Links booklink

Contact Us: admin [ a t ] ucptt.com