Search

Sweat Based Health Tracker That Is Better Than Anything Known

When Fitbit first came into the market I was wowed. I told myself that was cool. I could track all sorts of things about my health and performance. Along with Fitbit came a host of other gadgets that can help you understand your health status. But they all lacked one quality – they could not replace diagnostic tests required by medical doctors.

Woman with a health tracker on wrist
 

Now, there is a product that can. It is a sweat-based flexible electronic sensing thread that can be sewn into clothing to analyze all sorts of biomarkers and give accurate diagnosis. The threads come equipped with special sensors for collecting sweat while you are walking, running, working, or even watching TV. It then has electronic components that are wirelessly connected to a smartphone for real-time data acquisition and processing. These patches are just great.

They were developed by engineers at Tufts University who saw a need in the market. Present biomarkers could only track heart rate, temperature, glucose levels, walking distance and take only gross measurements. They could not do the real work of replacing laboratory diagnosis required often by doctors when analyzing your health status. So, the engineers decided to concentrate on something that could replace blood diagnosis. They decided on sweat.

Sweat is holistic. If you can detect and track sweat you could detect and track electrolytes in the sweat, like sodium, chloride, and ammonium ions, along with other biomarkers that could be detected for a more accurate analysis while doing it at your comfort. These patches are more accurate than present trackers. They are more indicative of the human health status and could be used for athletic performance measurement, workplace safety, clinical diagnosis, and even managing chronic health conditions.

For example, take the ability to detect sodium in sweat. With these threads on clothing, one could detect when he or she is hydrated or if there was electrolytic imbalance in the body in a matter of seconds. Lactate sensitivity is built into the threads and it can be used to indicate muscle fatigue for athletes or those who do strenuous activities. Cortisol, which is a stress hormone, could be detected in sweat and it can be used to assess emotional stress as well as metabolic and immune functions. The whole range of uses of these threads when sewn into clothing are immense. Their benefits are beyond recount. Even athletes could use the patches sewn into their clothing to monitor their physical exertion and aid them in predicting performance peaks or decline during competition.

The engineers came up with a unique ability to integrate these patches into clothing using flexible threads that were coated with conductor links and these threads are different for detecting different biomarkers that are present in sweat. The threads are then connected to a miniature circuit module linked to microprocessors with wireless capability for real-time communication with a smartphone.

When the engineers were asked why they chose sweat they said it is not only convenient to collect when clothing is on, it is easily accessible, can be collected non-invasively, and it correlates with the samples that could be derived from blood. I think I would love to invest in the company that would make this product commercially viable. It would replace many diagnostic techniques that we have today because sweat is a good surrogate for diagnostic fluid such as blood samples.

During tests it was discovered that the markers were accurate to about 5 to 30 seconds, enough for the real time needs of the average health conscious individual.

This is surely an innovative twist to helping those who are health conscious and individuals with chronic health problems; not to mention athletes who need to monitor all sorts of biological markers for performance enhancement. The engineers solved a problem.

You can read the full report at the Tufts website.

Coding Python ATM Machine That Gives Only $5 And $8

 

I recently went to the bank to withdraw some money. The attendant at the ATM told me the ATM can only give out money in 1,000 naira and 500 naira notes. When he told me, I started wondering if I could be able to code a machine that gives out money based on a specified denomination. So, I told myself, what if the machine can only give out $5 and $8 change. How can I code that?

 I nearly got knocked over on my way home thinking about the problem. But since problems are to be solved, I came up with a nice solution in my head that I want to describe.

How not to go about it.

Initially, I starting thinking of using the modulo 5 or modulo 8. That was nice and easy. But I came to a caveat, if I used modulo 8, I could only get change for amounts that were definitely multiples of 8 and not of 5. If I used modulo 5, I could only get amounts that were definitely modulo 5 and not 8. That would not work out. I started thinking of the nature of the problem before going down to the solution.

The nature of the problem.

What if the machine gives out change only in $5 and then has an internal memory that keeps track of how much change it could be able to give in $8 from what remains based on the amount already given out in $5? For example. It could not give out change for $12 because after taking out $5 what remains is $7. But it could give out change for $13, or $15.

Another aspect of the problem is that if your amount is below $5, it cannot give you any change because it only has $5 and $8. So, you have to forfeit it. Too bad!

Then, I had to start giving out change based on the smaller amount which is $5. First of all, I first check if the amount is a multiple of $5. If it is, that is easy, just give out change based on the number of $5 that is required by doing integer division. But if the amount is not a multiple of $5, then we need to do a little arithmetic here.

Let’s say we can give out $21 in change. What combinations of $5 and $8 do we use? Since we are starting out with $5 as the smaller amount. We first check if $21 is a multiple of $5. No, it’s not, so the change will include $8. Let’s give 0 $5. Is the remainder a multiple of $8? No because the remainder is $21 and it is not a multiple of $8. Then let’s give out the first $5. The remainder becomes $16. Is the remainder a multiple of $8? Yes, because 2 $8s give $16. So, we have our change.

