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 .
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)
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)
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")
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 :
Python The dictionary contains the following built-in functions :
Python The dictionary contains the following built-in methods :