Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用Try和Except的更快替代方法_Python_C - Fatal编程技术网

在Python中使用Try和Except的更快替代方法

在Python中使用Try和Except的更快替代方法,python,c,Python,C,完成函数str1,str2,如果str1字符的一部分可以重新排列以匹配str2,则返回true,否则返回false 注: 仅使用小写字母a-z。不包括标点符号或数字。 需要考虑性能 我可以用C语言解决这个问题。因为我对学习Python感兴趣,所以我也尝试用Python来解决这个问题,但不幸的是遇到了超时错误。我不知道如何在Python中解决它,就像我在C中解决它一样 所以,请告诉我如何在Python中高效地实现这一点,最好使用与C相同或更好的技术 #include <stdbool.h&g

完成函数str1,str2,如果str1字符的一部分可以重新排列以匹配str2,则返回true,否则返回false

注:

仅使用小写字母a-z。不包括标点符号或数字。 需要考虑性能 我可以用C语言解决这个问题。因为我对学习Python感兴趣,所以我也尝试用Python来解决这个问题,但不幸的是遇到了超时错误。我不知道如何在Python中解决它,就像我在C中解决它一样

所以,请告诉我如何在Python中高效地实现这一点,最好使用与C相同或更好的技术

#include <stdbool.h>

bool scramble(const char* str1, const char* str2)
{
    // store number of occurrences of each character in str1 to arr
    int arr[26] = { 0 };

    while (*str1) {
        arr[*str1 - 'a'] += 1;
        str1++;
    }

    // check if each character of str2 is in arr
    while (*str2) {

        if (arr[*str2 - 'a'] >= 1)
            arr[*str2 - 'a'] -= 1;
        else
            return false;

        str2++;
    }

    return true;
}
另外,如果你发现我的C代码有问题,请通知我

PS:对不起,我的英语不好。

问题不在于尝试,只在于你的算法的复杂性是二次的,当字符串变得非常大时,它会开始崩溃。对于s2中的每个字符,您需要查看s1。CodeWars网站对最多600000个字符的字符串运行测试。一个关于^2的算法将是一个问题

这里有一个选项,在小字符串上速度较慢,但在大字符串上可以更好地扩展:

from collections import Counter

def scramble(s1, s2):
    c1 = Counter(s1)
    c2 = Counter(s2)
    return all(c1.get(k, 0) >= s for k, s in c2.items())

它的工作原理是对每个字符串进行一次传递以获得计数,然后再进行一次传递以进行测试。它通过了codewars站点上的所有测试。

因为我认为您对Python非常陌生。您可以找到有关此系列的更多信息:

defaultdict是一种集合包/库的方法,它使用一些初始值初始化数据结构。 例如:

输出:

0
{ANY_KEY: 0}
因此,由于我们已经给出了DefaultDictent,即int,定义任何键都将始终使用括号中给出的值初始化

import collections
def scramble(s1, s2):
    counter = collections.defaultdict(int)

    for char in s1:
        counter[char]+=1
    for char in s2:
         counter[char]-=1
         if counter[char] <= -1:
             return False
    return True

为什么不开始使用与在C中相同的方法在python中找到解决方案呢?是的,我确实是python新手:您使用的方法与我在C中使用的方法相同,对吗?您能解释一下collections.defaultdict的作用吗?defaultdict是collections包/库的一种方法,它用一些初始值初始化数据结构。谢谢。在您指出他们正在使用多达600000个字符的输入进行测试之前,我没有意识到复杂性可能是一个问题。
0
{ANY_KEY: 0}
import collections
def scramble(s1, s2):
    counter = collections.defaultdict(int)

    for char in s1:
        counter[char]+=1
    for char in s2:
         counter[char]-=1
         if counter[char] <= -1:
             return False
    return True