Random inputs and loops in python - python

from random import randint as r
x = r(1, 100)
y = r(1, 10)
def rannum(x,y):
if (x==y):
m = 2*y
else:
z = x * y
print z
rannum(x,y)
I have value of x and y which are randomly generated and I have a function which has two condition. How could I construct loop to meet my x==y condition? How could I know home many times I ran the loop to meet this condition. I am fairly new to programming and got stuck to this point. Please suggest/recommend me the way to achieve the result. I have made the range of smaller so that there could be high probability of selecting same number.Thankyou

I don't know why you are doing it, but below is what I understand from your question.
from random import randint as r
def rannum(x,y):
if (x==y):
m = 2*y
print m
else:
z = x * y
print z
count=0
while True:
count=count+1
x = r(1, 100)
y = r(1, 10)
if (x==y):
print "x is equal to y after count=",count
rannum(x,y)
break

Related

Plotting a piecewise function in python with numpy

Note: This is for homework so please don't post full code responses, just help on what I'm misusing would be appreciated
I'm trying to plot a piecewise defined function where when 0 < x <= 10 it will be a constant (KQ/10) and for x > 10 it will be KQ/x for 10 < x < 50. Currently my result comes back as a single value instead of my expected result of an array with a constant value up until x > 10 and then varying values until x = 50
My current code
import matplotlib.pyplot as plt
import scipy
x = np.linspace(0, 50, 1)
R = 10
r = np.linspace(10, 50, 1)
k = 1/(4*np.pi*constants.epsilon_0)
Q = 1
def inside(x):
return k*Q/R
def outer(x):
return k*Q/x
result = np.piecewise(
x,
[x <= R, x > R ],
[lambda x: inside(x), lambda x: outer(x)]
)
result
#plt.plot(x,result)
#plt.axis([0, 50,0, 500000])
#plt.xlabel('x')
#plt.ylabel('y')```
x = np.linspace(0, 50, 1)
isnt how linspace works... this only creates one data point ...
x = np.linspace(0, 50, 10000) ... would create 10k datapoints
perhaps you wanted np.arange(0,50,1) ?

How to generate all the possible combinations of three variables that sum to 1

I need to solve the equation x + y + z = 1.
I need to generate all the possible combinations of x, y, z so the equation is correct
I want the values of x, y, z to be between 0.1 and 0.9 with jump of 0.1.
So the values are restricted to [0.1, 0.2, ..., 0.8, 0.9]
I have found this answer Finding all combinations of multiple variables summing to 1
However it applies to R not python.
It would be very helpfull if someone would enlighten me.
Instead of a nested triple loop, you can consider generating all triplets
triplets = [(x/10.0, y/10.0, (10-x-y)/10.0) for x in range(1,9) for y in range(1,10-x)]
where each triplet (a,b,c) represents the possible values to be assigned to x, y, and z.
Note that I'm multiplying by 10 for then dividing when building the triplets to avoid rounding errors that might come up when doing directly:
if x/10 + y/10 + z/10 == 1:
The most primitive solution would be a nested loop over all combinations:
def variable_combinations(sum_up_to=1):
for x in range(1, 10):
for y in range(1, 10):
for z in range(1, 10):
if x/10 + y/10 + z/10 == sum_up_to:
yield (x/10, y/10, z/10)
all_solutions = list(variable_combinations())
Avoiding nested loops directly in python:
import itertools
import numpy as np
x = y = z = [ i/10 for i in range(1,10)]
p = itertools.product(x,y,z)
combs = [e for e in p if np.sum(e) == 1]
Now combs is a list of triplets (tuples) that sum to 1.

Test whole range of possible inputs for a given question

Is there a quick way to find the maximum value (float) from a function and the corresponding arguments x, y that are both integers between 0 and 100 (inclusive)? Do I need to use the assert function or something like that to get the range of all possible inputs?
def fun_A(x,y):
import math
if x == y:
return 0
first = math.cos((y%75)*(math.pi/180))
second = math.sin((x%30)*(math.pi/180))
return (first + second) / (abs(x - y))
For small problems like this it is probably fast enough to evaluate every possible combination and choose the maximum. The numpy library makes this easy to write and pretty fast as well:
import numpy as np
def fun_A(x, y):
first = np.cos((y%75)*(np.pi/180))
second = np.sin((x%30)*(np.pi/180))
return np.where(x == y, 0, (first + second) / (abs(x - y)))
x, y = np.mgrid[0:101, 0:101]
f = fun_A(x, y)
maxindex = np.argmax(f)
print('Max =', f.flat[maxindex], ' at x =', x.flat[maxindex], 'y =', y.flat[maxindex])
Output:
Max = 1.4591796850315724 at x = 89 y = 88
Things to note:
I've just replaced calls to math with calls to np.
x and y are matrices which allow us to evaluate every possible combination the two values in one function call.
I would do this for the tan function :
from math import tan
y = 0
x = 0
for x_iteration in range(0, 101):
if tan(x_iteration) > y :
x = x_iteration
y = tan(x_iteration)
x = int(x)
y = int(y)
It's fairly straightforward to write a program to solve this:
max_result = None
max_x = 0
max_y = 0
for x in range(0, 101):
for y in range(0, 101):
result = fun_A(x, y)
if max_result is None or result > max_result:
max_result = result
max_x = x
max_y = y
print(f"x={max_x} and y={max_y} produced the maximum result of {max_result}")

Plotting a graph given function definition

I'm currently trying to plot a graph of iterations of a certain function in python. I have defined the function as stated below but I am unsure on how to plot the graph such that the y value is on the y axis and the iteration number is on the x axis.
So, I have tried using the plt.plot function with different values in as my x values but using logistic(4, 0.7) as the y value for the y axis.
def logistic(A, x):
y = A * x * (1 - x)
return y
But each return an error. Can anyone shed any light on this, I want to do a total of 1000 iterations.
I dont understand much what you are saying concerning x being number ofiteration while you are showing us function logistic(4, 0.7). As far as I know, iterations is integer, whole number. You cant iterate just halfly or partially
def logistic(A, x):
y = A * x * (1 - x)
return y
A = 1
x_vals = []
y_vals = []
for x in range(1,1000):
x_vals.append(x)
y_vals.append(logistic(A,x))
#plt.plot(x_vals,y_vals) # See every iteration
#plt.show()
plt.plot(x_vals,y_vals) # See all iterations at once
plt.show()
Ah, the logistic map. Are you trying to make a cobweb plot? If so, your error may be elsewhere. As others have mentioned, you should post the error message and your code, so we can better help you. However, based on what you've given us, you can use numpy.arrays to achieve your desired result.
import numpy as np
import matplotlib.pyplot as plt
start = 0
end = 1
num = 1000
# Create array of 'num' evenly spaced values between 'start' and 'end'
x = np.linspace(start, end, num)
# Initialize y array
y = np.zeros(len(x))
# Logistic function
def logistic(A, x):
y = A * x * (1 - x)
return y
# Add values to y array
for i in range(len(x)):
y[i] = logistic(4, x[i])
plt.plot(x,y)
plt.show()
However, with numpy.arrays, you can omit the for loop and just do
x = np.linspace(start, end, num)
y = logistic(4, x)
and you'll get the same result, but faster.

Need to figure out the random number the function gives me

Since I am using random generator to place the ships how can I be able to get the exact value of x and y coordinate from my function:
def addShip(board):
x = randint(0, 9)
y = randint(0, 9)
board[x][y] = 1
How would i be able to print the exact value that the function used for x and y? Any help would be appreciated
def addShip(board):
x = randint(0, 9)
y = randint(0, 9)
return x, y
board[x][y] = 1

Categories