Second, i’ll will be moving the frequency of Snake_Bytes [] to every other Wednesday. This is to provide higher quality information and also to allow me space and time to write other blogs. i trust dear reader y’all do not mind.
Third, i noticed i was remiss in explaining a function i used in a previous Snake_Byte [ ] that of the Python built-in function called range.
Range is a very useful function for, well, creating iterations on variables and loops.
# lets see how this works:
range(4)
[0,1,2,3]
How easy can that be?
Four items were returned. Now we can create a range or a for loop over that list – very meta huh?
Please note in the above example the list starts off with 0. So what if you want your range function to start with 1 base index instead of 0? You can specify that in the range function:
# Start with 1 for intial index
range (1,4)
[1,2,3]
Note the last number in the index in order to be inclusive for the entire index.
Lets try something a little more advanced with some eye candy:
%matplotlib inline
x_cords = range(-50,50)
y_cords = [x*x for x in x_cords]
plt.plot(x_cords, y_cords)
plt.show()
We passed a computation into the loop to compute over the indices of range x in this case.
In one of the previous Snake_Bytes[] i utilized a for loop and range which is extremely powerful to iterate over sequences:
for i in range (3):
print(i,"Pythons")
0 Pythons
1 Pythons
2 Pythons
For those that really need power when it comes to indexing, sequencing and iteration you can change the list for instance, as we move across it. For example:
L = [1,2,3,4,5,6]
#no add one to each row
# or L[1] = L[i] +1 used all
# the time in matrix operations
for i in range(len(L)):
L[i] += 1
print (L)
[2,3,4,5,6,7]
Note there is a more “slick” way to do this with listcomprehension without changing the original list in place. However, that’s outside the scope if you will of this Snake_Byte[] . Maybe i should do that for the next one?
Well, i hope you have a slight idea of the power of range.
Also, i think this was more “byte-able” and not tl;dr. Let me know!
Second, as we head into the holiday season i was thoughting about an interview question i always ask people:
“What is it you want?”
i usually get either contorted faces or a blank stare. No i didn’t ask you to write a Markov chain algorithm to predict the next meme cryptocurrency or describe the differences between NATS or Kafka distributed processing systems or where do you want to be in five years type of questions.
Let me repeat:
“What is it you want?”
i usually have to prompt folks.
“Ok, like you want a G5 Gulfstream or an island? How about a puppy?”
“You want to be a writer? A painter, a musician, or a teacher?”
Invariably when they answer they want to be doing “something else” as the above profession if money were no object, i always respond, “Then why are you interviewing here? Go do what you just said you wanted to do in the first place.”
Unless you think you want a puppy or a plane. However, there is an unending number of ways to be compensated for your passion. You can have your proverbial cake and eat it as well.
This usually gets people pretty animated.
Then i ask:
‘Which would you rather be? Famous or Rich?”
Blanks stares.
You see most people truly don’t think about what they deeply truly desire and want in life.
So i am going to be taking the rest of the year in my non-copious free time to thought about and reflect on what i truly want and desire.
The reason i am using thoughting is that most if not all have thought about this very issue with no answers.
It’s very interesting at least from what i can tell in western civilization we are not taught to think about what we want when most if not all of what drives us is obtaining something.
Then i have a third question:
“Which is worse a lie or greed?”
None of these questions are as difficult as the first. However the last one i have people who i have hired in the past who have discussed this question with me for decades.
Most people are petrified of success. What do you do when you get everything you want?
Charlie don’t forget what happeneed to the man who suddenly got everything he always wanted… He lived Happily Ever After!
~ Willy Wonka
You have to reassess what you want – yet again.
Maybe you don’t really know what you want? It appears most folks just want predictability and control. Well if you could have that isn’t that living in the past because you already know what is going to happen? Just a thought as it were. Maybe you don’t like surprises. Then again the wonder of life is the unexpected.
Or maybe they want power. Power over what exactly?
So go give it some thought. In the meantime here is a great piece by Alan Watts. He even mentions a Klien Bottle which amazingly someone sent me one which i greatly cherish.
As always would love to see some comments on the posts.
Expose yourself to as much randomness as possible.
~ Ben Casnocha
First i trust everyone is safe.
Second it is WEDNESDAY and that must mean a Snake_Byte or you are working in a startup because every day is WEDNESDAY in a startup!
i almost didn’t get this one done because well life happens but i want to remain true to the goals herewith to the best of my ability.
So in today’s Snake_Byte we are going to cover Random and PseudoRandom Numbers. i really liked this one because it was more in line with scientific computing and numerical optimization.
The random module in Python generates what is called pseudorandom numbers. It is in the vernacular a pseudorandom number generator (PRNG). This generation includes different types of distributions for said numbers.
So what is a pseudorandom number:
“A pseudorandom number generator (PRNG), also known as a deterministic random bit generator, is an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers.” ~ Wikipedia
The important aspect here is: theproperties approximate sequences of random numbers. So this means that it is statistically random even though it was generated by a deterministic response.
While i have used the random module and have even generated various random number algorithms i learned something new in this blog. The pseudorandom number generator in Python uses an algorithm called the Mersenne Twister algorithm. The period of said algorithm is length 2**19937-1 for the 32 bit version and there is also a 64-bit version. The underlying implementation in C is both fast and thread-safe. The Mersenne Twister is one of the most extensively tested random number generators in existence. One issue though is that due to the deterministic nature of the algorithm it is not suitable for cryptographic methods.
Let us delve down into some code into the various random module offerings, shall we?
i like using %system in Jupyter Lab to create an interactive session. First we import random. Lets look at random.random() which returns a uniform distribution and when multiplied by a integer bounds it within that distribution range:
%system
import random
for i in range (5):
x = random.random() * 100
print (x)
Next let us look at random.randrange(start, stop[, step]) which returns a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)) but doesn’t actually build a range object.
Parameter
Description
start
Optional. An integer specifying at which position to start. Default 0
stop
Required. An integer specifying at which position to end.
step
Optional. An integer specifying the incrementation. Default 1
random.ranrange parameters
for i in range (5):
print(random.randrange(10, 100,1))
84
21
94
91
87
Now let us move on to some calls that you would use in signal processing, statistics or machine learning. The first one is gauss(). gauss() returns a gaussian distribution using the following mathematics:
Gaussian distribution (also known as normal distribution) is a bell-shaped curve (aka the bell curve), and it is assumed that during any measurement values will follow a normal distribution with an equal number of measurements above and below the mean value.
Parameter
Description
mu
the mean
sigma
the standard deviation
returns
a random gaussian distribution floating number
gauss() parameters
# import the required libraries
import random
import matplotlib.pyplot as plt
#set the inline magic
%matplotlib inline
# store the random numbers in a list
nums = []
mu = 100
sigma = 50
for i in range(100000):
temp = random.gauss(mu, sigma)
nums.append(temp)
# plot the distribution
plt.hist(nums, bins = 500, ec="red")
plt.show()
There are several more parameters in the random module, setter functions, seed functions and very complex statistical functions. Hit stack overflow and give it a try! Also it doesn’t hurt if you dust off that probability and statistics textbook!
As a last thought which came first the framework of entropy or the framework of randomness? As well as is everything truly random? i would love to hear your thought in the comments!
M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”, ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998
Muzak To Muzak To Blog By: Black Sabbath – The End: Live In Birmingham
There is geometry in the humming of the strings, there is music in the spacing of the spheres.
Pythagoras
First, i trust everyone is safe.
Second, this is the SB[3]. We are going to be covering some basics in Python of what constitutes a string, modifying a string, and explaining several string manipulation methods.
I also realized in the last Snake_Byte that i didn’t reference the book that i randomly open and choose the subject for the Snake_Byte. I will be adding that as a reference at the end of the blog.
Strings can be used to represent just about anything.
They can be binary values of bytes, internet addresses, names, and Unicode for international localization.
They are part of a larger class of objects called sequences. In fact, python strings are immutable sequences. Immutability means you cannot change the sequence or the sequence does not change over time.
The most simplistic string is an empty string:
a = “ “ # with either singe or double quotes
There are numerous expression operations, modules, and methods for string manipulations.
Python also supports much more advanced operations for those familiar with regular expressions (regex) it supports them via re. Even more advanced operations are available such as XML parsing and the like.
Python is really into strings.
So let us get literal, shall we?
For String Literals there are countless ways to create and manipulate strings in your code:
Single Quotes:
a = `i w”ish you water’
Double Quotes;
A = “i w’ish you water”
Even triple quotes (made me think of the “tres commas” episode from Silicon Valley)
A = ```... i wish you water ```
Single and double quotes are by far the most used. I prefer double quotes probably due to the other languages i learned before Python.
Python also supports the liberal use of backslashes aka escape sequences. I’m sure everyone is familiar with said character `\`.
Escape sequences let us embed bytecodes into strings that are otherwise difficult to type.
So let’s see here:
s = 't\nc\nt\njr'
print (s)
t
c
t
jr
So here i used ‘\n’ to represent the byte containing the binary value for newline character which is ASCII code 10. There are several accessible representations:
‘\a\’ # bell
‘\b\’ #backspace
‘\f’ # formfeed for all the dot matrix printers we use
‘\r’ #carriage return
You can even do different Unicode hex values:
‘\Uhhhhhhhh’ #32 bit hex count the number of h’s
With respect to binary file representations of note in Python 3.0 binary file content is represented by an actual byte string with operations similar to normal strings.
One big difference between Python and another language like C is that that the zero (null) byte doesn’t terminate and in fact, there are no character string terminations in Python. Also, the strings length and text reside in memory.
s = 'a\0b\0c'
print (s)
len (s)
abc
5
So what can we do with strings in Python?
Well, we can concatenate:
a = "i wish"
print(len (a))
b = " you water"
print (len(b))
c = a + b
print (len(c))
print (c)
6
10
16
i wish you water
So adding two strings creates a new string object and a new address in memory. It is also a form of operator overloading in place. The ‘ + ‘ sign does the job for strings and can add numerics. You also don’t have to “pre-declare” and allocate memory which is one of the advantages of Python. In Python, computational processes are described directly by the programmer. A declarative language abstracts away procedural details however Python isn’t purely declarative which is outside the scope of the blog.
So what else? Well, there is indexing and slicing:
Strings are ordered collections of characters ergo we can access the characters by the positions within the ordering.
You access the component by providing a numerical offset via square brackets this is indexing.
S = "i wish you water"
print (S[0], S[4], S[-1])
i s r
Since we can index we can slice:
S = "i wish you water"
print (S[1:3], S[2:10], S[9:10])
w wish you u
Slicing is a particular form of indexing more akin to parsing where you analyze the structure.
Python once again creates a new object containing the contiguous section identified by the offset pair. It is important to note the left offset is taken to be the inclusive lower bound and the right is the non-inclusive upper bound. The inclusivedefinition is important here: Including the endpoints of an interval. For example, “the interval from 1 to 2, inclusive” means the closed interval written [1, 2]. This means Python fetches all items from the lower bound up to but not including the upper bound.
What about changing a string?
Let’s try it:
S = "i wish you water"
S[0] = "x"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last) <ipython-input-67-a6fd56571822>
in <module> 1 S = "i wish you water" ----> 2 S[0] = "x"
TypeError: 'str' object does not support item assignment
Ok, what just happened? Well, remember the word immutable? You cannot change it in place.
To change a string you need to create a new one through various methods. In the current case we will use a combination of concatenation, indexing, and slicing to bring it all together:
S = "i wish you water"
S = 'x ' + S[2] + S[3:17]
print (S)
x wish you water
This brings us to methods.
Stings in Python provide a set of methods that implements much more complex text processing. Just like in other languages a method or function takes parameters and returns a value. A “method” is a specific type of function: it must be part of a “class”, so has access to the class’ member variables. A function is usually discrete and all variables must be passed into the function.
Given the previous example there is a replace method:
S = "i wish you water"
S = S.replace ('i wish you water', 'x wish you water')
print (S)
x wish you water
Let’s try some other methods;
# captialize the first letter in a string:
S = "i wish you water"
S.capitalize()
'I wish you water'
# capitalize all the letters in a string:
S = "i wish you water"
S.upper()
'I WISH YOU WATER'
# check if the string is a digit:
S = "i wish you water"
S.isdigit()
False
# check it again:
S = "999"
S.isdigit()
TRUE
# strip trailing spaces in a string:
S = "i wish you water "
x = S.rstrip()
print("of all fruits", x, "is my favorite")
of all fruits i wish you water is my favorite
The list is seemingly endless.
One more caveat emptor you should use stings methods, not the original string module that was deprecated in Python 3.0
We could in fact write multiple chapters on strings by themselves. However, this is supposed to be a little nibble of what the Snake language can offer. We have added the reference that we used to make this blog at the end. I believe it is one of the best books out there for learning Python.