Incremnting division in python - python

I am new and I need to know whether it is possible to increment division the same way you can increment addition or subtraction in python. Thank you!

If by incrementing addition you mean += then, of course yes, it is available for all the arithmetic operators...
a = 100
a //= 9
print(a)
Output:-
11
b = 1024
b /= 2
print(b)
Output:-
512.0

Related

Order of Operations - Python 3

Can someone explain why c is equal to 25 and not 30? I keep getting 30 by multiplying a*(b//a) and then adding b to it after.
a=10
b=3*(a-5)
c=b+(b//a)*a
Just do it step by step and you'll see that you're doing
c = 15 + 1*10
Hence c is 25. b//a is floor division, meaning 15/10 becomes 1
An easy way to understand whats going on is to print each steps:
a=10
b=3*(a-5)
print(b)
print(b//a)
print((b//a)*a)
print(b+(b//a)*a)
c=b+(b//a)*a
output
15
1
10
25
(15//10) is equal to 1 so the formula for c is equivalent to 15+1*10 The // operator is floor division which round down to the nearest integer. In additon all the values you are using are integers. To get 30 you need to use the normal divsion operator / and case one of the operands in the division to a floating point number, like this: c = b+(float(b)/a)*a That code sets c to 30.0.
c = b + (b//a)*a = b + ((b//a)*a) = 15 + ((15//10)*10) = 15 + (1*10) = 25
Does this clear it up?
The crucial part is 15//10, because // performs integer division which rounds down to the next integer. Note the difference between / and // in Python 3.
>>> 15/10
1.5
>>> 15//10
1

How Can I Fix An Overflow Error From the Calculation In Python 3?

I created a program to calculate primes with mill's constant, but anyway, it results in huge computations being done. For instance, 1.306... ** 5661
It throws an overflow error. How can I fix this? I tried xrange, and it failed to help me because that no longer exists in python 3. I don't know how to reduce it.
Can anyone give me some help? Thanks a lot!
Edit: here's the code:
theta = 1.3063778838630806904686144926026
bottom = int(input("lower bound: "))
top = int(input("high bound: "))
for i in range(0,top + 1):
print(round(theta ** (3**i))) # causes the error
Here's how to calculate Mill's primes using integers. First you need to write Mill's constant as a fraction. I used one of the values from the Wikipedia article.
num, den = 1551795687, 1187861266
print(num / den)
for i in range(1, 8):
e = 3 ** i
n = num ** e
d = den ** e
print(i, n // d)
output
1.3063778838630806
1 2
2 11
3 1361
4 2521008887
5 16022236204009819034551083884
6 4113101149215105495247660946168530631843333312378291569324941703732418013747202413154
7 69583804376962776892757521964751417769589800913915250464742380681561387050414758147961918413247296927859465626141517084928624751186191429632740787663513270579366994745400890812584434492059975056388739246886951607326825627525396066637918379217513934013930
To perform more accurate calculations you'll need to use a better starting fraction, but that will cause n and d to grow even more rapidly.
Thank you, #PM 2Ring and #Blurp! You helped me a lot by pointing out the decimal module, which was exactly what I needed! It turns out that 559397567061773305900... is prime!

Writing a simple function using while

A Python HOMEWORK Assignment asks me to write a function “that takes as input a positive whole number, and prints out a multiplication, table showing all the whole number multiplications up to and including the input number.”(Also using the while loop)
# This is an example of the output of the function
print_multiplication_table(3)
>>> 1 * 1 = 1
>>> 1 * 2 = 2
>>> 1 * 3 = 3
>>> 2 * 1 = 2
>>> 2 * 2 = 4
>>> 2 * 3 = 6
>>> 3 * 1 = 3
>>> 3 * 2 = 6
>>> 3 * 3 = 9
I know how to start, but don’t know what to do next. I just need some help with the algorithm. Please DO NOT WRITE THE CORRECT CODE, because I want to learn. Instead tell me the logic and reasoning.
Here is my reasoning:
The function should multiply all real numbers to the given value(n) times 1 less than n or (n-1)
The function should multiply all real numbers to n(including n) times two less than n or (n-2)
The function should multiply all real numbers to n(including n) times three less than n or (n-3) and so on... until we reach n
When the function reaches n, the function should also multiply all real numbers to n(including n) times n
The function should then stop or in the while loop "break"
Then the function has to print the results
So this is what I have so far:
def print_multiplication_table(n): # n for a number
if n >=0:
while somehting:
# The code rest of the code that I need help on
else:
return "The input is not a positive whole number.Try anohter input!"
Edit: Here's what I have after all the wonderful answers from everyone
"""
i * j = answer
i is counting from 1 to n
for each i, j is counting from 1 to n
"""
def print_multiplication_table(n): # n for a number
if n >=0:
i = 0
j = 0
while i <n:
i = i + 1
while j <i:
j = j + 1
answer = i * j
print i, " * ",j,"=",answer
else:
return "The input is not a positive whole number.Try another input!"
It's still not completely done!
For example:
print_multiplication_table(2)
# The output
>>>1 * 1 = 1
>>>2 * 2 = 4
And NOT
>>> 1 * 1 = 1
>>> 1 * 2 = 2
>>> 2 * 1 = 2
>>> 2 * 2 = 4
What am I doing wrong?
I'm a little mad about the while loop requirement, because for loops are better suited for this in Python. But learning is learning!
Let's think. Why do a While True? That will never terminate without a break statement, which I think is kind of lame. How about another condition?
What about variables? I think you might need two. One for each number you want to multiply. And make sure you add to them in the while loop.
I'm happy to add to this answer if you need more help.
Your logic is pretty good. But here's a summary of mine:
stop the loop when the product of the 2 numbers is n * n.
In the mean time, print each number and their product. If the first number isn't n, increment it. Once that's n, start incrementing the second one. (This could be done with if statements, but nested loops would be better.) If they're both n, the while block will break because the condition will be met.
As per your comment, here's a little piece of hint-y psuedocode:
while something:
while something else:
do something fun
j += 1
i += 1
where should original assignment of i and j go? What is something, something else, and something fun?
This problem is better implemented using nested loops since you have two counters. First figure out the limits (start, end values) for the two counters. Initialize your counters to lower limits at the beginning of the function, and test the upper limits in the while loops.
The first step towards being able to produce a certain output is to recognize the pattern in that output.
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
The number on the right of = should be trivial to determine, since we can calculate it by multiplying the other two numbers on each row; obtaining those is the core of the assignment. Think of the two operands of * as two counters, let's call them i and j. We can see that i is counting from 1 to 3, but for each i, j is counting from 1 to 3 (resulting in a total of 9 rows; more generally there will be n2 rows). Therefore, you might try using nested loops, one to loop i (from 1 to n) and another to loop j (from 1 to n) for each i. On each iteration of the nested loop, you can print the string containing i, j and i*j in the desired format.

count number of ones in a given integer

How do you count the number of ones in a given integer's binary representation.
Say you are given a number 20, which is 10100 in binary, so number of ones is 2.
What you're looking for is called the Hamming weight, and there are a lot of algorithms to do it. Here's another straightforward one:
def ones(n):
w = 0
while (n):
w += 1
n &= n - 1
return w
Use the awesome collections module.
>>> from collections import Counter
>>> binary = bin(20)[2:]
>>> Counter(binary)
Counter({'0': 3, '1': 2})
Or you can use the built-in function count():
>>> binary = bin(20)[2:]
>>> binary.count('1')
2
Or even:
>>> sum(1 for i in bin(20)[2:] if i == '1')
2
But that last solution is slower than using count()
>>> num = 20
>>> bin(num)[2:].count('1')
2
The usual way to make this blinding fast is to use lookup tables:
table = [bin(i)[2:].count('1') for i in range(256)]
def pop_count(n):
cnt = 0
while n > 0:
cnt += table[n & 255]
n >>= 8
return cnt
In Python, any solution using bin and list.count will be faster, but this is nice if you want to write it in assembler.
The int type has a new method int.bit_count() since python 3.10a, returning the number of ones in the binary expansion of a given integer, also known as the population count as follows:
n = 20
bin(n)
'0b10100'
n.bit_count() returns 2 as it has 2 ones in the binary representation.
The str.count method and bin function make short work of this little challenge:
>>> def ones(x):
"Count the number of ones in an integer's binary representation"
return bin(x).count('1')
>>> ones(20)
2
You can do this using bit shifting >> and bitwise and & to inspect the least significant bit, like this:
def count_ones(x):
result = 0
while x > 0:
result += x & 1
x = x >> 1
return result
This works by shifting the bits right until the value becomes zero, counting the number of times the least significant bit is 1 along the way.
I am a new coder and I found this one logic simple. Might be easier for newbies to understand.
def onesInDecimal(n):
count = 0
while(n!=0):
if (n%2!=0):
count = count+1
n = n-1
n = n/2
else:
n = n/2
return count
For a special case when you need to check quickly whether the binary form of the integer x has only a single 1 (and thus is a power of 2), you can use this check:
if x == -(x | (-x)):
...
The expression -(x | (-x)) is the number that you get if you replace all 1s except the last one (the least significant bit) in the binary representation of x with 0.
Example:
12 = 1100 in binary
-12 = ...110100 in binary (with an infinite number of leading 1s)
12 | (-12) = ...111100 in binary (with an infinite number of leading 1s)
-(12 | (-12)) = 100 in binary
If the input number is 'number'
number =20
len(bin(number)[2:].replace('0',''))
Another solution is
from collections import Counter
Counter(list(bin(number))[2:])['1']

Exercise on Summing Digits | What's with n // = 10 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the reason for having ‘//’ in Python?
While trying to do an exercise on summing digits, I stumbled on this solution:
def sum_digits(n):
import math
total = 0
for i in range(int(math.log10(n)) + 1):
total += n % 10
n //= 10
return total
My question is, what does the second to last line do? How is that proper syntax?
That implements what is called floor division. Floor division (indicated by // here) truncates the decimal and returns the integer result, while 'normal' division returns the answer you may 'expect' (with decimals). In Python 3.x, a greater distinction was made between the two, meaning that the two operators return different results. Here is an example using Python 3:
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
Prior to Python 3.x, there is no difference between the two, unless you use the special built-in from __future__ import division, which then makes the division operators perform as they would in Python 3.x (this is using Python 2.6.5):
In [1]: 10 / 3
Out[1]: 3
In [2]: 10 // 3
Out[2]: 3
In [3]: from __future__ import division
In [4]: 10 / 3
Out[4]: 3.3333333333333335
In [5]: 10 // 3
Out[5]: 3
Therefore when you see something like n //= 10, it is using the same +=/-=/*=/etc syntax that you may have seen, where it takes the current value of n and performs the operation before the equal sign with the following variable as the second argument, returning the result into n. For example:
In [6]: n = 50
In [7]: n += 10
In [8]: n
Out[8]: 60
In [9]: n -= 20
In [10]: n
Out[10]: 40
In [11]: n //= 10
In [12]: n
Out[12]: 4
// is the floor division operator. It always truncates the return value to the largest integer smaller than or equal to the answer.
The second to last line is a combination of operators, in a way, including an uncommon one, which is why it's a little confusing.
Let's piece it apart.
First, // in Python is floor division, which basically is division rounded down to the nearest whole number. Thus,
>>> 16//5
3
>>> 2//1
2
>>> 4//3
1
>>> 2//5
0
Finally, the = is there because of a Python syntax that allows one to perform an operation on a variable, and then immediately reassign the result to the variable. You've probably seen it most commonly in +=, as:
>>> a = 5
>>> a += 7
>>> a
12
In this case, //= means "perform floor division, floor dividing the variable by the second argument, then assign the result to the original input variable." Thus:
>>> a = 10
>>> a //= 6
>>> a
1
for the assignment in Python A += B equals to A = A + B ,A *= B equals to A = A * B
same thing applies to "Floor Divide" as well , A //= B equals to A = A // B
Floor Division means return the truncated integer number
>>> 5 // 3 # 1.6
1 # 0.6 will be throw off

Categories

Resources