avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

2596.Check the Cavaliers patrol plan

  2024-01-01
字数统计: 215字   |   阅读时长: 1min

topic:

screenshot2023-09-13 afternoon5.14.07.png
topic链接

Thought:

I thought it was at first glance NQueen question,Then read it for a long time and didn’t read the question for a long time,So take a look at the answer()。
turn out to begrid[row][col] Index cells (row, col) It is the first of the Cavaliers grid[row][col] Cell。meanspos[grid[i][j]] = (i, j)
Then I understand,Set the initial value(2,1),Then from(0,0)Start traverse each point andlastIs the difference in the value of the value?2,1or1,2,if not,Just returnFalse。

In the answer,ylbUsepairwiseThe method of calculating the two elements of the front and rear
for (x1, y1), (x2, y2) in pairwise(pos): dx, dy = abs(x1 - x2), abs(y1 - y2)

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def checkValidGrid(self, grid: List[List[int]]) -> bool:
if grid[0][0]:
return False
n = len(grid)
pos = [(0, 0)] * (n * n)
for i in range(n):
for j in range(n):
pos[grid[i][j]] = (i, j)
last = -2, 1
for i, j in pos:
if (abs(i - last[0]) == 2 and abs(j - last[1]) == 1) or \
(abs(i - last[0]) == 1 and abs(j - last[1]) == 2):
pass
else:
print(i, j)
return False
last = (i, j)

return True
  • Python
  • answer
  • Array
  • matrix
  • simulation
  • Priority search
  • In -depth priority search

show all >>

2 .Two numbers

  2024-01-01
字数统计: 388字   |   阅读时长: 2min

topic:

2023-07-03.png
[2].Two numbers.md

Thought:

I originally wrote the stupidest way,把两个Linked转换成数字,Then add,再转换成Linked。But it’s strange that I was right when I was running locally,But it’s wrong when you submit,
What is deducted is a very strange oneprecompiled.listnode.ListNode,But mine is'__main__.ListNode'。
So I can only watch0x3fs answer。

Two node values ​​each time`l1.val`,`l2.val`In -digit`carry`Add,Divide 10 The remaining number is the digital digit that the current node needs to be saved,Divide10The business is the new position value

Code implementation,There is a trick to simplify code:ifrecursion中发现l2Length ratio ratiol1Longer,So it can be exchangedl1and l2,ensure l1Not an empty node,So as to simplify code logic。

Code:

1
2
3
4
5
6
7
8
9
10
11
class Solution:
# l1 and l2 Node for current traversal,carry Be in place
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode], carry=0) -> Optional[ListNode]:
if l1 is None and l2 is None: # recursion边界:l1 and l2 All empty nodes
return ListNode(carry) if carry else None # If you are in place,Just create an additional node
if l1 is None: # if l1 Empty,Then then l2 一定Not an empty node
l1, l2 = l2, l1 # exchange l1 and l2,ensure l1 non empty,从而简化Code
carry += l1.val + (l2.val if l2 else 0) # 节点值andcarry加在一起
l1.val = carry % 10 # Each node saves a digital position
l1.next = self.addTwoNumbers(l1.next, l2.next if l2 else None, carry // 10) # carry
return l1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode], carry = 0) -> Optional[ListNode]:
l1_list = []
l2_list=[]
def recursion_list(node:ListNode, listt):
if not node:
return listt
listt.append(node.val)
return recursion_list(node.next, listt)
l1_list = recursion_list(l1, l1_list)
l2_list = recursion_list(l2, l2_list)
l1_list = ''.join(map(str, l1_list))
l2_list = ''.join(map(str, l2_list))
l3 = str(int(l1_list)+int(l2_list))
print(l3)
def recursion_linkArray(num):
if not num:
return None
head = ListNode(0)
current = head
for c in num:
current.next = ListNode(int(c))
current = current.next
return head.next
head = recursion_linkArray(l3[::-1])
print(recursion_list(head, []))
print(type(l1), type(head))
return head
  • Python
  • answer
  • math
  • Linked
  • recursion

show all >>

213.Hiccup III

  2024-01-01
字数统计: 158字   |   阅读时长: 1min

topic:

screenshot2023-09-18 afternoon1.08.41.png
topic链接

Thought:

