决策树编程python

by Ivan Leo

伊万·利奥(Ivan Leo)

Python如何制定决策:编程中的控制流简介 (How Python makes decisions: an introduction to Control Flow in programming)

What is control flow?

什么是控制流程?

I find it easy to think of control flow in 3 different categories

我发现很容易想到3个不同类别的控制流

  1. Loops ( While, Do while, for )循环(While,Do While,for)
  2. Decision-Making ( if-else)决策(if-else)
  3. Exception Handling (Continue, Try-Except, Pass, Break)异常处理(继续,试穿,通过,中断)

These 3 categories roughly sum up the different options available to us when we talk about Control Flow in most programming languages.

当我们谈论大多数编程语言中的“控制流”时,这3个类别大致总结了可供我们使用的不同选项。

So let’s jump right in.

因此,让我们直接进入。

循环 (Loops)

Loops are basically a simple set of instructions that gets repeated until a condition is met.

循环基本上是一组简单的指令,可以重复执行直到满足条件。

A good analogy to use for a loop is whisking cake batter:

循环的一个很好的类比是搅拌面糊:

Based on this recipe, if we use a modern day mixer, 3 minutes is the perfect amount of time to mix the batter. If you were to give instructions to someone using this recipe, it would probably look something like this.

根据此配方 ,如果我们使用现代搅拌机,则3分钟是搅拌面糊的最佳时间。 如果您要向使用此食谱的人提供指导,它可能看起来像这样。

  1. Mix eggs, flour and secret recipe混合鸡蛋,面粉和秘方
  2. Start a stopwatch and begin mixing batter启动秒表并开始搅拌面糊
  3. Mix the batter until the stopwatch displays 3 minutes混合面糊直到秒表显示3分钟

If we were to translate this into psuedo-code, it would probably look something like this

如果我们将其转换为伪代码,则可能看起来像这样

#Start Timer<....code....>time = 0
While(time != 3 minutes):    time = newvalue    mix batter

In this case, we are using time to determine if we continue to mix our batter. But this doesn’t really help us take into account specific situations when we use different ingredients.

在这种情况下,我们将花费时间来确定是否继续搅拌面糊。 但这并不能真正帮助我们在使用不同成分时考虑到特定情况。

In this case, we have a few options

在这种情况下,我们有几种选择

  1. We could monitor the consistency of the batter我们可以监视面糊的一致性
  2. OR we could experiment with a whole bunch of ingredients, record the best times for each and then refer to this record each time we mix the cakes.或者,我们可以尝试一堆配料,记录每种配料的最佳时间,然后在我们每次混合蛋糕时都参考该记录。

Now stop for a moment and think, when would we use the first option and when would we use the second option?

现在停下来思考一下,何时使用第一个选项,何时使用第二个选项?

< Intentional Blank Left Here . Do stop and think for a while :) >

<有意留在这里的空白。 停下来思考一会儿:)>

The first option is more suited towards situations where we might encounter a lot of unpredictable combinations. It therefore makes sense to not only check time but also to add the safeguard of an additional parameter.

第一种选择更适合于我们可能遇到很多不可预测的组合的情况。 因此,不仅检查时间而且增加附加参数的安全性也是有意义的。

The second option is suited towards situations where we encounter repeated instances of multiple combinations. It’s commonly known as dynamic programming.

第二种选择适用于我们遇到多个组合的重复实例的情况。 通常称为动态编程。

In Dynamic Programming, each value is calculated once and then stored in a lookup table for future access. This helps to reduce the run time of future operations by reducing the lookup time, since the value doesn’t have to be recalculated, just looked up and returned.

在动态编程中,每个值只计算一次,然后存储在查找表中以供将来访问。 通过减少查找时间,这有助于减少将来操作的运行时间,因为不必重新计算该值,只需查找并返回即可。

Now let’s convert what we’ve learnt into code and examine what we can implement in python :)

现在,让我们将学习到的内容转换为代码,并检查可以在python中实现的内容:)

码 (Code)

In python, we have two main tools to use for looping

在python中,我们有两个主要的循环工具

  1. While LoopsWhile循环
  2. For Loops对于循环

While循环 (While Loops)

While Loops allows us to run a command indefinitely.

While循环使我们可以无限期地运行命令。

x = 1y = 2
while(x=2):    print("x is looping")
while(y=2):    print("Y is looping")

In the code above, only the second while loop will evaluate while the first will not. When we run the code, we’ll get the following output

在上面的代码中,只有第二个while循环会求值,而第一个不会。 运行代码时,将获得以下输出

>>>python runapp.pyY is loopingY is loopingY is loopingY is looping....

Here’s what happens for the first variable.

这是第一个变量发生的情况。

As seen above, the while loops does not print x since it does not meet the condition stipulated in the first while loop.

如上所述,while循环不打印x,因为它不满足第一个while循环中规定的条件。

How about the second condition? Well it follows something like this:

第二个条件怎么样? 好吧,它遵循这样的东西:

As we can see, the while loop constantly checks if a condition is true and only executes if the specified condition is true.

如我们所见,while循环不断检查条件是否为真,并且仅在指定条件为真时执行。

Here are some common implementations in python:

以下是python中的一些常见实现:

#Asking for User Inputwhile True:    userinput = input("Please Input Your Name: ")    if userinput.isalpha():       break;
print("Hello %s"%(userinput))
#Dealing with dynamic Variables (i.e. Parameters that can change )no = int(input("Please Enter the number of Loops: "))i = 0
while(i<n):    print(i)

Let’s look through the two examples.

让我们看两个例子。

例子1 (Example 1)

This example code (refer above) is a sample of code we could use to grab some user input. As you code more advanced programs, you’ll be able to code more advanced programs that can check user input or do more things with user input, but for now, we’re gonna print “Hello <userinput>”:

此示例代码(请参见上文)是我们可以用来获取一些用户输入的代码示例。 在编写更高级的程序时,您将能够编写更高级的程序,这些程序可以检查用户输入或使用用户输入执行更多操作,但是现在,我们将打印“ Hello <userinput>”:

While True:

Since True is always true ( I know it’s a bit counterintuitive but bear with me), this loop will run forever. True can never not be True.

由于True始终为true(我知道这有点违反直觉,但请耐心接受),因此此循环将永远运行。 True永远不能不是True

userinput = input("Please Input Your Name: ")

This allows us to get some input from the user and store it as a string. We create a variable called userinput and store a reference to that stored string in memory. (If you’re unsure about what’s happening here, I’ve written an article on variables in python, do check it out!)

这使我们能够从用户那里获得一些输入并将其存储为字符串。 我们创建一个名为userinput的变量,并将对该存储字符串的引用存储在内存中。 (如果您不确定这里发生了什么,我已经写了一篇关于python中变量的文章 ,请检查一下!)

if userinput.isalpha():       break;

Now comes the magic sauce. The .isalpha() method allows us to check if a string solely consists of characters.

现在来了魔术酱。 .isalpha()方法允许我们检查字符串是否仅由字符组成。

#Sample Output"12a".isalpha() #This returns False"12".isalpha() #This returns False"abc".isalpha() #This returns True

Using this function allows us to check if the user has input a proper name that consists solely of characters in the alphabet.

使用此功能,我们可以检查用户是否输入了仅由字母字符组成的专有名称。

If the user has input a proper name, the break function then allows us to exit the loop.

如果用户输入了适当的名称,则break函数将允许我们退出循环。

print("Hello %s"%(userinput))

This then allows us to execute the final line of code, printing out the string “hello <userName>”.

然后,这使我们能够执行代码的最后一行,打印出字符串“ hello <userName>”。

示例2:循环多个循环 (Example 2 : Looping for a number of Loops)

no = int(input("Please Enter the number of Loops: "))

This first line of code allows the user to input a certain value from the command line before converting it to an integer. This is done using the int() value.

该第一行代码允许用户在将其转换为整数之前从命令行输入特定值。 这是使用int()值完成的。

i = 0
while(i<n):    print(i)

Next we initialise a variable i to 0 to keep track of the number of loops we want to run, printing the value of i each time:

接下来,我们将变量i初始化为0,以跟踪我们要运行的循环数,每次都打印i的值:

#Sample OutputPlease Enter the number of Loops: 501234

It’s helpful to think of a while loop as such

这样考虑一下while循环会很有帮助

while(test_expression):    <code>

For Loops

对于循环

For Loops work a little differently than while Loops. Let’s examine the syntax

For循环的工作方式与while循环有所不同。 让我们检查一下语法

#Normal For LoopFor i in range(1,6,1):    <code>
#Iteration Loopfor i in [1,2,3,4,5]:    <code>

What’s happening here?

这里发生了什么事?

When you declare a For loop as seen in the first case , you are invoking what is known as a generator. This generates a list of numbers using the parameters you have specified.

如第一种情况所示,在声明For循环时,您正在调用所谓的生成器。 这将使用您指定的参数生成数字列表。

It’s helpful to think of the generator as a function that calls a list for now. While that’s not exactly how it works, it’s a close approximation. More to come on this topic!

将生成器视为现在调用列表的函数会很有帮助。 虽然这并不完全是它的工作原理,但这是一个近似值。 有关此主题的更多信息!

#This generates a list with values [1,2,3,4,5]For i in range(1,6,1):    <code>

This generated list can then be iterated using the inbuilt iteration function in python. This just means that we can call each item in this list in the order they are stored in.

然后可以使用python中的内置迭代函数来迭代生成的列表。 这只是意味着我们可以按照存储顺序调用此列表中的每个项目。

The second example functions in a similar way. In this case however, we explicitly specify the list to be iterated over instead of generating it with the range function.

第二个示例以类似的方式运行。 但是,在这种情况下,我们明确指定要迭代的列表,而不是使用range函数生成该列表。

for i in [1,2,3,4,5]:    <code>

Some useful cases

一些有用的案例

#Printing out items in a list
x = [...values...]for i in x:   print(i)
#Iterating Over items in a listy = [x**2 for i in x] #This is also known as list comprehension

Let’s examine these cases in greater detail!

让我们更详细地研究这些情况!

Example 1

例子1

x = [....values...]for i in x:

In this case, we are initialising a list called x with a certain number of variables. We then proceed to iterate over each value in x.

在这种情况下,我们正在初始化一个带有一定数量变量的名为x的列表。 然后,我们继续遍历x中的每个值。

print(i) #This prints out each value of x in its specified order

We call each value in x, in this case referred to as i, and print it out.

我们将x中的每个值(在这种情况下称为i)调用,并将其打印出来。

#Sample Outputx  = [1,2,3,4]for i in x:     print(i)
>>>python app.py1234

Example 2

例子2

y = [x**2 for i in x]

Let’s try to rewrite this in another form

让我们尝试以另一种形式重写它

for i in x:    y.append(x**2)
y = [x**2 for i in x]

These 2 are the same thing! However, list comprehensions tend to be faster.

这两个是同一回事! 但是,列表理解往往会更快。

做决定 (Decision-Making)

What comes to your mind when you think of decision-making while writing a program? For me, it’s definitely decision trees and flowcharts.

当您在编写程序时想到决策时,会想到什么? 对我来说,绝对是决策树和流程图。

While some of these (like the one below) are definitely ridiculous, I think they still offer a useful mental framework to visualise your program flow:

尽管其中一些(如以下示例)绝对是荒谬的,但我认为它们仍然提供了有用的思维框架来可视化您的程序流程:

I’ll use an analogy to talk about this before going on to show how to implement this using if-else and break-continue syntax.

在继续展示如何使用if-else和break-continue语法来实现这一点之前,我将使用一个类比来谈论它。

类比时间 (Analogy-Time)

Imagine that you’re trying to find the perfect restaurant for date night. You want to find something that is affordable and chic

想象一下,您正在寻找约会之夜的最佳餐厅。 您想找到实惠且时尚的东西

While you’re looking through trip advisor, your thought process would be something like this.

当您通过旅行顾问查找时,您的思考过程将是这样的。

You would only consider things that were cheap and chic. So every time you looked at a restaurant, you would check to see if it fit your criteria and eliminate those that did not.

您只会考虑便宜又时尚的东西。 因此,每次查看餐厅时,您都要检查它是否符合您的条件,并剔除不符合条件的人。

Similarly, decision making in a program works the same way. You set a bunch of possible scenarios and your program reacts accordingly.

同样,程序中的决策以相同的方式进行。 您设置了一堆可能的方案,并且程序会做出相应的React。

码 (code)

Let’s look at a simple program to find numbers which are multiples of two.

让我们看一个简单的程序,查找两个数字的倍数。

import random
x = random.randint(0,1000)
if x%2==0:
print(str(x)+" is a multiple of 2")
else:
print(str(x)+" is not a multiple of 2")

How does this program work?

该程序如何工作?

  1. We first generate a random number from 0 to 1000我们首先生成一个从0到1000的随机数
  2. We then divide this random number, x, by 2 and check if there is a remainder. ( % returns the remainder of a division )然后,我们将此随机数x除以2,然后检查是否有余数。 (%返回除法的余数)
  3. If there is no remainder, we print the statement “X is a multiple of 2”如果没有余数,我们将打印语句“ X是2的倍数”
  4. if there is a remainder, we print the statement “x is not a multiple of 2”如果有余数,则打印语句“ x不是2的倍数”

We know that all multiples of 2 follow the formula 2i where i is an integer. Therefore all multiples of 2 have to be divisible by 2. Hence, we use that as a way to evaluate if a number is a multiple of 2.

我们知道2的所有倍数都遵循公式2i,其中i是整数。 因此2的所有倍数必须被2整除。因此,我们将其用作评估数字是否为2的倍数的方法。

This can be visualised as a decision tree, as seen below.

可以将其可视化为决策树,如下所示。

As we can see, an if-else decision loop allows us to account for the values of our variables, allowing our program to return a different output w.r.t their values.

如我们所见,if-else决策循环使我们能够考虑变量的值,从而使程序可以通过其值返回不同的输出。

We can also use an if-else loop to account for the type of variables by modifying the above syntax slightly.

我们还可以使用if-else循环通过稍微修改上述语法来说明变量的类型。

def checking(n):
if type(n) == str:
print("String!")
elif type(n) == int:
print("Integer!")
else:
print("we're not sure what n is....")
x = [1,2,3,'a','bac',2.12]for i in x:    checking(i)

Pointers to note:

注意事项:

  1. We’ve used the elif statement in this context to add an additional possible case of n that we want to account for.在这种情况下,我们使用了elif语句来添加我们要考虑的n的其他可能情况。
  2. We’ve also used type as a condition to evaluate the variable instead of the original use of the value of the variable.我们还使用类型作为条件来评估变量,而不是最初使用变量的值。

异常处理 (Exception-Handling)

Sometimes in python, you will find that you’ll need to account for exceptions. These could be invalid operations (Eg. trying to divide 0 or stack overflow) or a class of values that you simply aren’t interested in.

有时在python中,您会发现需要考虑例外情况。 这些可能是无效的操作(例如,试图除以0或堆栈溢出)或您根本不感兴趣的一类值。

In these cases, we can use

在这种情况下,我们可以使用

  1. Continue继续
  2. Pass通过
  3. Try-except试穿除外
  4. Break打破

I’ll try to give a brief overview of the usage of these exception handling operations.

我将简要概述这些异常处理操作的用法。

继续 (Continue)

Look at the code below and try to guess what continue does:

查看下面的代码,并尝试猜测继续执行的操作:

y = [1,2,3,4,5,6,6,7,8]
x = []
for i in y:
if i in x:
continue
else:
x.append(i)     print(i)
print(x)

If you guessed that it basically skips the rest of the chunk of code, you’re right! Continue does just that.

如果您猜到它基本上会跳过其余的代码块,那么您是对的! 继续就是这样。

In the code above, we are trying to remove the duplicate values in y. We do so in the code using this process

在上面的代码中,我们试图删除y中的重复值。 我们使用此过程在代码中执行此操作

  1. We check if the variable, i, that we are evaluating is within the new list x.我们检查正在评估的变量i是否在新列表x内。
  2. If it is within the new list x, we “continue” and proceed to evaluate the next variable within list y.如果它在新列表x中,则我们“继续”并继续求值列表y中的下一个变量。
  3. if it is not within the new list x, we do not “continue” and instead proceed to append the variable to list x.如果它不在新列表x中,则我们不会“继续”,而是继续将变量追加到列表x中。

This eventually helps us to remove all the duplicate variables within x.

这最终将帮助我们删除x中所有重复的变量。

通过 (Pass)

y = [1,2,3,4,5,6,6,7,8]
x = []
for i in y:
if i in x:
pass
else:
x.append(i)    print(i)
print(x)

If you were to run the code, you would also notice that all of the duplicate variables were printed! This is a key difference between pass and continue.

