W
W
wawa2018-07-13 13:11:29
Python
wawa, 2018-07-13 13:11:29

How does the magic work with SoftTimeLimitExceeded?

Celery has this trick:

from myapp import app
from celery.exceptions import SoftTimeLimitExceeded

@app.task
def mytask():
    try:
        do_work()
    except SoftTimeLimitExceeded:
        clean_up_in_a_hurry()

Here do_work() is my function and there is no SoftTimeLimitExceeded in it. How is this SoftTimeLimitExceeded "slipped" into the try block? How does this magic work?

Answer the question

In order to leave comments, you need to log in

8 answer(s)
S
Sergey Lerg, 2014-11-19
@Lerg

Here you are on Lua, only the answer is 1 all the time.
I think you can reproduce in the desired language.
repl.it/40O

V
Vitaly Pukhov, 2014-11-19
@Neuroware

Use the C# List collection and form a new collection instead of deleting the elements in the old one, then you can repeat everything with the new collection. It is advisable to use recursion, this will simplify the code.

J
jcmvbkbc, 2014-11-19
@jcmvbkbc

CAMOKPYT Sergey Lerg cool, such a simple condition, and still "when keeping the account in a circle" was not mastered.
Sit down, both of you.
And, yes, Albert , do your own homework, it's in your own interest.

R
Rsa97, 2014-11-19
@Rsa97

It is necessary to delete in a circle, that is, for {1, 2, 3, 4, 5}
Skip the first, delete the second - {1, 3, 4, 5}
Skip the next (3), delete (4) - {1, 3, 5}
Skip next (5), go to next circle, delete (1) - {3, 5}
Skip next (3), delete (5) - {3}

A
aush, 2014-11-19
@aush

With arbitrary step:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(GetLastStanding(11, 4));
    }

    static int GetLastStanding(int n, int step)
    {
        var items = Enumerable.Range(0, n)
                        .Select(position => new Item { Position = position }).ToArray();
        var i = 0;
        var stepCounter = 0;
        var nCounter = n;
        while (nCounter > 1)
        {
            if (!items[i].Marked && ++stepCounter == step)
            {
                stepCounter = 0;
                items[i].Marked = true;
                --nCounter;
                Console.WriteLine(string.Join(", ",
                    items.Select(item => item.Marked ?
                        "_" : (item.Position + 1).ToString())));
            }

            i = (i + 1) % n;
        }
        return items.Single(item => !item.Marked).Position;
    }

    struct Item
    {
        public int Position;
        public bool Marked;
    }
}

L
lam0x86, 2014-11-20
@lam0x86

Don't listen to them all =)
Surely, the teacher wants to see a solution with a closed linked list. Something like this:

class Program
    {
        static void Main()
        {
            var personList = GenerateList(15); // personList указывает на первого человека в списке

            PrintList(personList);

            var p = personList;
            while (p != p.NextPerson) // пока человек не остался один в списке
            {
                #region Этот кусок для корректного вывода списка на экран. Если вывод не нужен, можно убрать
                if (personList == p.NextPerson)
                {
                    personList = p.NextPerson.NextPerson;
                }
                #endregion

                // <ВсяСоль>
                p = p.NextPerson = p.NextPerson.NextPerson;
                // </ВсяСоль>

                // Если убрать верхний регион, то может возникнуть ситуация, когда personList указывает на 
                // человека, который был удалён из списка. Возникнет бесконечный цикл.
                PrintList(personList);
            }
        }

        // Вывод списка на консоль
        private static void PrintList(Person personList)
        {
            var p = personList;
            do
            {
                System.Console.Out.Write(p.SequenceNumber);
                System.Console.Out.Write(" ");
                p = p.NextPerson;
            } while (p != personList);
            System.Console.Out.WriteLine();
        }

        // Генерация списка
        private static Person GenerateList(int n)
        {
            // Начинаем с последнего человека
            var currentPerson = new Person(n);
            var lastPerson = currentPerson;

            // затем создаём N-1 человек, указывая его порядковый номер и следующего за ним человека
            for (int i = n - 1; i > 0; i--)
            {
                currentPerson = new Person(i) { NextPerson = currentPerson };
            }

            // последнего человека закольцовываем с первым
            lastPerson.NextPerson = currentPerson;
            return currentPerson;
        }
    }

    class Person
    {
        public Person(int sequenceNumber)
        {
            SequenceNumber = sequenceNumber;
        }

        public int SequenceNumber { get; private set; }

        public Person NextPerson { get; set; }
    }

D
Dmitry Makarov, 2014-11-27
@DmitryITWorksMakarov

Another option with a linked list

using System;
using System.Collections.Generic;
using System.Linq;

namespace throughOneKill
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = 10;

            var list = new LinkedList<int>(Enumerable.Range(1, N));
            Console.WriteLine(string.Join(" ", list));
            var currentItem = list.First;
            while (list.Count != 1)
            {
                list.Remove(currentItem.Next ?? list.First);
                currentItem = currentItem.Next ?? list.First;
            }
            Console.WriteLine(list.First.Value);

            Console.ReadKey();
        }
    }
}

M
Maxim Grekhov, 2014-11-27
@Sterk

here is the simplest solution

var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
PrintList(list);
bool delete = false;
while (list.Count > 1)
{
    for (int i = 0; i < list.Count; i++)
    {
        if (delete) list.RemoveAt(i--);
        delete = !delete;
    }
    PrintList(list);
}
Console.Read();

print function
static void PrintList(IEnumerable<int> list)
{
    foreach (var item in list)
        Console.Write("{0} ", item);
    Console.WriteLine();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question