screen output of tuples - python

I got a question about displaying my output data. Here is my code:
coordinate = []
z=0
while z <= 10:
y = 0
while y < 10:
x = 0
while x < 10:
coordinate.append((x,y,z))
x += 1
coordinate.append((x,y,z))
y += 1
coordinate.append((x,y,z))
z += 1
for point in coordinate:
print(point)
My output data contains commas and parenthesis which I want to get rid of. I want my output to look like this:
0 0 0
1 0 0
2 0 0
etc. No comma and parenthesis, just the values.

Write the last two lines like this:
for x, y, z in coordinate:
print(x, y, z)

In addition to the answer by #flornquake, you can do something with those while
import itertools
# If you just want to print this thing, forget about building a list
# and just use the output of itertools.product
coordinate = list(itertools.product(range(0, 10), range(0, 10), range(0, 11)))
for point in coordinate:
print('{} {} {}'.format(*point))

Presuming you are using Python 3, you could do this:
for point in coordinate:
print(*point)
The "star" notation unpacks the tuple into its individual elements. The print function then displays the elements using the default separator, which is a single space character.

Related

Python: Comparing values in two lists

I've really tried looking all over for solutions to my problem but haven't been successful in finding anything. If someone else has already asked this question, I apologize. Onto the problem.
I have two lists in with values to be compared to each other. I have tried the following option.
list1 = [1,3,5,7,9]
list2 = [200,2]
x = 0
n = 0
y = 0
while x <= 9:
if list1[y] >= list2[n]:
print('TRUE')
x = x + 1
y = y + 1
if y > 4:
y = 0
n = n + 1
else:
print('FALSE')
x = x + 1
y = y + 1
if y > 4:
y = 0
n = n + 1
The only problem is, instead of the variables in place, I need to iterate through a list of values.
So instead, I would like the code to look something like this:
x = 0
n = [0,1]
y = [0,3]
z = len(n) + len(y) - 1
while x <= z:
if list1[y] >= list2[n]:
print('TRUE')
x = x + 1
else:
print('FALSE')
x = x + 1
Where n and y are index values of the numbers that I want to compare.
This does not work for me and I'm really not sure how else to do this.
Edit: I didn't think I had to explain everything by text since I included two sets of code. The first set of code works and it shows exactly what I am trying to do. The second is what I want it to do.
Broken down further I want to know if list1[0]>=list2[0], followed by list1[3]>=list2[0], followed by list1[0]>=list2[1], followed by list1[3]>=list2[1]. The outputs that I expect are in the code I provided.
Apologies if I wasn't clear before. I need to call specific index positions that I will have in a separate list. This is the problem that I tried to outline in the second code.
I think now get what you are trying to do.
First, there are two lists of "raw" data:
list1 = [1,3,5,7,9]
list2 = [200,2]
Then, there are two sets of "indices of interest":
y = [0, 3] # indices of interest for list1
n = [0, 1] # indices of interest for list2
I think the following can achieve what you want:
product = [(index1, index2) for index2 in n for index1 in y] #cartesian product
for index1, index2 in product:
if list1[index1] >= list2[index2]:
print("True")
else:
print("False")
Or if the cartesian product is not wanted, simply do it within nested loops:
for index2 in n:
for index1 in y:
if list1[index1] >= list2[index2]:
print("True")
else:
print("False")

Giving positional arguments for Co-ordinates and Clustering them together

so I have a data file and I'm wanting to find two things:
Whether the coordinates I give are inside or outside an area and returning if its true or not
Put each coordinates of "1" together in each line in its own list. This should return it in a dictionary.
The file has the following:
1 1 0 1 0 1
0 0 1 1 1 0
1 1 1 1 1 0
1 0 0 0 0 1
0 0 1 1 0 1
1 0 0 0 0 1
I've put the above into a list and each with the code:
lines = []
with open('area.dat', 'r') as a:
for line in a:
line = line.strip()
if not line:
continue
lines.append(list(map(int, line.split())))
data.extend(map(int, line.split()))
print(lines)
My attempts at code to get the coordinates and whether it's outside or inside the area (for both x and y)
area is the list of lists
x = int(input('enter x: '))
y = int(input('enter y: '))
def cords(x, y, area):
if x > 6 or y > 6:
print('Outside Area')
return(False)
else:
print('Inside Area')
return(True)
I want to get a coordinate x and y within the list "area" and return whether it is in or out this.
So for example if I put in cords(0,4,area) it will return "True" and if I put cords(3,7,area) it will return "False".
After this I then want to put them together in groups of 1's by each line.
so for example line 1 and 2 would give:
{1: [(0,4), (0,5)], 2: [(1,0), (1,1)]}
All help is appreciated thanks.
For the first part you have two options:
def cords(x, y):
return x >= 0 and x < 6 and y >= 0 and y < 6
This first option is static for an area size of 6x6, note that array indexing starts at 0 so 6 would already be out of bounds.
def cords(x, y, area):
return x >= 0 and x < len(area) and y >= 0 and y < len(area[0])
This second option dynamically checks whether the coordinates are in bounds of the given nested list. You might have to adjust it based on whether x and y relate to rows and columns or vice versa.
Now for your second part, you're creating a dictionary with redundant information, since the index (1 and 2 in your example) directly relates to the first axis (0 and 1 in your example), you might want to reconsider what you actually want to achieve here.
d = {}
for i,row in enumerate(lines):
n = []
for j,v in enumerate(row):
if v == 1:
n.append([i,j])
d[i+1] = n

What is difference between x,y = y,y+x and x=y , y=x+y?

I've just written these codes but outputs are different. second code's output is correct that I expected, but the first code's output is incorrect. but why?
def fib(n):
x = 0
y = 1
print x
for i in range(n):
x = y
y = x+y
print x
return x
output is; when n = 5
0
1
2
4
8
16
def fib(n):
x,y = 0,1
print x
for i in range(n):
x,y = y,x+y
print x
return x
output is; when n = 5
0
1
1
2
3
5
second code is correct but,
x,y = y,x+y and
x = y , y = x+y
they look like same but outputs are different why?
They give different outputs because with x=y, then y=x+y, you are setting x to the value of y. Then you take x, once its value has been updated and add it to y to find the y variable. With the one line variable declaration (x,y=y,y+x) in the y = y+x part of the equation, it will use a previous value of x instead of what you set it to in that line.
If you had:
x=0
y=1
Then you tried the one line declaration, it would look like this:
x,y=1,0+1
x,y=y,x+y
I hope this helped :)
The difference is that you will update x and then use it in the first example and you will directly use it in the second example.
x, y = 0, 1
x = y # after this line x will be 1
y = x + y # y = 1 + 1
Second example
x,y = 0, 1
x,y = y,x+y # x, y = (1, 0 + 1) the old value of x will be used
This is because it will first generate the tuple on the right-hand side and after that, the tuple in your case (1, 1) will be assigned to x and y
If you want to go without tuple, you'll have to assign the value of x to a new variable z before updating it with the value of y and use this new variable to calculate the value of y.
The code is from a different problem, but the output is a Fibonacci sequence.
x = 0
y = 1
print(x)
while y < 50:
print(y)
z = x
x = y
y = z+y

How do I use recursion to iterate through surrounding locations in a grid?

I am creating a mineseweeper game.
It asks for user input (row,, column) to 'click' on a location in a grid. The number displayed in that location represents the number of bombs in the 8 surrounding locations on the grid. There are regular bombs, which make you lose a life, and proximity bombs, which also reveal all 8 surrounding locations.
I need to use a recursive function to:
Go through surrounding items of a location in a grid to count bombs so I know which number to put in the location.
When I 'click' on a 'proximity' bomb, it exposes all surrounding items.
When I click on a '0', it checks the surrounding items and exposes all other '0's and their surrounding items, for example:
X X X X X
X X X X X
X X X X X
1 1 1 1 1
0 0 0 0 0
Grid = 5 X 5, displayed as
X X X X X
X X X X X
X X X X X
X X X X X
X X X X X
User input asks for row and column, which are then stored in a tuple as a dictionary key. After every turn it reprints the grid, displaying the previous turns which are stored in the dictionary.
This is what I have now: goes through surrounding locations and calculates the number for that location. So if the number is '0', I have to reveal the surrounding locations, who also go through their surrounding locations to check for
> def getNum(pos, bombPos, grid):
> num = 0
> for i in range(pos[0] - 1, pos[0]+2):
> for j in range(pos[1]-1, pos[1] + 2):
> if (i,j) != pos:
> if (i,j) == bombPos:
> num += 1
I have a hard time grasping the recursion concept as a whole and how it could be used in this project. Any help is appreciated. Thanks.

Is there a programmatical way to find the start and end of a series?

I have an equally spaced numbers like this:
x 1 2 3 4 y
I don't know the start and end values x and y. x can be greater than y or vice versa. All I know is the value of the inbetween values and their order in the list, i.e. 1 has an index of 1 (x's index is 0), 2 has an index of 2, and so on.
I also know how many numbers in between, so 4 in this case.
Is there a way to formulate this so I can find x and y using this info?
EDIT: More info:
x != y
x > y or y > x
The program generated the numbers inbetween using x and y given the number of items requested. So a linear interpolation from x to y, using the same increment for each value.
If I understand you correctly, you want something like linear extrapolation. Try this:
def get_xy(values):
assert(len(values) >= 2)
#(v1) use the first gain
m = values[1] - values[0]
#(v2) calculate the mean-gain
# (avg of v[i+1]-v[i])
m = sum(float(x-y) for x,y in zip(values[1:], values[:-2])) / (len(values) - 1)
return (values[0] - 1*m, values[-1] + 1*m)
print get_xy([ 1, 2, 3, 4])
print get_xy([-1,-2,-3,-4])
x,y = get_xy([ 1, 2, 3, 4])
print x,y # if you are unfamilar with tuples
v(1) is fatser but will only work, if every element is incremented/ decremented by the same value (a(n+1) - a(n) == a(n+2) - a(n+1) for all n if ais your sequence). v(2) will calculate the mean-gain for all elements. Note that the values are casted to float.

Categories