Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Algorithm to find min max possible 'islands' [closed]

$
0
0

Given a string. 'g' means the land and the 'o' means the sea. The part of the map that does not know whether it is land or sea is marked with an 'x'. Write a program that tells you the minimum and maximum possible number of islands given the map. An island is a series of lands that are on both sides of the ocean.

Example 1

Input:

oxxxo

Output:

02

Heres my attempt to solve the problem

def calculate_islands(world_map):     islands = 0     is_island = False     for char in world_map:         if char == 'g':             is_island = True         elif char == 'o':             if is_island:                 islands += 1                 is_island = False         if is_island:             islands += 1         return islandsdef x_calculate(world_map):     if 'x' not in world_map:         return calculate_islands(world_map), calculate_islands(world_map)    minimum = len(world_map)    maximum = 0    minimum = min(minimum, calculate_islands(world_map.replace('x', 'o')))    minimum = min(minimum, calculate_islands(world_map.replace('x', 'g')))    temp_map = world_map[:]    for i in range(len(temp_map)):        if temp_map[i] == 'x':            if i == 0 or temp_map[i-1] == 'o':                temp_map = temp_map[:i] +'g'+ temp_map[i+1:]            else:                temp_map = temp_map[:i] +'o'+ temp_map[i+1:]    maximum = calculate_islands(temp_map)    return minimum, maximumworld_map = input() min_islands, max_islands = x_calculate(world_map) print(min_islands) print(max_islands)

Is this code correct? How can I improve it?


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>