RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

全部问题

Martin Hope
user602691
Asked: 2024-07-02 04:53:42 +0000 UTC

找到最大长度的子序列,其总和为负且奇数

  • 9

健康)状况:

令S为从1开始连续编号的N个整数的序列。令S(L,R)表示由S中包含的连续元素组成的子序列,从编号为L的元素开始到编号为R的元素结束。我们需要找到这样的元素L和R的数量值,其中0 < L< R ≤ N,使得子序列S(L, R)的元素之和为奇数且负数。

在您的答案中,指出该子序列的长度(即该子序列中包含的元素数量)。如果有多个这样的子序列,请指出它们的最大长度。

输入数据
给出两个输入文件(文件 A(约 1000 个数字)和文件 B(约 300,000 个数字)),每个文件的第一行都包含数字 N (3 < N < 10,000,000) - 整数的数量。接下来的M行每一行包含一个绝对值不超过1000的整数。

在您的答案中,指明两个数字:首先是文件 A 的所需值,然后是文件 B 的所需值。

在输入文件中组织数据的典型示例

8
-73
153
35
0
-44
78
-69
2

使用这样的输入数据,问题条件通过 0 + (-44) + 78 + (-69) 和 0 + (-44) + 78 + (-69) + 2 之和满足。问题的答案是5号。

该问题有 2 个文件:for 和 for 300,000 个数字。

我的决定:

对于第一个文件,O(N^2)搜索算法是合适的。它不适合第二个,所以我尝试创建另一个。

这个想法是创建一个包含从第一个元素到第 i 个元素的所有元素之和的数组,以及 2 个包含偶数和奇数值的先前和的数组,其中每个元素都大于前一个元素。然后检查第一个数组的元素与具有不同奇偶校验的另一个数组的元素之间的差异。如果此差值小于 0,则继续进行下一个金额。

问题是,在 30,000 个元素之后,速度大大减慢,并且第二个文件的执行需要几个小时。谁能提出更好的解决方案?

我的代码

f = open('file.txt')
n = int(f.readline())
a = [int(f.readline())]
sums = [a[0]]
for i in f:
    i = int(i)
    a.append(i)
    sums.append(sums[-1]+i)
mxs0 = [[], []]
mxs1 = [[], []]
k0 = []
k1 = []

for i in range(2,n):
    if sums[i-2] % 2 == 0:
        if len(k0) == 0:
            k0.append(i-2)
        elif k0[-1] < sums[i-2]:
            k0.append(i-2)
    if sums[i-2] % 2 == 1:
        if len(k1) == 0:
            k1.append(i-2)
        elif k1[-1] < sums[i-2]:
            k1.append(i-2)
    mxs0.append(k0)
    mxs1.append(k1)

lens = []
for i in range(2,n):
    print(i)
    if sums[i]%2==0:
        if len(mxs1[i]) > 0 > sums[i]-sums[mxs1[i][-1]]:
            for j in range(len(mxs1[i])):
                if sums[i]-sums[mxs1[i][j]] < 0:
                    lens.append(a[mxs1[i][j] + 1:i + 1])
                    break
    else:
        if sums[i] < 0:
            lens.append(a[0:i+1])
        else:
            if len(mxs0[i]) > 0 > sums[i]-sums[mxs0[i][-1]]:
                for j in range(len(mxs0[i])):
                    if sums[i]-sums[mxs0[i][j]] < 0:
                        lens.append(a[mxs0[i][j] + 1:i + 1])
                        break
cc = 0
lens = [i for i in lens if type(i) != int]
for i in range(len(lens)):
    cc = max(cc, len(lens[i]))
print(cc)
python
  • 1 个回答
  • 104 Views
Martin Hope
rew
Asked: 2024-06-19 02:36:45 +0000 UTC

java 中的 case success(var value) 语法

  • 9

我在代码中遇到了这样的构造

Integer a = switch (result) {
    case Success(var value) -> value;
    case Failure(Throwable e) -> Assertions.fail();
};

我不明白为什么你要把它推到构造函数中var value

case Success(var value)

我试着用谷歌搜索一下switch,但没有看到任何类似的东西。

请告诉我这个设计叫什么,或者发表一篇关于它的文章。

java
  • 1 个回答
  • 48 Views
Martin Hope
Artem
Asked: 2024-05-26 14:57:56 +0000 UTC

您应该创建包装类型吗?在 C# 中提高代码可读性?(输入 1 个字段)

  • 9

C# 因在类型方面比 C++ 更严格而闻名。然而,我注意到没有人特别急于创建包装类型以提高可读性和易于转换。

例如,我正在编写代码,其中时间有时以秒为单位,有时以毫秒为单位,并且是恒定的,并且在可能的情况下,所有转换都是手动执行并乘以 1000。

我尝试创建两个类型为秒和毫秒的只读记录结构,从而重载转换运算符。我什至在其中包含了最大值的检查。