如果要运行代码,您还会注意到所有重复的变量都已打印! 这是通过和继续之间的关键区别。

This difference becomes useful if you are trying to run additional operations on the non-duplicate variables (eg. get a sum).

如果您尝试对非重复变量运行其他操作(例如,求和),则此区别将非常有用。

打破 (Break)

Break does what it says. It breaks your program or sub-program when you meet an exception.

打破了它所说的。 遇到异常时,它将中断您的程序或子程序。

Here’s a useful example of break:

这是一个有用的中断示例:

x = [1,3,5,7,2,3,5,7]
count = 0
for i in range(len(x)):
if x[i]%2==0:
print("There is an even number at index " + str(i))
break
else:
continue

In this example, we are trying to find the index of the first even number in our list x. Break allows us to do so by exiting the loop prematurely!

在此示例中,我们试图找到列表x中第一个偶数的索引。 Break允许我们过早退出循环!

试穿 (Try-Except)

Try-Except syntax is especially useful when it comes to dealing with errors in reading files or evaluating syntax. Some of the common exception errors are

当处理读取文件或评估语法中的错误时,Try-Except语法特别有用。 一些常见的异常错误是

  1. IOError: An inability to open the fileIOError:无法打开文件
  2. ImportError: Python cannot find and open the module you want to importImportError:Python无法找到并打开您要导入的模块
  3. ValueError: When you pass a value into a function with the wrong type or valueValueError:当您将值传递给类型或值错误的函数时
  4. KeyboardInterrupt: When you prematurely terminate your programKeyboardInterrupt:过早终止程序时
  5. EOFerror: When you’ve reached the end of the fileEOFerror:到达文件末尾时

Here’s an example of us trying to check for a ValueError:

这是我们尝试检查ValueError的示例:

try:
x = int(input("Please input some numbers: "))
print(x)
except ValueError as ve:
print("Please input numbers. NUMBERS not letters")

This program works because strings and letters cannot be coerced into integers. (Unless they’re integers which have been stored as strings i.e. “2”, “3” etc.)

该程序有效,因为不能将字符串和字母强制转换为整数。 (除非它们是已存储为字符串的整数,即“ 2”,“ 3”等。)

For those working with importing files, you might be familiar with ImportErrors. These can be accounted for by using the following syntax:

对于那些使用导入文件的人,您可能熟悉ImportErrors。 这些可以通过使用以下语法来解决:

try:
f = open('nofile.txt')
except FileNotFoundError:
print("Erm...there's no such file man")

The Try-except syntax can be thought of as such.

Try-except语法可以这样考虑。

try:    <code to be run in a nice world>except <Most Likely Error Name>:    <code to be run in error case 1>except <Another Likely Error>:    <code to be run in another unlikely error>

结论 (Conclusion)

This sorta sums up basic decision making in Python and many other programming languages. While the exact syntax will definitely differ, the basic principles are roughly the same.

这种归纳总结了Python和许多其他编程语言中的基本决策。 尽管确切的语法肯定会有所不同,但基本原理大致相同。

Once you’ve got the hang of control flow, you’ll be able to build programs that will make a big difference and can work the way you want! :)

一旦掌握了控制流程,就可以构建将产生重大变化并可以按您想要的方式工作的程序! :)

If you’ll like to read more about Variables in Python, check out an article I wrote on them here!

如果您想了解有关Python中变量的更多信息,请查看我在此处写的关于它们的文章!

翻译自: https://www.freecodecamp.org/news/control-flow-in-programming-b9fb4f4539c/

决策树编程python

