猿问

使用递归函数对整数进行随机排序

一个采用整数并对其进行随机排序的递归函数。依次从前一个数字和后面的一个数字,然后从前面的第二个和从后面的第二个数字,依次类推,直到被重新排列的数字与原始数字相同。


例如,123456将打印为162534或130将打印为103。任何帮助将不胜感激。


在字符串上,这很容易,需要整数的建议。


A = '130'


def shuffle(A):

    if len(A) <= 2:

        return A

    return (A[0] + A[-1]) + shuffle(A[1:-1])

输出:103


繁星淼淼
浏览 179回答 3
3回答

慕姐8265434

转换成字符串?A = 130def shuffle(A):&nbsp; &nbsp; A = str(A)&nbsp; &nbsp; if len(A) <= 2:&nbsp; &nbsp; &nbsp; &nbsp; return int(A)&nbsp; &nbsp; return int((A[0] + A[-1]) + str(shuffle(A[1:-1])))

PIPIONE

不转换为字符串:def shuffle(x):&nbsp; &nbsp; if x < 100:&nbsp; &nbsp; &nbsp; &nbsp; return x&nbsp; &nbsp; t = x&nbsp; &nbsp; l = 0&nbsp; &nbsp; while t > 0:&nbsp; &nbsp; &nbsp; &nbsp; t //= 10&nbsp; &nbsp; &nbsp; &nbsp; l += 1&nbsp; &nbsp; a = x // 10 ** (l-1) * 10 ** (l-1)&nbsp; &nbsp; b = (x % 10) * 10 ** (l-2)&nbsp; &nbsp; return a + b + shuffle((x - a) // 10)测试工作:>>> shuffle(123456)162534>>> shuffle(310)301

慕的地8271018

string使用slices正负索引进行迭代和使用def shuffle(phrase):&nbsp; even = 0&nbsp; odd = -1&nbsp; result = ''&nbsp; phrase = str(phrase)&nbsp; for n in range(len(phrase)):&nbsp; &nbsp; if int(n/2) == n/2:&nbsp; &nbsp; &nbsp; result = result + phrase[even]&nbsp; &nbsp; &nbsp; even += 1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; result = result + phrase[odd]&nbsp; &nbsp; &nbsp; odd += -1&nbsp; return result
随时随地看视频慕课网APP

相关分类

Python
我要回答