Python Programming Notes (Part 3) Ternary Operations, File Processing, Recursion, Scope, Generators (Supplementary)

1. Ternary operation

 

Ternary operation, also known as ternary operation, is a shorthand for simple conditional statements, such as:

 

Simple conditional processing:

  if condition is satisfied:
      val = 1
  else:
      val = 2

  

Change to ternary operation

  
  val = 1 if condition is true else 2

  

 

 

 

2. Intelligent detection of file encoding

Use the third-party module chardet

 

First install the chardet module, use the pip command to install

 

Usage of chardet

  
  import chardet
  f = open("staff_table.txt","rb")
  data =f.read()
  f.close()
  res = chardet.detect(data) #Use the detect method in the chardet module directly
  print(res)

  

output result

  
  {'encoding': 'utf-8', 'confidence': 0.938125, 'language': ''}

  

Analysis: The result here directly gives a result that encoding is a judgment, and confidence is the probability that the result is correct

 

3. How to simulate file modification

Simulate a way to modify characters in a file

1. Modify the file to occupy the hard disk, that is, modify it in the hard disk

  import them
  f = open("test.txt","r+",encoding="utf-8")
  g = open("new_test.txt","w",encoding="utf-8")
  old_str = "的"
  new_str = "地"
  for line in f:
      if old_str in line:
          line = line.replace(old_str,new_str)
      g.write(line)
  f.close()
  g.close()
  os.replace("new_test.txt","test.txt") #Note that you cannot directly rename a file on Windows platform with os.replace()
  #or
  #os.remove("test.txt") #Note that on the Windows platform, you cannot directly use os.rename to rename a file to the name of an existing file, you must delete the original file first
  #os.rename("newtest.txt","test.txt")

  

 

 

2. Modify in memory

  
  f = open("test.txt","r+",encoding="utf-8")
  data =f.read()
  data = data.replace("hello","xxxx")
                 #Because f.read() reads the file and moves the cursor to the end of the file content, writing directly again will become append mode
  f.seek(0) #need to move the cursor to the beginning again,
  f.truncate() #Since the modified string may be shorter than the previous string, direct writing will have the previous characters behind the new writing
                 #Here you need to use the truncate() method of the file to clear the contents of the file
  f.write(data)
  f.close()

  

Fourth, the way to modify the file name

1. In the mac\linux system, use the os.rename() method directly

  
  import them
  os.rename("new_test.txt","test.txt")

  

2. In the windows system, the os.rename() method cannot be used directly, and an error will be reported, but the os.replace() method can be used, and the effect is the same as the os.rename() method

  
  import them
  os.replace("test.txt","new_test.txt")

  

 

5. Variable parameter group

1. *args is used to pass unnamed key-value variable-length parameter lists (positional parameters), and do not add ordinary parameters after that

  
  def send_msg(msg,*args,age):
      print("Information is", msg, args, age)
  send_msg("Hello, my message is",*["nicholas","male"],22)

  

Writing in this way will report an error, and the error will indicate that "age" is missing a parameter, because *args will receive 22 in the actual parameter, causing age to have no parameters.

It can be written like this

  
  def send_msg(msg,*args,age):
      print("Information is", msg, args, age)
  send_msg("Hello, my message is",*["nicholas","male"],age=22)

  

This way of writing will not report an error, but generally writing programs will not write this way.

5. Tail recursion optimization

In the recursive process, if the factorial of 1000! is calculated, there will be a problem of stack overflow, because in the execution of the function, each time a function is called, the calling position and internal variables of the current function will be saved in the stack, because the space of the stack is not Infinite (python is generally 1000 layers deep), if there are too many call layers, there will be a stack overflow.

At this time, tail recursion optimization can be used to solve the problem. The concept of tail call is very simple. It can be explained clearly in one sentence, that is, the last step of the recursive function function is to call the function itself.

example

  
  def jc(n):
      print(n)
      return jc(n +1)
  jc(1)

  

Since the tail call is the last step of the function, there is no need to keep the call record of the outer function, because the call location, internal variables and other information will not be used anymore. Therefore, tail recursion optimization can effectively prevent stack overflow, but tail recursion optimization requires the support of the compiler or interpreter, but most programming languages ​​do not optimize for tail recursion , nor does the Python interpreter optimize , and C language does not optimize for tail recursion. For optimization, the optimization is the same as the for loop execution, but python does not optimize, so even if the above jc() function is tail recursive, stack overflow will occur.

 

Six, eval (), exec ()

eval can execute an expression in string form and return the result of the calculation.

example

  
  print(eval("1+2+3"))

  

output result

  
  6

  

The exec() function executes the string str as a valid Python expression and does not return the result of the calculation

  
  exec('print("hello world !")')

  

output result

  
  hello world !

  

The inner and outer double quotes here cannot be the same, otherwise an error will be reported

 

