UK Bebras

 
 

OUCC Tutorials: code submission [3 of 4]

Tutorials index

Code Submission Tasks

Example 2 - Postfix
This task is used to illustrate

  • using a starter file
  • how to read from standard input
  • how to write to standard output
  • how the testing system can produce partial marks.

The task begins with some background information and instructions and in this case a starter file. To obtain the file you need to download the linked TXT file open it and then choose the file that uses the programming language you want to work with.

If you were to just paste the code from the provided file, it will compile but fail half the tests.

In this instance, because there are four tests, when the Score is produced you can get a further breakdown by clicking on the 'results' link next to your submission.



Lets look at the Python 3 file provided. (If you are using a different language open your own file and use the Python code as pseudocode to follow along.)

inputs = input().split()

a = int(inputs[0])
b = int(inputs[1])
operator = inputs[2]

if operator == "+":
    print(a + b)

It is fairly easy to see why this code only scores 50% when entered into the system. Two of the test cases require the + operator and two of the test cases require the * operator. Peter's code does not handle the * operator.

As we are told that there will only be these two operators we could solve the problem with an else clause (and this would score 100%) but this is not good style. We may later want to exptend this to handle minus and divide operations too. It is better therefore to use an elif statement with another test for the * operator.

The question grader runs a number of test files through the submitted program. There can be just one or a lot of them. They are not declared to the participants. After submission you are told what percentage of these tests have been passed successfully. In some of the more advanced tasks a test file might run thousands of separate smaller tests to check the code being submitted is efficient enough. Here are the tests going on in the background for this simple task:

test 1:
input: 2 4 +
expected output: 6

test 2:
input: 2 4 *
expected output: 8

test 3:
input: 10 20 +
expected output: 30

test 4:
input: 10 20 *
expected output: 200

In Python, one way of solving the first test would be to count characters in the string and do this:

my_string = input()

a = int(inputs[0])
b = int(inputs[3])
operator = inputs[5]

if operator == "+":
    print(a + b)

This would fail test 3 so we need to split the input by looking for spaces in the string provided in the input cases.

Try and solve the problem above, without looking at the answers below, to make sure you understand everything that is involved.

Important Note:
Do not send a string to standard output to ask for input.
Anything sent to standard output will be considered an answer, causing your programs to fail all tests.
my_string = input() is correct
my_string = input("Please enter your first number: ") will fail all tests.

Final Answers:

Language

Filename

Program

C

postfix.c

#include <stdio.h>
#include <string.h>

int main() {
  int a, b;
  char expr;
  scanf("%d %d %c", &a, &b, &expr);

  if (expr=='+') {
    printf("%d", a+b);
  }
  else if (expr=='*') {
    printf("%d", a*b);
  }
}

C++

postfix.cpp

#include <iostream>
#include <string>

using namespace std;

int main() {
  int a, b;
  string expr;
  cin >> a >> b >> expr;

  if (expr=="+") {
    cout << a+b;
  }
  else if (expr=="*") {
    std::cout << a*b;
  }
}

C#

postfix.cs

using System;

public class postfix {
  public static void Main() {
    string[] elements;
    elements = Console.ReadLine().Split(' ');
    if (elements[2]=="+") {
      Console.WriteLine(Int32.Parse(elements[0])+Int32.Parse(elements[1]));
    }
    if (elements[2]=="*") {
      Console.WriteLine(Int32.Parse(elements[0])*Int32.Parse(elements[1]));
    }
  }
}

Haskell

postfix.hs

main :: IO ()
main = interact ((++ "\n") . show . eval . words)
  where
    eval :: [String] -> Int
    eval [x, y, "+"] = read x + read y
    eval [x, y, "*"] = read x * read y

Java

postfix.java

[class needs to have same name as file]

import java.util.Scanner;

class postfix {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    String op = scanner.next();
    if(op.equals("+")) { System.out.println(a + b); }
    if(op.equals("*")) { System.out.println(a * b); }
  }
}

Javascript

postfix.js

#!/usr/bin/env node

'use strict';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('', (answer) => {
  // Answer Logic goes here:
  let values = answer.split(' ');
  if (values[2] === '+') {
    console.log(Number(values[0]) + Number(values[1]));
  } else if (values[2] === '*') {
    console.log(Number(values[0]) * Number(values[1]));
  };
  rl.close();
});

Kotlin

postfix.kt

fun main(args : Array<String>) {
 val (a, b, op) = readln()!!.split(' ')

  when(op) {
    "+" -> println(a.toInt() + b.toInt())
    "*" -> println(a.toInt() * b.toInt())
  }
}

Pascal

postfix.pas

program postfix;
uses sysutils;

var
  a, b: integer;
  c: string;
begin
  readln(a, b, c);
  c := Trim(c);
  if c='+' then
    begin
      writeln(a+b);
    end
  else
    begin
      writeln(a*b);
    end;
end.

Python 3

postfix.py

inputs = input().split()

a = int(inputs[0])
b = int(inputs[1])
operator = inputs[2]

if operator == "+":
    print(a + b)
elif operator == "*":
    print(a * b)

Ruby

postfix.rb

line = gets
parts = line.split ( " " )

if parts[2] == '+'
    puts parts[0].to_i + parts[1].to_i;
else
    puts parts[0].to_i * parts[1].to_i;
end

Visual Basic

postfix.vb

Module Postfix
Sub Main()
    Dim Inputargs() As String
    Dim Answer As Integer

    Inputargs = Console.ReadLine().Split(" ")
    If Inputargs(2) = "+" Then
        Answer = Int(Inputargs(0)) + Int(Inputargs(1))
    End If
    If Inputargs(2) = "*" Then
        Answer = Int(Inputargs(0)) * Int(Inputargs(1))
    End If
    Console.WriteLine(Answer)
End Sub
End Module

 

<< Back | Next >>

Code submission tasks - Intro

Example 1 - Hello, World!
Example 2 - Postfix
Exercise - Cat Words

Tutorials index