Member Avatar for soUPERMan

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()

Sorry, just a little late with the same cure.

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()
commented: yes, very pythonic +10
Member Avatar for soUPERMan

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.