How is remainder calculated with modulo when solving fractions? - python

As you can see, dividing 3/7 yields a fraction. But when I do 3%7 it yields 3. How could this be? I suppose I expected an output value of 4 (because it would take 4 to complete 7) or 0, (because there is no remainder at all if you use integer division such as 3//7).
>>> 3/7
0.42857142857142855
>>> 3%7
3
>>>
Just trying to understand the depths of Python. Thanks!

Remember long division? Before you learned about fractions, 50 divided by 7 would be 7, remainder 1. The remainder is the modulus. It is the numerator of the 1/7 remaining after integer division.

Let's use different numbers for demonstration.
42 divided by 5 gives a quotient of 8 and a remainder of 2. That means 42 // 5 == 8 and 42 % 5 == 2.
3 divided by 7 gives a quotient of 0 and a remainder of 3. That means 3 // 7 == 0 and 3 % 7 == 3.
In Python, // and % represent the quotient and remainder you probably learned about before you learned about fractions and real numbers. The only (possible) difference is that // floors and % matches the sign of the right-hand operand.

modulo returns the whole number after integer (floor) division.
>>>3//7
0 # with remainder 3
>>>3%7
3
>>>2//5
2 # with remainder 1
>>>2%5
1

Re-reading your question, it occurred to me you got your terms mixed up and that may have been the underlying confusion that none of us properly answered.
But when I do 3%7 it yields 3. How could this be? I suppose I expected an output value of 4 (because it would take 4 to complete 7)
So first that issue was masked when you said 4. Since 4 is greater than 3, 3 can be subtracted a second time, leaving 1. So 1 is the output of 7 % 3.
But you asked about 3 % 7, even though you then proceeded to explain 7 % 3. 3 % 7 is less than 1 (because 7 > 3). So that is why the modulus is still 3. Integer division gives you 0, so 3 is left.
Take the first term (3) divided by the second term (7) using integer division (resulting in 0). Subtract that number from the first term (3) and you get 3. So: 3 % 7 = 3

Related

Changing the final value in loop after one iteration

Design the source code to print the Knight sequence of a given number n.
Knight Sequence of a number starts with itself, the remaining terms of the sequence are
the sum of proper divisors of the immediate previous term.
Examples:
 The knight sequence for 10 is 10, 8, 7, 1, 0.
(Sum of proper divisors of 10 is 5 + 2 + 1 = 8.
Sum of proper divisors of 8 is 4 + 2 + 1 = 7.
The Sum of proper divisors of 7 is 1.
The Sum of proper divisors of 1 is 0.)
Note that there is no proper divisor of 1.
 The knight sequence for 6 is 6 (an infinite sequence of 6s).
When the knight sequence is repeating, print the repeating number and stop.
I am trying to solve this question and wrote this code:
n = int(input('Enter the value: '))
l = [n]
s = 0
for i in range(1, n):
if n % i == 0:
s += i
l.append(s)
print(set(l))
and this gives the output as:
Enter the value: 10
{8, 10}
The issue is that I am not able to figure out that how to continue this iteration to find the rest of the sequence....pls help me out

Number of digits after decimal point in pandas

I have CSV file with data:
Number
1.1
2.2
4.1
5.4
9.176
14.54345774
16.25664
If I print to display with pandas I get:
df = pd.read_csv('data.csv')
print(df)
Number
0 1.100000
1 2.200000
2 4.100000
3 5.400000
4 9.176000
5 14.543458
6 16.256640
But if I cut 14.54345774 to 14.543 output is changed:
Number
0 1.10000
1 2.20000
2 4.10000
3 5.40000
4 9.17600
5 14.54300
6 16.25664
The first case number of digits after decimal point in pandas is 6, second case is 5.
Why format is changed?
What pandas parameters should I change so these cases are equal? I want the number of digits after the decimal point to be constant and digits after the decimal point is round to max digits after the decimal point if it possibly.
UPDATE:
IMO, This moment arises on data initialization, so round don't get to desirable result if I want use 6 digits. It only can be decreased (6->5 digits), but it can't be increased (5->6).
You can use pd.set_option to set the decimal number display precision to e.g. 5 in this case:
pd.set_option("display.precision", 5)
or use:
pd.options.display.float_format = '{:.5f}'.format
Result:
print(df) # with original value of 14.54345774
Number
0 1.10000
1 2.20000
2 4.10000
3 5.40000
4 9.17600
5 14.54346
6 16.25664
You can use df.round(decimals=val) to fix number of digits after decimal to val.
Also, when you changed to 14.453, pandas didn't needed to show 6 digits then as 16.25664 has most digits after the decimal (i.e. 5) and so now it started showing 5 digits. You can fix this to some constant value so that it doesn't changes with operations.

Math function to find the biggest multiple of a number within a range

I want to know if there is a math expression that I can use to find this relation between two numbers.
Some examples of the input and expected output are below:
Input Multiple Result
4 3 3
6 3 6
8 3 6
4 4 4
12 4 12
16 5 15
Also, the expressions below from Wolfram Alpha show me the expected result but since they don't expand on the explanation on how to do it I can't learn from them...
Biggest multiple of 4 from 10
Biggest multiple of 4 from 12
try with // and % operators!
for //, you would do
Result = (Input // Multiple) * Multiple
This way you get how many times Multiple Fits into Input - this number is then multiplied with the Multiple itself and therefore gives you the expected results!
EDIT: how to do it with modulo %?
Result = Input - (Input % Multiple)
taken from MCO's answer!
You can employ modulo for this. For example, to calculate the biggest multiple of 4 that is less or equal than 13:
13 % 4 = 1
13 - 1 = 12
in python, that could look like this:
def biggest_multiple(multiple_of, input_number):
return input_number - input_number % multiple_of
So you use it as:
$ biggest_multiple(4, 9)
8
$ biggest_multiple(4, 12)
12
Here's how I would do it:
return int(input / multiple) * multiple
It truncates the division so that you get an integer, which you can multiply.
This can be trivial but damn easy to understand. To take into account if multiple is negative or zero
Multiple=[3,3,3,4,4,5,0,-5]
Input=[4,6,8,4,12,16,1,8]
Result=[]
for input,multiple in zip(Input,Multiple):
if(multiple):
Result.append((range(multiple,input+1,abs(multiple)))[-1])
else:
Result.append(0)
print(Result)
Output:
[3, 6, 6, 4, 12, 15, 0, 5]

Python character length of a binary value

I am looking for way to determine the number of characters my binary value takes up.
For example if my values binary values were 4, 20, and 60 I'd get the following results:
bin(4), 0b100 = 3
bin(20), 0b10100 = 5
bin(60), 0b111100 = 6
a = 20
a.bit_length()
>> 5
A positive integer n has b bits when 2b-1 ≤ n ≤ 2b – 1. So The number of bits required to represent an integer n is :
floor(log n)+1 # note that base of log is 2
And since you have 0b at the leading you need to add 2 to aforementioned formula.
So it would be :
floor(log n) + 3
And in python you can use math module like following:
math.floor(math.log(n, 2)) + 3
Example :
>>> math.floor(math.log(10, 2)) + 3
6.0
>>>
>>> len(bin(10))
6
>>> math.floor(math.log(77, 2)) + 3
9.0
>>> len(bin(77))
9
As a more Pythonic way you can also use int.bit_length which returns the number of bits needs to represent an integer object. So for get the number of require characters you can add it with 2 :
int.bit_length() + 2

Python: Why does right shift >> round down and where should it be used?

I've never used the >> and << operators, not because I've never needed them, but because I don't know if I could have used them, or where I should have.
100 >> 3 outputs 12 instead of 12.5. Why is this. Perhaps learning where to best use right shift will answer that implicitly, but I'm curious.
Right shift is not division
Let's look at what right-shift actually does, and it will become clear.
First, recall that a number is stored in memory as a collection of binary digits. If we have 8 bits of memory, we can store 2 as 00000010 and 5 as 00000101.
Right-shift takes those digits and shifts them to the right. For example, right-shifting our above two digits by one will give 00000001 and 00000010 respectively.
Notice that the lowest digit (right-most) is shifted off the end entirely and has no effect on the final result.
>> and << are the right and left bit shift operators, respectively. You should look at the binary representation of the numbers.
>>> bin(100)
'0b1100100'
>>> bin(12)
'0b1100'
The other answers explain the idea of bitshifting, but here's specifically what happens for 100>>3
100
128 64 32 16 8 4 2 1
0 1 1 0 0 1 0 0 = 100
100 >> 1
128 64 32 16 8 4 2 1
0 0 1 1 0 0 1 0 = 50
100 >> 2
128 64 32 16 8 4 2 1
0 0 0 1 1 0 0 1 = 25
100 >> 3
128 64 32 16 8 4 2 1
0 0 0 0 1 1 0 0 = 12
You won't often need to use it, unless you need some really quick division by 2, but even then, DON'T USE IT. it makes the code much more complicated then it needs to be, and the speed difference is unnoticeable.
The main time you'd ever need to use it would be if you're working with binary data, and you specifically need to shift the bits around. The only real use I've had for it was reading & writing ID3 tags, which stores size information in 7-bit bytes, like so:
0xxxxxxx 0xxxxxxx 0xxxxxxx 0xxxxxxx.
which would need to be put together like this:
0000xxxx xxxxxxxx xxxxxxxx xxxxxxxx
to give a normal integer in memory.
Bit shifting an integer gives another integer. For instance, the number 12 is written in binary as 0b1100. If we bit shift by 1 to the right, we get 0b110 = 6. If we bit shift by 2, we get 0b11 = 3. And lastly, if we bitshift by 3, we get 0b1 = 1 rather than 1.5. This is because the bits that are shifted beyond the register are lost.
One easy way to think of it is bitshifting to the right by N is the same as dividing by 2^N and then truncating the result.
I have read the answers above and just wanted to add a little bit more practical example, that I had seen before.
Let us assume, that you want to create a list of powers of two. So, you can do this using left shift:
n = 10
list_ = [1<<i for i in range(1, n+1)] # Where n is a maximum power.
print(list_)
# Output: [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
You can timeit it if you want, but I am pretty sure, that the code above is one the fastest solutions for this problem. But what I cannot understand is when you can use right shift.

Categories

Resources