Skip to content

559 Problems, 790 Solutions, 11 Languages

🟡 10 Kinds of People

Solution in Python
# 22/25


from copy import deepcopy

row, col = [int(d) for d in input().split()]
m = []
for _ in range(row):
    m.append([int(d) for d in input()])

directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]


def reachable(m, r1, c1, r2, c2):
    _m = deepcopy(m)

    q = []
    q.append((r1, c1))
    kind = _m[r1][c1]

    while len(q):
        r, c = q.pop()
        _m[r][c] = -1

        if (r, c) == (r2, c2):
            return True

        for x, y in directions:
            a = r + x
            b = c + y
            if a >= 0 and b >= 0 and a < row and b < col and _m[a][b] == kind:
                q.append((a, b))

    return False


n = int(input())
for _ in range(n):
    r1, c1, r2, c2 = [int(d) - 1 for d in input().split()]
    if reachable(m, r1, c1, r2, c2):
        print("decimal" if m[r1][c1] else "binary")
    else:
        print("neither")

🟡 1-D Frogger (Easy)

Solutions in 2 languages
#include <iostream>

using namespace std;

int main()
{
    int n, s, m, curspace, cnt = 0;
    cin >> n >> s >> m;
    int board[n];

    for (int i = 0; i < n; i++)
    {
        int tmp;
        cin >> tmp;
        board[i] = tmp;
    }
    curspace = s - 1;

    while (true)
    {
        if (curspace < 0)
        {
            cout << "left" << endl;
            break;
        }
        else if (curspace > n - 1)
        {
            cout << "right" << endl;
            break;
        }
        int temp = board[curspace];
        if (temp == 999)
        {
            cout << "cycle" << endl;
            break;
        }
        else if (temp == m)
        {
            cout << "magic" << endl;
            break;
        }
        else
        {
            cnt += 1;
            board[curspace] = 999;
            curspace += temp;
        }
    }
    cout << cnt << endl;
}
n, s, m = [int(d) for d in input().split()]
b = [int(d) for d in input().split()]
visited, hops = set(), 0
while True:
    if s in visited:
        print("cycle")
        break
    elif s < 1:
        print("left")
        break
    elif s > n:
        print("right")
        break
    elif b[s - 1] == m:
        print("magic")
        break
    else:
        visited.add(s)
        s += b[s - 1]
        hops += 1
print(hops)

🟡 3D Printed Statues

Solutions in 4 languages
package main

import (
    "fmt"
    "math"
)

func main() {
    var n int
    fmt.Scan(&n)
    d := 1.0
    for math.Pow(2, d-1) < float64(n) {
        d += 1
    }
    fmt.Println(d)
}
import java.util.Scanner;

class ThreeDPrintedStatues {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int d = 1;
        while (Math.pow(2, d - 1) < n) {
            d += 1;
        }
        System.out.println(d);
    }
}
1
2
3
4
5
6
n = io.read("*n")
d = 1
while 2 ^ (d - 1) < n do
    d = d + 1
end
print(d)
1
2
3
4
5
n = int(input())
d = 1
while 2 ** (d - 1) < n:
    d += 1
print(d)

🟡 4 thought

Solution in Python
from itertools import product

ops = ["+", "-", "*", "//"]

for _ in range(int(input())):
    s = int(input())
    solved = False
    for op1, op2, op3 in product(ops, ops, ops):
        e = f"4 {op1} 4 {op2} 4 {op3} 4"
        try:
            ans = eval(e) == s
        except:
            ans = False
        if ans:
            print(f"{e.replace('//','/')} = {s}")
            solved = True
            break
    if not solved:
        print("no solution")

🟡 99 Problems

Solutions in 2 languages
1
2
3
4
5
6
7
8
n = io.read("*n")
ceil = math.ceil(n / 100) * 100 - 1
floor = math.floor(n / 100) * 100 - 1
if math.abs(ceil - n) <= math.abs(n - floor) or floor < 0 then
    print(ceil)
else
    print(floor)
end
import math

n = int(input())
ceil = math.ceil(n / 100) * 100 - 1
floor = math.floor(n / 100) * 100 - 1
if ceil == floor:
    print(ceil)
else:
    if abs(ceil - n) <= abs(n - floor) or floor < 0:
        print(ceil)
    else:
        print(floor)

🟢 Aaah!

Solutions in 3 languages
package main

import (
    "fmt"
    "strings"
)

func main() {
    var a, b string
    fmt.Scan(&a)
    fmt.Scan(&b)
    if strings.Count(a, "a") >= strings.Count(b, "a") {
        fmt.Println("go")
    } else {
        fmt.Println("no")
    }
}
1
2
3
4
5
6
7
8
a, b = io.read(), io.read()
_, na = a:gsub("a", "")
_, nb = b:gsub("a", "")
if na >= nb then
    print("go")
else
    print("no")
end
1
2
3
4
5
a, b = input(), input()
if a.count("a") >= b.count("a"):
    print("go")
else:
    print("no")

🟢 ABC

Solution in Python
1
2
3
4
5
6
7
8
9
numbers = sorted([int(d) for d in input().split()])
orders = list(input())
order_map = {
    "A": 0,
    "B": 1,
    "C": 2,
}

print(" ".join([str(numbers[order_map[o]]) for o in orders]))

🟢 Above Average

Solution in Python
1
2
3
4
5
6
n = int(input())
for _ in range(n):
    numbers = [int(d) for d in input().split()[1:]]
    ave = sum(numbers) / len(numbers)
    above_ave = [d > ave for d in numbers]
    print(f"{sum(above_ave)/len(numbers):.3%}")

🟢 ACM Contest Scoring

Solution in Python
problems = {}
solved = set()
while True:
    line = input()
    if line == "-1":
        break
    t, p, ans = line.split()
    t = int(t)
    if p in solved:
        continue
    if p not in problems:
        problems[p] = [(t, ans)]
    else:
        problems[p].append((t, ans))
    if ans == "right":
        solved.add(p)

score = 0
for p in problems:
    t, ans = problems[p][-1]
    if ans == "right":
        score += t + 20 * len(problems[p][:-1])

print(len(solved), score)

🟢 Adding Trouble

Solutions in 2 languages
1
2
3
4
5
6
a, b, c = io.read("*n", "*n", "*n")
if a + b == c then
    print("correct!")
else
    print("wrong!")
end
1
2
3
4
5
a, b, c = [int(v) for v in input().split()]
if a + b == c:
    print("correct!")
else:
    print("wrong!")

🟡 Adding Words

Solution in Python
name = {}
value = {}
op = ["-", "+"]
while True:
    try:
        s = input().split()
    except:
        break

    if s[0] == "clear":
        name.clear()
        value.clear()
    elif s[0] == "def":
        n, v = s[1:]
        v = int(v)
        if n in name:
            value.pop(name[n])
        name[n] = v
        value[v] = n
    elif s[0] == "calc":
        try:
            ans = eval("".join([str(name[p]) if p not in op else p for p in s[1:-1]]))
        except:
            ans = "unknown"

        ans = value.get(ans, "unknown")
        print(" ".join(s[1:] + [ans]))

🟢 Add Two Numbers

Solutions in 5 languages
package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Println(a + b)
}
1
2
3
4
5
6
7
8
9
import java.util.Scanner;

class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = s.nextInt(), b = s.nextInt();
        System.out.println(a + b);
    }
}
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (line) => {
  [a, b] = line
    .trim()
    .split(" ")
    .map((e) => parseInt(e));
  console.log(a + b);
});
a, b = io.read("*n", "*n")
print(a + b)
1
2
3
4
5
line = input()
a, b = line.split()
a = int(a)
b = int(b)
print(a + b)

🟢 Akcija

Solution in Python
1
2
3
4
5
6
7
n = int(input())
c = [int(input()) for _ in range(n)]

c = sorted(c, reverse=True)
groups = [c[i : i + 3] if i + 3 < n else c[i:] for i in range(0, n, 3)]

print(sum(sum(g if len(g) < 3 else g[:2]) for g in groups))

🟢 Á leið í bíó

Solutions in 5 languages
#include <iostream>

using namespace std;

int main()
{
    int a, b, c;
    cin >> a >> b >> c;
    cout << c - a - b << endl;
    return 0;
}
package main

import "fmt"

func main() {
    var a, b, c int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Scan(&c)
    fmt.Println(c - a - b)
}
import java.util.Scanner;

class Aleidibio {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        int b = s.nextInt();
        int c = s.nextInt();
        System.out.println(c - a - b);
    }
}
a, b, c = io.read("*n", "*n", "*n")
print(c - a - b)
1
2
3
4
a = int(input())
b = int(input())
c = int(input())
print(c - a - b)

🟡 Alex and Barb

Solutions in 2 languages
1
2
3
4
5
6
7
k, m, n = io.read("*n", "*n", "*n")

if k % (m + n) < m then
    print("Barb")
else
    print("Alex")
end
1
2
3
k, m, n = [int(d) for d in input().split()]

print("Barb" if k % (m + n) < m else "Alex")

🟢 Alphabet Spam

Solution in Python
s = input()
total = len(s)
whites = s.count("_")
lowers = len([c for c in s if ord(c) >= ord("a") and ord(c) <= ord("z")])
uppers = len([c for c in s if ord(c) >= ord("A") and ord(c) <= ord("Z")])
symbols = total - whites - lowers - uppers
print(f"{whites/total:.15f}")
print(f"{lowers/total:.15f}")
print(f"{uppers/total:.15f}")
print(f"{symbols/total:.15f}")

🟢 Amerískur vinnustaður

Solutions in 2 languages
print(io.read("*n") * 0.09144)
print(int(input()) * 0.09144)

🟢 Amsterdam Distance

Solution in Python
import math

m, n, r = input().split()
m = int(m)
n = int(n)
r = float(r)
coords = [int(d) for d in input().split()]
p = r / n

dist1 = 0
dist1 += p * abs(coords[1] - coords[3])
dist1 += (
    math.pi
    * r
    * ((min(coords[3], coords[1]) if coords[3] != coords[1] else coords[1]) / n)
    * (abs(coords[0] - coords[2]) / m)
)

dist2 = p * abs(coords[1] + coords[3])

print(min(dist1, dist2))

🟢 A New Alphabet

Solutions in 2 languages
package main

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

func main() {
    mapping := map[string]string{
        "a": "@",
        "b": "8",
        "c": "(",
        "d": "|)",
        "e": "3",
        "f": "#",
        "g": "6",
        "h": "[-]",
        "i": "|",
        "j": "_|",
        "k": "|<",
        "l": "1",
        "m": "[]\\/[]",
        "n": "[]\\[]",
        "o": "0",
        "p": "|D",
        "q": "(,)",
        "r": "|Z",
        "s": "$",
        "t": "']['",
        "u": "|_|",
        "v": "\\/",
        "w": "\\/\\/",
        "x": "}{",
        "y": "`/",
        "z": "2",
    }
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    line := scanner.Text()
    runes := []rune(strings.ToLower(line))
    for i := 0; i < len(runes); i++ {
        v, ok := mapping[string(runes[i])]
        if ok {
            fmt.Printf(v)
        } else {
            fmt.Printf(string(runes[i]))
        }
    }
}
mapping = {
    "a": "@",
    "b": "8",
    "c": "(",
    "d": "|)",
    "e": "3",
    "f": "#",
    "g": "6",
    "h": "[-]",
    "i": "|",
    "j": "_|",
    "k": "|<",
    "l": "1",
    "m": "[]\\/[]",
    "n": "[]\\[]",
    "o": "0",
    "p": "|D",
    "q": "(,)",
    "r": "|Z",
    "s": "$",
    "t": "']['",
    "u": "|_|",
    "v": "\\/",
    "w": "\\/\\/",
    "x": "}{",
    "y": "`/",
    "z": "2",
}
print("".join([mapping.get(c, c) for c in input().lower()]))

🟢 Another Brick in the Wall

Solution in Python
h, w, n = [int(d) for d in input().split()]
b = [int(d) for d in input().split()]

i, tw, th, done = 0, 0, 0, False
while i < n:
    if tw + b[i] <= w:
        tw += b[i]
        if tw == w:
            tw = 0
            th += 1
        if th == h and tw == 0:
            done = True
            break
    else:
        break
    i += 1

print("YES" if done else "NO")

🟡 Another Candies

Solution in Python
1
2
3
4
5
6
7
8
9
for _ in range(int(input())):
    _ = input()
    n = int(input())
    s = 0
    for _ in range(n):
        s += int(input())
        if s > n:
            s %= n
    print("NO" if s % n else "YES")

🟢 Apaxiaaaaaaaaaaaans!

Solution in Python
1
2
3
4
5
6
name = input()
compact = ""
for s in name:
    if not compact or s != compact[-1]:
        compact += s
print(compact)

🟢 Honour Thy (Apaxian) Parent

Solution in Python
y, p = input().split()
if y.endswith("e"):
    name = y + "x" + p
elif y[-1] in "aiou":
    name = y[:-1] + "ex" + p
elif y.endswith("ex"):
    name = y + p
else:
    name = y + "ex" + p

print(name)

🟢 A Real Challenge

Solutions in 4 languages
package main

import (
    "fmt"
    "math"
)

func main() {
    var a int
    fmt.Scan(&a)
    fmt.Println(4 * math.Sqrt(float64(a)))
}
1
2
3
4
5
6
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (a) => {
  console.log(4 * Math.sqrt(parseInt(a)));
});
s = io.read("*n")
print(4 * math.sqrt(s))
1
2
3
4
import math

s = int(input())
print(4 * math.sqrt(s))

🟢 Are You Listening?

Solution in Python
import math

cx, cy, n = [int(d) for d in input().split()]

d = []
for _ in range(n):
    x, y, r = [int(d) for d in input().split()]
    d.append(((x - cx) ** 2 + (y - cy) ** 2) ** 0.5 - r)
v = sorted(d)[2]
print(math.floor(v) if v > 0 else 0)

🟡 Arithmetic

Solution in Python
import math

mapping8 = {
    "0": "000",
    "1": "001",
    "2": "010",
    "3": "011",
    "4": "100",
    "5": "101",
    "6": "110",
    "7": "111",
}
mapping16 = {
    "0000": "0",
    "0001": "1",
    "0010": "2",
    "0011": "3",
    "0100": "4",
    "0101": "5",
    "0110": "6",
    "0111": "7",
    "1000": "8",
    "1001": "9",
    "1010": "A",
    "1011": "B",
    "1100": "C",
    "1101": "D",
    "1110": "E",
    "1111": "F",
}

b = "".join([mapping8[c] for c in input()])
b = b.zfill(math.ceil(len(b) / 4) * 4)
ans = "".join([mapping16[b[i : i + 4]] for i in range(0, len(b), 4)])
if ans != "0":
    ans = ans.lstrip("0")
print(ans)

🟢 Arithmetic Functions

Solution in C++
#include "arithmeticfunctions.h"

// Compute x^3
int cube(int x)
{
    return x * x * x;
}

// Compute the maximum of x and y
int max(int x, int y)
{
    if (x > y)
    {
        return x;
    }
    else
    {
        return y;
    }
}

// Compute x - y
int difference(int x, int y)
{
    return x - y;
}

🟢 Arm Coordination

Solutions in 2 languages
1
2
3
4
5
x, y, r = io.read("*n", "*n", "*n")
print(x - r, y - r)
print(x + r, y - r)
print(x + r, y + r)
print(x - r, y + r)
1
2
3
4
5
6
x, y = [int(d) for d in input().split()]
r = int(input())
print(x - r, y - r)
print(x + r, y - r)
print(x + r, y + r)
print(x - r, y + r)

🟢 Army Strength (Easy)

Solution in Python
t = int(input())
for _ in range(t):
    input()
    ng, nm = [int(d) for d in input().split()]
    g = [int(d) for d in input().split()]
    m = [int(d) for d in input().split()]
    if max(m) > max(g):
        print("MechaGodzilla")
    else:
        print("Godzilla")

🟢 Army Strength (Hard)

Solution in Python
t = int(input())
for _ in range(t):
    input()
    ng, nm = [int(d) for d in input().split()]
    g = [int(d) for d in input().split()]
    m = [int(d) for d in input().split()]
    if max(m) > max(g):
        print("MechaGodzilla")
    else:
        print("Godzilla")

🟢 ASCII kassi

Solution in Python
1
2
3
4
5
n = int(input())
print(f'+{"-"*n}+')
for _ in range(n):
    print(f'|{" "*n}|')
print(f'+{"-"*n}+')

🟢 ASCII Kassi 2

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())
print(" " * (n + 1) + "x")
for i in range(n):
    print(" " * (n - i) + "/" + " " * (2 * i + 1) + "\\")
print("x" + " " * (2 * n + 1) + "x")
for i in range(n):
    print(" " * (i + 1) + "\\" + " " * (2 * (n - i) - 1) + "/")
print(" " * (n + 1) + "x")

🟢 Astrological Sign

Solutions in 2 languages
for _ = 1, io.read("*n") do
    d = io.read("*n")
    m = io.read():gsub("%s+", "")

    if (m == "Mar" and d >= 21) or (m == "Apr" and d <= 20) then
        print("Aries")
    elseif (m == "Apr" and d >= 21) or (m == "May" and d <= 20) then
        print("Taurus")
    elseif (m == "May" and d >= 21) or (m == "Jun" and d <= 21) then
        print("Gemini")
    elseif (m == "Jun" and d >= 22) or (m == "Jul" and d <= 22) then
        print("Cancer")
    elseif (m == "Jul" and d >= 23) or (m == "Aug" and d <= 22) then
        print("Leo")
    elseif (m == "Aug" and d >= 23) or (m == "Sep" and d <= 21) then
        print("Virgo")
    elseif (m == "Sep" and d >= 22) or (m == "Oct" and d <= 22) then
        print("Libra")
    elseif (m == "Oct" and d >= 23) or (m == "Nov" and d <= 22) then
        print("Scorpio")
    elseif (m == "Nov" and d >= 23) or (m == "Dec" and d <= 21) then
        print("Sagittarius")
    elseif (m == "Dec" and d >= 22) or (m == "Jan" and d <= 20) then
        print("Capricorn")
    elseif (m == "Jan" and d >= 21) or (m == "Feb" and d <= 19) then
        print("Aquarius")
    elseif (m == "Feb" and d >= 20) or (m == "Mar" and d <= 20) then
        print("Pisces")
    end
end
for _ in range(int(input())):
    d, m = input().split()
    d = int(d)
    if (m == "Mar" and d >= 21) or (m == "Apr" and d <= 20):
        print("Aries")
    elif (m == "Apr" and d >= 21) or (m == "May" and d <= 20):
        print("Taurus")
    elif (m == "May" and d >= 21) or (m == "Jun" and d <= 21):
        print("Gemini")
    elif (m == "Jun" and d >= 22) or (m == "Jul" and d <= 22):
        print("Cancer")
    elif (m == "Jul" and d >= 23) or (m == "Aug" and d <= 22):
        print("Leo")
    elif (m == "Aug" and d >= 23) or (m == "Sep" and d <= 21):
        print("Virgo")
    elif (m == "Sep" and d >= 22) or (m == "Oct" and d <= 22):
        print("Libra")
    elif (m == "Oct" and d >= 23) or (m == "Nov" and d <= 22):
        print("Scorpio")
    elif (m == "Nov" and d >= 23) or (m == "Dec" and d <= 21):
        print("Sagittarius")
    elif (m == "Dec" and d >= 22) or (m == "Jan" and d <= 20):
        print("Capricorn")
    elif (m == "Jan" and d >= 21) or (m == "Feb" and d <= 19):
        print("Aquarius")
    elif (m == "Feb" and d >= 20) or (m == "Mar" and d <= 20):
        print("Pisces")

🟢 Attendance

Solution in Python
n = int(input())
s = []
for _ in range(n):
    c = input()
    if c == "Present!":
        s.pop()
    else:
        s.append(c)
if not s:
    print("No Absences")
else:
    print("\n".join(s))

🟢 Autori

Solution in Python
print("".join([part[0] for part in input().split("-")]))

🟢 Average Character

Solution in Python
1
2
3
4
s = input()
s = [ord(c) for c in s]
s = sum(s) // len(s)
print(chr(s))

🟡 Paradox With Averages

Solution in Python
for _ in range(int(input())):
    input()
    ncs, ne = [int(d) for d in input().split()]
    students_cs, students_e = [], []

    while len(students_cs) < ncs or len(students_e) < ne:
        iq = [int(d) for d in input().split()]
        if len(students_cs) <= ncs:
            if len(iq) + len(students_cs) <= ncs:
                students_cs.extend(iq)
            else:
                ind = ncs - len(students_cs)
                students_cs.extend(iq[:ind])
                students_e.extend(iq[ind:])
        else:
            students_e.extend(iq)

    ave_cs, ave_e = sum(students_cs) / ncs, sum(students_e) / ne
    print(sum(p < ave_cs and p > ave_e for p in students_cs))

🟡 Paradox With Averages (Hard)

Solution in Python
for _ in range(int(input())):
    input()
    ncs, ne = [int(d) for d in input().split()]
    students_cs, students_e = [], []

    while len(students_cs) < ncs or len(students_e) < ne:
        iq = [int(d) for d in input().split()]
        if len(students_cs) <= ncs:
            if len(iq) + len(students_cs) <= ncs:
                students_cs.extend(iq)
            else:
                ind = ncs - len(students_cs)
                students_cs.extend(iq[:ind])
                students_e.extend(iq[ind:])
        else:
            students_e.extend(iq)

    ave_cs, ave_e = sum(students_cs) / ncs, sum(students_e) / ne
    print(sum(p < ave_cs and p > ave_e for p in students_cs))

🟢 Avion

Solution in Python
1
2
3
4
5
6
7
8
9
ans = []
for i in range(5):
    row = input()
    if "FBI" in row:
        ans.append(str(i + 1))
if not ans:
    print("HE GOT AWAY!")
else:
    print(" ".join(ans))

🟢 Babelfish

Solution in Python
d = []
while True:
    line = input()
    if not line:
        break
    w, f = line.split()
    d.append((f, w))

d = dict(d)
while True:
    try:
        line = input()
    except:
        break
    print(d.get(line, "eh"))

🟢 Baby Bites

Solution in Python
1
2
3
4
5
6
n = int(input())
a = input().split()
c = [str(d) for d in range(1, n + 1)]
inplace = [i == j if i.isnumeric() and j.isnumeric() else None for i, j in zip(a, c)]
inplace = [v for v in inplace if v is not None]
print("makes sense" if all(inplace) else "something is fishy")

🟢 Baby Panda

Solution in Python
1
2
3
4
5
6
7
8
9
import math

n, m = [int(d) for d in input().split()]
d = 0
while m:
    c = math.floor(math.log(m, 2))
    d += 1
    m -= 2**c
print(d)

🟢 Backspace

Solution in Python
1
2
3
4
5
6
7
ans = []
for c in input():
    if c != "<":
        ans.append(c)
    else:
        ans.pop()
print("".join(ans))

🟢 Bacon, Eggs, and Spam

Solution in Python
while True:
    n = int(input())
    if not n:
        break
    record = {}
    for _ in range(n):
        order = input().split()
        name = order[0]
        items = order[1:]
        for item in items:
            if item not in record:
                record[item] = [name]
            else:
                record[item].append(name)
    for name in sorted(record):
        print(name, " ".join(sorted(record[name])))
    print()

🟢 Bannorð

Solution in Python
1
2
3
s = set(input())
m = input().split()
print(" ".join(["*" * len(p) if s & set(p) else p for p in m]))

🟢 Basketball One-on-One

Solutions in 2 languages
1
2
3
4
5
6
7
8
9
import java.util.Scanner;

class BasketballOneOnOne {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String scores = s.nextLine();
        System.out.println(scores.charAt(scores.length() - 2));
    }
}
1
2
3
4
5
6
7
8
scores = input()
size = len(scores)
a = sum([int(scores[i + 1]) for i in range(size) if scores[i] == "A"])
b = sum([int(scores[i + 1]) for i in range(size) if scores[i] == "B"])
if a > b:
    print("A")
else:
    print("B")

🟢 Batter Up

Solution in Python
1
2
3
4
_ = input()
at_bats = [int(d) for d in input().split()]
ans = [d for d in at_bats if d >= 0]
print(sum(ans) / len(ans))

🟢 Beat the Spread!

Solution in Python
1
2
3
4
5
6
for _ in range(int(input())):
    a, b = [int(d) for d in input().split()]
    if a < b or (a + b) % 2:
        print("impossible")
    else:
        print((a + b) // 2, (a - b) // 2)

🟢 Beavergnaw

Solution in Python
import math

while True:
    D, V = [int(d) for d in input().split()]
    if not D and not V:
        break
    # R = D / 2
    # r = d / 2
    # V + π * (r**2) * (2*r) + 2 * (1/3) * π * (R-r) * (r**2 + r*R + R**2) == π * (R**2) * (2*R)
    print(math.pow(D**3 - 6 * V / math.pi, 1 / 3))

🟢 Beekeeper

Solution in Python
def count(word):
    return sum(word.count(c * 2) for c in "aeiouy")


while True:
    n = int(input())
    if not n:
        break
    words = []
    for _ in range(n):
        words.append(input())
    print(max(words, key=count))

🟢 Bela

Solution in Python
table = {
    "A": {True: 11, False: 11},
    "K": {True: 4, False: 4},
    "Q": {True: 3, False: 3},
    "J": {True: 20, False: 2},
    "T": {True: 10, False: 10},
    "9": {True: 14, False: 0},
    "8": {True: 0, False: 0},
    "7": {True: 0, False: 0},
}

n, b = input().split()
n = int(n)
total = 0

for _ in range(4 * n):
    card = input()
    f, s = card[0], card[1]
    total += table[f][s == b]

print(total)

🟢 Besta gjöfin

Solution in Python
1
2
3
4
5
6
7
n = int(input())
d = {}
for _ in range(n):
    k, v = input().split()
    v = int(v)
    d[k] = v
print(max(d, key=lambda k: d[k]))

🟢 Best Compression Ever

Solutions in 2 languages
1
2
3
4
5
6
n, b = io.read("*n", "*n")
if (2 ^ (b + 1)) - 1 >= n then
    print("yes")
else
    print("no")
end
n, b = [int(d) for d in input().split()]
print("yes" if (2 ** (b + 1)) - 1 >= n else "no")

🟢 Betting

Solutions in 3 languages
package main

import "fmt"

func main() {
    var a float32
    fmt.Scan(&a)
    fmt.Printf("%.10f", 100/a)
    fmt.Println()
    fmt.Printf("%.10f", 100/(100-a))
}
1
2
3
a = io.read("*n")
print(string.format("%.10f", 100 / a))
print(string.format("%.10f", 100 / (100 - a)))
1
2
3
a = int(input())
print(f"{100/a:.10f}")
print(f"{100/(100-a):.10f}")

🟢 Bijele

Solution in Python
1
2
3
should_contain = (1, 1, 2, 2, 2, 8)
found = [int(d) for d in input().split()]
print(" ".join([str(a - b) for a, b in zip(should_contain, found)]))

🟢 Bilað Lyklaborð

Solution in Python
1
2
3
4
5
6
7
s = input()
p = s[0]
print(p, end="")
for c in s[1:]:
    if c != p:
        print(c, end="")
    p = c

🟢 Bitte ein Bit

Solution in Python
print(input()[-1])

🟢 Black Friday

Solution in Python
from collections import Counter

n = input()
a = [int(d) for d in input().split()]
c = Counter(a)
keys = [k for k in c if c[k] == 1]
if not keys:
    print("none")
else:
    print(a.index(max(keys)) + 1)

🟢 Blaðra

Solutions in 2 languages
v, a, t = io.read("*n", "*n", "*n")
print(string.format("%.5f", v * t + a * t * t / 2))
v, a, t = [int(d) for d in input().split()]
print(f"{v*t+a*t*t/2:.5f}")

🟢 Blandað Best

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())
s = set()
for _ in range(n):
    s.add(input())
if len(s) == 2:
    print("blandad best")
else:
    print(s.pop())

🟢 Blueberry Waffle

Solutions in 2 languages
r, f = io.read("*n", "*n")

a = f // r
b = (f - a * r) / r >= 0.5 and 1 or 0

if (a + b) % 2 == 0 then
    print("up")
else
    print("down")
end
1
2
3
4
5
6
r, f = [int(d) for d in input().split()]

a = f // r
b = (f - a * r) / r >= 0.5

