简体   繁体   English

返回字符串列表中的X + 1项

[英]Returning the X+1 item in a list of strings

So far I have a function that creates gray code then I need to make a function that will return the gray code "plus one", basically the next in sequence. 到目前为止,我有一个创建格雷码的函数,然后我需要创建一个函数,它将返回格雷码“加一”,基本上是顺序的下一个。 so if D = (0,0,1,1) I need to return (0,0,1,0) 所以如果D =(0,0,1,1)我需要返回(0,0,1,0)

I have 我有

def gray(x):
    if x:
        return ['0' + x[0]] + gray(x[1:]) + ['1' + x[0]]
    else:
        return []

def graycode(n):
    if n:
        return gray(graycode(n-1))
    else:
        return ['']

then lastly, 最后,

def GrayFinal(D):
    z = ''.join(map(str,D))
    str(z)
    if z in graycode(len(D)):
        return graycode(len(D))[z+1]
    else:
        return ['']

I can't figure out how to return the Zth+1 entry 我无法弄清楚如何返回Zth + 1条目

If I interpreted your question correctly, the heart of your question really has nothing to do with Gray codes, but rather with the more general question, " Given an element I wish to find in a Python list, how do I retrieve the next element after that? " 如果我正确地解释了你的问题,那么问题的核心与格雷码完全没有关系,而是与更一般的问题相关,“ 鉴于我希望在Python列表中找到一个元素,如何在之后检索下一个元素那个?

Unfortunately I can only come up with a rather brain-dead solution right now which is 不幸的是,我现在只能提出一个相当大脑死亡的解决方案

def next_elem(elem, input_list):
    index = input_list.index(elem)
    return input_list[index + 1]

Note that this has absolutely no support whatsoever for error checking, which I assume in your case would be done in the body of the code. 请注意,这绝对不支持错误检查,我假设在您的情况下将在代码正文中完成。 Throwing that into your code would result in the following: 将其投入您的代码将导致以下结果:

def GrayFinal(D):
    z = ''.join(map(str,D))
    try:
        return next_elem(z, graycode(len(D)))
    except ValueError:
        # Doesn't look like z was ever in the Gray code generated
        return ['']
    except IndexError:
        # The next element is beyond the last element of the array!
        return next_elem('0' + z, graycode(len(D) + 1))

Here something I heard about: 这里我听说过:

>>> bin2gray = lambda x: (x >> 1) ^ x # create graycode
>>> for i in range(10):
    print(bin(bin2gray(i))[2:].zfill(4))


0000
0001
0011
0010
0110
0111
0101
0100
1100
1101

>>> def gray2bin(g):
    bits = list(map(int, bin(g)[2:]))
    n = [0]
    for bit in bits:
        if not n[-1]:
            n.append(bit)
        else:
            n.append(1 - bit)
    return sum([n[i] << (-1 - i) for i in range(-len(n), 0)])

>>> def inc(g):
    return bin2gray(gray2bin(g) + 1)

You will need to adapt the inc function if you want it to work with strings instead of ints. 如果您希望使用字符串而不是整数,则需要调整inc函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM