Is this working properly - Sum of Fibonacci in Python 3 - python

I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also.
Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101
Is it correct ?
Here is my code:
n = int(input())
print()
p = 0
d = 1
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
for i in range(n - 2):
p = d
d = z
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
print('Sum:', z)
EDIT: Code edited again, check it now. I just found on Wikipedia.. It depends from what number you start the loop. So if I use (0, 1, 1, 2, 3, 5, 8, 13, 21, and 34) as first 10 Fibonacci numbers, the sum is going to be 88, not 89.

The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively:
>>> cache = {}
>>> def fib(n):
if n == 0: return 0
if n == 1: return 1
if not n in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100

In your loop you are already starting the iteration at the 3rd position, since you set. So set your range to (n -2).
0: 1
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5

To get the sum of the Fibonacci numbers, using zero as the first in the series, you need to do this:
def run_it(n):
N2 = 0
N1 = 0
N = 0
z = N
for i in range(n):
print(N,z)
N2 = N1
N1 = N
if N is 0: N = 1
else: N = N1 + N2
z = z + N
run_it(int(input('Number: ')))
To calculate the sum using one as the start of the series, change the initial value of N from zero to one.

Related

Is there a way to insert an arbitrary symbol before the Python output value?

I'm calculating the matrix value with Python, but I want to distinguish the value of equtaion, is there a way?
x - y - 2z = 4
2x - y - z = 2
2x +y +4z = 16
I want to make the expression above like this when I print out the matrix from the function I created
1 -1 -2 | 4
2 -1 -1 | 2
2 1 4 | 16
Same as the rref result of this
1 0 0 | 24
0 1 0 | 72
0 0 1 | -26
def showMatrix():
print("\n")
for i in sd:
for j in i:
print(j, end="\t")
print("\n")
def getone(pp):
for i in range(len(sd[0])):
if sd[pp][pp] != 1:
q00 = sd[pp][pp]
for j in range(len(sd[0])):
sd[pp][j] = sd[pp][j] / q00
def getzero(r, c):
for i in range(len(sd[0])):
if sd[r][c] != 0:
q04 = sd[r][c]
for j in range(len(sd[0])):
sd[r][j] = sd[r][j] - ((q04) * sd[c][j])
sd = [
[1, 1, 2, 9],
[2, 4, -3, 1],
[3, 6, -5, 0]
]
showMatrix()
for i in range(len(sd)):
getone(i)
for j in range(len(sd)):
if i != j:
getzero(j, i)
showMatrix()
print("FiNAL result")
showMatrix()
Here is a function which takes a list of 4 numbers and returns a string representing an equation in x,y,z. It handles coefficients which are negative, zero, or +/-1 appropriately:
def make_equation(nums):
coefficients = nums[:3]
variables = 'xyz'
terms = []
for c,v in zip(coefficients,variables):
if c == 0:
continue
elif c == 1:
coef = ''
elif c == -1:
coef = '-'
else:
coef = str(c)
terms.append(coef + v)
s = ' + '.join(terms)
s = s.replace('+ -','- ')
return s + ' = ' + str(nums[3])
Typical example:
make_equation([2,-3,1,6])
With output:
'2x - 3y + z = 6'

Python code stops outputting during/after print statement, but the same part of code works when isolated as its own program. What's going on?

