WeixiangYan/CodeTransOcean huggingface dataset:
Task: Matrix with two diagonals


C++: #include <concepts>
#include <iostream>



void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
  for(int y = 0; y < size; y++)
  {
    for(int x = 0; x < size; x++)
    {
      std::cout << " " << f(x, y, size);
    }
    std::cout << "\n";
  }
  std::cout << "\n";
}

int main()
{
  
  auto diagonals = [](int x, int y, int size)
  {
    return x == y || ((size - x - 1) == y);
  };
  
  PrintMatrix(diagonals, 8);
  PrintMatrix(diagonals, 9);
}




Java: package example.diagdiag;

public class Program {

    public static void main(String[] args) {
        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);
        System.out.println(A);
    }

}

class DiagonalDiagonalMatrix {

    final int n;
    private double[][] a = null;

    public Matrix(int n) {
        this.n = n;
    }

    public double get(int i, int j) {
        if (a == null) {
            return (i == j || i == n - j + 1) ? 1.0 : 0.0;
        } else {
            return a[i - 1][j - 1];
        }
    }















    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sb.append('\t');
                sb.append(get(i, j));
            }
            sb.append('\n');
        }
        return sb.toString();
    }

}
Task: Matrix with two diagonals


C++: #include <concepts>
#include <iostream>



void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
  for(int y = 0; y < size; y++)
  {
    for(int x = 0; x < size; x++)
    {
      std::cout << " " << f(x, y, size);
    }
    std::cout << "\n";
  }
  std::cout << "\n";
}

int main()
{
  
  auto diagonals = [](int x, int y, int size)
  {
    return x == y || ((size - x - 1) == y);
  };
  
  PrintMatrix(diagonals, 8);
  PrintMatrix(diagonals, 9);
}






Python: 



def twoDiagonalMatrix(n):
    
    return matrix(
        n, n, lambda row, col: int(
            row in (col, 1 + (n - col))
        )
    )




def main():
    
    for n in [7, 8]:
        print(
            showMatrix(
                twoDiagonalMatrix(n)
            ) + '\n'
        )





def matrix(nRows, nCols, f):
    
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]



def showMatrix(rows):
    
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])



if __name__ == '__main__':
    main()
Task: Matrix with two diagonals




Go: package main

import "fmt"

func specialMatrix(n uint) {
    for i := uint(0); i < n; i++ {
        for j := uint(0); j < n; j++ {
            if i == j || i+j == n-1 {
                fmt.Printf("%d ", 1)
            } else {
                fmt.Printf("%d ", 0)
            }
        }
        fmt.Println()
    }
}

func main() {
    specialMatrix(8) 
    fmt.Println()
    specialMatrix(9) 
}


Java: package example.diagdiag;

public class Program {

    public static void main(String[] args) {
        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);
        System.out.println(A);
    }

}

class DiagonalDiagonalMatrix {

    final int n;
    private double[][] a = null;

    public Matrix(int n) {
        this.n = n;
    }

    public double get(int i, int j) {
        if (a == null) {
            return (i == j || i == n - j + 1) ? 1.0 : 0.0;
        } else {
            return a[i - 1][j - 1];
        }
    }















    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sb.append('\t');
                sb.append(get(i, j));
            }
            sb.append('\n');
        }
        return sb.toString();
    }

}
Task: Matrix with two diagonals





Java: package example.diagdiag;

public class Program {

    public static void main(String[] args) {
        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);
        System.out.println(A);
    }

}

class DiagonalDiagonalMatrix {

    final int n;
    private double[][] a = null;

    public Matrix(int n) {
        this.n = n;
    }

    public double get(int i, int j) {
        if (a == null) {
            return (i == j || i == n - j + 1) ? 1.0 : 0.0;
        } else {
            return a[i - 1][j - 1];
        }
    }















    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sb.append('\t');
                sb.append(get(i, j));
            }
            sb.append('\n');
        }
        return sb.toString();
    }

}



Python: 



def twoDiagonalMatrix(n):
    
    return matrix(
        n, n, lambda row, col: int(
            row in (col, 1 + (n - col))
        )
    )




def main():
    
    for n in [7, 8]:
        print(
            showMatrix(
                twoDiagonalMatrix(n)
            ) + '\n'
        )





def matrix(nRows, nCols, f):
    
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]



def showMatrix(rows):
    
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])



if __name__ == '__main__':
    main()
Task: Matrix with two diagonals




Go: package main

import "fmt"

