Đảo ngược các từ trong một chuỗi Python mà không cần sử dụng chức năng

Chúng tôi được cung cấp một chuỗi làm đầu vào trong Python và nhiệm vụ của chúng tôi là đảo ngược các từ có trong chuỗi. Chúng tôi sẽ sử dụng các hàm chuỗi khác nhau trong Python để hoàn thành chương trình

Phạm vi

  • Trong bài viết này, chúng ta sẽ tìm hiểu cách đảo ngược các từ của một chuỗi được nhập làm đầu vào trong Python
  • Chúng ta sẽ nghiên cứu cách triển khai các hàm chuỗi tích hợp sẵn của Python như split[], Reverse[] và join[] trong chương trình của chúng ta để đảo ngược các từ trong một chuỗi

Làm thế nào để đảo ngược các từ trong một chuỗi Python?

Trong Python, một chuỗi được tạo bằng cách đặt một dòng ký tự bên trong dấu nháy đơn, nháy kép hoặc nháy ba. Đảo ngược từ trong một chuỗi có nghĩa là chúng ta phải đảo ngược vị trí của tất cả các từ trong chuỗi đã cho

ví dụ

Chúng ta hãy xem xét một số ví dụ

Input: Hello World
Output: World Hello

Input: I love Programming
Output: Programming love I

Phương pháp - 1. Đảo ngược các từ riêng lẻ và sau đó đảo ngược toàn bộ chuỗi

Trực giác của cách tiếp cận này là trước tiên đảo ngược từng từ có trong chuỗi riêng lẻ,

Ví dụ.
Tôi thích viết mã, tôi là gnidoc. Bây giờ, chúng ta phải đảo ngược toàn bộ chuỗi để có được kết quả mong muốn, trong trường hợp của ví dụ này sẽ được mã hóa như I.

Bây giờ chúng ta hãy xem cách triển khai phương pháp này để đảo ngược các từ trong một chuỗi bằng Python

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]

đầu ra

phân tích độ phức tạp

Vì chúng ta duyệt qua toàn bộ chuỗi một lần để đảo ngược các từ trong chuỗi, Độ phức tạp Thời gian là O[n]O[n]O[n], trong đó nnn là kích thước của chuỗi

Mặc dù cần có một không gian phụ trợ để lưu trữ chuỗi theo cách ngược lại, Độ phức tạp của Không gian là O[1]O[1]O[1]

Trong bài viết này, bạn sẽ học, Trong python, cách đảo ngược thứ tự các từ trong chuỗi. Xin lưu ý rằng ở đây chúng tôi không đảo ngược ký tự

Ví dụ

# Program to explain reverse Word in String or Sentence
# Using for split[] function

# Define a function
def reverse_word[string]:
    # Split string with blank space
    # And convert to list
    rlist=string.split[]

    # Reverse list using reverse function
    rlist.reverse[]

    # Convert list to string with space
    return " ".join[rlist]

string = 'This is Our Website Stechies'

# Print Original and Reverse string
print['Original String: ', string]
print['Reverse String: ', reverse_word[string]]

đầu ra.  

Original :  This is Our Website Stechies
Reverse :  Stechies Website Our is This

Giải trình

Trong ví dụ trên, đầu tiên, chúng ta chuyển đổi một chuỗi thành danh sách bằng hàm split[], sau đó đảo ngược thứ tự của danh sách bằng hàm reverse[] và chuyển đổi danh sách ngược thành chuỗi bằng phương thức join[]

Bạn chỉ ra sự đảo ngược của hai chuỗi.

Original :  This is Our Website Stechies
Reverse :  Stechies Website Our is This
4 và
Original :  This is Our Website Stechies
Reverse :  Stechies Website Our is This
5. Nhưng mã của bạn chỉ có thể đảo ngược một chuỗi. Nếu bạn cũng muốn đảo ngược chuỗi khác, bạn phải sao chép mã

Thay vào đó, hãy viết một hàm. Chúng có thể được gọi nhiều lần

def reverse_words[sentence]:
    .. your code here ...
    return final_str

str1 = "John Doe"
reversed1 = reverse_words[str1]
print[f"string: {str1}\nlen: {len[str1]}"]
print[f"Reversed_string: {reversed1}\nlen: {len[reversed1]}"]

str2 = "Happy new year! 2022"
reversed2 = reverse_words[str2]
print[f"string: {str2}\nlen: {len[str2]}"]
print[f"Reversed_string: {reversed2}\nlen: {len[reversed2]}"]

Khi viết hàm, hãy sử dụng gợi ý kiểu và

def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
0 để cung cấp thêm thông tin về cách sử dụng hàm

def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str

Với định nghĩa hàm trên,

def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
1 sẽ mô tả hàm giống như cách mà
def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
2 mô tả hàm in

Ngoài ra, văn bản

def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
3 trong
def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
4 có thể được sử dụng để kiểm tra, thông qua mô-đun
def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
5

def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
6 là gì?

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
3

"Bộ đếm" bắt đầu từ 0. Tại không gian đầu tiên, nó tăng lên 1 và một hành động được thực hiện. Ở khoảng trống thứ hai và bất kỳ khoảng trống nào tiếp theo, nó tăng lên 2 và ngay lập tức được đặt lại thành 1. Vì nó chỉ có thể nhận các giá trị 0, 1 hoặc 2 nên nó không thực sự là một bộ đếm

