2013-09-27 1 views
-1

어떻게 컴퓨터 과학자 대화 판처럼 생각하고, 연습 중 하나가 다음 요구 사항이하려면 사용하여 파이썬을 배우고 :내 파이썬 코드에 어떤 문제가 있는지 파악하는 데 도움이 필요

"에 변수에 할당을하여 예를 들어시, 연설, 케이크 구우기 지침, 영감을주는 구절 등을 포함하는 삼중 인용 문자열을 프로그래밍하십시오.

영문자 수를 계산하는 함수를 작성하십시오 z 또는 A부터 Z까지)를 입력 한 다음 문자 'e'가 얼마나 많은지 추적합니다. 함수는 다음과 같이 텍스트 분석을 인쇄해야합니다 :

텍스트에 243 자의 알파벳 문자가 포함되어 있으며 그 중 109 개 (44.8 %)는 'e'입니다. "

나는 (내가) 묻는 질문을 정확히하는 것처럼 보이지만 코드를 테스트 할 때 솔루션을 점검 할 때 결과가 달라진다.

내 코드 :

text = ''' "If the automobile had followed the same development cycle as the computer, a 
Rolls-Royce would today cost $100, get a million miles per gallon, and explode 
once a year, killing everyone inside." 
-Robert Cringely''' 

lowercase_text = text.lower() 

def charCounter(some_text): 
    e_counter = 0 
    char_counter = 0 

    for char in lowercase_text:  
     if char == 'e': 
      e_counter = e_counter + 1 
     else: 
      char_counter = char_counter + 1 

    return ("Your text contains " + str(char_counter) + " alphabetic characters, of which " + str(e_counter) + " (" + str((e_counter/char_counter) * 100) + "%)" + "are 'e'.") 

내 코드 출력 : 저자 솔루션이

def count(p): 
    lows="abcdefghijklmnopqrstuvwxyz" 
    ups="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 

    numberOfe = 0 
    totalChars = 0 
    for achar in p: 
     if achar in lows or achar in ups: 
      totalChars = totalChars + 1 
      if achar == 'e': 
       numberOfe = numberOfe + 1 


    percent_with_e = (numberOfe/totalChars) * 100 
    print("Your text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.") 


p = '''"If the automobile had followed the same development cycle as the computer, a 
Rolls-Royce would today cost $100, get a million miles per gallon, and explode 
once a year, killing everyone inside." 
-Robert Cringely''' 

count(p) 

코드 출력 : 저자가 제공하는

Your text contains 188 alphabetic characters, of which 25 (13.297872340425531%)are 'e'. 

솔루션 코드

Your text contains 166 alphabetic characters of which 25 (15.060240963855422 %) are 'e'. 

누군가 내가 뭘 잘못하고 있는지 설명해 주시겠습니까? 왜 결과에 이러한 차이가 있는지 나는 알지 못합니다.

+0

스택 오버플로에서 게시물 서식을 지정하는 방법에 대해 알아보십시오. –

답변

4

해결 방법은 문자가 실제로 영숫자인지 여부와 공백을 계산하는지 여부를 확인하지 않습니다. 또한 'e'는 총 문자 수에 추가되지 않습니다.

for char in lowercase_text:  
    if char == 'e': 
     e_counter = e_counter + 1 
    else: 
     char_counter = char_counter + 1 

그것은 다음과 같아야합니다 :

for char in lowercase_text:  
    # Check if we have an alphanumeric string and continue the loop if not 
    if not char.isalpha(): 
     continue 
    # Increment the total character counter 
    char_counter += 1 
    # Additionaly, increment the 'e' counter if we have an 'e' 
    if char == 'e': 
     e_counter += 1 
+0

저에게 문제를 설명해 주셔서 감사합니다. 귀하의 솔루션을 시도하고 이제 올바른 결과를 반환합니다. – Radu

0

당신은해야 할 일이 아닌 구두점, 숫자 및 공백을 카운트에 포함하고 있습니다.

0

를 나는 이미 해결 될의 문제에 대한 해결책 (NO downvotes가있어 바랍니다

문제에 대한 루프 당신에),이 문제를 해결하기위한 더 평범한 방법을 제시하고자합니다 (아무런 업보도 필요하지 않습니다) :

import string 

text = ''' "If the automobile had followed the same development cycle as the computer, a 
Rolls-Royce would today cost $100, get a million miles per gallon, and explode 
once a year, killing everyone inside." 
-Robert Cringely''' 

def check_character(text, character): 
    text = text.lower() 
    count_sum = len(list(c for c in text if c in string.ascii_lowercase)) 
    count_char = len(list(c for c in text if c == character)) 
    return count_sum, count_char, 100 * count_char/float(count_sum) 

char = 'e' 
result = check_character(text, char) + (char,) 

print("Your text contains {} alphabetic characters of which {} ({:.2f}%) are '{}'.".format(*result)) 
관련 문제