但我再次开始怀疑自己是否正确地花了两周的时间来完成这一切……为什么没有人这样做。我无法回答这个问题,但以下想法悄然浮现:

  • 程序速度下降
  • int/uint/long 的持续问题,我总是想节省空间并不断使用 int/uint/long 以确保它适合或使用负数
  • 转换运算符的问题(我最近发现它们在 Sharp 中向后工作,并且我尝试解决这个问题的任何尝试都归结为每个人都写这是一个错误或一个功能这一事实。尽管我没有看到这有任何意义完全没有(实际上是这样的)
  • 每个人都只是编写程序并最初使用 DateTime/TimeSpan - 然而,有时在几秒钟内为一个变量分配 8 个字节仍然是大胆的,特别是当一个类中有很多这样的变量并且经常使用时

一般来说,请分享您的经验。也许如果我从头开始编写程序,我就不会打扰。我遇到过由不同的人编写的项目 + 使用多个库,而这些库又具有自己的数据存储类型。有这样的油醋汁,我就坐下来,以为我会把所有的东西都清理干净。现在我越来越被怀疑所淹没,我简直陷入了恍惚之中:“我应该继续花时间在这上面,还是退缩而不受苦?”

public readonly record struct Seconds
{
    public readonly int Ticks;
    public readonly static Seconds MaxValue = new Seconds(int.MaxValue);
    public readonly static Seconds MinValue = new Seconds(int.MinValue);
    public readonly static Seconds Zero = new Seconds(0);

    public Seconds(int ticks)
    {
        Ticks = ticks;
    }

    public static implicit operator int(Seconds time)
    {
        return time.Ticks;
    }

    public static explicit operator Seconds(int ticks)
    {
        return new Seconds(ticks);
    }

    public static implicit operator float(Seconds time)
    {
        return time.Ticks;
    }

    public static implicit operator TimeSpan(Seconds time)
    {
        return TimeSpan.FromSeconds(time.Ticks);
    }

    public static explicit operator Seconds(TimeSpan span)
    {
        var ticks = span.TotalSeconds;
        if (ticks < int.MinValue || ticks > int.MaxValue)
            throw new Exception("explicit operator Seconds(TimeSpan) : out of range value");
        return new((int)ticks);
    }

    public static explicit operator Seconds(Milliseconds time)
    {
        return new(time.Ticks / 1000);
    }

    public static explicit operator Seconds(RelativeTime span)
    {
        return new((int)(span.Milliseconds / 1000));
    }

    public static Seconds operator -(Seconds right)
    {
        return (Seconds)(-right.Ticks);
    }

    public static Seconds operator -(Seconds left, Seconds right)
    {
        return (Seconds)(left.Ticks - right.Ticks);
    }

    public static Seconds operator +(Seconds left, Seconds right)
    {
        return (Seconds)(left.Ticks + right.Ticks);
    }

    public static Seconds operator *(Seconds left, Seconds right)
    {
        return (Seconds)(left.Ticks * right.Ticks);
    }

    public static float operator /(Seconds left, Seconds right)
    {
        return (float)left.Ticks / right.Ticks;
    }

    public static Seconds operator %(Seconds left, Seconds right)
    {
        return (Seconds)(left.Ticks % right.Ticks);
    }

    public static bool operator >(Seconds left, Seconds right)
    {
        return left.Ticks > right.Ticks;
    }

    public static bool operator <(Seconds left, Seconds right)
    {
        return left.Ticks < right.Ticks;
    }

    public static bool operator >=(Seconds left, Seconds right)
    {
        return left.Ticks >= right.Ticks;
    }

    public static bool operator <=(Seconds left, Seconds right)
    {
        return left.Ticks <= right.Ticks;
    }

    public override string ToString()
    {
        return Ticks.ToString();
    }

    public static bool TryParse(string s, out Seconds result)
    {        
        bool isSuccessful = int.TryParse(s, out int parsed);
        result = (Seconds)parsed;
        return isSuccessful;
    }
}


public readonly record struct Milliseconds
{
    public readonly int Ticks;
    public readonly static Milliseconds MaxValue = new Milliseconds(int.MaxValue);
    public readonly static Milliseconds MinValue = new Milliseconds(int.MinValue);
    public readonly static Milliseconds Zero = new Milliseconds(0);

    public Milliseconds(int ticks)
    {
        Ticks = ticks;
    }

    public static implicit operator int(Milliseconds time)
    {
        return time.Ticks;
    }

    public static explicit operator Milliseconds(int ticks)
    {
        return new Milliseconds(ticks);
    }

    public static implicit operator float(Milliseconds time)
    {
        return time.Ticks;
    }

    public static implicit operator TimeSpan(Milliseconds time)
    {
        return TimeSpan.FromMilliseconds(time.Ticks);
    }

    public static explicit operator Milliseconds(TimeSpan span)
    {
        var ticks = span.TotalMilliseconds;
        if (ticks > int.MaxValue || ticks < int.MinValue)
            throw new Exception("explicit operator Milliseconds(TimeSpan) : out of range value");
        return new((int)ticks);
    }

    public static explicit operator Milliseconds(Seconds time)
    {
        var ticks = (long)time.Ticks * 1000;
        if (ticks > int.MaxValue || ticks < int.MinValue)
            throw new Exception("explicit operator Milliseconds(Seconds) : out of range value");
        return new Milliseconds((int)ticks);
    }

    public static explicit operator Milliseconds(RelativeTime span)
    {
        var ticks = span.Milliseconds;
        if (ticks > int.MaxValue)
            throw new Exception("explicit operator Milliseconds(RelativeTime) : out of range value");
        return new((int)ticks);
    }

    public static Milliseconds operator -(Milliseconds right)
    {
        return (Milliseconds)(-right.Ticks);
    }

    public static Milliseconds operator -(Milliseconds left, Milliseconds right)
    {
        return (Milliseconds)(left.Ticks - right.Ticks);
    }

    public static Milliseconds operator +(Milliseconds left, Milliseconds right)
    {
        return (Milliseconds)(left.Ticks + right.Ticks);
    }

    public static Milliseconds operator *(Milliseconds left, Milliseconds right)
    {
        return (Milliseconds)(left.Ticks * right.Ticks);
    }

    public static float operator /(Milliseconds left, Milliseconds right)
    {
        return (float)left.Ticks / right.Ticks;
    }

    public static Milliseconds operator %(Milliseconds left, Milliseconds right)
    {
        return (Milliseconds)(left.Ticks % right.Ticks);
    }

    public static bool operator >(Milliseconds left, Milliseconds right)
    {
        return left.Ticks > right.Ticks;
    }

    public static bool operator <(Milliseconds left, Milliseconds right)
    {
        return left.Ticks < right.Ticks;
    }

    public static bool operator >=(Milliseconds left, Milliseconds right)
    {
        return left.Ticks >= right.Ticks;
    }

    public static bool operator <=(Milliseconds left, Milliseconds right)
    {
        return left.Ticks <= right.Ticks;
    }

    public override string ToString()
    {
        return Ticks.ToString();
    }

    public static bool TryParse(string s, out Milliseconds result)
    {
        bool isSuccessful = int.TryParse(s, out int parsed);
        result = (Milliseconds)parsed;
        return isSuccessful;
    }
}

public readonly record struct RelativeTime
{
    public readonly uint Milliseconds;
    public readonly static RelativeTime MaxValue = new RelativeTime(uint.MaxValue);
    public readonly static RelativeTime MinValue = new RelativeTime(uint.MinValue);
    public readonly static RelativeTime Zero = new RelativeTime(0);

    public RelativeTime(uint milliseconds)
    {
        Milliseconds = milliseconds;
    }

    public static implicit operator uint(RelativeTime time)
    {
        return time.Milliseconds;
    }

    public static explicit operator RelativeTime(uint milliseconds)
    {
        return new RelativeTime(milliseconds);
    }    

    public static implicit operator float(RelativeTime time)
    {
        return time.Milliseconds;
    }

    public static RelativeTime operator -(RelativeTime left, RelativeTime right)
    {
        return (RelativeTime)(left.Milliseconds - right.Milliseconds);
    }

    public static RelativeTime operator +(RelativeTime left, RelativeTime right)
    {
        return (RelativeTime)(left.Milliseconds + right.Milliseconds);
    }

    public static RelativeTime operator +(RelativeTime left, Milliseconds right)
    {
        return (RelativeTime)(left.Milliseconds + right.Ticks);
    }

    public static RelativeTime operator -(RelativeTime left, Milliseconds right)
    {
        return (RelativeTime)(left.Milliseconds - right.Ticks);
    }

    public static bool operator >(RelativeTime left, RelativeTime right)
    {
        return left.Milliseconds > right.Milliseconds;
    }

    public static bool operator <(RelativeTime left, RelativeTime right)
    {
        return left.Milliseconds < right.Milliseconds;
    }

    public static bool operator >=(RelativeTime left, RelativeTime right)
    {
        return left.Milliseconds >= right.Milliseconds;
    }

    public static bool operator <=(RelativeTime left, RelativeTime right)
    {
        return left.Milliseconds <= right.Milliseconds;
    }

    public override string ToString()
    {
        return Milliseconds.ToString();
    }

    public static bool TryParse(string s, out RelativeTime result)
    {
        bool isSuccessful = uint.TryParse(s, out uint parsed);
        result = (RelativeTime)parsed;
        return isSuccessful;
    }
}

public readonly record struct UnixTime
{
    public readonly int Seconds;
    public static readonly UnixTime Zero = new UnixTime(0);
    public static readonly UnixTime Infinity = new UnixTime(-1);

    public UnixTime(int ticks)
    {
        if (ticks < 0 && ticks != -1)
            throw new Exception("constructor UnixTime(int) : too low value");
        Seconds = ticks;
    }

    public static implicit operator int(UnixTime time)
    {
        return time.Seconds;
    }

    public static explicit operator UnixTime(int seconds)
    {
        if (seconds < 0 && seconds != -1)
            throw new Exception("explicit operator UnixTime(int) : too low value");
        return new UnixTime(seconds);
    }

    public static explicit operator UnixTime(UnixTime64 time)
    {
        if (time.Seconds > int.MaxValue)
            throw new Exception("explicit operator UnixTime(UnixTime64) : too high value");
        return (UnixTime)(int)time.Seconds;
    }

    public static explicit operator UnixTime(UnixTimeMS time)
    {
        var seconds = time.Milliseconds / 1000;
        if (seconds > int.MaxValue)
            throw new Exception("explicit operator UnixTime(UnixTimeMS) : too high value");
        return (UnixTime)(int)seconds;
    }

    public static explicit operator DateTime(UnixTime time)
    {
        if (time == Infinity)
            return Time.Infinity;

        if (time == 0)
            return Time.Zero;

        return DateTimeOffset.FromUnixTimeSeconds(time).UtcDateTime;
    }

    public static explicit operator UnixTime(DateTime dateTime)
    {
        if (dateTime == Time.Infinity)
            return Infinity;

        if (dateTime == Time.Zero)
            return Zero;

        if (dateTime < DateTimeOffset.UnixEpoch.UtcDateTime)
            throw new Exception("explicit operator UnixTime(DateTime) : too low value");

        long ticks = new DateTimeOffset(dateTime).ToUnixTimeSeconds();

        if (ticks > int.MaxValue)
            throw new Exception("explicit operator UnixTime(DateTime) : too high value");
        return (UnixTime)(int)ticks;
    }

    public static Seconds operator -(UnixTime left, UnixTime right)
    {
        return (Seconds)(left.Seconds - right.Seconds);
    }

    public static UnixTime operator +(UnixTime left, Seconds right)
    {
        return (UnixTime)(left.Seconds + right.Ticks);
    }

    public static UnixTime operator -(UnixTime left, Seconds right)
    {
        return (UnixTime)(left.Seconds - right.Ticks);
    }

    public static bool operator >(UnixTime left, UnixTime right)
    {
        return left.Seconds > right.Seconds;
    }

    public static bool operator <(UnixTime left, UnixTime right)
    {
        return left.Seconds < right.Seconds;
    }

    public static bool operator >=(UnixTime left, UnixTime right)
    {
        return left.Seconds >= right.Seconds;
    }

    public static bool operator <=(UnixTime left, UnixTime right)
    {
        return left.Seconds <= right.Seconds;
    }
}

public readonly record struct UnixTime64
{
    public readonly long Seconds;
    public static readonly UnixTime64 Zero = new UnixTime64(0);
    public static readonly UnixTime64 Infinity = new UnixTime64(-1);

    public UnixTime64(long seconds)
    {
        if (seconds < 0 && seconds != -1)
            throw new Exception("constructor UnixTime64(long) : too low value");
        Seconds = seconds;
    }

    public static implicit operator long(UnixTime64 time)
    {
        return time.Seconds;
    }

    public static explicit operator UnixTime64(long seconds)
    {
        if (seconds < 0 && seconds != -1)
            throw new Exception("explicit operator UnixTime64(long) : too low value");
        return new UnixTime64(seconds);
    }

    public static explicit operator int(UnixTime64 time)
    {
        if (time.Seconds < 0 && time.Seconds != -1 || time.Seconds > int.MaxValue)
            throw new Exception("explicit operator int(UnixTime64) : out of range value");
        return (int)time.Seconds;
    }

    public static implicit operator UnixTime64(UnixTime time)
    {
        return (UnixTime64)time.Seconds;
    }

    public static explicit operator UnixTime64(UnixTimeMS time)
    {
        var seconds = time.Milliseconds / 1000;
        return (UnixTime64)seconds;
    }

    public static explicit operator DateTime(UnixTime64 time)
    {
        if (time == Infinity)
            return Time.Infinity;

        if (time == 0)
            return Time.Zero;

        return DateTimeOffset.FromUnixTimeSeconds(time).UtcDateTime;
    }

    public static explicit operator UnixTime64(DateTime dateTime)
    {
        if (dateTime == Time.Infinity)
            return Infinity;

        if (dateTime == Time.Zero)
            return Zero;

        if (dateTime < DateTimeOffset.UnixEpoch.UtcDateTime)
            throw new Exception("explicit operator UnixTime64(DateTime) : too low value");

        return (UnixTime64)new DateTimeOffset(dateTime).ToUnixTimeSeconds();
    }

    public static Seconds operator -(UnixTime64 left, UnixTime64 right)
    {
        return (Seconds)(left.Seconds - right.Seconds);
    }

    public static UnixTime64 operator +(UnixTime64 left, Seconds right)
    {
        return (UnixTime64)(left.Seconds + right.Ticks);
    }

    public static UnixTime64 operator -(UnixTime64 left, Seconds right)
    {
        return (UnixTime64)(left.Seconds - right.Ticks);
    }

    public static bool operator >(UnixTime64 left, UnixTime64 right)
    {
        return left.Seconds > right.Seconds;
    }

    public static bool operator <(UnixTime64 left, UnixTime64 right)
    {
        return left.Seconds < right.Seconds;
    }

    public static bool operator >=(UnixTime64 left, UnixTime64 right)
    {
        return left.Seconds >= right.Seconds;
    }

    public static bool operator <=(UnixTime64 left, UnixTime64 right)
    {
        return left.Seconds <= right.Seconds;
    }
}

public readonly record struct UnixTimeMS
{
    public readonly long Milliseconds;
    public static readonly UnixTimeMS Zero = new UnixTimeMS(0);
    public static readonly UnixTimeMS Infinity = new UnixTimeMS(-1);

    public UnixTimeMS(long milliseconds)
    {
        if (milliseconds < 0 && milliseconds != -1)
            throw new Exception("constructor UnixTimeMS(long) : too low value");
        Milliseconds = milliseconds;
    }

    public static implicit operator long(UnixTimeMS time)
    {
        return time.Milliseconds;
    }

    public static explicit operator UnixTimeMS(long milliseconds)
    {
        if (milliseconds < 0 && milliseconds != -1)
            throw new Exception("explicit operator UnixTimeMS(long) : too low value");
        return new UnixTimeMS(milliseconds);
    }

    public static explicit operator int(UnixTimeMS time)
    {
        if (time.Milliseconds < 0 && time.Milliseconds != -1 || time.Milliseconds > int.MaxValue)
            throw new Exception("explicit operator int(UnixTimeMS) : out of range value");
        return (int)time.Milliseconds;
    }

    public static implicit operator UnixTimeMS(UnixTime time)
    {
        long milliseconds = time.Seconds * 1000L;
        return (UnixTimeMS)milliseconds;
    }

    public static explicit operator UnixTimeMS(UnixTime64 time)
    {
        if (time.Seconds > long.MaxValue / 1000)
            throw new Exception("explicit operator UnixTimeMS(UnixTime64) : too high value");
        long milliseconds = time.Seconds * 1000L;
        return (UnixTimeMS)milliseconds;
    }

    public static explicit operator DateTime(UnixTimeMS time)
    {
        if (time == Infinity)
            return Time.Infinity;

        if (time == 0)
            return Time.Zero;

        return DateTimeOffset.FromUnixTimeSeconds(time).UtcDateTime;
    }

    public static explicit operator UnixTimeMS(DateTime dateTime)
    {
        if (dateTime == Time.Infinity)
            return Infinity;

        if (dateTime == Time.Zero)
            return Zero;

        if (dateTime < DateTimeOffset.UnixEpoch.UtcDateTime)
            throw new Exception("explicit operator UnixTimeMS(DateTime) : too low value");

        return (UnixTimeMS)new DateTimeOffset(dateTime).ToUnixTimeMilliseconds();
    }

    public static Seconds operator -(UnixTimeMS left, UnixTimeMS right)
    {
        return (Seconds)(left.Milliseconds - right.Milliseconds);
    }

    public static UnixTimeMS operator +(UnixTimeMS left, Seconds right)
    {
        return (UnixTimeMS)(left.Milliseconds + right.Ticks);
    }

    public static UnixTimeMS operator -(UnixTimeMS left, Seconds right)
    {
        return (UnixTimeMS)(left.Milliseconds - right.Ticks);
    }

    public static bool operator >(UnixTimeMS left, UnixTimeMS right)
    {
        return left.Milliseconds > right.Milliseconds;
    }

    public static bool operator <(UnixTimeMS left, UnixTimeMS right)
    {
        return left.Milliseconds < right.Milliseconds;
    }

    public static bool operator >=(UnixTimeMS left, UnixTimeMS right)
    {
        return left.Milliseconds >= right.Milliseconds;
    }

    public static bool operator <=(UnixTimeMS left, UnixTimeMS right)
    {
        return left.Milliseconds <= right.Milliseconds;
    }
}

public static class Time
{
    static Time()
    {
        ApplicationStartTime = Process.GetCurrentProcess().StartTime.ToUniversalTime();
        Zero = DateTime.MinValue;
        Infinity = DateTime.MaxValue;
    }

    public static readonly DateTime ApplicationStartTime;
    public static readonly TimeSpan StartLocalOffset;

    public static readonly Seconds Minute = (Seconds)60;
    public static readonly Seconds Hour = (Seconds)(Minute * 60);
    public static readonly Seconds Day = (Seconds)(Hour * 24);
    public static readonly Seconds Week = (Seconds)(Day * 7);
    public static readonly Seconds Month = (Seconds)(Day * 30);
    public static readonly Seconds Year = (Seconds)(Month * 12);
    public static readonly Milliseconds InMilliseconds = (Milliseconds)1000;

    public static readonly DateTime Zero;
    public static readonly DateTime Infinity;

    /// <summary>
    /// Gets the current local time.
    /// </summary>
    public static DateTimeOffset NowLocal => DateTimeOffset.Now;

    /// <summary>
    /// Gets the current UTC time.
    /// </summary>
    public static DateTime Now => DateTime.UtcNow;

    /// <summary>
    /// Gets the application UpTime.
    /// </summary>
    public static TimeSpan UpTime => Now - ApplicationStartTime;

    /// <summary>
    /// Gets the application time relative to application start time in ms.
    /// </summary>
    public static RelativeTime NowRelative => (RelativeTime)UpTime.ToMilliseconds();

    /// <summary>
    /// Gets the difference to current UTC time.
    /// </summary>
    public static TimeSpan Diff(DateTime oldTime)
    {
        return Diff(oldTime, Now);
    }    

    /// <summary>
    /// Gets the difference to current UpTime.
    /// </summary>
    public static TimeSpan Diff(TimeSpan oldUpTime)
    {
        return UpTime - oldUpTime;
    }

    /// <summary>
    /// Gets the difference to current RelativeTime in milliseconds.
    /// </summary>
    public static Milliseconds Diff(RelativeTime oldMSTime)
    {
        return Diff(oldMSTime, NowRelative);
    }

    /// <summary>
    /// Gets the difference between two time points.
    /// </summary>
    public static TimeSpan Diff(DateTime oldTime, DateTime newTime)
    {
        return newTime - oldTime;
    }

    /// <summary>
    /// Gets the difference between two time spans.
    /// </summary>
    public static TimeSpan Diff(TimeSpan oldTimeSpan, TimeSpan newTimeSpan)
    {
        return newTimeSpan - oldTimeSpan;
    }

    /// <summary>
    /// Gets the difference between two relative to UpTime spans in milliseconds.
    /// </summary>
    public static Milliseconds Diff(RelativeTime oldMSTime, RelativeTime newMSTime)
    {
        if (oldMSTime > newMSTime)
            return (Milliseconds)((RelativeTime)0xFFFFFFFF - oldMSTime + newMSTime);
        else
            return (Milliseconds)(newMSTime - oldMSTime);
    }
}

是的,所有这些类型都被使用,我无法摆脱它们。一部分在数据库,一部分在客户端,一部分在服务器。

Я понял что при передаче в функцию особо ничего не меняет 4 или 8 байт особенно учитывая х64 систему. Но есть в коде куча переменных с какимито таймерами или оперативными настройками, где хранится от 0 до 1 часа времени. Если сделать все 8 байт - размеры классов вырастут вдвое и втрое, а они все подвязаны к количеству клиентов онлайн. Так что расходы реально возрастают.

П.С. В коде проблема с 2038 годом решена тем, что в клиенте используется relative time 4байта. Экономия места как бы + оверфлов раз в месяц при стабильном аптайме (который правильно считает разницу). Естественно используется для какой-то ерунды. Там где нужно точно передать дату - используют 8байт, но UnixTime исключительно. Проблема же 2038 в коде сервера и базы данных пока не решена, но похоже пока это откладывается до 2038.

Показанный код - это все новое. В коде это просто int uint long + иногда комментарии или захардкоржено в имени переменной/метода. Распутываю до сих пор и нахожу даже баги, когда в sec пихали ms

И да, в самой базе данных все хранится в uint/ulong, а в коде используется все разнообразие. -1 => uint.MaxValue - вот так захардкоржено и все)

c#
  • 1 个回答
  • 106 Views
Martin Hope
Universall
Asked: 2024-04-18 05:17:05 +0000 UTC

Fastapi:如何使用中间件更改响应内容

  • 9

任务

我想编写将数据添加到最终响应的中间件。也就是说,这个答案:

{
    "user": ...,
    "some_field": ...
}

它应该变成这样:

{
    "some_additional_field": ...,
    "data": {
        "user": ...,
        "some_field": ...
    }
}

为此我编写了中间件:

class ResponseFormatterMiddleware:
    async def _post_process_response(self, response: Response) -> Response:
        response.body = response.render({
            "some_additional_field": 123,
            "data": response.body
        })

        return response

    async def __call__(self, request: Request, call_next) -> Response:
        response = await call_next(request)
        return await self._post_process_response(response)

并添加它:

app.middleware("http")(ResponseFormatterMiddleware())

但我收到一个错误:

AttributeError: '_StreamingResponse' object has no attribute 'body'

之后我发现我收到的输入不是fastapi.Request, but starlette.middleware.base._CachedRequest,但是执行控制器后我收到的输入不是fastapi.Response, but starlette.middleware.base._StreamingResponse。

问题)

是否可以像 django 中那样做 +- ?也就是说,使用中间件将附加信息写入请求中,然后以某种方式更改最终响应。

是否有可能以某种方式使用对象fastapi而不是starlette中间件?

python
  • 1 个回答
  • 121 Views
Martin Hope
Кирилл
Asked: 2024-03-29 00:52:16 +0000 UTC

为什么施特拉森的算法在 2047 年之后速度急剧下降?

  • 9

我注意到维度从 1 到 2047 的矩阵的计算时间超过 6 秒

从 2048 开始,它们从 44 +- 秒开始。时间如此跳跃的原因可能是什么?

对于 2047 矩阵,RAM 升至 279 MB;对于 2048,RAM 升至 1042 MB

同时,有足够的RAM,她很难只数数

using System.Diagnostics;
using System.Text;
class Program
{
    static void Main(string[] args)
    {
        int m = 0, n = 0;
        while (true)
        {
            Stopwatch stopwatch = new Stopwatch();
            InputDate(ref m, "строк m");
            InputDate(ref n, "колонок n");

            int[][] matrix1 = GenerateMatrix(m, n);
            int[][] matrix2 = GenerateMatrix(m, n);
            int nn = GetNewDimension(ref m, ref n);

            int[][] aN = Addition2SquareMatrix(matrix1, nn, m, n);          
            int[][] bN = Addition2SquareMatrix(matrix2, nn, m, n);
           
            stopwatch.Start();
            int[][] temp = MultiStrassen(aN, bN, nn);

            stopwatch.Stop();

            //OutputMatrix(matrix1);
            //OutputMatrix(matrix2);
            //OutputMatrix(GetSubmatrix(temp, m, n));
            Console.WriteLine("\n" + stopwatch.Elapsed);
            Console.ReadKey();
        }
    }
    /// <summary>
    /// Ввод количество строк и столбцов
    /// </summary>
    /// <param name="number">запись числа в переменную</param>
    /// <param name="txt">передаваемый текст</param>
    static void InputDate(ref int number, string txt)
    {
        do
        {
            Console.Write($"Введите число {txt}: ");
            number = int.Parse(Console.ReadLine());
        }
        while (number <= 0);
    }
    
    /// <summary>
    /// получаем новую степень матрицы
    /// </summary>
    /// <param name="m">строка</param>
    /// <param name="n">столбец</param>
    /// <returns>возвращаем степень матрицы</returns>
    static int GetNewDimension(ref int m, ref int n) => 1 << (int)(Math.Log2(Math.Max(m, n))+1);
    
    /// <summary>
    /// Преобразуем матрицу к виду 2^n путём добавление дополнительных строк
    /// </summary>
    /// <param name="a">передаваемый массив</param>
    /// <param name="nn">наша новая степень матрицы (размерность)</param>
    /// <param name="m">количество строк</param>
    /// <param name="n">количество столбцов</param>
    /// <returns>возвращаем обновленную матрицу</returns>
    static int[][] Addition2SquareMatrix(int[][] a, int nn, int m, int n)
    {       
        int[][] result = new int[nn][];
        for (int i = 0; i < nn; i++)
        {
            result[i] = new int[nn];
            if (i < m)
            {
                for (int j = 0; j < n; j++)
                {
                    result[i][j] = a[i][j];
                }
            }
        }           
        return result;            
    }
    /// <summary>
    /// Алгоритм Штрассена
    /// </summary>
    /// <param name="a">1 матрица</param>
    /// <param name="b">2 матрица</param>
    /// <param name="n">размерность матрицы</param>
    /// <returns>возвращаем результат</returns>
    static int[][] MultiStrassen(int[][] a, int[][] b, int n)
    {
        if (n <= 64)
        {
            return Multiply(a, b);
        }

        n = n >> 1;

        int[][] a11 = new int[n][];
        int[][] a12 = new int[n][];
        int[][] a21 = new int[n][];
        int[][] a22 = new int[n][];

        int[][] b11 = new int[n][];
        int[][] b12 = new int[n][];
        int[][] b21 = new int[n][];
        int[][] b22 = new int[n][];

        for (int i = 0; i < n; i++)
        {
            a11[i] = new int[n];
            a12[i] = new int[n];
            a21[i] = new int[n];
            a22[i] = new int[n];

            b11[i] = new int[n];
            b12[i] = new int[n];
            b21[i] = new int[n];
            b22[i] = new int[n];
        }

        SplitMatrix(a, a11, a12, a21, a22);
        SplitMatrix(b, b11, b12, b21, b22);

        int[][] p1 = MultiStrassen(Summation(a11, a22), Summation(b11, b22), n);
        int[][] p2 = MultiStrassen(Summation(a21, a22), b11, n);
        int[][] p3 = MultiStrassen(a11, Subtraction(b12, b22), n);
        int[][] p4 = MultiStrassen(a22, Subtraction(b21, b11), n);
        int[][] p5 = MultiStrassen(Summation(a11, a12), b22, n);
        int[][] p6 = MultiStrassen(Subtraction(a21, a11), Summation(b11, b12), n);
        int[][] p7 = MultiStrassen(Subtraction(a12, a22), Summation(b21, b22), n);

        int[][] c11 = Summation(Summation(p1, p4), Subtraction(p7, p5));
        int[][] c12 = Summation(p3, p5);
        int[][] c21 = Summation(p2, p4);
        int[][] c22 = Summation(Subtraction(p1, p2), Summation(p3, p6));
        return CollectMatrix(c11, c12, c21, c22);
    }

