Back to Timeline
Avatar
unidentified

Эта штука меня всё больше пугает

what language is this:

use std::io;
use std::io::BufRead;

fn add_to_top(v: &mut Vec<i32>, val:i32, max_len:usize) {
    let mut pos : usize = 0;
    while pos < v.len() {
        if v[pos] < val { break }
        pos+=1
    }
    if pos < max_len {
        v.insert(pos, val);
        if v.len() > max_len {
            v.truncate(max_len)
        }
    }
}

fn main() {
    let mut cur : i32 = 0;
    let mut top = Vec::<i32>::new();
    for line in io::stdin().lock().lines() {
        match line.unwrap().trim() {
            "" => {
                add_to_top(&mut top, cur, 3);
                cur = 0
            }
            l => {
                let v : i32 = l.parse().unwrap();
                cur += v
            }
        }
    }
    add_to_top(&mut top, cur, 3);

    println!("{}", top.iter().sum::<i32>())
}

This is Rust.

Translate this to Python:

def add_to_top(v, val, max_len):
    pos = 0
    while pos < len(v):
        if v[pos] < val:
            break
        pos += 1
    if pos < max_len:
        v.insert(pos, val)
        if len(v) > max_len:
            v = v[:max_len]

def main():
    cur = 0
    top = []
    for line in sys.stdin.readlines():
        line = line.strip()
        if line == '':
            add_to_top(top, cur, 3)
            cur = 0
        else:
            v = int(line)
            cur += v
    add_to_top(top, cur, 3)

    print(sum(top))

main()

What is this code doing?

This code is reading lines from standard input and adding the numerical
values from each line to a running total (cur). If an empty line is
encountered, the current total is added to a list of top values (top) and the
running total is reset. After all lines have been processed, the sum of
the top three values is printed.
Comments (1)

Ну а что такого-то? Вот дать ему код с багом и спросить, что он делает, или почему не работает.