Add to polynomials - python

In this code there are four test cases. Three test cases are camed successfully but 4th test case was not getting expected output. Please help me.
I got 0x^3 as output in 4th test case but expected output is 0
Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
Output
Print the addition of polynomials A and B.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.Explanation
We need all test cases can be came when code was run. I want exact outputs for all test cases
Here is the question and test case inputs and outputs in the below url link
https://drive.google.com/file/d/1DhE2akiG_pX_Q_EoKaEY9EapSgz3xWhY/view?usp=sharing
def check_polinom(polinom):
checked = []
while polinom:
tmp = polinom.pop(0)
if polinom:
for i in range(len(polinom)-1, -1, -1):
if polinom[i][0] == tmp[0]:
tmp[1] += polinom[i][1]
polinom.pop(i)
checked.append(tmp)
return checked
def add_polinoms(pol_1, pol_2):
added = []
while pol_1 or pol_2:
if pol_1:
tmp = pol_1.pop(0)
for i in range(len(pol_2)):
if pol_2[i][0] == tmp[0]:
tmp[1] += pol_2[i][1]
pol_2.pop(i)
break
else:
tmp = pol_2.pop(0)
added.append(tmp)
added.sort(reverse=True)
return(added)
def print_polinom(polinom):
s = ''
if polinom:
if polinom[0][1] < 0:
s += '-'
polinom[0][1] = -polinom[0][1]
if polinom[0][1] == 1:
if polinom[0][0] == 0:
s += str(polinom[0][1])
elif polinom[0][0] == 1:
s += 'x'
else:
s += 'x^' + str(polinom[0][0])
else:
if polinom[0][0] == 1:
s += str(polinom[0][1]) + 'x'
elif polinom[0][0] == 0:
s += str(polinom[0][1])
else:
s += str(polinom[0][1]) + 'x^' + str(polinom[0][0])
polinom.pop(0)
for el in polinom:
if el[1] == 0:
continue
elif el[1] < 0:
s += ' - '
el[1] = -el[1]
else:
s += ' + '
if el[1] == 1:
if el[0] == 0:
s += str(el[1])
elif el[0] == 1:
s += 'x'
else:
s += 'x^' + str(el[0])
else:
if el[0] == 1:
s += str(el[1]) + 'x'
elif el[0] == 0:
s += str(el[1])
else:
s += str(el[1]) + 'x^' + str(el[0])
print(s)
def input_data():
while True:
try:
n = int(input())
break
except:
print('enter an integer N')
continue
a = list()
i = 1
while n > i-1:
try:
tmp = list(map(int,(input()).split()))
if len(tmp) != 2:
print('enter two space separated integers')
continue
a.append(tmp)
i += 1
except:
print('enter two space separated integers')
return a
a = check_polinom(input_data())
b = check_polinom(input_data())
c = add_polinoms(a,b)
print_polinom(c)

It seems that you code does not clean up 0 coefficients. An additional phase should be added to your processing. Once you have the final coefficients of your polinomial, you should have two adjustments. You have already described one, that turns items with coefficient 1 from the form 1x to simply x. Another one is when you turn 0x to nothing. Then you only have to be careful to output something, so you should not turn every term into nothing. That is why there is a description to represent it as 0.
The easiset way to make this work would thus be:
Add a function to check if a polinomial has all zero coefficients: is_zero_polinom
Do something like this in print_polinom:
if is_zero_polinom(polinom):
print('0')
return
<here comes the current code>

Related

What is logic behind runtime of programs?

Why do just writing the code in different order or style, changes the overall runtime?
For eg:
Why is result += "1" is more faster than result = "1" + result ?
More detailed example:
After writing a successful program for this Leetcode problem - Add Binary
here I have 2 code snippets both SAME, but a very subtle difference.
CODE 1
def addBinary(a, b):
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ""
carry = 0
for i in range(len(a)-1, -1, -1):
x = int(a[i])
y = int(b[i])
_sum = x + y + carry
if _sum == 3:
result += "1"
carry = 1
elif _sum == 2:
result += "0"
carry = 1
elif _sum == 1:
result += "1"
carry = 0
else:
result += "0"
carry = 0
if carry == 1:
result += "1"
return result[::-1]
CODE 2
def addBinary(a, b):
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ""
carry = 0
for i in range(len(a)-1, -1, -1):
x = int(a[i])
y = int(b[i])
_sum = x + y + carry
if _sum == 3:
result = "1" + result
carry = 1
elif _sum == 2:
result = "0" + result
carry = 1
elif _sum == 1:
result = "1" + result
carry = 0
else:
result = "0" + result
carry = 0
if carry == 1:
result += "1"
return result
The runtime for CODE 1 is 16 ms, and the runtime for CODE 2 is 47 ms. Why?
Adding characters to the end is optimised internally to reuse the same string (array of characters) in memory. Adding at the beginning requires creating a new string, with the position of each character shifted.

fictitious variable in bool function

