字轮班 [英] word shifts

查看:36
本文介绍了字轮班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


我制作了一个带有单词列表的功能(每行一个单词,文本文件)

并搜索所有单词

彼此转移的列表。 ''abc''转移1是''bcd''


请看一看,告诉我这是否是一个可行的解决方案。


def shift(word,amt):

ans =''''

用于单词中的字母:

ans = ans + chr( (ord(letter) - ord(''a'')+ amt)%26 + ord(''a''))

返回ans


def fileshift(x):

fin = open(x)

d = {}

for line in fin:

d [line.strip()] = [1]

for i in range(1,26):

ite = shift(line.strip(), i)

if d in d:

print ite

任何提示/建议/批评非常感谢..我正在努力

自学Python(并且还在开始)并且会喜欢任何有用的

信息。


谢谢!

Hello,

I made a function that takes a word list (one word per line, text file)
and searches for all the words in the list that are ''shifts'' of
eachother. ''abc'' shifted 1 is ''bcd''

Please take a look and tell me if this is a viable solution.

def shift(word, amt):
ans = ''''
for letter in word:
ans = ans + chr((ord(letter) - ord(''a'') + amt) % 26 + ord(''a''))
return ans

def fileshift(x):
fin = open(x)
d = {}
for line in fin:
d[line.strip()] = [1]
for i in range(1, 26):
ite = shift(line.strip(), i)
if ite in d:
print ite
Any tips/suggestions/critiques greatly appreciated.. I''m trying to
teach myself Python (and still beginning) and would love any helpful
info.

thanks!

推荐答案

En Sun,2008年5月4日02:17:07 -0300,dave< sq ************* @invalid.comescribió:
En Sun, 04 May 2008 02:17:07 -0300, dave <sq*************@invalid.comescribió:

您好,


我创建了一个带有单词列表的功能(每行一个单词,文本文件)

并搜索列表中的所有单词相互之间是'b'b'的''转变''。 ''abc''转移1是''bcd''


请看一看,告诉我这是否是一个可行的解决方案。


def shift(word,amt):

ans =''''

用于单词中的字母:

ans = ans + chr( (ord(letter) - ord(''a'')+ amt)%26 + ord(''a''))

返回ans


def fileshift(x):

fin = open(x)

d = {}

for line in fin:

d [line.strip()] = [1]

for i in range(1,26):

ite = shift(line.strip(), i)

if d in d:

print ite


任何提示/建议/批评都非常感谢..我''我试图用
自学Python(并且还在开始)并且会喜欢任何有用的

信息。
Hello,

I made a function that takes a word list (one word per line, text file)
and searches for all the words in the list that are ''shifts'' of
eachother. ''abc'' shifted 1 is ''bcd''

Please take a look and tell me if this is a viable solution.

def shift(word, amt):
ans = ''''
for letter in word:
ans = ans + chr((ord(letter) - ord(''a'') + amt) % 26 + ord(''a''))
return ans

def fileshift(x):
fin = open(x)
d = {}
for line in fin:
d[line.strip()] = [1]
for i in range(1, 26):
ite = shift(line.strip(), i)
if ite in d:
print ite
Any tips/suggestions/critiques greatly appreciated.. I''m trying to
teach myself Python (and still beginning) and would love any helpful
info.



首先,看一下代码,你很多次都在评估line.strip();我会避免它。

