一些关于笛卡儿产品的问题 [英] Some thougts on cartesian products

查看:53
本文介绍了一些关于笛卡儿产品的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,可以将字符串与数字相乘:

In Python, it is possible to multiply a string with a number:

" hello" * 3
''hellohellohello''


但是,你不能将一个字符串与另一个字符串相乘:

''hello''* ''world''
Traceback(最近一次调用最后一次):

文件"<交互式输入>",第1行,在?

TypeError :不能将序列乘以非int


有时我错过了这样的功能。

我期望的结果是笛卡儿产物"字符串。


这是一个新的列表和字符串对象的简单实现,

解释了我的意思。它还实现了列表和字符串的强大功能:


class plist(list):

""" list with cartesian product list"" ;


def __mul __(自我,其他):

if isinstance(其他,pstr):

返回plist([s + o for s in self for o in other])

if hasattr(other,''__ getitem__''):

返回plist([[s,o] for s in self for o in other])

else:

返回列表(个体经营)*其他


def __pow __(自我,其他):

if isinstance(other,int)和其他> 0:

如果其他== 1:

返回自我

返回自我*自我**(其他-1)


类pstr(str):

""" str with cartesian product list"""


def __mul __(self,other):

if hasattr(其他,''__ getitem__''):

返回plist([s + o for s in self for o in other ])

否则:

返回str(自我)*其他


def __pow __(自我,其他):

if isinstance(other,int)和其他> 0:

如果其他== 1:

返回自我

返回自我*自我**(其他-1)


使用这些新字符串,您可以执行以下操作:

pstr(" ab")* pstr(" cd")* pstr(" ef")
[''ace'',''acf'',''ade'',''adf'',''bce'',''bcf'',''bde'',''bdf'' ]

print pstr(" abcdefgh")* pstr(" 12345678")
[''a1'',''a2'',...,''a8' ','''b1'',''b2'',...,''b8'',

....,...,...,''h1'' ,''h2'',...,''h8'']

print pstr(" ACGU")** 3
"hello"*3 ''hellohellohello''

However, you can''t multiply a string with another string:
''hello''*''world'' Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: can''t multiply sequence by non-int

Sometimes I was missing such a feature.
What I expect as the result is the "cartesian product" of the strings.

Here is a simple implementation of new list and string objects that
explains what I mean. It also implements powers of lists and strings:

class plist(list):
"""list with cartesian product list"""

def __mul__(self, other):
if isinstance(other, pstr):
return plist([s+o for s in self for o in other])
if hasattr(other, ''__getitem__''):
return plist([[s, o] for s in self for o in other])
else:
return list(self)*other

def __pow__(self, other):
if isinstance(other, int) and other > 0:
if other == 1:
return self
return self * self**(other-1)

class pstr(str):
"""str with cartesian product list"""

def __mul__(self, other):
if hasattr(other, ''__getitem__''):
return plist([s+o for s in self for o in other])
else:
return str(self)*other

def __pow__(self, other):
if isinstance(other, int) and other > 0:
if other == 1:
return self
return self * self**(other-1)

With these new strings you can do the following:
pstr("ab")*pstr("cd")*pstr("ef") [''ace'', ''acf'', ''ade'', ''adf'', ''bce'', ''bcf'', ''bde'', ''bdf'']
print pstr("abcdefgh")*pstr("12345678") [''a1'', ''a2'', ..., ''a8'', ''b1'', ''b2'', ..., ''b8'',
...., ..., ..., ''h1'', ''h2'', ..., ''h8'']
print pstr("ACGU")**3



[''AAA'',''AAC'',''AAG'',''AAU'',''ACA'',''ACC'',''ACG'',. ..,

....,''UGC'',''UGG'',''UGU'',''UUA'',''UUC'',''UUG' ',''UUU'']

我认为这有时会非常方便并节省一些打字。


如果Python字符串具有此功能,您甚至可以超越

最近最短的Python编码竞赛中的117字节解决方案

http://www.pycontest.net),如下:


j =''''。join; seven_seg = lambda x:j(j(\

(''|''*''_''*''|'')[ord(''| B?@z?(àD°''[int(d)]) %e] \

for d in x)+''\ n''for e in(4,9,7))


这个只有110个字节。


或者你可以写一个简单的密码破解者:


def crack(加密,字母):

为字母表中的passwd ** 4:

如果crypt(passwd,crypted [:2])== crypted:

return passwd


例如,用alphabet = string.lowercase调用它。


笛卡儿积可能通常是inte休息的可迭代:


def imul(iterable1,iterable2):

""""""笛卡尔积的两个iterables"""

for object1 in iterable1:

for object2 in iterable2:

if isinstance(object1,basestring)and \

isinstance(object2,basestring):

yield object1 + object2

else:

yield(object1,object2)

>
def ipow(可迭代,数字):