Let’s take another example. Suppose we have $28. Is $28 a multiple of $5? No. So the change will include $8. Let’s give out 0 $5. Is the remainder, the original $28 a multiple of $8? No, it is not. So we know our change will include both $5 and $8. So, let’s give out 1 $5. After giving out a single $5, we remains is $23 which is not divisible by $8. So we give out the second $5, that is, $10. The remainder is now $18 which is not divisible by $8. So we give out the next $5 which makes it 3 of $5 or $15. The remainder is $13 which is not divisible by $8. But we have not exhausted the number of $5 we can give out, so we will keep giving out $5 until we exhaust our supply. So now we give out our 4th $5, which is $20. The remainder is now $8 and it is divisible by $8. So, we have our answer. If we have $28 the change we can give using just $5 and $8 is 4 $5 and 1 $8.

Now, let’s take an example of an amount we cannot give change for you to see how the code works. Let’s take $27. First we ask if it is divisible by $5? Not it cannot, so we will also give $8. So, giving just no $5, is $26 divisible by $8? No, it is not, so if we can give out change, then it will include both $5 and $8. But can we? I said we cannot. Let’s prove it. So, we’ll calculate the number of $5 iterations we can go through in the code. That is, the maximum number of $5 we can give since we are starting with $5 and that is 5 five dollars. So, we will keep giving out $5 and comparing the remainder with $8 until we exhaust our supply of $5. $27 divided by $5 without remainder is 5. So, we will give out $5 five times. Let’s give out the first $5. The remainder is $22 and it is not divisible by $8. So we give out the second $5 to make it $10. The remainder is $17 which is not divisible by $8. So we give out the third $5 making it $15 and the remainder, $12, is not divisible by $8. So we give out our fourth $5 to make it $20. The remainder after that is $7 which is not divisible by $8. We could stop here and say that since the remainder is lesser than $7 there is not way. But the code will check one more time for the fifth $5 and that is $25 to give a remainder of $1 which is not divisible by $8 without remainder. So, we cannot give out accurate change using just $5 and $8 when the amount is $27.

Here is the code snippet which you can run from here:

There is a handy function I have included, print_change. It takes the number of $5 and $8 along with the amount we can give change in and prints out the result on the screen. It makes the printing look elegant and beautiful.

And in case you did not notice, you could see from the printed result that our $5 and $8 ATM machine can give change for any amount above $27. It can give you change for all amounts from $28 to infinity. Just lovely machine that doesn’t like the poor.

You can download the script from this link if you desire and run it on your machine.

Email Validity Check Using A Python Filter

I encountered a problem recently of how to check for email validity. When doing web scraping or handling data sets, you get to play with emails a lot and having a handy function that does this check in an efficient way would be useful. So, I decided to come up with a function that does it.

 

In this article, I will be using a filter and a list of emails to do the check. I decided on using a list of emails because it would better help you understand what I am doing. Most times, if you are scraping data, you might have to implement a file handler for it. But not to worry, converting from one to the other is easy.

What are valid emails?

Valid emails have the form: username@websitename.extension. Each of the elements have their different rules. For example, username can usually contain letters, digits, dashes or underscores. Website name can only have letters and digits while the extension is usually at least 2 and maximum 3 letters in length. So, having that we will use regular expressions, or regex, to match for valid emails. Remember earlier posts, finding a match with regular expressions and also understanding python search and match regex methods where I told you that when you have to search strings think regex first? This is a handy application.

So, this is the regex we will be using. I have modularized it in a handy function called fun.


def fun(s):
    # return True if s is a valid email, else return False
    pattern = r'^[\w-]+@[a-zA-Z0-9]+\.[a-z]{2,3}$'   
    m = re.match(pattern,s)
    if m:
        return True
    else:
        return False 

Now let me explain the regex above in case you have not read the earlier posts on regex. Just look at the value for the variable, pattern. I will be explaining each of the strings in the pattern. "^[\w-]+" is the pattern to match the username. It says start from the beginning of the string. That is why we are using match in the next line. Match one or more letters, digits, or underscores (as \w), or match one or more dashes (as -). That’s for the username validation. The next string is "@". Just match @ after the earlier username match. Now comes the website name matching string. "[a-zA-Z0-9]" states that after the @ symbol, we should look for a website name as one or more letters or digits. That’s that. Next comes "\.". What I want to match here is the single period, ., after the website name, but I have to backslash it. Without a backslash the "." symbol says match any character but with a backslash it means to match the period, ., character. Then, lastly is the end of the pattern, the extension match. I denoted this with "[a-z]{2,3}$" and what this means is that match at least 2 or at most 3 lowercase letters which are at the end of the string. Note that this must be at the end of the string. Sometimes we could get an extension like .server and that would not be a match unless it is a .com, .co, .io, .net etc.

