C言語で今まで書いてきたプログラムをPythonに書き直すというのが今回の課題。順番に紹介します。
Hello World
# get_string and print, with concatenation
from cs50 import get_string
answer = get_string("What's your name? ")
print("hello, " + answer)
Mario Less
from cs50 import get_int
while True:
h = get_int('height: ')
if h > 0 and h < 9:
break
for i in range(h):
print(' ' * (h - 1 - i), end='')
print('#' * (i + 1))
Mario More
from cs50 import get_int
while True:
h = get_int('height: ')
if h > 0 and h < 9:
break
for i in range(h):
print(' ' * (h - 1 - i), end='')
print('#' * (i + 1), end=' ')
print('#' * (i + 1))
C言語ではこうだった…
Cash
from cs50 import get_float
# Get positive float from user
while True:
change = get_float("Change owed: ")
if change > 0:
break
# declare variables
total, count = change * 100, 0
# calculate count of coins
for x in [25, 10, 5, 1]:
while total >= x:
total -= x
count += 1
# print result
print(f"{count}")
C言語ではこうだった…
Credit
from cs50 import get_string
import re
import sys
number = get_string("NUMBER: ")
check = []
# Invalid credit card check - # of digits
# AMEX: 15-digit, MasterCard: 16-digit, and Visa: 13- and 16-digit
if (len(number)) not in (13, 15, 16):
print("INVALID")
sys.exit(1)
# if valid digits, for the length of the string
for i in range(len(number)):
if i % 2 == (-2 + len(number)) % 2:
digits = str(int(number[i]) * 2)
for j in range(len(digits)):
check.append(int(digits[j]))
else:
check.append(int(number[i]))
total = str(sum(check))
# check credit card issuer
if re.search("0$", total):
if re.search("^3(4|7)", number):
print("AMEX")
elif number[0] == str(4):
print("VISA")
elif re.search("^5(1|2|3|4|5)", number):
print("MASTERCARD")
else:
print("INVALID")
C言語ではこうだった…
Readability
from cs50 import get_string
import string
text = get_string('Text: ')
letters = 0
words = 1
sentences = 0
for letter in text:
# Count number of sentences
if letter == '!' or letter == '?' or letter == '.':
sentences += 1
# Continue the search
elif letter in string.punctuation:
continue
# Count number of words
elif letter in string.whitespace:
words += 1
# Count number of letters
else:
letters += 1
# Check
# print('letters: ' + str(letters))
# print('words: ' + str(words))
# print('sentences: ' + str(sentences))
# Calculate based on Coleman-Liau formula
L = (letters / words) * 100
S = (sentences / words) * 100
index = round((0.0588 * L) - (0.296 * S) - 15.8)
# Print correct grade based on liau indx
if index > 16:
print("Grade 16+")
elif index < 1:
print("Before Grade 1")
else:
print(f"Grade {index}")
DNAは次回!
未希 諒
香港在住の34歳サラリーマン。戦略家、写真家、旅人、サウナー。 2025年までに季節を選びながら世界中を飛び回る仕事をするために準備中。その道中で発見した気づきや気になる話題を中心に発信しています。2010年より旅をスタートし通算500箇所の宿に宿泊。年間の3分の1をホテルで暮らす。
Related posts
About media
Ramps Blog は、ノマドによるノマドのためのブログです。日本、香港、シンガポール、タイ、台湾のノマド生活を通じて見えた景色、特に食、カルチャー、テクノロジー、ビジネス、アート、デザインなどについて発信しています。
Recent Posts
Twitter feed is not available at the moment.