How can an average equation be added to this? - python

I am taking GCSE programming and have be set a task to create a program which takes "n" amount of numbers and works out the average.
#presets for varibles
nCount = 0
total = 0
average = 0.0
Numbers = []
ValidInt = False
#start of string
nCount = (input("How many numbers? "))
print(nCount)
while not ValidInt:
try:
int(nCount)
ValidInt = True
except:
nCount = input("Please Enter An Interger Number")
#validation loops untill an interger is entered
for x in range (int(nCount)):
Numbers.append(input("Please Enter The Next Number"))
This is what i have so far but cannot think how i can code it to work out an average from this information? Any help is much appreciated, Thank you(i am not looking for answers just help in what function as i should use)

You're really close to the answer. Looks like you've got everything setup and ready to calculate the average, so very good job.
Python's got two built-in functions sum and len which can be used to calculate the sum of all the numbers, then divide that sum by how many numbers have been collected. Add this as the last line in your program and check the output.
Note: Since inputs were taken as integers (whole numbers) and the average will usually be a non-whole number, we make one of the numbers a float before calculating the average:
print(sum(Numbers)/float(len(Numbers)))
Edit: Or, since you've got a variable that already holds how many numbers the user has input, nCount, we can use this calculation, which will give the same answer:
print(sum(Numbers)/float(nCount)).
Try both and choose one or make your own.

Related

How do you show a user that their 3 digit integer input has the same numbers as a computer generated 3 digit integer but they're in a wrong position?

I am creating a guessing game where you need to guess the exact number that the computer (i.e Python) has generated. I am making it have an easy mode (which generates a 3-digit number for the user to guess) and a hard mode (which generates a 4-digit number for the user to guess).
However, for the easy mode, I want to be able to tell the user that they have one (or more) number in their guess which is correct but it is in the wrong position.
So far, I have used index positions for the computer to note what numbers (in what order) are in the computer-generated, as shown in my code below:
def easy_mode():
easy_num = randint(100,999)
easy_digit_splitter1 = str(easy_num)[0]
easy_digit_splitter2 = str(easy_num)[1]
easy_digit_splitter3 = str(easy_num)[2]
I know that I will need a variable that stores the user's guess under the code above (as well as a while loop), but how do I compare both the "easy_num" and the variable which will store the user's guess and tell the user that they have a correct number in their guess but it's in the wrong position?
Once you get your user guess and your random number you can convert to list and iterate:
easy_num_list = list(str(easy_num))
user_guess_list = list(user_guess)
#iterate through each digit in the user guess. `i` is the index of the digit we are iterating.
for i in range(0, len(user_guess_list)):
Then in that loop you can do your testing:
easy_num_list = list(str(easy_num))
user_guess_list = list(user_guess)
#iterate through each digit in the user guess. `i` is the index of the digit we are iterating.
for i in range(0, len(user_guess_list)):
#use the `in` operator to see if this digit from the user's guess is in the randomly generated number
if user_guess_list[i] in easy_num_list:
print("number",user_guess_list[i],"is in the random number")
#check to see if this digit from the user's guess is in the exact same index/position as the randomly generated number
if user_guess_list[i] == easy_num_list[i]:
print("and it's in the right spot")
else:
print("but it's not in the right spot")
else:
print("number",user_guess_list[i],"is not in the random number")
There's more clean and elegant ways to do this logic, but this should get you in the ballpark.

Been using rand.int for a while and seeing unexpected results

