Making a randomly generated 2d map in python is taking too long to process all of the map generation - python-3.x

import random
l = "lava"
d = "dessert"
f = "forest"
v = "village"
s = "sect"
w = "water"
c = "city"
m = "mountains"
p = "plains"
t = "swamp"
map_list = [l,d,f,v,s,w,c,m,p,t]
map = []
for i in range(50):
map.append([])
def rdm_map(x):
for i in range(50):
map[x].append(random.choice(map_list))
def map_create():
x = 0
while x <= len(map):
rdm_map(x)
x + 1
map_create()
print(map[2][1])
I'm not getting anything for output not even an error code.I'm trying to create a randomly generated game map of descent size but when i went to run it nothing happened i'm thinking since my computer isn't that great its just taking way to long to process but i just wanted to post it on here to double check. If that is the issue is there a way to lessen the load without lessening the map size?

You have the following bugs:
Inside the map_create you must change x + 1 to x += 1. For this reason your script runs for ever.
After that you should change the while x <= len(map): to while x < len(map):. If you keep the previous, you will get a Index Error.
In any case, your code can be further improved. Please try to read some pages of the tutorial first.

Related

Find global maximum of an equation using python

I am trying to write some codes to find the global maximum of an equation, e.g. f = -x**4.
Here is what I have got at the moment.
import sympy
x = sympy.symbols('x')
f = -x**4
df = sympy.diff(f,x)
ans = sympy.solve(df,x)
Then I am stuck. How should I substitute ans back into f, and how would I know if that would be the maximum, but not the minimum or a saddle point?
If you are just looking for the global maximum and nothing else, then there is already a function for that. See the following:
from sympy import *
x = symbols('x')
f = -x**4
print(maximum(f, x)) # 0
If you want more information such as the x value that gives that max or maybe local maxima, you'll have to do more manual work. In the following, I find the critical values as you have done above and then I show the values as those critical points.
diff_f = diff(f, x)
critical_points = solve(diff_f, x)
print(critical_points) # x values
for point in critical_points:
print(f.subs(x, point)) # f(x) values
This can be extended to include the second derivative test as follows:
d_f = diff(f, x)
dd_f = diff(f, x, 2)
critical_points = solve(d_f, x)
for point in critical_points:
if dd_f.subs(x, point) < 0:
print(f"Local maximum at x={point} with f({point})={f.subs(x, point)}")
elif dd_f.subs(x, point) > 0:
print(f"Local minimum at x={point} with f({point})={f.subs(x, point)}")
else:
print(f"Inconclusive at x={point} with f({point})={f.subs(x, point)}")
To find the global max, you would need to take all your critical points and evaluate the function at those points. Then pick the max from those.
outputs = [f.subs(x, point) for point in critical_points]
optimal_x = [point for point in critical_points if f.subs(x, point) == max(outputs)]
print(f"The values x={optimal_x} all produce a global max at f(x)={max(outputs)}")
The above should work for most elementary functions. Apologies for the inconsistent naming of variables.
If you are struggling with simple things like substitution, I suggest going through the docs for an hour or two.

Using Julia to plot the mandelbrot with multithreading, race condition problem

