程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python knowledge: simplifying complex loops with structure

編輯:Python

One 、 explain

         In traditional computer languages , Some problems are solved by “ hard ” count , And in the python in , There are many problems , Data structures can make a big difference , The rational application of these structures , Can save time . stay python in , These phenomena are common . In this paper , We will basically use two different data structures to simplify a problem .

Two 、 Problem description

         In a sequence , We will sum some two values in the front row , Equal to the value of a subsequent element , Print out all these elements . such as :

Input sequence : a=[1,2,3,4,5,6]

Output element pair : (1 2)         (1 3)         (1 4)         (1 5)         (2 3)        ( 2 4)

3、 ... and 、 Solution 1

The most basic method will include three rings . The resulting time complexity is O(n^3).

def suminarray(a):
k = 0
lis = []
n = len(a)
for i in range(n - 1):
for j in range(i + 1, n):
for l in range(n):
if (a[i] + a[j] == a[l]):
lis.append((a[i], a[j]))
k += 1
if (k > 0):
return lis
else:
return ("NOT EXIST")
ss = [1,2,3,4,5,6,7]
tt = suminarray(ss)

Four 、 Solution 2

Instead of the third cycle , We can use data structures to store array values , So that they can be easily retrieved when searching .
We will start with a list ( Original array itself )

def suminarray(a):
k=0
lis=[]
n=len(a)
for i in range(n-1):
for j in range(i+1,n):
if (a[i]+a[j]) in a:
lis.append([a[i],a[j]])
k+=1
if(k>0):
return lis
else:
return ("NOT EXIST")

5、 ... and 、 Solution 3 : Use dictionaries to simplify cases

We will now use search , It is considered the most efficient data structure when searching for elements .

def suminarray(a):
k=0
lis=[]
n=len(a)
s={i : 1 for i in a}
print(s)
for i in range(n-1):
for j in range(i+1,n):
if s.get((a[i]+a[j]),0)==1:
lis.append([a[i],a[j]])
k+=1
if(k>0):
return lis
else:
return ("NOT EXIST")
ss = [1,2,3,4,5,6,7]
tt = suminarray(ss)

That's all for the article . More about the uses of dictionaries are as follows :

6、 ... and 、 Dictionary built-in functions & Method

Python The dictionary contains the following built-in functions :

Serial number Functions and descriptions 1cmp(dict1, dict2)
Compare two dictionary elements .2len(dict)
Count the number of dictionary elements , That's the total number of bonds .3str(dict)
The printable string representation of the output Dictionary .4type(variable)
Returns the type of variable entered , If the variable is a dictionary, return the dictionary type .

Python The dictionary contains the following built-in methods :

Serial number Functions and descriptions 1dict.clear()
Delete all elements in the dictionary 2dict.copy()
Returns a shallow copy of a dictionary 3dict.fromkeys(seq[, val])
Create a new dictionary , In sequence seq The middle element is the key of the dictionary ,val Is the initial value of all keys in the dictionary 4dict.get(key, default=None)
Returns the value of the specified key , If the value is not returned in the dictionary default value 5dict.has_key(key)
If the key is in the dictionary dict Back in true, Otherwise return to false6dict.items()
Return traversable as a list ( key , value ) Tuple array 7dict.keys()
Return all keys of a dictionary as a list 8dict.setdefault(key, default=None)
and get() similar , But if the key does not exist in the dictionary , The key will be added and the value will be set to default9dict.update(dict2)
Put the dictionary dict2 Key / Value pair update to dict in 10dict.values()
Returns all values in the dictionary as a list 11pop(key[,default])
Delete dictionary given key key The corresponding value , The return value is the deleted value .key Value must be given . otherwise , return default value .12popitem()
Returns and deletes the last pair of keys and values in the dictionary .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved