python printing list items incremented on lines - python

I am trying to take a user input and print out a list of numbers in a box format onto different lines in python.
right now i have:
horizontalsize = int (input ('please enter horizontal size '))
verticalsize = int (input ('please enter vertical size '))
numbers = horizontalsize * verticalsize
mylist = []
mylist.append(range(1,numbers))
for i in range(1,numbers,horizontalsize):
print (i)
The user will input a height and width and if the height input is 5 and the width input is 3 it should print:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
right now im currently getting:
1
4
7
10
13
How can i get the rest of the numbers to fill in?
Any help is greatly appreciated!

This should work:
for i in range(1, numbers, horizontalsize):
lst = range(i, i+horizontalsize)
print lst # format is [1,2,3]
print ' '.join(map(str,lst)) # format is "1 2 3"
You can also declare a 2D list by list comprehension, example:
>>> horizontalsize = 3
>>> numbers = 15
>>> ll = [[x for x in range(y,y+horizontalsize)]
for y in range(1,numbers,horizontalsize)]
>>> ll
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
>>> for line in ll:
... print ' '.join(map(str,line))
...
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15

The range() you are using will start at 1, go up to numbers, and increase by horizontalsize each time. You are pulling your values for i directly from that range, so those will be the only values you get. One simple solution is to add a second, nested loop to generate the missing values (between i and i+horizontalsize).
for i in range(1,numbers,horizontalsize):
for j in range(i, i+horizontalsize):
print (j, end=" ")
print() #for the newline after every row

Your loop steps skips all the numbers between 1 and 1+horizontalsize, and you just print that number out (without worrying about putting things on the newline). You either need to insert a nested for loop, or modify your range to go over every number, and then put the newline only after specific ones.
That second solution, which uses modulo operator:
for i in range(1,(numbers+1)):
print(i,end=" ")
if i % horizontalsize == 0:
print()
Which gives me:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15

Related

How to input a number x and print it x times, increasing by 2 each time

I need to take number x as input and print the first x odd numbers. If input 8 was given, the output would be: 1 3 5 7 9 11 13 15.
x = int(input('Enter your number:'))
for i in range(2*x):
if i % 2 == 1:
print(i)
Here is a solution without loop. It uses range to get directly the even numbers, converts those integers to string and displays them all at once using newlines as separator:
n = int(input('Enter your number:'))
print('\n'.join(map(str,range(1,2*n,2))))
output for 8 as input:
1
3
5
7
9
11
13
15

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

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

formatting output with for loop or different method in python

I did a program to calculate the inventory in python;however, i have problem formatting the layout output. What I have done so far is:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
for j in range(col):
print "%6d" %(a[i][j]),
print "%s%6d\n" %(d[i],(b[i])),
print "\n" ,
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
so the output comes the 7 x 4 matrix and the total to the right hand side and by column total. However I want to put some names on the left hand side to represent the specific name like size small etc so i used a dictionary but what i am getting is on the right hand side just before the row total. I can't figure out how can i put it on the left hand side in the same row as the numbers. I want to put two columns apart from the number (matrix) which one would be a size in the first far left column in the middle and then in second column names as u can see specified used in dictionary and then the numbers would come in the same row.
Thanks a lot for any help or suggestions. I did a program to calculate the inventory in python;however, i have problem formatting the layout output. What I have done so far is:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
for j in range(col):
print "%6d" %(a[i][j]),
print "%s%6d\n" %(d[i],(b[i])),
print "\n" ,
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
so the output comes the 7 x 4 matrix and the total to the right hand side and by column total. However I want to put some names on the left hand side to represent the specific name like size small etc so i used a dictionary but what i am getting is on the right hand side just before the row total. I can't figure out how can i put it on the left hand side in the same row as the numbers. I want to put two columns apart from the number (matrix) which one would be a size in the first far left column in the middle and then in second column names as u can see specified used in dictionary and then the numbers would come in the same row.
Thanks a lot for any help or suggestions.
I want it to look like this
small 1 1 1 1 1 1 1 7
medium 1 1 1 1 1 1 1 7
size large 1 1 1 1 1 1 1 7
xlarge 1 1 1 1 1 1 1 7
4 4 4 4 4 4 4 28
and i get
1 1 1 1 1 1 1 small 7
1 1 1 1 1 1 1 medium 7
1 1 1 1 1 1 1 large 7
1 1 1 1 1 1 1 xlarge 7
4 4 4 4 4 4 4 28
sorry for not being specific enough previously.
Just print it before the row:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
print d[i].ljust(6),
for j in range(col):
print "%6d" %(a[i][j]),
print "%6d\n" %(b[i]),
print "\n" ,
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
This assumes you want the first column left justified. Right justification (rjust()) and centering (center()) are also available.
Also, since you're just using contiguous numeric indices, you can just use a list instead of a dictionary.
As a side note, more descriptive variables are never a bad thing. Also, according to this, % formatting is obsolete, and the format() method should be used in new programs.
You just have to move the "%s" and the appropriate variable to the correct position:
def summary(a,b,c,row,col,tot):
d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
for i in range(row):
print "%8s" % d[i],
for j in range(col):
print "%6d" %(a[i][j]),
print "%6d\n" % ((b[i])),
print "\n" ,
print "%8s" % " ",
for j in range(col):
print "%6d" %(c[j]),
print "%6d\n" %tot
When calling this with (note that this are just test-numbers, you will replace them with the real ones):
summary([[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7]], [12, 13, 14, 15],
[22, 23, 24, 25, 26, 27, 28], 4, 7, 7777)
you get something like:
Small 1 2 3 4 5 6 7 12
Medium 1 2 3 4 5 6 7 13
Large 1 2 3 4 5 6 7 14
Xlarge 1 2 3 4 5 6 7 15
22 23 24 25 26 27 28 7777
If you want the names left adjusted, you have to add a '-' before the format description like:
print "%-8s" % d[i],

Categories