Python の宿題で、「正の整数を入力として取り、入力値までのすべての整数の乗算を示す乗算表を出力する」関数を作成するように求められます (while ループも使用)。
# This is an example of the output of the function
print_multiplication_table(3)
>>> 1 * 1 = 1
>>> 1 * 2 = 2
>>> 1 * 3 = 3
>>> 2 * 1 = 2
>>> 2 * 2 = 4
>>> 2 * 3 = 6
>>> 3 * 1 = 3
>>> 3 * 2 = 6
>>> 3 * 3 = 9
始め方はわかったけど、次に何をすればいいのかわからない。アルゴリズムの助けが必要です。私は学びたいので、正しいコードを書かないでください。代わりに、論理と推論を教えてください。
これが私の推論です:
- この関数は、すべての実数に、指定された値 (n) に n より 1 を掛けた値、または (n-1) を乗算する必要があります。
- この関数は、すべての実数を n(n を含む) x n の 2 倍または (n-2) に乗算する必要があります。
- この関数は、すべての実数を n(n を含む) x n の 3 倍、または (n-3) などに乗算する必要があります... n に到達するまで
- 関数が n に達すると、関数はすべての実数を n (n を含む) x n に乗算する必要があります。
- その後、関数は停止するか、while ループで「ブレーク」する必要があります。
- 次に、関数は結果を出力する必要があります
だから、これは私がこれまで持っているものです:
def print_multiplication_table(n): # n for a number
if n >=0:
while somehting:
# The code rest of the code that I need help on
else:
return "The input is not a positive whole number.Try anohter input!"
編集:みんなからの素晴らしい回答の後に私が持っているものは次のとおりです
"""
i * j = answer
i is counting from 1 to n
for each i, j is counting from 1 to n
"""
def print_multiplication_table(n): # n for a number
if n >=0:
i = 0
j = 0
while i <n:
i = i + 1
while j <i:
j = j + 1
answer = i * j
print i, " * ",j,"=",answer
else:
return "The input is not a positive whole number.Try another input!"
まだ完全には終わっていません!例えば:
print_multiplication_table(2)
# The output
>>>1 * 1 = 1
>>>2 * 2 = 4
そして、そうではありません
>>> 1 * 1 = 1
>>> 1 * 2 = 2
>>> 2 * 1 = 2
>>> 2 * 2 = 4
私は何を間違っていますか?