2013-03-24 12 views
-3

나는 임의의 단어 파일을 가지고 있으며 그 중 일부는 문장으로되어 있고 일부는 그렇지 않습니다. 그 회문 중 일부는 3 자 이상입니다. 어떻게 계산합니까? 나는 조건을 더 좋게 만드는 방법을 궁금해. 나는 길이가 될 수 있다고 생각했지만, 나는 내 대답으로 0을 계속 지니고있다. 나는 그것이 .txt 파일을 가지고 있기 때문에 사실이 아님을 안다. 어디에서 엉망이 되었습니까?Python 3.2 - 단어를 소문자로 변환 & 적어도 3 글자의 단어 목록에있는 문장의 수

number_of_words = [] 

with open('words.txt') as wordFile: 
    for word in wordFile: 
     word = word.strip() 
     for letter in word: 
      letter_lower = letter.lower() 

def count_pali(wordFile): 
    count_pali = 0 
    for word in wordFile: 
     word = word.strip() 
     if word == word[::-1]: 
      count_pali += 1 
    return count_pali 

print(count_pali) 

count = 0 
for number in number_of_words: 
    if number >= 3: 
     count += 1 

print("Number of palindromes in the list of words that have at least 3 letters: {}".format(count)) 

답변

0

코드는 바로 루프까지 잘 보이는 : 논리의 문제가 여기에있다

for number in number_of_words: 
    if number >= 3: 
     count += 1 

. number_of_words의 데이터 구조에 대해 생각하고 실제로 파이썬에 'number> = 3'조건과 비교할 것을 요구한다면, 당신이 그것을 통해 멋지게 생각할 것이라고 생각합니다.

--- 수정보기 :

# Getting the words into a list 
# word_file = [word1, word2, word3, ..., wordn] 
word_file = open('words.txt').readlines() 

# set up counters 
count_pali, high_score = 0, 0 
# iterate through each word and test it 

for word in word_file: 

    # strip newline character 
    word = word.strip() 

    # if word is palindrome 
    if word == word[::-1]: 
     count_pali += 1 

     # if word is palindrome AND word is longer than 3 letters 
     if len(word) > 3: 
      high_score += 1 

print('Number of palindromes in the list of words that have at least 3 letter: {}'.format(high_score)) 

참고 : count_pali는 : 회문에게 HIGH_SCORE 단어의 총 수를 계산 : (단어 이상 3 개 문자 렌 있습니다 회문의 총 수를 계산) : 단어가 palindrome 인 경우 단어의 길이를 테스트합니다

행운을 비네!

+0

흠 ... 이전에 정의 된/발견 된 문장과 비교할 것입니다. 하지만 어떻게하면 다시 불러올 수 있습니까?이 루프에서 사용할 수 있고 길이가 같은 상태로 만들 수 있습니까? 내 문장의 길이는 숫자의 길이와 일치해야한다는 것을 알고 있지만 어떻게 쓰는지 확신 할 수 없습니다. – user2172079

+0

괜찮 았나. 귀하의 코드가 올바르게 이해 된 경우 : count_pali() 함수는 회문이 발견 될 때마다 증분하여 총 회문 수를 계산합니다. 그리고 ... 또한이 문장 중 얼마나 많은 글자가 3 글자 이상인지를 세고 싶습니다. 그래서 회문 테스트 후 if 문을 직접 사용해 볼 수 있습니까? 의사 코드에서는 다음과 같이 보일 것입니다 : # 위의 코드는 ... 단어 인 경우 회문 : 마지막 코멘트에 더 추가 count_pali + 1 –

+0

: 여기 '# 당신 앞의 코드를 ... 단어 인 경우 회문 : count_pali + 1 단어 이상 3 글자 이상 인 경우 long_word +1 ' 더 가깝습니까? –

0

당신은 count을 계산하기 위해 number_of_words 통해 반복하고 있지만 number_of_words는 따라서 루프

for number in number_of_words: 
    if number >= 3: 
     count += 1 

가 실행 빈 목록으로 초기화하고 그 이후 변경되지 않습니다 정확히 0 번

+0

그건 의미가 있습니다. 어떤 이유로 나는 목록에 []의 가치를 부여하는 것이 어떤 숫자이든 될 수 있다는 것을 의미한다고 생각했습니다. 그렇게 할 수있는 방법이 있습니까? 또는 무엇을 반복해야합니까? 그것은 count_pali가 될 수 없기 때문에 그것은 함수이고 wordFile은 다음과 같이 다시 열어도 작동하지 않습니다. 'with open ('words.txt') wordFile : count = 0 number 단어 개수가 = 3 인 경우 : 개수 + = 1 ' – user2172079

+0