print("up" if (a + b) % 2 == 0 else "down")

🟢 Bluetooth

Solution in Python
n = int(input())
cond = {}


def f(t):
    if t[0].isdigit():
        return (f'R{"u" if t[1]=="+" else "l"}', t[0])
    else:
        return (f'L{"u" if t[0]=="+" else "l"}', t[1])


for _ in range(n):
    t, p = input().split()
    q, d = f(t)
    if p == "b":
        if p not in cond:
            cond[p] = [q]
        else:
            cond[p].append(q)
    elif p == "m":
        if p not in cond:
            cond[p] = [(q, d)]
        else:
            cond[p].append((q, d))

l, r = True, True

if "R" in [c[0] for c in cond.get("b", [])]:
    r = False
if "L" in [c[0] for c in cond.get("b", [])]:
    l = False

ru = len([d for q, d in cond.get("m", []) if q == "Ru"])
rl = len([d for q, d in cond.get("m", []) if q == "Rl"])
lu = len([d for q, d in cond.get("m", []) if q == "Lu"])
ll = len([d for q, d in cond.get("m", []) if q == "Ll"])

if ru == 8 or rl == 8:
    r = False
if lu == 8 or ll == 8:
    l = False

if not l and not r:
    print(2)
elif l and not r:
    print(0)
elif r and not l:
    print(1)
else:
    print("?")

🟢 Boat Parts

Solution in Python
p, n = [int(d) for d in input().split()]
boat = set()
d = -1
for i in range(n):
    w = input()
    boat.add(w)
    if len(boat) == p:
        d = i + 1
        break
if d == -1:
    print("paradox avoided")
else:
    print(d)

🟢 Booking a Room

Solution in Python
1
2
3
4
r, n = [int(d) for d in input().split()]
booked = [int(input()) for _ in range(n)]
available = set(range(1, 1 + r)) - set(booked)
print("too late" if r == n else available.pop())

🟢 Boss Battle

Solutions in 2 languages
1
2
3
4
5
6
n = io.read("*n")
if n // 4 > 0 then
    print(n - 2)
else
    print(1)
end
n = int(input())
print(n - 2 if n // 4 else 1)

🟢 Bottled-Up Feelings

Solution in Python
s, v1, v2 = [int(d) for d in input().split()]

n1 = s // v1
if not s % v1:
    print(n1, 0)
else:
    while True:
        if not (s - n1 * v1) % v2:
            print(n1, (s - n1 * v1) // v2)
            break
        else:
            n1 -= 1
            if n1 < 0:
                break
    if n1 < 0:
        print("Impossible")

🟢 Bounding Robots

Solution in Python
while True:
    room_x, room_y = [int(d) for d in input().split()]
    if not room_x and not room_y:
        break

    robot_x, robot_y = 0, 0
    actual_x, actual_y = 0, 0

    n = int(input())
    for _ in range(n):
        direction, step = input().split()
        step = int(step)

        if direction == "u":
            robot_y += step
            actual_y = min(room_y - 1, actual_y + step)
        elif direction == "d":
            robot_y -= step
            actual_y = max(0, actual_y - step)
        elif direction == "r":
            robot_x += step
            actual_x = min(room_x - 1, actual_x + step)
        elif direction == "l":
            robot_x -= step
            actual_x = max(0, actual_x - step)

    print(f"Robot thinks {robot_x} {robot_y}")
    print(f"Actually at {actual_x} {actual_y}")
    print()

🟢 Bracket Matching

Solution in Python
n = int(input())
s = input()
stack = []
is_valid = True
for i in range(n):
    c = s[i]
    if c in ("(", "[", "{"):
        stack.append(c)
    else:
        if len(stack) == 0:
            is_valid = False
            break
        last = stack.pop()
        if c == ")" and last != "(":
            is_valid = False
            break
        if c == "]" and last != "[":
            is_valid = False
            break
        if c == "}" and last != "{":
            is_valid = False
            break

print("Valid" if is_valid and not len(stack) else "Invalid")

🟢 Breaking Branches

Solutions in 7 languages
package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
    if n%2 == 0 {
        fmt.Println("Alice")
        fmt.Println(1)
    } else {
        fmt.Println("Bob")
    }
}
1
2
3
4
5
6
7
main = do
    input <- getLine
    let n = (read input :: Int)
    if  n `mod` 2  ==  0
    then do putStrLn "Alice"
            putStrLn "1"
        else putStrLn "Bob"
import java.util.Scanner;

class BreakingBranches {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        if (n % 2 == 0) {
            System.out.println("Alice");
            System.out.println(1);
        } else {
            System.out.println("Bob");
        }
    }
}
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (n) => {
  if (parseInt(n) % 2) {
    console.log("Bob");
  } else {
    console.log("Alice");
    console.log(1);
  }
});
1
2
3
4
5
6
7
8
fun main() {
    if (readLine()!!.toInt() % 2 == 0) {
        println("Alice")
        println(1)
    } else {
        println("Bob")
    }
}
1
2
3
4
5
6
7
n = io.read("*n")
if n % 2 == 1 then
    print('Bob')
else
    print('Alice')
    print(1)
end
1
2
3
4
5
6
n = int(input())
if n % 2:
    print("Bob")
else:
    print("Alice")
    print(1)

🟡 Broken Calculator

Solution in Python
prev = 1
for _ in range(int(input())):
    a, op, b = input().split()
    a, b = int(a), int(b)
    if op == "+":
        ans = a + b - prev
    elif op == "-":
        ans = (a - b) * prev
    elif op == "*":
        ans = (a * b) ** 2
    elif op == "/":
        ans = (a + 1) // 2 if a % 2 else a // 2

    print(ans)
    prev = ans

🟢 Broken Swords

Solution in Python
tb, lr = 0, 0
for _ in range(int(input())):
    s = input()
    tb += s[:2].count("0")
    lr += s[2:].count("0")

swords = min(tb, lr) // 2
tb -= swords * 2
lr -= swords * 2

print(f"{swords} {tb} {lr}")

🟢 Buka

Solution in Python
a, op, b = input(), input(), input()
pa, pb = a.count("0"), b.count("0")
if op == "*":
    print(f"1{'0'*(pa+pb)}")
elif op == "+":
    if pa == pb:
        ans = f"2{'0'*pa}"
    else:
        ans = f"1{'0'*(abs(pa-pb)-1)}1{'0'*min(pa,pb)}"
    print(ans)

🟢 Bus

Solution in Python
1
2
3
4
5
6
7
8
9
def f(n):
    if n == 1:
        return 1
    else:
        return int(2 * (f(n - 1) + 0.5))


for _ in range(int(input())):
    print(f(int(input())))

🟢 Bus Numbers

Solution in Python
n = int(input())
numbers = sorted([int(d) for d in input().split()])

prev = numbers[0]
ans = {prev: 1}
for i in range(1, n):
    if numbers[i] == prev + ans[prev]:
        ans[prev] += 1
    else:
        prev = numbers[i]
        ans[prev] = 1

print(
    " ".join(
        [
            f"{key}-{key+value-1}"
            if value > 2
            else " ".join([str(d) for d in range(key, key + value)])
            for key, value in ans.items()
        ]
    )
)

🟡 Calculator

Solution in Python
1
2
3
4
5
while True:
    try:
        print(f"{eval(input()):.2f}")
    except:
        break

🟢 Calories From Fat

Solution in Python
mapping = {"fat": 9, "protein": 4, "sugar": 4, "starch": 4, "alcohol": 7}


def c(x, category):
    if "g" in x:
        return (int(x[:-1]) * mapping[category], "C")
    elif "C" in x:
        return (int(x[:-1]), "C")
    elif "%" in x:
        return (int(x[:-1]) / 100, "%")


def solve(items):
    fat_c, total_c = 0, 0
    for fat, protein, sugar, starch, alcohol in items:
        fat_c += fat
        total_c += fat + protein + sugar + starch + alcohol

    return f"{fat_c/total_c:.0%}"


items = []
while True:
    s = input()
    if s == "-":
        if not items:
            break
        print(solve(items))

        items = []
        continue

    fat, protein, sugar, starch, alcohol = s.split()
    mapping.keys()

    total_c, total_p = 0, 0

    reading = []
    for v, k in zip(s.split(), mapping.keys()):
        n, t = c(v, k)
        if t == "C":
            total_c += n
        elif t == "%":
            total_p += n
        reading.append((n, t))

    total_c = total_c / (1 - total_p)

    item = []
    for n, t in reading:
        if t == "%":
            item.append(n * total_c)
        else:
            item.append(n)

    items.append(item)

🟢 Canadians, eh?

Solutions in 3 languages
package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    line := scanner.Text()
    if strings.HasSuffix(line, "eh?") {
        fmt.Println("Canadian!")
    } else {
        fmt.Println("Imposter!")
    }
}
import java.util.Scanner;

class CanadiansEh {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String line = s.nextLine();
        if (line.endsWith("eh?")) {
            System.out.println("Canadian!");
        } else {
            System.out.println("Imposter!");
        }
    }
}
1
2
3
4
5
line = input()
if line.endswith("eh?"):
    print("Canadian!")
else:
    print("Imposter!")

🟢 Candy Store

Solution in Python
n, q = [int(d) for d in input().split()]
m = {}
for _ in range(n):
    name = input()
    init = "".join([p[0] for p in name.split()])
    if init not in m:
        m[init] = name
    else:
        m[init] = "ambiguous"
for _ in range(q):
    print(m.get(input(), "nobody"))

🟢 Careful Ascent

Solution in Python
a, b = [int(d) for d in input().split()]
n = int(input())
shields = []
for _ in range(n):
    l, u, f = input().split()
    l = int(l)
    u = int(u)
    f = float(f)
    shields.append((l, u, f))

shields.append((b,))
s = shields[0][0]
for i in range(n):
    s += (shields[i][1] - shields[i][0]) * shields[i][2]
    s += shields[i + 1][0] - shields[i][1]
print(f"{a/s:.6f}")

🟢 Solving for Carrots

Solutions in 2 languages
1
2
3
4
5
n, ans = io.read("*n", "*n")
for _ = 1, n do
    io.read()
end
print(ans)
1
2
3
4
n, ans = [int(d) for d in input().split()]
for _ in range(n):
    input()
print(ans)

🟡 Catalan Numbers

Solution in Python
1
2
3
4
5
6
7
8
# https://en.wikipedia.org/wiki/Catalan_number
p = [1]
for i in range(10000):
    p.append(p[-1] * (i + 1))

for _ in range(int(input())):
    n = int(input())
    print(p[2 * n] // (p[n + 1] * p[n]))

🟡 CD

Solution in Python
while True:
    n, m = [int(d) for d in input().split()]
    if not n and not m:
        break
    a = [int(input()) for _ in range(n)]
    b = [int(input()) for _ in range(m)]
    total, i, j = 0, 0, 0
    while i < n and j < m:
        if a[i] == b[j]:
            total += 1
            i += 1
            j += 1
        elif a[i] < b[j]:
            i += 1
        else:
            j += 1
    while i < n:
        if a[i] == b[-1]:
            total += 1
            break
        i += 1
    while j < n:
        if a[-1] == b[j]:
            total += 1
            break
        j += 1
    print(total)

🟢 Cetiri

Solutions in 2 languages
package main

import (
    "fmt"
    "sort"
)

func main() {
    var a, b, c int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Scan(&c)
    s := []int{a, b, c}
    sort.Ints(s)
    a, b, c = s[0], s[1], s[2]
    if c-b == b-a {
        fmt.Println(c + c - b)
    } else if c-b > b-a {
        fmt.Println(c - b + a)
    } else {
        fmt.Println(a + c - b)
    }
}
1
2
3
4
5
6
7
a, b, c = sorted([int(d) for d in input().split()])
if c - b == b - a:
    print(c + c - b)
elif c - b > b - a:
    print(c - b + a)
else:
    print(a + c - b)

🟢 Cetvrta

Solution in Python
from collections import Counter

x, y = Counter(), Counter()

for _ in range(3):
    _x, _y = [int(d) for d in input().split()]
    x[_x] += 1
    y[_y] += 1


for key in x:
    if x[key] == 1:
        print(key, " ")
        break

for key in y:
    if y[key] == 1:
        print(key)
        break

🟢 Champernowne Verification

Solution in Python
n = input()
k = 0
while n:
    k += 1
    if n.startswith(str(k)):
        n = n[len(str(k)) :]
    else:
        k = -1
        break
print(k)

🟢 Chanukah Challenge

Solutions in 2 languages
1
2
3
4
for _ = 1, io.read("*n") do
    k, n = io.read("*n", "*n")
    print(k, math.floor((1 + n) * n / 2 + n))
end
1
2
3
for _ in range(int(input())):
    k, n = [int(d) for d in input().split()]
    print(k, int((1 + n) * n / 2 + n))

🟢 Character Development

Solution in Python
def f(m):
    ans = 0
    for n in range(2, m + 1):
        a, b = 1, 1
        for i in range(m - n + 1, m + 1):
            a *= i
        for i in range(1, n + 1):
            b *= i
        ans += a // b
    return ans


print(f(int(input())))

🟢 Chocolate Division

Solutions in 2 languages
1
2
3
4
5
6
7
8
9
r, c = io.read("*n", "*n")

chocolate_bar_cuts = (r * c) - 1

if chocolate_bar_cuts % 2 == 1 then
    print("Alf")
else
    print("Beata")
end
1
2
3
4
5
6
7
8
r, c = [int(v) for v in input().split()]

chocolate_bar_cuts = (r * c) - 1

if chocolate_bar_cuts % 2 == 1:
    print("Alf")
else:
    print("Beata")

🟢 Preludes

Solution in Python
alternatives = [("A#", "Bb"), ("C#", "Db"), ("D#", "Eb"), ("F#", "Gb"), ("G#", "Ab")]


m = dict(alternatives + [(b, a) for a, b in alternatives])

i = 1
while True:
    try:
        s = input()
    except:
        break
    key, tone = s.split()
    if key in m:
        print(f"Case {i}: {m[key]} {tone}")
    else:
        print(f"Case {i}: UNIQUE")

    i += 1

🟢 Chugging

Solutions in 2 languages
n, ta, da, tb, db = io.read("*n", "*n", "*n", "*n", "*n")
a = n * ta + da * (n - 1) * n / 2
b = n * tb + db * (n - 1) * n / 2
if a == b then
    print("=")
elseif a < b then
    print("Alice")
else
    print("Bob")
end
n = int(input())
ta, da = [int(d) for d in input().split()]
tb, db = [int(d) for d in input().split()]
a = n * ta + da * (n - 1) * n / 2
b = n * tb + db * (n - 1) * n / 2
if a == b:
    print("=")
elif a < b:
    print("Alice")
else:
    print("Bob")

🟢 Cinema Crowds

Solution in Python
n, m = [int(v) for v in input().split()]

size = [int(v) for v in input().split()]

groups_admitted = 0

for i in range(m):
    if size[i] <= n:
        n -= size[i]
        groups_admitted += 1

print(m - groups_admitted)

🟢 Cinema Crowds 2

Solution in Python
n, m = [int(t) for t in input().split()]
p = [int(t) for t in input().split()]

d = 0
l = 0
for i in range(m):
    if p[i] > n - d:
        break
    else:
        k = p[i]
        d += k
        l += 1

print(m - l)

🟢 Class Field Trip

Solution in Python
a = input()
b = input()

i, j = 0, 0
ans = []
while i < len(a) and j < len(b):
    if a[i] < b[j]:
        ans.append(a[i])
        i += 1
    else:
        ans.append(b[j])
        j += 1


ans += a[i:] if i < len(a) else b[j:]

print("".join(ans))

🟢 Climbing Worm

Solutions in 2 languages
a, b, h = io.read("*n", "*n", "*n")
t = 0
while h >= 0 do
    h = h - a
    t = t + 1
    if h <= 0 then
        break
    end
    h = h + b
end
print(t)
1
2
3
4
5
6
7
8
9
a, b, h = [int(d) for d in input().split()]
t = 0
while h >= 0:
    h -= a
    t += 1
    if h <= 0:
        break
    h += b
print(t)

🟡 A Furious Cocktail

Solution in Python
n, t = [int(d) for d in input().split()]
p = [int(input()) for _ in range(n)]
p = sorted(p, reverse=True)
ending = p[0]
able = True
for i in range(1, n):
    if t * i >= ending:
        print("NO")
        able = False
        break
    if t * i + p[i] < ending:
        ending = t * i + p[i]
if able:
    print("YES")

🟡 Code Cleanups

Solution in Python
n = int(input())
p = [int(d) for d in input().split()]
prev = []
t = 0
for v in p:
    if not prev:
        prev.append(v)
        continue
    d = (19 + sum(prev)) // len(prev)
    if v <= d:
        prev.append(v)
    else:
        prev = [v]
        t += 1
if prev:
    t += 1
print(t)

🟢 Code to Save Lives

Solution in Python
1
2
3
4
5
t = int(input())
for _ in range(t):
    a = int(input().replace(" ", ""))
    b = int(input().replace(" ", ""))
    print(" ".join(str(a + b)))

🟢 Coffee Cup Combo

Solution in Python
n = int(input())
awake = [0] * n
s = list(input())
for i in range(n):
    if s[i] == "1":
        awake[i] = 1
        if i + 1 < n:
            awake[i + 1] = 1
        if i + 2 < n:
            awake[i + 2] = 1
print(sum(awake))

🟢 Cold-puter Science

Solution in Python
_ = input()
print(len([t for t in input().split() if "-" in t]))

🟢 Jumbled Compass

Solutions in 2 languages
1
2
3
4
5
6
n1, n2 = io.read("*n", "*n")
d = (n2 - n1) % 360
if d > 180 then
    d = d - 360
end
print(d)
1
2
3
4
5
n1, n2 = int(input()), int(input())
d = (n2 - n1) % 360
if d > 180:
    d -= 360
print(d)

🟢 Competitive Arcade Basketball

Solution in Python
from collections import Counter

n, p, m = [int(d) for d in input().split()]

records = Counter()
winners = []
names = [input() for _ in range(n)]
for r in range(m):
    name, point = input().split()
    point = int(point)
    records[name] += point
    if records[name] >= p and name not in winners:
        winners.append(name)
if not winners:
    print("No winner!")
else:
    print("\n".join([f"{n} wins!" for n in winners]))

🟢 Completing the Square

Solutions in 2 languages
x1, y1 = io.read("*n", "*n")
x2, y2 = io.read("*n", "*n")
x3, y3 = io.read("*n", "*n")

d12 = (x1 - x2) ^ 2 + (y1 - y2) ^ 2
d13 = (x1 - x3) ^ 2 + (y1 - y3) ^ 2
d23 = (x2 - x3) ^ 2 + (y2 - y3) ^ 2

if d12 == d13 then
    x, y = x2 + x3 - x1, y2 + y3 - y1
elseif d12 == d23 then
    x, y = x1 + x3 - x2, y1 + y3 - y2
else
    x, y = x1 + x2 - x3, y1 + y2 - y3
end
print(x, y)
x1, y1 = [int(d) for d in input().split()]
x2, y2 = [int(d) for d in input().split()]
x3, y3 = [int(d) for d in input().split()]

d12 = (x1 - x2) ** 2 + (y1 - y2) ** 2
d13 = (x1 - x3) ** 2 + (y1 - y3) ** 2
d23 = (x2 - x3) ** 2 + (y2 - y3) ** 2

if d12 == d13:
    x, y = x2 + x3 - x1, y2 + y3 - y1
elif d12 == d23:
    x, y = x1 + x3 - x2, y1 + y3 - y2
else:
    x, y = x1 + x2 - x3, y1 + y2 - y3

print(x, y)

🟢 Compound Words

Solution in Python
from itertools import permutations

l = []
while True:
    try:
        l.extend(input().split())
    except:
        break

w = set()
for i, j in permutations(l, 2):
    w.add(f"{i}{j}")


print("\n".join(sorted(w)))

🟢 Conformity

Solution in Python
from collections import Counter

n = int(input())
entries = []
for _ in range(n):
    entries.append(" ".join(sorted(input().split())))

summary = Counter(entries)
popular = max(summary.values())

print(sum([summary[e] for e in summary if summary[e] == popular]))

🟢 Contest Struggles

Solutions in 2 languages
1
2
3
4
5
6
7
n, k, d, s = io.read("*n", "*n", "*n", "*n")
ans = (n * d - k * s) / (n - k)
if ans < 0 or ans > 100 then
    print("impossible")
else
    print(ans)
end
1
2
3
4
5
6
7
n, k = [int(c) for c in input().split()]
d, s = [int(c) for c in input().split()]
ans = (n * d - k * s) / (n - k)
if ans < 0 or ans > 100:
    print("impossible")
else:
    print(f"{ans:.7f}")

🟢 Contingency Planning

Solution in Python
def permutations(n, c):
    value = 1
    for i in range(n - c + 1, n + 1):
        value *= i
    return value


n = int(input())
ans = 0
for i in range(1, n + 1):
    ans += permutations(n, i)
if ans > 1_000_000_000:
    print("JUST RUN!!")
else:
    print(ans)

🟢 Cryptographer's Conundrum

Solution in Python
text = input()
total = 0
for i in range(0, len(text), 3):
    if text[i] != "P":
        total += 1
    if text[i + 1] != "E":
        total += 1
    if text[i + 2] != "R":
        total += 1
print(total)

🟢 Convex Polygon Area

Solution in Python
for _ in range(int(input())):
    values = [int(d) for d in input().split()]
    coords = values[1:]
    n = values[0]

    coords.append(coords[0])
    coords.append(coords[1])

    area = 0
    for i in range(0, 2 * n, 2):
        x1, y1 = coords[i], coords[i + 1]
        x2, y2 = coords[i + 2], coords[i + 3]
        area += x1 * y2 - x2 * y1

    print(0.5 * abs(area))

🟢 Cooking Water

Solutions in 2 languages
n = io.read("*n")
lb, ub = 0, 1000
for _ = 1, n do
    a, b = io.read("*n", "*n")
    lb = math.max(lb, a)
    ub = math.min(ub, b)
end
if lb > ub then
    print("edward is right")
else
    print("gunilla has a point")
end
n = int(input())
lb, ub = 0, 1000
for _ in range(n):
    a, b = [int(d) for d in input().split()]
    lb = max(lb, a)
    ub = min(ub, b)

if lb > ub:
    print("edward is right")
else:
    print("gunilla has a point")

🟢 Cornhusker

Solution in Python
1
2
3
4
5
a = [int(d) for d in input().split()]
n, kwf = [int(d) for d in input().split()]
s = sum([a[i] * a[i + 1] for i in range(0, 10, 2)])

print(int(int(s / 5) * n / kwf))

🟢 Cosmic Path Optimization

Solution in Python
1
2
3
4
5
import math

m = int(input())
t = [int(d) for d in input().split()]
print(f"{math.floor(sum(t)/m)}")

🟢 Costume Contest

Solution in Python
1
2
3
4
5
6
7
from collections import Counter

n = int(input())
c = Counter()
for _ in range(n):
    c[input()] += 1
print("\n".join(sorted([k for k, v in c.items() if v == min(c.values())])))

🟢 Count Doubles

Solution in Python
1
2
3
4
5
6
7
n, m = [int(d) for d in input().split()]
values = [int(d) for d in input().split()]
ans = 0
for i in range(n - m + 1):
    if len([v for v in values[i : i + m] if not v % 2]) >= 2:
        ans += 1
print(ans)

🟢 Counting Clauses

Solutions in 2 languages
1
2
3
4
5
6
7
8
9
m, _ = io.read("*n", "*n")
for _ = 1, m do
    io.read()
end
if m >= 8 then
    print("satisfactory")
else
    print("unsatisfactory")
end
1
2
3
4
5
6
7
m, _ = [int(d) for d in input().split()]
for _ in range(m):
    input()
if m >= 8:
    print("satisfactory")
else:
    print("unsatisfactory")

🟢 Count the Vowels

Solution in Python
print(len([c for c in input().lower() if c in "aeiou"]))

🟢 Course Scheduling

Solution in Python
from collections import Counter

c = Counter()
n = {}

for _ in range(int(input())):
    r = input().split()
    name, course = " ".join(r[:2]), r[-1]
    if course not in n:
        n[course] = set()

    if name not in n[course]:
        c[course] += 1
        n[course].add(name)

for k in sorted(c.keys()):
    print(f"{k} {c[k]}")

🟢 CPR Number

Solution in Python
1
2
3
4
5
6
7
8
9
cpr = input().replace("-", "")
values = [4, 3, 2, 7, 6, 5, 4, 3, 2, 1]
total = 0
for d, v in zip(cpr, values):
    total += int(d) * v
if not total % 11:
    print(1)
else:
    print(0)

🟢 Crne

Solutions in 3 languages
package main

import (
    "fmt"
)

func main() {
    var n int
    fmt.Scan(&n)
    a := n / 2
    b := n - a
    fmt.Println((a + 1) * (b + 1))
}
1
2
3
4
n = io.read("*n")
a = n // 2
b = n - a
print((a + 1) * (b + 1))
1
2
3
4
n = int(input())
a = n // 2
b = n - a
print((a + 1) * (b + 1))

🟢 Cudoviste

Solution in Python
r, c = [int(d) for d in input().split()]
parking = []
for _ in range(r):
    parking.append(input())


def count_spaces(parking, squash):
    total = 0
    for i in range(r - 1):
        for j in range(c - 1):
            spaces = [
                parking[i][j],
                parking[i + 1][j],
                parking[i][j + 1],
                parking[i + 1][j + 1],
            ]
            if (
                all(s in ".X" for s in spaces)
                and sum([s == "X" for s in spaces]) == squash
            ):
                total += 1
    return total


for num in range(0, 5):
    print(count_spaces(parking, num))

🟢 Stacking Cups

Solution in Python
1
2
3
4
5
6
7
8
9
size = {}
for _ in range(int(input())):
    parts = input().split()
    if parts[0].isdigit():
        size[parts[1]] = int(parts[0]) / 2
    else:
        size[parts[0]] = int(parts[1])
for color in sorted(size, key=lambda x: size[x]):
    print(color)

🟢 Cut in Line

Solution in Python
n = int(input())
queue = []
for _ in range(n):
    queue.append(input())

c = int(input())
for _ in range(c):
    event = input().split()
    if event[0] == "leave":
        queue.remove(event[1])
    elif event[0] == "cut":
        queue.insert(queue.index(event[2]), event[1])

for name in queue:
    print(name)

🟢 Cut the Negativity

Solution in Python
n = int(input())

positives = []
for i in range(n):
    numbers = [int(d) for d in input().split()]
    for j in range(n):
        if numbers[j] > 0:
            positives.append((str(i + 1), str(j + 1), str(numbers[j])))

print(len(positives))
for p in positives:
    print(" ".join(p))

🟢 Cyanide Rivers

Solution in Python
1
2
3
4
5
import math

s = input()
t = s.split("1")
print(max([math.ceil(len(z) / 2) for z in t]))

🟢 Cypher Decypher

Solution in Python
from string import ascii_uppercase


def f(n, m):
    return ascii_uppercase[(n * m) % 26]


m = input()
for _ in range(int(input())):
    s = input()
    print("".join([f(ascii_uppercase.index(c), int(d)) for c, d in zip(s, m)]))

🟢 Damaged Equation

Solution in Python
from itertools import product

a, b, c, d = [int(d) for d in input().split()]
ops = ["*", "+", "-", "//"]
valid = False
for op1, op2 in product(ops, ops):
    e = f"{a} {op1} {b} == {c} {op2} {d}"
    try:
        if eval(e):
            print(e.replace("==", "=").replace("//", "/"))
            valid = True
    except:
        pass
if not valid:
    print("problems ahead")

🟢 Darts

Solutions in 2 languages
t = io.read("*n")
for _ = 1, t do
    n = io.read("*n")
    score = 0
    for _ = 1, n do
        x, y = io.read("*n", "*n")
        dist = (x ^ 2 + y ^ 2) ^ 0.5
        if dist > 200 then
            p = 0
        elseif dist % 20 == 0 then
            p = math.min(11 - dist // 20, 10)
        else
            p = 10 - dist // 20
        end
        score = score + math.floor(p)
    end
    print(score)
end
t = int(input())
for _ in range(t):
    n = int(input())
    score = 0
    for _ in range(n):
        x, y = [int(d) for d in input().split()]
        dist = (x**2 + y**2) ** 0.5
        if dist > 200:
            p = 0
        elif dist % 20 == 0:
            p = min(11 - dist // 20, 10)
        else:
            p = 10 - dist // 20
        score += int(p)
    print(score)

🟢 Das Blinkenlights

Solution in Python
1
2
3
4
import math

p, q, s = [int(d) for d in input().split()]
print("yes" if p * q / math.gcd(p, q) <= s else "no")

🟢 Datum

Solution in Python
1
2
3
4
from datetime import datetime

d, m = [int(d) for d in input().split()]
print(datetime(year=2009, month=m, day=d).strftime("%A"))

🟢 Death Knight Hero

Solution in Python
1
2
3
4
5
total = 0
for _ in range(int(input())):
    if "CD" not in input():
        total += 1
print(total)

🟢 Deathstar

Solution in Python
1
2
3
4
5
6
7
n = int(input())
a = [0] * n
for i in range(n):
    m = [int(d) for d in input().split()]
    for v in m:
        a[i] |= v
print(" ".join([str(d) for d in a]))

🟢 Delimiter Soup

Solution in Python
n = int(input())
s = input()

stack = []

valid = True

for i in range(n):
    c = s[i]
    if c in ["(", "[", "{"]:
        stack.append(c)
    if c in [")", "]", "}"]:
        if len(stack) == 0:
            valid = False
            break

        v = stack.pop()
        if c == ")" and v != "(":
            valid = False
            break
        elif c == "]" and v != "[":
            valid = False
            break
        elif c == "}" and v != "{":
            valid = False
            break

if valid:
    print("ok so far")
else:
    print(c, i)

🟢 Detailed Differences

Solution in Python
1
2
3
4
5
6
for _ in range(int(input())):
    s1, s2 = input(), input()
    result = ["." if c1 == c2 else "*" for c1, c2 in zip(s1, s2)]
    print(s1)
    print(s2)
    print("".join(result))

🟢 D Fyrir Dreki

Solutions in 2 languages
1
2
3
4
5
6
7
8
9
a, b, c = io.read("*n", "*n", "*n")
t = b * b - 4 * a * c
if t < 0 then
    print(0)
elseif t == 0 then
    print(1)
else
    print(2)
end
1
2
3
4
5
6
7
8
a, b, c = int(input()), int(input()), int(input())
t = b * b - 4 * a * c
if t < 0:
    print(0)
elif t == 0:
    print(1)
else:
    print(2)

🟢 Dice Cup

Solution in Python
d1, d2 = [int(d) for d in input().split()]

sums = []
for i in range(1, d1 + 1):
    for j in range(1, d2 + 1):
        sums.append(i + j)

from collections import Counter

c = Counter(sums)
most_likely = max(c.values())
for key in sorted(c.keys()):
    if c[key] == most_likely:
        print(key)

🟢 Dice Game

Solution in Python
g = [int(d) for d in input().split()]
e = [int(d) for d in input().split()]


def ev(d):
    total, count = 0, 0
    for i in range(d[0], d[1] + 1):
        for j in range(d[2], d[3] + 1):
            total += i + j
            count += 1
    return total / count


ratio = ev(g) / ev(e)
if ratio > 1:
    print("Gunnar")
elif ratio < 1:
    print("Emma")
else:
    print("Tie")

🟡 A Different Problem

Solution in Python
1
2
3
4
5
6
7
while True:
    try:
        line = input()
    except:
        break
    a, b = [int(d) for d in line.split()]
    print(abs(a - b))

🟢 Different Distances

Solution in Python
1
2
3
4
5
6
while True:
    line = input()
    if line == "0":
        break
    x1, y1, x2, y2, p = [float(d) for d in line.split()]
    print((abs(x1 - x2) ** p + abs(y1 - y2) ** p) ** (1 / p))

🟢 Digit Swap

Solutions in 4 languages
package main

import (
    "fmt"
)

func reverse(str string) (ans string) {
    for _, v := range str {
        ans = string(v) + ans
    }
    return
}
func main() {
    var str string
    fmt.Scan(&str)
    fmt.Println(reverse(str))
}
import java.util.*;

class DigitSwap {
    public static void main(String[] argv){
        Scanner s = new Scanner(System.in);
        StringBuilder ans = new StringBuilder();
        ans.append(s.nextLine());
        ans.reverse();
        System.out.println(ans);
    }
}
1
2
3
fun main() {
    println(StringBuilder(readLine()).reverse())
}
print(input()[::-1])

🟢 Disc District

Solutions in 2 languages
print(1, io.read())
print(1, input())

🟢 Distributing Poffins

Solutions in 3 languages
#include <iostream>

using namespace std;

int main()
{
    long long n, m;
    cin >> n >> m;

    if (m % n == 0)
    {
        cout << 0;
    }
    else
    {
        cout << 1;
    }

    return 0;
}
1
2
3
4
5
6
n, m = io.read("*n", "*n")
if m % n == 0 then
    print(0)
else
    print(1)
end
n, m = [int(d) for d in input().split()]
print(1 if m % n else 0)

🟢 Divvying Up

Solutions in 2 languages
n = io.read("*n")
total = 0
for i = 1, n do
    total = total + io.read("*n")
end
if total % 3 > 0 then
    print("no")
else
    print("yes")
end
1
2
3
4
5
6
_ = input()
p = [int(d) for d in input().split()]
if sum(p) % 3:
    print("no")
else:
    print("yes")

🟢 Don't Fall Down Stairs

Solution in Python
1
2
3
n = int(input())
a = [int(d) for d in input().split()] + [0]
print(sum(max(a[i] - a[i + 1] - 1, 0) for i in range(n)))

🟢 Double Password

Solutions in 2 languages
import java.util.Scanner;

class DoublePassword {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String a = s.nextLine();
        String b = s.nextLine();
        int number = 1;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == b.charAt(i)) {
                number *= 1;
            } else {
                number *= 2;
            }
        }
        System.out.println(number);

    }
}
1
2
3
4
5
6
7
8
a, b = input(), input()
number = 1
for c1, c2 in zip(a, b):
    if c1 == c2:
        number *= 1
    else:
        number *= 2