看起来你只是为了键使用字典 - 这里的集合类型更合适(参见 http://docs.python.org/lib/types-set.html )。在任何情况下,我都会使用像None这样的值而不是[1]

但是我会使用不同的算法。我没有为给定的单词生成所有可能的移位,而是从每个先前的单词中减去新读取的单词(这里,减去两个单词意味着将字符代码减去对应的位置,模26)。换句话时,所有位置都有相同的数字。


-

Gabriel Genellina

First, looking at the code, you''re evaluating line.strip() a lot of times; I''d avoid it.
Looks like you''re using a dictionary just for the keys - the set type is more adequate here (see http://docs.python.org/lib/types-set.html ). In any case, I''d use a value like None instead of [1]
But I''d use a different algorithm. Instead of generating all posible shifts for a given word, I''d substract the newly read word from each previous words (here, "substract two words" means substract the character code for corresponding positions, modulo 26). Shifted words, when substracted, have the same number on all positions.

--
Gabriel Genellina


5月4日凌晨2点04分,Gabriel Genellina < gagsl -... @ yahoo.com.arwrote:
On May 4, 2:04*am, "Gabriel Genellina" <gagsl-...@yahoo.com.arwrote:

En Sun,2008年5月4日02:17:07 -0300,dave< squareswallo .. 。@invalid.comescribió:
En Sun, 04 May 2008 02:17:07 -0300, dave <squareswallo...@invalid.comescribió:

你好,
Hello,


我做了一个函数单词列表(每行一个单词,文本文件)

并搜索列表中所有单词$ shift的单词。 *''abc''移位1是''bcd''
I made a function that takes a word list (one word per line, text file)
and searches for all the words in the list that are ''shifts'' of
eachother. *''abc'' shifted 1 is ''bcd''


请看看并告诉我这是否是一个可行的解决方案。
Please take a look and tell me if this is a viable solution.


* def shift(word,amt):

* * ans =''''

* *用于单词中的字母:

* * * * * * ans = ans + chr((ord(letter) - ord(''a'')+ amt)%26 + ord(''''))

* * return ans
*def shift(word, amt):
* *ans = ''''
* *for letter in word:
* * * * * *ans = ans + chr((ord(letter) - ord(''a'') + amt) % 26 + ord(''a''))
* *return ans


def fileshift(x):

* * fin = open(x)

* * d = {}

* * for line in fin:

* * * * * * d [line.strip()] = [1]

* * * * * *我在范围内(1,26):

* * * * * * * * * * ite = shift(line.strip(),i)

* * * * * * * * * * if if in d:

* * * * * * * * * * * * * * print ite
def fileshift(x):
* *fin = open(x)
* *d = {}
* *for line in fin:
* * * * * *d[line.strip()] = [1]
* * * * * *for i in range(1, 26):
* * * * * * * * * *ite = shift(line.strip(), i)
* * * * * * * * * *if ite in d:
* * * * * * * * * * * * * *print ite


任何提示/建议/批评非常感谢..我''我想要自己学习Python(并且还在开始),并且会喜欢任何有用的

信息。
Any tips/suggestions/critiques greatly appreciated.. I''m trying to
teach myself Python (and still beginning) and would love any helpful
info.



首先,查看代码,你正在评估line.strip()很多次;我会避免它。

看起来你只是为了键使用字典 - 这里的集合类型更合适(参见http://docs.python.org/lib/types-set.html)。在任何情况下,我都会使用像None这样的值而不是[1]

但是我会使用不同的算法。我没有为给定的单词生成所有可能的移位,而是从每个先前的单词中减去新读取的单词(这里,减去两个单词意味着将字符代码减去对应的位置,模26)。在减去时,移位的单词在所有位置上具有相同的数字。


First, looking at the code, you''re evaluating line.strip() a lot of times;I''d avoid it.
Looks like you''re using a dictionary just for the keys - the set type is more adequate here (seehttp://docs.python.org/lib/types-set.html). In any case, I''d use a value like None instead of [1]
But I''d use a different algorithm. Instead of generating all posible shifts for a given word, I''d substract the newly read word from each previous words (here, "substract two words" means substract the character code for corresponding positions, modulo 26). Shifted words, when substracted, have the same number on all positions.



更快的算法是为每个单词创建一个''键'',定义为ord差异的

元组(模26) )连续字符。例如,

''acf''的关键是(2,3); ''c''在''''之后是2个位置,在''c''之后是''''3 b / b
位置。移位的单词(只有这些)具有相同的键。

这是一个简单的实现,生成所有列表

等同移位的单词:
<来自集合的
导入defaultdict


def iter_shifted(单词):

key2shifted = defaultdict(list)

单词中的单词:

ords = map(ord,word)

key = tuple((ords [i] -ords [i-1])%26

for x in xrange(1,len(ords)))

key2shifted [key] .append(word)

for shift2shifted。 itervalues():

如果len(转移)1:

收益率转移


如果__name__ ==''__ main__'' :

words =''abc bef jas cba cde zab azy hkl''。split()

for it in iter_shifted(words):

打印转移


#***输出***

#[''bef'',''hkl'']

#[''abc'',''cde'',''zab'']

#[''cba'',''azy'' ]


A faster algorithm is to create a ''key'' for each word, defined as the
tuple of ord differences (modulo 26) of consecutive characters. E.g.
the key of ''acf'' is (2,3); ''c'' is 2 positions after ''a'' and ''f'' 3
positions after ''c''. Shifted words (and only these) have the same key.
Here''s a straightforward implementation that generates all the lists
of equally-shifted words:

from collections import defaultdict

def iter_shifted(words):
key2shifted = defaultdict(list)
for word in words:
ords = map(ord,word)
key = tuple((ords[i]-ords[i-1]) % 26
for i in xrange(1,len(ords)))
key2shifted[key].append(word)
for shifted in key2shifted.itervalues():
if len(shifted) 1:
yield shifted

if __name__ == ''__main__'':
words = ''abc bef jas cba cde zab azy hkl''.split()
for shifted in iter_shifted(words):
print shifted

# *** output ***
#[''bef'', ''hkl'']
#[''abc'', ''cde'', ''zab'']
#[''cba'', ''azy'']


dave写道:
dave wrote:

我创建了一个带字列表的函数(每行一个字,文本文件)

并搜索列表中所有单词的'shift''

海誓山盟。 ?*''abc''转移1是''bcd''


请看一下,告诉我这是否是一个可行的解决方案。


?* def shift(word,amt):

?*?*?*?*?*?*?*?* ans =''''

?*?*?*?*?*?*?*?*用于单词中的字母:

?*?*?*?*?*?*?*?*?*?* ?*?*?*?*?*?* ans = ans + chr((ord(letter) - ord(''a'')+ amt)%26 +
I made a function that takes a word list (one word per line, text file)
and searches for all the words in the list that are ''shifts'' of
eachother. ?*''abc'' shifted 1 is ''bcd''

Please take a look and tell me if this is a viable solution.

?*def shift(word, amt):
?*?*?*?*?*?*?*?*ans = ''''
?*?*?*?*?*?*?*?*for letter in word:
?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*ans = ans + chr((ord(letter) - ord(''a'') + amt) % 26 +



ord(''a''))

ord(''a''))


?*?*?*?*?*?*?*?* return ans


def fileshift(x):

?*?*?*?*?*?*?*?* fin = open(x)

?*?*?*?*?*?*?*?* d = {}

?*?*?*?*?*?*?*?* for line in fin:

?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?* d [line.strip()] = [1]

?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*表示i在范围内(1 ,26):

?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?* ?*?*?*?*?*它e = shift(line.strip(),i)

?*?*?*?*?*?*?*?*?*? *?*?*?*?*?*?*?*?*?*?*?*?*?* * *如果迭代在d:

?*?*?*?* ?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?* ?*?*?*?*?*?*?* print ite


任何提示/建议/批评非常感谢..我正在努力

自学Python(并且还在开始)并且会喜欢任何有用的

信息。
?*?*?*?*?*?*?*?*return ans

def fileshift(x):
?*?*?*?*?*?*?*?*fin = open(x)
?*?*?*?*?*?*?*?*d = {}
?*?*?*?*?*?*?*?*for line in fin:
?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*d[line.strip()] = [1]
?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*for i in range(1, 26):
?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*it e = shift(line.strip(), i)
?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*if ite in d:
?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?*?* ?*?*?*?*?*?*?*print ite
Any tips/suggestions/critiques greatly appreciated.. I''m trying to
teach myself Python (and still beginning) and would love any helpful
info.



我的想法:


将open()调用移出fileshift()并使其与任意
iterables。

在字典中存储该单词的标准化版本。如果

中的每个单词都保证dict以a开头。你可以将

测试的数量减少到一个。

如果你有很多单词,你可以建立一个快速shift()函数基于

str.translate()。

使用和不使用文件名参数调用以下脚本:


从字符串导入ascii_lowercase as chars,maketrans


tables = [maketrans(chars,chars [i:] + chars [:i])for i in range(26)]


def shift(word,n):

返回word.translate(表[n%26])


def normalize(word):

a = word [0]

返回班次(word,ord(a) - ord(a))


def findshifted (单词):

d = {}

单词中的单词:

d.setdefault(normalize(word),[])。append (字)

返回d

如果__name__ ==" __ main __":

import sys

args = sys.argv [1:]

if args:

words =(line.strip()for line in open(args [0]))

else:

impo rt随机

sample =""" \

alpha

beta

gamma
delta

""" .split()


words = sample + [shift(random.choice(sample), random.randrange(26))

for _ in range(10)]


items = findshifted(words).items()

items.sort()

for k,v in items:

print k," - >",v


彼得

My ideas:

Move the open() call out of fileshift() and have it working with arbitrary
iterables.
Store a normalized version of the word in the dictionary. if every word in
the dict is guaranteed to start with an "a" you can reduce the number of
tests to one.
If you have many words you can build a fast shift() function based on
str.translate().

Invoke the following script both with and without a filename argument:

from string import ascii_lowercase as chars, maketrans

tables = [maketrans(chars, chars[i:] + chars[:i]) for i in range(26)]

def shift(word, n):
return word.translate(tables[n%26])

def normalize(word):
a = word[0]
return shift(word, ord("a") - ord(a))

def findshifted(words):
d = {}
for word in words:
d.setdefault(normalize(word), []).append(word)
return d
if __name__ == "__main__":
import sys
args = sys.argv[1:]
if args:
words = (line.strip() for line in open(args[0]))
else:
import random
sample = """\
alpha
beta
gamma
delta
""".split()

words = sample + [shift(random.choice(sample), random.randrange(26))
for _ in range(10)]

items = findshifted(words).items()
items.sort()
for k, v in items:
print k, "-->", v

Peter


这篇关于字轮班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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