473,394 Members | 1,755 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Help with Random Sequence Generator

Hello everyone!

I am new to this forum and currently am enrolled in an intro to ECS class where we are working on python programming. This is our last assignment for python and I have been able to do the others successfully but am having some troubles with this one. I have read the different chapters in the book and have tried to google my problem but have not been able to find any solution to help me yet...hence why I am here!

Basically I need to create a program that will first as the user to input a positive integer. If the input is not a positive integer (i.e. negative, letter, etc.) they will get an error message asking them to input a positive integer. When they do input a positive integer the program will generate a random sequence of numbers of length determined by the user. For example if the user inputs the number 5, the program will spit out [1, 3, 6, 4, 9] and will then tell the user which number is largest in the sequence.

So far I this is what I have come up with:
Expand|Select|Wrap|Line Numbers
  1. import random
  2. random.seed(1)
  3.  
  4. integer = int(input("Please enter a positive number:"))
  5.  
  6. while integer <= 0:
  7.  integer = int(input("This is not a positive integer. Please enter a positive integer:"))
  8.  
  9. if integer > 0:
  10.  L = [random.randrange(10) for k in range (integer)]
  11.  largest = max (L)
  12.  print ("The random sequence is ",L,". The largest number in the sequence is ",largest,".",sep="")
  13.  input("\n\nPress the enter key to exit.")

However there are a few issues that I am encountering with my code. First I do not know where to implement the isdigit() function so that the user cannot input a letter. Right now when a letter is inputed I just get a ValueError message. Second...my program always comes up with the same integers in the same order. They are 1, 8, 7, 2, 4, 4, etc. Is there anyway that I can fix this? Should I try to implement a random.shuffle function and if so how would I do that?

Thank you very much in advance for any help you can provide . I have been stuck on this for about 5 hours now (I know pathetic) and as a final attempt decided to post on this forum! I am currently using Python 3.1.
May 19 '12 #1

✓ answered by bvdet

After calling random.seed(1), the list comprehension will always return the same sequence. If you omit the argument, the basic random number generator will be initialized with the system time.

See if this works (untested):
Expand|Select|Wrap|Line Numbers
  1. while True:
  2.     i = input("Please enter a positive number:")
  3.     if i.isdigit():
  4.         integer = int(i)
  5.         break
  6.     print("You did not enter a positive integer. Please enter a positive integer")

6 2679
bvdet
2,851 Expert Mod 2GB
Do not call random.seed(). You can catch the ValueError and check isdigit() in a try/except block inside a while loop. Something like:
Expand|Select|Wrap|Line Numbers
  1. while True:
  2.     try:
  3.         integer = int(raw_input("Please enter a positive number:"))
  4.         if integer < 1:
  5.             raise Exception
  6.         break
  7.     except:
  8.         print "The value you entered (%s) was not a positive integer." % (integer)
I am using Python 2.7, so your code will be a little different. I would prefer to get the input in a function and return the value when a valid number was entered.
Expand|Select|Wrap|Line Numbers
  1. def getint():
  2.     i = raw_input("Please enter a positive number:")
  3.     if i.isdigit():
  4.         return int(i)
  5.     print "The value you entered (%s) was not a positive integer." % (i)
  6.     return False
  7.  
  8. while True:
  9.     integer = getint()
  10.     if integer:
  11.         break
May 19 '12 #2
Awesome thank you for replying! I am sorry but I do not understand a lot of that code still. What is the (%s) that you have written down? I tried to implement code like that however I was receiving an error saying that I did not have True defined. Sorry I am still really inexperienced with Python :p.
May 20 '12 #3
bvdet
2,851 Expert Mod 2GB
The %s is a placeholder for i. You can do the same thing with concatenation as in:
Expand|Select|Wrap|Line Numbers
  1. "The value you entered" + str(1) + "was not a positive integer." 
You can start the while loop with anything that evaluates True as in
Expand|Select|Wrap|Line Numbers
  1. while 1:
May 20 '12 #4
Ok thank you. Concerning my random sequence and its tendency to always come up with the same numbers is that a result of how I wrote it? Is there a way for me to write the sequence to rectify that issue?

Sorry for all the questions but I still do not understand some of what you are saying. Is there any way for me to add isdigit() to the code I have written so far? Or am I going to have to rewrite it?

My teacher gave these hints concerning this assignment:

Your program should first import the random module. Right after that, you must put in this line of code: random.seed(1).

You must check the user's input is actually an integer greater than
0. You can do this by using a while loop to keep asking the user
until he/she enters the correct input.

Once you get the input, you may use the randrange() function in the
random module. For example, random.randrange(10) will generate a
random integer number less than 10.

To fill your sequence with the number of integers specified by the
user, you may use a for loop. Inside the for loop, you should call randrange to generate a random number and add that to your sequence.

To find the largest number, you may use a for loop to go through
each number in your sequence and determine which one is the largest.

I have tried to implement those suggestions with the exception of the for loop. I was unsure of how to do so.
May 20 '12 #5
bvdet
2,851 Expert Mod 2GB
After calling random.seed(1), the list comprehension will always return the same sequence. If you omit the argument, the basic random number generator will be initialized with the system time.

See if this works (untested):
Expand|Select|Wrap|Line Numbers
  1. while True:
  2.     i = input("Please enter a positive number:")
  3.     if i.isdigit():
  4.         integer = int(i)
  5.         break
  6.     print("You did not enter a positive integer. Please enter a positive integer")
May 20 '12 #6
Thank you so very much! It is working perfectly now :).
May 20 '12 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Aaron | last post by:
I need some help writing this function the function returns a list of random non-duplicate integers in a string, 1 parameter indicating the maximum range. string randGen(int maxRange) ...
3
by: Joe | last post by:
Hi, I have been working on some code that requires a high use of random numbers within. Mostly I either have to either: 1) flip a coin i.e. 0 or 1, or 2) generate a double between 0 and 1. I...
4
by: Carl | last post by:
Hi, I am running some Monte Carlo simulations under C++ and have noticed that there seems to be some bias evident. For example when using random sampling on the function f(x) = x between...
4
by: Nel | last post by:
Hi all, I am driving myself crazy trying to think of a solution to this - perhaps one of you guys can see a simple solution. The problem is displaying the contents of an array in what appears...
70
by: Ben Pfaff | last post by:
One issue that comes up fairly often around here is the poor quality of the pseudo-random number generators supplied with many C implementations. As a result, we have to recommend things like...
4
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause...
5
by: Peteroid | last post by:
I know how to use rand() to generate random POSITIVE-INTEGER numbers. But, I'd like to generate a random DOUBLE number in the range of 0.0 to 1.0 with resolution of a double (i.e., every possible...
16
by: jason.cipriani | last post by:
I am looking for a random number generator implementation with the following requirements: - Thread-safe, re-entrant. - Produces consistently reproducible sequences of psuedo-random numbers...
5
by: nkomli | last post by:
Does anyone know where I can find a version of the ran3 random number generator for C++ that will play nice on windows as a console app, preferably something you can call simply with random1...
4
by: jhernandy | last post by:
I have built a Table using HTML and would like to have a random number genereator, genereate numbers in each of the 5 boxes on the table with no duplicates between 1-50, I have a problem getting the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.