您的位置:首页 > 编程语言 > Python开发

从一个题看python凶残

2014-03-07 13:14 127 查看
这几天看python感觉很不适应,刚好有人问一个算法题。我第一思路用c实现一遍,时间复杂度n空间复杂度大点,后想到用python发现python凶残的无语。

编写一个函数,实现的功能是在A字符串中没有出现但是在B字符串中出现,把在B字符串中出现的字符保存到字符串U中,并输出字符串U;例如:A字符串“ADCEF",B字符串“gg”,则字符串U是“gg”

c代码如下:

#include<iostream>
/*
函数功能:查找在A字符串中有而B字符中没,并输出到out中
*/
static void difstr(const char *source,const char *dest,char *out)
{
if(dest==NULL){*out='\0';return;}
if(source==NULL){memcpy(out,dest,strlen(dest)+1);return;}
char hash[256];
int len1=strlen(source);
memset(hash,0,sizeof(hash));
for(int i=0;i<len1;i++)
hash[source[i]]=1;
len1=strlen(dest);
for(int i=0;i<len1;i++)
{
if(!hash[dest[i]])
*out++=dest[i];
}
*out='\0';
}

下面函数主要是在空间复杂度上优化,用位图思路
static void difstr1(const char *source,const char *dest,char *out)
{
if(dest==NULL){*out='\0';return;}
if(source==NULL){memcpy(out,dest,strlen(dest)+1);return;}
#define LEN(x) x/8
#define LEN1(x) x%8
char hash[LEN(256)];
memset(hash,0,sizeof(hash));
int len1=strlen(source);
#define or(x,n) (x)|=(1<<(n))
for(int i=0;i<len1;i++)
or(hash[LEN(source[i])],LEN1(source[i]));
len1=strlen(dest);
#define getbit(n,pos) (n>>pos)&1
for(int i=0;i<len1;i++)
{
if(!getbit((int)hash[LEN(dest[i])],LEN1(dest[i])))
*out++=dest[i];
}
*out='\0';
}
int main()
{
char *s="abc";
char *ss="ad";
char out[30];
difstr1(s,ss,out);
printf("%s",out);
}


python代码

for x in b:
if not x in a:
print(x)


这里没有存储直接打印虽然目前不会写测试python运行时间,但从代码量上看python提高生产力是无可置疑的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: