I would like to ask you an output question through Python txt file return.

Asked 2 years ago, Updated 2 years ago, 13 views

In the txt file, mix the words that are Hoemun and the words that are not Hoemun, and separate the words with enter.

abba
gooloog
sosoassaosos
became
smilims
level
madam
mom
...

You read a text file in this way, and as a result, you print out only the words that are Hoemun, except for the words that are not Hoemun How can I print it out

Sample Output

abba
gooloog
sosoassaosos
...

I can't connect the two words, putting them in the list separately and printing them out after checking the return using stacks and queues.

def palindrome(s):
    qu = []
    st = []
    for x in s:
        if x.isalpha():
            qu.append(x.lower())
            st.append(x.lower())
    while qu:
        if qu.pop() != st.pop():
            return False
    return True

with open('Palindrome_file.txt','r') as f:
    list_file = []
    for line in f:
        list_file.append(line)

for i in len(list_file):
    print(palindrome(i))

It's not finished yet, but this is what I've organized so far. Please give us a lot of answers.

python palindrome

2022-09-22 12:30

1 Answers

There are too many palindrome-related algorithms on the Internet, but Python is easy to access by index, so it doesn't seem necessary to use stacks and queues.

Python can be accessed by index as shown below when there is a string abcd with variable s. - You can access it from the back with a symbol.

s = 'abcd'
s[0] # a
s[-1] #d
def palindrome(s):
    For i in range (len(s) //2): # Repeat half the length of the string
        if s[i]!= s[-(i+1)]: return False # If it is different from the previous character and the latter character, it is false
    If there's nothing else, it's true

Python is consistent with the etherator. What it means is that Python, if you use it for, etc., it finds out as much as possible whether it's repeatable. You need to understand this part well so that you can code concisely.

Typical examples of implementing iter are str, list, tuple, dict, file, generator. This can be repeated by the iter method on its own when it enters the iteration.

If you organize it, you don't need to save it on the list separately, you can use it right away as below.

with open('Palindrome_file.txt','r') as f:
    words = [word.rstrip() for word in if palindrome(word.rstrip())] # Remove linefeed character(\n) for rstrip()
    print(words)

In summary, it will be as follows.

def palindrome(s):
    for i in range(len(s) // 2):
        if s[i] != s[-(i + 1)]: return False
    return True

with open('Palindrome_file.txt','r') as f:
    words = [word.rstrip() for word in f if palindrome(word.rstrip())]
    print(words)


2022-09-22 12:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.