Using random function to find "cut off" values on python - python

I need help with this problem and I think the major reason I don't know how to do it is because I don't really understand what it is asking for.
The problem is asking to write a program that will find the curve of a class. It has to find the "cut off" values for A,B,C and D. 40% of the class will receive an A, as well as a B(40%), 10% will receive a C and the remaining 10% will get a D.
The grades have to be generated randomly between 20 - 100 and the number of student has to be an input. a tuple has to be returned with the cut off values of A,B,C and D.
It also gives me the hint to use list.sort() and min(list)
I honestly don't really get what this is asking for, so far I have this but I am not sure what I am doing.
import random
def Cutoffgrade():
students=float(input('How many students are in the class?'))
grades=list(range(20,101))
list.sort(grades)
Astudents=students*0.4
Bstudents=students*0.4
Cstudents=students*0.1
Dstudents=students*0.1
I also have this other function I did which I know is something similar to what I have to do, but I just don't get this problem.
Here is the other function I did for a different problem that is somewhat asking for a random list as well:
def createlist(v1,v2):
random.randint(v1,v2)
random.randrange(v1,v2)
numlist=[]
for i in range(5):
n=random.randrange(v1,v2)
numlist.append(n)
print(numlist)
So I have been trying to transform this function into what I would need for the new problem but don't know how.

Since this is a homework question and I imagine your professor isn't very likely to get back to you during the weekend I will give you some hints at how to tackle this:
First build a list of grades using random.randint(start, stop) and a list comprehension or standard for loop
Sort the list.
Determine how many students should be in each grade bracket.
Slice the list into the appropriate chunks and find the min() of each list.

Related

Finding a set of values

I have a curve_hex generator, it uses two coordinates, I'm looking for only one coordinate. The script searches for one coordinate value easily, but if I specify several coordinates for the search, then it does not find anything.
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
One value is found normally. But if I add several values, the script writes an error
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
if str(curve_hex).find(wanted)!=-1:
print (curve_hex[str(curve_hex).find(wanted):str(curve_hex).find(wanted)+len(wanted)])
else:
print ('not')
Tell me how to do it right. What am I doing wrong. I have just started learning python.
Very exciting that you are learning python, I would also suggest that you might want to spend some time in the stackoverflow section explaining how to ask a question because I am not 100% sure what you are trying to achieve with your code.
From my understanding, if you are happy with your if else conditions, and your only problem is that you can’t add multiple values to wanted. I would convert wanted to a list that includes all your wanted values, and loop over those.
Something like this:
wanted = ['586..{copy the whole value here}', '108...{copy the value here}']
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
for value in wanted:
if str(curve_hex).find(value)!=-1:
print (curve_hex[str(curve_hex).find(value):str(curve_hex).find(value)+len(value)])
else:
print ('not')
Edit: formatting and typos
You are misleadiong some basic concepts:
Difinitions like this result in diferent types
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238'
type(wanted) # string
wanted='58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252'
type(wanted) # tuple
curve_hex='(58611774815559422402170859520215717661755632997646071327165159211728464937238, 108722706890170119196943746054760504186165603293283329661416022207913727808252)'
type(wanted) # string
So you should choose a type first. Tuple is the best case.
wanted=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
curve_hex=('58611774815559422402170859520215717661755632997646071327165159211728464937238', '108722706890170119196943746054760504186165603293283329661416022207913727808252')
for i in wanted:
for x,j in enumerate(curve_hex):
if i in j:
print(f'{i} in {curve_hex} at position {x}')

Python:Is there any way to remove an item from a list (random) after it has been used? Or change results of random.choice [duplicate]