I have a task to make a program that find the fictitious variables in bool function(the bool function has a form like 010101010..).
import itertools
a = 0
fict =0
print("How many variables:")
args = int(input())
while True:
print('The function:')
func = input()
if 2**args == len(func):
break
for i in itertools.product('01', repeat=args):
print(' '.join(i) + ' ' + func[a])
print('-----------')
fict += int(func[a])
a+=1
matr = list(func)
b = None
iter = 2
check = 0
if fict % 2 != 0:
print("There is no fictitious variables")
if fict % 2 == 0:
for k in range(args):
for s in range(2**check):
if matr[:] == matr[:]:
check+=1
Algorithm for recognizing a fictitious variable from a truth table.
For the variable x1, the halves of the column of the function values ​​are compared: the upper and lower ones, since it is in the upper half that x1 = 0, and in the lower half, x1 = 1, if they coincide, then the variable x1 is fictitious;
for the variable x2, the column quarters in each half are compared, since it is in the upper quarters that x2 = 0, and in the lower quarters x2 = 1, if the quarters in each half coincide, then the variable x2 is fictitious;
and so on (quarters are followed by 1/8, 1/16, ...).
And I dont understand how to do this algorithm in python or maybe there is a lot easier algorithms.
import itertools
a = 0
fict =0
print("How many variables:")
args = int(input())
while True:
print('The function:')
func = input()
if 2**args == len(func):
break
for i in itertools.product('01', repeat=args):
print(' '.join(i) + ' ' + func[a])
print('-----------')
fict += int(func[a])
a+=1
matr = list(func)
b = None
iter = 1
check = 0
if fict % 2 != 0:
print("There is no fictitious variables")
if fict % 2 == 0:
for k in range(args):
for s in range(2**check):
if matr[:int((2**args) / 2**iter)] == matr[int((2**args) / 2**iter ) : int(((2**args) / 2**iter) + (2**args) / 2**iter)]:
del matr[:int(((2**args) / 2**iter) + (2**args) / 2**iter)]
if len(matr) == 0:
print('Fictitious' + ' ' + str(k+1))
check += 1
iter += 1
matr = list(func)
It works

Writing a "Chessboard" function in Python that prints out requested length of binary

I have an assignment for my Python course that I'm struggling with.
We are supposed to make a function that prints out binary as follows:
If the input is:
chessboard(3)
It should print out:
101
010
101
And so forth..
Its a "simple" program but I'm really new to coding.
I can produce a while loop that writes out the correct length and amount of lines but I'm struggling to produce variation between the lines.
This is what I have come up with so far:
def chessboard(n):
height = n
length = n
while height > 0:
while length > 0:
print("1", end="")
length -= 1
if length > 0:
print("0", end="")
length -= 1
height -= 1
if length == 0:
break
else:
print()
length = n
With the input:
chessboard(3)
It prints out:
101
101
101
Could someone help me figure out how I could start every other line with zero instead of one?
As I understand it, it is simple :
print("stackoverflow")
def chessboard(n):
finalSentence1 = ""
finalSentence2 = ""
for i in range(n): #we add 0 and 1 as much as we have n
if i%2 == 0: #
finalSentence1 += "1"
finalSentence2 += "0"
else:
finalSentence1 += "0"
finalSentence2 += "1"
for i in range(n): #we print as much as we have n
if i%2 == 0:
print(finalSentence1)
else:
print(finalSentence2)
chessboard(3)
returns :
stackoverflow
101
010
101
I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
def chessboard(x):
i = 0
while i < x:
if i % 2 == 0:
row = "10"*x
else:
row = "01"*x
print(row[0:x])
i += 1

Loops and Collatz Conjecture

I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :
start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))
def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'
def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break
def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after
def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)
print('Biggest Steps is :' + str(biggest_steps))
compute_collatz(how_many, start_num)
this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks
Don't read my code until you have tried it yourself.
Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.
.
def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_
print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(x)
print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
you didn't save your biggest_steps and compared always the last 2 only.
I would suggest following change.
def compute_collatz(n_times, collatz_number):
biggest_steps = 0
for _ in range(n_times):
steps = collatz(collatz_number)
if steps > biggest_steps:
biggest_steps = steps
collatz_number += 1
print('Biggest Steps is :' + str(biggest_steps))

Convert integers to binary, need to remove leading zero

I wrote a program to convert an integer to binary without using bin(). However, when executed, this function adds a leading zero.
def decimalToBinary(n):
def helper(n):
if n == 0:
return '0'
else:
if n%2 == 1:
binaryDigit = '1'
else:
binaryDigit = '0'
return helper(n//2) + binaryDigit
helper(n)
print(helper(n))
Output:
>>> decimalToBinary(100)
01100100
How can I change this so that when 100 is input, the output is 1100100, rather than 01100100?
Use empty string in if n == 0: return "" to skip this zero.
Only 0 needs "leading zero" so you have to use extra if to recognize this value and return 0
def decimalToBinary(n):
def helper(n):
if n == 0:
return '' # <- empty string
else:
if n%2 == 1:
binaryDigit = '1'
else:
binaryDigit = '0'
return helper(n//2) + binaryDigit
if n == 0:
result = '0' # <- "leading zero" only for `n == 0`
else:
result = helper(n)
print(result)
# --- test ---
for x in range(16):
decimalToBinary(x)
My suggestion would be
print(str(helper(n)).lstrip("0"))
or
print(str(helper(n))[1:])
unless helper(n) already returns a string, in this case remove str() in the examples.
Use some kind of trim function.
I believe in python you will find something similar to this:
trimStart("0") // example from C#
This is primitive method but will work for sure :)
Something I found somewhere, a long time ago in a galaxy far away:
n = 100
b = ''
while n > 0:
b = str(n % 2) + b
n >>= 1
print(b) # 1100100

Categories