Happy Numbers!!! Now I need help with input checking...

So, over the weekend I wrote and debugged this python script:

#This program checks to see if a number is happy.
#A number is happy if, when you recursively take the sum of the square of the digits, it equals 1.

def main():
	global originalNumber
	global number
	global numbers
	number = originalNumber
	numbers = []
def getNumber():
	global originalNumber
	originalNumber = str(raw_input("Please tell me a number: "))
		test = int(originalNumber)
	except ValueError:
		print "Sorry, that was not a valid number."
	if int(originalNumber) < 0:
		print "Only positive numbers, please."
def check():
	global originalNumber
	global number
	global numbers
	if number == 1:
		numbers = []
		number = str(number)
		print "%d is happy!" % (int(originalNumber))
	elif number == int(originalNumber) or number == 42:
		numbers = []
		number = str(number)
		print "%d is unhappy." % (int(originalNumber))
		numbers = []
		number = str(number)
def sumSquare():
	global number
	global numbers
	for item in number:
	numbers = [item**2 for item in numbers]
	number = 0
	for item in numbers:
		number += item
def choice():
	again = str(raw_input("Would you like to test another number (y/n)? 
	if again == "y":
	elif again == "n":
		print "Goodbye."
		print "Please press either 'y' for 'Yes', or 'n' for 'No'."

So, try your favorite numbers to see if they are happy!

Edit 1: Put in the comments so it is 64 lines of code. Yay for geekiness!

Edit 2: Note that this is NOT a Blender python script. This is just a Python script. Download/install Python, save this script in a text file called something like “happy.py”, and then run this script through the command: “python happy.py” On Linux, and maybe other Unix systems, you can enable the file as executable, then run it as “./happy.py”.

Edit 3: Here is more information about Happy Numbers: http://en.wikipedia.org/wiki/Happy_number

Edit 4: Wow, lots of editing this post on the first day I make it. Windows users, you can just double click on the .py file to make it run. Linux users might be able to do this, at least it works in Gnome if you tell it to run in a terminal after double-clicking.

An excellent piece of coding. I am quite impressed that you are releasing it to the general public instead of hogging it like the larger corporate players in the tough market. On behalf of some of the non-programming community I offer my gratitute.

Eh, I’m not entirely releasing it. I have a module-specific version for myself, though its not hard to modify this version to match the other one.

Its actually my first program to be useful(?), and I’m just sharing my joy for actually completing it in one weekend (would have posted it before now if school hadn’t blocked Blenderartists.)

Edit 1: Also, I took out the comments. Otherwise, instead of 60 lines of code, it would be 64 lines of code. Although I’m realizing how absolutely geeky it would be to have it at 64 lines…

I’ll put in the comments.

Edit 2: If there is a need or want for the module version, I’ll post it as well. Its actually the same thing but with most of the error checking cut out, and main() is renamed to tell() and has one attribute, so its tell(h).

Not hard to figure out how to convert this version to the module.

But, anyways, this topic is supposed to be everyone posting their favorite numbers, and whether they’re happy numbers or not.

My favorite number is 505, and it is not happy :(.

Oh. . . … ok.

Good work, Tynach. Here’s my code to do the same thing, which I whipped together this afternoon, in C:

1 #include<stdio.h>
2 #include<conio.h>
3 int n;
4 int check(int);
5 int main()
6 {
7     printf("enter a number.");
8     scanf("%d",&n);
9     check(n);
10 }
11 int check(int x)
12 {
13     int tx=x,sum=0,a;
14     while(tx!=0)
15     {
16         a=tx%10;
17         sum+=a*a;
18         tx/=10;
19     }        
20     sum+=tx*tx;
21     if (sum==1)
22     printf("%d is happy.",n);
23     else if (sum==4||sum==n)
24     printf("%d isn't happy.",n);
25     else
26     check(sum);
27     getch();
28 }

It doesn’t check for new numbers, or check for valid inputs, but I was feeling too lazy to include that. It might be a total of 40 lines if I did that.

Notice I didn’t use your algorithm, (though it’s surprisingly similar from what i gather). I don’t know why you’ve used 42 anyway, it works fine with 4, mentioned in Wikipedia.

I didn’t take the time to read your code, because I hardly know the abc’s of python… I just checked out wiki for what happy numbers are.

Thanks for the info anyway!

EDIT: My favourite number is 417, which, I assure you, isn’t happy.:frowning:

Also, do you know that 28, 496 and 8128 are perfectly happy?

I found out using a combination of my ‘Perfect numbers upto n’ and this program.

do HappyNumbers have Applications in science ?

And here, is another one to generate perfect numbers, with a slightly redundant code:

int n,i;
int check(int);
int main()
    int ret;
    printf("Enter a number");
        if (ret==1)
int check(int x)
    int sum=0,a;
    if (sum==1)
    return (1);
    else if (sum==4||sum==i)
    return (0);
    return check(sum);

Yeah, my code was really short at first too, but I debugged it so that no matter what you put in there, it wouldn’t crash the program unless it was an actual keyboard interrupt, like Ctrl+C or Ctrl+Z.

I don’t know the C language. But, here’s what I did:

I took a number from the user, and put it into a string.

It then checked to see if it can be turned into an integer, to make sure you put in a valid number.

Then I separated the string out into separate letters by adding each item in the string into a list. Then each entry in the list was turned into an integer, and then squared, then added together.

Then it repeats.

Each time it repeats it tests to see if it is going to 1, the original number, or 42, and it tells the user if it is happy or not based on that.

More than half the code is error handling.

Hey, one thing I noticed is that you have only two functions, one with a while… loop in it.

I wonder if that’s more efficient than my method of having everything as a function and having it call other functions or recall the function to simulate a loop.

I’m not much of a programmer. Which would you recommend overall?

LOL. Sorry to dissapoint you, but I’m not much of a programmer either. :o

The reason I don’t have many functions, is that I haven’t included functions to check for an invalid number, and to repeat the whole thing, based on the user’s wish.

From what I know about programming, it’s always better to make various --even small–functions and then call them. But recursive functions are discouraged, as told to me by some programmers in a forum…

What I did, was to call the check function, which would divide the int by 10, find it’s remainder, and again, until it got every digit, and simultaneously added their squares. The loop was basically to get each individual digit, and not to check for it’s ‘Happiness’.

Notice that I did call the check function, which did exactly what you did, I think. Though, I suppose that would work with a while/for loop as well, and that is a better way.

Best of luck with your programming!

Indeed it is, as every time a function is called a new namespace needs to be created. You should only define functions when the code needs to be reused or could be useful elsewhere in the future. There a lots of redundant type converters in your code and usage of global variables should be kept to a minimum. Also you should use a env shebang for portability as it’s common for multiple versions of python to be installed.

#!/usr/bin/env python
#This program checks to see if a number is happy.
#A number is happy if, when you recursively take the sum of the square of the digits, it equals 1.

def main():
	while True:
		while True:
				number = raw_input("Please tell me a number: ")
				if int(number) < 1:
					print "Only positive numbers, please.
				else: break
			except ValueError:
				print "Sorry, that was not a valid number.

		print number, "is", "happy." if is_happy_number(number) else "unhappy."

		while True:
			again = raw_input("
Would you like to test another number (y/n)? ")
			if again == "y" or again == "yes":
			elif again == "n" or again == "no":
				print "Goodbye."

def is_happy_number(number):
	while True:
		number = sum([int(n) ** 2 for n in str(number)])
		if number == 1: return True
		elif number == 4: return False


Wow, thanks N30N, that helped me a lot.

I’ll try to rewrite the program and see if I can get it close to what you have. I’m just beginning programing, so I don’t know what is considered good coding practices (though in an XKCD comic it mentioned that if I use GOTO that velociraptors will come after me).

Tynach, seems you’re learning python, just as I’m trying to. At the moment I’m very into the problems of projecteuler.net. If you want to do some nice little programs which are actually useful or teach you a lot about efficiency and developing a bit more complex algorithms, you might want to take a look at that, too. It’s a lot about maths but usually the problems are solvable without extensive knowledge of mathematical methods and in the worst case, at least the first dozen can be done with a bit of brute force.
Just telling you since the search for “Happy numbers” reminds me a lot of the problems there :wink:

(Keep in mind, though, that you will not really learn about coding style there or how to manage big projects - it’s about getting a feeling for the language and the ability to actually code the methods you have in mind for solving the problem.)

Tynach, you still on high school or in college? I want to know if college’s dictatorial on what you do.

I’m in Highschool, not college. Learning this in my free time.

Same here. 9th grade.

N30N, I’m having some troubles understanding parts of your code. In particular, this line:

print number, “is”, “happy.” if is_happy_number(number) else “unhappy.”

I see what it means and does, but how does it work? It doesn’t make much sense to me.

I’m not N30N but I want to try…to see if I get it :wink:
Actually it seems simple. First, the Number number itself is printed, followed by a string “is”. Simple.
Then there is an if clause, that determines which string is printed afterward (it is evaluated before something else gets printed to the screen). In the case that number is a happy number (and so is_happy_number(number) returns True), the string “happy.” is printed. If False is returned, the string “unhappy” is printed.
Not the , that separates the if clause from the rest of the arguments for the print statement.
An equivalent way to put it would be:
if is_happy_number(number): s = “happy.”
else: s = “unhappy.”
print number, “is”, s
The possibility to put the if clause into the print statement itself is saving you two lines of code and is actually increasing the legibility of the code ( in my opinion). Special Python syntax, I guess ( I did not know of that trick myself - thanks for the tip!).

Well technically it’s a ternary selection expression not a if clause.

Probably should have also used text formating to make it a bit more legible.

That was only added in Python 2.5, and I was hoping to be more on the level of compatibility with older versions of Python, as I’m still learning and I don’t want to get into the advanced things.

I was trying to re-write the code with a normal if-then statement, and I couldn’t get it right :confused: