2016-12-04 2 views
-4

Ecrivez une fonction ou un programme qui prendra 2 tableaux d'entiers, "current" et "target", et produira 2 tableaux représentant une liste d'additions et une liste de suppressions de sorte que l'application des additions et des suppressions au "array donnera le tableau" target ".Python Array Diff

Par exemple, étant donné les entrées suivantes:

current = [1, 3, 5, 6, 8, 9] 

target = [1, 2, 5, 7, 9] 

Les sorties seraient:

additions: [2, 7] 

deletions: [3, 6, 8] 

Pour que ce qui suit est vrai:

actuelle ([1, 3, 5, 6, 8, 9]) + additions ([2, 7]) - suppressions ([3, 6, 8]) = cible ([1, 2, 5, 7, 9])

Solution:

Jusqu'à présent, j'ai ceci:

--------------------------- 

# import array function 
from array import array 

# create an integer array named current 
current = array('i', [1, 3, 5, 6, 8, 9]) 

# add items from additions list into current array using the fromlist() method 
additions = [2, 7] 
current.fromlist(additions) 

# remove items on deletions list from current array using the.  remove() method 
current.remove(3) 
current.remove(6) 
current.remove(8) 

+1

Quel est le problème? – Dekel

+0

Pouvez-vous clarifier "ne fonctionne pas"? Avez-vous une erreur? – Dekel

+0

Excuses- ça marche plus ou moins mais je suis en panne sur la liste finale une fois que je franchirai –

Répondre

0

Il travaillera pour vous ...

def addlist(current,target): 
     add = [] 
     intersection = set(current) & set(target) 
     for i in target: 
       if i not in intersection: 
         add.append(i) 
     return add 

def removeList(current,target): 
     remove = [] 
     intersection = set(current) & set(target) 
     for i in current: 
       if i not in intersection: 
         remove.append(i) 
     return remove 

def main(): 
     current = [1, 3, 5, 6, 8, 9] 
     target = [1, 2, 5, 7, 9] 
     print(addlist(current,target)) 
     print(removeList(current,target)) 

if __name__=="__main__": 
     main() 
0

Ci-dessous devrait être facile à comprendre.

>>> current = [1, 3, 5, 6, 8, 9] 
>>> target = [1, 2, 5, 7, 9] 
>>> set(current) & set(target) 
set([1, 5, 9]) 
>>> unique = list(set(current) & set(target)) 
>>> additions = [i for i in target if i not in unique] 
>>> additions 
[2, 7] 
>>> deletions = [i for i in current if i not in unique] 
>>> deletions 
[3, 6, 8] 
>>> 
0

Cela fonctionne aussi bien.

current = [1, 3, 5, 6, 8, 9] 
target = [1, 2, 5, 7, 9] 
additions=[x for x in target if x not in current] 
deletions=[x for x in current if x not in target]