Reference ylb 大佬的answer,
这道题andHiccup1and2The difference is,这道题是一棵Binary tree,And you can’t rob the neighboring node。
So his youngest child problem is:Robbing the current node,You can’t rob your left and right children。
If you steal root node,那么不能偷取其左右子node,Result root.val+lb +rb;
If not steal root node,那么可以偷取其左右子node,Result max(la, lb)+max(ra ,rb)。

Code:

1
2
3
4
5
6
7
8
9
10
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
def _rob(root: Optional[TreeNode]) -> (int, int):
# Minority problem:dp[i]=dp[i-2]+nums[i], dp[i-1]
if not root:
return 0, 0
la, lb = _rob(root.left)
ra, rb = _rob(root.right)
return root.val + lb + rb, max(la, lb) + max(ra, rb)
return max(_rob(root))
  • Python
  • answer
  • Dynamic planning
  • Binary tree
  • In -depth priority search
  • Tree

show all >>

LCP 06.Coin

  2024-01-01
字数统计: 65字   |   阅读时长: 1min

topic:

screenshot2023-09-21 morning12.12.09.png
topic链接

Thought:

now that4Two times,3也Two times,So it means that this question is nothing more than“As much as possible2indivual2indivual取,Turn count+1”
Although it can be optimized at running time,But I prefer to write a line

Code:

1
2
3
class Solution:
def minCount(self, coins: List[int]) -> int:
return sum(i // 2 + i % 2 for i in coins)
  • Python
  • answer
  • math
  • Array

show all >>

LCP 50.Gem supply

  2024-01-01
字数统计: 58字   |   阅读时长: 1min

topic:

screenshot2023-09-15 afternoon2.23.12.png
topic链接

Thought:

LCPThe beginning is the meaning of novice village,简单的simulation,Traversaloperations,rightgemCalculate the addition and subtraction。

Code:

1
2
3
4
5
6
7
class Solution:
def giveGem(self, gem: List[int], operations: List[List[int]]) -> int:
for i, j in operations:
trade = gem[i] // 2
gem[i] -= trade
gem[j] += trade
return max(gem)-min(gem)
  • Python
  • answer
  • Array
  • simulation

show all >>

GOlanguage# GOlanguage可爱捏

  2024-01-01
字数统计: 216字   |   阅读时长: 1min

motorcycle.svg

1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
fmt.Println("Hello world")
arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(a(arr))
}
1
2
3
4
5
6
7
8
9
10
package main

func a(x []int) []int {
for i := 0; i < len(x); i++ {
if i%2 == 0 {
x[i] = 1
}
}
return x
}
Modify the string
1
2
3
4
5
6
7
8
9
s := "hello"
c := []byte(s) // String s Convert []byte type
c[0] = 'c'
s2 := string(c) // Conversion back string type
fmt.Printf("%s\n", s2)

s := "hello"
s = "c" + s[1:] // Although the string cannot be changed,But sliced ​​operation
fmt.Printf("%s\n", s)

What to do if you want to declare a multi -line string?able to pass`To declare:

1
2
m := `hello
world`

` The string of the included isRawString,即String在代码中of形式就是打印时of形式,It has no character righteousness,Change will also output the original as the original

错误type

GoThere is a built -inerrortype,Specially used to process error information,GoofpackageThere is also a bag in iterrorsTo deal with errors:

1
2
3
4
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
  • Python
  • answer

show all >>

brief_alternate Assignment

  2024-01-01
字数统计: 791字   |   阅读时长: 4min

topic

brief_alternate.pdf
superstore_transaction.csv

Thought:

Self -studypandasData processing,Beforeimport csvMake much more useful。

What the knowledge point needs to be remembered is:

  1. df[“Name”] You can directly determine the first line as the name listed,并且返回一个只包含Nameof列表。
  2. idxmax()Return to the maximum valueindex,max()Maximum meal
  3. .loc The function is pandas An important function in it,Used to select and locate data in the data box。It allows you to choose some lines and columns,To make it DataFrame or Series Back to form。
    By using the line label and column label as the index,You can perform the following operations in the data box:
    .Choose a single line of data
    .Choose multi -line data
    .Select single -column data
    .Select multiple columns of data
    grammar: df.loc[row_indexer, column_indexer]
    in,row_indexer Is the label to choose a line,column_indexer Is the label of the column to be selected。
  4. unique()Return without duplicationvalueofnumbercount。
    code show as below:

superstore

s_p
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Import pandas library as pd
import pandas as pd

# Read CSV file named 'superstore_transaction.csv' and store it in a dataframe named 'df'
df = pd.read_csv("superstore_transaction.csv")

