본문 바로가기
<개인공부> - IT/[Python]

Python Multiple return values (Tuple, Dict)

by Aggies '19 2018. 8. 23.
반응형
# 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

[Tuple 이용]

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

반응형