why compiler doesn't stop iterating while loop - python-3.x

I made a program to print pyramid using * with my own way but whenever i run my program on compiler the program gets executed and doesn't stop after the for loop ends its iteration,here's my program which i think should stop executing after 10 iterations.
a = " "
b = ""
for i in range(10):
a = a[:-1]
b = (b * i) + '*'
print('\n')
for k in range(i):
print("{}{}".format(a,b), end="")
i am expecting the output like this:
*
***
*****
*******
*********
***********
*************
***************

Your problem probably comes from your b assignation.
Let's calculate the length of b at step i (from 0 to 10) (b(n) = b(n-1)*index + 1)
b(0) = 0*0 + 1 = 1
b(1) = 1*1 + 1 = 2
b(2) = 2*2 + 1 = 5
b(3) = 5*3 + 1 = 16
And so on, we can see the length of b is going exponential, for instance, for index = 10, len(b) = 986410
This increasing string might make the compiler slowing down.
You might want to try this code which does not keep in memory the strings.
height = 10
for i in range(height):
print(' '*(height-i-1)+'*'*(2*i+1))
output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

Try this improved code instead:
a = " " # empty string to be attached at the front and back (length is 11)
for i in range(10): # height of pyramid
a = a[:-1] # make string a bit smaller to compensate for
b = '*' * (i*2 + 1) # the increasing amount of '*'s
print("{}{}{}".format(a, b, a)) # prints the pyramid
The len(a) should be the height of your pyramid plus the amount of padding wanted on the last row. For example:
*
***
*****
*******
There's 2 spaces left on the bottom row, and the height of the pyramid is 4. That means the length of a should be 6. Make a using a = ' '*(height + padding)

Related

Simpson's rule 3/8 for n intervals in Python

im trying to write a program that gives the integral approximation of e(x^2) between 0 and 1 based on this integral formula:
Formula
i've done this code so far but it keeps giving the wrong answer (Other methods gives 1.46 as an answer, this one gives 1.006).
I think that maybe there is a problem with the two for cycles that does the Riemman sum, or that there is a problem in the way i've wrote the formula. I also tried to re-write the formula in other ways but i had no success
Any kind of help is appreciated.
import math
import numpy as np
def f(x):
y = np.exp(x**2)
return y
a = float(input("¿Cual es el limite inferior? \n"))
b = float(input("¿Cual es el limite superior? \n"))
n = int(input("¿Cual es el numero de intervalos? "))
x = np.zeros([n+1])
y = np.zeros([n])
z = np.zeros([n])
h = (b-a)/n
print (h)
x[0] = a
x[n] = b
suma1 = 0
suma2 = 0
for i in np.arange(1,n):
x[i] = x[i-1] + h
suma1 = suma1 + f(x[i])
alfa = (x[i]-x[i-1])/3
for i in np.arange(0,n):
y[i] = (x[i-1]+ alfa)
suma2 = suma2 + f(y[i])
z[i] = y[i] + alfa
int3 = ((b-a)/(8*n)) * (f(x[0])+f(x[n]) + (3*(suma2+f(z[i]))) + (2*(suma1)))
print (int3)
I'm not a math major but I remember helping a friend with this rule for something about waterplane area for ships.
Here's an implementation based on Wikipedia's description of the Simpson's 3/8 rule:
# The input parameters
a, b, n = 0, 1, 10
# Divide the interval into 3*n sub-intervals
# and hence 3*n+1 endpoints
x = np.linspace(a,b,3*n+1)
y = f(x)
# The weight for each points
w = [1,3,3,1]
result = 0
for i in range(0, 3*n, 3):
# Calculate the area, 4 points at a time
result += (x[i+3] - x[i]) / 8 * (y[i:i+4] * w).sum()
# result = 1.4626525814387632
You can do it using numpy.vectorize (Based on this wikipedia post):
a, b, n = 0, 1, 10**6
h = (b-a) / n
x = np.linspace(0,n,n+1)*h + a
fv = np.vectorize(f)
(
3*h/8 * (
f(x[0]) +
3 * fv(x[np.mod(np.arange(len(x)), 3) != 0]).sum() + #skip every 3rd index
2 * fv(x[::3]).sum() + #get every 3rd index
f(x[-1])
)
)
#Output: 1.462654874404461
If you use numpy's built-in functions (which I think is always possible), performance will improve considerably:
a, b, n = 0, 1, 10**6
x = np.exp(np.square(np.linspace(0,n,n+1)*h + a))
(
3*h/8 * (
x[0] +
3 * x[np.mod(np.arange(len(x)), 3) != 0].sum()+
2 * x[::3].sum() +
x[-1]
)
)
#Output: 1.462654874404461

