반응형
# Question:
# Write a program that accepts a sentence and calculate the number #of letters and digits.
# Suppose the following input is supplied to the program:
# hello world! 123
# Then, the output should be:
# LETTERS 10
# DIGITS 3
def countingStr(sentence):
countNum = 0
countChar = 0
for i in range(len(sentence)):
if((65 <= ord(sentence[i]) and ord(sentence[i]) <= 90) or (97 <= ord(sentence[i]) and ord(sentence[i]) <= 122)):
countChar += 1
elif(48 <= ord(sentence[i]) and ord(sentence[i]) <= 59):
countNum += 1
return (countChar, countNum)
countChar, countNum = countingStr(input())
print ('LETTERS: ', countChar)
print ('DIGITS: ', countNum)
[Dictionary 자료형]
def countingStr(sentence):
letterAndNumber = {'LETTERS' : 0, 'DIGITS' : 0}
for i in range(len(sentence)):
if(sentence[i].isalpha()):
letterAndNumber['LETTERS'] += 1
elif(sentence[i].isdigit()):
letterAndNumber['DIGITS'] += 1
return letterAndNumber
promptStr = input()
table = countingStr(promptStr)
print ('LETTERS: ', table.get('LETTERS'))
print ('DIGITS: ', table.get('DIGITS'))
Reference site :
https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt
반응형
'<개인공부> - IT > [Python]' 카테고리의 다른 글
Python in operator (Regular Expression Matching) (0) | 2019.01.10 |
---|---|
What does if __name__ == “__main__”: do? (0) | 2018.09.15 |
List 자료형의 Join함수 사용하기 (0) | 2018.08.21 |
Python Dictionary 자료형 사용해보기 (0) | 2018.08.20 |
Number of Things Challenge 함수 만들기 (0) | 2018.08.20 |