So, that’s for validating the email. Now how does a filter come in handy to do this.

What the filter function does.

The syntax of the filter function is filter(function, iterable). What it does is to take a sequence and filters it with the help of the given function. Each item in the sequence is filtered against the function and then a list is returned of the filtered sequence. So, what we are doing here is taking each email and filtering it against the fun function using the regex pattern match. The filter code is just a one liner – just filter it using the given function.


def filter_mail(emails):
    ''' input a sequence of email string 
    returns the elements in the sequence that returns True
    when filtered for email validity.'''
    return list(filter(fun, emails))  

In the complete code, I also included a print_email function. What the print_email function does is take an email, call the filter function which returns a list of the filtered emails, sort the list and then print the list. I wanted to make the print_email function a helper function to the filter_email function but decided it might not be readable that way, so had to leave it as is.


def print_email(emails):
    filtered_emails = filter_mail(emails)
    filtered_emails.sort()
    print(filtered_emails)

So, that is it – validating emails using a filter function with regular expressions. I have included two lists, a list containing invalid email and one containing valid emails for you to run and see how it was done.

You can download the script if you want to run it on your machine.

If you have any questions, you can leave it in the comments. Also, be sure to subscribe to my blog so you can receive new articles as they are posted.

Internet Security: Is There Such A Thing As An Unbreakable Code?

For centuries, people have been searching for ways to keep information from getting into the hands of the public. Cryptography gave them an answer to that. Cryptography has been used, both in its basic and sophisticated forms to hide sensitive information. Egyptian hieroglyphics contain the first known and verified example of ancient cryptography. In our age where internet is so rampant and people want to keep their personal information private, cryptography is gaining traction. But one cycle exists for all cryptography. First, someone finds a good code and starts using it, it becomes effective for some time and eventually someone somewhere breaks the code, rendering it ineffective. Because of this, people ask: Is there such a thing as an unbreakable code?

 

Can all encryption be broken

To help them answer this question and solve it, scientists came up with the concept of one-way functions. One-way functions are functions that are easy to compute on the given inputs but hard to invert. That is, you cannot get the inputs from the output when reversing it. One-way functions could make good candidates for code that cannot be easily broken. That is, it would be close to impossible to find an algorithm that would revert the output. Unfortunately, one-way functions are just a conjecture. But that conjecture has been behind much tools that have been built in cryptography, authentication, personal identification, and other data security applications.

Getting a one-way function that is feasible has huge ramifications in the internet age. It could solve the Internet security problem for good. Industries such as banking, telecommunications, and e-commerce would be in a hurry to apply it. Yes, it has been elusive but that is not to say that there have not been candidates.

One well known candidate for one-way functions involves the multiplication and factoring of prime numbers. To get the outputs, two prime numbers are given to a function and their product is computed. This function takes a quadratic time complexity. It is really hard to factor out the prime numbers given the output although it can be done in exponential time. Another candidate is the Rabin function which gave rise to the Rabin cryptosystem on the assumption that the Rabin function is one-way.

The two candidates above can be broken though if a really good mathematician knows how to write an efficient algorithm.

This problem was what Rafael Pass, Professor of computer science at Cornell Tech wanted to tackle. He believes that if he could find a really good and valid one-way function, then all internet security problem could be solved. Internet encryption would be safe for all. According to his postulate, a good one-way function is like lighting a match. After a match is lit, you cannot get back the sticks. They are now ashes. So, a good one-way function would be an encryption scheme in which the decryption would lie only in the hands of the person who encrypted it. To get a candidate, he looked to mathematics and to a field that is unrelated to cryptography – quantifying the amount of randomness in a string of numbers, or what is known as the Kolmogorov complexity.

The Kolmogorov complexity of an object is defined as the length of the shortest computer program that can generate that object as an output. The Kolmogorov complexity of a string that has a definite pattern to it, like ababababababab, which is writing ab 7 times, can easily be computed. But what if you have some random string? asdwer2345tgdhncjmckkjkd? How do you compute the Kolmogorov complexity in an efficient manner? It has been found that the Kolmogorov complexity for such random strings is computationally close to impossible. What makes it more infeasible is computing the time bounds of such an algorithm.

Taking from this idea, Professor Pass focused his research on whether an algorithm can solve the time-bounded Kolmogorov complexity. If such an algorithm exists, his research posits, then all cryptography can be broken. On the other hand, if no efficient algorithm exists for such a time-bound Kolmogorov complexity, then one-way functions do exist and they can be found.

His research has implications for encryption schemes that are widely used in the Internet. Popular social media platforms use encryption to make their platforms more secure, banks in e-banking platforms rely on encryption being more unbreakable, and overall, we depend on making sure our internet lives are kept free from the prying public. So, Professor Pass’ theory is of great interest and only time will tell when a really good algorithm can be found based on his research that would make sure our Internet security is compromised no matter what platform we are using.

Source for this article was from Cornell University.

The Big Advantage Of Understanding Python Regex methods

Regular expressions, or regex, in python is fun. It is a very fast way to search through a string for a given pattern. Whenever I have to search and I am dealing with a string, the first thing I do is to look for a solution in regex. If you know regular expressions, so many string operations will be easy. 

My earlier post, How To Find A Match When You Are Dating Floats, explains the basic syntax and use of regex. In this post, I will highlight two functions in using regex that could confuse anyone unless they understand how they work. I will also add a third method that serves as an extension to the two. 

So, what are the two methods? They involve searching for a pattern in a string and the two methods are re.search() and re.match(). They both do the same thing: search for a pattern in a string. 

How python re.match() works.

The syntax of python re.match() is re.match(pattern, string, flags=0). What it does is take a pattern, as the first argument and a string as the second argument and search for the pattern in the string. You could add in other flags if you want to like make it search multiline or ignore string case. 

Now, the subtlety of re.match() is that it returns a match object only if the pattern is at the beginning of the string. Else, if it is not at the beginning of the string, it returns None. This is very important to remember because many unsuspecting pythonistas have found themselves thinking their pattern was wrong when their match returned None. 

Let me illustrate this with a little code. 

 

From the code above, I changed the patterns. The first pattern started from the beginning of the string, line 4, and it returned a match object when I printed the object. But the second pattern, line 10, did not start from the beginning of the string. When you ran the code, you would have noticed that it printed None for this case. 

So, always remember, re.match() searches for the pattern at the beginning of the string. 

How python re.search() works

Now, the second method for searching for patterns is re.search(). The syntax is similar to re.match() but different from re.match() because it searches for the pattern anywhere in the string. Even if the string is multiline, it would still return a match if the pattern exists in the string. But it does not return a match for all locations where the pattern can be found in the string. Rather, it returns only the first match for the pattern. 

 

If you run the code above, you can see that it both gets a match at the beginning of the string and in the middle of the string. It gets a match anywhere in the string but returns a match object that corresponds only to the first match. 

So, remember the difference between these two useful methods and don’t make the mistake of fighting your terminal trying to understand why a pattern you thought was well formed turned out not to be giving you a match object. 

The bonus python regex method. 

This is a bonus method because it is the one I use most often. It is quite different from the earlier two. Remember the earlier two only return a single match object or None where there is no match. The bonus method is python re.findall(). This method, re.findall(), will scan the string from left to right for matches and will return all the matched patterns as a list of strings. Not a match object, but a list of strings. That comes quite useful several times you might say. I just love this method. Here is some little code to illustrate this. 

 

Notice that I am using the same code but just changing the methods. 

So you can see how powerful re.findall() is. It gives you the ability to see all the matches in a list, something that re.match() and re.search() do not make possible. 

I limited this post to just the rudimentary functionalities of all three methods. You can experiment with them now that you know how they work. Make out your own code with various concepts. 

And don’t forget to subscribe to my blog so that you can get updated articles as I publish them daily. The submit textbox is at the topright.

A Look Into The Future Of Wireless Brain-Computer Interfaces.

 

Brain-computer interfaces (BCI) or what some call the mind-machine interface is a system of connecting a human brain through wires or wirelessly to a machine in order to generate signals from the brain, transmit them to a computer and through a bidirectional information flow mechanism allow the computer to control motor functions of the human brain.

The idea of a mind-machine interface was popular in the 1970s but it was not until the 1990s that prosthetic devices that were attached to the brain appeared to be viable. One of the concepts behind these mind-machine devices is to capture the electrical activity of the brain through electroencelography (EEG), transmit them to a machine and then the machine generates signals that are able to control the functioning of the brain. Professor Jacques Vidal of the University of California, Los Angeles (UCLA) is credited with inventing the first BCI machine. This concept has been applied in neuroprosthetics which is the use of artificial devices to replace the function of impaired nervous functions and brain related problems.

Thanks to this inventive and innovative approach, many persons who have lost their vision, motor movements, and other body functions such as in paralysis, can be able to live normal lives using these machines. A breakthrough in BCI devices and neuroprosthetics was accomplished in 2009 when Alex Blainey, an independent researcher living in the UK, was able to control a 5 axis robot arm using the Emotiv EPOC. These devices could help even someone who has lost control of their spinal cord through a disease or injury to regain full movement .



One drawback though was that not only do they require wires but they can generate energy in the brain of recipients. A wired BCI device can limit the movement of the person on whose brain it is implanted. They would not be free to move at ease. While a BCI device generating enormous energy could do harm to the person on whom it is implanted.

