https://github.com/tiger40490/repo1/blob/py1/py/algo_tree/trie_Kyle.py is Usable for some rare coding IV. By Kyle Stewart.
— https://leetcode.com/problems/implement-trie-prefix-tree/ has a slightly more complete requirement.
I think I can modify (not write from scratch) Kyle’s code to add the word search.
Looks similar to the 10-billion phone number problem
python -m py_compile script.py
Working for me in Dec 2018. I think it didn’t work in an earlier experiment
It’s legal to write
return voidFunc() # voidFunc returns ‘None’ by default !
In a value-returning function, you can also omit the last return. It would return None by default
For timed coding tests, python offers this flexibility, similar to void ptr, or boost::Any.
https://github.com/tiger40490/repo1/blob/py1/py/combo_perm/nextPerm%40nSocks.py uses it.
Perhaps it best not to use it, but favor the tuple-return technique
Many details I tend to forget:
- the actual data can be either a tuple or dict. The dict version is powerful but less known
- if there’s just one item in the tuple, you don’t need to parenthesis — myStr = “%d” % var1
- for a tuple, the format specifier count must match the tuple length
- for a dict, each format specifier must name a valid key value.
myStr = "%(var1)d" % locals()) # locals() returns a dict including var1
- There are at least two q(%) in the above expression
- extra parentheses after the 2nd % are required:
“#%03d” % (id(node)%1000) # return last 3 digit of object id, with 0-padding
Background: Suppose in a big python application your main script imports a few packages and modules. One of them is mod2.py, which in turn imports mod2a.py.
Now You need to add invesgative logging/instrumentation to mod2a.py but this file is loaded from a readonly firm-wide repository, common practice in big teams. Here’s my tested technique:
1. clone mod2a.py to your home dir and add the logging. Now we need to import this modified version.
2. clone mod2.py to your home dir and open it to locate the importation of mod2a
3. edit mod2.py to change the importation of mod2a:
import mod2a # via /home/dir
All other imports should be unaffected.
4. edit main.py and update the importation of mod2.py to load it too from /home/dir
As an additional hack, Some people may rename the modified mod2a.py file. This is doable IIF the import line is
from mod2a import someSymbol
Otherwise, every mention of “mod2a” in mod2.py needs a change
print obj1 # by default shows limited content like
<testcases.multitest.result.Result object at 0x7fe7f08fc810>
It’s more useful to see the source code of the obj1’s type definition like “Result” in this case. Here’s how
print testcases.multitest.result.__file__ # assuming …result is a module
I prefer one single full-feature solution that’s enough for all my needs. The os.system() solution is limited. The subprocess module is clearly superior. One of the simplest features is
>>> subprocess.call([“ls”, “-l”])
If you need redirection and background, then try the single-string version
>>> subprocess.call(‘ls /tmp > /tmp/a.log &’, shell=True) # output goes to STDOUT, hard to capture
Note hex() is a built-in, but I find it inconvenient. I need to print in two-digits with leading 0.
Full source is hosted in https://github.com/tiger40490/repo1/blob/py1/tcpEchoServer.py
def Hex(data): # a generator function
for code in map(ord,data):
yield "%02x " % code
i += 1
if i%8==0: yield ' '
print ''.join(Hex("\x0a\x00")); exit(0)
I feel elegant techniques/idioms are usually non-OO, because OO code is too verbose to write quickly.
I feel best-practice cookbooks would showcase the most useful idioms.
# list comprehension and generator expressions. Until you start thinking in terms of these constructs, you aren’t truly a python practitioner.
# list processing functions — map() reduce() filter() zip(). I feel these are very popular in real projects.
Output typically uses “print”.
print >> myFileObject , arguments
print >> sys.stderr , arguments…
Quiz: so, in that case, how do you print to stdout?
Input from file is very common, so that's another quiz
Input from std input —
aLine = sys.stdin.readline()
all_the_Lines = myFileObject.readlines()
Some prefer the object-oriented way to output
The set container is much less used in python than dict and list.
https://github.com/tiger40490/repo1/blob/py1/py/combo_perm/abbrIterative.py — my github python script uses a few essential features of python set
- update() — bulk insert
Python import statement has many trivial or non-trivial scenarios. Here are some common ones:
Common scenario 1: we “import modu2” to execute modu2.py and also exposes all the “public” objects and functions in modu2 as modu2.something
(Simplest scenario but still not known to some programmers.)
Common scenario 2: if pack3 is a directory containing some python modules, we can
“import pack3.modu5” or “from pack3 import modu5”. Easy to understand.
Here’s a relative unusual scenario:
./pip install --verbose --no-deps --index-url=http://ficlonapd05.macbank:9090/api/ pymodels-linux==0.0.1.480 # assuming 0.0.1.480 is the pymodels version to test
>>> import pymodels
>>> pymodels.BlackImplyVol(.2, 3,3, 1, 0, 1,1)
In this case, there’s a pymodels directory but BlackImplVol is a function in the compiled library ./pymodels/pymodels_imp.so. How is this function accessible?
A: when “import pymodels” is run, the ./pymodels/__init__.py script executes, which does “from pymodels_imp import * “
from os import walk
import xml.dom.minidom as md
pretty_print = lambda f: ‘n’.join([line for line in md.parse(open(f)).toprettyxml(indent=’ ‘*2).split(‘n’) if line.strip()])
dirName, baseName = os.path.split(sys.argv)
for (path, dirs, files) in walk(sys.argv) :
for oFileName in files :
print oFileName; #raw_input(“…”)
if not re.search(“vol.*.xml$”,oFileName): continue
fullpath = path+”\”+oFileName;
except Exception as e:
print e; raw_input(“…”)
totalsubs = 0
for line in open (fullpath): #path+”\tmp.txt”) :
# $2 not supported!
# \b same as in perl
newStr, subsMade = re.subn(‘\b(Tenor=”.*?”)s+(Date=”.*?”)’ , “\2 \1”, line)
if (subsMade > 0):
print newStr, # comma to suppress n
totalsubs += subsMade
print str(totalsubs) + ” total substitutions made — ” + fullpath
print json.dumps(myDict, indent = 4)
# to verify
print eval( json.dumps(myDict) ) == myDict
–filter() == grep
–map() == map
–deleting a hash key — del myDict[“key2”]
–function returning multiple values — return (a,b,c)
value1, value2 = multi_valued_function()
–named param — f(id=123,age=38)
–looping over a file content — for aLine in open (“myFile”) :
–lots of command line options.