print(number)

🟢 Draga Frá

Solutions in 2 languages
n, m = io.read("*n", "*n")
print(n - m)
n, m = int(input()), int(input())
print(n - m)

🟢 Drinking Song

Solution in Python
n = int(input())
w = input()

for i in range(n):
    a = f"{n-i} bottle{'s' if n-i >1 else ''}"
    b = f"{'no more' if n-i-1==0 else n-i-1 } bottle{'' if n-i-1==1 else 's'}"
    c = f"{'one' if n-i>1 else 'it' }"
    d = f"{' on the wall' if n-i-1 else ''}"
    print(f"{a} of {w} on the wall, {a} of {w}.")
    print(f"Take {c} down, pass it around, {b} of {w}{d}.")
    if n - i - 1:
        print()

🟢 Driver's Dilemma

Solution in Python
c, x, m = [float(d) for d in input().split()]
top = 0
for _ in range(6):
    mph, mpg = [float(d) for d in input().split()]

    if m / mph * x + m / mpg <= c / 2:
        top = mph
if top:
    print(f"YES {top:.0f}")
else:
    print("NO")

🟢 DRM Messages

Solution in Python
l = ord("A")
r = ord("Z")


def divide(message):
    half = len(message) // 2
    return message[:half], message[half:]


def to_ord(c, rotation):
    new_chr = ord(c) + rotation
    return new_chr if new_chr <= r else l + (new_chr - r - 1)


def rotate(half):
    rotation = sum([ord(c) - l for c in half])
    rotation %= 26
    result = [to_ord(c, rotation) for c in half]
    return "".join([chr(c) for c in result])


def merge(first, second):
    rotations = [ord(c) - l for c in second]
    result = [to_ord(c, rotation) for c, rotation in zip(first, rotations)]
    return "".join([chr(c) for c in result])


message = input()
first, second = divide(message)
print(merge(rotate(first), rotate(second)))

🟢 Drunk Vigenère

Solution in Python
import string

uppers = string.ascii_uppercase


def unshift(c, k, f):
    index = uppers.index(k)
    if f:
        new_index = uppers.index(c) + index
    else:
        new_index = uppers.index(c) - index
    return uppers[new_index % 26]


message, key = input(), input()
print("".join([unshift(c, k, i % 2) for i, (c, k) in enumerate(zip(message, key))]))

🟢 Early Winter

Solution in Python
n, m = [int(_) for _ in input().split()]
d = [int(_) for _ in input().split()]
d = [v > m for v in d]


for k in range(n):
    if not d[k]:
        break

if all(d):
    print("It had never snowed this early!")
else:
    print(f"It hadn't snowed this early in {k} years!")

🟢 The Easiest Problem Is This One

Solution in Python
while True:
    n = input()
    if n == "0":
        break
    s1 = sum([int(d) for d in n])

    n = int(n)
    p = 11
    while True:
        s2 = sum([int(d) for d in str(n * p)])
        if s2 == s1:
            break
        p += 1

    print(p)

🟢 Echo Echo Echo

Solution in Python
word = input().strip()
print(" ".join([word] * 3))

🟢 Egypt

Solution in Python
1
2
3
4
5
6
7
8
while True:
    sides = sorted([int(d) for d in input().split()])
    if not all(sides):
        break
    if sides[0] ** 2 + sides[1] ** 2 == sides[2] ** 2:
        print("right")
    else:
        print("wrong")

🟢 Eiginnöfn

Solution in Python
n = int(input())
mapping = {}
for _ in range(n):
    names = input().split()
    mapping[names[0]] = names
m = int(input())
for _ in range(m):
    name = input()
    if name not in mapping:
        print("Neibb")
    elif name in mapping and len(mapping[name]) == 1:
        print("Jebb")
    else:
        print(f'Neibb en {" ".join(mapping[name])} er heima')

🟢 Ekki dauði opna inni

Solution in Python
1
2
3
4
5
6
7
8
9
l = []
while True:
    try:
        l.append(input().split("|"))
    except:
        break

l = [l[i][0] for i in range(len(l))] + [" "] + [l[i][1] for i in range(len(l))]
print("".join(l))

🟢 Election Paradox

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
p = [int(d) for d in input().split()]
p = sorted(p)
t = 0
for i in range(0, n // 2 + 1):
    t += p[i] // 2
for i in range(n // 2 + 1, n):
    t += p[i]
print(t)

🟢 Electrical Outlets

Solution in Python
for _ in range(int(input())):
    print(sum([int(d) - 1 for d in input().split()[1:]]) + 1)

🟢 Eligibility

Solution in Python
for _ in range(int(input())):
    name, pss, dob, courses = input().split()
    courses = int(courses)
    pss = [int(d) for d in pss.split("/")]
    dob = [int(d) for d in dob.split("/")]
    if pss[0] >= 2010 or dob[0] >= 1991:
        print(name, "eligible")
    elif courses > 40:
        print(name, "ineligible")
    else:
        print(name, "coach petitions")

🟢 Encoded Message

Solution in Python
import math

for _ in range(int(input())):
    message = input()
    size = int(math.sqrt(len(message)))
    m = []
    for i in range(size):
        m.append(message[i * size : (i + 1) * size])

    ans = []
    for i in range(size - 1, -1, -1):
        for j in range(size):
            ans.append(m[j][i])
    print("".join(ans))

🟢 Endurvinnsla

Solutions in 2 languages
_ = io.read()
p, n = io.read("*n", "*n")
total = 0
for _ = 1, n do
    if io.read() == "ekki plast" then
        total = total + 1
    end
end
if total <= p * n then
    print("Jebb")
else
    print("Neibb")
end
1
2
3
4
5
_ = input()
p = float(input())
n = int(input())
items = [input() == "ekki plast" for _ in range(n)]
print("Jebb" if sum(items) <= p * n else "Neibb")

🟢 Engineering English

Solution in Python
seen = set()

while True:
    try:
        s = input().split()
    except:
        break
    d = []
    for t in s:
        if t.lower() not in seen:
            seen.add(t.lower())
        else:
            t = "."
        d.append(t)
    print(" ".join(d))

🟢 Erase Securely

Solution in Python
n = int(input())
a, b = input(), input()
if n % 2:
    print(
        "Deletion", "failed" if not all([i != j for i, j in zip(a, b)]) else "succeeded"
    )
else:
    print(
        "Deletion", "failed" if not all([i == j for i, j in zip(a, b)]) else "succeeded"
    )

🟢 Espresso!

Solution in Python
n, s = [int(d) for d in input().split()]
refill = 0
tank = s
for _ in range(n):
    o = input()
    if "L" in o:
        w = int(o[:-1]) + 1
    else:
        w = int(o)
    if tank - w < 0:
        refill += 1
        tank = s

    tank -= w
print(refill)

🟢 Estimating the Area of a Circle

Solutions in 2 languages
1
2
3
4
5
6
7
while true do
    r, m, c = io.read("*n", "*n", "*n")
    if r == 0 and m == 0 and c == 0 then
        break
    end
    print(math.pi * r * r, 4 * r * r * c / m)
end
1
2
3
4
5
6
7
8
9
import math

while True:
    r, m, c = input().split()
    if r == "0" and m == "0" and c == "0":
        break
    r = float(r)
    m, c = int(m), int(c)
    print(math.pi * r * r, 4 * r * r * c / m)

🟢 Euler's Number

Solutions in 3 languages
#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
    int n;
    long double e, m;
    cin >> n;
    e = 1;
    m = 1;
    for (int i = 1; i <= n; i++)
    {
        m *= i;
        e += 1 / m;
    }
    cout << std::setprecision(13) << e << endl;
    return 0;
}
1
2
3
4
5
6
7
8
n = io.read("*n")
e = 1
m = 1.0
for i = 1, n do
    m = m * i
    e = e + 1 / m
end
print(string.format("%.12f", e))
1
2
3
4
5
6
7
n = int(input())
e = 1
m = 1
for i in range(1, n + 1):
    m *= i
    e += 1 / m
print(e)

🟢 Evening Out 1

Solutions in 3 languages
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    long int a, b;
    cin >> a >> b;
    long int c = a % b;
    cout << std::min(c, b - c);
    return 0;
}
1
2
3
a, b = io.read("*n", "*n")
c = a % b
print(math.min(c, b - c))
1
2
3
a, b = [int(d) for d in input().split()]
c = a % b
print(min(c, b - c))

🟢 Event Planning

Solution in Python
n, b, h, w = [int(d) for d in input().split()]

costs = []
for _ in range(h):
    p = int(input())
    a = [int(d) for d in input().split()]
    if not any([_a >= n for _a in a]):
        costs.append(None)
        continue
    c = p * n
    if c > b:
        c = None
    costs.append(c)

costs = [c for c in costs if c]
if not costs:
    print("stay home")
else:
    print(min(costs))

🟢 I've Been Everywhere, Man

Solution in Python
1
2
3
4
5
6
7
cities = {}
for i in range(int(input())):
    cities[i] = set()
    for _ in range(int(input())):
        cities[i].add(input())

print("\n".join([str(len(s)) for s in cities.values()]))

🟢 Exactly Electrical

Solutions in 2 languages
1
2
3
4
5
6
7
a, b, c, d, t = io.read("*n", "*n", "*n", "*n", "*n")
m = math.abs(a - c) + math.abs(b - d)
if m <= t and (m - t) % 2 == 0 then
    print("Y")
else
    print("N")
end
1
2
3
4
5
a, b = [int(d) for d in input().split()]
c, d = [int(d) for d in input().split()]
t = int(input())
m = abs(a - c) + abs(b - d)
print("Y" if m <= t and (m - t) % 2 == 0 else "N")

🟢 Exam

Solution in Python
k = int(input())
y = input()
f = input()
same, different = 0, 0
for a, b in zip(y, f):
    if a == b:
        same += 1
    else:
        different += 1
print(min(same, k) + min(different, (len(y) - k)))

🟢 Expected Earnings

Solutions in 2 languages
1
2
3
4
5
6
7
n, k, p = io.read("*n", "*n", "*n")
ev = n * p - k
if ev < 0 then
    print("spela")
else
    print("spela inte!")
end
1
2
3
4
5
6
7
8
9
n, k, p = input().split()
n = int(n)
k = int(k)
p = float(p)
ev = n * p - k
if ev < 0:
    print("spela")
else:
    print("spela inte!")

🟢 Eye of Sauron

Solutions in 2 languages
package main

import (
    "fmt"
    "strings"
)

func main() {
    var drawing string
    fmt.Scan(&drawing)
    parts := strings.Split(drawing, "()")
    left, right := parts[0], parts[1]
    if left == right {
        fmt.Println("correct")
    } else {
        fmt.Println("fix")
    }
}
1
2
3
4
5
6
drawing = input()
left, right = drawing.split("()")
if left == right:
    print("correct")
else:
    print("fix")

🟢 Fading Wind

Solution in Python
h, k, v, s = [int(d) for d in input().split()]
t = 0
while h > 0:
    v += s
    v -= max(1, v // 10)
    if v >= k:
        h += 1
    elif v > 0:
        h -= 1
        if not h:
            v = 0
    else:
        h = 0
        v = 0
    t += v
    if s > 0:
        s -= 1
print(t)

🟢 Faktor

Solutions in 2 languages
a, i = io.read("*n", "*n")
print(a * (i - 1) + 1)
a, i = [int(d) for d in input().split()]
print(a * (i - 1) + 1)

🟢 Falling Apart

Solution in Python
1
2
3
4
5
6
n = int(input())
a = sorted([int(d) for d in input().split()], reverse=True)
print(
    sum([a[i] for i in range(0, n, 2)]),
    sum([a[i] for i in range(1, n, 2)]),
)

🟢 False Sense of Security

Solution in Python
encoding = {
    "A": ".-",
    "B": "-...",
    "C": "-.-.",
    "D": "-..",
    "E": ".",
    "F": "..-.",
    "G": "--.",
    "H": "....",
    "I": "..",
    "J": ".---",
    "K": "-.-",
    "L": ".-..",
    "M": "--",
    "N": "-.",
    "O": "---",
    "P": ".--.",
    "Q": "--.-",
    "R": ".-.",
    "S": "...",
    "T": "-",
    "U": "..-",
    "V": "...-",
    "W": ".--",
    "X": "-..-",
    "Y": "-.--",
    "Z": "--..",
    "_": "..--",
    ",": ".-.-",
    ".": "---.",
    "?": "----",
}

decoding = dict([(v, k) for k, v in encoding.items()])

while True:
    try:
        encoded = input()
    except:
        break
    length = [len(encoding[c]) for c in encoded]
    morse = "".join([encoding[c] for c in encoded])

    ans, s = "", 0
    for i in reversed(length):
        ans += decoding[morse[s : s + i]]
        s += i
    print(ans)

🟢 Fast Food Prizes

Solution in Python
for _ in range(int(input())):
    n, m = [int(d) for d in input().split()]
    r = []
    for _ in range(n):
        s = input().split()
        p = int(s[-1])
        k = [int(d) for d in s[1:-1]]
        r.append((k, p))
    s = [int(d) for d in input().split()]

    ans = 0
    for t, p in r:
        c = min([s[d - 1] for d in t])
        ans += p * c

    print(ans)

🟢 FBI Universal Control Numbers

Solution in Python
m = {
    "0": 0,
    "1": 1,
    "2": 2,
    "3": 3,
    "4": 4,
    "5": 5,
    "6": 6,
    "7": 7,
    "8": 8,
    "9": 9,
    "A": 10,
    "B": 8,
    "C": 11,
    "D": 12,
    "E": 13,
    "F": 14,
    "G": 11,
    "H": 15,
    "I": 1,
    "J": 16,
    "K": 17,
    "L": 18,
    "M": 19,
    "N": 20,
    "O": 0,
    "P": 21,
    "Q": 0,
    "R": 22,
    "S": 5,
    "T": 23,
    "U": 24,
    "V": 24,
    "W": 25,
    "X": 26,
    "Y": 24,
    "Z": 2,
}
w = [2, 4, 5, 7, 8, 10, 11, 13]

for _ in range(int(input())):
    i, d = input().split()
    t = sum([m[b] * a for a, b in zip(w, d)])
    if t % 27 == m[d[-1]]:
        s = sum([m[b] * 27**a for a, b in zip(range(8), d[:8][::-1])])
        print(f"{i} {s}")
    else:
        print(f"{i} Invalid")

🟢 Ferskasta Jarmið

Solution in Python
1
2
3
4
5
6
7
n = int(input())
memes = {}
for _ in range(n):
    item = input().split()
    meme, score = item[0], int(item[1]) * int(item[2])
    memes[meme] = score
print(max(memes, key=lambda v: (memes[v], -sorted(memes).index(v))))

🟢 Framtíðar FIFA

Solutions in 2 languages
n, m = io.read("*n", "*n")
print(2022 + n // m)
1
2
3
n = int(input())
m = int(input())
print(2022 + n // m)

🟢 Fifty Shades of Pink

Solution in Python
1
2
3
4
5
6
7
8
9
total = 0
for _ in range(int(input())):
    button = input().lower()
    if "pink" in button or "rose" in button:
        total += 1
if not total:
    print("I must watch Star Wars with my daughter")
else:
    print(total)

🟢 Filip

Solution in Python
1
2
3
4
5
6
a, b = input().split()
a, b = a[::-1], b[::-1]
if a > b:
    print(a)
else:
    print(b)

🟢 Fimmtudagstilboð

Solution in Python
y = int(input())
print(1000 + 100 * (y - 2020) if y > 2020 else 1000)

🟢 Final Exam

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
ans, score = [], 0
for i in range(n):
    ans.append(input())
    if i == 0:
        continue
    if ans[i] == ans[i - 1]:
        score += 1
print(score)

🟢 Finding An A

Solutions in 3 languages
#include <iostream>

using namespace std;

int main()
{
    string a;
    cin >> a;

    int found = a.find_first_of("a");

    cout << a.substr(found);

    return 0;
}
package main

import (
    "fmt"
    "strings"
)

func main() {
    var s string
    fmt.Scan(&s)
    index := strings.Index(s, "a")
    fmt.Println(s[index:])
}
word = input()
print(word[word.find("a") :])

🟢 FizzBuzz

Solution in Python
x, y, n = [int(d) for d in input().split()]
for i in range(1, n + 1):
    ans = ""
    if not i % x:
        ans += "Fizz"
    if not i % y:
        ans += "Buzz"
    if not ans:
        ans = i
    print(ans)

🟢 Fjöldi Bókstafa

Solution in Python
print(sum(s.isalpha() for s in input()))

🟢 Flatbökuveisla

Solutions in 2 languages
1
2
3
m = io.read("*n")
n = io.read("*n")
print(m % n)
1
2
3
n = int(input())
m = int(input())
print(n - n // m * m)

🟢 Flexible Spaces

Solution in Python
1
2
3
4
5
6
7
8
w, p = [int(d) for d in input().split()]
l = [int(d) for d in input().split()]
l = [0] + l + [w]
c = set()
for i in range(p + 1):
    for j in range(i + 1, p + 2):
        c.add(l[j] - l[i])
print(" ".join([str(d) for d in sorted(c)]))

🟢 Flýtibaka

Solutions in 11 languages
1
2
3
4
5
6
7
8
9
#include <iostream>

using namespace std;

int main()
{
    cout << "";
    return 0;
}
1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("")
}
main = do
    putStrLn ""
1
2
3
4
5
class Flytibaka {
    public static void main(String[] args) {
        System.out.println("");
    }
}
print()
console.log("");
1
2
3
fun main() {
    println("")
}
print()
print()
puts ""
1
2
3
fn main() {
    println!("");
}

🟢 Birthday Memorization

Solution in Python
n = int(input())
records = {}
for _ in range(n):
    s, c, date = input().split()
    c = int(c)
    date = "".join(date.split("/")[::-1])
    if date not in records:
        records[date] = (s, c)
    else:
        _, _c = records[date]
        if c > _c:
            records[date] = (s, c)
print(len(records.keys()))
ordered_keys = sorted(records, key=lambda k: records[k][0])
for key in ordered_keys:
    print(records[key][0])

🟢 Forced Choice

Solution in Python
1
2
3
4
5
6
_, p, s = input().split()
for _ in range(int(s)):
    if p in input().split()[1:]:
        print("KEEP")
    else:
        print("REMOVE")

🟢 Four Die Rolls

Solution in Python
n = int(input())
d = [int(d) for d in input().split()]
t = 6 ** (4 - n)
if len(set(d)) < len(d):
    m = 0
else:
    m = 1
    for _ in range(n, 4):
        m *= 6 - n
        n += 1
print(m, t - m)

🟢 Free Food

Solution in Python
1
2
3
4
5
6
n = int(input())
days = set()
for _ in range(n):
    start, end = [int(d) for d in input().split()]
    days.update(range(start, end + 1))
print(len(days))

🟢 From A to B

Solution in Python
a, b = [int(d) for d in input().split()]

if a <= b:
    print(b - a)
else:
    total = 0
    while a > b:
        if a % 2:
            a += 1
            total += 1
        a /= 2
        total += 1
    total += b - a
    print(int(total))

🟢 Frosh Week

Solution in Python
1
2
3
4
5
6
7
8
_ = input()
t = sorted([int(d) for d in input().split()])
l = sorted([int(d) for d in input().split()])
i = 0
for d in l:
    if t[i] <= d:
        i += 1
print(i)

🟢 FYI

Solutions in 4 languages
package main

import (
    "fmt"
    "strings"
)

func main() {
    var s string
    fmt.Scan(&s)
    if strings.HasPrefix(s, "555") {
        fmt.Println(1)
    } else {
        fmt.Println(0)
    }
}
1
2
3
4
5
if io.read():find("^555") ~= nil then
    print(1)
else
    print(0)
end
1
2
3
4
if input().startswith("555"):
    print(1)
else:
    print(0)
1
2
3
4
5
6
s = gets
if s.start_with?("555")
    puts 1
else
    puts 0
end

🟢 Fyrirtækjanafn

Solution in Python
s = input()
print("".join(c for c in s if c.lower() in "aeiouy"))

🟢 Gandalf's Spell

Solution in Python
c = list(input())
s = input().split()
if len(c) != len(s):
    print("False")
else:
    d, valid = {}, True
    for a, b in zip(c, s):
        if a not in d:
            d[a] = b
        else:
            if d[a] != b:
                print("False")
                valid = False
                break
    if valid:
        if len(set(d.keys())) == len(set(d.values())):
            print("True")
        else:
            print("False")

🟢 GCD

Solutions in 2 languages
1
2
3
4
5
6
a, b = io.read("*n", "*n")
function gcd(a, b)
    return b == 0 and a or gcd(b, a % b)
end

print(gcd(a, b))
1
2
3
4
5
import math

a, b = [int(d) for d in input().split()]

print(math.gcd(a, b))

🟢 GCVWR

Solution in Python
1
2
3
4
g, t, n = [int(d) for d in input().split()]
capacity = (g - t) * 0.9
items = sum([int(d) for d in input().split()])
print(int(capacity - items))

🟢 Gene Block

Solution in Python
mapping = {
    1: 3,
    2: 6,
    3: 9,
    4: 2,
    5: 5,
    6: 8,
    7: 1,
    8: 4,
    9: 7,
    0: 10,
}

for _ in range(int(input())):
    n = int(input())
    d = n % 10

    if n >= 7 * mapping[d]:
        print(mapping[d])
    else:
        print(-1)

🟢 Gerrymandering

Solution in Python
p, _ = [int(d) for d in input().split()]
votes = {}
for _ in range(p):
    d, a, b = [int(d) for d in input().split()]
    if d not in votes:
        votes[d] = {"A": a, "B": b}
    else:
        votes[d]["A"] += a
        votes[d]["B"] += b

total_wa, total_wb = 0, 0
for d in sorted(votes):
    total = votes[d]["A"] + votes[d]["B"]
    t = total // 2 + 1
    winner = "A" if votes[d]["A"] > votes[d]["B"] else "B"
    wa = votes[d]["A"] - t if votes[d]["A"] > votes[d]["B"] else votes[d]["A"]
    wb = votes[d]["B"] - t if votes[d]["B"] > votes[d]["A"] else votes[d]["B"]
    print(winner, wa, wb)
    total_wa += wa
    total_wb += wb
v = sum([sum(ab.values()) for ab in votes.values()])
print(abs(total_wa - total_wb) / v)

🟢 Ghost Leg

Solution in Python
1
2
3
4
5
6
n, m = [int(d) for d in input().split()]
v = [str(d) for d in list(range(1, n + 1))]
for _ in range(m):
    a = int(input())
    v[a - 1], v[a] = v[a], v[a - 1]
print("\n".join(v))

🟢 Glasses Foggy, Mom's Spaghetti

Solution in Python
import math

d, x, y, h = input().split()
d = int(d)
x = int(x)
y = int(y)
h = int(h)

angle1 = (math.atan(y / x)) - (math.atan((y - h / 2) / x))
angle2 = (math.atan((y + h / 2) / x)) - (math.atan(y / x))

d1 = math.tan(angle1) * d
d2 = math.tan(angle2) * d

print(d1 + d2)

🟢 Goat Rope

Solution in Python
x, y, x1, y1, x2, y2 = [int(d) for d in input().split()]

if x >= x1 and x <= x2:
    print(min(abs(y - y1), abs(y - y2)))
elif y >= y1 and y <= y2:
    print(min(abs(x - x1), abs(x - x2)))
else:
    x3, y3 = x1, y2
    x4, y4 = x2, y1
    l = [
        ((x - a) ** 2 + (y - b) ** 2) ** 0.5
        for a, b in [(x1, y1), (x2, y2), (x1, y2), (x2, y1)]
    ]
    print(min(l))

🟢 Goomba Stacks

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
total = 0
result = True
for _ in range(n):
    g, b = [int(d) for d in input().split()]
    total += g
    if total < b:
        result = False
print("possible" if result else "impossible")

🟢 Grading

Solution in Python
line = input()
score = int(input())
a, b, c, d, e = [int(d) for d in line.split()]
if score >= a:
    print("A")
elif score >= b:
    print("B")
elif score >= c:
    print("C")
elif score >= d:
    print("D")
elif score >= e:
    print("E")
else:
    print("F")

🟢 Grass Seed Inc.

Solution in Python
1
2
3
4
5
6
c = float(input())
total = 0
for _ in range(int(input())):
    w, l = [float(d) for d in input().split()]
    total += c * w * l
print(f"{total:.7f}")

🟢 Greedily Increasing Subsequence

Solution in Python
n = int(input())
a = [int(d) for d in input().split()]

g = [a[0]]
for i in range(1, n):
    v = a[i]
    if v > g[-1]:
        g.append(v)
print(len(g))
print(" ".join([str(d) for d in g]))

🟢 Greedy Polygons

Solution in Python
1
2
3
4
5
6
7
8
import math

for _ in range(int(input())):
    n, l, d, g = [int(d) for d in input().split()]
    a = n * l * l / (4 * math.tan(math.pi / n))
    a += n * l * d * g
    a += math.pi * ((d * g) ** 2)
    print(a)

🟢 Greetings!

Solution in Python
print(input().replace("e", "ee"))

🟡 Guess the Number

Solutions in 2 languages
s, e = 1, 1000
while true do
    guess = (s + e) // 2
    print(guess)
    resp = io.read()
    if resp == "correct" then
        break
    elseif resp == "higher" then
        s = guess + 1
    else
        e = guess
    end
end
start, end = 1, 1000
while True:
    guess = (start + end) // 2
    print(guess)
    resp = input()
    if resp == "correct":
        break
    elif resp == "higher":
        start = guess + 1
    else:
        end = guess

🟢 Guess Who

Solution in Python
n, m, q = [int(d) for d in input().split()]
M = []
for _ in range(n):
    M.append(input())
Q = []
for _ in range(q):
    Q.append(input().split())
ans = [all([c[int(i) - 1] == v for i, v in Q]) for c in M]
if sum(ans) > 1:
    print("ambiguous")
    print(sum(ans))
else:
    print("unique")
    print(ans.index(True) + 1)

🟢 Watch Out For Those Hailstones!

Solutions in 2 languages
package main

import (
    "fmt"
)

func h(n int) int {
    if n == 1 {
        return 1
    } else if n%2 == 0 {
        return n + h(n/2)
    } else {
        return n + h(3*n+1)
    }
}

func main() {
    var n int
    fmt.Scan(&n)
    fmt.Println(h(n))
}
1
2
3
4
5
6
7
8
9
def h(n):
    if n == 1:
        return 1
    else:
        return n + (h(n // 2) if n % 2 == 0 else h(3 * n + 1))


n = int(input())
print(h(n))

🟢 Hailstone Sequences

Solution in Python
n = int(input())
s = [n]
while True:
    v = s[-1]
    if v == 1:
        break
    elif v % 2 == 0:
        s.append(v // 2)
    else:
        s.append(3 * v + 1)
print(len(s))
Solution in Python
import math

while True:
    try:
        r, x, y = [float(d) for d in input().split()]
    except:
        break
    if x**2 + y**2 >= r**2:
        print("miss")
    else:
        # https://mathworld.wolfram.com/CircularSegment.html
        d = math.sqrt(x**2 + y**2)
        h = r - d
        a = math.acos((r - h) / r)
        t = (r - h) * math.sqrt(2 * r * h - h * h)
        p = (r**2) * a
        s = p - t
        print(math.pi * (r**2) - s, s)

🟢 Hanging Out on the Terrace

Solution in Python
l, x = [int(d) for d in input().split()]
o, r = 0, 0
for _ in range(x):
    action, n = input().split()
    n = int(n)
    if action == "leave":
        o -= n
    elif action == "enter":
        if o + n > l:
            r += 1
        else:
            o += n
print(r)

🟢 Hangman

Solution in Python
word = set(list(input()))
guess = input()
tries = 0
correct = 0
for c in guess:
    if c in word:
        correct += 1
    else:
        tries += 1

    if correct == len(word):
        break

if tries >= 10:
    print("LOSE")
else:
    print("WIN")

🟢 Hardwood Species

Solution in Python
from collections import Counter

names = []
while True:
    try:
        names.append(input())
    except:
        break
total = len(names)
names = Counter(names)
for n in sorted(names):
    print(n, f"{names[n]/total*100:.6f}")

🟢 Harshad Numbers

Solution in Python
1
2
3
4
5
6
7
n = int(input())
while True:
    sd = sum([int(d) for d in str(n)])
    if not n % sd:
        break
    n += 1
print(n)

🟢 Haughty Cuisine

Solution in Python
1
2
3
4
5
6
7
8
from random import randint

n = int(input())
menu = []
for _ in range(n):
    menu.append(input().split())

print("\n".join(menu[randint(0, n - 1)]))

🟢 Head Guard

Solution in Python
while True:
    try:
        s = input()
    except:
        break
    parts = []
    prev, t = s[0], 1
    for c in s[1:]:
        if c != prev:
            parts.append((prev, t))
            t = 1
            prev = c
        else:
            t += 1
    parts.append((prev, t))
    print("".join([f"{v}{k}" for k, v in parts]))

🟢 Heart Rate

Solution in Python
1
2
3
4
5
6
for _ in range(int(input())):
    b, p = [float(d) for d in input().split()]
    min_abpm = 60 / p * (b - 1)
    bpm = 60 * b / p
    max_abpm = 60 / p * (b + 1)
    print(f"{min_abpm:.4f} {bpm:.4f} {max_abpm:.4f}")

🟢 Homework

Solution in Python
1
2
3
4
5
6
7
8
9
total = 0
parts = input().split(";")
for part in parts:
    ranges = part.split("-")
    if len(ranges) == 1:
        total += 1
    else:
        total += len(range(int(ranges[0]), int(ranges[1]))) + 1
print(total)

🟢 Heir's Dilemma

Solution in Python
l, h = [int(d) for d in input().split()]
total = 0
for i in range(l, h + 1):
    digits = set(str(i))
    if len(digits) != 6 or "0" in digits:
        continue
    if not all([i % int(d) == 0 for d in digits]):
        continue
    total += 1
print(total)

🟢 Heliocentric

Solution in Python
def offset(d, b):
    return (b - d % b) % b


cc = 1
while True:
    try:
        a, b = [int(d) for d in input().split()]
    except:
        break

    offset_a, offset_b = offset(a, 365), offset(b, 687)

    if offset_a == offset_b:
        print(f"Case {cc}:", offset_a)
    else:
        t = offset_a
        while True:
            t += 365
            if (offset(t, 687) + offset_b) % 687 == 0:
                break
        print(f"Case {cc}:", t)

    cc += 1

🟢 Hello World!

Solutions in 11 languages
#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    return 0;
}
1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}
main = putStrLn "Hello World!"
1
2
3
4
5
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
print("Hello World!")
console.log("Hello World!");
1
2
3
fun main() {
    println("Hello World!")
}
print("Hello World!")
print("Hello World!")
puts "Hello World!"
1
2
3
fn main() {
    println!("Hello World!");
}

🟢 Help a PhD candidate out!

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())
for _ in range(n):
    line = input()
    parts = line.split("+")
    if len(parts) == 1:
        print("skipped")
    else:
        print(int(parts[0]) + int(parts[1]))

🟢 Herman

Solutions in 2 languages
1
2
3
r = io.read("*n")
print(string.format("%.6f", math.pi * r * r))
print(2 * r * r)
1
2
3
4
5
import math

r = int(input())
print(f"{math.pi*r*r:.6f}")
print(2 * r * r)

🟢 Heroes of Velmar

Solution in Python
m = {
    "Shadow": 6,
    "Gale": 5,
    "Ranger": 4,
    "Anvil": 7,
    "Vexia": 3,
    "Guardian": 8,
    "Thunderheart": 6,
    "Frostwhisper": 2,
    "Voidclaw": 3,
    "Ironwood": 3,
    "Zenith": 4,
    "Seraphina": 1,
}


def calculate(heros, location):
    boost = 0

    if "Seraphina" in heros:
        boost += heros.count("Seraphina") * (len(heros) - 1)

    if location == "center":
        boost += heros.count("Zenith") * 5

    if len(heros) == 4:
        boost += m["Thunderheart"] * heros.count("Thunderheart")

    return sum([m[h] for h in heros]) + boost


l1 = calculate(input().split()[1:], "left")
l2 = calculate(input().split()[1:], "left")
c1 = calculate(input().split()[1:], "center")
c2 = calculate(input().split()[1:], "center")
r1 = calculate(input().split()[1:], "right")
r2 = calculate(input().split()[1:], "right")

s1, s2 = 0, 0

if l1 > l2:
    s1 += 1
elif l1 < l2:
    s2 += 1

if c1 > c2:
    s1 += 1
elif c1 < c2:
    s2 += 1

if r1 > r2:
    s1 += 1
elif r1 < r2:
    s2 += 1

if s1 > s2:
    print("Player 1")
elif s1 < s2:
    print("Player 2")
else:
    if l1 + c1 + r1 > l2 + c2 + r2:
        print("Player 1")
    elif l1 + c1 + r1 < l2 + c2 + r2:
        print("Player 2")
    else:
        print("Tie")

🟢 Hipp Hipp

Solutions in 2 languages
1
2
3
for _ = 1, 20 do
    print("Hipp hipp hurra!")
end
for _ in range(20):
    print("Hipp hipp hurra!")

🟢 Hipp Hipp Húrra

Solutions in 2 languages
1
2
3
4
5
n = io.read()
d = io.read("*n")
for _ = 1, d do
    print(string.format("Hipp hipp hurra, %s!", n))
end
1
2
3
4
n = input()
x = int(input())
for _ in range(x):
    print(f"Hipp hipp hurra, {n}!")

🟢 Hissing Microphone

Solutions in 3 languages
#include <iostream>

using namespace std;

int main()
{
    string a;
    cin >> a;

    if (a.find("ss") == -1)
    {
        cout << "no hiss" << endl;
    }
    else
    {
        cout << "hiss" << endl;
    }

    return 0;
}
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (line) => {
  if (line.includes("ss")) {
    console.log("hiss");
  } else {
    console.log("no hiss");
  }
});
1
2
3
4
5
a = input()
if "ss" in a:
    print("hiss")
else:
    print("no hiss")

🟢 Hitting the Targets

Solution in Python
def in_rectangle(x1, y1, x2, y2, x, y):
    x1, x2 = min(x1, x2), max(x1, x2)
    y1, y2 = min(y1, y2), max(y1, y2)
    if x in range(x1, x2 + 1) and y in range(y1, y2 + 1):
        return True
    else:
        return False


def in_circle(x0, y0, r, x, y):
    return (x0 - x) ** 2 + (y0 - y) ** 2 <= r**2


m = int(input())
shapes = []
for _ in range(m):
    values = input().split()
    shapes.append((values[0], *[int(d) for d in values[1:]]))

n = int(input())
for _ in range(n):
    total = 0
    x, y = [int(d) for d in input().split()]
    for shape in shapes:
        if shape[0] == "rectangle":
            total += in_rectangle(*shape[1:], x, y)
        elif shape[0] == "circle":
            total += in_circle(*shape[1:], x, y)
    print(total)

🟢 Hnappasetningaskipti

Solution in Python
table = """
qwerty  dvorak  bjarki
~   ~   0
1   1   2
2   2   4
3   3   8
4   4   6
5   5   1
6   6   3
7   7   5
8   8   7
9   9   9
0   0   =
-   [   -
=   ]   /
q   '   b
w   ,   j
e   .   a
r   p   r
t   y   k
y   f   i
u   g   g
i   c   u
o   r   s
p   l   t
[   /   .
]   =   ,
a   a   l
s   o   o
d   e   e
f   u   m
g   i   p
h   d   d
j   h   c
k   t   n
l   n   v
;   s   q
'   -   ;
z   ;   [
x   q   ]
c   j   y
v   k   z
b   x   h
n   b   w
m   m   f
,   w   x
.   v   '
/   z   ~
""".strip()

m = {
    "qwerty": [row.split("\t")[0] for row in table.split("\n")[1:]],
    "dvorak": [row.split("\t")[1] for row in table.split("\n")[1:]],
    "bjarki": [row.split("\t")[2] for row in table.split("\n")[1:]],
}
k, _, v = input().split()
mapping = dict(zip(m[k], m[v]))

s = input()
print("".join(mapping.get(c, c) for c in s))

🟢 Hot Hike

Solution in Python
1
2
3
4
5
6
n = int(input())
t = [int(d) for d in input().split()]
order = sorted(range(n - 2), key=lambda k: max(t[k], t[k + 2]))
d = order[0]
v = max(t[d], t[d + 2])
print(d + 1, v)

🟢 Howl

Solutions in 2 languages
1
2
3
4
s = io.read()
s, _ = s:gsub("A", "AW")
s, _ = s:gsub("WW", "WAW")
print(s)
print(input().replace("A", "AW").replace("WW", "WAW"))

🟢 Hraðgreining

Solutions in 3 languages
package main

import (
    "fmt"
    "strings"
)

func main() {
    var s string
    fmt.Scan(&s)
    if strings.Contains(s, "COV") {
        fmt.Println("Veikur!")
    } else {
        fmt.Println("Ekki veikur!")
    }
}
1
2
3
4
5
if string.find(io.read(), "COV") then
    print("Veikur!")
else
    print("Ekki veikur!")
end
print("Veikur!" if "COV" in input() else "Ekki veikur!")

🟢 The Amazing Human Cannonball

Solution in Python
import math

for _ in range(int(input())):
    v0, a, x1, h1, h2 = [float(d) for d in input().split()]
    a = math.radians(a)
    t = x1 / (v0 * math.cos(a))
    y = v0 * t * math.sin(a) - 0.5 * 9.81 * (t**2)
    if y < h1 + 1 or y > h2 - 1:
        print("Not Safe")
    else:
        print("Safe")

🟢 Hvert Skal Mæta?

Solution in Python
mapping = {
    "Reykjavik": "Reykjavik",
    "Kopavogur": "Reykjavik",
    "Hafnarfjordur": "Reykjavik",
    "Reykjanesbaer": "Reykjavik",
    "Akureyri": "Akureyri",
    "Gardabaer": "Reykjavik",
    "Mosfellsbaer": "Reykjavik",
    "Arborg": "Reykjavik",
    "Akranes": "Reykjavik",
    "Fjardabyggd": "Akureyri",
    "Mulathing": "Akureyri",
    "Seltjarnarnes": "Reykjavik",
}
print(mapping[input()])

🟢 ICPC Awards

Solution in Python
1
2
3
4
5
6
7
n = int(input())
shown = {}
for _ in range(n):
    u, t = input().split()
    if u not in shown and len(shown.keys()) < 12:
        print(u, t)
        shown[u] = True

🟢 Illuminati Spotti

Solution in Python
n = int(input())
m = []
for _ in range(n):
    m.append(input().split())
total = 0
for i in range(1, n - 1):
    for j in range(i):
        for k in range(i + 1, n):
            if m[i][j] == m[k][j] == m[k][i] == "1":
                total += 1
print(total)

🟢 Inflation

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())
c = [int(d) for d in input().split()]
s = range(1, n + 1)
f = [b / a for a, b in zip(s, sorted(c))]
if max(f) > 1:
    print("impossible")
else:
    print(min(f))

🟡 Inheritance

Solution in Python
1
2
3
4
5
6
7
8
9
from itertools import product

p = input()
ans = []
for i in range(len(p)):
    for t in product("24", repeat=i + 1):
        if int(p) % int("".join(t)) == 0:
            ans.append(int("".join(t)))
print("\n".join([str(d) for d in sorted(ans)]))

🟢 International Dates

Solution in Python
1
2
3
4
5
6
7
8
aa, bb, _ = [int(d) for d in input().split("/")]

if aa > 12 and bb <= 12:
    print("EU")
elif aa <= 12 and bb > 12:
    print("US")
else:
    print("either")

🟢 I Repeat Myself I Repeat Myself I Repeat

Solution in Python
1
2
3
4
5
6
7
8
import math

for _ in range(int(input())):
    s = input()
    for n in range(1, len(s) + 1):
        if (s[:n] * math.ceil(len(s) / n)).startswith(s):
            print(n)
            break

🟡 Is It Even?

Solution in Python
n, k = [int(d) for d in input().split()]

for _ in range(n):
    x = int(input())
    while True:
        if x % 2 == 0:
            x //= 2
            k -= 1
        else:
            break
    if k <= 0:
        break

print(0 if k > 0 else 1)

🟢 IsItHalloween.com

Solutions in 2 languages
package main

import "fmt"

func main() {
    var m, d string
    fmt.Scan(&m)
    fmt.Scan(&d)
    if (m == "OCT" && d == "31") || (m == "DEC" && d == "25") {
        fmt.Println("yup")
    } else {
        fmt.Println("nope")
    }
}
1
2
3
4
5
m, d = input().split()
if (m == "OCT" and d == "31") or (m == "DEC" and d == "25"):
    print("yup")
else:
    print("nope")

🟢 Is Y a Vowel?

Solution in Python
1
2
3
4
5
6
7
8
w = input()
a, b = 0, 0
for c in w:
    if c in "aeiou":
        a += 1
    if c == "y":
        b += 1
print(a, a + b)

🟢 Jabuke

Solution in Python
xa, ya = [int(d) for d in input().split()]
xb, yb = [int(d) for d in input().split()]
xc, yc = [int(d) for d in input().split()]
n = int(input())
area = abs(xa * (yb - yc) + xb * (yc - ya) + xc * (ya - yb)) / 2
print(f"{area:.1f}")


def sign(x1, y1, x2, y2, x3, y3):
    return (x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3)


def in_triangle(x, y, x1, y1, x2, y2, x3, y3):
    d1 = sign(x, y, x1, y1, x2, y2)
    d2 = sign(x, y, x2, y2, x3, y3)
    d3 = sign(x, y, x3, y3, x1, y1)

    has_neg = d1 < 0 or d2 < 0 or d3 < 0
    has_pos = d1 > 0 or d2 > 0 or d3 > 0

    return not (has_neg and has_pos)


total = 0
for _ in range(n):
    x, y = [int(d) for d in input().split()]
    if in_triangle(x, y, xa, ya, xb, yb, xc, yc):
        total += 1
print(total)

🟢 Jack-O'-Lantern Juxtaposition

Solution in Python
1
2
3
4
5
numbers = [int(n) for n in input().split()]
result = 1
for n in numbers:
    result *= n
print(result)

🟢 Janitor Troubles

Solution in Python
1
2
3
4
5
import math

a, b, c, d = [int(d) for d in input().split()]
s = (a + b + c + d) / 2
print(math.sqrt((s - a) * (s - b) * (s - c) * (s - d)))

🟢 Jazz it Up!

Solution in Python
import math

n = int(input())
m = 2
while True:
    f = True
    for k in range(2, math.ceil(math.sqrt(n * m))):
        if not n * m % (k**2):
            f = False
            break
    if not f:
        m += 1
    else:
        break
print(m)

🟢 Jewelry Box

Solution in Python
def f(h):
    a = x - 2 * h
    b = y - 2 * h
    return a * b * h


for _ in range(int(input())):
    x, y = [int(d) for d in input().split()]
    h = (x + y - ((x + y) ** 2 - 3 * x * y) ** 0.5) / 6
    print(f"{f(h):.11f}")

🟢 Job Expenses

Solution in Python
_ = input()
print(-sum([int(d) for d in input().split() if "-" in d]))

🟢 Joint Jog Jam

Solution in Python
1
2
3
4
5
6
7
8
9
import math


def dist(x1, y1, x2, y2):
    return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)


coords = [int(d) for d in input().split()]
print(max(dist(*coords[:4]), dist(*coords[4:])))

🟢 Judging Moose

Solutions in 3 languages
package main

import "fmt"

func main() {
    var l, r int
    fmt.Scan(&l)
    fmt.Scan(&r)
    if l == 0 && r == 0 {
        fmt.Println("Not a moose")
    } else {
        p := 2 * l
        if r > l {
            p = 2 * r
        }
        t := "Odd"
        if l == r {
            t = "Even"
        }
        fmt.Println(t, p)
    }
}
l, r = io.read("*n", "*n")
if l == 0 and r == 0 then
    print("Not a moose")
else
    p = 2 * math.max(l, r)
    if l ~= r then
        print("Odd", p)
    else
        print("Even", p)
    end
end
1
2
3
4
5
6
l, r = [int(d) for d in input().split()]
if not l and not r:
    print("Not a moose")
else:
    p = 2 * max(l, r)
    print("Odd" if l != r else "Even", p)

🟢 Jumbo Javelin

Solutions in 2 languages
1
2
3
4
5
6
7
n = io.read("*n")
length = 0
for _ = 1, n do
    length = length + io.read("*n")
end
length = length - (n - 1)
print(length)
1
2
3
4
5
6
n = int(input())
length = 0
for _ in range(n):
    length += int(input())
length -= n - 1
print(length)

🟢 Just a Minute

Solution in Python
1
2
3
4
5
6
7
8
9
a, b = [], []
for _ in range(int(input())):
    x, y = [int(d) for d in input().split()]
    a.append(x * 60)
    b.append(y)
ans = sum(b) / sum(a)
if ans <= 1:
    ans = "measurement error"
print(ans)

🟢 Kafkaesque

Solutions in 2 languages
n = io.read("*n")
t, c = 0, 1
for _ = 1, n do
    v = io.read("*n")
    if v < t then
        t = 0
        c = c + 1
    end
    t = v
end
print(c)
1
2
3
4
5
6
7
8
9
n = int(input())
t, c = 0, 1
for _ in range(n):
    v = int(input())
    if v < t:
        t = 0
        c += 1
    t = v
print(c)

🟡 Running Race

Solution in Python
l, k, _ = [int(d) for d in input().split()]

record = {}
for _ in range(l):
    i, t = input().split()
    mm, ss = [int(d) for d in t.split(".")]
    s = mm * 60 + ss
    if i in record:
        record[i].append(s)
    else:
        record[i] = [s]

delete = [i for i in record if len(record[i]) != k]
for i in delete:
    record.pop(i)

sorted_i = sorted(record, key=lambda i: (sum(record[i]), int(i)))
print("\n".join(sorted_i))

🟢 Karte

Solution in Python
from collections import Counter

s = input()
cards = {
    "P": Counter(),
    "K": Counter(),
    "H": Counter(),
    "T": Counter(),
}
duplicated = False
for i in range(0, len(s), 3):
    suit = s[i]
    card = s[i + 1 : i + 3]
    if cards[suit][card]:
        duplicated = True
        break
    cards[suit][card] += 1

if not duplicated:
    print(" ".join([str(13 - len(c)) for c in cards.values()]))
else:
    print("GRESKA")

🟢 kcuD dlanoD

Solution in Python
a, b = input().split()
a = list(a)[::-1]
for i in range(len(a)):
    if a[i] == "5":
        a[i] = "2"
    elif a[i] == "2":
        a[i] = "5"
b = list(b)[::-1]
for i in range(len(b)):
    if b[i] == "5":
        b[i] = "2"
    elif b[i] == "2":
        b[i] = "5"
a, b = int("".join(a)), int("".join(b))
if a > b:
    print(1)
else:
    print(2)

🟢 Kemija

Solutions in 2 languages
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (line) => {
  for (let c of "aeiou") {
    const regex = new RegExp(`${c}p${c}`, "g");
    line = line.replace(regex, c);
  }
  console.log(line);
});
1
2
3
4
5
6
s = input()

for c in "aeiou":
    s = s.replace(f"{c}p{c}", c)

print(s)

🟢 Keys, Phone, Wallet

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
items = [input() for _ in range(n)]
ready = True
for item in ["keys", "phone", "wallet"]:
    if item not in items:
        print(item)
        ready = False
if ready:
    print("ready")

🟢 The Key to Cryptography

Solution in Python
import string

uppers = string.ascii_uppercase


def decrypt(c, k):
    index = (uppers.index(c) - uppers.index(k)) % 26
    return uppers[index]


m, w = input(), input()

size_w = len(w)
size_m = len(m)
o = []
for i in range(0, size_m, size_w):
    if i + size_w < size_m:
        l = zip(m[i : i + size_w], w)
    else:
        l = zip(m[i:], w)
    t = "".join([decrypt(c, k) for c, k in l])
    o.append(t)
    w = t
print("".join(o))

🟢 Keywords

Solution in Python
1
2
3
4
keywords = set()
for _ in range(int(input())):
    keywords.add(input().lower().replace("-", " "))
print(len(keywords))

🟢 Kiki Boba

Solutions in 2 languages
package main

import (
    "fmt"
    "strings"
)

func main() {
    var w string
    fmt.Scan(&w)
    b := strings.Count(w, "b")
    k := strings.Count(w, "k")
    if b > k {
        fmt.Println("boba")
    } else if b < k {
        fmt.Println("kiki")
    } else if b > 0 {
        fmt.Println("boki")
    } else {
        fmt.Println("none")
    }
}
w = input()
b, k = w.count("b"), w.count("k")
if not b and not k:
    print("none")
elif b == k:
    print("boki")
elif b > k:
    print("boba")
else:
    print("kiki")

🟢 Kínahvísl

Solution in Python
1
2
3
s1 = input()
s2 = input()
print(sum(a != b for a, b in zip(s1, s2)) + 1)

🟢 Kitten on a Tree

Solution in Python
k = input()
b = []
while True:
    line = input()
    if line == "-1":
        break
    b.append(line.split())

p = [k]
t = k
while True:
    found = False
    for row in b:
        if t in row[1:]:
            p.append(row[0])
            found = True
            t = row[0]
            break
    if not found:
        break

print(" ".join(p))

🟢 Kleptography

Solution in Python
from string import ascii_lowercase as l

n, m = [int(d) for d in input().split()]
p = input()
c = input()
p = p[::-1]
c = c[::-1]

ans = ""
for i in range(0, m, n):
    if i + n < m:
        part = c[i : i + n]
    else:
        part = c[i:]

    ans += p
    p = "".join([l[(l.index(a) - l.index(b)) % 26] for a, b in zip(part, p)])

ans += p
print(ans[::-1][n:])

🟢 Knight Packing

Solutions in 3 languages
1
2
3
4
5
6
7
fun main() {
    if (readLine()!!.toInt() % 2 == 1) {
        println("first")
    } else {
        println("second")
    }
}
1
2
3
4
5
if io.read("*n") % 2 == 1 then
    print("first")
else
    print("second")
end
1
2
3
4
if int(input()) % 2:
    print("first")
else:
    print("second")

🟢 Knot Knowledge

Solution in Python
1
2
3
4
input()
total = set(input().split())
known = set(input().split())
print((total - known).pop())

🟢 Kornislav

Solution in Python
numbers = sorted([int(d) for d in input().split()])
print(numbers[0] * numbers[2])

🟢 Križaljka

Solution in Python
a, b = input().split()
for i in range(len(a)):
    if a[i] in b:
        j = b.index(a[i])
        break

rows = []

for k in range(j):
    rows.append("." * i + b[k] + "." * (len(a) - i - 1))

rows.append(a)

for k in range(j + 1, len(b)):
    rows.append("." * i + b[k] + "." * (len(a) - i - 1))

print("\n".join(rows))

🟢 Kveðja

Solution in Python
print(f"Kvedja,\n{input()}")

🟢 Ladder

Solution in Python
1
2
3
4
import math

h, v = [int(d) for d in input().split()]
print(math.ceil(h / math.sin(math.radians(v))))

🟢 Lægð yfir landinu

Solution in Python
n, m = [int(d) for d in input().split()]
p = []
for _ in range(n):
    p.append([int(d) for d in input().split()])

f = False
for i in range(1, n - 1):
    for j in range(1, m - 1):
        c = []
        c.append(p[i - 1][j])
        c.append(p[i][j - 1])
        c.append(p[i + 1][j])
        c.append(p[i][j + 1])
        if all(v > p[i][j] for v in c):
            f = True
            break
    if f:
        break

print("Jebb" if f else "Neibb")

🟡 Lamps

Solution in Python
h, p = [int(d) for d in input().split()]

days = 0
cost_bulb, cost_lamp = 5, 60
used_bulb, used_lamp = 0, 0

while True:
    days += 1
    cost_bulb += 60 * h * p / 100000
    cost_lamp += 11 * h * p / 100000
    used_bulb += h
    used_lamp += h

    if used_bulb > 1000:
        cost_bulb += 5
        used_bulb -= 1000

    if used_lamp > 8000:
        cost_lamp += 60
        used_lamp -= 8000

    if cost_bulb > cost_lamp:
        break

print(days)

🟢 Laptop Sticker

Solutions in 4 languages
#include <iostream>

using namespace std;

int main()
{
    int wc, hc, ws, hs;
    cin >> wc >> hc >> ws >> hs;
    if (wc - 2 >= ws && hc - 2 >= hs)
    {
        cout << 1 << endl;
    }
    else
    {
        cout << 0 << endl;
    }
    return 0;
}
package main

import "fmt"

func main() {
    var wc, hc, ws, hs int
    fmt.Scan(&wc)
    fmt.Scan(&hc)
    fmt.Scan(&ws)
    fmt.Scan(&hs)
    if wc-2 >= ws && hc-2 >= hs {

        fmt.Println(1)

    } else {

        fmt.Println(0)

    }
}
1
2
3
4
5
6
wc, hc, ws, hs = io.read("*n", "*n", "*n", "*n")
if wc - 2 >= ws and hc - 2 >= hs then
    print(1)
else
    print(0)
end
1
2
3
4
5
wc, hc, ws, hs = [int(d) for d in input().split()]
if wc - 2 >= ws and hc - 2 >= hs:
    print(1)
else:
    print(0)

🟢 Last Factorial Digit

Solutions in 2 languages
1
2
3
4
5
6
7
8
for _ = 1, io.read("*n") do
    n = io.read("*n")
    number = 1
    for i = 1, n do
        number = number * i
    end
    print(number % 10)
end
1
2
3
4
5
6
for _ in range(int(input())):
    n = int(input())
    number = 1
    for i in range(1, n + 1):
        number *= i
    print(number % 10)

🟢 Left Beehind

Solutions in 3 languages
package main

import "fmt"

func main() {
    var x, y int
    for true {
        fmt.Scan(&x)
        fmt.Scan(&y)
        if x == 0 && y == 0 {
            break
        }
        if x+y == 13 {
            fmt.Println("Never speak again.")
        } else if x > y {
            fmt.Println("To the convention.")
        } else if x == y {
            fmt.Println("Undecided.")
        } else {
            fmt.Println("Left beehind.")
        }
    }
}
import java.util.Scanner;

class LeftBeehind {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        while (true) {
            int x = s.nextInt();
            int y = s.nextInt();
            if (x == 0 && y == 0) {
                break;
            }
            if (x + y == 13) {
                System.out.println("Never speak again.");
            } else if (x > y) {
                System.out.println("To the convention.");
            } else if (x == y) {
                System.out.println("Undecided.");
            } else {
                System.out.println("Left beehind.");
            }
        }
    }
}
while True:
    x, y = [int(d) for d in input().split()]
    if not x and not y:
        break
    if x + y == 13:
        print("Never speak again.")
    elif x > y:
        print("To the convention.")
    elif x == y:
        print("Undecided.")
    else:
        print("Left beehind.")

🟢 Leggja saman

Solutions in 3 languages
package main

import "fmt"

func main() {
    var n, m int
    fmt.Scan(&n)
    fmt.Scan(&m)
    fmt.Println(n + m)
}
n, m = io.read("*n", "*n")
print(n + m)
1
2
3
m = int(input())
n = int(input())
print(m + n)

🟢 License to Launch

Solution in Python
1
2
3
_ = input()
junks = [int(d) for d in input().split()]
print(junks.index(min(junks)))

🟢 Liðaskipting 2

Solution in Python
1
2
3
n = int(input())
print(n)
print(n // 3 + (1 if n % 3 else 0))

🟢 Lines Per Hour

Solution in Python
n, lph = [int(d) for d in input().split()]
loc = sorted([int(input()) for _ in range(n)])
s, l = 0, 0
for v in loc:
    if l + v <= 5 * lph:
        l += v
        s += 1
    else:
        break
print(s)

🟢 Line Them Up

Solution in Python
n = int(input())
names = []
for _ in range(n):
    names.append(input())
order = []
for i in range(1, n):
    order.append(names[i] > names[i - 1])
if all(order):
    print("INCREASING")
elif not any(order):
    print("DECREASING")
else:
    print("NEITHER")

🟡 A List Game

Solution in Python
import math

x = int(input())

p = 1
total = 0

while x % 2 == 0:
    p = 2
    x /= 2
    total += 1


for i in range(3, math.ceil(math.sqrt(x)) + 1, 2):
    while x % i == 0:
        p = i
        x /= i
        total += 1
if x > 1:
    total += 1


if p == 1:
    total = 1


print(total)

🟢 Locust Locus

Solution in Python
1
2
3
4
5
6
7
8
9
from math import gcd

n = int(input())
l = []
for _ in range(n):
    y, c1, c2 = [int(d) for d in input().split()]
    g = gcd(c1, c2)
    l.append(y + g * (c1 // g) * (c2 // g))
print(min(l))

🟢 Logic Functions

Solution in C++
#include "logicfunctions.h"

// Compute xor
void exclusive(bool x, bool y, bool &ans)
{
    ans = x != y;
}

// Compute implication
void implies(bool x, bool y, bool &ans)
{
    if (x && !y)
    {
        ans = false;
    }
    else
    {
        ans = true;
    }
}

// Compute equivalence
void equivalence(bool x, bool y, bool &ans)
{
    ans = x == y;
}

🟢 Lost Lineup

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
order = [int(d) for d in input().split()]
d = range(1, n)
order = dict(zip(d, order))
ranges = range(1, n + 1)
result = ["1"]
for k in sorted(order, key=lambda x: order[x]):
    result.append(str(ranges[k]))
print(" ".join(result))

🟢 Lubbi Lærir

Solution in Python
print(input()[0])

🟢 Luhn's Checksum Algorithm

Solution in Python
for _ in range(int(input())):
    n = input()[::-1]
    checksum = 0
    for i in range(len(n)):
        s = int(n[i]) * (i % 2 + 1)
        if s > 9:
            s = sum([int(d) for d in str(s)])
        checksum += s

    print("FAIL" if checksum % 10 else "PASS")

🟢 Mæting

Solution in Python
from collections import Counter

d = Counter()
for _ in range(int(input())):
    d[input()] = 0

for _ in range(int(input())):
    l = input().split()
    if len(l) == 1:
        continue
    for n in l[1:]:
        d[n] += 1

for k in sorted(d, key=lambda k: -d[k]):
    print(d[k], k)

🟢 Magic Trick

Solution in Python
s = input()
counter = {}
guess = 1
for c in s:
    if c in counter:
        guess = 0
        break
    else:
        counter[c] = None
print(guess)

🟢 Making A Meowth

Solutions in 2 languages
n, p, x, y = io.read("*n", "*n", "*n", "*n")
print(p * x + p // (n - 1) * y)
n, p, x, y = [int(d) for d in input().split()]
print(p * x + p // (n - 1) * y)

🟢 Identifying Map Tiles

Solutions in 2 languages
package main

import (
    "fmt"
    "math"
)

func main() {
    var s string
    fmt.Scanln(&s)
    zoom := len(s)
    var x, y float64
    for i := 0; i < zoom; i++ {
        d := math.Pow(2, float64(zoom)-float64(i)-1)
        if s[i] == '1' {
            x += d
        } else if s[i] == '2' {
            y += d
        } else if s[i] == '3' {
            x += d
            y += d
        }
    }
    fmt.Printf("%d %d %d", zoom, int64(x), int64(y))
}
s = input()
x, y = 0, 0
zoom = len(s)
for i in range(len(s)):
    d = 2 ** (zoom - i - 1)
    if s[i] == "1":
        x += d
    elif s[i] == "2":
        y += d
    elif s[i] == "3":
        x += d
        y += d
print(f"{zoom} {x} {y}")

🟢 Marko

Solution in Python
mapping = {
    "2": "abc",
    "3": "def",
    "4": "ghi",
    "5": "jkl",
    "6": "mno",
    "7": "pqrs",
    "8": "tuv",
    "9": "wxyz",
}
n = []
for _ in range(int(input())):
    w = input()
    t = ""
    for c in w:
        for d, r in mapping.items():
            if c in r:
                t += d
                break
    n.append(t)

d = input()
print(sum([d == t for t in n]))

🟢 Mars Window

Solutions in 2 languages
1
2
3
4
5
6
y = io.read("*n")
if 26 - ((y - 2018) * 12 - 4) % 26 <= 12 then
    print("YES")
else
    print("NO")
end
y = int(input())
print("YES" if 26 - ((y - 2018) * 12 - 4) % 26 <= 12 else "NO")

🟢 Math Homework

Solution in Python
b, d, c, l = [int(d) for d in input().split()]
solved = False
for i in range(l // b + 1):
    for j in range((l - b * i) // d + 1):
        for k in range((l - b * i - d * j) // c + 1):
            if b * i + d * j + c * k == l:
                print(i, j, k)
                solved = True
if not solved:
    print("impossible")

🟢 Mean Words

Solution in Python
n = int(input())
words = []
for _ in range(n):
    words.append(input())
m = max([len(w) for w in words])
ans = []
for i in range(m):
    values = [ord(w[i]) for w in words if len(w) > i]
    ans.append(sum(values) // len(values))
print("".join(chr(d) for d in ans))

🟢 Imperial Measurement

Solution in Python
mapping = {
    "th": "thou",
    "in": "inch",
    "ft": "foot",
    "yd": "yard",
    "ch": "chain",
    "fur": "furlong",
    "mi": "mile",
    "lea": "league",
}
names = list(mapping.values())
scale = [1, 1000, 12, 3, 22, 10, 8, 3]

v, a, _, b = input().split()
v = int(v)
na, nb = mapping.get(a, a), mapping.get(b, b)
ia, ib = names.index(na), names.index(nb)

rate = 1
for s in scale[min(ia, ib) + 1 : max(ia, ib) + 1]:
    rate *= s

print(v * rate if ia > ib else v / rate)

🟢 Message

Solution in Python
1
2
3
4
5
6
7
8
9
n, m = [int(d) for d in input().split()]
cells = []
for _ in range(n):
    cells.append(input())
message = ""
for j in range(m):
    for i in range(n):
        message += cells[i][j] if cells[i][j] != "." else ""
print(message)

🟡 Meow Factor

Solution in Python
from collections import Counter
from math import ceil, sqrt

c = Counter({1: 9})
n = int(input())
for i in range(2, ceil(sqrt(n))):
    while n % i == 0:
        c[i] += 1
        n //= i
    if i**9 >= n:
        break

t = 1
for k, v in c.items():
    if v >= 9:
        t *= k ** (v // 9)
print(t)

🟢 Metaprogramming

Solution in Python
c = {}
while True:
    try:
        s = input()
    except:
        break
    parts = s.split()
    if parts[0] == "define":
        v, n = parts[1:]
        c[n] = int(v)
    elif parts[0] == "eval":
        x, y, z = parts[1:]
        if x not in c or z not in c:
            print("undefined")
        elif y == "=":
            print("true" if c[x] == c[z] else "false")
        elif y == ">":
            print("true" if c[x] > c[z] else "false")
        elif y == "<":
            print("true" if c[x] < c[z] else "false")

🟢 Methodic Multiplication

Solution in Python
1
2
3
a, b = input(), input()
t = a.count("S") * b.count("S")
print("S(" * t + "0" + ")" * t)

🟢 Metronome

Solutions in 2 languages
n = io.read("*n")
print(string.format("%.2f", n / 4))
n = int(input())
print(f"{n/4:.2f}")

🟢 Mia

Solution in Python
def score(a, b):
    roll = set([a, b])
    if roll == {1, 2}:
        return (3, None)
    elif len(roll) == 1:
        return (2, a)
    else:
        a, b = min(a, b), max(b, a)
        return (1, 10 * b + a)


while True:
    rolls = [int(d) for d in input().split()]
    if not any(rolls):
        break
    score1 = score(*rolls[:2])
    score2 = score(*rolls[2:])
    if score1 == score2:
        print("Tie.")
    elif score1[0] == score2[0]:
        print(f"Player {1 if score1[1] > score2[1] else 2} wins.")
    else:
        print(f"Player {1 if score1[0] > score2[0] else 2} wins.")

🟢 Miði

Solution in Python
1
2
3
4
5
n = int(input())
parts = []
for _ in range(n):
    parts.append(input())
print("".join(p[::-1] for p in parts[::-1]))

🟢 Millifærsla

Solution in Python
1
2
3
4
names, fees = ["Monnei", "Fjee", "Dolladollabilljoll"], []
for _ in range(3):
    fees.append(int(input()))
print(names[fees.index(min(fees))])

🟢 Minimum Scalar Product

Solution in Python
1
2
3
4
5
6
7
t = int(input())
for i in range(t):
    _ = input()
    a = sorted([int(d) for d in input().split()])
    b = sorted([int(d) for d in input().split()], reverse=True)
    v = sum(x * y for x, y in zip(a, b))
    print(f"Case #{i+1}: {v}")

🟢 Missing Numbers

Solution in Python
numbers = []
for _ in range(int(input())):
    numbers.append(int(input()))

is_good_job = True
for i in range(1, max(numbers) + 1):
    if i not in numbers:
        is_good_job = False
        print(i)

if is_good_job:
    print("good job")

🟢 Mixed Fractions

Solution in Python
1
2
3
4
5
6
7
while True:
    m, n = [int(d) for d in input().split()]
    if not m and not n:
        break
    a = m // n
    b = m % n
    print(f"{a} {b} / {n}")

🟢 Mjehuric

Solution in Python
1
2
3
4
5
6
f = input().split()
while f != [str(d) for d in range(1, 6)]:
    for i in range(4):
        if f[i] > f[i + 1]:
            f[i], f[i + 1] = f[i + 1], f[i]
            print(" ".join(f))

🟢 Moderate Pace

Solution in Python
1
2
3
4
n = int(input())
distances = [[int(d) for d in input().split()] for _ in range(3)]
plan = [sorted([d[i] for d in distances])[1] for i in range(n)]
print(" ".join([str(d) for d in plan]))

🟢 Modulo

Solution in Python
1
2
3
4
n = set()
for _ in range(10):
    n.add(int(input()) % 42)
print(len(n))

🟢 Monopoly

Solution in Python
n = int(input())
a = [int(d) for d in input().split()]
t = 0
m = 0
for i in range(1, 7):
    for j in range(1, 7):
        t += 1
        if i + j in a:
            m += 1
print(m / t)

🟢 Moscow Dream

Solution in Python
1
2
3
4
5
6
a, b, c, n = [int(d) for d in input().split()]

if not all(d > 0 for d in [a, b, c]):
    print("NO")
else:
    print("YES" if a + b + c >= n and n >= 3 else "NO")

🟢 Mosquito Multiplication

Solution in Python
while True:
    try:
        m, p, l, e, r, s, n = [int(d) for d in input().split()]
    except:
        break
    for _ in range(n):
        pp = p
        p = l // r
        l = e * m
        m = pp // s
    print(m)

🟢 Moving Day

Solutions in 2 languages
1
2
3
4
5
6
7
n, v = io.read("*n", "*n")
b = {}
for i = 1, n do
    l, w, h = io.read("*n", "*n", "*n")
    b[i] = (l * w * h)
end
print(math.max(table.unpack(b)) - v)
1
2
3
4
5
6
n, v = [int(d) for d in input().split()]
b = []
for _ in range(n):
    l, w, h = [int(d) for d in input().split()]
    b.append(l * w * h)
print(max(b) - v)

🟢 MrCodeFormatGrader

Solution in Python
def f(numbers):
    prev = numbers[0]
    ans = {prev: 1}
    for i in range(1, len(numbers)):
        if numbers[i] == prev + ans[prev]:
            ans[prev] += 1
        else:
            prev = numbers[i]
            ans[prev] = 1

    parts = [
        f"{key}-{key+value-1}"
        if value > 1
        else " ".join([str(d) for d in range(key, key + value)])
        for key, value in ans.items()
    ]

    return ", ".join(parts[:-1]) + " and " + parts[-1]


c, n = [int(d) for d in input().split()]
errors = [int(d) for d in input().split()]
correct = [i for i in range(1, 1 + c) if i not in errors]

print("Errors:", f(errors))
print("Correct:", f(correct))

🟢 Mult!

Solution in Python
n = int(input())
b = None
for _ in range(n):
    d = int(input())
    if not b:
        b = d
        continue

    if d % b == 0:
        print(d)
        b = None

🟢 Mumble Rap

Solution in Python
n = int(input())
s = input()
a = []
d = ""
import string

for i in range(n):
    if s[i] in string.digits:
        d += s[i]

    else:
        if d:
            a.append(int(d))
            d = ""
if d:
    a.append(int(d))

print(max(a))

🟢 Musical Scales

Solution in Python
notes = ["A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"]
offset = [2, 2, 1, 2, 2, 2]
majors = {}
for i in range(len(notes)):
    name = notes[i]
    progression = [name]
    for i in offset:
        index = (notes.index(progression[-1]) + i) % len(notes)
        progression.append(notes[index])
    majors[name] = progression

_ = input()
scales = set(input().split())
print(" ".join([n for n in majors if scales < set(majors[n])]) or "none")

🟢 Music Your Way

Solution in Python
cols = input().split()
m = int(input())
songs = [input().split() for _ in range(m)]
n = int(input())

for i in range(n):
    col = input()
    index = cols.index(col)
    songs = sorted(songs, key=lambda k: k[index])
    print(" ".join(cols))
    for song in songs:
        print(" ".join(song))
    if i < n - 1:
        print()

🟢 Mylla

Solution in Python
board = []
for _ in range(3):
    board.append(list(input()))

winner = ""
for i in range(3):
    if board[i][0] == board[i][1] == board[i][2] and board[i][0] != "_":
        winner = board[i][0]
        break
    elif board[0][i] == board[1][i] == board[2][i] and board[0][i] != "_":
        winner = board[0][i]
        break

if board[0][0] == board[1][1] == board[2][2] and board[1][1] != "_":
    winner = board[1][1]
elif board[0][2] == board[1][1] == board[2][0] and board[1][1] != "_":
    winner = board[1][1]

if winner == "O":
    winner = "Jebb"
else:
    winner = "Neibb"

print(winner)

🟡 Name Generation

Solution in Python
import string
from random import choice, randint

vowels = set("aeiou")
consonants = set(string.ascii_lowercase) - vowels
names = set()


def f(w):
    return "".join([choice(list(consonants)) if c else choice(list(vowels)) for c in w])


for _ in range(int(input())):
    s = randint(3, 20)
    w = []
    for i in range(s):
        if i < 2:
            w.append(randint(0, 1))
        else:
            if w[-1] == w[-2]:
                w.append((w[-2] + 1) % 2)
            else:
                w.append(randint(0, 1))

    name = f(w)
    while name in names:
        name = f(w)
    names.add(name)

    print(name)

🟢 Nasty Hacks

Solutions in 3 languages
#include <iostream>

using namespace std;

int main()
{
    int n, r, e, c;
    cin >> n;

    for (int i = 0; i < n; i++)
    {
        cin >> r >> e >> c;
        if ((e - c) > r)
        {
            cout << "advertise";
        }
        else if ((e - c) < r)
        {
            cout << "do not advertise";
        }
        else
        {
            cout << "does not matter";
        }
    }
}
for _ = 1, io.read("*n") do
    r, e, c = io.read("*n", "*n", "*n")
    if e > r + c then
        print("advertise")
    elseif e < r + c then
        print("do not advertise")
    else
        print("does not matter")
    end
end
1
2
3
4
5
6
7
8
for _ in range(int(input())):
    r, e, c = [int(d) for d in input().split()]
    if e > r + c:
        print("advertise")
    elif e < r + c:
        print("do not advertise")
    else:
        print("does not matter")

🟢 No Duplicates

Solution in Python
words = input().split()

counter = {}
repeated = False
for w in words:
    if w in counter:
        repeated = True
        break
    else:
        counter[w] = None
if repeated:
    print("no")
else:
    print("yes")

🟢 NOP

Solution in Python
s = input()
i, m, p = 0, {}, None

for c in s:
    if c.isupper():
        m[i] = 1
        p = i
        i += 1
    else:
        m[p] += 1

print(
    sum(
        4 - m[k] % 4 if m[k] % 4 else (4 if not m[k] else 0)
        for k in list(m.keys())[:-1]
    )
)

🟢 Not Amused

Solution in Python
from collections import Counter

d = 1
while True:
    try:
        s = input().split()

        if "OPEN" in s:
            book = {}
            t = Counter()
        elif "ENTER" in s:
            book[s[1]] = int(s[2])
        elif "EXIT" in s:
            t[s[1]] += int(s[2]) - book.pop(s[1])
        elif "CLOSE" in s:
            print(f"Day {d}")
            for k in sorted(t):
                print(f"{k} ${t[k]/10:.2f}")
            print()
            d += 1
    except:
        break

🟢 No Thanks!

Solution in Python
n = int(input())
v = sorted([int(d) for d in input().split()])

prev = v[0]
ans = {prev: 1}
for i in range(1, n):
    if v[i] == prev + ans[prev]:
        ans[prev] += 1
    else:
        prev = v[i]
        ans[prev] = 1

print(sum(ans.keys()))

🟢 N-sum

Solutions in 2 languages
import java.util.Scanner;

class NSum {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += s.nextInt();
        }
        System.out.println(ans);
    }
}
1
2
3
4
5
_ = int(input())
numbers = []
for d in input().split():
    numbers.append(int(d))
print(sum(numbers))

🟢 Number Fun

Solutions in 2 languages
1
2
3
4
5
6
7
8
for _ = 1, io.read("*n") do
    a, b, c = io.read("*n", "*n", "*n")
    if a + b == c or a * b == c or a - b == c or b - a == c or a == b * c or b == a * c then
        print("Possible")
    else
        print("Impossible")
    end
end
1
2
3
4
5
6
for _ in range(int(input())):
    a, b, c = [int(d) for d in input().split()]
    if a + b == c or a * b == c or a - b == c or b - a == c or a / b == c or b / a == c:
        print("Possible")
    else:
        print("Impossible")

🟢 Numbers On a Tree

Solution in Python
items = input().split()
if len(items) == 2:
    h, s = items
else:
    h, s = items[0], ""

total, i = 2 ** (int(h) + 1), 1

for c in s:
    i *= 2
    if c == "R":
        i += 1

print(total - i)

🟢 Odd Echo

Solution in Python
1
2
3
4
5
6
n = int(input())
words = []
for _ in range(n):
    words.append(input())
for i in range(0, n, 2):
    print(words[i])

🟢 Odd Gnome

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
for _ in range(n):
    g = [int(d) for d in input().split()][1:]
    prev = g[0]
    for i in range(1, len(g)):
        if g[i] != prev + 1:
            break
        prev = g[i]
    print(i + 1)

🟢 Oddities

Solutions in 2 languages
1
2
3
4
5
6
7
8
9
for _ = 1, io.read("*n") do
    x = io.read("*n")
    if x % 2 == 1 then
        ans = 'odd'
    else
        ans = 'even'
    end
    print(string.format("%d is %s", x, ans))
end
1
2
3
4
5
6
7
8
n = int(input())
for _ in range(n):
    x = int(input())
    if x % 2:
        res = "odd"
    else:
        res = "even"
    print(f"{x} is {res}")

🟢 Odd Man Out

Solution in Python
1
2
3
4
5
6
7
from collections import Counter

n = int(input())
for i in range(n):
    _ = input()
    c = Counter(input().split())
    print(f"Case #{i+1}: {' '.join(v for v in c if c[v]==1)}")

🟢 Off-World Records

Solutions in 3 languages
import java.util.Scanner;

class OffWorldRecords {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int c = s.nextInt();
        int p = s.nextInt();
        int ans = 0;

        for (int i = 0; i < n; i++) {
            int h = s.nextInt();
            if (h > c + p) {
                ans += 1;
                p = c;
                c = h;
            }
        }
        System.out.println(ans);
    }
}
n, c, p = io.read("*n", "*n", "*n")
ans = 0
for _ = 1, n do
    h = io.read("*n")
    if h > c + p then
        ans = ans + 1
        c, p = h, c
    end
end
print(ans)
1
2
3
4
5
6
7
8
n, c, p = [int(d) for d in input().split()]
ans = 0
for _ in range(n):
    h = int(input())
    if h > c + p:
        ans += 1
        c, p = h, c
print(ans)

🟢 Reverse

Solution in Python
1
2
3
4
5
6
n = int(input())
numbers = []
for _ in range(n):
    numbers.append(int(input()))
for d in numbers[::-1]:
    print(d)

🟢 Oktalni

Solution in Python
import math

mapping = {
    "000": "0",
    "001": "1",
    "010": "2",
    "011": "3",
    "100": "4",
    "101": "5",
    "110": "6",
    "111": "7",
}
b = input()
length = 3 * math.ceil(len(b) / 3)
b = b.zfill(length)

print("".join([mapping[b[i : i + 3]] for i in range(0, length, 3)]))

🟢 One Chicken Per Person!

Solution in Python
n, m = [int(d) for d in input().split()]

diff = n - m
if diff > 0:
    print(f"Dr. Chaz needs {diff} more piece{'s' if diff >1 else ''} of chicken!")
else:
    diff = abs(diff)
    print(
        f"Dr. Chaz will have {diff} piece{'s' if diff >1 else ''} of chicken left over!"
    )

🟢 Ordered Problem Set

Solution in Python
n = int(input())
d = [int(input()) for _ in range(n)]
ans = []
for i in range(2, n + 1):
    if n % i:
        continue
    f = True
    k = n // i
    for j in range(k, n, k):
        if max(d[j - k : j]) >= min(d[j : j + k]):
            f = False
            break
    if f:
        ans.append(str(i))
print("\n".join(ans) if ans else -1)

🟢 Ordinals

Solution in Python
1
2
3
4
5
6
7
8
9
def f(n):
    if n == 0:
        return "{}"
    else:
        ans = ",".join([f(i) for i in range(n)])
        return "{" + ans + "}"


print(f(int(input())))

🟢 Ornaments

Solution in Python
import math

while True:
    r, h, s = [int(d) for d in input().split()]
    if not r and not h and not s:
        break
    l = math.sqrt(h**2 - r**2) * 2
    a = math.pi - math.acos(r / h)
    l += 2 * math.pi * r * (a / math.pi)
    l *= 1 + s / 100
    print(f"{l:.2f}")

🟢 Östgötska

Solution in Python
1
2
3
4
5
6
sentence = input()
words = sentence.split()
if len([w for w in words if "ae" in w]) / len(words) >= 0.4:
    print("dae ae ju traeligt va")
else:
    print("haer talar vi rikssvenska")

🟢 Overdraft

Solutions in 2 languages
n = io.read("*n")
s = 0
b = 0
for _ = 1, n do
    t = io.read("*n")
    if t > 0 then
        b = b + t
    elseif b + t < 0 then
        s = s - (b + t)
        b = 0
    else
        b = b + t
    end
end
print(s)
n = int(input())
s = 0
b = 0
for _ in range(n):
    t = int(input())
    if t > 0:
        b += t
    elif b + t < 0:
        s -= b + t
        b = 0
    else:
        b += t
print(s)

🟢 Óvissa

Solutions in 3 languages
package main

import (
    "fmt"
    "strings"
)

func main() {
    var s string
    fmt.Scan(&s)
    fmt.Println(strings.Count(s, "u"))
}
1
2
3
s = io.read()
_, count = string.gsub(s, "u", "")
print(count)
print(input().count("u"))

🟢 The Owl and the Fox

Solution in Python
def sd(n):
    return sum([int(d) for d in str(n)])


for _ in range(int(input())):
    n = int(input())
    s = sd(n) - 1
    d = n - 1
    while True:
        if sd(d) == s:
            break
        d -= 1
    print(d)

🟢 Pachyderm Peanut Packing

Solution in Python
def inbox(coords, x, y):
    if x >= coords[0] and x <= coords[2] and y >= coords[1] and y <= coords[3]:
        return True
    return False


while True:
    n = int(input())
    if not n:
        break
    box = {}
    for i in range(n):
        desc = input().split()
        size = desc[-1]
        coords = [float(d) for d in desc[:-1]]
        box[i] = (coords, size)
    m = int(input())
    for _ in range(m):
        desc = input().split()
        size = desc[-1]
        x, y = [float(d) for d in desc[:-1]]
        floor = True
        for i in range(n):
            coords, box_size = box[i]
            if inbox(coords, x, y):
                floor = False
                break
        if floor:
            status = "floor"
        else:
            status = "correct" if box_size == size else box_size
        print(size, status)
    print()

🟢 Pallatölur

Solutions in 3 languages
package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a)
    fmt.Scan(&b)

    if (a <= 2) && (2 <= b) {
        fmt.Println("1")
        fmt.Println("2")
    } else {
        fmt.Println(":(")
    }
}
1
2
3
4
5
6
7
a, b = io.read("*n", "*n")
if (a <= 2) and (2 <= b) then
    print(1)
    print(2)
else
    print(":(")
end
1
2
3
4
5
6
a, b = int(input()), int(input())
if 2 in range(a, b + 1):
    print(1)
    print(2)
else:
    print(":(")

🟢 Parent Gap

Solution in Python
from datetime import datetime

year = int(input())

mother = datetime(year, 5, 1).isoweekday()
father = datetime(year, 6, 1).isoweekday()

x = 7 - mother
y = 7 - father
daymother = 1 + x + 7
dayfather = 1 + y + 14

daymother = datetime(year, 5, daymother)
dayfather = datetime(year, 6, dayfather)

print(((dayfather - daymother).days) // 7, "weeks")

🟢 Parket

Solution in Python
1
2
3
4
5
6
7
8
9
import math

r, b = [int(d) for d in input().split()]
w = math.floor((r + b) ** 0.5)
while w:
    if (r + b) / w == (r + 4) / 2 - w:
        print((r + 4) // 2 - w, w)
        break
    w -= 1

🟢 Parking

Solution in Python
a, b, c = [int(d) for d in input().split()]
t = [0] * 100
for _ in range(3):
    start, end = [int(d) - 1 for d in input().split()]
    for i in range(start, end):
        t[i] += 1

total = 0
mapping = {
    3: c,
    2: b,
    1: a,
}
for s in t:
    total += mapping.get(s, 0) * s
print(total)

🟢 Parking

Solution in Python
1
2
3
4
for _ in range(int(input())):
    _ = input()
    positions = [int(d) for d in input().split()]
    print(2 * (max(positions) - min(positions)))

🟡 Parsing Hex

Solution in Python
import re

h = []
while True:
    try:
        s = input()
        h.extend(re.findall(r"0[xX][0-9a-fA-F]+", s))
    except:
        break
for n in h:
    print(n, int(n, 0))

🟡 Pascal

Solution in Python
import math

n = int(input())

f = False
for i in range(2, math.ceil(math.sqrt(n)) + 1):
    if n % i == 0:
        f = True
        break
if f:
    print(n - n // i)
else:
    print(n - 1)

🟢 Patuljci

Solution in Python
d = [int(input()) for _ in range(9)]
diff = sum(d) - 100
end = False
for i in range(8):
    for j in range(i + 1, 9):
        if d[i] + d[j] == diff:
            end = True
            break
    if end:
        break
print("\n".join([str(d[k]) for k in range(9) if k not in [i, j]]))

🟢 Paul Eigon

Solutions in 2 languages
package main

import "fmt"

func main() {
    var n, p, q int
    fmt.Scan(&n)
    fmt.Scan(&p)
    fmt.Scan(&q)
    if ((p+q)/n)%2 == 0 {
        fmt.Println("paul")
    } else {
        fmt.Println("opponent")
    }
}
1
2
3
4
5
6
n, p, q = [int(d) for d in input().split()]

if ((p + q) // n) % 2 == 0:
    print("paul")
else:
    print("opponent")

🟢 Peach Powder Polygon

Solutions in 2 languages
1
2
3
4
5
if io.read("*n") % 4 > 0 then
    print("Yes")
else
    print("No")
end
n = int(input())
print("Yes" if n % 4 else "No")

🟡 Pea Soup and Pancakes

Solution in Python
found = False
for _ in range(int(input())):
    k = int(input())

    name = input()
    items = [input() for _ in range(k)]
    if "pea soup" in items and "pancakes" in items:
        found = True
        print(name)
        break

if not found:
    print("Anywhere is fine I guess")

🟢 Pencil Crayons

Solution in Python
1
2
3
4
5
n, k = [int(d) for d in input().split()]
t = 0
for _ in range(n):
    t += k - len(set(input().split()))
print(t)

🟢 Peningar

Solution in Python
1
2
3
4
5
6
import math

n, d = [int(d) for d in input().split()]
v = [int(d) for d in input().split()]
lcm = n * d // math.gcd(n, d)
print(sum(v[i % n] for i in range(0, lcm, d)))

🟢 Peragrams

Solution in Python
1
2
3
4
5
6
7
from collections import Counter

s = Counter(input())
v = [d for d in s.values() if d % 2]
v = sorted(v)[:-1]

print(len(v))

🟢 Perket

Solution in Python
from itertools import combinations

n = int(input())
l = [[int(d) for d in input().split()] for _ in range(n)]

c = []
for i in range(1, n + 1):
    c.extend(list(combinations(l, i)))

d = []
for i in c:
    s, b = 1, 0
    for x, y in i:
        s *= x
        b += y
    d.append(abs(s - b))

print(min(d))

🟢 Permuted Arithmetic Sequence

Solution in Python
def arithmetic(n):
    d = [n[i] - n[i + 1] for i in range(len(n) - 1)]
    return True if len(set(d)) == 1 else False


for _ in range(int(input())):
    s = input().split()
    n = [int(d) for d in s[1:]]
    if arithmetic(n):
        print("arithmetic")
    elif arithmetic(sorted(n)):
        print("permuted arithmetic")
    else:
        print("non-arithmetic")

🟢 Pervasive Heart Monitor

Solution in Python
while True:
    try:
        line = input().split()
    except:
        break

    name, rate = [], []
    for p in line:
        if p.isalpha():
            name.append(p)
        else:
            rate.append(float(p))
    name = " ".join(name)
    rate = sum(rate) / len(rate)
    print(f"{rate:.6f} {name}")

🟢 Pet

Solution in Python
1
2
3
4
5
6
7
8
winner, max_score = 0, 0
for i in range(5):
    score = sum([int(d) for d in input().split()])
    if score > max_score:
        max_score = score
        winner = i + 1

print(winner, max_score)

🟢 Piece of Cake!

Solutions in 2 languages
n, h, v = io.read("*n", "*n", "*n")
print(4 * math.max(h * v, (n - h) * (n - v), h * (n - v), v * (n - h)))
n, h, v = [int(d) for d in input().split()]
print(4 * max(h * v, (n - h) * (n - v), h * (n - v), v * (n - h)))

🟢 Pig Latin

Solution in Python
def translate(w):
    if w[0] in "aeiouy":
        return w + "yay"
    else:
        i = 1
        while i < len(w):
            if w[i] in "aeiouy":
                break
            i += 1
        return w[i:] + w[:i] + "ay"


while True:
    try:
        text = input()
        print(" ".join([translate(w) for w in text.split()]))
    except:
        break

🟡 A Vicious Pikeman (Easy)

Solution in Python
def f(n, time, l):
    total_time, penalty = 0, 0
    for i, t in enumerate(sorted(l)):
        if total_time + t > time:
            return i, penalty
        total_time += t
        penalty = (penalty + total_time) % 1_000_000_007
    return n, penalty


n, t = [int(d) for d in input().split()]
a, b, c, t0 = [int(d) for d in input().split()]
l = [t0]
for _ in range(n - 1):
    l.append(((a * l[-1] + b) % c) + 1)


n, penalty = f(n, t, l)
print(n, penalty)

🟢 Pinni Frændi

Solution in Python
n = int(input())
print(f"0.{'0'*(n-1)}1")

🟢 Pizza Crust

Solutions in 2 languages
r, c = io.read("*n", "*n")
print(string.format("%.6f", (r - c) ^ 2 / r ^ 2 * 100))
r, c = [int(d) for d in input().split()]
print(f"{(r-c)**2 / r**2 * 100:.6f}")

🟢 Pizzubestun

Solution in Python
1
2
3
4
5
6
n = int(input())
prices = [int(input().split()[-1]) for _ in range(n)]
if n % 2:
    prices.append(0)
prices = sorted(prices, reverse=True)
print(sum(prices[i] for i in range(0, len(prices), 2)))

🟢 Planetaris

Solution in Python
_, a = [int(d) for d in input().split()]
e = sorted([int(d) + 1 for d in input().split()])

t = 0
for s in e:
    if a >= s:
        t += 1
        a -= s
    else:
        break
print(t)

🟢 Planina

Solution in Python
1
2
3
4
5
6
7
8
9
def p(n):
    if n == 1:
        return 3
    else:
        return p(n - 1) * 2 - 1


n = int(input())
print(p(n) ** 2)

🟢 Planting Trees

Solution in Python
1
2
3
4
5
n = int(input())
t = [int(d) for d in input().split()]

days = [v + d for v, d in zip(sorted(t, reverse=True), range(1, n + 1))]
print(max(days) + 1)

🟢 Pokechat

Solution in Python
1
2
3
4
chars = input()
ids = input()
ids = [int(ids[i : i + 3]) - 1 for i in range(0, len(ids), 3)]
print("".join([chars[i] for i in ids]))

🟢 Poker Hand

Solution in Python
1
2
3
4
from collections import Counter

hands = [h[0] for h in input().split()]
print(max(Counter(hands).values()))

🟢 Polygon Area

Solution in Python
while True:
    n = int(input())
    if not n:
        break
    p = [[int(d) for d in input().split()] for _ in range(n)]
    a, b = 0, 0
    for i in range(n - 1):
        a += (p[i + 1][0] - p[i][0]) * (p[i + 1][1] + p[i][1])
        b += p[i][0] * p[i + 1][1] - p[i][1] * p[i + 1][0]

    a += (p[0][0] - p[-1][0]) * (p[0][1] + p[-1][1])
    b += p[-1][0] * p[0][1] - p[-1][1] * p[0][0]

    print("CCW" if a < 0 else "CW", f"{abs(b/2):.1f}")

🟢 Polynomial Multiplication 1

Solution in Python
from collections import Counter

for _ in range(int(input())):
    n = int(input())
    a = [int(d) for d in input().split()]
    m = int(input())
    b = [int(d) for d in input().split()]
    p = Counter()
    for i in range(n + 1):
        for j in range(m + 1):
            p[i + j] += a[i] * b[j]
    keys = max([k for k in p.keys() if p[k] != 0])
    print(keys)
    print(" ".join([str(p[k]) for k in range(keys + 1)]))

🟢 Popularity Contest

Solution in Python
1
2
3
4
5
6
7
n, m = [int(d) for d in input().split()]
p = [0] * n
for _ in range(m):
    a, b = [int(d) - 1 for d in input().split()]
    p[a] += 1
    p[b] += 1
print(" ".join([str(a - b) for a, b in zip(p, range(1, 1 + n))]))

🟢 Pot

Solution in Python
1
2
3
4
5
6
7
n = int(input())
total = 0
for _ in range(n):
    line = input()
    n, p = int(line[:-1]), int(line[-1])
    total += n**p
print(total)

🟢 Saving Princess Peach

Solution in Python
1
2
3
4
5
6
7
8
9
n, y = [int(d) for d in input().split()]
found = []
for _ in range(y):
    found.append(int(input()))
found = set(found)
for i in range(n):
    if i not in found:
        print(i)
print(f"Mario got {len(found)} of the dangerous obstacles.")

🟢 Printing Costs

Solution in Python
t = """
    0        !   9        "   6        #  24        $  29        %  22
&  24        '   3        (  12        )  12        *  17        +  13
,   7        -   7        .   4        /  10        0  22        1  19
2  22        3  23        4  21        5  27        6  26        7  16
8  23        9  26        :   8        ;  11        <  10        =  14
>  10        ?  15        @  32        A  24        B  29        C  20
D  26        E  26        F  20        G  25        H  25        I  18
J  18        K  21        L  16        M  28        N  25        O  26
P  23        Q  31        R  28        S  25        T  16        U  23
V  19        W  26        X  18        Y  14        Z  22        [  18
\  10        ]  18        ^   7        _   8        `   3        a  23
b  25        c  17        d  25        e  23        f  18        g  30
h  21        i  15        j  20        k  21        l  16        m  22
n  18        o  20        p  25        q  25        r  13        s  21
t  17        u  17        v  13        w  19        x  13        y  24
z  19        {  18        |  12        }  18        ~   9
"""

m = []
for row in t.splitlines():
    if not row:
        continue
    values = row.split()
    if len(values) % 2:
        values.insert(0, " ")

    for i in range(0, len(values), 2):
        m.append((values[i], int(values[i + 1])))
m = dict(m)

while True:
    try:
        s = input()
    except:
        break
    print(sum([m[c] for c in s]))

🟢 Prjónamynstur

Solution in Python
mapping = {
    ".": 20,
    "O": 10,
    "\\": 25,
    "/": 25,
    "A": 35,
    "^": 5,
    "v": 22,
}
n, _ = input().split()
cost = 0
for _ in range(int(n)):
    for c in input():
        cost += mapping[c]
print(cost)

🟢 Provinces and Gold

Solution in Python
g, s, c = [int(d) for d in input().split()]

buying = 3 * g + 2 * s + 1 * c
result = []

if buying >= 8:
    result.append("Province")
elif buying >= 5:
    result.append("Duchy")
elif buying >= 2:
    result.append("Estate")

if buying >= 6:
    result.append("Gold")
elif buying >= 3:
    result.append("Silver")
else:
    result.append("Copper")

print(" or ".join(result))

🟢 Prsteni

Solution in Python
import math

_ = input()
numbers = [int(d) for d in input().split()]

base = numbers.pop(0)

gcd = [math.gcd(base, n) for n in numbers]

for g, n in zip(gcd, numbers):
    print(f"{int(base/g)}/{int(n/g)}")

🟢 Prva

Solution in Python
r, c = [int(d) for d in input().split()]
puzzle = []
for _ in range(r):
    puzzle.append(input())

words = set()
for row in puzzle:
    words.update([w for w in row.split("#") if len(w) > 1])
for i in range(c):
    col = "".join([row[i] for row in puzzle])
    words.update([w for w in col.split("#") if len(w) > 1])

print(sorted(words)[0])

🟢 Ptice

Solution in Python
def adrian(n):
    if n == 0:
        return ""
    elif n == 1:
        return "A"
    elif n == 2:
        return "AB"
    elif n == 3:
        return "ABC"
    else:
        duplicate = n // 3
        return adrian(3) * duplicate + adrian(n % 3)


def bruno(n):
    if n == 0:
        return ""
    elif n == 1:
        return "B"
    elif n == 2:
        return "BA"
    elif n == 3:
        return "BAB"
    elif n == 4:
        return "BABC"
    else:
        duplicate = n // 4
        return bruno(4) * duplicate + bruno(n % 4)


def goran(n):
    if n == 0:
        return ""
    elif n in [1, 2]:
        return "C" * n
    elif n in [3, 4]:
        return "CC" + "A" * (n - 2)
    elif n in [5, 6]:
        return "CCAA" + "B" * (n - 4)
    else:
        duplicate = n // 6
        return goran(6) * duplicate + goran(n % 6)


def get_score(ans, guess):
    return sum([a == g for a, g in zip(ans, guess)])


n = int(input())
ans = input()

result = {}
result["Adrian"] = get_score(ans, adrian(n))
result["Bruno"] = get_score(ans, bruno(n))
result["Goran"] = get_score(ans, goran(n))

best = max(result.values())
print(best)

for name, score in result.items():
    if score == best:
        print(name)

🟢 Pub Crawl

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())
m = {}
for _ in range(n):
    name, k, t = input().split()
    m[name] = (int(k) + 1) * int(t)

ans = max(m, key=lambda k: m[k])
print(ans, m[ans])

🟢 Plants vs Bad Guys

Solutions in 2 languages
1
2
3
4
5
6
7
n = io.read("*n")
local min = math.huge
for i = 1, n do
    value = io.read("*n")
    min   = min < value and min or value
end
print(1 + min)
_ = input()
print(1 + min(int(d) for d in input().split()))

🟢 Building Pyramids

Solution in Python
n = int(input())

height = 0
while True:
    height += 1
    blocks = (2 * height - 1) ** 2
    if blocks > n:
        height -= 1
        break
    n -= blocks

print(height)

🟢 Quality-Adjusted Life-Year

Solution in Python
1
2
3
4
5
6
qaly = 0
for _ in range(int(input())):
    q, y = input().split()
    q, y = float(q), float(y)
    qaly += q * y
print(qaly)

🟢 Quadrant Selection

Solutions in 4 languages
package main

import "fmt"

func main() {
    var x, y int
    fmt.Scan(&x)
    fmt.Scan(&y)
    if x > 0 {
        if y > 0 {
            fmt.Println(1)
        } else {
            fmt.Println(4)
        }
    } else {
        if y > 0 {
            fmt.Println(2)
        } else {
            fmt.Println(3)
        }
    }
}
import java.util.Scanner;

class QuadrantSelection {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int x = s.nextInt();
        int y = s.nextInt();

        if (x > 0) {
            if (y > 0) {
                System.out.println(1);
            } else {
                System.out.println(4);
            }
        } else {
            if (y > 0) {
                System.out.println(2);
            } else {
                System.out.println(3);
            }
        }

    }
}
x = int(input())
y = int(input())
if x > 0:
    if y > 0:
        print(1)
    else:
        print(4)
else:
    if y > 0:
        print(2)
    else:
        print(3)
fn main() {
    let mut line1 = String::new();
    std::io::stdin().read_line(&mut line1).unwrap();
    let x: i32 = line1.trim().parse().unwrap();

    let mut line2 = String::new();
    std::io::stdin().read_line(&mut line2).unwrap();
    let y: i32 = line2.trim().parse().unwrap();

    if x > 0 {
        if y > 0 {
            println!("1");
        } else {
            println!("4");
        }
    } else {
        if y > 0 {
            println!("2");
        } else {
            println!("3");
        }
    }
}

🟢 Quick Brown Fox

Solution in Python
import string

for _ in range(int(input())):
    p = set([c for c in input().lower() if c.isalpha()])
    if len(p) == 26:
        print("pangram")
    else:
        print(
            f"missing {''.join([c for c in string.ascii_lowercase[:26] if c not in p])}"
        )

🟢 Quick Estimates

Solutions in 2 languages
import java.util.Scanner;

class QuickEstimates {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for (int i = 0; i < n; i++) {
            String cost = s.next();
            System.out.println(cost.length());
        }
    }
}
for _ in range(int(input())):
    print(len(input()))

🟢 Quite a Problem

Solution in Python
while True:
    try:
        line = input()
    except:
        break

    if "problem" in line.lower():
        print("yes")
    else:
        print("no")

🟢 R2

Solutions in 5 languages
#include <iostream>

using namespace std;

int main()
{
    int r1, s;
    cin >> r1 >> s;
    cout << 2 * s - r1 << endl;
    return 0;
}
package main

import "fmt"

func main() {
    var r1, s int
    fmt.Scan(&r1)
    fmt.Scan(&s)
    fmt.Println(2*s - r1)
}
import java.util.Scanner;

class R2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int r1 = scanner.nextInt();
        int s = scanner.nextInt();
        System.out.println(2 * s - r1);
    }
}
1
2
3
4
r1 = io.read("*n")
s = io.read("*n")
r2 = 2 * s - r1
print(r2)
1
2
3
r1, s = [int(d) for d in input().split()]
r2 = 2 * s - r1
print(r2)

🟢 Racing Around the Alphabet

Solution in Python
import math

tokens = dict([(chr(c), c - ord("A") + 1) for c in range(ord("A"), ord("Z") + 1)])
tokens[" "] = 27
tokens["'"] = 28
t = math.pi * 60 / (28 * 15)
for _ in range(int(input())):
    m = input()
    total = 1
    prev = m[0]
    for c in m[1:]:
        dist = abs(tokens[prev] - tokens[c])
        total += 1 + t * min(dist, 28 - dist)
        prev = c
    print(total)

🟢 Raðgreining 1

Solution in Python
n, m = [int(d) for d in input().split()]
ans = ["?"] * n
valid = True
for _ in range(m):
    s, k = input().split()
    s = int(s)
    for a, b in zip(ans[s - 1 : s - 1 + len(k)], list(k)):
        if a != "?" and a != b:
            valid = False
    ans[s - 1 : s - 1 + len(k)] = list(k)
print("".join(ans) if valid else "Villa")

🟢 Ragged Right

Solution in Python
1
2
3
4
5
6
7
8
9
l = []
while True:
    try:
        s = input()
    except:
        break
    l.append(len(s))
m = max(l)
print(sum([(n - m) ** 2 for n in l[:-1]]))

🟢 Railroad

Solutions in 4 languages
package main

import "fmt"

func main() {
    var x, y int
    fmt.Scan(&x)
    fmt.Scan(&y)
    if y%2 == 1 {
        fmt.Println("impossible")
    } else {
        fmt.Println("possible")
    }
}
import java.util.Scanner;

class Railroad {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int x = s.nextInt();
        int y = s.nextInt();
        if (y % 2 == 1) {
            System.out.println("impossible");
        } else {
            System.out.println("possible");
        }
    }
}
1
2
3
4
5
6
7
x = io.read("*n")
y = io.read("*n")
if y % 2 == 1 then
    print("impossible")
else
    print("possible")
end
1
2
3
4
5
_, y = [int(d) for d in input().split()]
if y % 2:
    print("impossible")
else:
    print("possible")

🟡 A Rank Problem

Solution in Python
1
2
3
4
5
6
7
8
9
n, m = [int(d) for d in input().split()]
ranking = [f"T{i}" for i in range(1, 1 + n)]
for _ in range(m):
    i, j = input().split()
    if ranking.index(i) < ranking.index(j):
        continue
    ranking.remove(j)
    ranking.insert(ranking.index(i) + 1, j)
print(" ".join(ranking))

🟢 Rating Problems

Solutions in 2 languages
import java.util.Scanner;

class RatingProblems {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int k = s.nextInt();
        int score = 0;
        for (int i = 0; i < k; i++) {
            score += s.nextInt();
        }
        float min = (score - 3 * (n - k)) / (float) n;
        float max = (score + 3 * (n - k)) / (float) n;
        System.out.println(min + " " + max);
    }
}
1
2
3
4
5
6
n, k = [int(d) for d in input().split()]
score = 0
for _ in range(k):
    score += int(input())

print((score - 3 * (n - k)) / n, (score + 3 * (n - k)) / n)

🟢 A Rational Sequence 2

Solution in Python
def f(l, r):
    if l == r:
        return 1
    elif l > r:
        return 2 * f(l - r, r) + 1
    else:
        return 2 * f(l, r - l)


for _ in range(int(input())):
    k, v = input().split()
    l, r = [int(d) for d in v.split("/")]
    print(f"{k} {f(l,r)}")

🟢 Scaling Recipes

Solution in Python
for i in range(int(input())):
    r, p, d = [int(d) for d in input().split()]
    recipe = {}
    main = None
    for _ in range(r):
        name, weight, percent = input().split()
        weight = float(weight)
        percent = float(percent)
        if percent == 100.0:
            main = name
        recipe[name] = (weight, percent)
    scale = d / p
    print(f"Recipe # {i+1}")
    dw = recipe[main][0] * scale
    for k in recipe:
        print(k, f"{recipe[k][1] * dw / 100:.1f}")
    print("-" * 40)

🟢 Recount

Solution in Python
from collections import Counter

c = Counter()
while True:
    try:
        name = input()
    except:
        break
    c[name] += 1

highest = max(c.values())
names = [k for k in c if c[k] == highest]
print("Runoff!" if len(names) > 1 else names.pop())

🟢 Rectangle Area

Solution in Python
1
2
3
x1, y1, x2, y2 = [float(d) for d in input().split()]

print(abs((x1 - x2) * (y1 - y2)))

🟢 Reduced ID Numbers

Solution in Python
g = int(input())
ids = []
for _ in range(g):
    ids.append(int(input()))

m = 1
while True:
    v = [d % m for d in ids]
    if g == len(set(v)):
        break
    m += 1

print(m)

🟢 Reduplication

Solution in Python
1
2
3
s = input()
n = int(input())
print(s * n)

🟢 Relocation

Solution in Python
1
2
3
4
5
6
7
8
n, q = [int(d) for d in input().split()]
x = [int(d) for d in input().split()]
for _ in range(q):
    req = [int(d) for d in input().split()]
    if req[0] == 1:
        x[req[1] - 1] = req[2]
    elif req[0] == 2:
        print(abs(x[req[1] - 1] - x[req[2] - 1]))

🟢 Restaurant Opening

Solution in Python
from itertools import product

n, m = [int(d) for d in input().split()]

g = []
for _ in range(n):
    g.append([int(d) for d in input().split()])

l = list(product(range(n), range(m)))

c = []
for i, j in l:
    s = 0
    for a, b in l:
        s += g[a][b] * (abs(i - a) + abs(j - b))
    c.append(s)

print(min(c))

🟢 Reversed Binary Numbers

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())

b = []
while n:
    b.append(n % 2)
    n //= 2

print(sum([d * (2**p) for d, p in zip(b, reversed(range(len(b))))]))

🟢 Reverse Rot

Solution in Python
import string

rotations = string.ascii_uppercase + "_."


def rotate(c, n):
    index = (rotations.index(c) + n) % 28
    return rotations[index]


while True:
    line = input()
    if line == "0":
        break
    n, m = line.split()
    n = int(n)
    print("".join([rotate(c, n) for c in m[::-1]]))

🟢 Riječi

Solutions in 4 languages
package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
    a := 1
    b := 0
    for i := 0; i < n; i++ {
        a, b = b, b+a
    }
    fmt.Println(a, b)
}
import java.util.Scanner;

class Rijeci {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int k = s.nextInt();
        int a = 1;
        int b = 0;
        for (int i = 0; i < k; i++) {
            int t = b;
            b = a + b;
            a = t;

        }

        System.out.println(a + " " + b);
    }
}
1
2
3
4
5
6
k = io.read("*n")
local a, b = 1, 0
for i = 1, k do
    a, b = b, b + a
end
print(a, b)
1
2
3
4
5
6
k = int(input())
a, b = 1, 0
for _ in range(k):
    a, b = b, b + a

print(a, b)

🟢 Roaming Romans

Solutions in 3 languages
1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
    var x float64
    fmt.Scan(&x)
    fmt.Println(int(x*1000*5280/4854 + 0.5))
}
x = io.read("*n")
print(math.floor(x * 1000 * 5280 / 4854 + .5))
x = float(input())
print(int(x * 1000 * 5280 / 4854 + 0.5))

🟢 Run-Length Encoding, Run!

Solution in Python
action, s = input().split()
if action == "D":
    print("".join([s[i] * int(s[i + 1]) for i in range(0, len(s), 2)]))
elif action == "E":
    parts = []
    prev, t = s[0], 1
    for c in s[1:]:
        if c != prev:
            parts.append((prev, t))
            t = 1
            prev = c
        else:
            t += 1
    parts.append((prev, t))

    print("".join([f"{k}{v}" for k, v in parts]))

🟢 Same Digits (Easy)

Solution in Python
a, b = [int(d) for d in input().split()]
pairs = []
for x in range(a, b + 1):
    for y in range(x, b + 1):
        xy = x * y
        if sorted(str(xy)) == sorted(str(x) + str(y)):
            pairs.append((x, y, xy))
print(f"{len(pairs)} digit-preserving pair(s)")
for x, y, xy in pairs:
    print(f"x = {x}, y = {y}, xy = {xy}")

🟢 Same Digits (Hard)

Solution in Python
a, b = [int(d) for d in input().split()]
pairs = []
for x in range(a, b + 1):
    for y in range(x, b + 1):
        xy = x * y
        if x * y > b:
            break
        if sorted(str(xy)) == sorted(str(x) + str(y)):
            pairs.append((x, y, xy))
    if x * x > b:
        break

print(f"{len(pairs)} digit-preserving pair(s)")
for x, y, xy in pairs:
    print(f"x = {x}, y = {y}, xy = {xy}")

🟢 Sanic

Solutions in 2 languages
print(io.read("*n") - 1)
print(float(input()) - 1)

🟢 Saving Daylight

Solution in Python
while True:
    try:
        s = input().split()
    except:
        break

    t1, t2 = s[-2:]

    h1, m1 = [int(d) for d in t1.split(":")]
    h2, m2 = [int(d) for d in t2.split(":")]

    mins = (h2 - h1) * 60 + (m2 - m1)
    h = mins // 60
    m = mins % 60

    ans = s[:-2]
    ans.extend([str(h), "hours", str(m), "minutes"])

    print(" ".join(ans))

🟢 Saving For Retirement

Solution in Python
1
2
3
4
5
6
7
8
import math

B, Br, Bs, A, As = [int(d) for d in input().split()]
rate = Bs * (Br - B) / As
Ar = math.ceil(rate) + A
if rate.is_integer():
    Ar += 1
print(Ar)

🟢 Scaling Recipe

Solution in Python
import math

n, x, y = [int(d) for d in input().split()]
i = [int(input()) for _ in range(n)]

# for python 3.9+ (https://docs.python.org/3.9/library/math.html#math.gcd)
# s = math.gcd(x, *i)

s = math.gcd(x, i[0])
for k in range(1, n):
    s = math.gcd(s, i[k])

x /= s
i = [v / s for v in i]

scale = y / x
for v in i:
    print(int(scale * v))

🟢 School Spirit

Solution in Python
n = int(input())
s = []
for _ in range(n):
    s.append(int(input()))


def group_score(s):
    gs = 0
    for i in range(len(s)):
        gs += s[i] * (0.8**i)
    return 0.2 * gs


print(group_score(s))
new_gs = []
for i in range(n):
    new_gs.append(group_score([s[j] for j in range(n) if j != i]))
print(sum(new_gs) / len(new_gs))

🟢 Secret Message

Solution in Python
import math

for _ in range(int(input())):
    m = input()
    k = math.ceil(len(m) ** 0.5)

    m += "*" * (k * k - len(m))
    rows = [m[i : i + k] for i in range(0, len(m), k)]

    s = []
    for i in range(k):
        s.append("".join([row[i] for row in rows if row[i] != "*"][::-1]))
    print("".join(s))

🟢 Secure Doors

Solution in Python
1
2
3
4
5
6
7
8
9
pool = set()
for _ in range(int(input())):
    action, name = input().split()
    if action == "entry":
        print(name, "entered", "(ANOMALY)" if name in pool else "")
        pool.add(name)
    elif action == "exit":
        print(name, "exited", "(ANOMALY)" if name not in pool else "")
        pool.discard(name)

🟢 Server

Solution in Python
1
2
3
4
5
6
7
8
9
_, t = [int(d) for d in input().split()]
total, used = 0, 0
for v in [int(d) for d in input().split()]:
    if used + v <= t:
        total += 1
        used += v
    else:
        break
print(total)

🟢 Seven Wonders

Solution in Python
1
2
3
4
5
6
7
8
9
from collections import Counter

c = Counter(input())
score = 0
for value in c.values():
    score += value**2
if len(c.values()) == 3:
    score += 7 * min(c.values())
print(score)

🟢 Shandy

Solutions in 2 languages
b, l = io.read("*n", "*n")
print(math.min(b, l) * 2)
1
2
3
b = int(input())
l = int(input())
print(min(b, l) * 2)

🟢 Shattered Cake

Solution in Python
1
2
3
4
5
6
w, n = int(input()), int(input())
total = 0
for _ in range(n):
    _w, _l = [int(d) for d in input().split()]
    total += _w * _l
print(int(total / w))

🟢 Shopaholic

Solution in Python
1
2
3
4
5
6
7
n = int(input())
c = [int(d) for d in input().split()]

c = sorted(c, reverse=True)
groups = [c[i : i + 3] if i + 3 < n else c[i:] for i in range(0, n, 3)]

print(sum(g[-1] if len(g) == 3 else 0 for g in groups))

🟢 Shopping List (Easy)

Solution in Python
n, m = [int(d) for d in input().split()]
items = []
for _ in range(n):
    items.append(set(input().split()))

ans = items[0]
ans = ans.intersection(*items[1:])

print(len(ans))
print("\n".join(sorted(list(ans))))

🟢 Sibice

Solution in Python
1
2
3
4
5
6
7
8
9
import math

n, w, h = [int(d) for d in input().split()]
for _ in range(n):
    line = int(input())
    if line <= math.sqrt(w**2 + h**2):
        print("DA")
    else:
        print("NE")

🟢 Sideways Sorting

Solution in Python
while True:
    r, c = [int(d) for d in input().split()]
    if not r and not c:
        break
    s = []
    for _ in range(r):
        s.append(input())
    items = []
    for i in range(c):
        items.append("".join(s[j][i] for j in range(r)))
    items = sorted(items, key=lambda t: t.lower())
    for i in range(r):
        print("".join(items[j][i] for j in range(c)))

🟢 Digit Product

Solution in Python
def digit_product(x):
    ans = 1
    while x:
        ans *= x % 10 or 1
        x //= 10
    return ans


x = int(input())
while True:
    x = digit_product(x)
    if x < 10:
        break
print(x)

🟢 Simon Says

Solution in Python
1
2
3
4
5
6
7
for _ in range(int(input())):
    command = input()
    start = "simon says "
    if command.startswith(start):
        print(command[len(start) :])
    else:
        print()

🟢 Simone

Solution in Python
from collections import Counter

n, k = [int(d) for d in input().split()]

s = Counter(int(d) for d in input().split())

least = min(s.values())
if len(s.values()) < k:
    least = 0
ans = 0
c = []
for i in range(k):
    if s[i + 1] == least:
        c.append(str(i + 1))
        ans += 1
print(ans)
print(" ".join(c))

🟢 Simon Says

Solution in Python
1
2
3
4
5
for _ in range(int(input())):
    command = input()
    start = "Simon says "
    if command.startswith(start):
        print(command[len(start) :])

🟢 Simple Addition

Solution in Python
a, b = input(), input()

a = a[::-1]
b = b[::-1]
i = 0
ans = ""
carry = 0
while i < len(a) or i < len(b):
    if i < len(a) and i < len(b):
        s = int(a[i]) + int(b[i]) + carry

    elif i < len(a):
        s = int(a[i]) + carry

    else:
        s = int(b[i]) + carry
    ans += str(s % 10)
    carry = s // 10
    i += 1
if carry:
    ans += str(carry)
print(ans[::-1])

# or simply
# print(int(a) + int(b))

🟢 Simple Factoring

Solution in Python
1
2
3
4
5
6
7
8
for _ in range(int(input())):
    a, b, c = [int(d) for d in input().split()]
    import math

    if not b**2 - 4 * a * c < 0 and math.sqrt(b**2 - 4 * a * c).is_integer():
        print("YES")
    else:
        print("NO")

🟡 Simplicity

Solution in Python
1
2
3
from collections import Counter

print(sum([v for _, v in Counter(input()).most_common()[2:]]))

🟢 Sith

Solution in Python
_ = input()
a = int(input())
b = int(input())
diff = int(input())
if diff <= 0:
    print("JEDI")
elif a < b:
    print("SITH")
else:
    print("VEIT EKKI")

🟢 Sjecista

Solution in Python
n = int(input())
print((n - 3) * (n - 2) * (n - 1) * (n) // 24)

🟢 Skammstöfun

Solution in Python
1
2
3
_ = input()
words = input().split()
print("".join([w[0] for w in words if w[0].isupper()]))

🟢 Skener

Solution in Python
r, _, zr, zc = [int(d) for d in input().split()]
matrix = []
for _ in range(r):
    matrix.append(input())

ans = []

for row in matrix:
    for i in range(zr):
        ans.append(row)

for row in ans:
    print("".join([col * zc for col in row]))

🟢 Skocimis

Solutions in 3 languages
package main

import "fmt"

func main() {
    var a, b, c int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Scan(&c)
    x := b - a
    y := c - b
    ans := x
    if ans < y {
        ans = y
    }
    ans -= 1
    fmt.Println(ans)
}
a, b, c = io.read("*n", "*n", "*n")
print(math.max(b - a, c - b) - 1)
a, b, c = [int(d) for d in input().split()]
print(max(b - a, c - b) - 1)

🟢 Skotleikur

Solution in Python
k = int(input())
a = int(input())
b = int(input())
ans = []
for i in range(0, k // a + 1):
    if (k - a * i) % b == 0:
        ans.append((i, (k - a * i) // b))
print(len(ans))
for i, j in ans:
    print(i, j)

🟢 Turn It Up!

Solution in Python
1
2
3
4
5
6
7
volume = 7
for _ in range(int(input())):
    if input() == "Skru op!":
        volume = min(volume + 1, 10)
    else:
        volume = max(volume - 1, 0)
print(volume)

🟢 Slatkisi

Solution in Python
1
2
3
4
c, k = [int(d) for d in input().split()]
d = 10**k
c = (c // d) * d + (d if (c % d) / d >= 0.5 else 0)
print(c)

🟢 SMIL

Solutions in 2 languages
import java.util.Scanner;

class SMIL {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String m = s.nextLine();
        int size = m.length();
        int i = 0;
        while (i < size) {
            if (m.charAt(i) == ':' || m.charAt(i) == ';') {
                if (i + 1 < size && m.charAt(i + 1) == ')') {
                    System.out.println(i);
                    i += 2;
                    continue;
                }
                if (i + 2 < size && m.charAt(i + 1) == '-' && m.charAt(i + 2) == ')') {
                    System.out.println(i);
                    i += 3;
                    continue;
                }
            }
            i += 1;
        }
    }
}
s = input()

i = 0
size = len(s)
while i < size:
    if s[i] in [":", ";"]:
        if i + 1 < size and s[i + 1] == ")":
            print(i)
            i += 2
            continue
        if i + 2 < size and s[i + 1] == "-" and s[i + 2] == ")":
            print(i)
            i += 3
            continue

    i += 1

🟡 Snapper Chain (Easy)

Solution in Python
1
2
3
4
5
6
7
8
9
t = int(input())
for i in range(t):
    n, k = [int(d) for d in input().split()]
    on = True
    for _ in range(n):
        if not k % 2:
            on = False
        k //= 2
    print(f'Case #{i+1}: {"ON" if on else "OFF"}')

🟢 Snapper Chain (Hard)

Solution in Python
1
2
3
4
5
6
7
8
9
t = int(input())
for i in range(t):
    n, k = [int(d) for d in input().split()]
    on = True
    for _ in range(n):
        if not k % 2:
            on = False
        k //= 2
    print(f'Case #{i+1}: {"ON" if on else "OFF"}')

🟢 Soda Slurper

Solutions in 2 languages
package main

import "fmt"

func main() {
    var e, f, c int
    fmt.Scan(&e)
    fmt.Scan(&f)
    fmt.Scan(&c)
    total := 0
    s := e + f
    for s >= c {
        total += s / c
        s = s%c + s/c
    }
    fmt.Println(total)
}
1
2
3
4
5
6
7
e, f, c = [int(d) for d in input().split()]
total = 0
s = e + f
while s >= c:
    total += s // c
    s = s % c + s // c
print(total)

🟢 Sok

Solution in Python
1
2
3
4
a, b, c = [int(d) for d in input().split()]
i, j, k = [int(d) for d in input().split()]
s = min(a / i, b / j, c / k)
print(a - i * s, b - j * s, c - k * s)

🟢 Some Sum

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
if n == 1:
    print("Either")
elif n == 2:
    print("Odd")
elif n % 2 == 0:
    print("Even" if (n / 2) % 2 == 0 else "Odd")
else:
    print("Either")

🟡 Sort

Solution in Python
from collections import Counter

n, c = [int(d) for d in input().split()]
num = [int(d) for d in input().split()]

freq = Counter(num)
print(
    " ".join(
        [
            str(d)
            for d in sorted(
                num, key=lambda k: (freq[k], n - num.index(k)), reverse=True
            )
        ]
    )
)

🟢 Sort of Sorting

Solution in Python
first = True
while True:
    n = int(input())
    if not n:
        break
    else:
        if not first:
            print()
    first = False
    names = []
    for _ in range(n):
        names.append(input())
    print("\n".join(sorted(names, key=lambda k: k[:2])))

🟢 Sort Two Numbers

Solutions in 4 languages
#include <iostream>

using namespace std;

int main()
{
    int a = 0, b = 0;
    cin >> a >> b;
    if (a < b)
    {
        cout << a << " " << b;
    }
    else
    {
        cout << b << " " << a;
    }
}
package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a)
    fmt.Scan(&b)
    if a < b {
        fmt.Printf("%d %d\n", a, b)
    } else {
        fmt.Printf("%d %d\n", b, a)
    }
}
1
2
3
4
5
6
a, b = io.read("*n", "*n")
if a < b then
    print(a, b)
else
    print(b, a)
end
1
2
3
4
5
6
line = input()
a, b = [int(d) for d in line.split()]
if a < b:
    print(a, b)
else:
    print(b, a)

🟢 Sóttkví

Solutions in 2 languages
import java.util.Scanner;

class Sottkvi {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int k = s.nextInt();
        int today = s.nextInt();
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int d = s.nextInt();
            if (d + 14 - today <= k) {
                ans += 1;
            }
        }
        System.out.println(ans);

    }
}
1
2
3
4
5
6
7
n, k, today = [int(d) for d in input().split()]
res = 0
for _ in range(n):
    d = int(input())
    if d + 14 - today <= k:
        res += 1
print(res)

🟢 Soundex

Solution in Python
m = {
    "B": 1,
    "F": 1,
    "P": 1,
    "V": 1,
    "C": 2,
    "G": 2,
    "J": 2,
    "K": 2,
    "Q": 2,
    "S": 2,
    "X": 2,
    "Z": 2,
    "D": 3,
    "T": 3,
    "L": 4,
    "M": 5,
    "N": 5,
    "R": 6,
}

while True:
    try:
        s = input()
        s = [str(m.get(c, "")) for c in s]
        prev = s[0]
        ans = [prev]
        for c in s[1:]:
            if c != prev:
                ans.append(c)
                prev = c
        print("".join(ans))
    except:
        break

🟢 Soylent

Solution in Python
1
2
3
4
5
import math

for _ in range(int(input())):
    n = int(input())
    print(math.ceil(n / 400))

🟢 Space Race

Solution in Python
1
2
3
4
5
6
7
8
n = int(input())
_ = input()
d = {}
for _ in range(n):
    entry = input().split()
    d[entry[0]] = float(entry[-1])

print(min(d, key=lambda k: d[k]))

🟢 Spavanac

Solutions in 3 languages
#include <iostream>

using namespace std;

int main()
{
    int h, m;
    cin >> h >> m;

    int mm = m - 45;
    int borrow = 0;
    if (mm < 0)
    {
        mm += 60;
        borrow = 1;
    }
    int hh = h - borrow;
    if (hh < 0)
    {
        hh += 24;
    }
    cout << hh << " " << mm << endl;
    return 0;
}
import java.util.Scanner;

class Spavanac {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int h = s.nextInt();
        int m = s.nextInt();

        int mm = m - 45;
        int borrow = 0;
        if (mm < 0) {
            mm += 60;
            borrow = 1;
        }

        int hh = h - borrow;
        if (hh < 0) {
            hh += 24;
        }
        System.out.println(hh + " " + mm);
    }
}
h, m = [int(d) for d in input().split()]

mm = m - 45

borrow = 0
if mm < 0:
    mm += 60
    borrow = 1

hh = h - borrow
if hh < 0:
    hh += 24

print(hh, mm)

🟢 Speeding

Solution in Python
n = int(input())
mile, time, max_speed = 0, 0, 0
for _ in range(n):
    t, s = [int(d) for d in input().split()]
    if not t and not s:
        continue
    speed = int((s - mile) / (t - time))
    if speed > max_speed:
        max_speed = speed
    mile, time = s, t
print(max_speed)

🟢 Speed Limit

Solution in Python
while True:
    n = int(input())
    if n == -1:
        break
    miles = 0
    elapsed = 0
    for _ in range(n):
        s, t = [int(d) for d in input().split()]
        miles += s * (t - elapsed)
        elapsed = t
    print(f"{miles} miles")

🟢 Spelling Bee

Solution in Python
hexagon = input()
c = hexagon[0]
hexagon = set(list(hexagon))
n = int(input())
valid = []
for _ in range(n):
    w = input()
    if c in w and len(w) >= 4 and set(list(w)) <= hexagon:
        valid.append(w)
print("\n".join(valid))

🟢 Spritt

Solution in Python
1
2
3
4
5
6
7
8
n, x = [int(d) for d in input().split()]
for _ in range(n):
    x -= int(input())
    if x < 0:
        print("Neibb")
        break
if x >= 0:
    print("Jebb")

🟢 Square Peg

Solution in Python
1
2
3
4
5
l, r = [int(d) for d in input().split()]
if 2 * (l / 2) ** 2 <= r**2:
    print("fits")
else:
    print("nope")

🟢 Illuminated City

Solution in Python
n = int(input())
x = int(input())
y = int(input())
l = sorted([int(d) for d in input().split()])

total, c = 0, 0
for d in l:
    if (total + d * x) / (c + 1) <= y:
        total += d * x
        c += 1
    else:
        break
print(c)

🟢 Stafur

Solution in Python
1
2
3
4
5
6
7
l = input()
if l in "AEIOU":
    print("Jebb")
elif l == "Y":
    print("Kannski")
else:
    print("Neibb")

🟢 Statistics

Solution in Python
1
2
3
4
5
6
7
8
9
case_num = 0
while True:
    try:
        line = input()
    except:
        break
    case_num += 1
    numbers = [int(d) for d in line.split()[1:]]
    print(f"Case {case_num}: {min(numbers)} {max(numbers)} {max(numbers)-min(numbers)}")

🟢 Sticky Keys

Solution in Python
1
2
3
4
5
6
7
message = input()

l = [message[0]]
for i in message[1:]:
    if i != l[-1]:
        l.append(i)
print("".join(l))

🟢 Messy lists

Solution in Python
1
2
3
4
n = int(input())
a = [int(d) for d in input().split()]
s = sorted(a)
print(sum([i != j for i, j in zip(a, s)]))

🟢 Stopwatch

Solution in Python
n = int(input())
times = []
for _ in range(n):
    times.append(int(input()))
if n % 2:
    print("still running")
else:
    seconds = 0
    for i in range(0, n, 2):
        seconds += times[i + 1] - times[i]
    print(seconds)

🟢 Stórafmæli

Solutions in 2 languages
1
2
3
4
5
6
n = io.read("*n")
if n % 10 == 0 then
    print('Jebb')
else
    print('Neibb')
end
n = int(input())
print("Jebb" if n % 10 == 0 else "Neibb")

🟢 Streets Ahead

Solution in Python
1
2
3
4
5
6
7
8
9
n, q = [int(d) for d in input().split()]

s = {}
for i in range(n):
    s[input()] = i

for _ in range(q):
    a, b = input().split()
    print(abs(s[a] - s[b]) - 1)

🟢 Successful Zoom

Solution in Python
n = int(input())
x = [int(d) for d in input().split()]
found = False
for k in range(1, n // 2 + 1):
    v = [x[i] for i in range(k - 1, n, k)]
    if all([v[i] < v[i + 1] for i in range(len(v) - 1)]):
        print(k)
        found = True
        break
if not found:
    print("ABORT!")

🟢 Sum Kind of Problem

Solution in Python
1
2
3
4
5
6
for _ in range(int(input())):
    k, n = [int(d) for d in input().split()]
    s1 = sum(range(1, n + 1))
    s2 = sum(range(1, 2 * n + 1, 2))
    s3 = sum(range(2, 2 * (n + 1), 2))
    print(k, s1, s2, s3)

🟢 Sum of the Others

Solution in Python
while True:
    try:
        n = [int(d) for d in input().split()]
    except:
        break

    for i in range(len(n)):
        if n[i] == sum([n[j] for j in range(len(n)) if j != i]):
            print(n[i])
            break

🟢 Sum Squared Digits Function

Solution in Python
1
2
3
4
5
6
7
for _ in range(int(input())):
    k, b, n = [int(d) for d in input().split()]
    ssd = 0
    while n:
        ssd += (n % b) ** 2
        n //= b
    print(k, ssd)

🟢 Sun and Moon

Solutions in 2 languages
1
2
3
4
5
6
7
8
ds, dy, dm, ym = io.read("*n", "*n", "*n", "*n")

for t = 1, 5000 do
    if (t + ds) % dy == 0 and (t + dm) % ym == 0 then
        print(t)
        break
    end
end
1
2
3
4
5
6
7
sun_years_ago, sun_cycle = [int(v) for v in input().split()]
moon_years_ago, moon_cycle = [int(v) for v in input().split()]

for t in range(1, 5001):
    if (t + sun_years_ago) % sun_cycle == 0 and (t + moon_years_ago) % moon_cycle == 0:
        print(t)
        break

🟢 Symmetric Order

Solution in Python
set_num = 0
while True:
    size = int(input())
    if size == 0:
        break

    names = []
    for _ in range(size):
        names.append(input())

    set_num += 1
    print(f"SET {set_num}")

    top, bottom = [], []
    for i in range(1, size, 2):
        bottom.append(names[i])
    for i in range(0, size, 2):
        top.append(names[i])
    names = top + bottom[::-1]
    for name in names:
        print(name)

🟢 Synchronizing Lists

Solution in Python
while True:
    n = int(input())
    if not n:
        break
    a, b = [], []
    for _ in range(n):
        a.append(int(input()))
    for _ in range(n):
        b.append(int(input()))
    mapping = dict(zip(sorted(a), sorted(b)))
    for key in a:
        print(mapping[key])
    print()

🟢 T9 Spelling

Solution in Python
n = int(input())
mapping = {
    "2": "abc",
    "3": "def",
    "4": "ghi",
    "5": "jkl",
    "6": "mno",
    "7": "pqrs",
    "8": "tuv",
    "9": "wxyz",
    "0": " ",
}

for i in range(n):
    ans = []
    prev = ""
    for c in input():
        for d, r in mapping.items():
            if c in r:
                if d == prev:
                    ans.append(" ")
                ans.append(d * (r.index(c) + 1))
                prev = d
                break
    print(f"Case #{i+1}: {''.join(ans)}")

🟢 Tai's formula

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
t1, v1 = [float(d) for d in input().split()]
total = 0
for _ in range(n - 1):
    t2, v2 = [float(d) for d in input().split()]
    total += (v1 + v2) * (t2 - t1) / 2
    t1, v1 = t2, v2
total /= 1000
print(total)

🟢 Tajna

Solution in Python
s = input()

l = len(s)
r = int(l**0.5)
while l % r:
    r -= 1
c = l // r

parts = [s[i : i + r] for i in range(0, l, r)]

print("".join(["".join([row[i] for row in parts]) for i in range(r)]))

🟢 Takk fyrir mig

Solution in Python
1
2
3
n = int(input())
for _ in range(n):
    print(f"Takk {input()}")

🟢 Tarifa

Solutions in 2 languages
1
2
3
4
5
6
7
x = io.read("*n")
n = io.read("*n")
local used = 0
for i = 1, n do
    used = used + io.read("*n")
end
print(x * (n + 1) - used)
1
2
3
4
5
6
x = int(input())
n = int(input())
used = 0
for _ in range(n):
    used += int(input())
print(x * (n + 1) - used)

🟢 Time Travelling Temperatures

Solution in Python
1
2
3
4
5
x, y = [int(d) for d in input().split()]
if y == 1:
    print("ALL GOOD" if not x else "IMPOSSIBLE")
else:
    print(-x / (y - 1))

🟡 Temperature Confusion

Solution in Python
1
2
3
4
5
6
7
8
9
import math

a, b = [int(d) for d in input().split("/")]
x, y = 5 * a - 160 * b, 9 * b
gcd = math.gcd(x, y)
x //= gcd
y //= gcd

print(f"{x}/{y}")

🟢 Test Drive

Solution in Python
a, b, c = [int(d) for d in input().split()]
x, y = b - a, c - b
if x == y:
    print("cruised")
elif x * y < 0:
    print("turned")
elif abs(y) > abs(x):
    print("accelerated")
else:
    print("braked")

🟢 Tetration

Solution in Python
1
2
3
4
import math

n = float(input())
print(f"{math.pow(n,1/n):.6f}")

🟢 Thanos

Solutions in 2 languages
1
2
3
4
5
6
7
8
9
for _ = 1, io.read("*n") do
    p, r, f = io.read("*n", "*n", "*n")
    y = 0
    while p <= f do
        p = p * r
        y = y + 1
    end
    print(y)
end
1
2
3
4
5
6
7
for _ in range(int(input())):
    p, r, f = [int(d) for d in input().split()]
    y = 0
    while p <= f:
        p *= r
        y += 1
    print(y)

🟢 The Grand Adventure

Solution in Python
mapping = {"b": "$", "t": "|", "j": "*"}
for _ in range(int(input())):
    a = input()
    bag = []
    early_fail = False
    for i in a:
        if i in mapping.values():
            bag.append(i)
        elif i in mapping:
            if not bag or bag.pop() != mapping[i]:
                print("NO")
                early_fail = True
                break
    if not early_fail:
        print("YES" if not bag else "NO")

🟢 The Last Problem

Solutions in 3 languages
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    s := scanner.Text()
    fmt.Println("Thank you,", s+",", "and farewell!")
}
print(string.format("Thank you, %s, and farewell!", io.read()))
print(f"Thank you, {input()}, and farewell!")

🟢 The Plank

Solutions in 4 languages
#include <iostream>

using namespace std;

int f(int n)
{
    if (n == 0)
    {
        return 1;
    }
    else if (n == 1)
    {
        return 1;
    }
    else if (n == 2)
    {
        return 2;
    }
    else
    {
        return f(n - 1) + f(n - 2) + f(n - 3);
    }
}

int main()
{
    int n;
    cin >> n;
    cout << f(n) << endl;
    return 0;
}
package main

import "fmt"

func f(n int) int {
    if n == 0 {
        return 1
    } else if n == 1 {
        return 1
    } else if n == 2 {
        return 2
    } else {
        return f(n-1) + f(n-2) + f(n-3)
    }

}

func main() {
    var n int
    fmt.Scan(&n)
    fmt.Println(f(n))
}
function f(n)
  if n == 0 then
    return 1
  elseif n == 1 then
    return 1
  elseif n == 2 then
    return 2
  else
    return f(n - 1) + f(n - 2) + f(n - 3)
  end
end

n = io.read("*n")
print(f(n))
1
2
3
4
5
6
7
8
def f(n):
    if n < 3:
        return {0: 1, 1: 1, 2: 2}[n]
    else:
        return f(n - 1) + f(n - 2) + f(n - 3)


print(f(int(input())))

🟢 This Ain't Your Grandpa's Checkerboard

Solution in Python
n = int(input())
b = []
for _ in range(n):
    b.append(input())


def check(b, n):
    for row in b:
        if row.count("W") != row.count("B"):
            return False

        for j in range(0, n - 3):
            if row[j] == row[j + 1] == row[j + 2]:
                return False

    for i in range(n):
        col = ["".join(row[i]) for row in b]

        if col.count("W") != col.count("B"):
            return False

        for j in range(0, n - 3):
            if col[j] == col[j + 1] == col[j + 2]:
                return False

    return True


valid = check(b, n)
print(1 if valid else 0)

🟢 Til hamingju

Solutions in 5 languages
console.log("TIL HAMINGJU MED AFMAELID FORRITUNARKEPPNI FRAMHALDSSKOLANNA!");
1
2
3
fun main() {
    println("TIL HAMINGJU MED AFMAELID FORRITUNARKEPPNI FRAMHALDSSKOLANNA!")
}
print("TIL HAMINGJU MED AFMAELID FORRITUNARKEPPNI FRAMHALDSSKOLANNA!")
print("TIL HAMINGJU MED AFMAELID FORRITUNARKEPPNI FRAMHALDSSKOLANNA!")
puts "TIL HAMINGJU MED AFMAELID FORRITUNARKEPPNI FRAMHALDSSKOLANNA!"

🟢 Stuck In A Time Loop

Solutions in 3 languages
#include <iostream>

using namespace std;

int main()
{
    int a;
    cin >> a;
    for (int i = 0; i < a; i++)
    {
        cout << i + 1 << " Abracadabra" << endl;
    }
}
1
2
3
for i = 1, io.read("*n") do
    print(string.format("%d Abracadabra", i))
end
1
2
3
n = int(input())
for i in range(n):
    print(f"{i+1} Abracadabra")

🟢 Title Cost

Solution in Python
1
2
3
s, c = input().split()
c = float(c)
print(min(c, len(s)))

🟢 Töflur

Solution in Python
1
2
3
4
n = int(input())
a = sorted([int(d) for d in input().split()])
score = sum([(a[j] - a[j + 1]) ** 2 for j in range(n - 1)])
print(score)

🟢 Toilet Seat

Solution in Python
t = input()


def u(pos, preference):
    if pos == preference == "U":
        return 0
    elif pos == preference == "D":
        return 1
    elif pos == "U" and preference == "D":
        return 2
    else:
        return 1


def l(pos, preference):
    if pos == preference == "U":
        return 1
    elif pos == preference == "D":
        return 0
    elif pos == "U" and preference == "D":
        return 1
    else:
        return 2


def b(pos, preference):
    if pos == preference:
        return 0
    else:
        return 1


pu = [u(pos, preference) for pos, preference in zip(t[0] + "U" * (len(t) - 2), t[1:])]
pl = [l(pos, preference) for pos, preference in zip(t[0] + "D" * (len(t) - 2), t[1:])]
pb = [b(pos, preference) for pos, preference in zip(t[0] + t[1:-1], t[1:])]

print(sum(pu))
print(sum(pl))
print(sum(pb))

🟢 Tok Tik

Solution in Python
n = int(input())
d = {}
for _ in range(n):
    s, v = input().split()
    v = int(v)
    if s not in d:
        d[s] = v
    else:
        d[s] += v
print(max(d, key=lambda k: d[k]))

🟢 ToLower

Solution in Python
p, t = [int(d) for d in input().split()]
score = 0
for _ in range(p):
    solved = True
    for _ in range(t):
        s = input()
        if solved:
            s = s[0].lower() + s[1:]
            if s.lower() == s:
                continue
        solved = False
    if solved:
        score += 1
print(score)

🟢 Tölvunarfræðingar telja

Solutions in 5 languages
#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;
    cout << n - 1 << endl;
    return 0;
}
1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
    fmt.Println(n-1)
}
1
2
3
fun main() {
    println(readLine()!!.toInt() - 1)
}
n = io.read("*n")
print(n - 1)
print(int(input()) - 1)

🟢 Tower Construction

Solutions in 2 languages
n = io.read("*n")
t = 0
top = 0
for _ = 1, n do
    d = io.read("*n")
    if top == 0 or d > top then
        t = t + 1
    end
    top = d
end
print(t)
1
2
3
4
5
6
7
8
9
_ = input()
n = 0
top = 0
for d in [int(d) for d in input().split()]:
    if not top or d > top:
        n += 1
    top = d

print(n)

🟢 Touchscreen Keyboard

Solution in Python
k = [
    "qwertyuiop",
    "asdfghjkl",
    "zxcvbnm",
]


def d(a, b):
    for r1 in range(3):
        if a in k[r1]:
            c1 = k[r1].index(a)
            break
    for r2 in range(3):
        if b in k[r2]:
            c2 = k[r2].index(b)
            break

    return abs(c1 - c2) + abs(r1 - r2)


for _ in range(int(input())):
    x, n = input().split()
    n, w = int(n), []

    for _ in range(n):
        y = input()
        dist = sum([d(a, b) for a, b in zip(list(x), list(y))])
        w.append([y, dist])

    print("\n".join([f"{k} {v}" for k, v in sorted(w, key=lambda k: (k[1], k[0]))]))

🟢 Tracking Shares

Solution in Python
c = int(input())
shares = {}
days = set()
for i in range(c):
    k = int(input())
    record = {}
    for _ in range(k):
        n, d = [int(d) for d in input().split()]
        days.add(d)
        record[d] = n
    shares[i] = record

days = sorted(list(days))
ans = [0] * c
for i in range(len(days)):
    d = days[i]
    a = list(shares[j].get(d, ans[j]) for j in shares)
    ans = a
    print(sum(a), end=" ")

🟢 Training

Solutions in 2 languages
1
2
3
4
5
6
7
8
n, s = io.read("*n", "*n")
for _ = 1, n do
    a, b = io.read("*n", "*n")
    if s >= a and s <= b then
        s = s + 1
    end
end
print(s)
1
2
3
4
5
6
n, s = [int(d) for d in input().split()]
for _ in range(n):
    a, b = [int(d) for d in input().split()]
    if s >= a and s <= b:
        s += 1
print(s)

🟢 Tram

Solutions in 2 languages
1
2
3
4
5
6
7
n = io.read("*n")
d = 0
for i = 1, n do
    x, y = io.read("*n", "*n")
    d = d + 2 * (x - y)
end
print(-d / (2 * n))
1
2
3
4
5
6
n = int(input())
d = 0
for _ in range(n):
    x, y = [int(i) for i in input().split()]
    d += 2 * (x - y)
print(-d / (2 * n))

🟢 Transit Woes

Solution in Python
s, t, n = [int(d) for d in input().split()]
ds = [int(d) for d in input().split()]
bs = [int(d) for d in input().split()]
cs = [int(d) for d in input().split()]

for i in range(n):
    s += ds[i]
    if not s % cs[i]:
        wait_b = 0
    else:
        wait_b = cs[i] - s % cs[i]
    s += wait_b + bs[i]

s += ds[n]

if s <= t:
    print("yes")
else:
    print("no")

🟢 Trapizza

Solutions in 2 languages
d, a, b, h = io.read("*n", "*n", "*n", "*n")
m = math.pi * d * d / 4
t = (a + b) * h / 2
if m == t then
    print('Jafn storar!')
elseif m > t then
    print('Mahjong!')
else
    print('Trapizza!')
end
from math import pi

d = int(input())
a = int(input())
b = int(input())
h = int(input())
m = pi * d * d / 4
t = (a + b) * h / 2
if m == t:
    print("Jafn storar!")
elif m > t:
    print("Mahjong!")
else:
    print("Trapizza!")

🟢 Three in a Row

Solution in Python
1
2
3
4
5
6
7
8
9
import math

n = int(input())

t = 0
for i in range(1, math.ceil(n ** (1 / 3))):
    if i * (i + 1) * (i + 2) < n:
        t += 1
print(t)

🟢 Tri

Solution in Python
from operator import add, mul, sub, truediv

a, b, c = [int(d) for d in input().split()]
ops = {
    "+": add,
    "-": sub,
    "*": mul,
    "/": truediv,
}

for op, func in ops.items():
    if a == func(b, c):
        print(f"{a}={b}{op}{c}")
        break
    if func(a, b) == c:
        print(f"{a}{op}{b}={c}")

🟢 Triangle Area

Solutions in 5 languages
#include <iostream>

using namespace std;

int main()
{
    int h, b;
    cin >> h >> b;
    cout << float(h) * b / 2 << endl;
    return 0;
}
package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Println(float32(a) * float32(b) / 2)
}
import java.util.Scanner;

class TriangleArea {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        float a = s.nextFloat();
        int b = s.nextInt();
        System.out.println(a * b / 2);
    }
}
a, b = io.read("*n", "*n")
print(a * b / 2)
a, b = [int(d) for d in input().split()]
print(a * b / 2)

🟢 Trik

Solution in Python
moves = input()
ball = [1, 0, 0]
for move in moves:
    if move == "A":
        ball[0], ball[1] = ball[1], ball[0]
    if move == "B":
        ball[1], ball[2] = ball[2], ball[1]
    if move == "C":
        ball[0], ball[2] = ball[2], ball[0]

if ball[0]:
    print(1)
elif ball[1]:
    print(2)
else:
    print(3)

🟢 Triple Sevens

Solution in Python
_ = input()
print(777 if all("7" in input().split() for _ in range(3)) else 0)

🟢 Triple Texting

Solution in Python
from collections import Counter

s = input()
times = 3
size = len(s) // times
messages = []
for i in range(0, len(s), size):
    messages.append(s[i : i + size])

original = ""
for i in range(size):
    chars = [m[i] for m in messages]
    if len(set(chars)) == 1:
        original += chars[0]
    else:
        c = Counter(chars)
        original += max(c, key=lambda k: c[k])

print(original)

🟢 Troll Hunt

Solutions in 2 languages
1
2
3
4
5
6
7
b, k, g = io.read("*n", "*n", "*n")
b = b - 1
d = b // (k // g)
if b % (k // g) > 0 then
    d = d + 1
end
print(d)
1
2
3
4
5
6
b, k, g = [int(d) for d in input().split()]
b -= 1
d = b // (k // g)
if b % (k // g):
    d += 1
print(d)

🟢 Take Two Stones

Solutions in 7 languages
package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
    if n%2 == 1 {
        fmt.Println("Alice")
    } else {
        fmt.Println("Bob")
    }
}
1
2
3
4
5
6
main = do
    input <- getLine
    let n = (read input :: Int)
    if  n `mod` 2  ==  1
    then putStrLn "Alice"
        else putStrLn "Bob"
import java.util.Scanner;

class TakeTwoStones {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        if (n % 2 == 1) {
            System.out.println("Alice");
        } else {
            System.out.println("Bob");
        }
    }
}
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (n) => {
  if (parseInt(n) % 2) {
    console.log("Alice");
  } else {
    console.log("Bob");
  }
});
1
2
3
4
5
6
7
fun main() {
    if (readLine()!!.toInt() % 2 == 1) {
        println("Alice")
    } else {
        println("Bob")
    }
}
1
2
3
4
5
if io.read("*n") % 2 > 0 then
    print("Alice")
else
    print("Bob")
end
1
2
3
4
if int(input()) % 2:
    print("Alice")
else:
    print("Bob")

🟢 Two-sum

Solutions in 5 languages
#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    cout << a + b << endl;
    return 0;
}
package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Println(a + b)
}
import java.util.Scanner;

class TwoSum {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        int b = s.nextInt();
        System.out.println(a + b);
    }
}
a, b = io.read("*n", "*n")
print(a + b)
1
2
3
line = input()
a, b = [int(d) for d in line.split()]
print(a + b)

🟢 Úllen dúllen doff

Solution in Python
1
2
3
4
5
6
7
n = int(input())
names = input().split()
if n < 13:
    i = 13 % n - 1
else:
    i = 12
print(names[i])

🟢 Úllen Dúllen Doff 2

Solution in Python
1
2
3
4
5
n = int(input())
names = [input() for _ in range(n)]
s = 12 if n >= 13 else 13 % n - 1
names[0], names[s] = names[s], names[0]
print("\n".join(names))

🟢 Ultimate Binary Watch

Solution in Python
1
2
3
4
5
6
7
t = [int(d) for d in input()]
b = [f"{d:b}".zfill(4) for d in t]

for r in range(4):
    row = ["." if b[i][r] == "0" else "*" for i in range(4)]
    row.insert(2, " ")
    print(" ".join(row))

🟢 Umferð

Solution in Python
1
2
3
4
5
6
m = int(input())
n = int(input())
cars = 0
for _ in range(n):
    cars += input().count(".")
print(cars / (m * n))

🟢 Undead or Alive

Solution in Python
s = input()

smiley = ":)" in s

frowny = ":(" in s

if not frowny and smiley:
    print("alive")

elif frowny and not smiley:
    print("undead")

elif frowny and smiley:
    print("double agent")

else:
    print("machine")

🟢 Unlock Pattern

Solution in Python
import math


def dist(a, b):
    return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)


coords = {}
for i in range(3):
    n = [int(d) for d in input().split()]
    for j in range(3):
        coords[n[j]] = (i, j)

values = [coords[k] for k in sorted(coords)]
total, prev = 0, 0
for i in range(1, 9):
    total += dist(values[i], values[prev])
    prev = i
print(total)

🟢 Arrangement

Solution in Python
import math

n, m = int(input()), int(input())

k = math.ceil(m / n)

for _ in range(n - (n * k - m)):
    print("*" * k)
for _ in range(n * k - m):
    print("*" * (k - 1))

🟢 UTF-8

Solution in Python
n = int(input())
s = []
for _ in range(n):
    s.append(input())

i = 0
num = 0
err = False
t = [0] * 4
while i < n:
    a = s[i]
    if a.startswith("0") and not num:
        num = 0
        t[0] += 1
    elif a.startswith("110") and not num:
        t[1] += 1
        num = 1
    elif a.startswith("1110") and not num:
        t[2] += 1
        num = 2
    elif a.startswith("11110") and not num:
        t[3] += 1
        num = 3
    elif a.startswith("10") and num:
        num -= 1
    else:
        err = True
        break
    i += 1

if err or num:
    print("invalid")
else:
    print("\n".join([str(d) for d in t]))

🟡 Vaccine Efficacy

Solution in Python
participants = int(input())

vaccinated = 0
control = 0
infected_control_a = 0
infected_vaccinated_a = 0
infected_control_b = 0
infected_vaccinated_b = 0
infected_control_c = 0
infected_vaccinated_c = 0

for p in range(participants):
    record = input()
    v, a, b, c = list(record)

    if v == "N":
        control += 1
    else:
        vaccinated += 1

    if a == "Y":
        if v == "N":
            infected_control_a += 1
        else:
            infected_vaccinated_a += 1

    if b == "Y":
        if v == "N":
            infected_control_b += 1
        else:
            infected_vaccinated_b += 1

    if c == "Y":
        if v == "N":
            infected_control_c += 1
        else:
            infected_vaccinated_c += 1


def get_vaccine_efficacy(infected_vaccinated, vaccinated, infected_control, control):
    infection_rate_vaccinated = infected_vaccinated / vaccinated
    infection_rate_control = infected_control / control
    return 1 - infection_rate_vaccinated / infection_rate_control


vaccine_efficacy = [
    get_vaccine_efficacy(
        infected_vaccinated_a,
        vaccinated,
        infected_control_a,
        control,
    ),
    get_vaccine_efficacy(
        infected_vaccinated_b,
        vaccinated,
        infected_control_b,
        control,
    ),
    get_vaccine_efficacy(
        infected_vaccinated_c,
        vaccinated,
        infected_control_c,
        control,
    ),
]

for value in vaccine_efficacy:
    if value <= 0:
        print("Not Effective")
    else:
        print(f"{value*100:.6f}")

🟢 Right-of-Way

Solution in Python
d = ["North", "East", "South", "West"]
a, b, c = input().split()
ia = d.index(a)
ib = d.index(b)
ic = d.index(c)

ib = (ib - ia) % 4
ic = (ic - ia) % 4
ia -= ia

if ib == 2:
    print("Yes" if ic == 3 else "No")
elif ib == 1:
    print("Yes" if ic in [2, 3] else "No")
else:
    print("No")

🟢 Variable Arithmetic

Solution in Python
context = {}
while True:
    s = input()
    if s == "0":
        break

    if "=" in s:
        x, y = [d.strip() for d in s.split("=")]
        context[x] = int(y)
    else:
        v = [d.strip() for d in s.split("+")]
        t = 0
        n = []
        for d in v:
            if d.isdigit():
                t += int(d)
            elif d in context:
                t += context[d]
            else:
                n.append(d)
        if len(n) < len(v):
            n = [str(t)] + n
        print(" + ".join(n))

🟢 Veci

Solution in Python
from itertools import permutations

x = input()

values = sorted(set([int("".join(v)) for v in permutations(x, len(x))]))

index = values.index(int(x))
if index + 1 < len(values):
    print(values[index + 1])
else:
    print(0)

🟡 Vector Functions

Solution in C++
#include "vectorfunctions.h"
#include <algorithm>

void backwards(std::vector<int> &vec)
{
    vec = std::vector<int>(vec.rbegin(), vec.rend());
}

std::vector<int> everyOther(const std::vector<int> &vec)
{
    std::vector<int> ans;

    for (int i = 0; i < vec.size(); i += 2)
        ans.push_back(vec[i]);

    return ans;
}

int smallest(const std::vector<int> &vec)
{
    return *min_element(vec.begin(), vec.end());
}

int sum(const std::vector<int> &vec)
{
    int ans = 0;

    for (auto it = begin(vec); it != end(vec); ++it)
    {
        ans += *it;
    }

    return ans;
}

int veryOdd(const std::vector<int> &suchVector)
{
    int ans = 0;
    for (int i = 1; i < suchVector.size(); i += 2)
    {
        if (suchVector[i] % 2 == 1)
            ans++;
    }

    return ans;
}

🟢 Veður - Lokaðar heiðar

Solution in Python
1
2
3
4
5
6
7
v = int(input())
for _ in range(int(input())):
    s, k = input().split()
    if int(k) >= v:
        print(s, "opin")
    else:
        print(s, "lokud")

🟢 Veður - Vindhraði

Solution in Python
k = float(input())
if k < 0.3:
    print("logn")
elif k < 1.6:
    print("Andvari")
elif k < 3.4:
    print("Kul")
elif k < 5.5:
    print("Gola")
elif k < 8.0:
    print("Stinningsgola")
elif k < 10.8:
    print("Kaldi")
elif k < 13.9:
    print("Stinningskaldi")
elif k < 17.2:
    print("Allhvass vindur")
elif k < 20.8:
    print("Hvassvidri")
elif k < 24.5:
    print("Stormur")
elif k < 28.5:
    print("Rok")

elif k < 32.7:
    print("Ofsavedur")
else:
    print("Farvidri")

🟢 Vefþjónatjón

Solution in Python
1
2
3
4
5
6
7
n = int(input())
parts = [0, 0, 0]
for _ in range(n):
    for i, value in enumerate(input().split()):
        if value == "J":
            parts[i] += 1
print(min(parts))

🟢 Velkomin!

Solutions in 6 languages
1
2
3
4
5
class Velkomin {
    public static void main(String[] args) {
        System.out.println("VELKOMIN!");
    }
}
console.log("VELKOMIN!");
1
2
3
fun main() {
    println("VELKOMIN!")
}
print("VELKOMIN!")
print("VELKOMIN!")
puts "VELKOMIN!"

🟢 Who wins?

Solution in Python
board = []
for _ in range(3):
    board.append(input().split())

winner = ""
for i in range(3):
    if board[i][0] == board[i][1] == board[i][2] and board[i][0] != "_":
        winner = board[i][0]
        break
    elif board[0][i] == board[1][i] == board[2][i] and board[0][i] != "_":
        winner = board[0][i]
        break

if board[0][0] == board[1][1] == board[2][2] and board[1][1] != "_":
    winner = board[1][1]
elif board[0][2] == board[1][1] == board[2][0] and board[1][1] != "_":
    winner = board[1][1]

if not winner:
    winner = "ingen"
elif winner == "X":
    winner = "Johan"
else:
    winner = "Abdullah"

print(f"{winner} har vunnit")

🟢 Video Speedup

Solution in Python
n, p, k = [int(d) for d in input().split()]
i = [int(d) for d in input().split()]

start, total = 0, 0
speed = 1
for ti in i:
    total += speed * (ti - start)
    start = ti
    speed += p / 100
total += speed * (k - start)
print(f"{total:.3f}")

🟢 Viðsnúningur

Solutions in 3 languages
1
2
3
fun main() {
    println(StringBuilder(readLine()).reverse())
}
print(io.read():reverse())
print(input()[::-1])
Solution in Python
for _ in range(int(input())):
    n = int(input())
    votes = [int(input()) for _ in range(n)]
    largest = max(votes)
    if votes.count(largest) > 1:
        print("no winner")
    else:
        total = sum(votes)
        winner = votes.index(largest)
        print(
            "majority" if votes[winner] > total / 2 else "minority",
            "winner",
            winner + 1,
        )

🟢 Warehouse

Solution in Python
for _ in range(int(input())):
    n = int(input())
    warehouse = {}
    for _ in range(n):
        s = input().split()
        name, quantity = s[0], int(s[1])
        if name not in warehouse:
            warehouse[name] = quantity
        else:
            warehouse[name] += quantity
    print(len(warehouse))
    names = sorted(warehouse)
    for name in sorted(
        warehouse, key=lambda k: (warehouse[k], -names.index(k)), reverse=True
    ):
        print(name, warehouse[name])

🟢 Water Journal

Solution in Python
n, a, b = [int(d) for d in input().split()]
w = [int(input()) for _ in range(n - 1)]
if a in w and b in w:
    print("\n".join([str(d) for d in range(a, b + 1)]))
elif a in w and b not in w:
    print(b)
elif a not in w and b in w:
    print(a)
else:
    print(-1)

🟢 Weak Vertices

Solution in Python
from itertools import combinations

while True:
    n = int(input())
    if n == -1:
        break
    graph = {}
    for i in range(n):
        graph[str(i)] = [str(v) for v, e in zip(range(n), input().split()) if e == "1"]

    # listing the weak vertices ordered from least to greatest
    # I guess it means vertex number, not the weakness
    # keys = sorted(graph, key=lambda x: len(graph[x]), reverse=True)

    keys = graph.keys()

    result = []

    for key in keys:
        has_triangle = False
        for a, b in combinations(graph[key], 2):
            if a in graph[b] and b in graph[a]:
                has_triangle = True
                break

        if not has_triangle:
            result.append(key)

    print(" ".join(result))

🟡 WERTYU

Solution in Python
mapping = {
    # row 1
    "1": "`",
    "2": "1",
    "3": "2",
    "4": "3",
    "5": "4",
    "6": "5",
    "7": "6",
    "8": "7",
    "9": "8",
    "0": "9",
    "-": "0",
    "=": "-",
    # row 2
    "W": "Q",
    "E": "W",
    "R": "E",
    "T": "R",
    "Y": "T",
    "U": "Y",
    "I": "U",
    "O": "I",
    "P": "O",
    "[": "P",
    "]": "[",
    "\\": "]",
    # row 3
    "S": "A",
    "D": "S",
    "F": "D",
    "G": "F",
    "H": "G",
    "J": "H",
    "K": "J",
    "L": "K",
    ";": "L",
    "'": ";",
    # row 4
    "X": "Z",
    "C": "X",
    "V": "C",
    "B": "V",
    "N": "B",
    "M": "N",
    ",": "M",
    ".": ",",
    "/": ".",
    " ": " ",
}

while True:
    try:
        s = input()
    except:
        break
    print("".join([mapping[c] for c in s]))

🟢 What does the fox say?

Solution in Python
for _ in range(int(input())):
    words = input().split()
    others = set()
    while True:
        line = input()
        if line == "what does the fox say?":
            break
        w = line.split()[-1]
        others.add(w)
    print(" ".join(w for w in words if w not in others))

🟢 Which is Greater?

Solutions in 6 languages
#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    int ans = (a > b) ? 1 : 0;
    cout << ans << endl;
    return 0;
}
package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a)
    fmt.Scan(&b)
    if a > b {
        fmt.Println(1)
    } else {
        fmt.Println(0)
    }
}
import java.util.Scanner;

class WhichisGreater {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        int b = s.nextInt();
        if (a>b){
            System.out.println(1);
        }else{
            System.out.println(0);
        }
    }
}
const readline = require("readline");
const rl = readline.createInterface(process.stdin, process.stdout);

rl.question("", (line) => {
  [a, b] = line
    .trim()
    .split(" ")
    .map((e) => parseInt(e));
  if (a > b) {
    console.log(1);
  } else {
    console.log(0);
  }
});
1
2
3
4
5
6
a, b = io.read("*n", "*n")
if a > b then
    print(1)
else
    print(0)
end
1
2
3
4
5
a, b = [int(d) for d in input().split()]
if a > b:
    print(1)
else:
    print(0)

🟡 Wizard of Odds

Solutions in 2 languages
1
2
3
4
5
6
n, k = io.read("*n", "*n")
if math.log(n, 2) <= k then
    print("Your wish is granted!")
else
    print("You will become a flying monkey!")
end
1
2
3
4
5
6
7
8
import math

n, k = [int(d) for d in input().split()]
ans = math.log(n, 2) <= k
if ans:
    print("Your wish is granted!")
else:
    print("You will become a flying monkey!")

🟡 Words for Numbers

Solution in Python
mapping = {
    0: "zero",
    1: "one",
    2: "two",
    3: "three",
    4: "four",
    5: "five",
    6: "six",
    7: "seven",
    8: "eight",
    9: "nine",
    10: "ten",
    11: "eleven",
    12: "twelve",
}


def f(d):
    if d < 13:
        return mapping[d]

    ones = d % 10
    if d < 20:
        return {3: "thir", 5: "fif", 8: "eigh"}.get(ones, mapping[ones]) + "teen"

    tens = d // 10
    return (
        {2: "twen", 3: "thir", 4: "for", 5: "fif", 8: "eigh"}.get(tens, mapping[tens])
        + "ty"
        + ("-" + mapping[ones] if ones else "")
    )


def t(w):
    if w.isdigit():
        return f(int(w))
    else:
        return w


while True:
    try:
        words = input()
    except:
        break
    print(" ".join([t(w) for w in words.split()]))

🟢 Yin and Yang Stones

Solution in Python
s = input()
print(1 if s.count("W") == s.count("B") else 0)

🟢 Yoda

Solution in Python
a, b = input(), input()
size = max(len(a), len(b))

a = [int(d) for d in a.zfill(size)]
b = [int(d) for d in b.zfill(size)]

ans_a = [d1 for d1, d2 in zip(a, b) if d1 >= d2]
ans_b = [d2 for d1, d2 in zip(a, b) if d2 >= d1]


def f(ans):
    if not ans:
        return "YODA"
    else:
        return int("".join([str(d) for d in ans]))


print(f(ans_a))
print(f(ans_b))

🟢 Zamka

Solution in Python
l, d, x = input(), input(), input()
l, d, x = int(l), int(d), int(x)

for i in range(l, d + 1):
    if sum([int(d) for d in str(i)]) == x:
        print(i)
        break

for i in range(d, l - 1, -1):
    if sum([int(d) for d in str(i)]) == x:
        print(i)
        break

🟢 Stand on Zanzibar

Solutions in 2 languages
import java.util.Scanner;

class StandOnZanzibar {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        for (int i = 0; i < t; i++) {
            int total = 0;
            int n = 0;
            int init = 1;
            while (true) {
                n = s.nextInt();
                if (n == 0) {
                    break;
                }
                total += Math.max(n - 2 * init, 0);
                init = n;
            }
            System.out.println(total);
        }
    }
}
1
2
3
4
5
6
for _ in range(int(input())):
    numbers = [int(d) for d in input().split()[:-1]]
    total = 0
    for i in range(1, len(numbers)):
        total += max(numbers[i] - 2 * numbers[i - 1], 0)
    print(total)

🟢 Un-bear-able Zoo

Solution in Python
from collections import Counter

lc = 0
while True:
    n = int(input())
    if not n:
        break
    lc += 1
    l = Counter()
    for _ in range(n):
        animal = input().lower().split()
        l[animal[-1]] += 1
    print(f"List {lc}:")
    print("\n".join([f"{k} | {l[k]}" for k in sorted(l)]))

🟢 Zoom

Solution in Python
1
2
3
n, k = [int(d) for d in input().split()]
x = [int(d) for d in input().split()]
print(" ".join([str(x[i]) for i in range(k - 1, n, k)]))

🟢 Zyxab

Solution in Python
1
2
3
4
5
6
7
8
9
n = int(input())
names = [input() for _ in range(n)]
names = [n for n in names if len(set(n)) == len(n) and len(n) >= 5]
if names:
    least = min(len(n) for n in names)
    names = [n for n in names if len(n) == least]
    print(max(names))
else:
    print("Neibb")