Search

Coding Python Functions Converting To Any Base That Fits Your Fancy

Sometimes while doing maths, we are faced with converting from one base to the other. Python is good for occasions like this. That is why I love programming in python. In this post, I will describe two ways you can convert any number in base 10 to any other base.

 

First, the more than one line way.

We will use simple mathematical logic to do the base conversion. In maths when you are converting from base 10 to any other base, what you do is that you repeatedly divide the number by the base, including the quotient, and keep the remainder until the quotient gets to zero. When you get the list of remainders, you then reverse the list and you have your converted number in that base. In this simplistic example that is also what we are going to do. I will be using two built-in functions to carry out this activity.

The first function is the divmod function. The syntax of the divmod function is divmod(numerator, denominator). The denominator divides the numerator. What the function returns is a tuple consisting of the quotient and the remainder. That’s it. So, we will be using this function to repeatedly divide the number and its quotient while returning the quotient and the remainder. The quotient will be checked against a condition that it has not gotten to zero while we will be collecting the remainder in a list. Just like you do in maths. When the quotient gets to zero, the division will end.

Then the second function we will be using is the reversed function. The syntax of the reversed function is reversed(sequence). As the name implies, reversed just takes a sequence and reverses the items in the sequence. So simple.

Now that we have our two handy functions, we are ready to write code that will convert any number to any base. I will call the function we will use for this, converter.

Here is the code:

I want you to note that while appending the remainder to each remainder_digits list, I first converted them to a string. If I did not, reversed would not be able to reverse them. Also in line 6 I used the ‘’.join statement to cast the list to a string.

You can download the script for the code above from here.

That’s the logical way to go about it. Now let me introduce you on how to do it with numpy.

One liner Numpy.

Numpy is fundamental for scientific and mathematical computing in python. As you know we are dealing with mathematical things here; numpy has a handy function for handling it. But I would add that numpy is somewhat of an overkill. The simple method I introduced above for programming it in python is enough. But in case you want something that can do it in one line and faster, then you can use numpy.

First, to use numpy it has to be installed on your machine. You can use the command: pip install numpy to install it on your machine, and if it is already installed, then you are good to go. Next, on your script you need to import numpy into your script using the statement: import numpy.

We will be using the numpy.base_repr function for this conversion. The syntax of the function is numpy.base_repr(number, base=2, padding=0). The only positional argument is the number you want to convert. The next is a keyword argument and this signifies the base you want to be converting to. The default is base 2. Then the next keyword argument is the padding you want for the numbers. The default is 0, that is, don’t pad the result with leading zeros. This is in case you want to pad the results. In case you need a refresher on positional and keyword arguments, you can see this earlier post on keyword and positional arguments.

Now that we have everything set up, let us see the one line of code that can do this for us.

You can download the script for the code above from here.

That’s it. Numpy is just another easier way of doing it with more added functionality. Numpy is beautiful. Note though that this function in numpy can only convert bases from base 2 to base 36. So if you need a base that is higher than 36, you should use the first converter function instead.

If you want to keep receiving python posts like this, just subscribe to this blog using your email. Happy pythoning.

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.

Matched content