Im getting errors with this, please advice me on what to do:

def displayHappy():
    numLimit = input("Enter a positive integer: ")
    countHappy = 0
    countUnhappy = 0
    liHappy = []
    for num in range(1, numLimit + 1):
        inNum = num
        while inNum != 1 and inNum != 4:
            inNum = zap(inNum)
            
        if inNum == 1:
            print num
            liHappy.append(num)
            countHappy += 1
        else:
             countUnhappy += 1
            # print num
    print liHappy

    for i in range(len(liHappy)):
        if liHappy[i+1] - liHappy[i] == 1:
            print 'lovers'
   
def zap(intNum):
	total = 0
	while intNum != 0:
		last = intNum % 10
		total += last**2
		intNum = intNum / 10

	return total       



    
    print ""
    print "There are",str(countHappy)," happy numbers and",\
          str(countUnhappy),"unhappy numbers"

displayHappy()

Here is a version that runs. I just removed the last index in the lovers loop

def displayHappy():
    numLimit = input("Enter a positive integer: ")
    countHappy = 0
    countUnhappy = 0
    liHappy = []
    for num in range(1, numLimit + 1):
        inNum = num
        while inNum != 1 and inNum != 4:
            inNum = zap(inNum)
            
        if inNum == 1:
            liHappy.append(num)
            countHappy += 1
        else:
             countUnhappy += 1
    print liHappy

    for i in range(len(liHappy)-1):
        if liHappy[i+1] - liHappy[i] == 1:
            print "lovers: %d, %d" % (liHappy[i], liHappy[i+1])

def zap(intNum):
	total = 0
	while intNum != 0:
		last = intNum % 10
		total += last**2
		intNum = intNum / 10

	return total

displayHappy()

Here is a more compact and pythonic approach

def displayHappy():
    numLimit = input("Enter a positive integer: ")
    liHappy = list(i for i in range(1, numLimit+1) if isHappy(i))
    print liHappy

    for i in range(len(liHappy)-1):
        if liHappy[i+1] - liHappy[i] == 1:
            print "lovers: %d, %d" % (liHappy[i], liHappy[i+1])

def isHappy(num):
    while not num in (1, 4):
        num = zap(num)
    return num == 1

def zap(num):
    return sum(d**2 for d in digits(num))

def digits(num):
    while num:
        num, digit = divmod(num, 10)
        yield digit

displayHappy()

Edited 6 Years Ago by Gribouillis: n/a

Comments
yes, very pythonic

Thanks everyone...i think i was too obsessed with the bigger picture and forgot the details :P

This question has already been answered. Start a new discussion instead.