决策树编程python_Python如何制定决策:编程中的控制流简介相关推荐

  1. 阿里技术专家加多:Java异步编程实战之基于JDK中的Future实现异步编程 | 文末赠书...

    正文共:14244 字 8 图 预计阅读时间: 36 分钟 本节内容摘自<Java异步编程实战>中的一小节. 一.前言 本节主要讲解如何使用JDK中的Future实现异步编程,这包含如何使 ...

  2. php单词出现频率,PHP编程计算文件或数组中单词出现频率的方法

    本文实例讲述了PHP编程计算文件或数组中单词出现频率的方法.分享给大家供大家参考,具体如下: 如果是小文件,可以一次性读入到数组中,使用方便的数组计数函数进行词频统计(假设文件中内容都是空格隔开的单词 ...

  3. 【异步编程学习笔记】JDK中的FutureTask和CompletableFuture详解(使用示例、源码)

    文章目录 FutureTask概述 使用实例 类图结构 FutureTask的run()方法 FutureTask的局限性 CompletableFuture概述 CompletableFuture代 ...

  4. 【强烈推荐】《剑指Offer:名企面试官精讲典型编程题》一书中IT名企经典面试题

    各位程序猿: <剑指Offer> 一书源自该书作者何海涛坚持更新与编写的博客( http://zhedahht.blog.163.com/ ),该博客收集整理了大量如微软.Google等知 ...

  5. 【Linux】一步一步学Linux网络编程教程汇总(更新中......)

    00. 目录 文章目录 00. 目录 01. 基础理论知识 02. 初级编程 03. 高级编程 04. LibEvent库 05. 06. 07. 01. 基础理论知识 [Linux网络编程]网络协议 ...

  6. php gridview,PHP编程:yii2-GridView在开发中常用的功能及技巧总结

    <PHP编程:yii2-GridView在开发中常用的功能及技巧总结>要点: 本文介绍了PHP编程:yii2-GridView在开发中常用的功能及技巧总结,希望对您有用.如果有疑问,可以联 ...

  7. SCREEN屏幕编程时候必须保证SCREN中词典的字段格式必须和数据表中字段的类型长度一致!...

    此时任意操作都会出现如下问题 /h调试 回车调试被激活任意操作 执行到第23行时候报错"请输入一个数值",检查数据表中字段参考数据元素以及对应的域均是char类型,此时检查scre ...

  8. java 打印abcd_用JAVA编程统计字符串ABCD123!@#$%ab中大写字母、小写字母、数字、其它字符的个数并打印出来...

    /** * 编程统计字符串"ABCD123!@#$%ab"中大写字母.小写字母.数字.其它字符的个数并打 印出来. */ public class Job1Test { publi ...

  9. 汇编语言:实验10 根据材料编程—3.数值显示,编程,将data段中的数据以十进制形式显示出来

    问题描述 编程,将data段中的数据以十进制的形式显示出来. data segmentdw 123,12666,1,8,3,38 data ends 实验效果 实验要求 子程序描述 名称:dtoc 功 ...

最新文章

  1. raspberry pi下使用mp3blaster播放mp3音乐
  2. mysql 密码清楚_mysql 密码清除
  3. 龙果支付 mysql_龙果支付系统搭建与部署
  4. Gentle.Net学习笔记四:修改代码,使用Oracle数据库
  5. 国外的老师是怎么教Golang的?
  6. Linux的链接工具 putty 以及一些命令。
  7. docker学习记录 docker 脚本----gitlab,nexus3(二)
  8. matlab自适应遗传算法代码,matlab自适应遗传算法
  9. 怎么用Canoe CAPL发送诊断
  10. php写出个人所得税,php趣味编程-php求个人所得税
  11. 基于深度学习机器学习的中文期刊分类
  12. 经济预测与决策matlab试题,经济预测与决策技术及MATLAB实现第5章 投入产出预测法.ppt...
  13. 如果GOOGLE退出中国,我们怎么办???
  14. java 设置页面宽度_java – PDFBox设置A5页面大小
  15. 中文分词语言模型和动态规划
  16. OS X EI Captan 中Rootless
  17. IntelliJ IDEA 15在线激活码(破解)--License server 15.0.2本人亲测
  18. 正则表达式验证手机号码、身份证号码、邮箱、统一社会信用代码/营业执照号
  19. 业务系统需要怎样的全局唯一ID? #Ticktick#(环信首席架构师:一乐)
  20. 摒弃encoder-decoder结构,Pervasive Attention模型与Keras实现

热门文章

  1. windows中运行qt5构建的程序提示 无法启动此程序,因为计算机中丢失qt5Cored.dll 解决方法
  2. 草稿selenium显示等待
  3. centos-安装ifconfig
  4. go 简单的RPC服务与客户端通讯
  5. 为什么需要云压力性能测试?
  6. TCP连接(Time_Wait、Close_Wait)说明
  7. 十项全能的java大神
  8. spring和redis的整合-超越昨天的自己系列(7)
  9. 守护进程实现时间服务器
  10. mac下配置android sdk环境 安装eclipse