func specialMatrix(n uint) {
    for i := uint(0); i < n; i++ {
        for j := uint(0); j < n; j++ {
            if i == j || i+j == n-1 {
                fmt.Printf("%d ", 1)
            } else {
                fmt.Printf("%d ", 0)
            }
        }
        fmt.Println()
    }
}

func main() {
    specialMatrix(8) 
    fmt.Println()
    specialMatrix(9) 
}




Python: 



def twoDiagonalMatrix(n):
    
    return matrix(
        n, n, lambda row, col: int(
            row in (col, 1 + (n - col))
        )
    )




def main():
    
    for n in [7, 8]:
        print(
            showMatrix(
                twoDiagonalMatrix(n)
            ) + '\n'
        )





def matrix(nRows, nCols, f):
    
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]



def showMatrix(rows):
    
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])



if __name__ == '__main__':
    main()
Task: Matrix with two diagonals

C: #include <stdio.h>

void specialMatrix(unsigned int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            if (i == j || i + j == n - 1) {
                printf("%d ", 1);
            } else {
                printf("%d ", 0);
            }
        }
        printf("\n");
    }
}

int main() {
    specialMatrix(10); 
    printf("\n");
    specialMatrix(11); 
    return 0;
}


C++: #include <concepts>
#include <iostream>



void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
  for(int y = 0; y < size; y++)
  {
    for(int x = 0; x < size; x++)
    {
      std::cout << " " << f(x, y, size);
    }
    std::cout << "\n";
  }
  std::cout << "\n";
}

int main()
{
  
  auto diagonals = [](int x, int y, int size)
  {
    return x == y || ((size - x - 1) == y);
  };
  
  PrintMatrix(diagonals, 8);
  PrintMatrix(diagonals, 9);
}
Task: Matrix with two diagonals

C: #include <stdio.h>

void specialMatrix(unsigned int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            if (i == j || i + j == n - 1) {
                printf("%d ", 1);
            } else {
                printf("%d ", 0);
            }
        }
        printf("\n");
    }
}

int main() {
    specialMatrix(10); 
    printf("\n");
    specialMatrix(11); 
    return 0;
}







Python: 



def twoDiagonalMatrix(n):
    
    return matrix(
        n, n, lambda row, col: int(
            row in (col, 1 + (n - col))
        )
    )




def main():
    
    for n in [7, 8]:
        print(
            showMatrix(
                twoDiagonalMatrix(n)
            ) + '\n'
        )





def matrix(nRows, nCols, f):
    
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]



def showMatrix(rows):
    
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])



if __name__ == '__main__':
    main()
Task: Matrix with two diagonals

C: #include <stdio.h>

void specialMatrix(unsigned int n) {
    int i, j;
    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            if (i == j || i + j == n - 1) {
                printf("%d ", 1);
            } else {
                printf("%d ", 0);
            }
        }
        printf("\n");
    }
}

int main() {
    specialMatrix(10); 
    printf("\n");
    specialMatrix(11); 
    return 0;
}






PHP: <?php

$n = 9; // the number of rows

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0';
    }
    echo "\n";
}
Task: Matrix with two diagonals


C++: #include <concepts>
#include <iostream>



void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
  for(int y = 0; y < size; y++)
  {
    for(int x = 0; x < size; x++)
    {
      std::cout << " " << f(x, y, size);
    }
    std::cout << "\n";
  }
  std::cout << "\n";
}

int main()
{
  
  auto diagonals = [](int x, int y, int size)
  {
    return x == y || ((size - x - 1) == y);
  };
  
  PrintMatrix(diagonals, 8);
  PrintMatrix(diagonals, 9);
}





PHP: <?php

$n = 9; // the number of rows

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0';
    }
    echo "\n";
}
Task: Matrix with two diagonals




Go: package main

import "fmt"

func specialMatrix(n uint) {
    for i := uint(0); i < n; i++ {
        for j := uint(0); j < n; j++ {
            if i == j || i+j == n-1 {
                fmt.Printf("%d ", 1)
            } else {
                fmt.Printf("%d ", 0)
            }
        }
        fmt.Println()
    }
}

func main() {
    specialMatrix(8) 
    fmt.Println()
    specialMatrix(9) 
}



PHP: <?php

$n = 9; // the number of rows

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0';
    }
    echo "\n";
}
Task: Matrix with two diagonals





Java: package example.diagdiag;

public class Program {

    public static void main(String[] args) {
        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);
        System.out.println(A);
    }

}

