How can I save integers displayed in the console? - python

I created a Python program that calculates the digits of pi and displays them in the console as the calculation is running. Eventually, it starts deleting numbers that were first displayed. How could I save the numbers as they're being displayed? Here is the code:
def calcPi(limit):
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
yield n
if counter == 0:
yield '.'
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
def main():
pi_digits = calcPi(int(input(
"Enter the number of decimals to calculate to: ")))
i = 0
for d in pi_digits:
print(d, end='')
i += 1
if i == 55:
print("")
i = 0
if __name__ == '__main__':
main()

You can write to a txt file instead of printing. For example:
with open("output.txt", "a") as f:
instead of printing,
print(d, end='')
do
f.write(str(d))
and instead of printing,
print('')
do
f.write('\n')

On most UNIX operating systems you can use the tee command:
python calculate_pi.py | tee output.txt
This will let you see the output in your terminal and write it to the file at the same time.

Related

How would this be written without using yield?

I've tried and failed multiple times trying to replace yield, but I don't seem to be successful, the goal is to have the same function, without yield.
def calcPi(limit): # Generator function
"""
Prints out the digits of PI
until it reaches the given limit
"""
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if counter == 0:
yield '.'
# end
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
Added the full function as people were asking for it in the comments,
Just define a list and collect the digits:
def calcPi(limit): # Generator function
"""
Collects the digits of PI
until it reaches the given limit
"""
pi = []
...
while ...:
...
# yield n
pi.append(n)
...
#break
return pi

how to print two Sticking diamonds in python

I would like to write a python program to print the above shape( I am new to python)
but I have write the program of single diamond and now I have a problem to solve this,
would u guide to find the algorithm?
* *
*** ***
**********
*** ***
* *
this is the single diamond:
def Diamond(rows):
n = 0
for i in range(1, rows + 1):
for j in range (1, (rows - i) + 1):
print(end = " ")
while n != (2 * i - 1):
print("*", end = "")
n = n + 1
n = 0
print()
k = 1
n = 1
for i in range(1, rows):
for j in range (1, k + 1):
print(end = " ")
k = k + 1
while n <= (2 * (rows - i) - 1):
print("*", end = "")
n = n + 1
n = 1
print()
rows = int(input())
Diamond(rows)
I was bored, here you go.
In [36]: def print_diamonds(width, ds):
...: r = width//2
...: for i in range(-r, r+1):
...: print((' '*(abs(i)) + '*'*((r-abs(i))*2+1) + ' '*(abs(i)))*ds)
...:
In [37]: print_diamonds(5, 2)
* *
*** ***
**********
*** ***
* *
Your question is vague but here is a function for a single diamond per line. I'm not sure what do you expect. Be mor explicite.
vect = ('*', '***', '*****', '***', '*')
def method():
for i in range(0,5):
print(abs((2-i))*" ",vect[i])

While Loop not functioning properly

I am testing a simple linear diophantine equations code. Here is the code:
a = 3
b = 4
n = 67
i = 0
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
i = i + 1
else:
print("No possible solution!")
break
When the code is run, it is able to find the possible x and y in this equation (which is fine). But, what I can't figure out is why is the print "No Possible solution!" is getting printed together with the answer. The else block is suppose to appear only if a solution is not possible e.g a = 3, b = 4 and n = 2.
Any advice will be appreciated.
print("No possible solution!") is inside the else case so it will execute regardless of whether any solutions were found or not.
Here is one way to fix it where a boolean variable keeps track of whether a solution was found or not and prints the message based on the state of that variable:
a = 3
b = 4
n = 2
i = 0
solution_found = False
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
solution_found = True
i = i + 1
else:
break
if not solution_found:
print("No possible solution!")
Use flag to identify solution is available or not.
a = 3
b = 4
n = 67
i = 0
isSolutionAvailable=False
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
isSolutionAvailable=True
i = i + 1
else:
break
if(not(isSolutionAvailable)):
print("No possible solution!")

How to print a triangle in python?

I want to make a function to print triangle like the following picture. User can insert the row number of the triangle. The total lenght of first row is must an odd.
I try to use below code :
def triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = 5
triangle(n)
Here is the expected output image :
and here is my actual output image :
but I can't remove the star middle star. And it's not Upside - Down Triangle
You could try a different way.
def triangle(n) :
for i in range(1,n+1) :
for j in range(1,i) :
print (" ",end="")
for j in range(1,(n * 2 - (2 * i - 1))
+1) :
if (i == 1 or j == 1 or
j == (n * 2 - (2 * i - 1))) :
print ("*", end="")
else :
print(" ", end="")
print ("")
n = 5
triangle(n)
Not sure how cool implementation is this but it gives results:
def triangle(n):
print(' '.join(['*']*(n+2)))
s = int((n/2)+1)
for i in range(s):
star_list = [' ']*(n+2)
star_list[-i-2] = ' *'
star_list[i+1] = '*'
print(''.join(star_list))
n = 5
triangle(n)
Output:
* * * * * * *
* *
* *
*
for n = 7:
* * * * * * * * *
* *
* *
* *
*
I would try a recursive solution where you call the printTriangle() function. This way, it will print the point first and move it's way down the call stack.

Printing empty Pyramid

I want to write a program that prints this output:
*
* *
* *
* *
*
But it prints this instead:
*
* *
* * *
* * * *
* * * * *
Suppose n = 5 is the input from the user, then the first star should be in the centre, and the ending star as well, so I can divide the input number by 2 to get the position of the first and the last star.
For the rest of the stars I am not understanding how to make it so that if one star is above then the next star should not be below it.
def Empty_triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
Empty_triangle(n)
How about this sort of thing?
print("\n".join([" "*(n-2-i)+"*"+" "*(2*i-1)+("*"if i>0 else"") for i in list(range(n-1))+[0]]))
Which, for example, for n=5, gives this output:
*
* *
* *
* *
*
Is this the kind of thing you had in mind?
Here's a less code-golfish version
def Empty_triangle(n):
for i in list(range(n-1))+[0]: #i.e. [0,1,2,3,4,0] so the last line is the same as the first
line = ""
leadingSpaces = n-2-i
line += " "*leadingSpaces
line += "*"
if i != 0:
middleSpaces = 2*i-1
line += " "*middleSpaces
line += "*"
print(line)
# Driver Code
n = 5
Empty_triangle(n)

Categories

Resources