Help with Random Sequence Generator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HerpsForDerps
    New Member
    • May 2012
    • 4

    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:
    Code:
    import random
    random.seed(1)
    
    integer = int(input("Please enter a positive number:"))
    
    while integer <= 0:
     integer = int(input("This is not a positive integer. Please enter a positive integer:"))
    
    if integer > 0:
     L = [random.randrange(10) for k in range (integer)]
     largest = max (L)
     print ("The random sequence is ",L,". The largest number in the sequence is ",largest,".",sep="")
     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.
    Last edited by bvdet; May 19 '12, 11:13 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Do not call random.seed(). You can catch the ValueError and check isdigit() in a try/except block inside a while loop. Something like:
    Code:
    while True:
        try:
            integer = int(raw_input("Please enter a positive number:"))
            if integer < 1:
                raise Exception
            break
        except:
            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.
    Code:
    def getint():
        i = raw_input("Please enter a positive number:")
        if i.isdigit():
            return int(i)
        print "The value you entered (%s) was not a positive integer." % (i)
        return False
    
    while True:
        integer = getint()
        if integer:
            break

    Comment

    • HerpsForDerps
      New Member
      • May 2012
      • 4

      #3
      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.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        The %s is a placeholder for i. You can do the same thing with concatenation as in:
        Code:
        "The value you entered" + str(1) + "was not a positive integer."
        You can start the while loop with anything that evaluates True as in
        Code:
        while 1:

        Comment

        • HerpsForDerps
          New Member
          • May 2012
          • 4

          #5
          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.randrang e(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.

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            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):
            Code:
            while True:
                i = input("Please enter a positive number:")
                if i.isdigit():
                    integer = int(i)
                    break
                print("You did not enter a positive integer. Please enter a positive integer")

            Comment

            • HerpsForDerps
              New Member
              • May 2012
              • 4

              #7
              Thank you so very much! It is working perfectly now :).

              Comment

              Working...