Reputation: 13
so i have this assignment where i'm given a "map"
island = \
[' /---------\ ',
' | x \ ',
' / \--\ ',
' / x | ',
' | x | ',
' \ \ ',
' \ x /\/\ / ',
' \---/ \ | ',
' /--/ ']
Write a program that counts the number of treasures on the island (x marks the spot) and creates a list of coordinates, e.g. [(1,11), ...] ((1,11) is the actual location of the top treasure in the example) and then prints out a report in the form: There are 3 treasures. There is a treasure at (1,11). There is a treasure at .... Hint: start with a (very short) expression for the symbol in the ith row and the jth column.
Write a program that calculates the length of the coastline. Assume that an '-'
and a '|'
are 1 mile
, and a '\'
, '/'
is 1.4 miles
. (This is only a very rough estimate, for many reasons, some of them mathematical).
i'm not even sure where to begin here....can anybody help me out or at the very least point me in the right direction?
Upvotes: 0
Views: 6047
Reputation: 1
I am a beginner to python and the problem is quite interesting, my solution to this problem is as follows: thanks to @Eric for giving an idea for start
island = \
[' /---------\ ',
' | x \ ',
' / \--\ ',
' / x | ',
' | x | ',
' \ \ ',
' \ x /\/\ / ',
' \---/ \ | ',
' /--/ ']
Distance={
"-":1.0,
"|":1,
"\\":1.4,
"/":1.4
}
Treasure_Location = []
Miles = []
for row, line in enumerate(island):
#print(row, line)
for column, cell in enumerate(line):
if cell== "x":
Treasure_Location.append((row, column))
if cell in Distance:
z=Distance.get(cell)
Miles.append(z)
Total_miles= sum(Miles)
print ("Co-ordinates of the Treasure in the Island are:\n")
print("\nTreasure 1: " + str(Treasure_Location[0]))
print("\nTreasure 2: " + str(Treasure_Location[1]))
print("\nTreasure 3: " + str(Treasure_Location[2]))
print("\nTreasure 4: " + str(Treasure_Location[3]))
print("\nThe length of the Coastal line is:"+str(Total_miles))
Upvotes: 0
Reputation: 747
2 dimensional grids are pretty easily represented in some sort of an array. Create an array that stores all of your grid in a way you understand how to lookup what coordinate x,y is in that array.
Check for all the treasures by iterating through the array's indexes.
The coastline is just a perimeter measurement but it's represented much simpler, every character you find is equivalent to some number. Just run a loop again, looking for these character and when you encounter them, increase some running sum of the coastline.
*You could do all of this in a single loop or in other simple ways...best way for you to do it is to break it up into pieces so you understand how to do this.
Upvotes: 0
Reputation: 97571
For the sake of posting a (semi-pythonic) solution:
# reads as it means - coords where the cell is "x"
treasure_coords = [
(x, y) for y, row in enumerate(island)
for x, c in enumerate(row)
if c == 'x'
]
# slightly more cryptic
coast_length = sum(
1 if c in '-|' else
1.4 if c in '/\\' else
0
for c in ''.join(island)
)
Upvotes: 1
Reputation: 45542
Since people are posting complete solutions, here is one that is Pythonic but not advanced.
segment_lengths = {'\\':1.4,'/':1.4,'-':1,'|':1}
coast_len = 0
treasure_coords = []
for y, line in enumerate(island):
for x, c in enumerate(line):
coast_len += segment_lengths.get(c, 0)
if c == 'x':
treasure_coords.append((y, x))
print len(treasure_coords), 'treasures found at', treasure_coords
print 'island coast length is', coast_len
Prints:
4 treasures found at [(1, 11), (3, 8), (4, 14), (6, 9)]
island coast length is 49.0
edit: J.F. Sebastian offers an if-elif based solution:
coast_length = 0
treasure_coords = []
for y, row in enumerate(island):
for x, c in enumerate(row):
if c in r'\/':
coast_length += 1.4
elif c in '-|':
coast_length += 1
elif c == 'x':
treasure_coords.append((y, x))
print("There are %d treasures." % (len(treasure_coords),))
for y, x in treasure_coords:
print("There is a treasure at (%2d, %2d)." % (y, x))
print("The length of the coastline is %.1f." % (coast_length,))
Upvotes: 1
Reputation: 250931
Pythonic solution for length of coastline part:
In [144]: strs
Out[144]:
[' /---------\\ ',
' | x \\ ',
' / \\--\\ ',
' / x | ',
' | x | ',
' \\ \\ ',
' \\ x /\\/\\ / ',
' \\---/ \\ | ',
' /--/ ']
In [145]: dic={'\\':1.4,'/':1.4,'-':1,'|':1}
In [146]: sum(dic.get(y,0) for x in strs for y in x)
Out[146]: 48.999999999999979
or
In [149]: sum(map(lambda x:dic.get(x,0),chain(*strs)))
Out[149]: 48.999999999999979
or (As suggested by Eric):
In [197]: sum(dic.get(x,0) for x in chain(*strs))
Out[197]: 48.999999999999979
for co-ordinates:
In [185]: [(i,m.start()) for i,x in enumerate(strs) for m in re.finditer('x',x)]
Out[185]: [(1, 11), (3, 8), (4, 14), (6, 9)]
Upvotes: 0
Reputation: 1209
Since each line is a value in a list, you can use a simple 'in' check to see if there is a treasure.
for line in island:
if 'x' in island[line]:
print '%d,%d' %line,island[line].index('x')
Easy way to get your cords.
Upvotes: -1
Reputation: 3224
To get the length of the coastline, you just need to count the instances of each coast character.
>>> from itertools import groupby
>>> dict([(k, len(list(g))) for k, g in groupby(sorted(''.join(island)))])
{' ': 162, '-': 16, '/': 9, '\\': 11, 'x': 4, '|': 5}
Then you can add them up:
>>> char_counts = dict([(k, len(list(g))) for k, g in groupby(sorted(''.join(island)))])
>>> char_counts['-'] + char_counts['|'] + 1.4 * (char_counts['/'] + char_counts['\\'])
49.0
Upvotes: 0
Reputation: 77
Very simple way to do that would be just iterate over every single char (recording the current col/row_ and check it for being 'x' or one of the coast symbols. Like that:
length = 0.0
x = 0
y = 0
for line in island:
x += 1
y = 0
for char in line:
y += 1
if char == 'x': print 'There is a treasure at (%d,%d)' % (x, y)
elif char in ('-', '|'):
length += 1
elif char in ('\\', '/'):
length += 1.4
print 'Coast length is', length
Of course it doesn't check for treasures in the sea, coast integrity, etc.
Upvotes: 0
Reputation: 97571
First thing you'll want to do is iterate over the array
for column, line in enumerate(island):
print column, line
That gives you
0 /---------\
1 | x \
2 / \--\
3 / x |
4 | x |
5 \ \
6 \ x /\/\ /
7 \---/ \ |
8 /--/
Ok, so how about iterating horizontally over each row? Exactly the same:
for column, line in enumerate(island):
for row, cell in enumerate(line):
print "entry at", row, column, "is", cell
Warning: gives long output!
That should be enough to get you started
Upvotes: 7