class DiagonalDiagonalMatrix {

    final int n;
    private double[][] a = null;

    public Matrix(int n) {
        this.n = n;
    }

    public double get(int i, int j) {
        if (a == null) {
            return (i == j || i == n - j + 1) ? 1.0 : 0.0;
        } else {
            return a[i - 1][j - 1];
        }
    }















    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sb.append('\t');
                sb.append(get(i, j));
            }
            sb.append('\n');
        }
        return sb.toString();
    }

}


PHP: <?php

$n = 9; // the number of rows

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0';
    }
    echo "\n";
}
Task: Matrix with two diagonals






PHP: <?php

$n = 9; // the number of rows

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j <= $n; $j++) {
        echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0';
    }
    echo "\n";
}


Python: 



def twoDiagonalMatrix(n):
    
    return matrix(
        n, n, lambda row, col: int(
            row in (col, 1 + (n - col))
        )
    )




def main():
    
    for n in [7, 8]:
        print(
            showMatrix(
                twoDiagonalMatrix(n)
            ) + '\n'
        )





def matrix(nRows, nCols, f):
    
    return [
        [f(y, x) for x in range(1, 1 + nCols)]
        for y in range(1, 1 + nRows)
    ]



def showMatrix(rows):
    
    return '\n'.join([
        ' '.join([str(x) for x in y]) for y in rows
    ])



if __name__ == '__main__':
    main()
Task: Top rank per group

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    const char *name, *id, *dept;
    int sal;
} person;

person ppl[] = {
    {"Tyler Bennett",   "E10297", "D101", 32000},
    {"John Rappl",      "E21437", "D050", 47000},
    {"George Woltman",  "E00127", "D101", 53500},
    {"Adam Smith",      "E63535", "D202", 18000},
    {"Claire Buckman",  "E39876", "D202", 27800},
    {"David McClellan", "E04242", "D101", 41500},
    {"Rich Holcomb",    "E01234", "D202", 49500},
    {"Nathan Adams",    "E41298", "D050", 21900},
    {"Richard Potter",  "E43128", "D101", 15900},
    {"David Motsinger", "E27002", "D202", 19250},
    {"Tim Sampair",     "E03033", "D101", 27000},
    {"Kim Arlich",      "E10001", "D190", 57000},
    {"Timothy Grove",   "E16398", "D190", 29900},
};

int pcmp(const void *a, const void *b)
{
    const person *aa = a, *bb = b;
    int x = strcmp(aa->dept, bb->dept);
    if (x) return x;
    return aa->sal > bb->sal ? -1 : aa->sal < bb->sal;
}

#define N sizeof(ppl)/sizeof(person)
void top(int n)
{
    int i, rank;
    qsort(ppl, N, sizeof(person), pcmp);

    for (i = rank = 0; i < N; i++) {
        if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) {
            rank = 0;
            printf("\n");
        }

        if (rank++ < n)
            printf("%s %d: %s\n", ppl[i].dept, ppl[i].sal, ppl[i].name);
    }
}

int main()
{
    top(2);
    return 0;
}





Java: import java.io.File;
import java.util.*;

public class TopRankPerGroup {

    private static class Employee {
        final String name;
        final String id;
        final String department;
        final int salary;

        Employee(String[] rec) {
            name = rec[0];
            id = rec[1];
            salary = Integer.parseInt(rec[2]);
            department = rec[3];
        }

        @Override
        public String toString() {
            return String.format("%s %s %d %s", id, name, salary, department);
        }
    }

    public static void main(String[] args) throws Exception {
        int N = args.length > 0 ? Integer.parseInt(args[0]) : 3;

        Map<String, List<Employee>> records = new TreeMap<>();
        try (Scanner sc = new Scanner(new File("data.txt"))) {
            while (sc.hasNextLine()) {
                String[] rec = sc.nextLine().trim().split(", ");

                List<Employee> lst = records.get(rec[3]);
                if (lst == null) {
                    lst = new ArrayList<>();
                    records.put(rec[3], lst);
                }
                lst.add(new Employee(rec));
            }
        }

        records.forEach((key, val) -> {
            System.out.printf("%nDepartment %s%n", key);
            val.stream()
                .sorted((a, b) -> Integer.compare(b.salary, a.salary))
                .limit(N).forEach(System.out::println);
        });
    }
}
Task: Top rank per group







Python: from collections import defaultdict
from heapq import nlargest
 