When appending a tuple to a list, I can append (a + b + c) or (a, b + c) or (a + b, c) but appending (a, b ,c) causes the program to refuse to run

Here's the code
def check_right_angle(a, b, c):
if a**2 + b**2 == c**2:
return True
return False
def mn_to_abc(m, n):
return m**2 - n**2, 2 * m * n, m**2 + n**2
list_solutions = []
for i in range(1001): #Getting all primitive triples using Euclid's formula <= 1000
list_solutions.append([])
if i == 0:
continue
for m in range(1, int(i/2) - 1):
n = int(i / (2 * m) - m)
if m > n and n > 0:
a, b, c = mn_to_abc(m, n)
if check_right_angle(a, b, c) and a + b + c == i:
list_solutions[i].append((a, b, c))
for item in list_solutions: #Getting the remaining triples by using the primitive triples
for abc in item:
for i in range(1, 85): # 85 since 3x + 4x + 5x = 1000 => x = 83.3333 = 84
try:
new_a = abc[0] * i
new_b = abc[1] * i
new_c = abc[2] * i
if new_a + new_b + new_c <= 1000:
list_solutions[new_a + new_b + new_c].append((new_a, new_b, new_c))
else:
break
except:
continue
print(len(list_solutions[120]))
print(list_solutions[120])
The situation is mostly explained in the title but this code refuses to run unless line 30 is replaced with either one of the following lines:
list_solutions[new_a + new_b + new_c].append((new_a+ new_b, new_c))
list_solutions[new_a + new_b + new_c].append((new_a+ new_b+ new_c))
list_solutions[new_a + new_b + new_c].append((new_a, new_b+ new_c))
I've even tried to append it as a list instead of a tuple but to no avail. Such a weird thing to run into.
Never mind fellas, just had an epiphany. Turns out adding to a list you're iterating is a terrible, terrible idea. Before line 30 I added this code:
if not (new_a, new_b, new_c) in list_solutions[new_a + new_b + new_c]:
You might have noticed that I'm still adding to that same list I'm iterating through, but for some reason, as long as the items in that list don't repeat themselves, everything is fine.
I would close this question now, but it's telling me I can only accept my own answer in 2 days.

Python(AI Constraint satisfaction problem) Fitting square and/or rectangular (2d) tiles onto a rectangular ground

