Why does my Go solution to this problem fail, when Python passes?

Hi,

I am teaching myself Go by doing simple programming challenges. One problem I have solved in Python is this one:

https://codeforces.com/contest/463/problem/B

My code in Python that passes all the tests is as follows:

import math
import os

file = os.sys.stdin

n = int(file.readline().split(' ')[0])

heights = file.readline().split(' ')
heights.insert(0, 0)

cost = 0
energy = 0

for i, _ in enumerate(heights):
    if i == 0:
        continue
    gain = int(heights[i - 1]) - int(heights[i])
    energy += gain

    if energy < 0:
        cost += -energy
        energy = 0

print(cost)

However, when I translate this to Go, my solution fails. My solution in Go:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)


func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	check(err)

	scanner.Scan()
	heights := strings.Fields(scanner.Text())
	heights = append([]string{"0"}, heights...)

	cost := 0
	energy := 0

	for i := 1; i <= n; i ++ {
		a, err := strconv.Atoi((heights[i - 1]))
		check(err)

		b, err := strconv.Atoi((heights[i]))
		check(err)

		gain := a - b
		energy += gain

		if energy < 0 {
			cost += -energy
			energy = 0
		}
	}

	fmt.Println(cost)
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
} 

The reason is that it fails Test 9. Here is the error message:

Now it seems something is going wrong with the string conversion. I have read the documents but cannot figure out what is going on. Could someone please guide me through what this could be?

Instead of strings.Split() I also used the strings.Fields() function, but that also failed.

Thank you!

Your program need an argument from stdin (eg, command line). Without any valid value will give an error in line 16.

https://play.golang.org/p/9-V6AnYx_R9

1 Like

Thanks @geosoft1,

I can see that the issue is line 16 now. But I am still not sure what is going on as the Codeforces server should provide input as seen in the picture with the error message.

For the failing case, it should be 100000, and a bunch of numbers in the second line.

Is there a reason why the input of 100000 is not being picked up by the Codeforces server when it runs the program? Am I making a mistake somewhere?

EDIT: I figured it out - I am using a Mac and the newline character is ā€˜\nā€™, whereas the server is using a carriage return ā€˜\r\nā€™ as the newline character. Switching to a newline for Windows fixed it.

1 Like