n1 = 0
n2 = 1
fiblist = []
while True:
newNum = n1 + n2
fiblist.append(newNum)
n1 = n2
n2 = newNum
if newNum >= 10000:
print(flist)
break
Run Code Online (Sandbox Code Playgroud)
beginner programmer: is there an easier way to write this or some other more effective way
Your code can be simplified to the following.
fiblist = [0, 1] # initialize with first two numbers
while fiblist[-1] < 10000: # while last number <= threshold
fiblist.append(fiblist[-1] + fiblist[-2]) # next is sum of last 2 numbers
print(fiblist)
Run Code Online (Sandbox Code Playgroud)
Explanation (provided since you asked for things to learn to be a better coder)
Simplification of your code to above based upon principles from two references
Using reference 1
PEP 8 Guide: "Function names should be lowercase, with words separated by underscores as necessary to improve readability". This is Python-specific. Other languages (i.e. C++, Java, Clojure, JavaScript, etc.) have their own preferred styles. So for Python: new_num rather than newNum (i.e. not camelCase for variables and function names).
Using reference 2
Zen of Python: "Simple is better than complex".
Your while loop is overly complicated by focusing on two objectives, namely: (1) generating fibonacci numbers, and (2) printing fibonacci numbers). From Single Repository Principle we know less is better than more (i.e. objectives).
Simplify by creating code blocks with single rather than multiple objectives.
while True: # objective 1--generating fib numbers
newNum = n1 + n2
fiblist.append(newNum)
n1 = n2
n2 = newNum
if newNum >= 10000:
break
print(fiblist) # objective 2--printing fib numbers
Run Code Online (Sandbox Code Playgroud)
接下来,我们通过提高鲁棒性来简化。 健壮性——“简单的对象允许你单独关注每个任务的特殊性,并减少你在任何给定时间需要考虑的输入/输出变量的数量”。fiblist 是一个简单的对象,我们可以用它来替换 n1、n2 和 new_num,如下所示:
fiblist[-2] is n1
fiblist[-1] is n2
fiblist[-1] is new_num (after append)
Run Code Online (Sandbox Code Playgroud)
使用健壮性,代码变为:
while fiblist[-1] < 10000:
fiblist.append(fiblist[-1] + fiblist[-2])
Run Code Online (Sandbox Code Playgroud)
为了使其工作,我们需要在 while 循环之前将 fiblist 初始化为:
fiblist = [0, 1]
Run Code Online (Sandbox Code Playgroud)
因此,通过这一系列的简化,我们得到了建议的代码。
成为更好程序员的其他参考资料
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |