Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci numbers python, what should i learn to be a better programmer (self taught ) [closed]

n1 = 0
n2 = 1
fiblist = []
while True:     
     newNum = n1 + n2
     fiblist.append(newNum)
     n1 = n2
     n2 = newNum
     if newNum >= 10000:
          print(flist)
          break

beginner programmer: is there an easier way to write this or some other more effective way

like image 837
anthony pizarro Avatar asked Dec 02 '19 03:12

anthony pizarro


Video Answer


1 Answers

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)

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

  1. Style guide: Python Style Guide
  2. Python Mantra: Zen of Python

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

Next, we simplify by improving robustness. Robustness — "Simple objects allow you to focus on the specificities of each task individually and reduces the amount of input/output variables you need to consider at any given time". fiblist is a simple object we can use to replace n1, n2, and new_num as follows:

fiblist[-2] is n1
fiblist[-1] is n2
fiblist[-1] is new_num (after append)

Using robustness the code becomes:

while fiblist[-1] < 10000:
    fiblist.append(fiblist[-1] + fiblist[-2])

In order for this to work, we need to initialize fiblist before the while loop to:

fiblist = [0, 1]

Thus with this sequence of simplifications, we obtain the suggested code.

Additional References to be a better Programmer

  1. Fibonacci Code Examples

  2. What Python tutorials should I read

like image 104
DarrylG Avatar answered Oct 31 '22 07:10

DarrylG