0

I am very new to programming and to a site like this and am in fact just starting class. I understand the basics of Python and have been banging my head against the wall with this for two days now.

Below are the requirements for the program followed by my embarrassing attempt at the code immediately after. I'm not looking for it to be given to me, but I just can't figure out how to move forward.

  1. In main, generate a random integer that is greater than 5 and less than 13.
  2. Print this number on its own line.
  3. Call the makelist function with the random integer as the sole argument.
  4. Inside the makelist function:

    • Make an empty list.

    • Use a loop to append to the list a number of elements equal to the random integer argument. All new list elements must be random integers ranging from 1 to 100, inclusive. Duplicates are okay.

    • Return the list to main.

  5. Back in main, catch the returned list and sort it.

  6. Finally, use a for loop to display the sorted list elements, all on one line,
  7. Separated by single spaces.

Code so far:

import random

def main():
    random_int = random.randint(6, 12)
    print (random_int)
    makelist()

def makelist():
    num_list = []
    for count in range(1, 101)
        num_list.append(random_int)

main()
3
  • 1
    Which part are you specifically struggling with? Commented May 21, 2015 at 23:49
  • Number one is probably figuring out how to append a number of elements to the empty list that is equal to the random integer argument. That because the list is in a different function from the random integer. I also don't understand how to return the list to main or "catch" it once there. Commented May 21, 2015 at 23:53
  • wich version of python? Commented May 26, 2015 at 18:56

7 Answers 7

2

Another solution:

from random import randint

def makelist(count):
    return [randint(1, 100) for _ in range(count)]

def main():
    random_integer = randint(6, 12)  # Generate a random integer where 5 < i < 13
    print(random_integer)  # Print this integer on its own line
    unsorted_list = makelist(count=random_integer)  # Make a list
    sorted_list = sorted(unsorted_list)  # Sort the list
    print(' ' . join([str(i) for i in sorted_list]))  # Print it out

main()

The main thing to take away from this is that makelist returns a list comprehension, which is totally not necessary to use. You should have quite enough with all these answers to figure it out.

David is right, of course. makelist doesn't need to exist, although it does serve to add a bit of readability to the exercise (and may be "required," as OP's guidelines suggest). You could just as easily go all the way with something like:

from random import randint

count = randint(6, 12)
print(count)
print(' ' . join([str(i) for i in sorted([randint(1, 100) for _ in range(count)])]))

It depends on how deep your particular rabbit hole goes. I certainly wouldn't turn that in to the professor...

Sign up to request clarification or add additional context in comments.

2 Comments

@MichaelBlakely Using list comprehensions would certainly be more sensible for makelist(which doesn't really have to be a function in the first place) but I think we should try to edit OP's existing code rather than just overhauling it. Although since that's already been done, this is a fine addition to the post.
@MichaelBlakely Since you are overhauling the code though, why don't you just get rid of makelist()?
1

You have done most part of it.

In order to create a new list in makelist with a length equal to the random int you got in main(), you have to pass that number via arguments, like the code below.

Also, you have to assign makelist to return to a variable in main, so that you can use whatever output makelist has produced. This can be done simply via var = makelist(random_int). I called this variable elements.

Finally, there are a few options to sort the list. One of them is to use Python's built-in function sorted and pass the final list as argument. Iterate over it and print each value.

import random

def main():
    random_int = random.randint(6, 12)
    print (random_int)
    elements = makelist(random_int)
    for i in sorted(elements):
        print (i,)

def makelist(random_int):
    num_list = []
    for count in range(random_int):
        num_list.append(random.randint(1, 100))
    return num_list

main()

4 Comments

@PadraicCunningham well-noticed. Thank you
Incredibly helpful thank you! I am in the process of digesting all this information.
Minor issues: you're missing a colon on the for loop in makelist. You're not printing all of the numbers onto one line as the directions stated.
@RafaelCardoso Not sure how big of a deal it is to Wes but this still prints each element in the list to its own line, not "all on one line, separated by single spaces."
1

If you just want a better version of your existing program, I have fixed your code and compressed it into a single function below. However, I think it is more constructive to edit what you have already written rather than redoing it - see the rest of my answer for details on fixing your code.**

from random import randint

def main():
    random_int = random.randint(6, 13)
    print(random_int)
    rand_list = [randint(1, 100) for _ in range(random_int)]
    return sorted(rand_list)

print main()

In main, generate a random integer that is greater than 5 and less than 13.

  1. random_int should be assigned to random.randint(6, 12) as the randint function uses inclusive range parameters

Call the makelist function with the random integer as sole argument.

  1. Your make_listfunction currently takes no arguments, so let's change it's definition to def make_list(list_lengh):. Now we can pass in the random integer from main() as input.

use a loop to append to the list a number of elements equal to the random integer argument.

  1. In the second line of code in the make_list function you are calling range with default arguments of (1, 101), which isn't what you want. You want to call range on list_length because you want to loop the same number of times as the random integer created in main().

All new list elements must be random integers ranging from 1 to 100, inclusive.

  1. You don't want num_list.append(random_int). That will simply give you the [random_int]*random_int. Instead append random.randint(1, 101).

Finally, use a for loop to display the sorted list elements, all on one line

  1. There are a number of ways you could do this, but since you want to print all of the integers onto one line, let's append the integers to a string with a loop and then return the string at the end.

Like so:

num_string = ""
for i in sorted(rand_list):
    num_string += str(i) + " "
return num_string

Once you have made all those revisions, you aren't to far from where you started, but the code now possesses the desired behavior.

import random

def main():
    random_int = random.randint(6, 13)
    print(random_int)
    rand_list = make_list(random_int)
    num_string = ""
    for i in sorted(rand_list):
        num_string += str(i) + " "
    return num_string

def make_list(list_length):
    num_list = []
    for count in range(list_length):
        num_list.append(random.randint(1, 101))
    return num_list

print main()

Example output:

10
20 63 63 71 78 83 83 84 87 94

1 Comment

@Wes There are certainly more concise and sensibly ways of writing this code, but I was trying to keep it as close to your original code as possible. If you want me to add a much shorter version, let me know.
0
import random


def main():
    random_int = random.randint(6, 12)
    print (random_int)
    for i in sorted(makelist(random_int)):
        print i,   
def makelist(random_int):
    num_list = []
    for count in range(random_int):
        rand=random.randint(1,100)
        num_list.append(rand)
    return num_list

main()

1 Comment

This answer is completely redundant.
0

It could be:

import random

def makelist(i):
    list_ = []
    for c in range(i):
        list_.append(random.randint(1, 100))
    return list_

def main():
    c = random.randint(5, 13)
    print c
    catched_list = makelist(c)
    s = ' ' . join([str(x) for x in catched_list])
    print s
main()

Comments

0

This is the code in the shortest and smartest way:

import random

def main():
    global random_int
    random_int = random.randint(5, 13)
    print random_int
    makelist(random_int)
    random_list.sort
    string = ' ' . join([str(x) for x in random_list])
    print string

def makelist(list_length):
    global random_list
    random_list = []
    for x in range (list_length):
        random_list.append(random.randint(0, 100))

main()

Comments

-1

The issues you're having are mostly syntactic.

Your random_int variable is being created, but it is also being kept within the main() function. It needs to be passed up into the greater namespace, either by creating the variable before you define the function, or by using global as so:

def main():
    global random_int = random.randint(5, 13)

Your makelist() function needs to have random_int as a declared variable in the definition - that's the 'as an argument' part of the assignment. It looks like:

def makelist(random_int):

You'll also want to change the for count in range() line to read for count in random.randrange(1, 101).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.