search
HomeBackend DevelopmentPython TutorialLet's talk about python programming ideas

This article brings you relevant knowledge about python, which mainly organizes issues related to programming ideas. Python is an object-oriented oop (Object Oriented Programming) scripting language. The core of programming thinking is to understand functional logic. Let’s take a look at it. I hope it will be helpful to everyone.

Let's talk about python programming ideas

Recommended learning: python video tutorial

Python is an object-orientedoop(Object Oriented Programming) scripting language.

Object-oriented is a method that uses the concept of objects (entities) to build models and simulate the objective world to analyze, design, and implement software.

In object-oriented programming, objects contain two meanings, one of which is data and the other is action. The object-oriented approach combines data and methods into a whole and then models it systemically.

The core of python programming thinking isunderstanding functional logic. If you don’t understand the logic of solving a problem, then your code will look like It is very confusing and difficult to read, so once the logic is clear and the functions are systematically programmed according to modules, your code design will definitely be beautiful! ! !

1 Basic programming pattern

Any programming includes IPO, which represent the following:

  • I: Input input , the input of the program

  • P: Process processing, the main logical process of the program

  • O: Output, the output of the program

So if you want to implement a certain function through a computer, thenThe basic programming pattern contains three parts, as follows:

  • Determine the IPO: clarify the input and output of the functions that need to be realized, as well as the main implementation logic process;

  • Write the program: carry out the logical process of calculation and solution through programming language Design display;

  • Debugging program: debug the written program according to the logical process to ensure that the program runs correctly according to the correct logic.

2 Effective method to solve complex problems: top-down (design)

##2.1 Top-down-divide and conquer

If the logic to realize the function is relatively complex, it needs to be

modularly designed to decompose the complex problem into multiple Simple problems, among which simple problems can continue to be decomposed into simpler problems until the functional logic can be realized through module programming, which is also the top-down characteristic of programming. The summary is as follows:

    Express a general problem into a form composed of several small problems
  • Use the same method to further decompose small problems
  • Until, the small problem can be Computer simple and clear solution

2.2 Example 1: Sports competition analysis

2.2.1 Overall program framework

printlnfo()                                                                               using using using                           ’ s ’s ’ s ‐   ‐ ‐ ‐ ‐ ‐ Step 1: Print the introductory information of the program                    

getlnputs()                                          .                           . Step 3: Use the ability values ​​of players A and B to simulate n games.
printSummary() Step 4: Output the number and probability of players A and B winning the game

# 导入python资源包
from random import random
 
# 用户体验模块 
def printIntro():
    print("这个程序模拟两个选手A和B的某种竞技比赛")
    print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
 
# 获得A和B的能力值与场次模块 
def getIntputs():
    a = eval(input("请输入A的能力值(0-1):"))
    b = eval(input("请输入B的能力值(0-1):"))
    n = eval(input("模拟比赛的场次:"))
    return a, b, n
 
# 模拟n局比赛模块 
def simNGames(n, probA, probB):
    winsA, winsB = 0, 0
    for i in range(n):
        scoreA, scoreB = simOneGame(probA, probB)
        if scoreA > scoreB:
            winsA += 1
        else:
            winsB += 1
    return winsA, winsB
 
# 判断比赛结束条件 
def gameOver(a, b):
    return a == 15 or b == 15
 
# 模拟n次单局比赛=模拟n局比赛 
def simOneGame(probA, probB):
    scoreA, scoreB = 0, 0
    serving = "A"
    while not gameOver(scoreA, scoreB):
        if serving == "A":
            if random() 
2.2.3 Test results

##2.3 Example 2: Fibonacci The deed sequence

The top-down method is actually

using recursion to solve the sub-problem. The final solution only needs to call the recursive formula, sub- The problem is gradually solved recursively to the lower levels.

Programming:

cache = {}