I'm new to Julia and I am trying to implement Julia's multithreading but I believe I am running into the "race condition problem". Here I am plotting the mandelbrot but I believe because of the race condition the array index [n] is messing with the color mapping. I tried using the atomic feature to the index n but apparently i cant use that type as an index. Here are pictures to compare as well as the code block.
Thanks!
module MandelBrot
using Plots
#make some functions for mandelbrot stuff
#find out if a number is part of the set
#remember the mandelbrot is symmetrical about the real number plane
function mandel(c)
#determine if a number is in the set or not in the set -
max_iter = 1000;
bound = 2
z = 0
n = 0
#if the magnitude of z exceeds two we know we are done.
while abs(z)<bound && n<max_iter
z = z^2+c
n+=1
end
return n #if n is 1000 assume c is good, else not of the set
end
#map n to a color
function brot(n)
rgb = 250
m = (n%rgb) /rgb#divide 250
if 0< n <= 250
c = RGB(1,m,0)
elseif 250<n<=500
c = RGB(1-m,1,0)
elseif 500<n<=750
c = RGB(0,1,m)
elseif 750<n<=999
c = RGB(0,1-m,1)
else
c=RGB(0,0,0)
end
return c
#TODO: append this c to an array of color values
end
#mrandom
function mandelbrot(reals,imags)
#generate #real amount of points between -2 and 1
#and #imag amount of points between 0 and i
#determine if any of those combinations are in the mandelbrot set
r = LinRange(-2,1,reals)
i = LinRange(-1,1,imags)
master_list = zeros(Complex{Float64},reals*imags,1)
color_assign = Array{RGB{Float64}}(undef,reals*imags,1)
#n = Threads.Atomic{Int64}(1)
n = 1
Threads.#threads for real_num in r
for imaginary_num in i
#z = complex(real_num, imaginary_num) #create the number
#master_list[n] = z #add it to the list
#color_assign[n,1] = (brot ∘ mandel)(z) #function of function! \circ + tab
#or would this be faster? since we dont change z all the time?
master_list[n] = complex(real_num, imaginary_num)
color_assign[n,1] = (brot ∘ mandel)(complex(real_num, imaginary_num))
n+=1
#Threads.atomic_add!(n,1)
end
end
gr(markerstrokewidth=0,markerstrokealpha=0,markersize=.5,legend=false)
scatter(master_list,markerstrokecolor=color_assign,color=color_assign,aspect_ratio=:equal)
end
#end statement for the module
end
julia> #time m.mandelbrot(1000,1000)
2.260481 seconds (6.01 M allocations: 477.081 MiB, 9.56% gc time)
Here is what should help:
function mandelbrot(reals,imags)
r = LinRange(-2,1,reals)
i = LinRange(0,1,imags)
master_list = zeros(Complex{Float64},reals*imags,1)
color_assign = Array{RGB{Float64}}(undef,reals*imags,1)
Threads.#threads for a in 1:reals
real_num = r[a]
for (b, imaginary_num) in enumerate(i)
n = (a-1)*imags + b
master_list[n] = complex(real_num, imaginary_num)
color_assign[n, 1] = (brot ∘ mandel)(complex(real_num, imaginary_num))
end
end
gr(markerstrokewidth=0,markerstrokealpha=0,markersize=1,legend=false)
scatter(master_list,markerstrokecolor=color_assign,color=color_assign,aspect_ratio=:equal)
end
The approach is to compute n as a function of indices along r and i.
Also note that I use 1:reals and not just enumerate(r) as Threads.#threads does not accept arbitrary iterators.
Note though that your code could probably be cleaned up in other but it is hard to do this without a fully reproducible example.

Karatsuba recursive code is not working correctly

I want to implement Karatsuba multiplication algorithm in python.But it is not working completely.
The code is not working for the values of x or y greater than 999.For inputs below 1000,the program is showing correct result.It is also showing correct results on base cases.
#Karatsuba method of multiplication.
f = int(input()) #Inputs
e = int(input())
def prod(x,y):
r = str(x)
t = str(y)
lx = len(r) #Calculation of Lengths
ly = len(t)
#Base Case
if(lx == 1 or ly == 1):
return x*y
#Other Case
else:
o = lx//2
p = ly//2
a = x//(10*o) #Calculation of a,b,c and d.
b = x-(a*10*o) #The Calculation is done by
c = y//(10*p) #calculating the length of x and y
d = y-(c*10*p) #and then dividing it by half.
#Then we just remove the half of the digits of the no.
return (10**o)*(10**p)*prod(a,c)+(10**o)*prod(a,d)+(10**p)*prod(b,c)+prod(b,d)
print(prod(f,e))
I think there are some bugs in the calculation of a,b,c and d.
a = x//(10**o)
b = x-(a*10**o)
c = y//(10**p)
d = y-(c*10**p)
You meant 10 to the power of, but wrote 10 multiplied with.
You should train to find those kinds of bugs yourself. There are multiple ways to do that:
Do the algorithm manually on paper for specific inputs, then step through your code and see if it matches
Reduce the code down to sub-portions and see if their expected value matches the produced value. In your case, check for every call of prod() what the expected output would be and what it produced, to find minimal input values that produce erroneous results.
Step through the code with the debugger. Before every line, think about what the result should be and then see if the line produces that result.

