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


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


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:
    gain = int(heights[i - 1]) - int(heights[i])
    energy += gain

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


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

package main

import (

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

	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]))

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

		gain := a - b
		energy += gain

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


func check(err error) {
	if err != nil {

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.


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