    /// <summary>
    /// Разделение на матрицу на под матрицы
    /// </summary>
    /// <param name="a">исходная матрица</param>
    /// <param name="a11">матрицы а11</param>
    /// <param name="a12">матрица а12</param>
    /// <param name="a21">матрица а21</param>
    /// <param name="a22">матрица а22</param>
    static void SplitMatrix(int[][] a, int[][] a11, int[][] a12, int[][] a21, int[][] a22)
    {
        int n = a.Length >> 1;

        for (int i = 0; i < n; i++)
        {
            Array.Copy(a[i], 0, a11[i], 0, n);
            Array.Copy(a[i], n, a12[i], 0, n);
            Array.Copy(a[i + n], 0, a21[i], 0, n);
            Array.Copy(a[i + n], n, a22[i], 0, n);
        }
    }
    /// <summary>
    /// Объединение подматриц в одну матрицу
    /// </summary>
    /// <param name="a11"></param>
    /// <param name="a12"></param>
    /// <param name="a21"></param>
    /// <param name="a22"></param>
    /// <returns>возвращаем объединённую матрицу</returns>
    static int[][] CollectMatrix(int[][] a11, int[][] a12, int[][] a21, int[][] a22)
    {
        int n = a11.Length;
        var b = (n << 1);

        int[][] a = new int[b][];
        for (int i = 0; i < b; i++)
        {
            a[i] = new int[b];
        }

        for (int i = 0; i < n; i++)
        {
            Array.Copy(a11[i], 0, a[i], 0, n);
            Array.Copy(a12[i], 0, a[i], n, n);
            Array.Copy(a21[i], 0, a[i + n], 0, n);
            Array.Copy(a22[i], 0, a[i + n], n, n);
        }

        return a;
    }
    /// <summary>
    /// Разность между матрицами
    /// </summary>
    /// <param name="a">матрица 1</param>
    /// <param name="b">матрица 2</param>
    /// <returns>результат разности матриц</returns>
    static int[][] Subtraction(int[][] a, int[][] b)
    {
        int n = a.Length;
        int m = a[0].Length;
        int[][] c = new int[n][];

        for (int i = 0; i < n; i++)
        {
            c[i] = new int[m];
            for (int j = 0; j < m; j++)
            {
                c[i][j] = a[i][j] - b[i][j];
            }
        }
        return c;
    }
    /// <summary>
    /// Умножение матриц
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns>результат умножения </returns>
    static int[][] Multiply(int[][] a, int[][] b)
    {
        int rowsA = a.Length;
        int columnsB = b[0].Length;
        int columnsA_rowsB = a[0].Length;

        int[][] c = new int[rowsA][];
        for (int i = 0; i < rowsA; i++)
        {
            c[i] = new int[columnsB];
            for (int j = 0; j < columnsB; j++)
            {
                int sum = 0;
                for (int k = 0; k < columnsA_rowsB; k++)
                {
                    sum += a[i][k] * b[k][j];
                }
                c[i][j] = sum;
            }
        }
        return c;
    }

