2016-08-09 6 views
-1

Ich füge zwei Binärzahlen als Zeichenfolgen eingegeben und ihre Summe als eine Zeichenfolge im Binärformat mit dieser method.Hinzufügen von Binärzahlen ohne Konvertierung in Dezimal oder Verwendung von integrierten Funktionen

Irgendwelche Gedanken, um meinen Code zum Laufen zu bringen?

def add(a,b): 
    a = list(a) 
    b = list(b) 
    equalize(a,b) 
    sum_check(a,b,ctr) 
    out = " ".join(str(x) for x in sum_check(a,b,ctr)) 
    out.replace(" ","") 
    print(out) 

def equalize(a,b): 
    if len(a) > len(b): 
     for i in range(0, len(a)-len(b)): 
      b.insert(0,'0') 
    elif len(a) < len(b): 
     for i in range(0, len(b)-len(a)): 
      a.insert(0,'0') 

def sum_check(a,b): 

    out = [] 
    ctr = 0 

    def sum(a, b): 

     if ctr > 0: 
      if a[-1] + b[-1] == 2: 
       out.append('1') 
      elif a[-1] + b[-1] == 0: 
       out.append('1') 
       ctr -= 1 
      else: # a[-1] + b[-1] = 1 
       out.append('0') 
       ctr -= 1 
     else: # ctr = 0 
      if a[-1] + b[-1] == 2: 
       out.append('1') 
       ctr += 1 
      elif a[-1] + b[-1] == 0: 
       out.append('0') 
      else: # a[-1] + b[-1] = 1 
       out.append('1') 

    for i in range(len(a)): 
     if i == 0: 
      sum(a,b) 
     else: 
      new_a = a[:-1] 
      new_b = b[:-1] 
      sum(new_a, new_b) 

    return out 
+0

könnte jemand mir helfen, meinen Codeblock bearbeiten? Ich kann es nicht zur Arbeit bringen. – user2516746

+2

Viele mögliche Probleme hier. Aber sagen Sie uns, was ist Ihr Problem: erwartet vs vs Ergebnis, oder crash dann Fehler und traceback –

Antwort

0

Ihr Algorithmus ist nicht wirklich einfach (ich würde es völlig neu zu schreiben, würde ich zumindest auch geben Funktionen und Variablen explizite Namen, um den Algorithmus wieder schneller später zu verstehen, wie ctr sollte jedenfalls explizit beziehen sich auf tragen etc.).

Trotzdem, hier ist es, korrigiert und funktioniert. Ich habe einige Kommentare an Stellen eingefügt, an denen ich Dinge geändert habe (entweder Fehler im Algorithmus oder Python-Programmierfehler).

Ich habe def sum(...) außerhalb sum_check setzen, es ist klarer auf diese Weise.

Obwohl Sie wissen sollten, dass sum ein python builtin ist, sollten Sie einen anderen Namen finden, um zu vermeiden, den eingebauten Namespace zu verlieren (aber ich schätze, dass Ihr Algorithmus nur zu Trainingszwecken dient, da Sie alles durch eine Operation ersetzen könnten) auf Binärzahlen direkt:

$ python3 
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> a = int('10110', 2) 
>>> b = int('1011100', 2) 
>>> bin(a + b) 
'0b1110010' 
>>> 

).

Auch habe ich ein paar Debugging print Anweisungen, um zu sehen, was passiert. Außerdem wurde ein Beispiel zur Überprüfung aller Fälle durchgespielt.

Letzte Anmerkung: Es stürzte zuerst, weil Sie ctr verwendet haben, bevor Sie es definiert hatten. Dies war die erste Korrektur.

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 


def equalize(a, b): 
    if len(a) > len(b): 
     for i in range(0, len(a) - len(b)): 
      b.insert(0, 0) 
    elif len(a) < len(b): 
     for i in range(0, len(b) - len(a)): 
      a.insert(0, 0) 
    return a, b 