# Remove "$" and "," from the values in the 'Profit' column and convert it to integer
df["Profit"] = df["Profit"].str.replace('$', "").str.replace(",", "").astype(int)

# Remove "$" and "," from the values in the 'Sales' column and convert it to integer
df["Sales"] = df["Sales"].str.replace('$', "").str.replace(",", "").astype(int)

# Get the index of the row with the maximum value in the 'Profit' column and store it in 'col_max_profit'
col_max_profit = df["Profit"].idxmax()
# Get the index of the row with the maximum value in the 'Sales' column and store it in 'col_max_sales'
col_max_sales = df["Sales"].idxmax()

# Store the details of the transaction with highest sales
highest_sales_info = [
"=========================\n"
"HIGHEST SALES TRANSACTION\n"
"=========================\n",
"Category: {}\n".format(df.loc[col_max_sales, "Category"]),
"Customer Name: {}\n".format(df.loc[col_max_sales, "Customer Name"]),
"Product Name: {}\n".format(df.loc[col_max_sales, "Product Name"]),
"Segment: {}\n".format(df.loc[col_max_sales, "Segment"]),
"Sub-Category: {}\n".format(df.loc[col_max_sales, "Sub-Category"]),
"Profit: {}\n".format(df["Sales"].max()),
]

# Store the details of the transaction with the highest profit
highest_profit_info = [
"==========================\n"
"HIGHEST PROFIT TRANSACTION\n"
"==========================\n",
"Category: {}\n".format(df.loc[col_max_profit, "Category"]),
"Customer Name: {}\n".format(df.loc[col_max_profit, "Customer Name"]),
"Product Name: {}\n".format(df.loc[col_max_profit, "Product Name"]),
"Segment: {}\n".format(df.loc[col_max_profit, "Segment"]),
"Sub-Category: {}\n".format(df.loc[col_max_profit, "Sub-Category"]),
"Profit: {}\n".format(df["Profit"].max()),
]

# Open a file named 'summary_report.txt' in 'append' mode and store it in 'file'
with open("summary_report.txt", "a") as file:
# Write the 'highest_sales_info' details to the file
file.write(''.join(highest_sales_info))
file.write(''.join(highest_profit_info))

api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import requests

url = ""
payload = {}
headers = {
"apikey": ""
}
r = requests.request("GET", url, headers=headers, data=payload) # responseAPI
# 查看response结果
print("Status code:", r.status_code)
# Back content isjsonFormat file
# WillAPIresponse存储在一个变量中
# json()Function only decodesjsonFormat return
response_dict = r.json()
# print(response_dict)
# process result 获得response字典
# 探索有关仓库of信息 response_dict字典of嵌套
# print(response_dict['info']['rate'])

f = open("summary_report.txt", "w")
head = [
"=================================================\n"
"SINGAPORE TO US DOLLAR EXCHANGE RATE IN REAL TIME\n"
"=================================================\n"
]
f.writelines(head)
f.writelines([str(response_dict['info']['rate'])+"\n"])
f.close()
print("over")

customers
1
2
3
4
5
6
7
8
9
10
11
12
import pandas as pd

df = pd.read_csv("superstore_transaction.csv")
highest_sales_info = [
"====================\n"
"SUPERSTORE CUSTOMERS\n"
"====================\n",
"TOTAL: {}\n".format(df["Customer Name"].nunique(), "Category"),
]
with open("summary_report.txt", "a") as file:
file.writelines(highest_sales_info)

  • Python
  • pandas

show all >>

Some doubt

  2024-01-01
字数统计: 575字   |   阅读时长: 3min

Table of contents

