Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Not sure why this works...
#1
I'm working on a project for class and I was not sure why this didn't work:

Input:
0
9
def hcf(a, b):
  
  for i in range(a):
    if a > b:
	    a -= b
    elif b > a:
    	b -= a
  print(a)

hcf(int(input()), int(input()))
Output:
0 (Answer should be 9)

I then started adding random things to my code and discovered that the following code worked:
Input:
0
9
def hcf(a, b):
  
  for i in range(a):
    if a > b:
	    a -= b
    elif b > a:
    	b -= a
  print(a or b)

hcf(int(input()), int(input()))
Output:
9

I know this is an odd question but I would like a better understanding of how that changed the code, making it work.
Reply
#2
write your code like:
def hcf(a, b):
    print('at start: a: {}, b: {}'.format(a,b ))
    print('\nfor i in range: {}'.format(a))
    for i in range(a):
        if a > b:
            print('a > b')
            a -= b
            print('a -= b: {}'.format(a))
        elif b > a:
            print('b > a')
            b -= a
            print('b -= a: {}'.format(a))
    print('a or b: {}'.format(a or b))


hcf(int(input()), int(input()))
Get output like:
Output:
2 3 at start: a: 2, b: 3 for i in range: 2 b > a b -= a: 2 a > b a -= b: 1 a or b: 1
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020