def fib(number):
    if number in cache:
        return cache[number]
    if number == 0 or number == 1:
        return 1
    else:
        cache[number] = fib(number - 1) + fib(number - 2)
    return cache[number]

if __name__ == '__main__':
    print(fib(35))

Run result:

14930352
>>>

Understanding top-down design thinking: divide and conquer

3 Effective testing methods for gradually building complex systems: bottom-up (execution)

3.1 Bottom-up-modular integration

自底向上(执行)就是一种逐步组建复杂系统的有效测试方法。首先将需要解决的问题分为各个三元进行测试,接着按照自顶向下相反的路径进行操作,然后对各个单元进行逐步组装,直至系统各部分以组装的思路都经过测试和验证。

理解自底向上的执行思维:模块化集成

自底向上分析思想:

  • 任何时候栈中符号串和剩余符号串组成一个句型,当句柄出现在栈顶符号串中时,就用该句柄进行归约,这样一直归约到输入串只剩结束符、栈中符号只剩下开始符号,此时认为输入符号串是文法的句子,否则报错。

自底向上是⼀种求解动态规划问题的方法,它不使用递归式,而是直接使用循环来计算所有可能的结果,往上层逐渐累加子问题的解。在求解子问题的最优解的同时,也相当于是在求解整个问题的最优解。其中最难的部分是找到求解最终问题的递归关系式,或者说状态转移方程。

3.2 举例:0-1背包问题

3.2.1 问题描述

你现在想买⼀大堆算法书,有一个容量为 V 的背包,这个商店⼀共有 个商品。问题在于,你最多只能拿 W kg 的东西,其中 wi vi 分别表示第 i 个商品的重量和价值。最终的目标就是在能拿的下的情况下,获得最大价值,求解哪些物品可以放进背包。

对于每⼀个商品你有两个选择:拿或者不拿。

3.2.2 自底向上分析

⾸先要做的就是要找到“子问题”是什么。通过分析发现:每次背包新装进⼀个物品就可以把剩余的承重能力作为⼀个新的背包来求解,⼀直递推到承重为0的背包问题。

m[i,w] 表示偷到商品的总价值,其中 i 表示⼀共多少个商品,w 表示总重量,所以求解 m[i,w]就是子问题,那么看到某⼀个商品i的时候,如何决定是不是要装进背包,需要考虑以下:

  • 该物品的重量大于背包的总重量,不考虑,换下⼀个商品;
  • 该商品的重量小于背包的总重量,那么尝试把它装进去,如果装不下就把其他东西换出来,看看装进去后的总价值是不是更高了,否则还是按照之前的装法;
  • 极端情况,所有的物品都装不下或者背包的承重能力为0,那么总价值都是0;

由以上的分析,可以得出m[i,w]的状态转移方程为:

m[i,w] = max{m[i-1,w], m[i-1,w-wi]+vi}

3.2.3 程序设计

# 循环的⽅式,自底向上求解
cache = {}
items = range(1,9)
weights = [10,1,5,9,10,7,3,12,5]
values = [10,20,30,15,40,6,9,12,18]
# 最⼤承重能⼒
W = 4

def knapsack():
    for w in range(W+1):
        cache[get_key(0,w)] = 0
    for i in items:
        cache[get_key(i,0)] = 0
        for w in range(W+1):
            if w >= weights[i]:
                if cache[get_key(i-1,w-weights[i])] + values[i] > cache[get_key(i-1,w)]:
                    cache[get_key(i,w)] = values[i] + cache[get_key(i-1,w-weights[i])]
                else:
                    cache[get_key(i,w)] = cache[get_key(i-1,w)]
            else:
                cache[get_key(i,w)] = cache[get_key(i-1,w)]
    return cache[get_key(8,W)]

def get_key(i,w):
    return str(i)+','+str(w)

if __name__ == '__main__':
    # 背包把所有东西都能装进去做假设开始
    print(knapsack())
29
>>>

推荐学习:python

The above is the detailed content of Let's talk about python programming ideas. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment