How to Sort Three Numbers and Generate Fibonacci Sequences in Python
This article demonstrates two Python examples: sorting three input integers in ascending order using simple comparisons and swaps, and generating Fibonacci numbers through iterative, recursive, and list‑building methods, complete with code snippets and sample outputs.
Example 1
Problem: Input three integers x, y, z and output them in ascending order.
Analysis: Compare x with y and swap if x > y, then compare x with z and swap if x > z, ensuring x holds the smallest value.
<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
l = []
for i in range(3):
x = int(raw_input('integer:\n'))
l.append(x)
l.sort()
print l
</code>Sample input and output:
<code>integer:
8
integer:
5
integer:
6
[5, 6, 8]
</code>Example 2
Problem: Generate Fibonacci numbers.
Analysis: The Fibonacci sequence is defined recursively: F0 = 0, F1 = 1, Fn = F(n‑1) + F(n‑2) for n ≥ 2.
<code>F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1] + F[n-2] (n>=2)
</code>Method 1 – Iterative:
<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
a, b = 1, 1
for i in range(n-1):
a, b = b, a+b
return a
print fib(10) # 55
</code>Method 2 – Recursive:
<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
print fib(10) # 55
</code>Method 3 – Return full list:
<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
print fib(10) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.