How can a return statement of a Python function keep strings in the same line like print(argument, end='')? - python-3.x

I am fresh off the coding boat and I am attempting to have the return values of a python function all print on one line. I know to use print(argument, en= ''), although I cannot include a print function in the return of a defined function.
Ultimately I am trying to get each first item of a list in a list, then the second and so on to print the design turned 90 degrees. I am first getting each list in a for loop then getting each index from there and printing in a second for loop.
With the code the way I have it now, I get the result I need, but there is "None" at the end of each line because I have a print function in a function instead of a "return" so I can have each index value printed on one line per list. I am curious about how to have the values displayed on one line without using the end argument of a print function in a function return. And I would always love to see a better/faster way to achieve this result.
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
Thank you!
grid = [['.', '.', '.', '.', '.', '.',],
['.', '0', '0', '.', '.', '.',],
['0', '0', '0', '0', '.', '.',],
['0', '0', '0', '0', '0', '.',],
['.', '0', '0', '0', '0', '0',],
['0', '0', '0', '0', '0', '.',],
['0', '0', '0', '0', '.', '.',],
['.', '0', '0', '.', '.', '.',],
['.', '.', '.', '.', '.', '.',]]
xLength = len(grid[0])-1
yLength = len(grid)-1
listX = list(range(0, xLength))
listY = list(range(0, yLength))
def listGrid(y = 0):
for x in grid:
print(x[y], end = '')
for num in listX:
print(listGrid(num))

You need to return a value from the function - if a function does not return anythin, it returns None implicitly. Your code prints the "data" inside the function and you print the return of the function by
print(listGrid(num)) # prints None
Print the results of your function outside, using end="" is an option:
grid = [['.', '.', '.', '.', '.', '.',],
['.', '0', '0', '.', '.', '.',],
['0', '0', '0', '0', '.', '.',],
['0', '0', '0', '0', '0', '.',],
['.', '0', '0', '0', '0', '0',],
['0', '0', '0', '0', '0', '.',],
['0', '0', '0', '0', '.', '.',],
['.', '0', '0', '.', '.', '.',],
['.', '.', '.', '.', '.', '.',]]
xLength = len(grid[0]) # fix, do not subtract 1 - range is upper border exclusive
yLength = len(grid)-1
listX = list(range(0, xLength))
listY = list(range(0, yLength))
def listGrid(y = 0):
return [x[y] for x in grid] # return a list
for num in listX:
for r in listGrid(num):
print(r, end="")
print()
Or you leverate zip() to make columns from your rows and print them:
# directly operates on your data - you do not need anything of your code beside
# the grid definition
for c in zip(*grid):
print(''.join(c))
Output:
..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....

Related

Python - how to reassign the cells' values in a DataFrame given a list ? - finding a fast way to achive it in a big data table

I have a big table with the size of 5,905,635*30 (see figure 1), and a list with the size 5,905,635 of rows (see figure 2). I want to reassign the cells' values in the table, given the elements of the list (see figure 3).
figure 1
figure 2
figure 3
For example, like the codes below, I want to get df2 given df1 and list1; an easy way is to loop the elements of list1, the first element is 'B', so assign the first row of column B to 1 in df1, and the second element is 'C', then assign the second row of column C to 1, and etc. The final result should be df2. The problem with this solution is too slow if I have a big size of table. I wonder if there is a fast way to achieve this goal.
df1 = pd.DataFrame({'A': ['0', '0','0', '0', '0', '0', '0'],
'B': ['0', '0','0', '0', '0', '0', '0'],
'C': ['0', '0','0', '0', '0', '0', '0'],
'D': ['0', '0','0', '0', '0', '0', '0'],
'E': ['0', '0','0', '0', '0', '0', '0']})
list1 = ['B','C','A','E','D','A','D']
df2 = pd.DataFrame({'A': ['0', '0','1', '0', '0', '1', '0'],
'B': ['1', '0','0', '0', '0', '0', '0'],
'C': ['0', '1','0', '0', '0', '0', '0'],
'D': ['0', '0','0', '0', '1', '0', '1'],
'E': ['0', '0','0', '1', '0', '0', '0']})
The problem of this solusion is too slow if I have a big size of the table. I wonder if there is a fast way to achieve this goal.

While swapping in python using rindex for this specific case why swapping is not happening?

While swapping in python using rindex for this specific case why swapping is not happening? Case-1 is giving correct ans, but not case-2.
Case-1:
S=['1', '1', '1', '2', '1', '1']
S[S.index('1')], S[''.join(S).rindex('2')] = S[''.join(S).rindex('2')], S[S.index('1')]
print(S)
Output: ['2', '1', '1', '1', '1', '1']
Case-2:
S=['2', '1', '1', '1', '1', '1']
S[S.index('1')], S[''.join(S).rindex('2')] = S[''.join(S).rindex('2')], S[S.index('1')]
print(S)
Output: ['2', '1', '1', '1', '1', '1']
But Expected Output: ['1', '2', '1', '1', '1', '1']
Calculate your indices before doing the swap, not in the middle of it:
index1, index2 = S.index('1'), ''.join(S).rindex('2')
S[index1], S[index2] = S[index2], S[index1]

Fastest way to check if a list pattern is present in another list of varying lengths?

Suppose I have a list of lists of varying lengths.
list1 = [['0', '0'],['0', '1', '0', ' '],['0', '1', ' ', '0', '1', ' '],['1', '1', ' ', ' ', '1', '1', ' ', '0'],[]]
I want to compare this list against another list of lists:
list2=[['0','0','0','0'],['1','1','1','1']]
Now, I want to check if list2 is contained in list1. The output should be True since list1 has ['1', '1', ' ', ' ', '1', '1', ' ', '0'] which contains ['1','1','1','1']
What would be the best way to check if any of the list2 elements are present in list1? The answer should be a Boolean in case any of the list2 elements are found in list1 by maintaining order.
I have tried quite a few things, but can't seem to get the desired output. Thanks in advance for the suggestions.
This will do the trick
list1 = [['0', '0'], ['0', '1', '0', ' '], ['0', '1', ' ', '0', '1', ' '], ['1', '1', ' ', ' ', '1', '1', ' ', '0'], []]
list2 = [['0', '0', '0', '0'], ['1', '1', '1', '1']]
for i in list2:
string2 = ''.join(i)
for j in list1:
string1 = ''.join(j).replace(' ','')
if string2 in string1:
print('yes',i,j)
# output yes ['1', '1', '1', '1'] ['1', '1', ' ', ' ', '1', '1', ' ', '0']
Simplistic approach:
list1 = [['0', '0'],['0', '1', '0', ' '],['0', '1', ' ', '0', '1', ' '],
['1', '1', ' ', ' ', '1', '1', ' ', '0'],[]]
list2 = [['0','0','0','0'],['1','1','1','1']]
# computing the shortened strings once, storing as string,orignal - tuples
texts = [(''.join(inner).replace(" ",""),inner) for inner in list1]
find = [(''.join(inner).replace(" ",""),inner) for inner in list2]
for (shortened,inner) in texts:
for (pattern,f) in find:
if pattern in shortened:
print("Found", f , "in", inner)
to get
Found ['1', '1', '1', '1'] in ['1', '1', ' ', ' ', '1', '1', ' ', '0']
It is simplistic because it is a quadratic search.

Turn a tuple containing letters, numbers, symbols, or tags, into a string

I have found the stackoverflow question:
Python convert tuple to string a great source so far, but my list of strings contain "#" and "\n".
(the following example has been shortened for readability. The actual tuple would create 7 lines when completed)
I would like to turn this tuple:
('\n', '0', '#', '0', '0', '0', '0', '#', '\n', '0', '#', '#', '0', '0', '#', '#', '\n')
into a multi-line string like this.
"""
0#0000#
0##00##
"""
The code that seems to make the most sense to me is written in the above mentioned thread by Mohammed, but when tried, the tuple stays exactly the same.
''.join(map(str, tup))
Any assistance would be greatly appreciated.
edited. complete code.
mylist = [('\n', '0', '#', '0', '0', '0', '0', '#', '\n', '0', '#', '#', '0', '0', '#', '#', '\n', '0', '#', '#', '#', '#', '#', '#', '\n', '0', '#', '#', '0', '0', '#', '#', '\n', '0', '0', '0', '0', '0', '0', '0', '\n')]
tuple = str(mylist).strip('[]')
string = "".join(tuple)
with the hopes of it returning:
"""
0#0000#
0##00##
0######
0##00##
0000000
"""
however, when i print or return the above code, the unjoined tuple is the product.

How to properly use the range() function to print/iterate a grid

If I have a list/grid:
grid = [
['.', '.', '.', '.', '.', '.'], #[0,0]-[0,5]
['.', '0', '0', '.', '.', '.'], #[1,0]-[1,5]
['0', '0', '0', '0', '.', '.'], #[2,0]-[2,5]
['0', '0', '0', '0', '0', '.'], #[3,0]-[3,5]
['.', '0', '0', '0', '0', '0'], #[4,0]-[4,5]
['0', '0', '0', '0', '0', '.'], #[5,0]-[5,5]
['0', '0', '0', '0', '.', '.'], #[6,0]-[6,5]
['.', '0', '0', '.', '.', '.'], #[7,0]-[7,5]
['.', '.', '.', '.', '.', '.']] #[8,0]-[8,5]
What would be the best method to step through this grid and print out the contents, would it be range()?
something like:
def print_grid(grid):
I see a lot of this for i in range()- what is the 'i' when it is never declared or is it a type of counter? I'm very new to python so excuse any confusion. Would I use a nested for loop to step through the cords of the grid?
for i in range(limit) creates a list of numbers from 0 to limit, and goes through each item in limit and sets i to that item. However, for going through and printing a grid, using range() isn't the best method.
for row in grid:
for item in row:
print(item, end = " ")
print()
for row in grid goes through each list in grid, and sets row to that list. for item in row goes through each item in row and sets item to that item. print(item, end = " ") prints item out, and end = " " makes it so that instead of a newline being added after print, it adds a space. The empty print command after the inner for loop inserts a new line for the next row to be printed on.
Hope this clarifies your confusion

Resources