""""""""""

如果数字== 1:

for iterable中的对象:

yield对象

elif number> 1:
$ c $ b for object1 in iterable:

for object2 in ipow(iterable,number-1):

yield object1 + object2


class istr(str):

""" str with iterable cartesian product"""


def __mul __(self,other):

if isinstance(other,str):

return imul(self,other)

else:

返回str(自我)*其他


def __pow __(自我,其他):

return ipow(self,other)


我想知道是否可以通过某种方式添加类似的功能来支付
Python。我注意到Python有很多聚合函数可以使用
" reduce"给出集合对象(如reduce,filter,min,max,sum,

hash)和保持相同大小的函数(如map,sort或zip),但

很少有能够膨胀的功能给定的对象(如范围和

枚举)。我知道,这些功能很危险,因为它们还会增加程序消耗的时间和内存。尽管如此,有时他们

是有道理的,无论何时你出于某种原因,只需要*通过所有组合*行走



[''AAA'', ''AAC'', ''AAG'', ''AAU'', ''ACA'', ''ACC'', ''ACG'', ...,
...., ''UGC'', ''UGG'', ''UGU'', ''UUA'', ''UUC'', ''UUG'', ''UUU'']

I think this can be quite handy at times and save some typing.

If Python strings had this ability, you could even outdo the
117 byte solution in the recent shortest Python coding contest
(http://www.pycontest.net), as follows:

j=''''.join;seven_seg=lambda x:j(j(\
('' |''*''_ ''*'' |'')[ord(''|B?@z?(àD°''[int(d)])%e]\
for d in x)+''\n''for e in(4,9,7))

This has only 110 bytes.

Or you could write a simple password cracker like that:

def crack(crypted, alphabet):
for passwd in alphabet**4:
if crypt(passwd, crypted[:2]) == crypted:
return passwd

And call it with alphabet = string.lowercase, for example.

Cartesian products may be generally interesting for iterables:

def imul(iterable1, iterable2):
"""cartesian product of two iterables"""
for object1 in iterable1:
for object2 in iterable2:
if isinstance(object1, basestring) and \
isinstance(object2, basestring):
yield object1 + object2
else:
yield (object1, object2)

def ipow(iterable, number):
"""cartesian product power of an iterable"""
if number == 1:
for object in iterable:
yield object
elif number > 1:
for object1 in iterable:
for object2 in ipow(iterable, number-1):
yield object1 + object2

class istr(str):
"""str with iterable cartesian product"""

def __mul__(self, other):
if isinstance(other, str):
return imul(self, other)
else:
return str(self)*other

def __pow__(self, other):
return ipow(self, other)

I was wondering if similar functionality could be added in some way to
Python. I noticed that Python has a lot of aggregate functions that can
"reduce" given collection objects (like reduce, filter, min, max, sum,
hash) and functions that keep the same size (like map, sort or zip), but
few functions that can "inflate" the given objects (like range and
enumerate). I know, such functions are dangerous because they also
inflate time and memory consumed by the program. Still, sometimes they
can make sense, whenever you for some reason simply *have* to walk
through all the combinations.

推荐答案

Christoph Zwerschke写道:
Christoph Zwerschke wrote:
有时我错过了这样一个功能。
我期望的结果是笛卡儿产物"字符串。
Sometimes I was missing such a feature.
What I expect as the result is the "cartesian product" of the strings.




我也一直在考虑它。我也喜欢列表:



I''ve been thinking of it as well. I''d like it for lists too:

range(3)** 2
range(3)**2



[(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1) ),(2,2)]


-

Giovanni Bajo


[(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

--
Giovanni Bajo



Giovanni Bajo写道:

Giovanni Bajo wrote:
Christoph Zwerschke写道:
Christoph Zwerschke wrote:
有时我错过了这样的功能。
我期待的是结果是笛卡尔积。字符串。
Sometimes I was missing such a feature.
What I expect as the result is the "cartesian product" of the strings.



我一直在考虑它。我也喜欢列表:



I''ve been thinking of it as well. I''d like it for lists too:

range(3)** 2
range(3)**2


[ (0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2) ,2)]

- Giovanni Bajo


[(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

--
Giovanni Bajo




但为什么这不被解释为[0,1, 4]喜欢它在Mathematica中?


我更喜欢一个多态分布(* args)函数(或生成器

)作用于列表类对象的元组相同的大小。可以将

扩展为通过单个默认参数分发(* args [,default])

当两个类似列表的对象时插入分发表中

的大小不一样。


Kay



But why isn''t this interpreted as [0, 1, 4] like it is in Mathematica?

I would prefer a polymorphic distribute(*args) function ( or generator
) that acts on tuples of listlike objects of equal size. It could be
extended to distribute(*args[,default]) by a single default argument
that is inserted in the distribution table when two listlike objects
have not the same size.

Kay


Kay Schluehr< ka *** *******@gmx.net>写道:

...
Kay Schluehr <ka**********@gmx.net> wrote:
...
>范围(3)** 2 [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0), (2,1),(2,2)]
> range(3)**2 [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]



......但为什么这不被解释为[0,1,4],就像它是在Mathematica?


... But why isn''t this interpreted as [0, 1, 4] like it is in Mathematica?




由于范围(3)* 2是[0,1,2,0,1,2],它将是非常可怕的,痛苦的
如果** 2被解释为每个项目的正方形,则
不一致。

Alex



Since range(3)*2 is [0, 1, 2, 0, 1, 2], it would be horribly, painfully
inconsistent if **2 was interpreted as "square each item".
Alex


这篇关于一些关于笛卡儿产品的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