Need to figure out the random number the function gives me - python

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

Related

Why does this python code not swap the numbers?

Why does this python code not swap the numbers?
def swap(x, y):
'''THe swap function'''
print("INSIDE")
temp = x
x = y
y = temp
#Driver_code
x = 2
y = 3
swap(x, y)
print(x)
print(y)
In the Swap function add this one line:
global x,y;
The problem is when you are calling the swap() function it is making its own variable x and y,
not using the global variable x and y
Because the swap is inside the function.
You're swapping the values of the function parameters x and y, which are different from the x and y that are used below.
Just do this:
x, y = y, x
The swap function is not returning values
def swap(x, y):
'''THe swap function'''
print("INSIDE")
temp = x
x=y
y= temp
return x,y
#Driver_code
x = 2
y = 3
x,y=swap(x, y)
print(x)
print(y)
Here, you assign the returning values to x and y.

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) ?

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}")

What's wrong with my maths in my attempt to draw the Mandelbrot set?

I am currently trying to code a programm in python which result in drawing the mandelbrot set. The shape of the fractal looks ok but the outline isn't precise at all. I am trying to figuring if the problem comes from my maths or my code
I tried to raise the max number of iterations (which I called i) to see if the calculation was just too low but it didn't change much.
import numpy as np
from PIL import Image
taille = 1000
nb_points = 500
centre_x = taille/2
centre_y = taille/2
fractale = np.zeros((taille, taille, 3), dtype = np.uint8)
for x in range(-nb_points,nb_points):
x = float(x)
x = x/250
for y in range(-nb_points,nb_points):
y = float(y)
y = y/250
X = float(0)
Y = float(0)
i = 0
module_carre = 0
while module_carre < 4 and i <20 :
X = float(X**2 - Y**2 + x)
Y = float(2*X*Y + y)
i += 1
module_carre = float(X*X + Y*Y)
if module_carre < 4:
i=0
couleur = liste_couleur[i]
fractale[centre_x + x*250,centre_y + y*250] = couleur
imgpil = Image.fromarray(fractale, 'RGB')
imgpil.save("resultat.jpg")
I am French that's why you might not understand everything. I didn't paste all the lines about defining differents shades of blue etc...
I don't understand why my outline is this bad. I believe that it comes from my maths but i don't see any errors.
It's my first time posting on stack overflow and i don't understand evey tools yet. I didn't manage to add the image of the output
Sorry for my English and I hope you'll be able to help me fix my code
The main problem is here:
X = float(X**2 - Y**2 + x)
Y = float(2*X*Y + y)
In the calculation for Y, you want to use the old value of X, but it's already been updated and is no longer available. You could instead do:
new_X = float(X**2 - Y**2 + x)
Y = float(2*X*Y + y)
X = new_X
Or you could update them in parallel:
X, Y = float(X**2 - Y**2 + x), float(2*X*Y + y)
Also, you don't need the calls to float, so all you really need is:
X, Y = X**2 - Y**2 + x, 2*X*Y + y
By the way, Python does have a built-in complex number class, so you could initialize z and Z as z = complex(x, y) and Z = complex(0.0, 0.0).
Then your loop body would have:
Z = Z**2 + z
I also suggest increasing the maximum number of iterations. Limiting it to 20 will give very low resolution. I usually use at least 1000, at least for points near the boundary, when generating high-res images.

Random inputs and loops in 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

Categories