    /// <summary>
    /// Суммирование матриц
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    static int[][] Summation(int[][] a, int[][] b)
    {
        int n = a.Length;
        int m = a[0].Length;
        int[][] c = new int[n][];
        for (int i = 0; i < n; i++)
        {
            c[i] = new int[m];
        }

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                c[i][j] = a[i][j] + b[i][j];
            }
        }

        return c;
    }
    /// <summary>
    /// Убирает лишние строки матриц
    /// </summary>
    /// <param name="a"></param>
    /// <param name="n"></param>
    /// <param name="m"></param>
    /// <returns>возвращаем матрицу</returns>
    static int[][] GetSubmatrix(int[][] a, int n, int m)
    {        
        int[][] result = new int[n][];
        for (int i = 0; i < n; i++)
        {
            result[i] = new int[m];
            Array.Copy(a[i], 0, result[i], 0, m);
        }
        return result;       
    }

    /// <summary>
    /// Генерация произвольного размера матрицы
    /// </summary>
    /// <param name="m">количество строк</param>
    /// <param name="n">количество столбцов</param>
    /// <returns>возврощаем матрицу</returns>
    static int[][] GenerateMatrix(int m, int n)
    {
        Random rand = new Random();
        int[][] matrix = new int[m][];

        for (int i = 0; i < m; i++)
        {
            matrix[i] = new int[n];
            for (int j = 0; j < n; j++)
            {
                matrix[i][j] = rand.Next(1, 100);
            }
        }
        return matrix;
    }
    /// <summary>
    /// Вывод на экран матриц
    /// </summary>
    /// <param name="matrix"></param>
    static void OutputMatrix(int[][] matrix)
    {
        var sb = new StringBuilder();
        foreach (int[] row in matrix)
        {
            foreach (int element in row)
            {
                sb.Append(element);
                sb.Append(' ');
            }
            sb.Length--;
            sb.AppendLine();
        }
        Console.WriteLine($"\n" + sb);
    }
}
    
c#
  • 2 个回答
  • 135 Views
上一页
下一页

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5