I've been running some code for an hour or so using a rand.int function, where the code models a dice's roll, where the dice has ten faces, and you have to roll it six times in a row, and each time it has to roll the same number, and it is tracking how many tries it takes for this to happen.
success = 0
times = 0
count = 0
total = 0
for h in range(0,100):
for i in range(0,10):
times = 0
while success == 0:
numbers = [0,0,0,0,0,0,0,0,0,0]
for j in range(0,6):
x = int(random.randint(0,9))
numbers[x] = 1
count = numbers.count(1)
if count == 1:
success = 1
else:
times += 1
print(i)
total += times
success = 0
randtst = open("RandomTesting.txt", "a" )
randtst.write(str(total / 10)+"\n")
randtst.close()
And running this code, this has been going into a file, the contents of which is below
https://pastebin.com/7kRK1Z5f
And taking the average of these numbers using
newtotal = 0
totalamounts = 0
with open ('RandomTesting.txt', 'rt') as rndtxt:
for myline in rndtxt: ,
newtotal += float(myline)
totalamounts += 1
print(newtotal / totalamounts)
Which returns 742073.7449342106. This number is incorrect, (I think) as this is not near to 10^6. I tried getting rid of the contents and doing it again, but to no avail, the number is nowhere near 10^6. Can anyone see a problem with this?
Note: I am not asking for fixes to the code or anything, I am asking whether something has gone wrong to get the above number rather that 100,000
There are several issues working against you here. Bottom line up front:
your code doesn't do what you described as your intent;
you currently have no yardstick for measuring whether your results agree with the theoretical answer; and
your expectations regarding the correct answer are incorrect.
I felt that your code was overly complex for the task you were describing, so I wrote my own version from scratch. I factored out the basic experiment of rolling six 10-sided dice and checking to see if the outcomes were all equal by creating a list of length 6 comprised of 10-sided die rolls. Borrowing shamelessly from BoarGules' comment, I threw the results into a set—which only stores unique elements—and counted the size of the set. The dice are all the same value if and only if the size of the set is 1. I kept repeating this while the number of distinct elements was greater than 1, maintaining a tally of how many trials that required, and returned the number of trials once identical die rolls were obtained.
That basic experiment is then run for any desired number of replications, with the results placed in a numpy array. The resulting data was processed by numpy and scipy to yield the average number of trials and a 95% confidence interval for the mean. The confidence interval uses the estimated variability of the results to construct a lower and an upper bound for the mean. The bounds produced this way should contain the true mean for 95% of estimates generated in this way if the underlying assumptions are met, and address the second point in my BLUF.
Here's the code:
import random
import scipy.stats as st
import numpy as np
NUM_DIGITS = 6
SAMPLE_SIZE = 1000
def expt():
num_trials = 1
while(len(set([random.randrange(10) for _ in range(NUM_DIGITS)])) > 1):
num_trials += 1
return num_trials
data = np.array([expt() for _ in range(SAMPLE_SIZE)])
mu_hat = np.mean(data)
ci = st.t.interval(alpha=0.95, df=SAMPLE_SIZE-1, loc=mu_hat, scale=st.sem(data))
print(mu_hat, ci)
The probability of producing 6 identical results of a particular value from a 10-sided die is 10-6, but there are 10 possible particular values so the overall probability of producing all duplicates is 10*10-6, or 10-5. Consequently, the expected number of trials until you obtain a set of duplicates is 105. The code above took a little over 5 minutes to run on my computer, and produced 102493.559 (96461.16185897154, 108525.95614102845) as the output. Rounding to integers, this means that the average number of trials was 102493 and we're 95% confident that the true mean lies somewhere between 96461 and 108526. This particular range contains 105, i.e., it is consistent with the expected value. Rerunning the program will yield different numbers, but 95% of such runs should also contain the expected value, and the handful that don't should still be close.
Might I suggest if you're working with whole integers that you should be receiving a whole number back instead of a floating point(if I'm understanding what you're trying to do.).
##randtst.write(str(total / 10)+"\n") Original
##randtst.write(str(total // 10)+"\n")
Using a floor division instead of a division sign will round down the number to a whole number which is more idea for what you're trying to do.
If you ARE using floating point numbers, perhaps using the % instead. This will not only divide your number, but also ONLY returns the remainder.
% is Modulo in python
// is floor division in python
Those signs will keep your numbers stable and easier to work if your total returns a floating point integer.
If this isn't the case, you will have to account for every number behind the decimal to the right of it.
And if this IS the case, your result will never reach 10x^6 because the line for totalling your value is stuck in a loop.
I hope this helps you in anyway and if not, please let me know as I'm also learning python.

random based on percentage in python [duplicate]

This question already has answers here:
A weighted version of random.choice
(28 answers)
Closed 2 years ago.
i have a list ["a","b","c"] where `"a" should represent 85% of the output and "b" should represent 10% of the output and "c" should represent 5%
i want to print a array that has these percentage of its size and the array size is variable
for ex: if input size is 20 then "a" should in the array 17 times and "b" should be there 2 times and "c" 1 time
any idea ?
If I got your question well, I would start by getting:
the ouput number
the percentages you want the three letters to represent (unless it's fixed at 85 - 10 - 5)
then proceed to divide said input number by 100 and multiply it by the desired percentage, to initiate a for loop for each of the letters, populating your array (which will stay variable in size).
To represent what I got of your question in Python3:
print("please type an integer, then Enter : ")
# the following integer will be the size of your array. Here I chose to prompt the user so that you can execute and see for yourself that you can change it as you like and the solution will stay valid.
startingInteger = int(input())
print(f"the startingInteger is {startingInteger}")
print("what is the percentage of a?")
aPercentage = int(input())
print("what is the percentage of b?")
bPercentage = int(input())
print("what is the percentage of c?")
cPercentage = int(input())
array = []
for i in range(int(round(startingInteger/100*aPercentage))):
array.append("a")
for i in range(int(round(startingInteger/100*bPercentage))):
array.append("b")
for i in range(int(round(startingInteger/100*cPercentage))):
array.append("c")
print(array)
You would then need to scramble the resulting array (if that's what you mean by "random"), which should pose no problem if you import the "random" module and use the scrambled(). It's quick and dirty and inelegant but the logic is very explicit this way, hope it illustrates the idea.

Converting Binary to Decimal in python (without built in binary function)

Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.

In Python, how do I create a visual data of my output represented on a number line?

I just picked up Python as my second language a few days ago and I managed to create a little program that asks the user for a random number and the computer generates random numbers until that random number equals the user's number.
import random
import time
print("Enter a random number. I will try to find it")
password = int(input() )
start = time.time()
for i in range(2 ** 10):
rand_num = random.randint(0, 100)
if rand_num == password:
print("Number found!", password)
end = time.time()
print(" It took", end - start, "seconds to find the number")
break
else:
print(rand_num, "is not the number")
To step things up, I want to create like a visual representation of all the randomly generated numbers on a number line.
Something like this:
I have tried looking on Google but haven't gotten any success.
Thanks
You will need to store the values generated while searching for the number entered by the user.
Have a read about lists and dictionaries. You could store in a list all the numbers generated while searching, and then aggregate the results for display once you find it.
Or you could use a dictionary to store a count of the numbers that fall in to ranges such as 0-10, 10-20, etc.
Creating the graph would be another question all together. Have a go at solving the first part, aggregating the results, and then worry about the visual display.

Categories

Resources