I have a module with one method:
def find_inverse_matrix(C, log=False):
n = C.shape[0]
Cs = C.copy()
i = 0
C = np.matrix(np.eye(n))
B = np.matrix(np.eye(n))
J = set(range(n))
S = [0] * n
if log: print Cs
while i <= n-1:
if log: print '\nIteration', i
f = False
j = 0
ei = get_ek(i, n)
for j in J:
cj = get_ck(Cs, j)
alpha = (ei * B * cj)[0, 0]
if log: print 'alpha%s = %s' % (j, alpha)
if not(is_zero(alpha)):
f = True
break
if not(f):
exit('Inverse matrix is not exist')
J.remove(j)
S[j] = i
C[:, i] = Cs[:, j]
if log: print 'C%s:\n%s' % (i, C)
D = get_Dkz(i, B * C[:, i])
if log: print 'D%s:\n%s' % (i, D)
B = D * B
if log: print 'B%s:\n%s' % (i, B)
i += 1
if log: print '\n S = ', S
if log: print 'Result'
R = construct_matrix(B, S)
if log: print R
if log: print '\nCheck result:'
if log: print Cs * R
return R
If I call this method from this file it shows all print, but if I call if from another all print should be suppressed. Now I use check before every print, but how it do simple and pretty in 'pythonic' style?
Normally, print is a statement in the language. But if you add the line from __future__ import print_function to your imports then it is used as a function. This means two things:
a) You need to use this as a function - meaning print(Cs) instead of print Cs.
b) You can override it, since in python functions are objects you can play with.
You can define your own "my_print" functions which you can later change instead of the builtin print.
Example:
>>> from __future__ import print_function
>>> _print_ = print
>>> def myprint(*arg, **kwarg):
... _print_("yeah.")
... _print_(*arg,** kwarg)
...
>>> myprint("ok")
yeah.
ok
>>> print = myprint
>>> print('3')
yeah.
3
>>>
So just write your myprint function so that it'd check for "log" before, and your prints should be the same. Or just override print only when you don't want to suppress printing.
if __name__ == '__main__': will execute a block of code only if a file is executed directly, not loaded as a module. You can set a flag there to turn on logging.
A more pythonic way might be to pass a log function into the module instead of a flag. That way you could pass in an empty function to suppress logging.
Related
import os; import time;
not_command_error = "error: not an command"
empty_error = "error: file empty"
def read(file):
e = open(file, "r")
b = e.readlines()
e.close()
return b
code_file = "put your code here"
e = read(code_file)
if e == []:
print("\033[0;37;41m",empty_error)
time.sleep(90000)
count = len(e)
print(count)
g = 0
l = 0
while True:
l+= 1
t = open(code_file, "r")
y = t.readlines(l)
t.close()
k = len(y)
print(y[k])
u = y[k]
g+= 1
if count == g:
break
this is my code, and I get and index out of range error, any help?
i tried changing the format and it still didn't work.
i get index out of range error, do i not use a variable?
This part of your code will throw an index out of range error:
k = len(y)
print(y[k])
Indices for lists in Python go from 0 to len(x) - 1, so to access the last element, k should equal len(y) - 1.
Even better (thanks, #MarkK!), you can use negative indices to access the end of the array:
print(y[-1])
I need a short function to return the answer to a string of multiplication/addition with pemdas. For example it should take "6*3+4" and return 22 or "7+3*10" and return 37. Ideally it could easily be changed to include division/subtraction.
I've tried doing this with index operations.
def pemdas(s):
mult = "*"
add = "+"
mi = s.index(mult)
res = int(s[mi-1])*int(s[mi+1])
s = s[0:mi-1:]+s[mi+2::]
s = s.replace(add,"")
res = res + int(s)
return res
Works with 1st test case but not the second. Unfortunately this fails with any double digit integer inputs. Is there a simple way of doing this without eval() and just the standard library?
You can write a simple parser:
import operator, re
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
def _eval(tokens):
a, *b = tokens
if not b:
return int(a)
if b[0] in {'*', '/'}:
while b and b[0] in {'*', '/'}:
a = ops[b[0]](int(a), int(b[1]))
b = b[2:]
return a if not b else ops[b[0]](a, _eval(b[1:]))
return ops[b[0]](int(a), _eval(b[1:]))
print(_eval(re.findall('\d+|[\+\*\-/]', "2*3*4+1")))
print(_eval(re.findall('\d+|[\+\*\-/]', "6+3*4")))
print(_eval(re.findall('\d+|[\+\*\-/]', "7*3+10")))
print(_eval(re.findall('\d+|[\+\*\-/]', "1+2*3*4+5")))
Output:
25
18
31
30
Edit: solution without re or operator:
def tokenize(stream):
l, s = [], ''
for i in stream:
if i.isdigit():
s += i
else:
l.append(s)
l.append(i)
s = ''
return l+[s]
ops = {'+':lambda x, y:x+y, '-':lambda x, y:x-y, '*':lambda x, y:x*y, '/':lambda x, y:x/float(y)}
...
Now, to evaluate:
print(_eval(tokenize("6+3*4")))
Is it possible to know if generator was used? i.e.
def code_reader(code):
for c in code:
yield c
code_rdr = code_reader(my_code)
a = code_rdr.next()
foo(code_rdr)
After foo call I would like to know if .next() was called on code_rdr by foo or not.
Of course I could wrap it by some class with a counter for next() calls.
Is there any easy way to do so?
Python 3.2+ has inspect.getgeneratorstate(). So you can simply use inspect.getgeneratorstate(gen) == 'GEN_CREATED':
>>> import inspect
>>> gen = (i for i in range(3))
>>> inspect.getgeneratorstate(gen)
'GEN_CREATED'
>>> next(gen)
0
>>> inspect.getgeneratorstate(gen)
'GEN_SUSPENDED'
I have used idea from attached possible answers, bellow is redefined code_reader function:
def code_reader(code):
length = len(code)
i = 0
while i < length:
val = (yield i)
if val != 'position':
yield code[i]
i += 1
by using .send('position') on I would have know position of next item to be generated, i.e.
a = code_reader("foobar")
print a.next()
print a.send('position')
print a.next()
print a.send('position')
print a.send('position')
print a.next()
print a.send('position')
output:
0
0
f
1
1
o
2
I'm try to append text strings randomly so that instead of just having an output like
>>>david
I will end up having something like
>>>DaViD
>>>dAviD
the code i have right now is this
import random
import string
print "Name Year"
text_file = open("names.txt", "r")
for line in text_file:
print line.strip()+"".join([random.choice(string.digits) for x in range(1, random.randint(1,9))])
and it outports this
>>>JOHN01361
I want that string to be somthing like
>>>jOhN01361
>>>john01361
>>>JOHN01361
>>>JoHn01361
Well, your specification is actually to randomly uppercase characters, and if you were so inclined, you could achieve that with the following list comprehension:
import random
s = "..."
s = "".join( random.choice([k.upper(), k ]) for k in s )
but there may be nicer ways ...
you probably want to do something like:
import random
lol = "lol apples"
def randomupper(c):
if random.random() > 0.5:
return c.upper()
return c.lower()
lol =''.join(map(randomupper, lol))
EDIT:
As pointed out by Shawn Chin in the comments, this can be simplified to:
lol = "".join((c.upper(), c)[random() > 0.5] for c in lol)
Very cool and, but slower than using map.
EDIT 2:
running some timer tests, it seems that
"".join( random.choice([k.upper(), k ]) for k in s )
is over 5 times slower than the map method, can anyone confirm this?
Times are:
no map: 5.922078471303955
map: 4.248832001003303
random.choice: 25.282491881882898
The following might be slightly more efficient than Nook's solution, also it doesn't rely on the text being lower-case to start with:
import random
txt = 'JOHN01361'
''.join(random.choice((x,y)) for x,y in zip(txt.upper(),txt.lower()))
Timing different implementations just for fun:
#!/usr/bin/env python
import random
def f1(s):
return ''.join(random.choice([x.upper(), x]) for x in s)
def f2(s):
return ''.join((x.upper(), x)[random.randint(0, 1)] for x in s)
def f3(s):
def randupper(c):
return random.random() > 0.5 and c.upper() or c
return ''.join(map(randupper, s))
def f4(s):
return ''.join(random.random() > 0.5 and x.upper() or x for x in s)
if __name__ == '__main__':
import timeit
timethis = ['f1', 'f2', 'f3', 'f4']
s = 'habia una vez... truz'
for f in timethis:
print '%s: %s' % (f,
timeit.repeat('%s(s)' % f, 'from __main__ import %s, s' % f,
repeat=5, number=1000))
This are my times:
f1: [0.12144303321838379, 0.13189697265625, 0.13808107376098633, 0.11335396766662598, 0.11961007118225098]
f2: [0.22459602355957031, 0.23735499382019043, 0.19971895217895508, 0.2097780704498291, 0.22068285942077637]
f3: [0.044358015060424805, 0.051508903503417969, 0.045358896255493164, 0.047426939010620117, 0.042778968811035156]
f4: [0.04383397102355957, 0.039394140243530273, 0.039273977279663086, 0.045912027359008789, 0.039510011672973633]
Given the following input file:
a = 2
b = 3
c = a * b
d = c + 4
I want to run the above input file through a python program that produces
the following output:
a = 2
b = 3
c = a * b = 6
d = c + 4 = 10
The input file is a legal python program, but the output is python with
extra output that prints the value of each variable to the right of the
declaration/assignment. Alternatively, the output could look like:
a = 2
b = 3
c = a * b
c = 6
d = c + 4
d = 10
The motivation for this is to implement a simple "engineer's notebook"
that allows chains of calculations without needing print statements
in the source file.
Here's what I have after modifying D.Shawley's (much appreciated) contribution:
#! /usr/bin/env python
from math import *
import sys
locals = dict()
for line in sys.stdin:
line = line.strip()
if line == '':
continue
saved = locals.copy()
stmt = compile(line,'<stdin>','single')
eval(stmt,None,locals)
print line,
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print
Something like the following is a good start. It's not very Pythonic, but it is pretty close. It doesn't distinguish between newly added variables and modified ones.
#! /usr/bin/env python
import sys
locals = dict()
for line in sys.stdin:
saved = locals.copy()
stmt = compile(line, '<stdin>', 'single')
eval(stmt, None, locals)
print line.strip(),
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print