I have to arrange and/or fit 2d tiles into a 2d square or rectangular plane with AI algorithm using python program. Each tile has a length and width. For example if a plane is 4x3 and set of tiles is
S={(2,3),(1,2),(2,2)}
these tiles can be rotated 90 degrees in order to fit the matrix.
input
first line contains length and width of the plane
second line number of tiles
and then the length,width of the subsequent tiles
but the inputs should be tab seperated
for eg
4 3
3
2 3
1 2
2 2
output
for eg
1 1 2 2
1 1 3 3
1 1 3 3
I have trouble solving this as i have to use only standard libraries in python no NumPy and no CSP library
~Edit 2`
my code so far I cant figure out how to add algorithm without csp library or to generate grid
from sys import stdin
a = stdin.readline()
x = a.split()
rectangular_plane = [[0] * int(x[0]) for i in range(int(x[1]))]
num_of_rectangles = stdin.readline()
r_widths = []
r_lengths= []
for l in range(int(num_of_rectangles)):
b = stdin.readline()
y = b.split()
r_lengths.insert(l,y[0])
r_widths.insert(l,y[1])
I've solved task with backtracking approach and without any non-standard modules.
Try it online!
import sys
nums = list(map(int, sys.stdin.read().split()))
pw, ph = nums[0:2]
ts = list(zip(nums[3::2], nums[4::2]))
assert len(ts) == nums[2]
if sum([e[0] * e[1] for e in ts]) != pw * ph:
print('Not possible!')
else:
def Solve(*, it = 0, p = None):
if p is None:
p = [[0] * pw for i in range(ph)]
if it >= len(ts):
for e0 in p:
for e1 in e0:
print(e1, end = ' ')
print()
return True
for tw, th in [(ts[it][0], ts[it][1]), (ts[it][1], ts[it][0])]:
zw = [0] * tw
ow = [it + 1] * tw
for i in range(ph - th + 1):
for j in range(pw - tw + 1):
if all(p[k][j : j + tw] == zw for k in range(i, i + th)):
for k in range(i, i + th):
p[k][j : j + tw] = ow
if Solve(it = it + 1, p = p):
return True
for k in range(i, i + th):
p[k][j : j + tw] = zw
return False
if not Solve():
print('Not possible!')
Example input:
4 3
3
2 3
1 2
2 2
Output:
1 1 2 2
1 1 3 3
1 1 3 3

I want to add two extremely large numbers in python which even bignum can't handle

I am new in python,I want to add two extremely large numbers in python which even bignum can't handle. I can take these two numbers as a string and then can calculate from the end and as like we used to do in old school addition process. we can take the carriage and add it to the next numbers and so on.
Please assist.
The question seemed interesting enough for a Christmas Day coding snack.
Here's my implementation using many of the builtins in Python.
reversed is used to iterate over the digit sequences from right to left, i.e. like we would when computing on paper
zip_longest "fills" in the sequences' ends with zeroes (as we would ignore digits on paper)
divmod computes the carried-forward value and the current digit in a single call.
The result is reversed, so it's once more reversed to be least-significant-digit-last, and stray zeroes on the left are removed using lstrip.
It does not handle negative numbers, though.
from itertools import zip_longest
def add(a, b):
out = []
a = [int(c) for c in str(a)]
b = [int(c) for c in str(b)]
carry = 0
for ca, cb in zip_longest(reversed(a), reversed(b), fillvalue=0):
carry, digit = divmod(ca + cb + carry, 10)
out.append(str(digit))
return "".join(reversed(out)).lstrip("0")
a = 9999 ** 29
b = 3725241 ** 9
assert add(a, b) == str(a + b)
I achieved that after 3 hours of work. :)
def add_func(num1,num2):
res_list = []
number1 = str(num1)
number2 = str(num2)
length1 = len(str(number1))
length2 = len(str(number2))
if(length1 > length2):
while(length1 > length2):
number2 = '0' + number2
length2 += 1
if(length2 > length1):
while(length2 > length1):
number1 = '0' + number1
length1 += 1
i = max(length1,length2)
carry = 0
while(i > 0):
if(int(number1[i-1]) + int(number2[i-1]) + carry > 9):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 1
if(i==1):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list[0]= result
elif(int(number1[i-1]) + int(number2[i-1]) > 9):
result = str(int(number1[i-1]) + int(number2[i-1]))
res_list.insert(0,(result[-1]))
carry = 1
else:
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 0
i -=1
final_output = ('').join(res_list)
return final_output
print(add_func(9999**29,3725241**9))

When approximating the value of pi with the leibniz formula

My question is: Why do these two programs provide different answers! Thank you in advance!
I created two programs that find the value of pi as close as possible based off of the user input for the total sum. However, I created two programs one that steps by 2 and one that steps by 4. I was wondering why the answers provided by the two codes are different.
Code that uses 2 step.
import math
total = 0
def main():
#input
n = int(input("How many numbers are we going to process: "))
#process
#initialize total
total = 0
#create the loop that runs via amount input
for i in range(0, n , 2):
total = total + ( 1 / ((i * 2) + 1)) - (1 / ((i * 2) + 3))
amount = total * 4
print(amount)
print("In comparison to pi the value is: ", (math.pi - amount))
main()
Code that uses 4 step
import math
total = 0
def main():
#input
n = int(input("How many numbers are we going to process: "))
#process
#initialize total
total = 0
#create the loop that runs via amount input
for i in range(0, n , 4):
total = total + ( 1 / ((i * 2) + 1)) - (1 / ((i * 2) + 3)) + (1/
((i * 2) + 5)) - (1/ ((i * 2) + 7))
amount = total * 4
print(amount)
print("In comparison to pi the value is: ", (math.pi - amount))
main()

Resources