So the answer is, only the second and the third
are equivalent. This is a little surprising. This was kind
of a tricky question. So the reason the first one
is not, if x is seven or greater, well, then seven
mod seven has the value zero. That's not the same
as the x that we started with. And that's the
case also if we have eight. Eight module seven has
the value one. Which is different from what we started with.
When the modulo is greater than the possible value of
x, and we said, x could be only between zero and
10, well, then, the result is always the same as
x. The third question, when we map x to its character
value, and then we take the order of that, we'll
char an order inverses, so that's equivalent. You would think that
would in the other direction and the reason it doesn't is
because the input to ord must be a one letter string.
If the input's not a single character, then ord produces
an error. So let's see that in the Python interpreter, if
we print the result of ord where the input is a
number and we said x was a number between zero and
three. Well, that gives us an error. And it gives an
error, because ord expects a string of length one, but the
input was an integer. There is a function that allows us
to turn numbers into strings. And that's the str function that
takes a number and gives us a string corresponding
to that number. So let's see what str of three
gives us, that will give us the string three,
we can't see in output here that it is actually
a string, but it is a string, and we
can actually use order on the result there. When we
run this, what we get is 51, not the
three that we passed in and that's because the ord
of the character three is 51.
答えは2つ目と3つ目だけが等しくなります
これは少し意外です ちょっと引っ掛け問題でしたね
1つ目が等しくならない理由は
xが7またはそれよりも大きい時
7 % 7はゼロの値になります
これは開始したxとは異なります
8の時も同様です 8 % 7は1の値になります
これは開始したものと違います
モジュロがxの可能性のある値より大きい場合
xがゼロと10の間にあると仮定すると
結果は常にxと同じになります
3つ目の問題はxを文字の値に対応させ
その順序を用いると
逆の順序でchrします ですから同等になります
逆になると思いましたか?
そうならない理由は
ordの入力が1文字の文字列でなくては
いけないからです
入力が1文字でなかったらordはエラーを発生させます
それをPythonインタプリタで確かめてみましょう
入力が数値で
xがゼロと3の間の数値だったと仮定します
ord(3)の結果を表示するとエラーが出されます
その理由は1つの長さの文字列を求めているからです
しかし入力は整数でした
数字を文字列に変えられる関数があります
それはstr関数です
その数値に対応する文字列を与えます
str(3)で何が得られるのか確認してみましょう
文字列3が得られるはずです
出力では確認できませんがこれは実際に文字列です
ここの結果でordを使用します これを実行すると
51になります 渡した3ではありません
それは文字列3のordが51だからです