Now, these challenges could be a thing of the past as research has suggested that neural implants in the brain could be done wirelessly while generating just one-tenth of the power of existing devices.

A team of electrical engineers and neuroscientists from Stanford University successfully created a breakthrough device that could give recipients a wider range of movement while not exposing them to harm through the heat generated by the implanted device. To test their data, they tried out their experiment on three nonhuman primates and one human participant in a clinical trial. Then while the subjects performed several movements by communicating with the computer using their brains, the researchers took extensive measurements. The results of the research validated the hypothesis from the researchers that a wireless device for neuroprosthesis was possible and commercially viable while using less power.

Only time would tell when the actual device would be built that would actually achieve the goal of the research: a mind-machine device that was safe yet wireless. The future of wireless brain-computer interfaces is just within reach.

How To Do Python Keyword Arguments Like An Expert

It is a little daunting for people who are new to python or transitioning to python from other languages to understand how keyword arguments work when compared to positional arguments. I will succinctly explain each of them here and show you how to use keyword arguments like a pro in no time.

Programmer at his terminal
Arguments in python are parameters that are passed to functions. When a function is called, a scope is created for the function with the arguments bound to the parameters within that scope. The argument could be a variable, value or object that is passed to the function (or method) as input.

There are two types of arguments that could be passed to python functions. They are positional arguments and keyword arguments.

Positional arguments are arguments that need to be included by the caller in their proper position or order in the function definition. Let’s take the complex() built-in function as an example. The syntax is complex([real[, imag]]) where the first argument is the real number and the second is the imaginary number. In complex numbers, the position is very important. A complex number with real 2 and imaginary number 3 is written as 2 + 3j. If the order is mistaken, then you have a different complex number. You need to note this when using the complex function. For example take this code sample below:

 

You can see from running the code that I interchanged the 2 and 3 just to show you how positional arguments work. When you change the position of the arguments, you get a different result. You must give the function the same number of arguments as is defined in the positional arguments, else it will return an error.

But there are times when you want to pass a sequence of arguments, such as an iterable to the function, then you can use the * operator to do this. Notice that I used this * operator in line 6 in the code below. This unpacks the iterable and passes each of the items in the iterable to the function in order.

 

What are keyword arguments?

Keyword arguments, as the name denotes, are arguments that are passed with a key=value syntax. That is a key first, an = sign, and then a value. Unlike positional arguments, the position of parameters or the order does not matter. You can state the arguments in any order you like. What matters are the names of the keys. In fact, when you pass a keyword argument, python creates a dictionary of key=value pairs for the arguments and inserts it into the function appropriately.

Let’s take an example using our complex function again.

 

You can see from line 1 and 3 that I interchanged the positions of the arguments while specifying their key=value pairs and it gave me the same object.

Keyword arguments can seem odd as we go on to take more complex examples, but I want you to know that as you practice with it, it would become more natural and you would love using them. They have advantages.

In python documentation, the phrase "keyword argument" is often shortened to kwargs. So when you see such shorthand know that it signifies keyword arguments.

What are the advantages of using keyword arguments.

  1. With keyword arguments, we can leave off some of the arguments and the default is used for those that are left off.
  2. Notice that in line 4 first_name was not given to the function and I asked it to use the default. In line 5, I did not pass any argument at all, instead it just used the default.

  3. If we want to achieve readability in passing arguments, we can rearrange the arguments to make them readable.
  4. The ability to rearrange the arguments at your willing makes you creative and provides code you can understand in the future.

  5. Objects that are being passed to the function are clear to use when we are passing them.
  6. Since we are using their names to pass them, we understand what we are doing in case we need to debug or read the code in the future. Consider these two lines for passing arguments to the complex function, which do you think is more readable?

     

    Line 1 and line 3 creates the same object, but you must agree with me that line 3 is more readable because looking at the keys you can easily know what object you are passing to the function.

Now that we have a basic idea of keyword arguments and how they are used in python, let us illustrate some more features of keyword arguments with more examples.

Keyword arguments and examples

One example of a built-in function that requires a keyword argument in python is the sorted function. After the first iterable, every other argument that is passed to the function must be a keyword argument. In the code below, I tried reversing the sort order without passing a keyword argument of reverse=True and it returned a TypeError.

 

There is a handy technique that comes in handy when you want to require that all your keyword arguments be named while having the ability to pass on arbitrary positional arguments. That is mixing positional and keyword arguments at the same time. When the positional arguments are more than one, you can use the *parameter statement (where parameter is a variable, value or object) to specify this. Remember, as I said before, when stating a keyword argument with a positional argument, the moment you insert a keyword argument in the parameter list, any other argument that comes next must be a keyword argument.

