Fundamentals 4 min read

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.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Sort Three Numbers and Generate Fibonacci Sequences in Python

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.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

l = []
for i in range(3):
    x = int(raw_input('integer:
'))
    l.append(x)
l.sort()
print l

Sample input and output:

integer:
8
integer:
5
integer:
6
[5, 6, 8]

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.

F0 = 0    (n=0)

F1 = 1    (n=1)

Fn = F[n-1] + F[n-2] (n>=2)

Method 1 – Iterative:

#!/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

Method 2 – Recursive:

#!/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

Method 3 – Return full list:

#!/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]
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Algorithms
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.