创建解码算法

2024-04-23 09:43:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如何创建一个算法来解码一个数字(代码)并将其与特定类型相关联?你知道吗

例如:

0= 1 =zombie

1= 2 =horror

2= 4 =romance

3= 8 =action

4= 16 =medieval

这是我的流派列表。这样设置的原因是,假设用户输入3,那么结果会是僵尸,因为1+2=3,所以很恐怖。你知道吗

如何创建一个函数,该函数将接受一个代码(int值)并返回与之关联的类型列表。如果代码是(12),我需要函数返回列表L=[4,8]。你知道吗

到目前为止我都知道了些什么!我知道,如果用户输入12,那么12小于16(2的下一次幂),并且是前两种类型的相加。我只是不知道怎么把它翻译成我的代码。你知道吗

def _decode(self, code):
  codes=[] #need and empty list to add the values to
  #need code that will take the code value and associate it to its respective genres. 
  return codes

到目前为止,我所做的是:

Def _decode(self, code):

codes=[]

for i in range (0,10):

 i = 2**i

 if i==code:

codes.append(i)

这样做的是,如果用户输入2,2已经是2的幂,并且只能与1个genera关联,那么它只会将该数字附加到列表codes=[]中。你知道吗

如果用户输入3怎么办?我知道3比2的下一次幂小,下一次幂是4,前两个数加在一起。如何将3拆分为1和2,并将这两个值附加到codes=[]列表中?你知道吗


Tags: andtheto函数代码用户self算法
2条回答

你可以列出所有的流派

>>> genres = ['zombie', 'horror', 'romance', 'action', 'medieval']

然后用索引左移(<<)对电影进行映射

>>> codes = {1 << index : value for index, value in enumerate(genres)}
>>> codes 
{1: 'zombie', 2: 'horror', 4: 'romance', 8: 'action', 16: 'medieval'}

然后使用逐位AND查找匹配的类型

>>> user = 7    # which is 1 + 2 + 4, or 0b111
>>> [movie for key,movie in codes.items() if user & key]
['zombie', 'horror', 'romance']

你只需要确保如果你对你的键进行位异或运算,你会得到所有的1

不知羞耻地从网上偷来,修改成不用字典:

>>> genres = 'zombie', 'horror', 'romance', 'action', 'medieval'
>>> user = 7
>>> [genre for i, genre in enumerate(genres) if user & 2**i]
['zombie', 'horror', 'romance']

相关问题 更多 >