Let’s take this summing function as an illustrative example. It sums all the numbers passed starting from 1 as default. Notice that I did not pass the parameter, initial, as argument, because I wanted to use it as default. You can experiment with it. What if you want to make the initial starting point 2 or 3? What sum would it return?

 

Also, to take our knowledge one step further, what if you don’t want to specify any positional arguments but you want an arbitrary number of keyword arguments. You use the statement **kwargs. You must have seen this often in the python documentation. What python does when it sees this in the function definition is to create a dictionary with the key=value of the passed in parameters. Let’s illustrate this with an example.

 

When using the **kwargs statement, order matters to the python interpreter. It will evaluate all the keys according to the order that they were passed.

I encourage you to use keyword arguments often. They give beauty to your programs. If you are not familiar with them, when writing any function ask yourself: can I use keyword arguments for this and make it more readable? It would solve you a whole lot of headache in the future.

The Next Big Thing About the Cerebellum Might Open Frontiers In Understanding The Brain

The cerebellum, which in Latin means “the little brain,” is at the hindbrain in all vertebrates. North of the cerebellum is the cerebral cortex which forms its outer layer. Formerly, due to its folding nature, the cerebellum was thought to be smaller than the cerebral cortex and so not much involved in as much activities in human behavior and cognition as the cortex. But recent research has disproved that point.


The cerebellum as earlier said was thought to be smaller because it is arranged in hundreds of folds which make it look small in surface area but researchers using ultra-high-field MRI imaging together with specialized software have found that the surface of the cerebellum is much larger than was believed. It was even found to be even bigger than the cerebral cortex. It is now said to be approximately more than 80 percent of the cerebral cortex.  

This research would now open the way for more research into the benefits of the cerebellum for human behavior and cognition. This is because since the cerebellum is bigger than the cortex, it shows that human evolution is more advanced than other vertebrates, even those closer to man like the macaque monkeys. Therefore, it will help us to understand how over the years man has adapted better than other vertebrates to the environment and has used the advantage afforded it by a bigger cerebellum to develop advanced levels of cognitive abilities.

The researchers also found that while the cerebral cortex was well arranged and the body parts they were controlling well defined, that is not the case for the cerebellum. The cerebellum receives information from disparate parts of the body in a random manner. That means, areas for coordinating the shoulder could lie side by side with areas coordinating the foot. This gives humans the advantage over other animals of coordinating different body parts all at the same time from one central location, enhancing efficiency.

Also, the researchers found that the cerebellum must have a higher role in controlling emotional responses more than was earlier thought. It is established that the cerebellum is involved in movement-related functions, but this study also delved into the study of damaged cerebellums and found that people with such challenges had problems understanding their emotions. But further research has to be done in this area.

In the coming years, with the results from the MRI study, researchers will be able to better understand how the brain works and not confine their knowledge to thinking the control of body functions is limited to specific areas of the brain. Mapping the cerebellum will be an interesting new frontier for scientific advancement and further understanding of the human body.

Expectations And Realities Of Python Lists And Dictionaries

Have you ever got stumped when you tried assessing an item in a list or dictionary because you received a result which you never expected? Some would say they found a bug. Truly, that bug rests in the fact that you did not understand the subtleties between types when using a list or dictionary.

programming can sometimes be confusing

Take this little program that shows the subtleties in accessing items in a dictionary.

The dictionary has three items, with the keys being ints and the values as strings. That is the first difference you should notice. This is just illustrative because keys of dictionaries can also be any immutable type. On line 3, I asked the interpreter to tell me if 10, int type, was a key, and if ‘10’, string type, was a key. It says True for the former and False for the latter. This is a problem I encounter while teaching on a daily basis. Many persons tend to confuse the int for the string and vice versa. They are different values.

Then comes accessing the items in the dictionary. On line four, I inserted 10 as the key to the dictionary. Note this: as key and not the index. Python reported the string, ten, as I expected. But notice what happens on the line 5 when I used the string ‘10’ as the index. Python gave a KeyError.

So, this shows that types really matters when you are accessing dictionaries. The same goes for lists.

How to find items in a list and dictionary.

Imagine we have a list of names.

When you run it, you should notice that the int 1 is not in the list. I could have used some other value, maybe ‘one’ or maybe ‘Rose’ but the "in" operator shows us whatever is in the list. One problem I have encountered with most of my students is that they don’t understand the subtleties of the in operator. What I always tell them is to consider it as going through each item in the list and looking for a match. If it returns a match, it returns True, and if not it returns False.

Now, what if we mistake an int for a string or vice versa in the list. Let’s take another list. This time of years.

If you run it, what it prints out is:


2019 in list.
2019 is not in list.

What is going on? It’s just simple. The items in the list are strings but on line 10 we gave it an int. So, when programming you have to be very careful not to be carried away and confuse an int for a string and vice versa.

What about indexing and keys.

