How do I EXTRACT all values ending in .000 and print them? - python

OK so I have a for loop running an equation iterating it a 0.005. I need it to print any "L" value ending in .000 and nothing else. How do I do that?
import numpy as np
import math
for D in np.arange(7, 9, 0.0050):
N = 28
n = 11
A = 7.32
P = 0.25
C = float(D)/float(P) #(P/8)*(2*L-N-n+((2*L-N-n)**(2)-0.810*(N-n)**(2))**(0.5)
L = 2*C+(N+n)/2+A/C
print("L = ", "%.3f"% float(L), '\n')
Problems I had:
I had to use np.arange as it wouldn't allow a float in a loop. If you can show me how to get around that, that'd be great.
When using np.arange, I would get "D" values like
D = 7.0009999999999994
L = 75.76939122982431
D = 7.001499999999999
L = 75.7733725630222
D = 7.001999999999999
L = 75.77735389888602
D = 7.002499999999999
L = 75.78133523741519
this causes errors when I go to use these numbers later in the code
this loop takes forever to compute. If there's a better way, show me. I have to make this quick or it won't get used.

This post explained why float is not working well in python:
numpy arange: how to make "precise" array of floats?
I used below code and it gave me precise decimal 3 numbers for both D & L in your calculation:
for i in range(7000, 9000, 5):
D = i/1000
print(D)
N = 28
n = 11
A = 7.32
P = 0.25
C = float(D)/float(P) #(P/8)*(2*L-N-n+((2*L-N-n)**(2)-0.810*(N-n)**(2))**(0.5)
L = 2*C+(N+n)/2+A/C
print("L = ", "%.3f"% float(L), '\n')

L3 is the variable
"%.3f"% is the 3rd decimal place
% 1 == 0 I'm not sure what this does, but 0 is the number I'm looking for.
if float("%.3f"% L3) % 1 == 0: #L3 is the variable
do_something()

Related

Creating multiple matrices with nested loop using numpy

import numpy as np
import random
x = np.linspace(-3.0,3.0,25)
b = 3; a = -3; n = 24
N = np.matrix(np.zeros(shape=(4,24)));
G = [] #want to save the 2 4by 24 matrices in G
s = []; g = []
Y = []
random.seed(4)
for j in range(0,2):
Y.append(np.random.randint(-6.0,6.0,size=(4,1)))
h = (b-a)/float(n)
s.append(0.5*h*((1+(np.cos((np.pi*(a-Y[j]))/3.0)))))
g.append(0.5*h*(1+(np.cos((np.pi*(b-Y[j]))/3.0))))
for k in range(0,Y[j].shape[0]):
for l in range(1, x.shape[0]-1):
N[k,l] = h*(1 + (np.cos((np.pi*(x[l]-Y[j][k]))/3.0)))
N[k,0] = s[j][k]
N = np.concatenate((N,g[j]),axis=1)
print(N)
Please, I need help. When I run this code, it produces just a single 4by25 matrix but it is suppose to be 2 4by25 matrix. I dont know why. My goal is to have the 2 4by25 matrices stored to variable G so that when i call G[0], it produces the first 4by25 and G[1] produces the second 4by25. Here Y outputs 2 4by1 coulmn vectors.
How is your code supposed to append 2 matrices to G? You are totally missing that part.
I don't really get what values you're looking for, so I can't tell you if values are added correctly, anyway you should add this line:
G.append(N)
(I'm just assuming you are appending N because it is the only 2x24 matrix)
Before the end of the first cylce, result should be something like:
for j in range(0,2):
Y.append(np.random.randint(-6.0,6.0,size=(4,1)))
h = (b-a)/float(n)
s.append(0.5*h*((1+(np.cos((np.pi*(a-Y[j]))/3.0)))))
g.append(0.5*h*(1+(np.cos((np.pi*(b-Y[j]))/3.0))))
for k in range(0,Y[j].shape[0]):
for l in range(1, x.shape[0]-1):
N[k,l] = h*(1 + (np.cos((np.pi*(x[l]-Y[j][k]))/3.0)))
N[k,0] = s[j][k]
N = np.concatenate((N,g[j]),axis=1)
G.append(N)

Python For loop not incrementing

clean_offset = len(malware)
tuple_clean = []
tuple_malware = []
for i in malware:
tuple_malware.append([malware.index(i), 0])
print(malware.index(i))
print(tuple_malware)
for j in clean:
tuple_clean.append([(clean_offset + clean.index(j)), 1])
print(clean.index(j))
print(tuple_clean)
import pdb; pdb.set_trace()
training_data_size_mal = 0.8 * len(malware)
training_data_size_clean = 0.8 * len(clean)
i increments as normal and produces correct output however j remains at 0 for three loops and then jumps to 3. I don't understand this.
There is a logical error on clean.index(j).
Array.index will return the first matched index in that array.
So if there are some equal variables there will be some error
You can inspect with below code.
malware = [1,2,3,4,5,6,7,8,8,8,8,8,2]
clean = [1,2,3,4,4,4,4,4,4,2,4,4,4,4]
clean_offset = len(malware)
tuple_clean = []
tuple_malware = []
for i in malware:
tuple_malware.append([malware.index(i), 0])
print(malware.index(i))
print(tuple_malware)
for j in clean:
tuple_clean.append([(clean_offset + clean.index(j)), 1])
print(clean.index(j))
print(tuple_clean)
training_data_size_mal = 0.8 * len(malware)
training_data_size_clean = 0.8 * len(clean)
for a in something
a is what is contained in something, not the index
for example:
for n in [1, 10, 9, 3]:
print(n)
gives
1
10
9
3
You either want
for i in range(len(malware))
or
for i, element in enumerate(malware)
at which point the i is the count and the element in the malware.index(i)
The last one is considered best practice when needing both the index and the element at that index in the loop.
op has already figured the question, but in case anyone is wondering or needs a TL;DR of Barkin's comment, its just a small correction,
replace
for i in malware
for j in clean
with
for i in range(len(malware))
for j in range(len(clean))
and at the end remove the .index() function, and place i and j.

How to solve this Array task in python that I couldn't for days?

I am trying to make a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 such that the result is 100
Understandably, there are a few people who have uploaded solutions already on the internet, but I want to come up with my own. Here's the non working code:
"""
This program outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100
"""
class solver:
def __init__(self):
"""
self.possibilities stores Arrays of type : [0]- always the sum of all operations
[1:9] all operations in int, where 0 equals plus, 1 equals minus, 2 equals nothing
"""
self.possibilities = []
self.possibilities.append([100])
for i in range(7):
self.possibilities.extend(self.makeNewIteration(i+1))
print(self.possibilities)
for obj in self.possibilities:
if 100 is obj[0]:
print(obj)
def makeNewIteration(self, i):
for obj in self.possibilities:
if(len(obj)<9):
if(obj[-1] is 3):#if case 3
#recalculate the result
currentResult = int(obj[0] + self.conceal(i-1, i))
else: currentResult = int(obj[0])
#print(obj)
possibilitiesNew = []
possibilitiesNew.append([currentResult + i] + obj[1:] + [1])#case 1
possibilitiesNew.append([currentResult - i] + obj[1:] + [2])#case 2
possibilitiesNew.append([currentResult] + obj[1:] + [3])#case 3
print("Iteration: "+str(i)+" : "+str(possibilitiesNew))
self.possibilities.remove(obj)#remove the old object
else:
print("finished.")
return possibilitiesNew
def conceal(self, x, y):
# makes 12 out of x=1 and y=2
return int(f'{x}{y}')
solve = solver()
The more I think about it the more problems I have.
I used to learn programming with an OOP mindset, and both the fact that it was a while ago and that this question is much easier with a procedural work flow makes me stuck. For example, what happens if there is two times "nothing" in a row ? does 1, 2, 3, 4 become 12,23 and ? ... I hope someone could fix the code a bit and I would figure out what I did wrong
Although eval should be avoided, here's another solution that uses it:
from itertools import product
[''.join(i) for i in product(*[[str(j)+'+', str(j) + '-', str(j)] for j in range(1, 9)] + ['9']) if eval(''.join(i))==100]
#['1+2+3-4+5+6+78+9', '1+2+34-5+67-8+9', '1+23-4+5+6+78-9', '1+23-4+56+7+8+9', '12+3+4+5-6-7+89', '12+3-4+5+67+8+9', '12-3-4+5-6+7+89', '123+4-5+67-89', '123+45-67+8-9', '123-4-5-6-7+8-9', '123-45-67+89']
My first approach would be
import itertools as it
import re
all_those_terms = (''.join([(sgn + str(i+1)) for i, sgn in enumerate(tpl)]) for tpl in it.product(['', '-', '+'], repeat=9) if tpl[0]!='')
for s in all_those_terms:
r = re.findall('[+-]\d+', '+'+s)
calc = sum(map(int, r))
if calc == 100:
print(s, '=', 100)
-1+2-3+4+5+6+78+9 = 100
+123-45-67+89 = 100
+123-4-5-6-7+8-9 = 100
+123+45-67+8-9 = 100
+123+4-5+67-89 = 100
+12-3-4+5-6+7+89 = 100
+12+3-4+5+67+8+9 = 100
+12+3+4+5-6-7+89 = 100
+1+23-4+56+7+8+9 = 100
+1+23-4+5+6+78-9 = 100
+1+2+34-5+67-8+9 = 100
+1+2+3-4+5+6+78+9 = 100
However, eval should be replaced, as it's dangerous...
I'll edit as soon as I have some time again...
EDIT: eval replaced...

Find mean of first 9 numbers then the next 9 numbers and so on from for loop

I have a for loop that gives me the following output.
0.53125
0.4375
0.546875
0.578125
0.75
0.734375
0.640625
0.53125
0.515625
0.828125
0.5
0.484375
0.59375
0.59375
0.734375
0.71875
0.609375
0.484375
.
.
.
How do I find the mean of the first 9 values, the next 9 values and so on and store them into a list like [0.58,0.20,...]? I have tried a lot of things but the values seem to be incorrect. What is the correct way of doing this?
What I did:
matchedRatioList = []
matchedRatio = 0
i = 0
for feature in range(90):
featureToCompare = featuresList[feature]
number = labelsList[feature]
match = difflib.SequenceMatcher(None,featureToCompare,imagePixList)
matchingRatio = match.ratio()
print(matchingRatio)
matchedRatio += matchingRatio
if i == 8:
matchedRatioList.append(matchedRatio / 9)
i = 0
matchedRatio = 0
i += 1
Once you have the list of numbers you can calculate the average of each group of 9 numbers using list comprehensions:
from statistics import mean
numbers = [0.53125, 0.4375, 0.546875, 0.578125, 0.75, 0.734375, 0.640625,
0.53125, 0.515625, 0.828125, 0.5, 0.484375, 0.59375, 0.59375,
0.734375, 0.71875, 0.609375, 0.484375]
group_len = 9
matched_ratios = [mean(group) for group in [numbers[i:i+group_len]
for i in range(0, len(numbers), group_len)]]
print(matched_ratios)
# [0.5850694444444444, 0.6163194444444444]
Your solution is close. Start with i = 1 and check for i == 9
matchedRatioList = []
matchedRatio = 0
i = 1 # change here
for feature in range(90):
...
matchedRatio += matchingRatio
if i == 9: # change here
matchedRatioList.append(matchedRatio / 9)
i = 0
matchedRatio = 0
i += 1
I do not know what you have tried so far, but I can present you with one solution to the problem.
Save all values in your for-loop to a buffer array. Use an if-statement with iterator % 9 == 0 inside your for-loop, which will make some portion of code execute only every 9 values.
Inside the if-statement you can write the mean value of your buffer array to a different output array. Reset your buffer array inside this if-statement as well, then this process is repeated and should behave in the way you want.
Try this
r = []
for b in a:
c += b
if i == 8:
c = c/9
r.append(c)
c = 0
i = 0
i += 1
since nobody used reduce so far :)
import functools
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
m = []
for i in range(9,len(l), 9):
m.append(functools.reduce(lambda x, y: x + y, l[i-9:i])/9)
print(m)
Using mean function from the statistics module of Python.
import statistics
# Sample Values list I created.
values_list = list()
for i in range(1,82):
values_list.append(i)
mean_list = list()
for i in range(0, len(values_list), 9):
mean_list.append(statistics.mean(values_list[i:i+9]))
for i in mean_list:
print(i)
This is the simplest way in which you can do it.
https://docs.python.org/3/library/statistics.html#statistics.mean
One-line solution given loop output in numbers:
[float(sum(a))/len(a) for a in zip(*[iter(numbers)]*9)]
Putting ideas from the other answers together, this could be the whole program:
from statistics import mean
matching_ratios = (difflib.SequenceMatcher(None, feature, imagePixList).ratio()
for feature in featuresList[:90])
matchedRatioList = [mean(group) for group in zip(*[matching_ratios] * 9)]

Issues with using np.linalg.solve in Python

Below, I'm trying to code a Crank-Nicholson numerical solution to the Navier-Stokes equation for momentum (simplified with placeholders for time being), but am having issues with solving for umat[timecount,:], and keep getting the error "ValueError: setting an array element with a sequence". I'm extremely new to Python, does anyone know what I could do differently to avoid this problem?
Thanks!!
def step(timesteps,dn,dt,Numvpts,Cd,g,alpha,Sl,gamma,theta_L,umat):
for timecount in range(0, timesteps+1):
if timecount == 0:
umat[timecount,:] = 0
else:
Km = 1 #placeholder for eddy viscosity
thetaM = 278.15 #placeholder for theta_m for time being
A = Km*dt/(2*(dn**2))
B = (-g*dt/theta_L)*thetaM*np.sin(alpha)
C = -dt*(1/(2*Sl) + Cd)
W_arr = np.zeros(Numvpts+1)
D = np.zeros(Numvpts+1)
for x in (0,Numvpts): #creating the vertical veocity term
if x==0:
W_arr[x] = 0
D[x] = 0
else:
W_arr[x] = W_arr[x-1] - (dn/Sl)*umat[timecount-1,x-1]
D = W_arr/(4*dn)
coef_mat_u = Neumann_mat(Numvpts,D-A,(1+2*A),-(A+D))
b_arr_u = np.zeros(Numvpts+1) #the array of known quantities
umat_forward = umat[timecount-1,2:Numvpts]
umat_center = umat[timecount-1,1:Numvpts-1]
umat_backward = umat[timecount-1,0:Numvpts-2]
b_arr_u = np.zeros(Numvpts+1)
for j in (0,Numvpts):
if j==0:
b_arr_u[j] = 0
elif j==Numvpts:
b_arr_u[j] = 0
else:
b_arr_u[j] = (A+D[j])*umat_backward[j]*(1-2*A)*umat_center[j] + (A-D[j])*umat_forward[j] - C*(umat_center[j]*umat_center[j]) - B
umat[timecount,:] = np.linalg.solve(coef_mat_u,b_arr_u)
return(umat)
Please note that,
for i in (0, 20):
print(i),
will give result 0 20 not 0 1 2 3 4 ... 20
So you have to use the range() function
for i in range(0, 20 + 1):
print(i),
to get 0 1 2 3 4 ... 20
I have not gone through your code rigorously, but I think the problem is in your two inner for loops:
for x in (0,Numvpts): #creating the vertical veocity term
which is setting values only at zero th and (Numvpts-1) th index. I think you must use
for x in range(0,Numvpts):
Similar is the case in (range() must be used):
for j in (0,Numvpts):
Also, here j never becomes == Numvpts, but you are checking the condition? I guess it must be == Numvpts-1
And also the else condition is called for every index other than 0? So in your code the right hand side vector has same numbers from index 1 onwards!
I think the fundamental problem is that you are not using range(). Also it is a good idea to solve the NS eqns for a small grid and manually check the A and b matrix to see whether they are being set correctly.

Categories

Resources