How to format file output into specific number of data columns? - python

I'm just asking a quick question on how to format how numbers are presented in a text file with however many columns I want.
ie.)
1 3 4
2 6 10
3 18 6
As of right now my text file is just writing a new line for ever iteration and I'm having trouble figuring out how to get it to right a new line after 3 iterations of the calculation.
for Number in range(1, 10001):
count = 0
for i in range(2, (Number // 2 + 1)):
if Number % i == 0:
count = count + 1
break
if count == 0 and Number != 1:
file.write(str(Number) + "\n")

You could track the count of numbers written to file, and each multiple of three, write a newline.
output_count = 0
for Number in range(1, 10001):
count = 0
for i in range(2, (Number // 2 + 1)):
if Number % i == 0:
count = count + 1
break
if count == 0 and Number != 1:
file.write(f'{Number} ')
output_count += 1
if output_count % 3 == 0:
file.write("\n")
Code Refactor
It is recommended to refactor the code into functions that tackle pieces of the problem, such as calculating primes versus input/output. For example, in Python 3, you could write the following:
from typing import List
def generate_primes(maximum: int) -> List[int]:
primes = []
for n in range(1, maximum):
count = 0
for i in range(2, (n // 2 + 1)):
if n % i == 0:
count = count + 1
break
if count == 0 and n != 1:
primes.append(n)
return primes
def write_to_file(filename: str, data: List[int], columns: int) -> None:
with open(filename, 'w') as file:
output_count = 0
for n in data:
output_count += 1
if output_count % columns == 0:
file.write(f"{n}\n")
else:
file.write(f"{n} ")
if __name__ == "__main__":
data = generate_primes(10001)
write_to_file("primes.txt", data, columns=3)
Output
2 3 5
7 11 13
17 19 23
29 31 37
41 43 47
53 59 61
67 71 73
79 83 89
...

Related

Check Modest number. How to include criteria where numLen<1 ---> return number cannot be split"

Here's the definition of Modest Number.
A number n is called modest if its digits can be separated into two numbers a and b such that n divided by b gives a as remainder.
For example, 2851111 is modest because divided by 1111 gives 285 as remainder.
Here's an example which I considered:
is_modest(21333) ➞ True
Combination 1: Left = 2 | Right = 1333 21333 % 1333 = 5 != Left
Combination 2: Left = 21 | Right = 333 21333 % 333 = 21 = Left
At least a combination satisfies the condition
Below is what I tried:
def isModest(num):
numStr = str(num)
numLen = len(numStr)
while numLen > 1:
for i in range(1, numLen):
rem = num % (int(numStr[i:])) # 5, 21, 15, 0
if rem == int(numStr[:i]):
return True
else:
return False
print(isModest(2036)) <br>
print(isModest(3412)) <br>
print(isModest(21333)) <br>
print(isModest(8)) #??? <br>
You don't need to use string manipulations. Dividing by powers of 10 will do it more efficiently
def isModest(N):
if N<10: return "cannot split"
p10 = 10
while p10 < N:
a,b = divmod(N,p10)
if b and N%b == a: return True
p10 *= 10
return False
for n in range(1,100):
if isModest(n) is True: print(n)
13
19
23
26
29
39
46
49
59
69
79
89

Why does program count one extra value (cycle "while")?

Why the program count one more value? For example, I give him N = 50. It gives out:
1
4
9
16
25
36
49
64
Code:
N = int(input())
n = 1
k = 1
while n < N:
n = k ** 2
print(n)
k = k + 1
As explained, you're checking n then changing n, you want to change n then check before continuing.
You can use the walrus operator to assign n and check it's value all in the while statement. (requires Python 3.8+)
N = int(input())
n = 1
k = 1
while (n := k**2) < N:
print(n)
k += 1
This essentially assigns n to k**2 then checks if that result is <N before continuing.
1
4
9
16
25
36
49
Your program outputs 1 4 9 16 25 36 49 64 if your input is 50 because the `while`` loop is checking the value before you increase it. Once in the loop, you increase it, calculate the square and then print.
If you want it to terminate, try setting calculating n as the last step in the loop:
N = int(input())
n = 1
k = 1
while n < N:
print(n)
k = k + 1
n = k ** 2
You're checking whether you reached the limit before you calculate the square and print it. So you're checking the previous value of n, not the one that's about to be printed.
Move the check inside the loop.
while True:
n = k ** 2
if n >= N:
break
print(n)
k += 1
The n < N is evaluated after you've changed (and printed) n.
n = 1
k = 1
N=50
while 1:
n = k ** 2
if n > N:
break
print(n)
k = k + 1
To fix this, break before you print, moving the evaluation inside the loop rather than after the last update of n
1
4
9
16
25
36
49
With the condition of your code, for example, when n = 49, The condition is fulfilled because 49 < 50 therefore it will continue to process the value and print the new one. But once n = 64 which is > 50, it stops. This is a possible solution:
N = int(input())
n = 1
k = 1
while True:
if n >= N:
break
n = k ** 2
print(n)
k = k + 1
This will continuously execute the code but once the condition is met that n >= N, it will stop executing.

A for loop to print dictionary items once without repeating the print function

I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and i'm not good at enlish.But i have a problem with this code.
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print('They are',n,end=' ')
The result of the code when ran comes out looking like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37
but i want it like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37
If you're completely determined not to use the print function more than once inside the loop, you could set a flag to determine whether to print the first two words. Like so:
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
first = 'They are '
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print(first + str(n), end=' ')
if len(first) > 0:
first = ''
The following solution may help you
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
num = [] # Create empty list
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
num.append(n)
# Write the print statement outside of the loop and use .join() function and for loop
#to print each element of the list look like the output you have posted
#
print('They are'," ".join(str(x) for x in num))
Output:
Displays prime numbers from 1 to N.
Please enter a value of n: 40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

Python. How do i count the number of divisors in nested for loop?

I have a code that generates triangular numbers, calculates the divisors for each triangular number and prints out 3 columns where the first column is the input numbers, the second column is the triangular numbers and the third column is the divisors of each triangular number. How can I count the number of divisors of each triangular number(count the numbers in the third column)?
for num in range(10):
triangle_number = num*(num+1)//2
print(num, end = ' ')
print(triangle_number, end = ' ')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
print()
Output looks like this:
0 0
1 1 1,
2 3 1,3,
3 6 1,2,3,6,
4 10 1,2,5,10,
5 15 1,3,5,15,
6 21 1,3,7,21,
7 28 1,2,4,7,14,28,
8 36 1,2,3,4,6,9,12,18,36,
9 45 1,3,5,9,15,45,
You can add a variable inside for loop and increment it when you get the divisor and print a the end.
for num in range(10):
count = 0
triangle_number = num*(num+1)//2
print(num, end = '\t')
print(triangle_number, end = '\t')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
count += 1
print("\t", count)
##Output:
##0 0 0
##1 1 1, 1
##2 3 1,3, 2
##3 6 1,2,3,6, 4
##4 10 1,2,5,10, 4
##5 15 1,3,5,15, 4
##6 21 1,3,7,21, 4
##7 28 1,2,4,7,14,28, 6
##8 36 1,2,3,4,6,9,12,18,36, 9
##9 45 1,3,5,9,15,45, 6
##Output order : input number, count of divisors divisors, triangular number
or you can create a list of divisors and measure length before printing.
for num in range(10):
divisors = []
triangle_number = num*(num+1)//2
print(num, end = '\t')
print(triangle_number, end = '\t')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
divisors.append(divisor)
print(len(divisors), "\t", ",".join(str(div )for div in divisors))
##Output:
##0 0 0
##1 1 1 1
##2 3 2 1,3
##3 6 4 1,2,3,6
##4 10 4 1,2,5,10
##5 15 4 1,3,5,15
##6 21 4 1,3,7,21
##7 28 6 1,2,4,7,14,28
##8 36 9 1,2,3,4,6,9,12,18,36
##9 45 6 1,3,5,9,15,45
##Output order : input number, triangular number, count of divisors divisors
You might replace your inner for loop using list comprehension and then just get length of that list using len function, that is replace:
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
with:
divisors = [divisor for divisor in range(1, triangle_number+1) if triangle_number%divisor == 0]
print(*divisors, sep=',', end=' ')
print(len(divisors), end='')
list comprehension is succint way of creating list which might be created via appending inside for loop, * (star operator) does unpacking, if you would have list x = [1, 2, 3] then print(*x) is equivalent of print(1, 2, 3) and so on.

logic errors with print the sum of all the numbers that are either multiple of three or five

I'm having some logic errors with my program. I've been trying to solve this for the last couple of hours. It's supposed to print the sum of all the numbers that are either multiple of three or five.
my output
1.)enter an integer number (0 to end): enter an integer number (0 to end):
2.)enter an integer number (0 to end): 3+ = 3
expected output
1.)enter an integer number (0 to end): 3 = 3
2.)enter an integer number (0 to end): 3+5 = 8
below is my code.
while True:
answer = ""
num = int(input("enter an integer number (0 to end): "))
end_answer = 0
if num == 0:
exit()
for i in range(1, num+1):
if i%3==0 or i%5==0 :
answer += str(i)
end_answer += i
if i != num and (i%3==0 or i%5==0):
answer += "+"
print(str(answer) + " = " + str(end_answer) )
I've seen similar answers for this just not in python specifically
The following (properly indented) code will give you what you need:
while True:
num = int(input('Enter an integer number (0 to end): '))
if num == 0: exit()
answer = ''
end_answer = 0
sep = ''
for i in range(1, num+1):
if i % 3 == 0 or i % 5 == 0 :
answer += sep + str(i)
sep = ' + '
end_answer += i
if end_answer > 0:
print(str(answer) + ' = ' + str(end_answer) )
Note that it uses a variable separator sep to more cleanly print the item you're working out. A sample run follows:
Enter an integer number (0 to end): 2
Enter an integer number (0 to end): 3
3 = 3
Enter an integer number (0 to end): 10
3 + 5 + 6 + 9 + 10 = 33
Enter an integer number (0 to end): 38
3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20 + 21 + 24 + 25 + 27 + 30 + 33 + 35 + 36 = 329
Enter an integer number (0 to end): 0
You can simplify your code a lot by using the sum builtin and f-strings for printed text formatting. This will likely be more efficient as well.
Code
from itertools import count
counter = count(1)
while True:
num = int(input(f'{next(counter)}). Enter an integer number (0 to end): '))
if num == 0:
break
nums = [x for x in range(1, num + 1) if x % 3 == 0 or x % 5 == 0]
print(f'{" + ".join(map(str, nums))} = {sum(nums)}')
Output
1). Enter an integer number (0 to end): 3
3 = 3
2). Enter an integer number (0 to end): 9
3 + 5 + 6 + 9 = 23
3). Enter an integer number (0 to end): 15
3 + 5 + 6 + 9 + 10 + 12 + 15 = 60
4). Enter an integer number (0 to end): 0

Categories