python function Tutorial: Python recursive function characteristics and principles resolved

This article describes the features of Python recursive functions and principles resolved by the text in the sample code described in great detail, has a certain reference value of learning for all of us to learn or work, a friend in need can refer to the
characteristics of a recursive function

Feature

An internal function call their own

Internal function can call other functions, of course, inside the function can also call their own

Code Features

The internal function code is the same, except for the different parameters, a different result of the processing

When the parameters satisfy a condition, the function is not executed

This is very important, often called recursive exports, there would be an infinite loop!

Sample Code

def sum_numbers(num):
  print(num)
  # 递归的出口很重要,否则会出现死循环
  if num == 1:
    return
  sum_numbers(num - 1)
sum_numbers(3)

Here Insert Picture Description
Recursive Case 2 - Calculate the accumulated number

demand

Define a function sum_numbers

Capable of receiving a num of the integer parameter

Calculation 1 + 2 + ... num of

def sum_numbers(num):
​  if num == 1:
    return 1
    # 假设 sum_numbers 能够完成 num - 1 的累加
  temp = sum_numbers(num - 1)
​  # 函数内部的核心算法就是 两个数字的相加
  return num + temp
​print(sum_numbers(2))

Here Insert Picture Description

#  
# 练习
#  创建一个函数,用来检查一个任意的字符串是否是回文字符串,如果是返回True,否则返回False
#  回文字符串,字符串从前往后念和从后往前念是一样的
#    abcba
#  abcdefgfedcba
#  先检查第一个字符和最后一个字符是否一致,如果不一致则不是回文字符串
#    如果一致,则看剩余的部分是否是回文字符串
#  检查 abcdefgfedcba 是不是回文
#  检查 bcdefgfedcb 是不是回文
#  检查 cdefgfedc 是不是回文
#  检查 defgfed 是不是回文
#  检查 efgfe 是不是回文
#  检查 fgf 是不是回文
#  检查 g 是不是回文
 
def hui_wen(s):
  '''
    该函数用来检查指定的字符串是否回文字符串,如果是返回True,否则返回False
 
    参数:
      s:就是要检查的字符串
  '''
  # 基线条件
  if len(s) < 2:
    # 字符串的长度小于2,则字符串一定是回文
    return True
  elif s[0] != s[-1]:
    # 第一个字符和最后一个字符不相等,不是回文字符串
    return False
    # 递归条件  
  return hui_wen(s[1:-1])
 
print(hui_wen('abcdefgfedcba'))

Here Insert Picture Description

I write to you, for everyone to recommend a very wide python learning resource gathering, click to enter , there is a senior programmer before learning to share experiences, study notes, there is a chance of business experience, and for everyone to carefully organize a python zero basis to project combat information to you on a daily basis python latest technology, prospects, learning to leave a message of small details
that's all for this article, I hope to learn everyone's help

Published 24 original articles · won praise 38 · views 20000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104761570