단계별로 수행 - 먼저 모든 단어 목록을 작성한 다음 단어가 회문인지 여부를 테스트하는 함수를 작성하십시오. 3 문자 이상 있는지 확인하십시오.이 기능을 테스트하십시오. – xuanji

+0

감사합니다. 그러나 어떻게 모든 단어의 목록을 만드나요? 내가 언급하고있는 단어는 특히 처음에 열어 두는 .txt 파일에있는 단어입니다. 나는 두 개의 조건을 테스트하기 위해 또 하나의 if 루프를 만들었고 리턴 만했다. def count_pali (wordFile) : count_pali = 0 wordofword : word = word.strip() word == word [: -1] : 경우 단어> = 3 : count_pali + = 1 반환 count_pali 인쇄 ("3 친구의 민은 할 수 있습니다 : {}". 형식 (count_pali))' 미안하지만 난 정말 이것에 대해 혼란 스러웠습니다! – user2172079

0

이 아무튼에게 귀하의 질문에 직접적으로 대답하지는 않겠지 만, 여기서 우리가 마주 쳤던 몇 가지 문제를 이해하는 데 도움이 될 수 있습니다. 대부분 목록에 추가하는 방법을 볼 수 있으며 문자열, 목록 및 정수 (실제로는 할 수없는 길이)를 가져 오는 것의 차이점을 알 수 있습니다. 당신은에 코드를 얻을 수있을 것입니다, 당신이 우리의 대답을 통해 볼 때,

def step_forward(): 
    raw_input('(Press ENTER to continue...)') 
    print('\n.\n.\n.') 

def experiment(): 
    """ Run a whole lot experiments to explore the idea of lists and 
variables""" 

    # create an empty list, test length 
    word_list = [] 
    print('the length of word_list is: {}'.format(len(word_list))) 
    # expect output to be zero 

    step_forward() 

    # add some words to the list 
    print('\nAdding some words...') 
    word_list.append('Hello') 
    word_list.append('Experimentation') 
    word_list.append('Interesting') 
    word_list.append('ending') 

    # test length of word_list again 
    print('\ttesting length again...') 
    print('\tthe length of word_list is: {}'.format(len(word_list))) 

    step_forward() 

    # print the length of each word in the list 
    print('\nget the length of each word...') 
    for each_word in word_list: 
     print('\t{word} has a length of: {length}'.format(word=each_word, length=len(each_word))) 
     # output: 
     # Hello has a length of: 5 
     # Experimentation has a length of: 15 
     # Interesting has a length of: 11 
     # ending has a length of: 6 

    step_forward() 

    # set up a couple of counters 
    short_word = 0 
    long_word = 0 

    # test the length of the counters: 
    print('\nTrying to get the length of our counter variables...') 
    try: 
     len(short_word) 
     len(long_word) 
    except TypeError: 
     print('\tERROR: You can not get the length of an int') 
    # you see, you can't get the length of an int 
    # but, you can get the length of a word, or string! 

    step_forward() 

    # we will make some new tests, and some assumptions: 
    #  short_word: a word is short, if it has less than 9 letters 
    #  long_word:  a word is long, if it has 9 or more letters 

    # this test will count how many short and long words there are 
    print('\nHow many short and long words are there?...') 
    for each_word in word_list: 
     if len(each_word) < 9: 
      short_word += 1 
     else: 
      long_word += 1 
    print('\tThere are {short} short words and {long} long words.'.format(short=short_word, long=long_word)) 

    step_forward() 

    # BUT... what if we want to know which are the SHORT words and which are the LONG words? 
    short_word = 0 
    long_word = 0 
    for each_word in word_list: 
     if len(each_word) < 9: 
      short_word += 1 
      print('\t{word} is a SHORT word'.format(word=each_word)) 
     else: 
      long_word += 1 
      print('\t{word} is a LONG word'.format(word=each_word)) 

    step_forward() 

    # and lastly, if you need to use the short of long words again, you can 
    # create new sublists 
    print('\nMaking two new lists...') 
    shorts = [] 
    longs = [] 
    short_word = 0 
    long_word = 0 

    for each_word in word_list: 
     if len(each_word) < 9: 
      short_word += 1 
      shorts.append(each_word) 
     else: 
      long_word += 1 
      longs.append(each_word) 

    print('short list: {}'.format(shorts)) 
    print('long list: {}'.format(longs)) 
    # now, the counters short_words and long_words should equal the length of the new lists 
    if short_word == len(shorts) and long_word == len(longs): 
     print('Hurray, its works!') 
    else: 
     print('Oh no!') 

experiment() 

을 바라 건데, 위의 미니 실험을 검사 :

아래의 코드를 실행 시도하고 무슨 일이 일어나고 있는지 검사 당신이 필요로하는 것을하십시오 :)