example

  
  code = '''
  def func():
      print('Hello')
      return 'nicholas'
  v = func ()
  print(v)
  '''
  exec(code)

  

output result

  
  Hello
  nicholas

  

example

  
  code = '''
  def func():
      print('Hello')
      return 'nicholas'
  v = func ()
  print(v)
  '''
  res = exec(code)
  print(res)
 

  

output result

 

  
  Hello
  nicholas
  None

  

exec() does not return the result of the calculation.

 

Seven, callable ()

To determine whether a thing is callable, callable refers to whether the object can be called using () brackets.

example

  
  li = [1,2,3]
  print(callable(li))

  

output result

 
False

  

Example 2

  
  def func():
      print("hello")
  print(callable(func))

  

output result

  
  True

  

8. Recursive practice

 

topic

How to guess a number, guess a number between 0 and 100, and write the guessing process.

write using dichotomy and recursion

  
  li = [i for i in range(100)]
  def search(num,data):
      num_max = len(data)
      num_mid = int(( num_max) / 2)
      if num > data[num_mid]:
          print("smaller")
          print("The first part of the list is %s, the end is %s"%(data[0],data[-1]))
          return search(num,data[num_mid:])
      elif num < data[num_mid]:
          print("bigger")
          print("The top of the list is %s, the end is %s" % (data[0], data[-1]))
          return search(num,data[:num_mid])
      else:
          print("find it")
  search(88,li)

  

 

 

9. Namespace

Also known as name space, as the name implies, it is a place to store names. What name is stored? For example, if the variable x=1 and 1 is stored in memory, where is the name x stored? The namespace is where the binding relationship between the name x and 1 is stored

There are 3 types of namespaces, as follows

  • locals: is the namespace within the function, including local variables and formal parameters

  • globals: global variables, print all variables of this program

  • builtins: namespace of built-in modules

The different scopes of different variables are determined by the namespace in which the variable is located. With the namespace, there is a scope.

scope is scope

  • Global scope: globally alive, globally valid

  • Local scope: temporary survival, local effective

View scope methods globals(), locals()

 

10. Search order of scope

LEGB stands for name lookup order: locals -> enclosing function -> globals -> builtins

  • locals is the namespace inside the function, including local variables and formal parameters

  • enclosing the namespace of the outer nested function

  • globals global variables, the namespace of the module where the function is defined

  • builtins Namespace for built-in modules

 

11. List Compilation + Ternary Operation

List comprehensions and ternary operations can be mixed

example

  
  li = [i if i < 3 else i*i for i in range(6)]
  print (li)

  

output result

  
  [0, 1, 2, 9, 16, 25]

  

example

  
  li = [i if i != "a" else i*2 for i in "nicholas"]
  print (li)

  

output result

  
  ['n', 'i', 'c', 'h', 'o', 'l', 'aa', 's']

  

Analysis: here for i in var, var can be a dictionary, a list, or a string

 

12. There are two ways to write the Fibonacci sequence

Find the nth element of the Fibonacci sequence

Method 1: Recursion

  
  def fib(n):
      if n == 0 or n == 1:
          return n
      else:
          return fib(n-1)+fib(n-2)
  print(fib(10))

  

Method 2: The loop method

  
  def fib2(n):
      a,b=0,1
      count = 1
      while count < n:
          a,b = b,a+b
          count = count + 1
      return b
  print(fib2(10))

  

Thirteen, isinstance()

You can use isinstance() to determine whether an object is an Iterator object (iterator) or whether Iterable is iterable (iterable object):

example

  from collections import Iterable
  li2 = (i for i in range(10)) #Generator expression
  dic = {"k1":"v1"}
  li = [1,2,3]
  s = "nicholas"
  n = 2
  print(isinstance(li2,Iterable))
  print(isinstance(dic,Iterable))
  print(isinstance(li,Iterable))
  print(isinstance(s,Iterable))
  print(isinstance(n,Iterable))

  

output result

  True
  True
  True
  True
  False

  

Analysis: Dictionaries, lists, and strings are all iterable objects. The generator here is the iterator.

Iterators must be iterable objects, and iterable objects are not necessarily iterators. For example, dictionaries, lists, etc. here need to use __iter__()methods to become iterators.

Example 2

  from collections import Iterator
  li2 = (i for i in range(10)) #Generator expression
  dic = {"k1":"v1"}
  li = [1,2,3]
  s = "nicholas"
  n = 2
  print(isinstance(li2,Iterator))
  print(isinstance(dic,Iterator))
  print(isinstance(li,Iterator))
  print(isinstance(s,Iterator))
  print(isinstance(n,Iterator))

  

output result

  
  True
  False
  False
  False
  False

  

Analysis: Here only generator expressions are iterators, containing both __iter__()methods and __next__()methods.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325305013&siteId=291194637