我需要为我的硕士论文将一些Python和Java例程翻译成伪代码,但我遇到了一些问题,无法想出一个具有以下特点的语法/风格:
- 一致性
- 易于理解
- 不过于冗长
- 不要过于接近自然语言
- 不要过于接近某种具体的编程语言。
DIJKSTRA(G, w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 S ← Ø
3 Q ← V[G]
4 while Q ≠ Ø
5 do u ← EXTRACT-MIN(Q)
6 S ← S ∪{u}
7 for each vertex v ∈ Adj[u]
8 do RELAX(u, v, w)
newalg
和clrscode
。后者是Cormen本人编写的。我不理解你对“不要太接近某些具体的编程语言”的要求。
Python通常被认为是编写伪代码的良好选择。也许一个略微简化的Python版本适合您。
在数学和技术领域中,Pascal一直是传统上最接近伪代码的语言。我不知道为什么,它就是这样。
我有一些关于这个理论的书(哦,我不知道,可能有10本)放在书架上。
Python可以是一种很好的编程语言,但有时也会变得难以阅读,这真是奇怪。老的编程语言更难以变得难以阅读——因为它们相对“简单”(谨慎地看待),比今天的语言要简单。它们可能更难以理解程序正在做什么,但更容易阅读(需要更少的语法/语言特性来理解程序的功能)。
这篇文章有些陈旧,但希望对其他人有所帮助。
《算法导论》(Cormen、Leiserson 和 Rivest 合写)是一本关于算法的好书,但其“伪代码”令人困惑。如 Q[1...n] 这样的记法并不清晰,需要在“伪代码”之外进行说明。此外,像《算法导论》这样的书籍喜欢使用数学语法,这违反了伪代码的一个目的。
伪代码应该做到两件事:抽象掉语法和易于阅读。如果实际代码比伪代码更具描述性,则它就不是伪代码。
假设你要编写一个简单的程序。
屏幕设计:
Welcome to the Consumer Discount Program!
Please enter the customers subtotal: 9999.99
The customer receives a 10 percent discount
The customer receives a 20 percent discount
The customer does not receive a discount
The customer's total is: 9999.99
TOTAL: double
SUB_TOTAL: double
DISCOUNT: double
伪代码:
DISCOUNT_PROGRAM
Print "Welcome to the Consumer Discount Program!"
Print "Please enter the customers subtotal:"
Input SUB_TOTAL
Select the case for SUB_TOTAL
SUB_TOTAL > 10000 AND SUB_TOTAL <= 50000
DISCOUNT = 0.1
Print "The customer receives a 10 percent discount"
SUB_TOTAL > 50000
DISCOUNT = 0.2
Print "The customer receives a 20 percent discount"
Otherwise
DISCOUNT = 0
Print "The customer does not a receive a discount"
TOTAL = SUB_TOTAL - (SUB_TOTAL * DISCOUNT)
Print "The customer's total is:", TOTAL
Print "Some stuff"
VALUE = 2 + 1
SOME_FUNCTION(SOME_VARIABLE)
选择:
if condition
Do one extra thing
if condition
do one extra thing
else
do one extra thing
if condition
do one extra thing
else if condition
do one extra thing
else
do one extra thing
Select the case for SYSTEM_NAME
condition 1
statement 1
condition 2
statement 2
condition 3
statement 3
otherwise
statement 4
while condition
do stuff
for SOME_VALUE TO ANOTHER_VALUE
do stuff
将其与此 N皇后问题的“伪代码”(https://en.wikipedia.org/wiki/Eight_queens_puzzle)进行比较:
PlaceQueens(Q[1 .. n],r)
if r = n + 1
print Q
else
for j ← 1 to n
legal ← True
for i ← 1 to r − 1
if (Q[i] = j) or (Q[i] = j + r − i) or (Q[i] = j − r + i)
legal ← False
if legal
Q[r] ← j
PlaceQueens(Q[1 .. n],r + 1)