Có vẻ như bạn đang cố gắng làm điều gì đó khác biệt ở những câu thơ đầu tiên ở bất kỳ khoảng trống nào tiếp theo. Một "cờ" boolean mang tính mô tả hơn trong những trường hợp này

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
4

def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
7,
def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
8 và
def reverse_words[sentence: str] -> str:
    """
    Reverse the words of a string.

    >>> reverse_words["John Doe"]
    'Doe John'

    >>> reverse_words["Happy new year! 2022"]
    '2022 year! new Happy'
    """

    .. your code here ...

    return final_str
9 đều giống nhau không phải là tên biến mô tả.

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
30 có vẻ mang tính mô tả hơn, nhưng nó được sử dụng trong các câu như

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
31, có nghĩa là giá trị của nó không thực sự là "cuối cùng", vì vậy, một lần nữa, nó cũng không phải là tên tốt nhất

# Program to explain reverse Word in String or Sentence
# Using for split[] function

# Define a function
def reverse_word[string]:
    # Split string with blank space
    # And convert to list
    rlist=string.split[]

    # Reverse list using reverse function
    rlist.reverse[]

    # Convert list to string with space
    return " ".join[rlist]

string = 'This is Our Website Stechies'

# Print Original and Reverse string
print['Original String: ', string]
print['Reverse String: ', reverse_word[string]]
0

Sử dụng

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
32 trong vòng lặp

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
33 không được tán thành trong giới Python lịch sự. Nếu

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
34 được yêu cầu trong phần thân của vòng lặp, thì nên ưu tiên sử dụng

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
35

# Program to explain reverse Word in String or Sentence
# Using for split[] function

# Define a function
def reverse_word[string]:
    # Split string with blank space
    # And convert to list
    rlist=string.split[]

    # Reverse list using reverse function
    rlist.reverse[]

    # Convert list to string with space
    return " ".join[rlist]

string = 'This is Our Website Stechies'

# Print Original and Reverse string
print['Original String: ', string]
print['Reverse String: ', reverse_word[string]]
5

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
36 được thực thi trên mỗi lần lặp không gian của vòng lặp. Nếu chuỗi của bạn rất, rất dài, đây có thể là nguyên nhân dẫn đến sự kém hiệu quả. Nó đang kiểm tra phần cuối của chuỗi, điều này xảy ra ở cuối vòng lặp. Tại sao không di chuyển mã kết thúc vòng lặp này ra khỏi vòng lặp?

# Program to explain reverse Word in String or Sentence
# Using for split[] function

# Define a function
def reverse_word[string]:
    # Split string with blank space
    # And convert to list
    rlist=string.split[]

    # Reverse list using reverse function
    rlist.reverse[]

    # Convert list to string with space
    return " ".join[rlist]

string = 'This is Our Website Stechies'

# Print Original and Reverse string
print['Original String: ', string]
print['Reverse String: ', reverse_word[string]]
7

Bằng cách loại bỏ phép thử

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
37 trong thân vòng lặp, chúng tôi thấy rằng chúng tôi không còn cần biến

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
34 nữa, do đó,

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
35 là không cần thiết và vòng lặp

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
33 có thể được đơn giản hóa hơn nữa

Original :  This is Our Website Stechies
Reverse :  Stechies Website Our is This
2

Xử lý mã của bạn [và sửa đổi ở trên của tôi] phải xử lý trường hợp đặc biệt của một từ riêng biệt với nhiều từ. Lý do là các từ kết thúc bằng cả dấu cách AND ở cuối chuỗi. Chúng tôi có thể giải quyết vấn đề này bằng cách cố ý thêm một khoảng trắng vào cuối chuỗi trước khi quá trình xử lý bắt đầu

def reverseWord[s, start, end]:
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end = end - 1

s = "I love Programming"

# convert string to a list of characters
s = list[s]
# to keep track of where each word starts
start = 0

while True:

    try:
        # find space
        end = s.index[' ', start]
        # Call reverseWord for each word
        reverseWord[s, start, end - 1]
        #update start variable
        start = end + 1

    # for the last word in string ValueError is returned
    except ValueError:
        # reverse the last word
        reverseWord[s, start, len[s] - 1]
        break

# reverse the entire list
s.reverse[]

# convert the character list back to string
s = "".join[s]

print[s]
41

Cảnh báo bổ sung này đảm bảo các từ sẽ luôn kết thúc bằng khoảng trắng và đơn giản hóa mã trong vòng lặp. Xử lý bổ sung nhỏ ở cuối có thể cần thiết để loại bỏ khoảng trống thừa trong đầu ra, tùy thuộc vào việc triển khai chính xác

Làm cách nào để đảo ngược một từ trong Python mà không cần sử dụng chức năng đảo ngược?

Chúng ta sẽ nối chuỗi rỗng str với giá trị của một biến lặp sẽ đảo ngược chuỗi từng ký tự một. Đến cuối vòng lặp for, str sẽ chứa chuỗi đã cho theo thứ tự ngược lại

Làm cách nào để đảo ngược chuỗi mà không sử dụng phương thức chuỗi?

Bạn có thể đảo ngược Chuỗi theo nhiều cách mà không cần sử dụng hàm reverse[]. Sử dụng đệ quy - Đệ quy là quá trình lặp lại các mục theo cách tự tương tự. .
chuyển đổi nó thành một mảng
Đảo ngược các phần tử của mảng
Tạo một Chuỗi khác bằng cách sử dụng mảng kết quả

Chủ Đề