1.background
2.holiday
[3.Programming preference](#3Programming preference)


1.background:

We have7One direction,Distinguished
1. Artificial Intelligence
2. Bioinformatics
3. Information Technology
4. Database Systems
5. e-Commerce Systems
6. Internet working
7. Data Science and Engineering

My course selection direction for the next semester isArtificial Intelligence
Not because I like itAIdirection,It’s just because there is a course called next semester9814,Very good to get high scores,And isAICompulsory course。

2.holiday:

I chose a course last semester,TaughtPython,feelPythonIs the best language in the world,So I always plan to learn。这个holiday的编程比赛and练习题全部都是用Pythonmade。

but在这个holiday的实践中发现,PythonThe place where it is used is very narrow,在国内基本上只有人工智能的direction。
and我holiday自学吴恩达的Machine LearningCourse,feel不是很感兴趣,If“Can’t find a job if you don’t learn this”,
Then I can learn。
It’s just that classmates are constantly talking,人工智能direction找不到工作,Basically, for the model alchemy,No technical content。I thought about it,feel说得对。Similar toChatGPTAnd the commercialization of painting modelAIIt’s not what I can write。


If it is a back end?
There are two ways in front of me to go:Java and C++。
I asked about the domestic market,JavaThe demand seems to be greater,但也更接近于饱and。
ThatJavaand*C++*What about the needs in foreign countries??PythonIs there a need in abroad??


If it is the front end?
It feels like there is no case that can succeed in the front end,BasicallyFull stack。
This blog actually made yesterday,Getting started is simple,But it feels very difficult to deepen,There are relatively few documents on the Internet。


If it is data analysis?
感觉and人工智能差不多,But the road should be widespread,And it seems to be able to use itPython?I’m not sure。


3.Programming preference:

For my preferences,I have only learned two languages ​​now,C and Python(JavaandC++andC#Already returned to the teacher)。
CIf you are, even a linked list has to be knocked out by yourself,And I am obsessed withPythonConvenience。
For example, the same question,I take753. Crack the safeGive an example,itsPythonThe solution is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def crackSafe(self, n: int, k: int) -> str:
seen = set()
ans = list()
highest = 10 ** (n - 1)

def dfs(node: int):
for x in range(k):
nei = node * 10 + x
if nei not in seen:
seen.add(nei)
dfs(nei % highest)
ans.append(str(x))

dfs(0)
return "".join(ans) + "0" * (n - 1)

andC++I have to write:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
private:
unordered_set<int> seen;
string ans;
int highest;
int k;

public:
void dfs(int node) {
for (int x = 0; x < k; ++x) {
int nei = node * 10 + x;
if (!seen.count(nei)) {
seen.insert(nei);
dfs(nei % highest);
ans += (x + '0');
}
}
}

string crackSafe(int n, int k) {
highest = pow(10, n - 1);
this->k = k;
dfs(0);
ans += string(n - 1, '0');
return ans;
}
};

CIt’s even longer。So what is doubtful lies in,feelPythongood,butPythonLack of posts。

置顶
  • Python
  • encryption

show all >>

Inline expansion

  2024-01-01
字数统计: 340字   |   阅读时长: 2min

9021Everyone is running for time,This happens to be$algorithm$Essence of development。

screenshot2023-10-08 afternoon11.35.38.png

“There is a bunch of functions of code and code without function calls,Which runs faster?”

Let’s talk about conclusions first:The code without function call runs faster。butreadabilityworse,andThe gap between running speed is not large。

We can ask the following questions:

  1. Why does the frequency call of the function cause a decline in performance?
  2. How to solve the decline in this performance?
  3. What is the Internal Union Extension?

Why does the frequency call of the function cause a decline in performance?

Function calls usually involve pressing the parameters into the stack、Jump to function code、Execute function code、Put the return value in the appropriate position、Then jump back to the place where the call function。

How to solve the decline in this performance?

Tailing recursive optimization、Dead code elimination、Constant communication and constant folding、Internal United Development, etc.。This chapter mainly talks about the expansion of the Internal United Nations。

What is the Internal Union Extension

Wikipedia:

Inline expansion is used to eliminate the time overhead (excess time) when a function is called. It is typically used for functions that execute frequently. It also has a space benefit for very small functions, and is an enabling transformation for other optimizations.
Internal expansion is used to eliminate the time overhead of the call function(Excess time)。It is usually used for frequent execution functions。For very small functions,It also has space advantages,And it is a conversion that supports other optimizations。

Frequent calling functions may cause some additional overhead,This overhead is due to the stack operation when the function calls、Factors caused by parameter transmission and return value processing。

To avoid this overhead,The compiler will try to replace the code of the function call to the function body,This process is called the Inner Union Extension(inline expansion)。

ref:
https://www.jstage.jst.go.jp/article/sptj1978/44/3/44_3_206/_pdf

https://www.semanticscholar.org/search?q=Inline%20expansion&sort=relevance

  • Composition principle

show all >>

math

  2024-01-01
转载   字数统计: 50字   |   阅读时长: 1min

like Rendering

more >>
  • math

show all >>

<< 上一页1…111213141516下一页 >>

153 篇 | 133k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号