I am trying to implement my own version of Hamming code with even parity (as shown here, except I'm starting counting the bits from left to right, rather than right to left) in Python.
My code is as follows:
# Python program to demonstrate Hamming code
def calcCheckBits(m):
# Use the formula 2 ^ r >= m + r + 1 to calculate the number of redundant bits.
# Iterate over 0 ... m and return the value that satisfies the equation.
for i in range(m):
if(2**i >= m + i + 1):
print("Number of redundant bits: " + str(i))
return i
def posCheckBits(data, r):
# Check bits are placed at the positions that correspond to the power of 2.
j = 0
k = 1
m = len(data)
res = ''
# If position is power of 2, then insert '0'; else, append the data.
for i in range(1, m + r + 1):
if(i == 2**j):
print("If " + str(i) + " == " + str(2**j))
res = res + '0'
print("check bit placed at position " + str(i))
print("res = " + res)
j += 1
else:
res = res + data[k - 1]
print("appending data at position " + str(i))
print("res = " + res)
k += 1
print("res: " + res)
return res
def determineCheckBits(data, r):
# Check bits are placed at the positions that correspond to powers of 2.
j = 0
m = len(data)
res = data
activatedBitCounter = 0
# If position i is a power of 2, then find the value of the check bit; else, do nothing.
for i in range(1, m + r + 1):
if(i == 2**j):
contributedToBy = [] # the bits that have i in their sum of powers of 2
print("If " + str(i) + " == " + str(2**j))
# Find the values that i is contributed to by (that is, the values where i contributes to its decomposition into a sum of powers of 2)
print("Now finding the values where " + str(i) + " contributes to its decomposition into a sum of powers of 2.")
for y in range(3, m + r + 1):
powers = []
z = 1
while z <= y:
if z & y:
powers.append(z)
z <<= 1
print("The list of powers is " + str(powers))
print("The powers of 2 that sum to " + str(y) + " are ")
for l in range(len(powers)):
print(powers[l])
if(i in powers):
contributedToBy.append(y)
print("The bits that have " + str(i) + " in their sum of powers of 2 are ")
for l in range(len(contributedToBy)):
print(contributedToBy[l])
for l in contributedToBy:
if(int(res[l - 1]) == 1):
activatedBitCounter += 1
# Check if the number of activated bits is odd.
# If so, then, since we want even parity, set the checkbit to 1; else, set to 0.
if((activatedBitCounter % 2) != 0):
res[i] = 1
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 1")
print("res is now " + str(res))
else:
res[i] = 0
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 0")
print("res is now " + str(res))
activatedBitCounter = 0 # reset counter
j += 1 # Append j by 1 to move onto next power
else:
print("else, position " + str(i) + " is not a power of 2, so res = " + res)
print("Final res value from function determineCheckBits: " + res)
return res
# Enter the data to be transmitted
data = '1100011' # codeword
print("data is: " + data)
# Calculate the number of parity bits required
m = len(data)
r = calcCheckBits(m)
# Determine the positions of check bits
arr = posCheckBits(data, r)
# Determine the check bits
arr = determineCheckBits(arr, r)
The transmitted codeword in this case is 1100011.
Each bit whose ordinal position is a power of 2 (1, 2, 4, 8) is a check bit and forces the parity of some 'collection' of bits including itself. Parity may be forced to be either even or odd.
A data bit contributes to the parity of all the bits in its decomposition into a sum of powers of 2. For example:
3 = 2 + 1
7 = 4 + 2 + 1
11 = 8 + 2 + 1
Making a list of these:
1 is contributed to by 3, 5, 7, 9, 11
2 is contributed to by 3, 6, 7, 10, 11
4 is contributed to by 5, 6, 7
8 is contributed to by 9, 10, 11
We then put the data bits in their positions and calculate each check bit.
For example, for 1100011, using even parity:
1 is contributed to by 3, 5, 7, 9, 11, and if we look at these bits for check 1, we have a 1 at bits 3, 5, and 11, which is odd (1 + 1 + 1 = 3), so since we want even parity, we set the bit 1 to 1. Skipping to 8, we see that 8 is contributed to by 9, 10, 11, and if we look at these bits for check 4, we have a 1 at bits 10 and 11, which is even (1 + 1 = 2), so since want even parity, we set the bit 8 to 0. This is how we get 11111000011.
The code above should produce 11111000011 from the input 1100011.
As you can see in the code, I've added a bunch of print statements for debugging. The problem is that this python code just randomly stops outputting anything at
The powers of 2 that sum to 3 are
1
2
as seen here:
It's just stuck there.
This is very perplexing, because if I execute only the part of the code that contains this print statement, it seems to work fine:
def testPowers(m, r):
# If position i is power of 2, then find the value of the parity bit; else, do nothing.
j = 0
for i in range(1, m + r + 1):
if(i == 2**j):
contributedToBy = [] # the bits that have i in their sum of powers of 2
print("If " + str(i) + " == " + str(2**j))
# Find the values that i is contributed to by (that is, the values where i contributes to its decomposition into a sum of powers of 2)
print("Now finding the values where " + str(i) + " contributes to its decomposition into a sum of powers of 2.")
for y in range(3, m + r + 1):
powers = []
z = 1
while z <= y:
if z & y:
powers.append(z)
z <<= 1
print("The powers of 2 that sum to " + str(y) + " are ")
for l in range(len(powers)):
print(powers[l])
if(i in powers):
contributedToBy.append(y)
print("The bits that have " + str(i) + " in their sum of powers of 2 are ")
for l in range(len(contributedToBy)):
print(contributedToBy[l])
m = 7
r = 4
testPowers(m, r)
I've only just started learning Python, so I honestly have no idea what's going wrong. Why isn't my code working, and how do I fix it?
EDIT1
I think I fixed the indentation error with z <<= 1, as Tim Roberts suggested, but now I get another error.
# Python program to demonstrate Hamming code
def calcCheckBits(m):
# Use the formula 2 ^ r >= m + r + 1 to calculate the number of redundant bits.
# Iterate over 0 ... m and return the value that satisfies the equation.
for i in range(m):
if(2**i >= m + i + 1):
print("Number of redundant bits: " + str(i))
return i
def posCheckBits(data, r):
# Check bits are placed at the positions that correspond to the power of 2.
j = 0
k = 1
m = len(data)
res = ''
# If position is power of 2, then insert '0'; else, append the data.
for i in range(1, m + r + 1):
if(i == 2**j):
print("If " + str(i) + " == " + str(2**j))
res = res + '0'
print("check bit placed at position " + str(i))
print("res = " + res)
j += 1
else:
res = res + data[k - 1]
print("appending data at position " + str(i))
print("res = " + res)
k += 1
print("res: " + res)
return res
def determineCheckBits(data, r):
# Check bits are placed at the positions that correspond to powers of 2.
j = 0
m = len(data)
res = data
activatedBitCounter = 0
# If position i is a power of 2, then find the value of the check bit; else, do nothing.
for i in range(1, m + r + 1):
if(i == 2**j):
contributedToBy = [] # the bits that have i in their sum of powers of 2
print("If " + str(i) + " == " + str(2**j))
# Find the values that i is contributed to by (that is, the values where i contributes to its decomposition into a sum of powers of 2)
print("Now finding the values where " + str(i) + " contributes to its decomposition into a sum of powers of 2.")
for y in range(3, m + r + 1):
powers = []
z = 1
while z <= y:
if z & y:
powers.append(z)
z <<= 1
print("The list of powers is " + str(powers))
print("The powers of 2 that sum to " + str(y) + " are ")
for l in range(len(powers)):
print(powers[l])
if(i in powers):
contributedToBy.append(y)
print("The bits that have " + str(i) + " in their sum of powers of 2 are ")
for l in range(len(contributedToBy)):
print(contributedToBy[l])
for l in contributedToBy:
if(int(res[l - 1]) == 1):
activatedBitCounter += 1
# Check if the number of activated bits is odd.
# If so, then, since we want even parity, set the checkbit to 1; else, set to 0.
if((activatedBitCounter % 2) != 0):
res[i] = 1
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 1")
print("res is now " + str(res))
else:
res[i] = 0
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 0")
print("res is now " + str(res))
activatedBitCounter = 0 # reset counter
j += 1 # Append j by 1 to move onto next power
else:
print("else, position " + str(i) + " is not a power of 2, so res = " + res)
print("Final res value from function determineCheckBits: " + res)
return res
# Enter the data to be transmitted
data = '1100011' # codeword
print("data is: " + data)
# Calculate the number of parity bits required
m = len(data)
r = calcCheckBits(m)
# Determine the positions of check bits
arr = posCheckBits(data, r)
# Determine the check bits
arr = determineCheckBits(arr, r)
Error:
appending data at position 11
res = 00101000011
res: 00101000011
If 1 == 1
Now finding the values where 1 contributes to its decomposition into a sum of powers of 2.
The list of powers is [1, 2]
The powers of 2 that sum to 3 are
1
2
The list of powers is [4]
The powers of 2 that sum to 4 are
4
The list of powers is [1, 4]
The powers of 2 that sum to 5 are
1
4
The list of powers is [2, 4]
The powers of 2 that sum to 6 are
2
4
The list of powers is [1, 2, 4]
The powers of 2 that sum to 7 are
1
2
4
The list of powers is [8]
The powers of 2 that sum to 8 are
8
The list of powers is [1, 8]
The powers of 2 that sum to 9 are
1
8
The list of powers is [2, 8]
The powers of 2 that sum to 10 are
2
8
The list of powers is [1, 2, 8]
The powers of 2 that sum to 11 are
1
2
8
The list of powers is [4, 8]
The powers of 2 that sum to 12 are
4
8
The list of powers is [1, 4, 8]
The powers of 2 that sum to 13 are
1
4
8
The list of powers is [2, 4, 8]
The powers of 2 that sum to 14 are
2
4
8
The list of powers is [1, 2, 4, 8]
The powers of 2 that sum to 15 are
1
2
4
8
The bits that have 1 in their sum of powers of 2 are
3
5
7
9
11
13
15
Traceback (most recent call last):
File "/Users/x/testMultiParts.py", line 106, in <module>
arr = determineCheckBits(arr, r)
File "/Users/x/testMultiParts.py", line 73, in determineCheckBits
if(int(res[l - 1]) == 1):
IndexError: string index out of range
Again, the other program doesn't have this error:
If 1 == 1
Now finding the values where 1 contributes to its decomposition into a sum of powers of 2.
The powers of 2 that sum to 3 are
1
2
The powers of 2 that sum to 4 are
4
The powers of 2 that sum to 5 are
1
4
The powers of 2 that sum to 6 are
2
4
The powers of 2 that sum to 7 are
1
2
4
The powers of 2 that sum to 8 are
8
The powers of 2 that sum to 9 are
1
8
The powers of 2 that sum to 10 are
2
8
The powers of 2 that sum to 11 are
1
2
8
The bits that have 1 in their sum of powers of 2 are
3
5
7
9
11
EDIT2
# Python program to demonstrate Hamming code
def calcCheckBits(m):
# Use the formula 2 ^ r >= m + r + 1 to calculate the number of redundant bits.
# Iterate over 0 ... m and return the value that satisfies the equation.
for i in range(m):
if(2**i >= m + i + 1):
print("Number of redundant bits: " + str(i))
return i
def posCheckBits(res, r):
# Check bits are placed at the positions that correspond to the power of 2.
j = 0
k = 1
m = len(data)
res = ''
# If position is power of 2, then insert '0'; else, append the data.
for i in range(1, m + r + 1):
if(i == 2**j):
print("If " + str(i) + " == " + str(2**j))
res = res + '0'
print("check bit placed at position " + str(i))
print("res = " + res)
j += 1
else:
res = res + data[k - 1]
print("appending data at position " + str(i))
print("res = " + res)
k += 1
print("res: " + res)
return res
def determineCheckBits(res, r):
# Check bits are placed at the positions that correspond to powers of 2.
j = 0
res = list(data)
m = len(res)
activatedBitCounter = 0
print("At the beginning, res is " + str(res))
print("At the beginning, m is " + str(m))
# If position i is a power of 2, then find the value of the check bit; else, do nothing.
for i in range(1, m + r + 1):
if(i == 2**j):
contributedToBy = [] # the bits that have i in their sum of powers of 2
print("If " + str(i) + " == " + str(2**j))
# Find the values that i is contributed to by (that is, the values where i contributes to its decomposition into a sum of powers of 2)
print("Now finding the values where " + str(i) + " contributes to its decomposition into a sum of powers of 2.")
for y in range(3, m + r + 1):
powers = []
z = 1
while z <= y:
if z & y:
powers.append(z)
z <<= 1
print("The list of powers is " + str(powers))
print("The powers of 2 that sum to " + str(y) + " are ")
for l in range(len(powers)):
print(powers[l])
if(i in powers):
contributedToBy.append(y)
print("The bits that have " + str(i) + " in their sum of powers of 2 are ")
for l in range(len(contributedToBy)):
print(contributedToBy[l])
for l in contributedToBy:
if(int(res[l - 1]) == 1):
activatedBitCounter += 1
# Check if the number of activated bits is odd.
# If so, then, since we want even parity, set the checkbit to 1; else, set to 0.
if((activatedBitCounter % 2) != 0):
res[i] = '1'
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 1")
print("res is now " + str(res))
else:
res[i] = '0'
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 0")
print("res is now " + str(res))
activatedBitCounter = 0 # reset counter
j += 1 # Append j by 1 to move onto next power
else:
print("else, position " + str(i) + " is not a power of 2, so res = " ''.join(res))
res = ''.join(res)
print("Final res value from function determineCheckBits: " + res)
return res
# Enter the data to be transmitted
data = '1100011' # codeword
print("data is: " + data)
# Calculate the number of parity bits required
m = len(data)
r = calcCheckBits(m)
# Determine the positions of check bits
arr = posCheckBits(data, r)
# Determine the check bits
arr = determineCheckBits(arr, r)
Error:
res = 00101000011
res: 00101000011
At the beginning, res is ['1', '1', '0', '0', '0', '1', '1']
At the beginning, m is 7
If 1 == 1
Now finding the values where 1 contributes to its decomposition into a sum of powers of 2.
The list of powers is [1, 2]
The powers of 2 that sum to 3 are
1
2
The list of powers is [4]
The powers of 2 that sum to 4 are
4
The list of powers is [1, 4]
The powers of 2 that sum to 5 are
1
4
The list of powers is [2, 4]
The powers of 2 that sum to 6 are
2
4
The list of powers is [1, 2, 4]
The powers of 2 that sum to 7 are
1
2
4
The list of powers is [8]
The powers of 2 that sum to 8 are
8
The list of powers is [1, 8]
The powers of 2 that sum to 9 are
1
8
The list of powers is [2, 8]
The powers of 2 that sum to 10 are
2
8
The list of powers is [1, 2, 8]
The powers of 2 that sum to 11 are
1
2
8
The bits that have 1 in their sum of powers of 2 are
3
5
7
9
11
Traceback (most recent call last):
File "/Users/x/testMultiParts.py", line 108, in <module>
arr = determineCheckBits(arr, r)
File "/Users/x/testMultiParts.py", line 75, in determineCheckBits
if(int(res[l - 1]) == 1):
IndexError: list index out of range
EDIT3
Ok, I think I got it!
# Python program to demonstrate Hamming code
def calcCheckBits(m):
# Use the formula 2 ^ r >= m + r + 1 to calculate the number of redundant bits.
# Iterate over 0 ... m and return the value that satisfies the equation.
for i in range(m):
if(2**i >= m + i + 1):
print("Number of redundant bits: " + str(i))
return i
def posCheckBits(res, r):
# Check bits are placed at the positions that correspond to the power of 2.
j = 0
k = 1
m = len(data)
res = ''
# If position is power of 2, then insert '0'; else, append the data.
for i in range(1, m + r + 1):
if(i == 2**j):
print("If " + str(i) + " == " + str(2**j))
res = res + '0'
print("check bit placed at position " + str(i))
print("res = " + res)
j += 1
else:
res = res + data[k - 1]
print("appending data at position " + str(i))
print("res = " + res)
k += 1
print("res: " + res)
return res
def determineCheckBits(arr, r):
# Check bits are placed at the positions that correspond to powers of 2.
j = 0
res = list(arr)
m = len(data)
activatedBitCounter = 0
print("At the beginning, res is " + str(res))
print("At the beginning, m is " + str(m))
# If position i is a power of 2, then find the value of the check bit; else, do nothing.
for i in range(1, m + r + 1):
if(i == 2**j):
contributedToBy = [] # the bits that have i in their sum of powers of 2
print("If " + str(i) + " == " + str(2**j))
# Find the values that i is contributed to by (that is, the values where i contributes to its decomposition into a sum of powers of 2)
print("Now finding the values where " + str(i) + " contributes to its decomposition into a sum of powers of 2.")
for y in range(3, m + r + 1):
powers = []
z = 1
while z <= y:
if z & y:
powers.append(z)
z <<= 1
print("The list of powers is " + str(powers))
print("The powers of 2 that sum to " + str(y) + " are ")
for l in range(len(powers)):
print(powers[l])
if(i in powers):
contributedToBy.append(y)
print("The bits that have " + str(i) + " in their sum of powers of 2 are ")
for l in range(len(contributedToBy)):
print(contributedToBy[l])
for l in contributedToBy:
print("contributedToBy is " + str(contributedToBy))
print("res is " + str(res))
print("res[l - 1] is " + res[l - 1])
if(int(res[l - 1]) == 1):
activatedBitCounter += 1
# Check if the number of activated bits is odd.
# If so, then, since we want even parity, set the checkbit to 1; else, set to 0.
if((activatedBitCounter % 2) != 0):
res[i - 1] = '1'
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 1")
print("res is now " + str(res))
else:
res[i - 1] = '0'
print("activatedBitCounter is " + str(activatedBitCounter) + " so set bit " + str(i) + " of res to 0")
print("res is now " + str(res))
activatedBitCounter = 0 # reset counter
j += 1 # Append j by 1 to move onto next power
else:
print("else, position " + str(i) + " is not a power of 2, so res = " ''.join(res))
res = ''.join(res)
print("Final res value from function determineCheckBits: " + res)
return res
# Enter the data to be transmitted
data = '1100011' # codeword
print("data is: " + data)
# Calculate the number of parity bits required
m = len(data)
r = calcCheckBits(m)
# Determine the positions of check bits
arr = posCheckBits(data, r)
# Determine the check bits
arr = determineCheckBits(arr, r)
Output:
res = 00101000011
res: 00101000011
At the beginning, res is ['0', '0', '1', '0', '1', '0', '0', '0', '0', '1', '1']
At the beginning, m is 7
If 1 == 1
Now finding the values where 1 contributes to its decomposition into a sum of powers of 2.
The list of powers is [1, 2]
The powers of 2 that sum to 3 are
1
2
... skip to 8 == 8:
If 8 == 8
Now finding the values where 8 contributes to its decomposition into a sum of powers of 2.
The list of powers is [1, 2]
The powers of 2 that sum to 3 are
1
2
The list of powers is [4]
The powers of 2 that sum to 4 are
4
The list of powers is [1, 4]
The powers of 2 that sum to 5 are
1
4
The list of powers is [2, 4]
The powers of 2 that sum to 6 are
2
4
The list of powers is [1, 2, 4]
The powers of 2 that sum to 7 are
1
2
4
The list of powers is [8]
The powers of 2 that sum to 8 are
8
The list of powers is [1, 8]
The powers of 2 that sum to 9 are
1
8
The list of powers is [2, 8]
The powers of 2 that sum to 10 are
2
8
The list of powers is [1, 2, 8]
The powers of 2 that sum to 11 are
1
2
8
The bits that have 8 in their sum of powers of 2 are
8
9
10
11
contributedToBy is [8, 9, 10, 11]
res is ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
res[l - 1] is 0
contributedToBy is [8, 9, 10, 11]
res is ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
res[l - 1] is 0
contributedToBy is [8, 9, 10, 11]
res is ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
res[l - 1] is 1
contributedToBy is [8, 9, 10, 11]
res is ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
res[l - 1] is 1
activatedBitCounter is 2 so set bit 8 of res to 0
res is now ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
else, position 91 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 1 is not a power of 2, so res = 1
else, position 101 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 1 is not a power of 2, so res = 1
else, position 111 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 1 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 0 is not a power of 2, so res = 1 is not a power of 2, so res = 1
Final res value from function determineCheckBits: 11111000011
And so we have 11111000011, as required!
EDIT4
I cleaned up the last part by changing it back to
else:
print("else, position " + str(i) + " is not a power of 2, so res = " + str(res))
This seems to clean up the output:
res is now ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
else, position 9 is not a power of 2, so res = ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
else, position 10 is not a power of 2, so res = ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
else, position 11 is not a power of 2, so res = ['1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1']
Final res value from function determineCheckBits: 11111000011
You're going to kick yourself. When you Ctrl-C to terminate the program, did you notice where it was looping?
The list of powers is [1, 2]
The powers of 2 that sum to 3 are
1
2
^CTraceback (most recent call last):
File "x.py", line 107, in <module>
arr = determineCheckBits(arr, r)
File "x.py", line 60, in determineCheckBits
while z <= y:
KeyboardInterrupt
If you'll look at that loop, you'll see that z never increments, so it loops forever. That's because line 63:
z <<= 1
is indented in one too many indents. If you fix that, it moves on. It does eventually get a different error, but that will be for another question.
EDIT
Other problems. In determineCheckBits, you are treating res as if it is a list of ints, trying to assign elements by index. It is not, it is a string. So, at the beginning, change:
res = data
to
res = list(data)
Towards the bottom, change
res[i] = 1
to
res[i] = '1'
and do the same 4 lines later with 0. Then, change the last 5 lines to:
else:
print("else, position " + str(i) + " is not a power of 2, so res = " + ''.join(res))
res = ''.join(res)
print("Final res value from function determineCheckBits: " + res)
return res
and I think you will have happiness.
Would you be upset if I did this in 28 lines?
data = '1100011'
bits = list(int(i) for i in data)
print(bits)
outbits = []
for i in range(1,99):
if bin(i).count('1') == 1:
outbits.append(0)
else:
outbits.append(bits.pop(0))
if not bits:
break
bits = outbits
print(bits)
ii = 1
while ii < len(bits):
sumx = 0
for i in range(len(bits)):
if i != ii-1 and (i+1) & ii:
sumx ^= bits[i]
bits[ii-1] = sumx
ii <<= 1
print(bits)

how many two-digit number ab that satisfy: ab = a² + b² + 1 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to figure out the above but I have come to a blank , this is what i have so far, this is the only information I was given for question in the title, I can not explain any further
# Challenge 4
n = int(input("N="))
# count how many two-digit number ab satisfy the equation
count = 0
for i in range( n ):
ab = int(input("Enter a two digit number:"))
def get_digit(number, ab):
return number // 10 ** ab % 10
a = get_digit(ab, 0)
b = get_digit(ab, 1)
if ab == (a ** 2) + (b ** 2) + 1:
count = count + 1
print( "Number of two-digit number ab that satisfy the equation=", count )
You can generate all two digit numbers by using range(10, 100) which will include 10...99. For any two digit number you can use integer division //10 to get the 10's digit, and modulus %10 to get the 1's digit.
for ab in range(10, 100):
a = ab // 10
b = ab % 10
if ab == a**2 + b**2 + 1:
print(ab)
Output
35
75
As a more concise list comprehension
>>> [ab for ab in range(10, 100) if ab == (ab//10)**2 + (ab%10)**2 + 1]
[35, 75]
And then obviously if you want the count you can just take the len of that list
>>> results = [ab for ab in range(10, 100) if ab == (ab//10)**2 + (ab%10)**2 + 1]
>>> len(results)
2
You could make a nested for loop where a and b are digits of the two-digit number a * 10 + b which ranges from 0 to 99.
count = 0
for a in range(1, 10):
for b in range(0, 10):
if a * 10 + b == a ** 2 + b ** 2 + 1:
print(a * 10 + b, ' ')
count += 1
print("\nNumber of two-digit number ab that satisfy the equation =", count)
Output:
35 75
Number of two-digit number ab that satisfy the equation = 2
Or alternatively by using a list comprehension you can pack those numbers in a list and then print.
out = [a * 10 + b for a in range(1, 10) for b in range (0, 10) if a * 10 + b == a ** 2 + b ** 2 + 1]
print(out)
print('Number of two-digit number ab that satisfy the equation =', len(out))
Output:
[35, 75]
Number of two-digit number ab that satisfy the equation = 2
Try this,
flag = 0
for val in range(10,100):
if val == (val // 10) ** 2 + (val % 10) ** 2 + 1:
flag += 1
print("Answer", flag)

Using set theory to find the shape area in Python

So I'm given the following diagram:
And I'm being asked to find the area of each polygon given n. The area is basically the sum of all blue squares since each square has an area of 1. So when n = 1, the area is one. When n = 2, the area is 5. Because of the relationship between each polygon, I know that I could knock this down using set theory.
n Area(n)
1 1
2 A(n-1) + (4 * (n-1)) = 5
3 A(n-1) + (4 * (n-1)) = 13
4 A(n-1) + (4 * (n-1)) = 25
5 A(n-1) + (4 * (n-1)) = 41
However, I didn't have as much luck trying to represent this in code:
def shapeArea(n):
prev_output = 0
output = 0
if n == 1:
output = 1
elif n > 1:
for i in range(n):
prev_output = n-1 + (4 * (n-1))
output = prev_output + (4 * (n-1))
return output
For example: For n = 2, I'm getting an output of 9 instead of 5.
You were close :-)
Here are the small fix-ups:
def shapeArea(n):
output = 1
for i in range(1, n):
output += 4 * i
return output
Running this:
for n in range(1, 6):
print(n, shapeArea(n))
Gives this output:
1 1
2 5
3 13
4 25
5 41
of course with Gauss's theorem the code would look like this:
def ShapeArea(n):
return 2*(n**2) - (2*n)+1
In a recursive solution, it is much simple from your logic.
def shape_area(n):
if n == 1:
return 1
return shape_area(n-1) + 4*(n-1)
You can use Gauss' trick to make a closed-form formula:
2*Area(n) =
1 + 4 + 8 + 12 + ... + 4(n-1)
+
1 + 4(n-1) + 4(n-2) + 4(n-3) + ... + 4
--------------------------------------------------
2 + 4n + 4n + 4n + ... + 4n
= (n-1)4n + 2
= 4n^2 - 4n + 2
So Area(n) = 2n2 - 2n + 1
def shape_area(n):
return sum([1] + [4*i for i in range(1, n)])

Nested Loop in Python

I'm trying to find the largest palindrome that is the product of two 3-digit numbers. My guest is that the palindrome will have the form abccba, so I will just loop over each digit and stop at the largest number that is the product of two 3-digit numbers.
This piece of code
def hasLargeDivisors(n):
"""
Function to determine if a number has two divisors
greater than 99
"""
d = 999
while n / d > 99 and n / d < 999 and d > 99:
if n % d is 0:
return True
d-=1
return False
def compisitePalindrome():
"""
Function to find the largest palindrome
that is the product of 2 three-digit numbers
"""
for a in reversed(xrange(1, 9)):
for b in reversed(xrange(0, 9)):
for c in reversed(xrange(0, 9)):
num = a*100001 + b*10010 + c*1100
if hasLargeDivisors(num):
return num
return 0
produces 888888 = 962 * 924, which is incorrect.
This code
def hasLargeDivisors(n):
"""
Function to determine if a number has two divisors
greater than 99
"""
d = 999
while n / d > 99 and n / d < 999 and d > 99:
if n % d is 0:
return True
d-=1
return False
def compisitePalindrome():
"""
Function to find the largest palindrome
that is the product of 2 three-digit numbers
"""
a = 9
for b in reversed(xrange(0, 9)):
for c in reversed(xrange(0, 9)):
num = a*100001 + b*10010 + c*1100
if hasLargeDivisors(num):
return num
return 0
produces 906609 = 993 * 913, which is correct.
I don't know where I went wrong.
xrange(1, 9) == (1, 2, 3, 4, 5, 6, 7, 8)
xrange(start, stop, step) generates all numbers from start to (but not including) stop, with a step of step.
xrange(5) == (0, 1, 2, 3, 4)
xrange(1, 5) == (1, 2, 3, 4)
xrange(1, 5, 2) == (1, 3)
You can do xrange(1, 10) to include 9 in the range as well.
There's only (approximately) half a million pairs of 3-digit numbers, so it's quicker and simpler to test them all.
def palindrome_3products():
for i in xrange(100, 1000):
for j in xrange(i, 1000):
if str(i * j) == str(i * j)[::-1]:
yield i * j, i, j
print max(palindrome_3products())

Categories