def sum(a, b, ctr): 
    out = '' 
    print('\n'.join(['-------', 'Working on:', str(a), str(b)])) 

    if ctr > 0: 
     if a[-1] + b[-1] == 2: 
      out = '1' 
      print('Case 1') 
     elif a[-1] + b[-1] == 0: 
      out = '1' 
      ctr -= 1 
      print('Case 2') 
     else: # a[-1] + b[-1] = 1 
      out = '0' 
      print('Case 3') 
      # ctr -= 1 (wrong) 
    else: # ctr = 0 
     if a[-1] + b[-1] == 2: 
      out = '0' # '1' was wrong 
      ctr += 1 
      print('Case 4') 
     elif a[-1] + b[-1] == 0: 
      out = '0' 
      print('Case 5') 
     else: # a[-1] + b[-1] = 1 
      out = '1' 
      print('Case 6') 
    print('Sum will return: ' + str(out) 
      + ' and carry: ' + str(ctr) + '\n-------') 
    return out, ctr 


def sum_check(a, b): 
    ctr = 0 
    out = [] 
    n = len(a) 
    for i in range(n): 
     if i != 0: 
      # You were always giving the same a and b to feed sum(). 
      # In order to change them, as it's not advised to iterate over a 
      # changing list (maybe not even possible), I stored the desired 
      # length in a number n. Then, I assign new values to a and b. 
      a = a[:-1] 
      b = b[:-1] 
     new_out, ctr = sum(a, b, ctr) 
     out.append(new_out) 
     print('Current out: ' + str(out) + ' and carry: ' + str(ctr)) 
    return out 


def add(a, b): 
    a = [int(x) for x in a] 
    b = [int(x) for x in b] 

    # You need to return the new contents of a and b, otherwise you'll keep 
    # them as they were before the call to equalize() 
    a, b = equalize(a, b) 

    print('\n'.join(['Equalized: ', str(a), str(b)])) 
    # On next line, [::-1] reverses the result (your algorithm returns a 
    # result to be read from right to left) 
    print('Result: ' + ''.join(sum_check(a, b)[::-1])) 


add('10110', '1011100') 

Ausgang:

Equalized: 
[0, 0, 1, 0, 1, 1, 0] 
[1, 0, 1, 1, 1, 0, 0] 
------- 
Working on: 
[0, 0, 1, 0, 1, 1, 0] 
[1, 0, 1, 1, 1, 0, 0] 
Case 5 
Sum will return: 0 and carry: 0 
------- 
Current out: ['0'] and carry: 0 
------- 
Working on: 
[0, 0, 1, 0, 1, 1] 
[1, 0, 1, 1, 1, 0] 
Case 6 
Sum will return: 1 and carry: 0 
------- 
Current out: ['0', '1'] and carry: 0 
------- 
Working on: 
[0, 0, 1, 0, 1] 
[1, 0, 1, 1, 1] 
Case 4 
Sum will return: 0 and carry: 1 
------- 
Current out: ['0', '1', '0'] and carry: 1 
------- 
Working on: 
[0, 0, 1, 0] 
[1, 0, 1, 1] 
Case 3 
Sum will return: 0 and carry: 1 
------- 
Current out: ['0', '1', '0', '0'] and carry: 1 
------- 
Working on: 
[0, 0, 1] 
[1, 0, 1] 
Case 1 
Sum will return: 1 and carry: 1 
------- 
Current out: ['0', '1', '0', '0', '1'] and carry: 1 
------- 
Working on: 
[0, 0] 
[1, 0] 
Case 2 
Sum will return: 1 and carry: 0 
------- 
Current out: ['0', '1', '0', '0', '1', '1'] and carry: 0 
------- 
Working on: 
[0] 
[1] 
Case 6 
Sum will return: 1 and carry: 0 
------- 
Current out: ['0', '1', '0', '0', '1', '1', '1'] and carry: 0 
Result: 1110010 
+0

Great perfekt, ich denke, mein Hauptproblem war, dass ich ctr vor der Definition verwendet hatte .. – user2516746

+0

Und ja das ist nur für die Praxis, ich weiß, dass es in binärer Addition eingebaut ist. – user2516746

Verwandte Themen