Python, nested loops print on one line, multiple copies - python

Very new to python so please excuse!
question is...to make an output look like
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
I am using user input for the limit and the number of copies ( in this example 5 and 3), so I have done this;
limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))
def output(limit):
for i in range(copies):
for x in range(limit):
print (x + 1, end=" ")
output(limit)
However the answer shows up as 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5. I know it's because of the end=" " but not sure how to get around it! Any help appreciated

Print new line explicitly for every loop:
def output(copies, limit):
for i in range(copies):
for x in range(limit):
print (x + 1, end=" ")
print() # <----
# print() # Add this if you want an empty line
output(copies, limit)

You got the part with the ranges correctly, but there's one thing you missed, you can specify a starting number:
v0 = range(1, limit + 1)
In order to convert a number to a string, use the str() function:
v1 = (str(x) for x in v0)
In order to put a space between adjacent numbers, use the string's join() memberfunction:
v2 = ' '.join(v1)
Then, you could either add the linebreaks yourself:
v3 = (v2 + '\n') * copies
print(v3, end='')
Alternatively in this form:
v3 = '\n'.join(v2 for i in range(copies))
print(v3)
Or you just print the same line multiple times in a plain loop:
for i in range(copies):
print(v2)
BTW: Note that v0 and v1 are generators, so joining them into a string v2 will change their internal state, so you can't simply repeat that and get the same results.

Just a little modification to your code:
def output(limit):
for i in range(copies):
for x in range(limit):
print(x + 1, end=' ')
print()

limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))
def output(limit):
for i in range(copies):
if (i!=0):
print()
print()
for x in range(limit):
print (x + 1, end="")
output(limit)

Related

How to make the two different code outputs appear in the same area?

I am trying to merge two outputs together so that it appears something like this:
0 1 2
0 ? ? ?
1 ? ? ?
2 ? ? ?
But it ended up appearing like this instead:
0 1 2
0
1
? ? ?
? ? ?
I tried this to make the codes appear but i have no idea how to place their outputs together
import random
rows = [3]
columns = [4]
def rowscol():
for j in range(columns[0]):
print(" " * 1, end="")
print(j, end="")
print()
for i in range(rows[0]):
print(i)
rowscol()
def create_game_board(rows, columns):
board = [[random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(columns[0])] for _ in range(rows[0])]
# If number of cells is odd, make the last cell an unused cell
if (rows[0] * columns[0]) % 2 != 0:
board[-1][-1] = "#"
return board
board = create_game_board(rows,columns)
# Function to display the game board
def display_board(board):
pad = " " * 30
for row in board:
line = pad + " ".join('?' if column != '#' else '#' for column in row)
print(line)
display_board(board)
Welcome to StackOverflow!
When using multidimensional arrays, like in your case a list of lists, I like to be able to index into them easily. Because of this I usually change it to a dict and use the coordiantes as keys. This way you can even store additional information about the board, like the dimension sizes or anything else.
I added a bunch of comments to explain how the code works but feel free to ask if anything isn't clear:
import random
import string
def create_game_board(rows, cols):
board = dict()
# save dimensions inside the dict itself
board['cols'] = cols
board['rows'] = rows
for y in range(rows):
for x in range(cols):
# add random letter to board at (x,y)
# x,y makes a tuple which can be a key in a dict
# changed to use string.ascii_uppercase so that you don't forget any letter
board[x, y] = random.choice(string.ascii_uppercase)
# change last element to # when both dimensions are odd
if (rows * cols) % 2 == 1:
board[rows-1, cols-1] = "#"
return board
def display_board(board):
# get dimensions
cols, rows = board['cols'], board['rows']
# print header
print(' '.join([' '] + [str(x) for x in range(cols)]))
for y in range(rows):
# print rows
#print(' '.join([str(y)] + [board[x, y] for x in range(cols)])) # to display the actual letter at this location
print(' '.join([str(y)] + ['?' if board[x, y] == '#' else '#' for x in range(cols)])) # using your display function
print() # separator empty line
board = create_game_board(3, 3)
display_board(board)
The output is nothing special when I'm using your method of printing, you might need to change that, I'm not sure how you wanted to display it. I added a line that allows you to print the values on those coordinates.
This is the output:
0 1 2
0 # # #
1 # # #
2 # # ?
Maybe something like?
def draw_board(board):
print(" " + " ".join([str(i) for i in range(len(board[0]))])) # print column numbers
for i in range(len(board)):
row = ""
for j in range(len(board[i])):
row += board[i][j] + " "
print(str(i) + " " + row)
draw_board(board)

How can I write a for loop in a more elaborative and efficient and pythonic way

I want to write this for loop in a more elaborative and in a efficient way...is there a way to do that
for index in indices:
x = seq[lowerIndex:(index+1)] #lower index is set to 0 so it will take the first broken string and also the last string
digests.append(x) #it will add the pieces here in to a given list format
print("length: "+ str(len(x)) + " range: " + str(lowerIndex + 1) + "-" + str(index+1)) #This will print the length of each piece and how long each piece is.
print(x) #this will print the piece or fragments
lowerIndex = index + 1 # this refers to the piece after the first piece
You can try:
# new indices contains the beginning index of all segments
indices = [i+1 for i in indices]
indices.insert(0, 0)
for from, to in zip(indices, indices[1:]): # pair 2 consecutive indices
x = seq[from:to]
digest.append(x)
print(f'length: {to-from} range: {from+1} - {to}') # use string format
print(x)
For example:
>>> seq = 'abcdefghijk'
>>> indices = [0, 3, 5, 6, 9]
---------- (result)
length: 3 range: 1 - 3
abc
length: 2 range 4 - 5
de
length: 1 range 6 - 6
f
length: 3 range 7 - 9
ghi

How to get rid of the use of "end" in loops(python) for only the last element?

By using end="-" I got this loop. I want to remove that '-' for the last element.
m=4
n=1
for i in range(1,4):
for x in range(5,n,-1):
print(" ",end="")
n+=2
for y in range(3,3-i,-1):
print(y,end="-")
for z in range(m,4):
print(z,end="-")
m-=1
print()
Output:
3-
3-2-3-
3-2-1-2-3-
Instead of using end, you can actually use sep, which only separates between elements which sounds like what you want. This will even reduce your loops a bit.
You will have to change the prints to be something like: print(*range(m, 4), sep='-').
The spaces (' ') loop is also not necessary and can be a single print, so your whole code can look like:
m = 4
n = 1
for i in range(1, 4):
print(" " * abs(5-n), end='')
n += 2
print(*range(3, 3-i, -1), *range(m, 4), sep='-')
m -= 1
It is also possible to only use the loop variable i and avoid maintaining m and n. So the code can be reduced to:
m = 4
for i in range(1, m):
print(" " * abs(5-i*2+1), end='')
print(*range(3, 3-i, -1), *range(m-i+1, m), sep='-')
which gives:
3
3-2-3
3-2-1-2-3
Finally, to make it more reasonable by m being the range being printed, and making it completely generic to allow any m you can do:
m = 4
for i in range(1, m+1):
print(" " * (m*2-i*2), end='')
print(*range(m, m-i, -1), *range(m-i+2, m+1), sep='-')
Which will now print up-to 4:
4
4-3-4
4-3-2-3-4
4-3-2-1-2-3-4
Welcome to SO!
Nice work progress! Here, in my solution I am trying to is to divide the responsibilities into smaller tasks.
To generate the number to print
To print these in design format
m=4
n=1
max_line_length = 20
def special_print(items):
# convert each number to string
str_items = [str(each) for each in items]
# prepare output string
output_string = '-'.join(str_items)
prefix = ' ' * (max_line_length - len(output_string))
print(prefix + output_string)
# try
# print(output_string.center(max_line_length))
for i in range(1,4):
items = []
n+=2
for y in range(3,3-i,-1):
items.append(y)
for z in range(m,4):
items.append(z)
m-=1
# print(items)
special_print(items)
Output
3
3-2-3
3-2-1-2-3
Note: This solution can be further simplified by Python Pros but I tried to keep simple enough for you to understand.
You can explore python string objects features like center, join and list-comprehension, len function to improve your Python skills.

python for loop for multiple conditions

Below is the code(I know below code is wrong syntax just sharing for understanding requirement) I am using to test multiple for loop.
server = ['1']
start = 2
end = 4
for x in range(start, end + 1) and for y in serverip:
print x
print y
Requirement.
for loop iterations must not cross server list length or range .
Input 1
start = 2
end = 4
server list length = 1 that is server = ['1']
expected output 1:
print
x = 2
y = 1
Input 2
start = 2
end = 4
server list length = 2 that is server = ['1','2']
expected output 2:
print
x = 2
y = 1
x = 3
y = 2
Input 3
start = 1
end = 1
server list length = 2 that is server = ['1','2']
expected output 3:
print
x = 1
y = 1
Please help.
The easiest way is to use the built-in zip function suggested in the comments. zip creates a list, or an iterator in python 3, with the iterators “zipped” together. Until one of the iterators runs out.
server = ['1']
start = 2
end = 4
for x, y in zip(range(start, end + 1), server):
print x
print y
Output:
2
1
https://docs.python.org/2/library/functions.html#zip :
This function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables. The
returned list is truncated in length to the length of the shortest
argument sequence.

Creating pattern using simple loops?

I am trying to create this pattern in python:
*
* *
* * *
* *
*
This is my program so far that I've come up with:
ster = "*"
space = " "
lines = 0
n = 3
x = 1
while lines <= 5:
print space*n, ster*x
n-= 1
x+= 1
lines += 1
What am I doing wrong?
Okay, first of all you can create a list of numbers which represents the number of stars in each line.
number_of_stars = 5
i_list = list(range(number_of_stars))
# extend the list by its inverse i_list[::-1]
# but exclude the first item
i_list.extend(i_list[::-1][1:])
print(i_list) # prints: [0, 1, 2, 3, 4, 3, 2, 1, 0]
Now you can go thru the list and print a multiple of *
for i in i_list:
print('* ' * i)
But this is not aligned properly. By adding multiple empty spaces to the left one can archive a solution:
for i in i_list:
print(' ' * (number_of_stars - i) + '* ' * i)
Note that in python one can repeat a string by using the multiplication symbol:
print('a'*5) # prints: aaaaa
Thank you for the help, I wrote a functional code for the problem. It was supposed to made using while loop(s).
This is what I did:
width = int(input("Width: "))
i = 1
while i < width*2:
if i < width:
print " " * (width-i) + "* " * i
else:
print " " * (i-width) + "* " * (2*width-i)
i = i + 1
Notice you have
3 spaces for 1 star
2 spaces for 2 stars
1 space for 3 stars.
For the upright triangle part of your diamond (including the large part). Then you have
2 spaces for 2 stars
3 spaces for 1 star
Without throwing out the answer, try analysing a certain pattern in what i've just pointed out. It can be achieved with 2 loops ( for or while, depending on your preference).

Categories