re.tk
re.tk

Reputation: 67

N loop string then move to the end

N loop to clone first string then move to the end of array

name = ["A" , "B", "C"]

Upvotes: 0

Views: 66

Answers (3)

Vincent Bénet
Vincent Bénet

Reputation: 1314

Here is an elegant way to do the job by writting a recursive function:

def f(N, n, result):
    if n == 0:
        return result[-1]
    else:
        return f(N, n - 1, result[1:] + [result[0]] * N)

def g(N, n, result):
    for _ in range(n):
        result = result[1:] + list(result[0]) * N
    return result[-1]

N = 2
print("N: " + str(N))
for n in range(1, 3):
    result = "".join(f(N, n, ["A" , "B", "C"]))
    last = result[-1]
    print("_" * 5)
    print("n: " + str(n))
    print("Result: " + str(result))
    print("Last: " + str(last))

Here the result:

N: 2
_____
n: 1
Result: BCAA
Last: A
_____
n: 2
Result: CAABB
Last: B

This method (f) is way slower than the other answer (g) and you are limited by recursion depth of python if n is over 997 on my computer. You can change it using sys.setrecursionlimit(xxx)

Time comparaison:

  • f: for n from 1 to 997: 2.130194664001465 s
  • g: for n from 1 to 997: 1.02400803565979 s

Upvotes: 1

Quang Minh Tran
Quang Minh Tran

Reputation: 26

maybe help you!

name = ["A" , "B", "C"]
def my_func() :
    value = input("Number of n : ")
    value = int(value)
    for i in range(value):
        # get first element then remove
        first_element = name.pop(0)
        # move to then end list name
        name.extend([first_element,first_element])
        # print current list name
        print(name)
    #print last name
    print(name[-1])

Test case:

Number of n : 2
['B', 'C', 'A', 'A']
['C', 'A', 'A', 'B', 'B']
B

Number of n : 3
['B', 'C', 'A', 'A']
['C', 'A', 'A', 'B', 'B']
['A', 'A', 'B', 'B', 'C', 'C']
C

Upvotes: 1

Bhavin Kariya
Bhavin Kariya

Reputation: 87

Try this code:

def my_func() :
    name = ["A" , "B", "C"]
    value = input("Number of n : ")
    value = int(value)
    for n in range(0, value):
        name = name[1:] + list(name[0]) * 2
        print(name)
    return name[-1]


print(my_func())

OUTPUT:

Number of n : 2
['B', 'C', 'A', 'A']
['C', 'A', 'A', 'B', 'B']
B

Upvotes: 1

Related Questions