data = [('Employee Name', 'Employee ID', 'Salary', 'Department'),
        ('Tyler Bennett', 'E10297', 32000, 'D101'),
        ('John Rappl', 'E21437', 47000, 'D050'),
        ('George Woltman', 'E00127', 53500, 'D101'),
        ('Adam Smith', 'E63535', 18000, 'D202'),
        ('Claire Buckman', 'E39876', 27800, 'D202'),
        ('David McClellan', 'E04242', 41500, 'D101'),
        ('Rich Holcomb', 'E01234', 49500, 'D202'),
        ('Nathan Adams', 'E41298', 21900, 'D050'),
        ('Richard Potter', 'E43128', 15900, 'D101'),
        ('David Motsinger', 'E27002', 19250, 'D202'),
        ('Tim Sampair', 'E03033', 27000, 'D101'),
        ('Kim Arlich', 'E10001', 57000, 'D190'),
        ('Timothy Grove', 'E16398', 29900, 'D190')]
 
departments = defaultdict(list)
for rec in data[1:]:
    departments[rec[-1]].append(rec)
 
N = 3
format = " %-15s " * len(data[0])
for department, recs in sorted(departments.items()):
    print ("Department %s" % department)
    print (format % data[0])
    for rec in nlargest(N, recs, key=lambda rec: rec[-2]):
        print (format % rec)
    print('')


VB: Private Sub top_rank(filename As String, n As Integer)
    Workbooks.OpenText filename:=filename, Comma:=True
    Dim ws As Worksheet
    Set ws = Sheets.Add: ws.Name = "output"
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "data!R1C1:R14C4", Version:=6).CreatePivotTable TableDestination:= _
        "output!R3C1", TableName:="TableName", DefaultVersion:=6
    With Sheets("output").PivotTables("TableName")
        .InGridDropZones = True
        .RowAxisLayout xlTabularRow
        .AddDataField Sheets("output").PivotTables("TableName"). _
                PivotFields("Salary"), "Top rank", xlSum
        .PivotFields("Department").Orientation = xlRowField
        .PivotFields("Department").Position = 1
        .PivotFields("Salary").Orientation = xlRowField
        .PivotFields("Salary").Position = 2
        .PivotFields("Employee Name").Orientation = xlRowField
        .PivotFields("Employee Name").Position = 3
        .PivotFields("Employee ID").Orientation = xlRowField
        .PivotFields("Employee ID").Position = 4
        .PivotFields("Salary").PivotFilters.Add2 Type:=xlTopCount, _
            DataField:=Sheets("output").PivotTables("TableName"). _
            PivotFields("Top rank"), Value1:=n
        .PivotFields("Salary").Subtotals = Array(False, False, False, False, _
            False, False, False, False, False, False, False, False)
        .PivotFields("Employee Name").Subtotals = Array(False, False, False, _
            False, False, False, False, False, False, False, False, False)
        .PivotFields("Department").Subtotals = Array(False, False, False, False, _
            False, False, False, False, False, False, False, False)
        .ColumnGrand = False
        .PivotFields("Salary").AutoSort xlDescending, "Salary"
    End With
End Sub

Public Sub main()
    top_rank filename:="D:\data.txt", n:=3
End Sub
Task: Top rank per group

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    const char *name, *id, *dept;
    int sal;
} person;

person ppl[] = {
    {"Tyler Bennett",   "E10297", "D101", 32000},
    {"John Rappl",      "E21437", "D050", 47000},
    {"George Woltman",  "E00127", "D101", 53500},
    {"Adam Smith",      "E63535", "D202", 18000},
    {"Claire Buckman",  "E39876", "D202", 27800},
    {"David McClellan", "E04242", "D101", 41500},
    {"Rich Holcomb",    "E01234", "D202", 49500},
    {"Nathan Adams",    "E41298", "D050", 21900},
    {"Richard Potter",  "E43128", "D101", 15900},
    {"David Motsinger", "E27002", "D202", 19250},
    {"Tim Sampair",     "E03033", "D101", 27000},
    {"Kim Arlich",      "E10001", "D190", 57000},
    {"Timothy Grove",   "E16398", "D190", 29900},
};

int pcmp(const void *a, const void *b)
{
    const person *aa = a, *bb = b;
    int x = strcmp(aa->dept, bb->dept);
    if (x) return x;
    return aa->sal > bb->sal ? -1 : aa->sal < bb->sal;
}

