Printing reverse Sum of numbers from 1 to n - python

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

Related

How can I reverse the value of the output?

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

Python: How to print multiplication table based on two inputs?

I'm attempting to write a program called multChart(x,y) that prints a multiplication table based on two inputs, one specifying the number of rows to print and another specifying the number of columns. So it would look like this:
>>> multChart(4,5):
1: 1 2 3 4 5
2: 2 4 6 8 10
3: 3 6 9 12 15
4: 4 8 12 16 20
Here's what my current code looks like:
def multChart(x,y):
for i in range(1,x+1):
print(i,':',i*1,i*2,i*3,i*4,i*5)
I'm totally stuck on how to implement the y value. I also know there should be a better way of printing the multiplication instead of i * multiples of five, but I'm not sure what loop to use. Any help would be greatly appreciated.
You need another loop inside your print for looping over the y range:
def multChart(x, y):
for i in range(1, x+1):
print(i, ':', *[i * z for z in range(1, y+1)])
def multChart(x,y):
for i in range(1,x+1):
print(i, ':', end=" ")
for j in range(1,y+1):
print(i*j, end =" ")
print()
multChart(4,5)
produces
1 : 1 2 3 4 5
2 : 2 4 6 8 10
3 : 3 6 9 12 15
4 : 4 8 12 16 20
You can use a second for loop for the second index. Also, note that you can use end in the print statement.
def multChart(x,y):
for i in range(1,x+1):
print(i,':',*list(map(lambda y: i*y,list(range(1,y+1 ) ) ) ) )
multChart(4,5)

Ulam Spiral (for diagonal numbers) writing program python

I am writing a code the represent the Ulam Spiral Diagonal Numbers and this is the code I typed myself
t = 1
i = 2
H = [1]
while i < 25691 :
for n in range(4):
t += i
H.append(t)
i += 2
print(H)
The number "25691" in the code is the side lenght of the spiral.If it was 7 then the spiral would contain 49 numbers etc.
Here H will give you the all numbers in diagonal. But I wonder is there a much faster way to do this.
For example if I increase the side lenght large amount it really takes forever to calculate the next H.
Code Example:
t = 1
i = 2
H = [1]
for j in range(25000,26000):
while i < j :
for n in range(4):
t += i
H.append(t)
i += 2
For example my computer cannot calculate it so, is there a faster way to do this ?
You dont need to calculate the intermediate values:
Diagonal, horizontal, and vertical lines in the number spiral correspond to polynomials of the form
where b and c are integer constants.
wikipedia
You can find b and c by solving a linear system of equations for two numbers.
17 16 15 14 13
18 5 4 3 12 ..
19 6 1 2 11 28
20 7 8 9 10 27
21 22 23 24 25 26
Eg for the line 1,2,11,28 etc:
f(0) = 4*0*0+0*b+c = 1 => c = 1
f(1) = 4*1*1+1*b+1 = 2 => 5+b = 2 => b = -3
f(2) = 4*2*2+2*(-3)+1 = 11
f(3) = 4*3*3+3*(-3)+1 = 28

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

Keeping Python from spacing after breaking a line when printing a List

(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)
I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."
e.g
2 4 as entrance
1 2
3 4
e.g 2 6
1 2
3 4
5 6
Okay... So, I thought on doing this:
line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1
if i != final:
List = list(range(1, final + 1, 1))
i += 1
while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')
print(*List)
Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)
So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:
2 10 as entrance
1 2
3 4
5 6
7 8
9 10
And, using the code I just posted, I get this as a result:
1 2
3 4
5 6
7 8
9 10
Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)
Well, I've tried pretty much anything. Hope anyone can help me.
Thanks in advance :)
You have built a list that includes each necessary character, including the linefeed. Therefore, you have a list like this:
[1, 2, '\n', 3, 4, '\n'...]
When you unpack arguments to print(), it puts a separator between each argument, defaulting to a space. So, it prints 1, then a space, then 2, then a space, then a linefeed, then a space... And that is why you have a space at the beginning of each line.
Instead of inserting linefeeds into a list, chunk that list with iter and next:
>>> def chunks(x, y):
... i = iter(range(1, y+1))
... for row in range(y//x):
... print(*(next(i) for _ in range(x)))
... t = tuple(i)
... if t:
... print(*t)
...
>>> chunks(2, 6)
1 2
3 4
5 6
>>> chunks(2, 7)
1 2
3 4
5 6
7
The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.
Try this approach: (EDITED)
x, y = input().split()
x, y = int(x), int(y)
for i in range(1, y+1):
if i % x == 0 or i == y:
print(i)
else:
print(i, end=" ")
Output for 3 11
1 2 3
4 5 6
7 8 9
10 11
Output for 2 10
1 2
3 4
5 6
7 8
9 10
Use itertools to take from an iterable in chunks:
>>> import itertools
>>> def print_stuff(x,y):
... it = iter(range(1, y + 1))
... chunk = list(itertools.islice(it,X))
... while chunk:
... print(*chunk)
... chunk = list(itertools.islice(it,X))
...
>>> print_stuff(2,4)
1 2
3 4
>>>
And here:
>>> print_stuff(2,10)
1 2
3 4
5 6
7 8
9 10
>>>
I split user input into two string then convert them into int and comapre if y greater than x by 2 because this is minimum for drawing your sequence
Then i make a list from 1 to y
And iterate over it 2 element for each iteration printing them
x,y=input().split()
if int(y)>int(x)+2:
s=range(1,int(y)+1)
for i in range(0,len(s),2):
print(' '.join(str(d) for d in s[i:i+2]))
result:
1 2
3 4
5 6
7 8
9 10

Categories