python - 确定两个数组是否是彼此的旋转版本

标签 python python-3.x algorithm

在JAVA中已经提出了类似的问题,但是有人可以帮助我改进代码:并解释我的代码的时间复杂度和空间复杂度是多少。我的代码检查两个数组是否是彼此的旋转版本:

列表1 = [1,2,3,4,5,6,7]

list2b = [4, 5, 6, 7, 1, 2, 3]

is_rotation(list1, list2b) 应返回 True。

list2c = [4, 5, 6, 9, 1, 2, 3]

is_rotation(list1, list2c) 应返回 False。

我的代码:

def is_rotation (list1,list2):

    i = 0
    j = 0
    k = 0

    result = True

    if len(list1) != len(list2):
        return False  

    while i < len(list1) -1 and j < len(list1) -1:

        if list1[i] == list2[j]:
            i = i +1
            j = j +1
            break
        elif list1[i] > list2[j]:
            j = j +1
        else:
            i = i +1
    else:
        return False

    for l in range(i,len(list1)):

        if i == j:
            if list1[i] != list2[j]: 
                return False
        elif list1[i] != list2[j] or list2[i] != list1[k]:
            return False
        else:
            i = i +1
            j = j +1
            k = k +1

    return result

最佳答案

有点古怪的方式:

def is_rotation(lst1, lst2):
    if(len(lst1)==len(lst2)):
        return (str(lst1)[1:-1] in str(lst2+lst2)) & (str(lst2)[1:-1] in str(lst1+lst1)) 
    else:
        return False

它是如何工作的:

(1) 检查两个列表的长度是否相同,如果不同则返回False

(2) 如果这样做,将第一个列表转换为 string,删除最外面的括号(通过删除第一个和最后一个字符 - 你可以在那里做任何括号,不仅仅是方括号,它可以也是一个元组)。

(3) lst2+lst2 将返回按顺序重复的 lst2 的所有元素(因此一个接着一个 lst2)。然后转换为字符串,它只会返回 list

的字符串格式

(4) 根据评论 - 为了处理极端情况 - 我们应该检查两种方式,因为如果 lst1lst2 的旋转版本,则 lst2lst1

的旋转版本

测试

print(is_rotation([561, 1, 1, 1, 135], [1, 1, 1, 1, 1]))
#outputs False
print(is_rotation([[1,2,3,4], 2, 3, 4], [1, 2,3,4]))
#outputs False
print(is_rotation([1, 2, 3, 4, 5], [4, 5, 1, 2, 3]))
#outputs True

关于python - 确定两个数组是否是彼此的旋转版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60470909/

相关文章:

Python - While 循环进入无限循环。我究竟做错了什么?

python /POpen/gpg : Supply passphrase and encryption text both through stdin or file descriptor

python-3.x - 如何在处理 secret API 时使用 Python 列出 Databricks 范围

python - Python 3.8 中 pyFFTW (scipy.fftpack) 导入错误

python - Alembic 修订版自动生成错误的配置读取

java - 在 Java 中使用数组添加两个 10 位数字

java - 围绕封闭三次样条绘制渐变

python - 在Python字典中的列表中搜索值

python - 无聊的AWK高手能不能帮忙转换一下这个Python程序呢?

javascript - 从给定节点查找树中父节点的路径