Finding probability from random number generator - python

I am working on a personal problem that requires me to find the probability that the sum of three randomly chosen real numbers between 0 and 1 is greater than 1. I have tried writing the code in python, but I think there's an error:
import random
a = random.random()
b = random.random()
c = random.random()
n = int(input("Enter a range: "))
for i in range(n):
wanted = 0
if (a + b + c > 1):
wanted += 1
else:
wanted += 0
print("The ratio is " + str(wanted/n))
Can you please point out the problems with my code or direct me otherwise?

To me seems like two issues :
each time you want to create a new set of random numbers, so they should go inside the loop
and wanted=0 should be before loop, you are resting it to 0 each time
import random
n = int(input("Enter a range: "))
wanted = 0
for _ in range(n):
a = random.random()
b = random.random()
c = random.random()
if a + b + c > 1:
wanted += 1
print(f"The ratio is {wanted/ n:.2%}")

Related

Count the number of Factors using while Loop on Python

I am new to Python and so I am a little unaware of the advanced functions. Here's how I approached this problem by breaking it into two .
First I found the factors of this number.
a = int(input("Enter Number to find Factors: "))
b = 1
while a >= b :
if a % b == 0 :
print(b)
b+=1
Second, I prepared the psudo code for counting numbers
b = 17
count = 0
while b > 0 :
rem = b % 10
b = b // 10
count += 1
print(count)
can you guys help me how should I proceed like how should I join these I think I am having problem with syntax
Modify your first solution to increase the count each time one is found.
a = int(input("Enter Number to find Factors: "))
b = 1
count = 0
while a >= b :
if a % b == 0 :
count += 1
print(b)
b+=1
Is this what you were asking for?
def get_factors(n, list):
b = 1
while n >= b :
if n % b == 0 :
list.append(b)
b+=1
def count_digits(n):
count = 0
while n > 0 :
n = n // 10
count += 1
return count
n = int(input("Enter Number to find Factors: "))
# getting the list of factors
factors = list()
get_factors(n, factors)
# printing the factors and the amount of digits in each factor
for f in factors:
print("Factor:", f, ", Digits:", count_digits(f))
Every time you want to join more than one piece of code you can create a function using:
def function_name(parameters)
Then put your code inside the function or functions and you can apply the functions to whatever variables you want.
You can create functions that don't return anything. Those can be used like this:
function_name(parameters)
Or you can create functions that return values and they can be used like this:
a = function_name(parameters)
For more information you can check w3school they explain it well: https://www.w3schools.com/python/python_functions.asp
In this answer I show how to connect the codes without using def.
You can just copy the second code and paste it inside of the if of the first one:
a = int(input("Enter Number to find Factors: "))
b = 1
while a >= b :
if a % b == 0 :
b2 = b
count = 0
while b2 > 0 :
b2 = b2 // 10
count += 1
print(b, count)
b+=1
remember to copy the value of b to a different variable.

I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly

I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly. I'm not sure what is wrong exactly, but I feel the code may be too complicated and somewhere, there is an error.
enter code here
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
for j in range(count):
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
while i <= len(list):
while t != 0 :
initial_guess = 10
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
i = i + 1
break
initial_guess = better_guess
i = i + 1
There are some errors in your code, #x pie has pointed out some of them but not all. The most important is that you are need to initalize t for every number in the list, so you can get the iterations for the numbers separately. Also, t needs to be incremented in the while loop, not inside the if block.
You can also clean up the code considerably, for example the j variable is not being used, list comprehension can be used to shorten the code (pythonic way), and iterating over lists can be done with for num in list.
Putting this altogether produces this:
count = int(input('How many numbers am I estimating John? \nCOUNT> '))
print("Input each number to estimate.")
list = [float(input(f'NUMBER {i+1}> ')) for i in range(count)]
print("The square roots are as follows:")
for num in list:
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + num/initial_guess) / 2
t += 1
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {num}^0.5 = {better_guess}")
break
initial_guess = better_guess
Sample run:
How many numbers am I estimating John?
COUNT> 4
Input each number to estimate.
NUMBER 1> 1
NUMBER 2> 9
NUMBER 3> 16
NUMBER 4> 4
The square roots are as follows:
OUTPUT After 9 iterations, 1.0^0.5 = 1.0
OUTPUT After 7 iterations, 9.0^0.5 = 3.0
OUTPUT After 7 iterations, 16.0^0.5 = 4.0
OUTPUT After 8 iterations, 4.0^0.5 = 2.0
#viggnah is right, and I just ignored the num of iterations. But I think #viggnah 's num of iterations are 1 bigger than the actual num of iterations. E.g., if input is 4 and initial guess is 2, the iteration should be 0 rather than 1. Also I add except in case of illegal input.
I suppose the following code works as you expect.
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
while True:
try:
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
break
except:
print("Invalid input! Try again.")
while i < len(list):
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
break
t = t + 1
initial_guess = better_guess
i = i + 1
You need to understand:
We only need initialize guess once for each number. So do it in the first while loop;
tneeds to be updated when initial_guess==better_guess rather than i, I believe this is a clerical error;
initial_guessneeds to be updated in the second loop;

I want to compute the sum of first N even numbers based on the user input N using recursive function

I want to compute the sum of first N even numbers based on the user input N using recursive function.
For example:
Sample Input N: 5
Sample Output: 2 + 4 + 6 + 8 + 10 = 30
I did my code in 2 ways but both of them gave wrong outputs. I'm doing something wrong in the function part sorting number in the loop. So I need some help!
n = int(input("Enter a nmuber: "))
for i in range(1,n+1):
for d in range(0,i+1,2):
print(d)
n = int(input("Enter a number: "))
def get_even(n):
for i in range(1,n+1,2):
d += i
print(d)
You can use the following.
Code
def sum_even(n):
# Base case
if n <= 1:
return 0
if n % 2:
# odd n
return sum_even(n - 1) # sum from next smaller even
else:
# even n
return n + sum_even(n - 2) # current plus sum from next smaller even
# Usage
n = int(input('Enter a nmuber: '))
print(sum_even(n))

How to generate a series using While loop

n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
sum = sum +1
i = i+1
print("The sum is" , sum)
I tried the above code but didn't got my answer.
The question is to generate a series that is: 1,4,7,10,13,16,19,22 using while loop.
To generate series you need to do two things:
Put the print inside the loop to output accumulator variable's value every iteration
Add 3 to sum every iteration and not 1 since it's the difference between series members
n = int(input("Enter n: ")) # n=8 should work
sum = 1
i = 1
while i <= n:
print(str(sum)+",")
sum = sum +3
i = i+1
I see two errors:
You should add i to sum,not 1 (this assumes you are interested in the sum as implied by the code)
You should be incrementing i by 3 not by 1
If I understand you correctly, you want this:
i = 1
while i <= 22:
print(i)
i += 3
n = int(input("Enter n: "))
count = 0
i = 1
sum = 0
while count <= n-1:
print(i)
sum += i
i += 3
count += 1
print("Sum is", sum)
You are going to want to increase the count by three every time with i += 3.
def createList():
user_input = input()
i = 1
list_of_vals = []
while i < int(user_input): # The max value:
list_of_vals.append(i)
i += 3
return list_of_vals
print (createList())
I think you want something like this:
n = int(input("Enter n: "))
series_sum = 0
i = 1
series = []
add = 3
while i <= n:
series.append(i)
series_sum = series_sum + i
i = i + add
print("series: ", series)
print("The sum is" , series_sum)
This would get you a series (and sum of elements) with the last element less than n, starting from i = 1 and increment add = 3

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

Categories