Warm tip: This article is reproduced from serverfault.com, please click

Cut m and n letters from end of string, then find number of turns to get back original string

发布于 2020-05-29 09:13:09

Question: Given are a string and m and n.

input 1: original string

input 2: m (less than length of string): cut m alphabets from end of string and then add to begining of string.

input 3: n (less than length of string) : cut n alphabets from end of string obtained from above step and then add to begining of that string.

This process is continued, need to find out the number turns it takes to get back original string.

def harry(str, m, n):
    le = len(str)
    org = str.upper()
    str = str.upper()
    turn = 0
    for i in str:
        str3 = str[-m:] # last n letters
        str = str.replace(' ', '')[:-m]
        str = str3 + str
        print(str)
        if org != str:
            turn = turn + 1
            str4 = str[-n:]
            str = str.replace(' ', '')[:-n]
            str= str4 + str
            print(str)
            turn = turn + 1
        if org == str:
            break
    print(turn)

str = input("Enter the string")
m=int(input("Enter the value of m"))
n=int(input("Enter the value of n"))
harry(str, m, n)

output obtained:

Enter the stringarya
Enter the value of m1
Enter the value of n2
AARY
RYAA
ARYA
2

original output to be obtained:

3 

(It takes 3 turns to get back original string Arya.)

I am getting output for all words except words like this, especially when same letter occurs consecutively. Please help me out with this.

Questioner
Sree
Viewed
0
Pygirl 2020-06-02 19:44:59

Actually you will take atleast one step to see whether they are equal or not. So your turn should start from 1.

See: https://ide.geeksforgeeks.org/Hw4AWx1O95

def harry(str, m, n):
    le = len(str)
    org = str.upper()
    str = str.upper()
    turn = 1 # <--------Here
    for i in str:
        str3 = str[-m:] # last n letters
        str = str.replace(' ', '')[:-m]
        str = str3 + str
        print(str)
        if org != str:
            turn = turn + 1
            str4 = str[-n:]
            str = str.replace(' ', '')[:-n]
            str= str4 + str
            print(str)
        if org == str:

            break
        turn = turn + 1 #< --------------- Here 

    print(turn)

str = input("Enter the string\n")
m=int(input("Enter the value of m\n"))
n=int(input("Enter the value of n\n"))
harry(str, m, n)