#define N sizeof(ppl)/sizeof(person)
void top(int n)
{
    int i, rank;
    qsort(ppl, N, sizeof(person), pcmp);

    for (i = rank = 0; i < N; i++) {
        if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) {
            rank = 0;
            printf("\n");
        }

        if (rank++ < n)
            printf("%s %d: %s\n", ppl[i].dept, ppl[i].sal, ppl[i].name);
    }
}

int main()
{
    top(2);
    return 0;
}







Python: from collections import defaultdict
from heapq import nlargest
 
data = [('Employee Name', 'Employee ID', 'Salary', 'Department'),
        ('Tyler Bennett', 'E10297', 32000, 'D101'),
        ('John Rappl', 'E21437', 47000, 'D050'),
        ('George Woltman', 'E00127', 53500, 'D101'),
        ('Adam Smith', 'E63535', 18000, 'D202'),
        ('Claire Buckman', 'E39876', 27800, 'D202'),
        ('David McClellan', 'E04242', 41500, 'D101'),
        ('Rich Holcomb', 'E01234', 49500, 'D202'),
        ('Nathan Adams', 'E41298', 21900, 'D050'),
        ('Richard Potter', 'E43128', 15900, 'D101'),
        ('David Motsinger', 'E27002', 19250, 'D202'),
        ('Tim Sampair', 'E03033', 27000, 'D101'),
        ('Kim Arlich', 'E10001', 57000, 'D190'),
        ('Timothy Grove', 'E16398', 29900, 'D190')]
 
departments = defaultdict(list)
for rec in data[1:]:
    departments[rec[-1]].append(rec)
 
N = 3
format = " %-15s " * len(data[0])
for department, recs in sorted(departments.items()):
    print ("Department %s" % department)
    print (format % data[0])
    for rec in nlargest(N, recs, key=lambda rec: rec[-2]):
        print (format % rec)
    print('')
Task: Top rank per group





Java: import java.io.File;
import java.util.*;

public class TopRankPerGroup {

    private static class Employee {
        final String name;
        final String id;
        final String department;
        final int salary;

        Employee(String[] rec) {
            name = rec[0];
            id = rec[1];
            salary = Integer.parseInt(rec[2]);
            department = rec[3];
        }

        @Override
        public String toString() {
            return String.format("%s %s %d %s", id, name, salary, department);
        }
    }

    public static void main(String[] args) throws Exception {
        int N = args.length > 0 ? Integer.parseInt(args[0]) : 3;

        Map<String, List<Employee>> records = new TreeMap<>();
        try (Scanner sc = new Scanner(new File("data.txt"))) {
            while (sc.hasNextLine()) {
                String[] rec = sc.nextLine().trim().split(", ");

                List<Employee> lst = records.get(rec[3]);
                if (lst == null) {
                    lst = new ArrayList<>();
                    records.put(rec[3], lst);
                }
                lst.add(new Employee(rec));
            }
        }

        records.forEach((key, val) -> {
            System.out.printf("%nDepartment %s%n", key);
            val.stream()
                .sorted((a, b) -> Integer.compare(b.salary, a.salary))
                .limit(N).forEach(System.out::println);
        });
    }
}



Python: from collections import defaultdict
from heapq import nlargest
 
data = [('Employee Name', 'Employee ID', 'Salary', 'Department'),
        ('Tyler Bennett', 'E10297', 32000, 'D101'),
        ('John Rappl', 'E21437', 47000, 'D050'),
        ('George Woltman', 'E00127', 53500, 'D101'),
        ('Adam Smith', 'E63535', 18000, 'D202'),
        ('Claire Buckman', 'E39876', 27800, 'D202'),
        ('David McClellan', 'E04242', 41500, 'D101'),
        ('Rich Holcomb', 'E01234', 49500, 'D202'),
        ('Nathan Adams', 'E41298', 21900, 'D050'),
        ('Richard Potter', 'E43128', 15900, 'D101'),
        ('David Motsinger', 'E27002', 19250, 'D202'),
        ('Tim Sampair', 'E03033', 27000, 'D101'),
        ('Kim Arlich', 'E10001', 57000, 'D190'),
        ('Timothy Grove', 'E16398', 29900, 'D190')]
 
departments = defaultdict(list)
for rec in data[1:]:
    departments[rec[-1]].append(rec)
 
N = 3
format = " %-15s " * len(data[0])
for department, recs in sorted(departments.items()):
    print ("Department %s" % department)
    print (format % data[0])
    for rec in nlargest(N, recs, key=lambda rec: rec[-2]):
        print (format % rec)
    print('')