What we expect is that when we give the interpreter something like variable_name[index] when it is an iterable, we should expect to get an item in return. But what item we get depends on the data structure we are using. If variable_name is a list, we will get an item in the list with that index. But if variable_name is a dictionary, what we get is a value of the key, index.

That gets many people confused sometimes. Well, it is all about knowing that lists and dictionaries are arranged differently. A list contains references to items of value and each item is indexed from zero. For example, let’s take our list of names again.


names = ['david', 'michael', 'daniel']

The list has three items which are referenced through an index. 'david' is at index 0, 'michael' is at index 1, and 'daniel' is at index 2. So, we can access the items through the indices. For example this command, names[0] will return david, while names[2] will return daniel.

But this is different with dictionaries. Let’s take a dictionary of ints as keys and strings as values for example.


num_dict = {10 : 'ten', 20 : 'twenty', 30 : 'thirty'}

If we run the statement num_dict[0] we will get a KeyError. You know why? Because dictionaries accesses its values based on the keys and 0 is not a key in the num_dict dictionary. So, don’t confuse this with that of lists. To access the second item in the dictionary which is ‘twenty’, we need to get it through its key, and the key is an int, 20. So we run the statement thus: num_dict[20] which returns ‘twenty’.

Note that keys of dictionaries can only be immutable types, including sets, while values for dictionaries can be of any type.

I hope you enjoyed this article. If you like receiving more solved problems like this from this blog, just subscribe and it will be sent to your inbox the moment I publish a new article.

How to find a match when you are dating floats in python

Have you ever wondered how to do things the easy way when dealing with strings? Maybe you want to match some strings and you get stomped.

For example, take this hackerrank.com challenge. The challenge says that given a string, find out if it is a float where floats have the following requirements:

1.Number can start with +, -, or . symbol. 
2.Number must contain at least one decimal symbol
3.Number must have exactly one . symbol
4.Number must not give any exceptions when converted using the float(N) expression where N is the string. 

Now, those are some requirements. We could code this literally in python but it would be unbeautiful and illogical. That is where the beauty of regular expressions come to play.

What are regular expressions?

A regular expression, sometimes denoted as regex, is a sequence of strings that defines a search pattern. For example, if you want to search for the word ‘bat’ in battered, you could use ‘bat’ as a regular expression. Therefore, for the challenge above, we would be using regular expressions to solve it simply and beautifully.

Introduction to python regex.

You can get the full details of the use of python regex at the python regex documentation page here.

But I will just briefly cover the main points.

In python, regular expressions can be composed of metacharacters and also the ability to do repetitions on characters.

First the metacharacters.

The basic metacharacters are:

  1. [ ] which is the set metacharacter. Anything within the [] character class will be included in the search. For example having [mnc] means to search for the occurrence of an m, n, or c in the original string. This metacharacter can also be a range. For example [a-c] means to match the set of characters between a and c. if denoted by [a-z] that means to match any lower case character.
  2. Complementary to the above is the complement of the set, [^ ]. This means that anything within this complementary set should not be included in the search. For example if you get [^ cab] it means when searching do not include the lower case letter c, a, or b in the search.
  3. \d is the metacharacter that says search only decimal digits. It is equivalent to [0-9]
  4. \D says match any non-digit character. It is equivalent to the complement set, [^0-9]
  5. \s says match any white space while \S is the complement that says do not match any whitespace.
  6. \w says match any alphanumeric character while \W says do not match alphanumeric characters.

Now, let’s talk about repeating matches.

There are four symbols for match repetition.

  1. * metacharacter says that the preceding character matches zero or more time. That means you can match it 0, 1, 2 etc infinite times. For example do*g will match dg, dog, doog, doooog, etc. Now you get it.
  2. + metacharacter says match the preceding character one or more times. Note its difference from *. That means it can match 1, 2, 3 etc times to infinity but can never match 0 time. Examples are for the above again, if we have do+g it will match dog, doog, dooog etc but not dg. Get it?
  3. ? metacharacter says match one or zero times. It is called the optional repeating character. For example having da?d will match dd and also match dad and nothing else.
  4. Now the last repeating character is {m,n} character. It says match the preceding character at least m number of times and at most n number of times.

Now, I believe that is what we need to start building our matching pattern.

From our challenge above we say we have a date with floats. Let’s build a matching pattern from a string that fulfils starting from +, - or . symbols. Then has at least one decimal symbol and exactly one . symbol. That gives us the following regex pattern:

pattern = r'[+\-]?[0-9]*.{1,1}\d+'

Let's explain the pattern slowly. [+\-]? says that the float could start with optional + or -. Notice that we backslashed the – because this would make python to recognize the character. If we didn’t backslash it, python would think it is a range because it is within a set metacharacter, [ ].

