LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-10-2012, 01:19 PM   #1
fusion1275
Member
 
Registered: Jul 2007
Location: Knaphill, Surrey
Distribution: Linux Mint
Posts: 310

Rep: Reputation: 36
Python 2.7 Lottery Script - Problems


Hello all,

So yesterday I set myself a project to learn python. So far its been fairly straightforward but tonight I have come across a couple of brick walls and I am wondering if anyone could assist.

The below code I am creating is to give me 6 random numbers in a range of 1 to 49.

Here are my questions:

1) Why do the numbers print out surrounded in brackets i.e [2, 10, 35, 35, 47, 49] ??
2) How do I prevent the numbers being duplicated "per run" as above "35, 35,"
3) Am I missing a way to shorten the code or write the code correctly? I never know if I am doing it right or wrong. Is it a case of "if it works, then its right?".

Here is my code:

Code:
# Choose the lottery numbers

import random


#Generate a list of 6 numbers in a range of 1 - 49

num1 = random.randrange(49) + 1 # Starts at 0 but adds 1 to make 49
num2 = random.randrange(49) + 1
num3 = random.randrange(49) + 1
num4 = random.randrange(49) + 1
num5 = random.randrange(49) + 1
num6 = random.randrange(49) + 1

total = num1, num2, num3, num4, num5, num6  # Put all numbers in a variable

winners = sorted(total)  # Sort and put in a winning variable to make your millions with!!
print winners
Thanks
 
Old 12-10-2012, 05:07 PM   #2
Snark1994
Senior Member
 
Registered: Sep 2010
Distribution: Debian
Posts: 1,632
Blog Entries: 3

Rep: Reputation: 346Reputation: 346Reputation: 346Reputation: 346
Good questions.

Quote:
Originally Posted by fusion1275 View Post
1) Why do the numbers print out surrounded in brackets i.e [2, 10, 35, 35, 47, 49] ??
The issue is this line

Code:
total = num1, num2, num3, num4, num5, num6  # Put all numbers in a variable
makes total into a tuple. It's the same as writing:

Code:
total = (num1, num2, num3, num4, num5, num6)
which is why it prints with brackets.

You could print them all out on the same line by doing

Code:
for i in total:
    print i,
print
or

Code:
output=''
for i in total: output += str(i) + " "
print output
Quote:
3) Am I missing a way to shorten the code or write the code correctly? I never know if I am doing it right or wrong. Is it a case of "if it works, then its right?".
I'll answer this one next because the answer to this feeds into the next one. It is often difficult to work out whether you are doing it right or wrong - I guess it's something you learn with practice. I would say there's no "right" way to do it, but there are definitely wrong ways to do it (and it's not as simple as "if it works, it's right" - perhaps "if it works, is concise, is easy to understand and maintain, is unlikely to be breakable by bad input, and is easily extensible, then you're on the right track")

The problem with your approach is this: suppose I asked you to generate 5000 numbers instead of just 6. With your approach, I suppose you would copy and paste the line 4994 times, then go through and change all the numbers on the end of 'num', then go back and change all the ones you missed, and you'd probably still be missing loads. It's an ugly way to program, and it's horribly timeconsuming and error-prone.

A better way to do it is to use a list (sometimes sort-of erroneously called an 'array' by python people).

Code:
my_list = []                               # create a new list
while len(my_list) < 6:                    # while it has fewer than 6 elements...
    my_list.append(random.randrange(49)+1) # ...add a new one
winners = sorted(my_list)  
print winners
You can see that my code is shorter, easier to understand, and if I wanted 5000 numbers, I could just change "6" to "5000" and I'd be done.

You could just as easily have used a "for" loop, but I feel a "while" loop is more intuitive in this case.

Quote:
2) How do I prevent the numbers being duplicated "per run" as above "35, 35,"
There are a couple of ways you could do this, but one way would be to check each time if you're going to add a number that has been picked already:
Code:
my_list = []                               # create a new list
while len(my_list) < 6:                    # while it has fewer than 6 elements...
    new_number = random.randrange(49)+1    # store the new number in a variable
    if not new_number in my_list:          # actually almost plain english
        my_list.append(new_number)         # put it in the list!
winners = sorted(my_list)  
print winners
Now there are still problems with this approach (what would happen if I changed the 6 to a 40? And what would happen if I changed the 6 to a 50?) but if you're only picking 6 numbers, it's probably good enough

Hope this helps,
 
Old 12-10-2012, 05:18 PM   #3
fusion1275
Member
 
Registered: Jul 2007
Location: Knaphill, Surrey
Distribution: Linux Mint
Posts: 310

Original Poster
Rep: Reputation: 36
Thats spot on mate, thank you very much!!

I try so hard at programming but always seem to find the slowest and longest ways on doing things. People are always telling me "You could of or should of done it this way". So am just wishing to start over with Python and try to nail this one as I have heard its the easiest out of the lot (Perl, C/C++ etc etc)

Time to get my head in the books even more.

Your explanation was just what I needed. Hope to see your replies again in my next questions whenever they maybe.


Thanks again and happy xmas
 
Old 12-10-2012, 05:38 PM   #4
TobiSGD
Moderator
 
Registered: Dec 2009
Location: Germany
Distribution: Whatever fits the task best
Posts: 17,148
Blog Entries: 2

Rep: Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886Reputation: 4886
As I see it your issues are not with understanding Python or any other programming language, but with basic concepts of programming.

Try to keep this in mind, it is a good starter for writing shorter and "nicer " programs:
- When you have to do the same thing for a number of times, like generating a random number in your example, consider to use a loop, like for-loops or while loops. Just like Snark1994 demonstrated.
- When you have to do the same thing for a number of times in different parts of your program (consider that you have to do the lottery thing in multiple parts of a larger program) consider to use a function for wrapping up the commands..
 
Old 12-10-2012, 06:30 PM   #5
ahzthecat
Member
 
Registered: May 2010
Location: Japan
Distribution: Slackware 13.37, Slackware 14, Wind0z8, Ubuntu 12.10
Posts: 156

Rep: Reputation: 9
http://ocw.mit.edu/courses/electrica...uary-iap-2011/

Here's a free online course from MIT on beginning python. I'm working through it myself. The assignments and exercises are quite good, the lectures are good, if a bit long. You can download the course materials and do them at your own pace.

I really like it :-)
 
1 members found this post helpful.
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to close open ports using a python script or a shell script in python ?? apanimesh061 Programming 3 11-20-2011 12:31 AM
Strigi search lottery veeall Slackware 3 02-11-2011 08:05 PM
Python related: How to access a Perl script behind a firewall from Python? vxc69 Programming 8 12-14-2010 07:32 AM
looking for a lottery statistics application for linux? Xplosive Linux - Software 1 06-15-2006 06:57 PM
mplayer - world's biggest lottery? dibblethewrecke Linux - Software 57 09-02-2004 04:22 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:09 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration