I'm having trouble adding two matrices in python - isa-swizzling

I want to add two matrcies in python 3 but the problem comes when I add input to the program
Here is my code
def addmatrix(a,b):
d=[]
n=0
while n < len (a):
c = []
k = 0
while k < len (a[0]) :
c.append(a[n][k]+b[n][k])
k += 1
n += 1
d.append (c)
return d
def main():
a = input("Enter a Matrix: ")
b = input("Enter another Matrix: ")
print (addmatrix(a,b))
main()
If the input is
Enter a Matrix: [[5,6], [1,2], [2,4]]
Enter another Matrix: [[2,3], [-6,0], [-2, 4]]
The output comes out as [['[['], ['[['], ['52'], [',,'], ['63'], [']]'], [',,'], [' '], ['[['], ['1-'], [',6'], ['2,'], [']0'], [',]'], [' ,'], ['[ '], ['2['], [',-'], ['42'], ['],'], ['] ']]
But if I take out the input from the program and make it so that
def main():
a = [[5,6], [1,2], [2,4]]
b = [[2,3], [-6,0], [-2, 4]]
print (addmatrix(a,b))
main()
The output then comes out as [[7, 9], [-5, 2], [0, 8]] which is correct.
Is there a way I can make my program work so that when a person inputs two matrices they add together? I'm new at python so any help will be appreciated :)

You will have to convert the user input into a Python object. Right now, it's a string.
You can use eval (which should not be used if you don't know what your users will input. I can type in __import__('os').system('rm /some/file.txt') and Python will delete a file):
a = eval(input("Enter a Matrix: "))
Or you can use ast.literal_eval, which is safe:
from ast import literal_eval
...
a = literal_eval(input("Enter a Matrix: "))

Try this:
import ast
def addmatrix(a,b):
return [map(sum, zip(*x)) for x in zip(a,b)]
def main():
a = ast.literal_eval(raw_input("Enter a Matrix: "))
b = ast.literal_eval(raw_input("Enter another Matrix: "))
print addmatrix(a,b)
main()

Related

jruby concurrent pool threads mixing up when combined for result

There is an array with indices [[0, n_0], [1, n_1], ..., [n, n_n]]. For each n_i a function is called. It is necessary to reorder the result from the threads by first component after every thread has terminated. As far as I could find a way to do this, I organized that the index is hard-coded by asking if the index is e.g. 0 and then starting the code separately for the hard-coded index 0. So far this a possible way to do it (even though the code looks as if someone didn't understand what a loop is for).
rest = []
tpl.each do |idx, vn|
if idx == 0
pool.post do
res = funk(vn)
p ['idx 0: ', res]
rest += [[0, res]]
end#pool.post
elsif idx == 1
pool.post do
res = funk(vn)
p ['idx 1: ', res]
rest += [[1, res]]
end#pool.post
end;end
But now there is a strange behaviour:
Index 0 and 1 are calculated accurately, but when the result of 1 is added one line later, the result of the former function is added (again).
["idx 1: ", [4]]
["idx 0: ", [16900]]
rest: [[0, [16900]], [1, [16900], ...]
This is not always the case, so it depends on the order of the appearance of the results.
If e.g. the calculation of index 0 is finished after the calculation of index 1, then idx 1 is missing, or wrong. But other cases of confused results also appear: idx 0 before idx 1, but result of idx 0 is the result of idx 1.
?
It looks like if the threads are not really separated. Can that be enforced, or is there a smarter way of keeping indeces?
One option, I found out, is to synchronize the threads, but that would make the algorithm slower again, so a better solution is:
The results don't get mixed up, if the rest-tuple already has the structure to differentiate the results coming in:
rest = [[], []]
tpl.each do |idx, vn|
if idx == 0
pool.post do
res = funk(vn)
p ['idx 0: ', res]
rest[0] << [0, res]
end#pool.post
elsif idx == 1
pool.post do
res = funk(vn)
p ['idx 1: ', res]
rest[1] << [1, res]
end#pool.post
end;end

Create words and its position in Pyspark

Hi I am trying to create string which will have words and its position as it appear in the input string. I am able to do it in python using below code -
from collections import defaultdict
import re
s = 'Create a string with position from a string a'
wp = defaultdict(list)
for n, k in enumerate(s.split()):
wp[k].append(n+1)
raw_output = re.search('{(.*)}', str(wp)).group(1).replace('[','').replace(']','')
final_output = re.sub("(\d), '", r"\1 '", raw_output)
And output is
"'Create': 1 'a': 2, 7, 9 'string': 3, 8 'with': 4 'position': 5 'from': 6"
How can I do the same in pyspark?
Pyspark has few additional concepts you might need to revisit, using RDD apis is the best
for your problem statement.
Here is a code snippet that should work for you.
def positional_encoder(sentence):
words=sentence.split(" ")
indexes=list(range(0,len(words)))
return list(zip(words,indexes))
data_rdd = sc.parallelize(["Create a string with position from a string a"])
words_index=data_rdd.map(lambda sentence: positional_encoder(sentence))
## Just for debugging:
words_index.collect() ## Remove this after debugging

Calculating Factorials using QBasic

I'm writing a program that calculates the Factorial of 5 numbers and output the results in a Tabular form but I keep getting Zeros.
Factorial Formula:. n! = nĂ—(n-1)!
I tried:
CLS
DIM arr(5) AS INTEGER
FOR x = 1 TO 5
INPUT "Enter Factors: ", n
NEXT x
f = 1
FOR i = 1 TO arr(n)
f = f * i
NEXT i
PRINT
PRINT "The factorial of input numbers are:";
PRINT
FOR x = 1 TO n
PRINT f(x)
NEXT x
END
and I'm expecting:
Numbers Factorrials
5 120
3 6
6 720
8 40320
4 24
You did some mistakes
FOR i = 1 TO arr(n)
where is n defined
you also never stored actual values into arr
PRINT f(x)
here you take from array f that is also not defined in your code
Possible solution to calculate arrays of factorials:
CLS
DIM arr(5) AS INTEGER
DIM ans(5) AS LONG
FOR x = 1 TO 5
INPUT "Enter Factors: ", arr(x)
f& = 1
FOR i = 1 TO arr(x)
f& = f& * i
NEXT i
ans(x) = f&
NEXT x
PRINT
PRINT "The factorial of input numbers are:";
PRINT
PRINT "Numbers", "Factorials"
FOR x = 1 TO 5
PRINT arr(x), ans(x)
NEXT x
END
I don't have a BASIC interpreter right in front of me, but I think this is what you're looking for:
CLS
DIM arr(5) AS INTEGER
DIM ans(5) AS LONG 'You need a separate array to store results in.
FOR x = 1 TO 5
INPUT "Enter Factors: ", arr(x)
NEXT x
FOR x = 1 to 5
f& = 1
FOR i = 1 TO arr(x)
f& = f& * i
NEXT i
ans(x) = f&
NEXT x
PRINT
PRINT "The factorial of input numbers are:";
PRINT
PRINT "Numbers", "Factorials"
FOR x = 1 TO 5
PRINT STR$(arr(x)), ans(x)
NEXT x
END
Just a comment though: In programming, you should avoid reusing variables unless you are short on memory. It can be done right, but it creates many opportunities for hard to find bugs in larger programs.
Possible solution to calculate arrays of factorials and square roots:
CLS
PRINT "Number of values";: INPUT n
DIM arr(n) AS INTEGER
DIM ans(n) AS LONG
FOR x = 1 TO n
PRINT "Enter value"; x;: INPUT arr(x)
f& = 1
FOR i = 1 TO arr(x)
f& = f& * i
NEXT i
ans(x) = f&
NEXT x
PRINT
PRINT "The factorial/square root of input numbers are:";
PRINT
PRINT "Number", "Factorial", "Squareroot"
FOR x = 1 TO n
PRINT arr(x), ans(x), SQR(arr(x))
NEXT x
END

Openmdao V1.7 Sellar MDF

I foound out something strange with the MDA of sellar problem on the doc page of OpenMDAO (http://openmdao.readthedocs.io/en/1.7.3/usr-guide/tutorials/sellar.html)
If I extract the code and only run the MDA (adding counters in the disciplines), I observe that the number of calls is differents between disciplines (twice the number of d2 for d1 discipline) which is not expected . Does someone has an answer ?
Here is the results
Coupling vars: 25.588303, 12.058488
Number of discipline 1 and 2 calls (10,5)
And here is the code
# For printing, use this import if you are running Python 2.x from __future__ import print_function
import numpy as np
from openmdao.api import Component from openmdao.api import ExecComp, IndepVarComp, Group, NLGaussSeidel, \
ScipyGMRES
class SellarDis1(Component):
"""Component containing Discipline 1."""
def __init__(self):
super(SellarDis1, self).__init__()
# Global Design Variable
self.add_param('z', val=np.zeros(2))
# Local Design Variable
self.add_param('x', val=0.)
# Coupling parameter
self.add_param('y2', val=1.0)
# Coupling output
self.add_output('y1', val=1.0)
self.execution_count = 0
def solve_nonlinear(self, params, unknowns, resids):
"""Evaluates the equation
y1 = z1**2 + z2 + x1 - 0.2*y2"""
z1 = params['z'][0]
z2 = params['z'][1]
x1 = params['x']
y2 = params['y2']
unknowns['y1'] = z1**2 + z2 + x1 - 0.2*y2
self.execution_count += 1
def linearize(self, params, unknowns, resids):
""" Jacobian for Sellar discipline 1."""
J = {}
J['y1','y2'] = -0.2
J['y1','z'] = np.array([[2*params['z'][0], 1.0]])
J['y1','x'] = 1.0
return J
class SellarDis2(Component):
"""Component containing Discipline 2."""
def __init__(self):
super(SellarDis2, self).__init__()
# Global Design Variable
self.add_param('z', val=np.zeros(2))
# Coupling parameter
self.add_param('y1', val=1.0)
# Coupling output
self.add_output('y2', val=1.0)
self.execution_count = 0
def solve_nonlinear(self, params, unknowns, resids):
"""Evaluates the equation
y2 = y1**(.5) + z1 + z2"""
z1 = params['z'][0]
z2 = params['z'][1]
y1 = params['y1']
# Note: this may cause some issues. However, y1 is constrained to be
# above 3.16, so lets just let it converge, and the optimizer will
# throw it out
y1 = abs(y1)
unknowns['y2'] = y1**.5 + z1 + z2
self.execution_count += 1
def linearize(self, params, unknowns, resids):
""" Jacobian for Sellar discipline 2."""
J = {}
J['y2', 'y1'] = .5*params['y1']**-.5
#Extra set of brackets below ensure we have a 2D array instead of a 1D array
# for the Jacobian; Note that Jacobian is 2D (num outputs x num inputs).
J['y2', 'z'] = np.array([[1.0, 1.0]])
return J
class SellarDerivatives(Group):
""" Group containing the Sellar MDA. This version uses the disciplines
with derivatives."""
def __init__(self):
super(SellarDerivatives, self).__init__()
self.add('px', IndepVarComp('x', 1.0), promotes=['x'])
self.add('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])
self.add('d1', SellarDis1(), promotes=['z', 'x', 'y1', 'y2'])
self.add('d2', SellarDis2(), promotes=['z', 'y1', 'y2'])
self.add('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0),
promotes=['obj', 'z', 'x', 'y1', 'y2'])
self.add('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['y1', 'con1'])
self.add('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2'])
self.nl_solver = NLGaussSeidel()
self.nl_solver.options['atol'] = 1.0e-12
self.ln_solver = ScipyGMRES()
from openmdao.api import Problem, ScipyOptimizer
top = Problem() top.root = SellarDerivatives()
#top.driver = ScipyOptimizer()
#top.driver.options['optimizer'] = 'SLSQP'
#top.driver.options['tol'] = 1.0e-8
#
#top.driver.add_desvar('z', lower=np.array([-10.0, 0.0]),
# upper=np.array([10.0, 10.0]))
#top.driver.add_desvar('x', lower=0.0, upper=10.0)
#
#top.driver.add_objective('obj')
#top.driver.add_constraint('con1', upper=0.0)
#top.driver.add_constraint('con2', upper=0.0)
top.setup()
# Setting initial values for design variables top['x'] = 1.0 top['z'] = np.array([5.0, 2.0])
top.run()
print("\n")
print("Coupling vars: %f, %f" % (top['y1'], top['y2']))
count1 = top.root.d1.execution_count
count2 = top.root.d2.execution_count
print("Number of discipline 1 and 2 calls (%i,%i)"% (count1,count2))
This is a good observation. Whenever you have a cycle, the "head" component runs a second time. The reason is as follows:
If you have a model with components that contain implicit states, a single execution looks like this:
Call solve_nonlinear to execute components
Call apply_nonlinear to calculate the residuals.
We don't have any components with implicit states in this model, but we indirectly created the need for one by having a cycle. Our execution looks like this:
Call solve_nonlinear to execute all components.
Call apply_nonlinear (which caches the unknowns, calls solve_nolinear, and saves the difference in unknowns) on just the "head" component to generate a residual that we can converge.
Here, the head component is just the first component that is executed based on however it determines what order to run the cycle in. You can verify that only a single head component gets extra runs by building a cycle with more than 2 components.

Extract numbers from string in MATLAB

I'm working with sscanf to extract a number from a string. The strings are usually in the form of:
'44 ppm'
'10 gallons'
'23.4 inches'
but ocassionally they are in the form of:
'<1 ppm'
If I use the following code:
x = sscanf('1 ppm','%f')
I get an output of
1
But if I add the less than sign in front of the one:
x = sscanf('<1 ppm','%f')
I get:
[]
How can I write this code so this actually produces a number? I'm not sure yet what number it should print...but let's just say it should print 1 for the moment.
You can use regexp:
s= '<1 ppm';
x=regexp(s, '.*?(\d+(\.\d+)*)', 'tokens' )
x{1}
Demo :
>> s= {'44 ppm', '10 gallons', '23.4 inches', '<1 ppm' } ;
>> x = regexp(s, '.*?(\d+(\.\d+)*)', 'tokens' );
>> cellfun( #(x) disp(x{1}), x ) % Demo for all
'44'
'10'
'23.4'
'1'