This question already has answers here:
Pick N distinct items at random from sequence of unknown length, in only one iteration
(10 answers)
Closed 6 years ago.
I really didn't know how to ask this question, and I probably sound stupid. I've been looking around for solutions to the problem I have been having, but everything I've tried hasn't worked.
I'm working on a project for my computer science class, as my final, that randomly generates an identity from a list of names, birthdays, cities, addresses, etc. (sidenote: my teacher hasn't actually taught me anything; we read notes and did quizzes that consisted of definitions from the notes, and when we can't figure something out he just tells us to ask our neighbor. And, this is my first post on here, so if the formatting is incorrect, and my coding skills suck, I apologize in advance.) Anyway, I'll get on with my question/problem.
At the beginning of the program, it asks if you would like to generate a male or female identity:
def get_info():
global gender
global name
gender=input("Enter a gender of which you would like to randomly generate M=male F=female:")
if gender==("F"):
name=fname
elif gender==("M"):
name=mname
else:
print("Please enter either an M or F.")
get_info()
which it then uses to determine which list the name comes from:
fname=random.choice(list(set(["girlynames","tina","caroline","etc"])))
or
mname=random.choice(list(set(["guynames","richard","earl","etc"])))
and then it prints out a random identity, including name, birthday, etc. like this:
Your new identity is:
Nathaniel Ellis
Your birthday is :
September 5 1985
Your address is :
470 MacMurray Acres
and I have added a function, after the main part of the program, that asks for user input if they would like to use the program again.
def retry():
again=input("Would you like to generate another? Y/yes N/no: ")
if again==('Y'):
get_info()
generate_identity()
retry()
elif again==('N'):
print("Thanks for using the identity generator! Have a spectacular day")
quit()
The problem is, every time I input 'Y', and a gender, it has the exact same results as it did the first time, even with a different gender all the results are the same besides the first name.
Your new identity is:
Ava Ellis
Your birthday is :
September 5 1985
Your address is :
470 MacMurray Acres
I feel like there is a simple solution to this, but everything I've read and tried from this website (along with other sources) haven't worked. Is there a way to remove an item from a list after it has been used? Or make it so the results vary every time? Or even a way to just, like, reset Python, since it is only pseudorandom? I have been stumped on this for 3 days now, it is due by next monday, and I've been here on stackoverflow trying to find a solution since I noticed the problem. Help will be greatly appreciated and you'll be a life saver! :)
You can remove a random item from a list with pop.
selection = random.choice(range(len(name_list)))
name = name_list.pop(selection)
This selects a random item from name_list, removes it, and assigns it to name.
That said, it looks like your random selection is working fine but you are not reassigning the value of name correctly. But you would need to post more of your code to know for sure. Double check that after retry is run you are both reassigning fname/mname and reassigning that to name, in that order.
What if you set the seed to a random number every time you launch the program, so your random.choice option would differ every time?
import random
seed = random.randint(0,9999)
random.seed(seed)

Need help understanding some code (Beginner)

I am trying to learn about while and for loops. This function prints out the highest number in a list. But, I'm not entirely sure how it works. Can anyone break down how it works for me. Maybe step by step and/or with a flowchart. I'm struggling and want to learn.
def highest_number(list_tested):
x=list_tested[0]
for number in list_tested:
if x<number:
x=number
print(x)
highest_number([1,5,3,2,3,4,5,8,5,21,2,8,9,3])
One of the most helpful things for understanding new code is going through it step by step:
PythonTutor has a visualizer: Paste in your code and hit visualize execution.
What this is going form the first to the last number and saying:
Is this new number bigger than the one I have? If so, keep the new number, if not keep the old number.
At the end, x will be the largest number.
See my comments for step by step explanation of each line
def highest_number(list_tested): # function defined to take a list
x=list_tested[0] # x is assigned the value of first element of list
for number in list_tested: # iterate over all the elements of input list
if x<number: # if value in 'x' is smaller than the current number
x=number # then store the value of current element in 'x'
print(x) # after iteration complete, print the value of 'x'
highest_number([1,5,3,2,3,4,5,8,5,21,2,8,9,3]) # just call to the function defined above
So basically, the function finds the largest number in the list by value.
It starts by setting the large number (x) as the first element of list, and then keeps comparing it to other elements of the list, until it finds an element which is greater than the largest number found till now (which is stored in x). So at the end, the largest value is stored in x.
Looks like you are new to the programming world. Maybe you should start with some basic concepts, for/while loops are some among which, that would be helpful for you before jumping into something like this.
Here is one of the explanations you may easily find on the Internet http://www.teamten.com/lawrence/programming/intro/intro8.html

Tuples birthday paradox

Tuples is n
The birthday problem equation is this:
Question:
For n = 200, write an algorithm (in Python) for enumerating the number of tuples in the sample space that satisfy the condition that at least two people have the same birthday. (Note that your algorithm will need to scan each tuple)
import itertools
print(list(itertools.permutations([0,0,0]))
I am wondering for this question how do I insert a n into this?
"how to get n in there":
n = 200
space = itertools.permutations(bday_pairs, n)
I've left out a couple parts of your code:
itertools returns a list; you don't need to coerce it.
Printing this result is likely not what you want with n = 200; that's a huge list.
Now, all you need to do is to build bday_pairs, the list of all possible pairs of birthdays. For convenience, I suggest that you use the integers 1-365. Since you haven't attacked that part of the problem at all, I'll leave that step up to you.
You still need to do the processing to count the sets with at least one matching birthday, another part of the problem you haven't attacked. However, I trust that the above code solves your stated problem?

Speed/structure optimization for a recursive tree

Edit -> short version:
In Python, unlike in C, if I pass a parameter to a function I -say: a dict-, the changes made within the function call will reflect outside (as if I passed a pointer instead of just the value)
I want to avoid this so:
-> I make a copy of my dict and pass the copy to my function
But the values of my dict can be some dict and this goes on until an undefinite depth
-> the recursive copy is very long.
Question: what is a pythonic way to go about this?
Long version:
I'm coding a master-mind playing robot with a n-digit code in Python.
You try to guess the code and for each try you get an answer in terms of how many white/black/none you have, meaning resp. "good digit good position"/"good digit wrong position"/"wrong digit" (but you don't know to which digit the whites/blacks/none refer)
I analyze the answers and build a tree of possibilities with a dictionary storing white/black/none.
I store a map of the possible positions of the numbers 0-9 within the code (a digit can appear more than once) in a list.
Ex: for a 3-digit game I will have [[x,y1,y2,y3][-1,0,1,4][...][...][][][][][][]] with:
x: the total number of times this digit appears in the code (default value being n+1, ie. 4 in the exemple) with positive meaning sure and negative "at least"
y1,y2,..,yn the position within the code: 1 means I know the digit is in this position, 0 I know it's not, and 4 (or anything) as default
In my exemple: I know that '1' appears at least once in the code (-1) that it is present in position 2 and that it is NOT present in position 1 and that position 3 is still hypothetically possible.
While I explore my tree of possibilities, I update this list. Which means that each branch of the tree will have its own copy of the list.
Since I recently discovered that, unlike in C, when I pass my list to a sub-method, any change made to it within the sub will reflect on the list outside, I manually copy my list each time with a small method:
def bak_symb(_s):
_b = [[z for z in _s[i]] for i in xrange(10)]
return _b
Now, I profiled my programm and noticed that 90% of the time is spent either in
append()
(the branches of my tree are nested dictionaries {w:{},b:0,n:{}} to which I append each branch of possibilities that I explore)For each branch : the programm has to find a n-digit code
or
my copying function
So I have three questions.
Is there a way to make this function faster?
Is there a something better adapted than the structures I chose (2-depth list for the symbols and nested dict for the hypothesis)
Is there a more adequate way of doing this than building this huge tree
All comments and remarks are welcome.
I'm self-taught in and might have missed some obvious pythonic way of doing some things.
Last but not least, I tried to find a good compromise between making this short and clear, here again don't hesitate to ask for more details.
Thanks in advance,
Matt

Categories