2017-11-28 6 views
0

Ich prüfe einige Karten reduziere Code in Ubuntu, Python 2 mit commmand:Map Reduce: Warum liefert dieser Code die richtige Ausgabe für max, aber nicht min?

cat testfile2 | ./mapper.py | sort | ./reducer.py 

ich die richtige Ausgabe für max bekommen, aber nicht min, je Mal, wenn ich den Wert 1 für min erhalten, als ob es hat nicht geändert von seinem ursprünglichen Wert. Jeder einzelne Wert "value" ist kleiner als 1, also sollte bei der ersten Iteration durch die for-Schleife min auf den ersten Wert wechseln und dann die min bei weiteren Iterationen aktualisieren. Verliere ich meine Meinung oder gibt es einen dummen Fehler im Code? Bitte helfen Sie!

#!/usr/bin/python 

import sys 

def reducer(): 
    max = 0 
    min = 1 
    old_tuple = ('foo', 'bar') 
    i = 0 

    for line in sys.stdin: 
     data = line.strip().split("\t") 

     if len(data) != 3: 
      continue 

     city, year, value = data 
     new_tuple = (city, year) 

     if old_tuple != new_tuple: 
      if i != 0: 
       print "{0}\t{1}\t{2}\t{3}".format(old_tuple[0], old_tuple[1], max, min)    
       max = 0 
       min = 1 
     i += 1  
     old_tuple = new_tuple 
     if min > value: 
      min = value 

     if max < value: 
      max = value 


    if old_tuple != ('foo', 'bar'): 
     print "{0}\t{1}\t{2}\t{3}".format(old_tuple[0], old_tuple[1], max, min) 



if __name__ == '__main__': 
    reducer() 

Der Ausgang I Aussehen bekommen wie so

Alert 2009 0.215236752 1 
Winnipeg 2017 0.032557214 1 
+1

Python ist nicht meine Sprache, aber es scheint, dass Sie vergessen haben, string 'value' in float zu konvertieren. Ohne eine solche Umwandlung wird der Vergleich lexikographisch und nicht numerisch durchgeführt. – gudok

Antwort

0

Zur einem Min- und Max-I wurde unter Verwendung als Variablennamen, die Schlüsselwörter sind. Nach dem Ändern

min => minimum 
max => maximum 

der Ausgang war immer noch falsch. Das gleiche Problem tatsächlich. Erst nachdem ich versucht hatte, das Min und Max auf pythonischer Art und Weise zu bekommen, funktionierte es. Ich bin neu bei Python, also ist dies vielleicht immer noch nicht der beste Python-Weg, aber der Code unten erhält zumindest die Min- und Max-Werte wie benötigt.

#!/usr/bin/python 

import sys 
import math 

def reducer(): 
    list_ = [] 
    old_tuple = ('foo', 'bar') 
    i = 0 

    for line in sys.stdin: 
     data = line.strip().split("\t") 

     if len(data) != 3: 
      continue 

     city, year, value = data 
     new_tuple = (city, year) 

     if old_tuple != new_tuple: 
      if i != 0: 
       print "{0}\t{1}\t{2}\t{3}".format(old_tuple[0], old_tuple[1], max(list_), min(list_))   
       list_ = []  

     i += 1 
     list_.append(value) 
     old_tuple = new_tuple 

    if old_tuple != ('foo', 'bar'): 
     print "{0}\t{1}\t{2}\t{3}".format(old_tuple[0], old_tuple[1], max(list_), min(list_)) 


if __name__ == '__main__': 
    reducer() 
Verwandte Themen