0

i'm trying to do split def function parameter into two user input then sum up both value then print out.

Example code:

def ab(b1, b2):
if not (b1 and b2):  # b1 or b2 is empty
    return b1 + b2
head = ab(b1[:-1], b2[:-1])
if b1[-1] == '0':  # 0+1 or 0+0
    return head + b2[-1]
if b2[-1] == '0':  # 1+0
    return head + '1'
#      V    NOTE   V <<< push overflow 1 to head
return ab(head, '1') + '0'


print ab('1','111')

I would like to change "print ab('1','111')" to user input.

My code:

def ab(b1, b2):
if not (b1 and b2):  # b1 or b2 is empty
    return b1 + b2
head = ab(b1[:-1], b2[:-1])
if b1[-1] == '0':  # 0+1 or 0+0
    return head + b2[-1]
if b2[-1] == '0':  # 1+0
    return head + '1'
#      V    NOTE   V <<< push overflow 1 to head
return ab(head, '1') + '0'

b1 = int(raw_input("enter number"))
b2 = int(raw_input("enter number"))


total = (b1,b2)

print total

My result: 1,111

Expect result:1000

2
  • 2
    Please fix your indentation... Commented Oct 28, 2016 at 9:49
  • 1
    Haven't you just missed the ab call? like total = ab(b1,b2) Commented Oct 28, 2016 at 9:50

2 Answers 2

2

I don't know how you're getting the return working here. First of all (as Daniel) stated, you have the function call missing/improper.

total = ab(b1,b2)

Secondly, you're type-casting (changing type of input from string to integer) - and in your function ab you're applying string slicing on the b1 and b2, which will result in an exception:

Traceback (most recent call last):
  File "split_def.py", line 33, in <module>
    total = ab_new(b1,b2)
  File "split_def.py", line 21, in ab_new
    head = ab_new(b1[:-1], b2[:-1])
TypeError: 'int' object has no attribute '__getitem__'

The final working code has to be:

def ab(b1, b2):
    if not (b1 and b2):  # b1 or b2 is empty
        return b1 + b2
    head = ab(b1[:-1], b2[:-1])
    if b1[-1] == '0':  # 0+1 or 0+0
        return head + b2[-1]
    if b2[-1] == '0':  # 1+0
        return head + '1'
    #      V    NOTE   V <<< push overflow 1 to head
    return ab(head, '1') + '0'

b1 = raw_input("enter number")
b2 = raw_input("enter number")

total = ab(b1,b2)

print "total", total
Sign up to request clarification or add additional context in comments.

Comments

1

You didn't call your function in the second snippet.

total = ab(b1,b2)

2 Comments

Result : TypeError: 'int' object has no attribute 'getitem'
So, ask yourself why you are converting those input strings to ints. In the first snippet, you pass strings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.