python scipy fmin not completing succesfully

I have a function that I am attempting to minimize for multiple values. For some values it terminates successfully however for others the error
Warning: Maximum number of function evaluations has been exceeded.
Is the error that is given. I am unsure of the role of maxiter and maxfun and how to increase or decrease these in order to successfully get to the minimum. My understanding is that these values are optional so I am unsure of what the default values are.
# create starting parameters, parameters equal to sin(x)
a = 1
k = 0
h = 0
wave_params = [a, k, h]
def wave_func(func_params):
"""This function calculates the difference between a sinewave (sin(x)) and raw_data (different sin wave)
This is the function that will be minimized by modulating a, b, k, and h parameters in order to minimize
the difference between curves."""
a = func_params[0]
b = 1
k = func_params[1]
h = func_params[2]
y_wave = a * np.sin((x_vals-h)/b) + k
error = np.sum((y_wave - raw_data) * (y_wave - raw_data))
return error
wave_optimized = scipy.optimize.fmin(wave_func, wave_params)
You can try using scipy.optimize.minimize with method='Nelder-Mead' https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html.
https://docs.scipy.org/doc/scipy/reference/optimize.minimize-neldermead.html#optimize-minimize-neldermead
Then you can just do
minimum = scipy.optimize.minimize(wave_func, wave_params, method='Nelder-Mead')
n_function_evaluations = minimum.nfev
n_iterations = minimum.nit
or you can customize the search algorithm like this:
minimum = scipy.optimize.minimize(
wave_func, wave_params, method='Nelder-Mead',
options={'maxiter': 10000, 'maxfev': 8000}
)
I don't know anything about fmin, but my guess is that it behaves extremely similarly.

Some basic python coding bug I don't know how to solve

I've encountered some problems when I was trying simulate school's math question,I've test the inner loop independently and the result is what I expect.I have no idea where is the problem and where can I get the resolution.It should be a simple bug.
This is the question:
There is a bag which includes three red balls ,four white balls and five black balls.Take one ball each time.Then what is the probability when red balls were the first color being collected.
And This is my code:(All annotations were not added in my code)
import random as rd
y = 1000 *//total try*
succ = 0 *//success times*
orgbg = ['r','r','r','w','w','w','w','b','b','b','b','b'] *//original bag for each loop initialization*
while (y >= 0):
redball = 0
blackball = 0
whiteball = 0
newbg = orgbg *//every bag for a single try*
while (redball < 3 and whiteball < 4 and blackball < 5):
tknum = rd.randrange(0,len(newbg),1)
tkball = newbg[tknum]
if (tkball == 'r'):
redball = redball + 1
elif (tkball =='w'):
whiteball = whiteball + 1
else:
blackball = blackball + 1
del newbg[tknum]
if (redball == 3):
succ = succ + 1
y = y - 1
print (succ)
This is what the error report says:
ValueError: empty range for randrange() (0,0, 0)
When I turn the code
tknum = rd.randrange(0,len(newbg),1)
into
tknum = rd.randrange(5,len(newbg),1)
The error reoprt says:
ValueError: empty range for randrange() (5,5, 0)
I guess it is the initialization in the outer loop newbg = orgbg doesn't work out,but how can that happen?
Sorry for giving such a length question ,I'm a beginner and this is the first time I ask question on StackOverFlow,you can also give me some suggestion on my code style or method and the way of asking question,next time I will be better,hope you don't mind.
I think that your problem is indeed linked with the initialization in the outer loop newbg = orgbg. To correct your code, you should modify this line with
newbg = deepcopy(orgbg)
and import the corresponding module at the start of your code:
from copy import deepcopy
The explanation of the bug is a bit complicated and is linked with the way that Python handles the memory when copying a list. In fact, there is two possibility for this: a shallow or a deep copy. Here, you made a shallow copy when a deep copy would have been necessary. It is better explained here: https://www.python-course.eu/deep_copy.php or What exactly is the difference between shallow copy, deepcopy and normal assignment operation?

Resources