I have this code:
def floyd(n):
count = 1
string = ""
for i in range(1,n+2):
for j in range(1,i):
string = string + " " + str(count)
count = count + 1
print(string)
string = ""
print floyd(6)
It prints:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
But I want it to look like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Will you help me figure out how to do so?
Python strings actually have a built-in center() method that can do that for you.
print(string.center(total_width))
You can set up total_width in advance with:
total_width = -1
for i in xrange(0, n):
total_width += 1 + len(str((n + n * n) / 2 - i))
Or
total_width = sum(1 + len(str((n + n * n) / 2 - i)) for i in xrange(0, n)) - 1
That is, the sum of the lengths of the string representations of the numbers in the same row as the nth triangle number (n² + n) ÷ 2.
Here’s a demo!
Using n you can find the last row first, the last number is (n**2 + n)/2, so the first number on last line is ((n**2 + n)/2) - (n-1), now last row is can be created using str.join and a list comprehension:
x = ((n**2 + n)/2)
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1))
Now we can use the width of this line in string formatting to center other lines properly.
Code:
from itertools import count
def floyd(n):
x = ((n**2 + n)/2)
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1))
width = len(last_row)
c = count(1)
for x in xrange(1, n):
line = ' '.join(str(next(c)) for _ in xrange(x))
print "{:^{}}".format(line, width)
print last_row
Demo:
>>> floyd(6)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
>>> floyd(8)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
def FloydT(n):
num=0
row=""
for i in range(1,n+1):
for j in range(1,i+1):
num+=1
row+=str(num)+" "
print(str.center(row,3*n)) # this line will do what you want
row=""
Related
#Print the user board
s = ''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += '\n'
print(dedent(s))
queens = list(map(int, input("Queens: ").split()))
I keep getting an error from my testcase environment of a last blank line before proceeding to the queens input below. What can I approach to fix
I have tried cleandoc from textwrap and while it works, it disrupts every required spacing and new distinctive lines for z from the "s" string which is a perfect 8 by 8 from 0 to 63.
Creating the right way instead of removing things after is easier:
from itertools import count
import toolz
n = 8
start_value = 0
counter = count(start_value)
rows = [" ".join(f"{num:2}" for num in toolz.take(n, counter)) for _ in range(n)]
print("\n".join(rows))
The itertools.count creates an iterable counter that gives the next value every time you want. Here the take function will get 8 items each time.
If you do not want the initial space, you'd better use join, which only adds the separator between consecutive items:
s = '\n'.join(' '.join('{:2d}'.format(i * n + j)
for j in range(n))
for i in range(n))
print(s)
gives as expected:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
Im currently in college and I have an assignment that involves multiplying the primes and non primes below 45, so that their product doesn't go over 45. The language is python and I have tried doing for loops and checking for prime and not prime with modulus but I don't know where to go from there. (can't utilize arrays or anything related only loops, while else, elif etc.)
for num in range (1, 45):
if num > 1:
for num2 in range(2, 45):
if (num%num2) == 0:
n = num2
print(n, 'is Prime')
if num * num2 < 45:
print('Number ', num, '*', num2, '=', num*num2)
What exactly im trying to achieve is to first find all the prime numbers, then multiply them by all the non primes. Those primes and non primes are in the range of 1 - 45. Then, I Have to multiply them and their product has to be less than 45 then print that.
UPDATE: So I tried Thanh Tùng Nguyễn's program which is very well built, but I Can't utilize functions since I haven't been taught that (aka would be weird), what I tried to do is simply take what the function is and tried to just implement it into the loops themselves setting n as a boolean value, but my print doesn't amount to anything and I can't catch what's happening. The terminal just stays completely empty. My guess is on the last 'if not' statement, where I have probably written it wrong because I can't understand it myself why it isn't working when im treating it the same as a function through the entire block.
Here's what I got:
from math import sqrt
for num1 in range (2, 46):
if num1 <= 1:
n = False
for i in range (2, int(sqrt(num1))):
if num1%i == 0:
n = False
n = True
if n == True:
for num2 in range (1, 46):
if num2 <= 1:
n = False
for j in range (2, int(sqrt(num2))):
if num2%j == 0:
n = False
n = True
if not n == True:
if num1 * num2 < 45:
print(num1, '*', num2, '=', num1*num2)
You could create a prime-number check function like this:
from math import sqrt
def checkPrime(num):
if num <= 1:
return False
for i in range(2, int(sqrt(num))+1):
if num % i == 0:
return False
return True
Note that you can just check from 2 to √n to optimize it. From there, just find all prime numbers below 45 and multiply it with a non-prime number:
from math import sqrt
def checkPrime(num):
if num <= 1:
return False
for i in range(2, int(sqrt(num))+1):
if num % i == 0:
return False
return True
for n in range(2, 45+1):
if checkPrime(n):
for j in range(1, 45+1):
if not checkPrime(j):
if n * j < 45:
print(n, " * ", j, " = ", n*j)
Output:
2 * 1 = 2
2 * 4 = 8
2 * 6 = 12
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
2 * 12 = 24
2 * 14 = 28
2 * 15 = 30
2 * 16 = 32
2 * 18 = 36
2 * 20 = 40
2 * 21 = 42
2 * 22 = 44
3 * 1 = 3
3 * 4 = 12
3 * 6 = 18
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
3 * 12 = 36
3 * 14 = 42
5 * 1 = 5
5 * 4 = 20
5 * 6 = 30
5 * 8 = 40
7 * 1 = 7
7 * 4 = 28
7 * 6 = 42
11 * 1 = 11
11 * 4 = 44
13 * 1 = 13
17 * 1 = 17
19 * 1 = 19
23 * 1 = 23
29 * 1 = 29
31 * 1 = 31
37 * 1 = 37
41 * 1 = 41
43 * 1 = 43
If I understand correctly, you need to multiply primes with non-primes. This means that the products will be formed of 3 or more primes.
To have 3 primes in the product, you can have 2 at most 5 times. You can have 3 at most 3 times, 5 at most twice, 7/11 no more than once.
So you only need to take into account 2, 3, 5, 7 and 11 as primes and combine them in sets of 3 or more without going over 45:
You could nest 5 for-loops for the number of 2s, 3s, 5s, 7s and 11s in the product.
For example:
for p2 in range(7):
for p3 in range(4):
for p5 in range(3):
for p7 in range(2):
for p11 in range(2):
prod = 2**p2 * 3**p3 * 5**p5 * 7**p7 * 11**p11
if prod > 45 : continue
if p2+p3+p5+p7+p11 < 3: continue
if p2: print(2,'x',prod//2,'=',prod)
if p3: print(3,'x',prod//3,'=',prod)
if p5: print(5,'x',prod//5,'=',prod)
if p7: print(7,'x',prod//7,'=',prod)
if p11: print(11,'x',prod//11,'=',prod)
Output:
3 x 15 = 45
5 x 9 = 45
3 x 9 = 27
2 x 21 = 42
3 x 14 = 42
7 x 6 = 42
2 x 15 = 30
3 x 10 = 30
5 x 6 = 30
2 x 9 = 18
3 x 6 = 18
2 x 22 = 44
11 x 4 = 44
2 x 14 = 28
7 x 4 = 28
2 x 10 = 20
5 x 4 = 20
2 x 6 = 12
3 x 4 = 12
2 x 18 = 36
3 x 12 = 36
2 x 4 = 8
2 x 20 = 40
5 x 8 = 40
2 x 12 = 24
3 x 8 = 24
2 x 8 = 16
2 x 16 = 32à
You can also do it the other way around, by counting the primes that form each number up to 45 and, if there are 3 or more primes, print the ones that are part of the number as you go:
for prod in range(8,46):
primeCount = 0
rest = prod
for prime in range(2,12):
while rest and rest % prime == 0:
primeCount += 1
rest = rest//prime
if primeCount<3: continue
if prod%2==0: print(prod,'=',2,'x',prod//2)
if prod%3==0: print(prod,'=',3,'x',prod//3)
if prod%5==0: print(prod,'=',5,'x',prod//5)
if prod%7==0: print(prod,'=',7,'x',prod//7)
if prod%11==0: print(prod,'=',11,'x',prod//11)
Note that, even though I'm dividing by non=primes in the counting loop, only primes will actually be counted because, as the rest is reduced, multiples of previous primes will no longer divide the rest evenly.
Output:
8 = 2 x 4
12 = 2 x 6
12 = 3 x 4
16 = 2 x 8
18 = 2 x 9
18 = 3 x 6
20 = 2 x 10
20 = 5 x 4
24 = 2 x 12
24 = 3 x 8
27 = 3 x 9
28 = 2 x 14
28 = 7 x 4
30 = 2 x 15
30 = 3 x 10
30 = 5 x 6
32 = 2 x 16
36 = 2 x 18
36 = 3 x 12
40 = 2 x 20
40 = 5 x 8
42 = 2 x 21
42 = 3 x 14
42 = 7 x 6
44 = 2 x 22
44 = 11 x 4
45 = 3 x 15
45 = 5 x 9
In this Program I need to rotate the matrix by one element in clockwise direction.I had done with the code but I have a problem with removing the newlione in the the last row in the given Matrix. In this Program the user has to give the input. The code is
def rotate(m):
if not len(m):
return
top=0
bottom=len(m)-1
left=0
right=len(m[0])-1
while(left<right and top < bottom):
prev=m[top+1][left]
for i in range(left,right+1):
curr=m[top][i]
m[top][i]=prev
prev=curr
top+=1
for i in range(top,bottom+1):
curr=m[i][right]
m[i][right]=prev
prev=curr
right-=1
for i in range(right,left-1,-1):
curr=m[bottom][i]
m[bottom][i]=prev
prev=curr
bottom-=1
for i in range(bottom,top-1,-1):
curr=m[i][left]
m[i][left]=prev
prev=curr
left+=1
return m
def printMatrix(m):
for row in m:
print(' '.join(str(n) for n in row))
n = int(input())
m = []
for i in range(1,n+1):
l = list(map(int, input ().split ()))
m.append(l)
marix=rotate(m)
printMatrix(m)
The Test Case is given Below
Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Expected Output:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12
Actual Output Which i get:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12\n
This is just an issue with your printMatrix() function, print() by defaults adds a newline. You could replace it with below to eliminate the last newline (though I'm not sure why this is so critical):
def printMatrix(m):
print('\n'.join(' '.join(str(n) for n in row) for row in m), end='')
I'm not sure how to do this. I know how to print a square shape by prompting for row and col, but don't quite understand how to only prompt for height and print an array of even numbers.
col = eval(input("Enter the number of columns: "))
row = eval(input("Enter the number of rows: "))
for j in range(row):
for i in range(col):
print("*", end=" ")
print()
this is how I would set up printing a square of asterisks, but how would I do this while only prompting for height and printing out even numbers? For example, if my height is "3", it should print out an array that looks like this:
0 2 4
6 8 10
12 14 16
Using next() on an iterator of the numbers:
h = 3
ns = iter(range(0,h**2*2,2))
for r in range(h):
for c in range(h):
print(next(ns), end='\t')
print()
which gives:
0 2 4
6 8 10
12 14 16
Using slicing and str.join:
h = 4
ns = list(range(0,h**2*2,2))
for r in range(0,len(ns),h):
print(" ".join(str(c) + "\t" for c in ns[r:r+h]))
which gives:
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30
Here is an approach by making a nested list and printing it out using a formatting function. Can replace the list comprehension with a generator comprehension for large lists.
def print_even_matrix(h):
l = [[2*(i + j) for j in range(h)] for i in range(0, h**2, h)]
listtab = lambda x: '\t'.join(map(str, x))
print '\n'.join(map(listtab, l))
>>> print_even_matrix(3)
0 2 4
6 8 10
12 14 16
>>> print_even_matrix(4)
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
x = 1
y = 1
while x <= 10 and y <= 12:
f = x * y
print(f)
y = y + 1
x = x + 1
tablesOneToTen()
I am trying to make a function that will give me values from the multiplication table from 1-10.
Should I add if and elif statements in addition to nested while loops to make this code work?
For these sort of iteration tasks you're better off using the for loop since you already know the boundaries you're working with, also Python makes creating for loops especially easy.
With while loops you have to check that you are in range using conditionals while also explicitly incrementing your counters making mistakes all the more likely.
Since you know you need multiplication tables for values of x and y ranging from 1-10 you can, to get you familiar with loops, create two for loops:
def tablesOneToTen(): # a function that will print out multiplication tables from 1-10
# This will iterate with values for x in the range [1-10]
for x in range(1, 11):
# Print the value of x for reference
print("Table for {} * (1 - 10)".format(x))
# iterate for values of y in a range [1-10]
for y in range(1, 11):
# Print the result of the multiplication
print(x * y, end=" ")
# Print a new Line.
print()
Running this will give you the tables you need:
Table for 1 * (1 - 10)
1 2 3 4 5 6 7 8 9 10
Table for 2 * (1 - 10)
2 4 6 8 10 12 14 16 18 20
Table for 3 * (1 - 10)
3 6 9 12 15 18 21 24 27 30
With a while loop, the logic is similar but of course just more verbose than it need to since you must initialize, evaluate the condition and increment.
As a testament to its uglyness, the while loop would look something like this:
def tablesOneToTen():
# initialize x counter
x = 1
# first condition
while x <= 10:
# print reference message
print("Table for {} * [1-10]".format(x))
# initialize y counter
y = 1
# second condition
while y <=10:
# print values
print(x*y, end=" ")
# increment y
y += 1
# print a new line
print(" ")
# increment x
x += 1
Using Python 3
for i in range(1, 10+1):
for j in range(i, (i*10)+1):
if (j % i == 0):
print(j, end="\t")
print()
or:
for i in range(1, 10+1):
for j in range(i, (i*10)+1, i):
print(j, end="\t")
print()
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Hope it would help you to get 1 to 10 table.
a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(*("{:3}" .format (i*col) for col in a))
print()