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.
Related
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
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>
so i have some code that works perfectly without a function. But i want to change this inside a function, but it does not work properly.
For example, i have the end="". This doesn't work in a function, without using print.
I also have more than one print statements. When i turn these to return, they don't work. So could someone please help me change this code to work in a function?
Thanks!
My code
def underscore_hash_staircase(number):
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
print(end=" ".replace(" ", "_"))
k = k - 1
for j in range(0, i + 1):
print("#", end="")
print("")
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
print('', end=' '.replace(" ", "_"))
j -= 1
k = 1
while k <= i:
print('#', end='')
k += 1
print()
i -= 1
print(underscore_hash_staircase(8))
so the code above doesn't work properly in a function, without the print statements. Please let me know how to get this working in a function without the print statements. Using returns. It should be exact output as what is being returned in this not function-working code.
Thanks again!
Since a function can only return one value, instead of printing, you want to add to a variable to return instead of printing. Try:
def underscore_hash_staircase(number):
returnValue = "" # start as empty string
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
returnValue += "_"
k = k - 1
for j in range(0, i + 1):
returnValue += "#"
returnValue += "\n" # adding a new line
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
returnValue += "_"
j -= 1
k = 1
while k <= i:
returnValue += "#"
k += 1
returnValue += "\n"
i -= 1
print(underscore_hash_staircase(8))
Edit: missed a print when replacing
The function should append to a string instead of printing, and then return the string. Append \n to add a newline.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
result += "_"
k = k - 1
for j in range(0, i + 1):
result += "#"
result += "\n"
else:
number = -number
i = number
while i >= 1:
j = number
while j > i:
result += "_"
j -= 1
k = 1
while k <= i:
result += "#"
k += 1
result += "\n"
i -= 1
return result
print(underscore_hash_staircase(8))
You also don't need all those inner loops. You can repeat a string by multiplying it.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(1, number + 1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
else:
number = -number
for i in range(number, 0, -1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
return result
print(underscore_hash_staircase(8))
print(underscore_hash_staircase(-8))
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]
import heapq
f = [int(x) for x in input().split()]
T=[]
for i in range(len(f)):
heapq.heappush(T,(f[i],str(i)))
while len(T)>1:
a=heapq.heappop(T)
b=heapq.heappop(T)
heapq.heappush(T,(a[0]+b[0],'('+a[1]+' '+b[1]+')' ))
temp = 0
cost = 0
index= 0
for i in T[0][1]:
if i == "(":
temp = temp + 1
elif i == ")":
temp = temp - 1
elif i == " ":
continue
else:
cost = cost + (temp*f[int(i)])
if i != "(" or ")" or " ":
index*=10
index+f[int(i)]
print(cost)
I am trying to make Huffman coding prefix-free cost code. my code works well, but when inputs are more than 9, it makes an error. I found when f[int(i)] is more than 10, it makes an error because the code reads it as 1 and 0. how can I fix this error?
> 43 13 12 16 9 7
230#correct
> 13 5 11 7 15 1 14 20 10 12 9
425#wrong
Update
the cost can be calculate while building the huffman tree.
import heapq
f = [int(x) for x in input().split()]
T=[]
for i in range(len(f)):
heapq.heappush(T,(f[i],0,str(i)))
while len(T)>1:
a=heapq.heappop(T)
b=heapq.heappop(T)
heapq.heappush(T,(a[0]+b[0],a[0]+b[0]+a[1]+b[1],'('+a[2]+' '+b[2]+')' ))
cost=heapq.heappop(T)[1]
print(cost)
Think "i" walk to the arrow, int(i) is 1, but the expect value is 10.
[(117, '(((2 9) (((5 1) 3) 0)) ((6 4) ((10 8) 7)))')]
^
You can check the code, it store the index value and caculate the cost after the walk through the full index string.
import heapq
f = [int(x) for x in input().split()]
T=[]
for i in range(len(f)):
heapq.heappush(T,(f[i],str(i)))
while len(T)>1:
a=heapq.heappop(T)
b=heapq.heappop(T)
heapq.heappush(T,(a[0]+b[0],'('+a[1]+' '+b[1]+')' ))
temp = 0
cost = 0
index= -1
for i in T[0][1]:
if i == "(":
temp = temp + 1
elif i == ")":
if index != -1:
cost = cost + (temp*f[index])
index = -1
temp = temp - 1
elif i == " ":
if index != -1:
cost = cost + (temp*f[index])
index = -1
else:
if index == -1:
index = int(i)
else:
index = 10 * index + int(i)
print(cost)