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.

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.

Matched content