How can I reverse the value of the output? - python

Let's put int 5 as a sample input; in my code its expressed as this:
n = int(input())
for i in range(0, n):
n = n - 1
print(n**2)
I get an output as:
16
9
4
1
0
Instead I want to reverse the result to:
0
1
4
9
16
How do you go about solving this problem?

The following will reverse the output:
n = int(input())
for i in range(0,n):
print(i**2)
It will loop from 0 to your inputted n value, printing it's square at each iteration. This also negates the need for the n = n - 1 line.
Output:
0 ** 2
1 ** 2
.
.
.
n ** 2

Related

Printing pattern without importing modules

Please help me print the pattern below as it is, if the input entered is 7:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
I figured out to find the middle element of the pattern with any input:
rows=int(input("Enter the number of rows:"))
l=[]
for x in range(1,rows+1):
if x%2!=0:
l.append(x)
mid_value=len(l)
Please help me complete the above pattern......
Thanks in advance!
If you use a list-of-lists to store the values, the value for any specific cell can be determined by doing some basic math involving the cell indexes and the number of rows.
An illustration:
def cell_value(i, j, n_rows):
# The value of any cell is the minimum distance
# from its own coordinates (i, j) to the "outside" (ie,
# an i or j less than 0 or equal to n_rows). Imagine an
# ant in the grid. How many steps would it have to take
# to escape the grid, using the shortest route?
return min(
abs(i - -1),
abs(i - n_rows),
abs(j - -1),
abs(j - n_rows),
)
N_ROWS = 7
rows = [
[
cell_value(i, j, N_ROWS)
for j in range(N_ROWS)
]
for i in range(N_ROWS)
]
for r in rows:
print(*r)
Output:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
This looks like a homework question, so I'm going to try and explain how to approach it rather than just provide code.
A few things worth noting to start:
- The pattern's symmetrical in both directions, so we can save some effort and logic by only solving the top-left quarter, and copying it to the rest.
- Each row is similar the the one before, with one added at the point where the row and column indices (i and j) are equal - rather than recalculate every row from scratch, we can take the one before as a base.
So, for the first row, make a list of 1s the length of your input (7, in this case).
Copy this for the seventh row (note: row6 = row0 won't create a copy; you'll need row6 = list(row0) )
For the second and sixth rows, take a copy of the first row. If i is equal to or greater than j and is in the first half of the row, add 1 to it. You'll need to copy that in reverse for the back half of the row. (Alternative - set the value to j+1 rather than just adding 1)
Repeat until the fourth row, and you should be done.
EDIT: code included, because it was an interesting problem
numberOfRows = int(input("Enter the number of rows:"))
listOut = [[1]*numberOfRows] * numberOfRows #grid of 1s of appropriate size
for j in range(int((numberOfRows+1)/2)): #symmetrical, so only look to the middle
if j > 0:
listOut[j] = list(listOut[j-1]) #copy previous row
for i in range(int((numberOfRows+1)/2)):
if i>=j:
listOut[j][i] = j+1
listOut[j][numberOfRows-(i+1)] = j+1
#copy current row to appropriate distance from the end
listOut[numberOfRows-(j+1)] = list(listOut[j])
for row in listOut:
# * for sequence unpacking, printing lists as strings w/o commas
print(*row)
It might not be the most elegant solution but something like this should work:
n = int(input('Enter the number of rows:'))
table = [[1 for _ in range(n)] for _ in range(n)]
start = 0
end = n
while start < end:
start += 1
end -= 1
for i in range(start, end):
for j in range(start, end):
table[i][j] += 1
for row in table:
print(' '.join(str(ele) for ele in row))
Simple implementation without using any list
n = int(input())
x = n
for i in range((n // 2 + 1) if n % 2 and n > 1 else n //2):
for l in range(1, i + 1):
print(l, end=' ')
print((str(i + 1) + ' ') * x, end='')
for r in range(i, 0, -1):
print(r, end=' ')
print()
x -= 2
y = 1
for j in range(n // 2, 0, -1):
for l in range(1, j):
print(l, end=' ')
print((str(j) + ' ') * (2 * y + 1 if n % 2 else 2 * y), end='')
for r in range(j-1, 0, -1):
print(r, end=' ')
print()
y += 1

python Program is saying 2 numbers are different when they are the same

Thanks for the help in advance.
I compare 2 variables which hold numbers with the operation !=
the program takes input like this
4
1 2 3 4
Then the program should return the highest product exluding a square product. In this case the result should be 12(4x3) not 16(4x4) but it is incorrectly returning 16.
The code is here
def max_pairwise_product():
n = int(input())
a = input().split()
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != integer1:
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
This is because your comparing an int to a str. I have edited your code minimally to fix this issue, but you have better to edit your list input before hand.
def max_pairwise_product():
n = int(input())
a = input().split() #If I were you I would do: a = [int(x) for x in input().split()]
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != int(integer1): #This is were I have changed
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
You compare string vs. integer which is always False:
for integer1 in a: # integer1 is a string
product = int(integer1) * n
if n != integer1: # n is a number
Fix:
def max_pairwise_product():
_ = input() # not used
a = "1 2 3 4".split() # input() removed and fixed input given
a = sorted(set(map(int,a))) # convert all to intergers and sort unique numbers
maxno = 0
for idx,number in enumerate(a):
for number2 in a[idx+1:]:
maxno = max( maxno, number*number2 )
return maxno
print(max_pairwise_product())
Output:
12
The loops are optimized leveraging the fact that they numbers are sorted and unique - thats why the second loop can be shorter - no need to recompute already computed results.
Its good if you get inputs like '1 1 1 1 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6' because it will only compute for '1 2 3 4 5 6' and never compute any paring twice.

Printing reverse Sum of numbers from 1 to n

I am learning python and I am really struggling to figure out how to write this code where I get an input a that is bigger than 1 and the output should look like this:
Sum from 1 to a
Sum from 2 to a
Sum from 3 to a
.....
a
E.g. for 5, the output should be:
15
14
12
9
5
This is what I have so far
a=int(input())
for t in range(a):
b=a*(a+1)/2
b=b-t
print(a+t)
I cant seem to figure out how to subtract it from reverse and how to print each results in the process
The following will work:
a = int(input())
# s = sum(range(1, a+1))
s = a * (a+1) // 2
for t in range(1, a+1):
print(s)
s -= t
Produces for a = 5:
15
14
12
9
5
Instead of only subtracting the counter t, you need to subtract the sum of 1 ... t.
Otherwise your code does not need to be changed, I just added the forcing to int.
a = int(input())
for t in range(a):
b=a*(a+1)//2
c=t*(t+1)//2
b=b-c
print(b)
Output:
15
14
12
9
5

How to make a grid with integers in python?

I have the following code which has to print out a board with numbers according to the size the user specified (for instance 3 means a 3 x 3 board):
n = d * d
count = 1
board = []
for i in range(d):
for j in range(d):
number = n - count
if number >= 0 :
tile = number
board.append[tile]
else:
exit(1)
count += 1
print(board)
I need to get this in a grid, so that the board is 3 x 3 in size ike this:
8 7 6
5 4 3
2 1 0
What I tried to do is to get each row in a list (so [8 7 6] [5 4.. etc) and then print those lists in a grid. In order to do that, I guess I would have to create an empty list and then add the numbers to that list, stopping after every d, so that each list is the specified length.
I now have a list of the numbers I want, but how do I seperate them into a grid?
I would really appreciate any help!
Here a function that takes the square size and print it.
If you need explanation don't hesitate to ask.
def my_print_square(d):
all_ = d * d
x = list(range(all_))
x.sort(reverse=True) # the x value is a list with all value sorted reverse.
i=0
while i < all_:
print(" ".join(map(str, x[i:i+d])))
i += d
my_print_square(5)
24 23 22 21 20
19 18 17 16 15
14 13 12 11 10
9 8 7 6 5
4 3 2 1 0
By default the print() function adds "\n" to the end of the string you want to print. You can override this by passing in the end argument.
print(string, end=" ")
In this case we are adding a space instead of a line break.
And then we have to print the linebreaks manually with print() at the end of each row.
n = d * d
count = 1
max_len = len(str(n-1))
form = "%" + str(max_len) + "d"
for i in range(d):
for j in range(d):
number = n - count
if number >= 0 :
tile = number
else:
exit(1)
count += 1
print(form%(tile), end=" ")
print()
EDIT: by figuring out the maximum length of the numbers we can adjust the format in which they're printed. This should support any size of board.
You can create the board as a nested list, where each list is a row in the board. Then concatenate them at the end:
def get_board(n):
# get the numbers
numbers = [i for i in range(n * n)]
# create the nested list representing the board
rev_board = [numbers[i:i+n][::-1] for i in range(0, len(numbers), n)]
return rev_board
board = get_board(3)
# print each list(row) of the board, from end to start
print('\n'.join(' '.join(str(x) for x in row) for row in reversed(board)))
Which outputs:
8 7 6
5 4 3
2 1 0
If you want to align the numbers for 4 or 5 sized grids, just use a %d format specifier:
board = get_board(4)
for line in reversed(board):
for number in line:
print("%2d" % number, end = " ")
print()
Which gives an aligned grid:
15 14 13 12
11 10 9 8
7 6 5 4
3 2 1 0

How do you triangulate a number in python?

I have to do these for school and I don't know how to.
Write a function print_triangular_numbers(n) that prints out the first n triangular numbers (n is an input). A call to print_triangular_numbers(5) would produce the following output:
n result
1 1
2 3
3 6
4 10
5 15
A triangular number can be expressed as
n(n+1)/2
Thus, you need to build a simple loop, starting at 1 and going through your passed parameter:
def print_triangular_numbers(n):
for x in range(1,n+1):
print x, x * (x + 1) / 2
The for loop starts at 1 and goes through n+1 because range is not inclusive of the end point.
This outputs:
1 1
2 3
3 6
4 10
5 15

Categories