Next is [0-9]?. This pattern says that any digit can occur zero of more times where it starts or does not start with + or -. Notice that we left off the . character in the first space. This is because if a float starts with the period, ., character, then it would not have any digit. So, that is why the period is coming after the digit.

The .{1,1} says that we will have at least and at most 1 period character. That is exactly one. Then the pattern says that it ends with a digit. There must be at least one digit. That is what the ending pattern, \d+, means. Notice that I interchanged [0-9] and \d. I just wanted you to realize that they are the same patterns.

One tool that you can use to build your regex patterns is found at regex101.com. This is a great site for using regular expressions. It has all the tools you need to understand regular expressions.

Now that we have created the regular expressions according to the challenge above, let us test it to see that it works. To do so, I compiled the pattern and created a comparison_list for the list of strings we want to check the pattern against. Then using a for loop I went through each of the items in the list looking for matches.

You would notice that the challenge involves casting the string to a float. I did not put that into the regex because that is not the function of regex but in the try block there is a conditional that checks for that.

Here is the code for the challenge.

You could create your own test suites and check out how your skill with regular expressions. They are a fun way to code. For other methods of the python regex, you could check out this post on python re match and python re search.

You could download the script for the solution here. Enjoy your date with regular expressions and floats.

Cubing the Fibonacci sequence using a map and lambda function in python

In this article, I will show how you can use the map and lambda function. We will be using a Fibonacci sequence to demonstrate this. The task we will be carrying out is to produce a Fibonacci sequence and then apply map to it in order to cube it while utilizing a lamda function. We will be introducing each of them in turn.

First, the Fibonacci sequence.

The Fibonacci sequence was discovered by an Italian mathematician, Leonardo Fibonacci. The sequence goes in the form 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,... Take a good look at the sequence and you will notice something. You will notice that from the third term, you need to sum the previous two terms to get the third term. That is a2, which is 1, is the sum of a1 and a0. The general formula for each nth term is: An= an-1 + an-2and the first two terms are given as a0 = 0 and a1 = 1.

So, let’s generate some code that will give us the Fibonacci sequence.

In the Fibonacci(num) function, we used a recursive definition for the Fibonacci function. As you can see from the last return, we called the Fibonacci function twice, asking it to sum the return values of the two previous calls.

Here is the code:

Now, we will create a list of the sum of any number of Fibonacci functions. For example, if we want to generate a list of the first n Fibonacci function, we would use the following code:

You will notice from the code above that I created a for loop that calls the Fibonacci function for each number we want to return. If you print the list, you will get the value for each Fibonacci number and all arranged in the list. For example, if we wanted to create a list of first five Fibonacci numbers the list, n_list, when printed, gives [0. 1. 1. 2. 3].

Now that we have our Fibonacci list ready. What we do next is use the map function to cube each element in the list. To carry out this cubing, I will use a lambda function.

But first, what is a map function?

A map function applies a given function to each element of an iterable such as a list, set, tuple etc. The syntax for the map function is map(function, iterable, …). This shows that the map can take more than one iterable. For example, let the function be a square function. We want to apply the square function to each element of the list [1,2,3,4].

This is how we would do it. First we write the square function and then use it as the function parameter in map, then insert the iterable as the second parameter in map. Here is the code:

The output from the above is:

[1, 4, 9, 16]

All the numbers squared. Used on its own, the map function will give you a map object. So, in order to print it out, I had to cast the map object to a list using list(map(square, the_list)). You could even cast it to a set or any iterable if you want. Note that this map function is not used in our task. It is just an illustration. The one we use will come below.

Now that we have our map function set out, what about the lambda function.

The lambda function definition

A lambda function is a simple function. It is a function having no name. You know that normally you would define functions with a name, but for lambda functions you just want to return a value without defining a function. A lambda function can take any number of arguments but it has only one line or expression that it returns. I love lambda functions whenever I want to write a one-liner function. The square function above could have been done using a lambda function.

The syntax for a lambda function is: lambda x, y : expression, where x and y are parameters. The expression is any valid operation on the parameters. You use only one line for it.

So, let’s go back to our task for today. We want to take the Fibonacci numbers list and cube every item in the list. We have already created the Fibonacci numbers list above. Now, how do we cube it combining a map and lambda function.

I will use just this one-liner.

From the lambda function above you can see that I used x as the parameter and the expression was that each x should be raised to power 3 or cubed. So, what the map function and lambda function is saying in essence is that take each item in n_list and then raise it to be power of 3 (or cube it) with map making sure we walk through each element in n_list. Map produces a map object and this object is then cast into a list using the list function and the value is referenced by cubed_fib which was then printed in the next line.

That is all for our task for today. If you want to keep on reading of other tasks I will be producing, just subscribe to this blog using the email subscription form above.

Here is the full code for the task:

For those of you who would like to have the file, you can download it here.

Matched content