<jupyter_start><jupyter_text>``` ASSIGNMENT METADATAassignment_id: "6-1"``` 練習文字列のリストが変数 `strings` に与えられたとき、それぞれの文字列の長さからなるリストを返す内包表記を記述してください。`strings = ['The', 'quick', 'brown']` のとき、結果は `[3, 5, 5]` となります。``` EXERCISE METADATAexercise_id: "StringLengths"```<jupyter_code>%%solution
strings = ['The', 'quick', 'brown']
def string_lengths(strings):
    """ # BEGIN PROMPT
    return [ここに内包表記を書く]
    """ # END PROMPT
    # BEGIN SOLUTION
    return [len(s) for s in strings]
    # END SOLUTION<jupyter_output><empty_output><jupyter_text>以下のセルを実行して、True が表示されることを確認してください。<jupyter_code>print(string_lengths(['The', 'quick', 'brown']) == [3, 5, 5])
%%inlinetest AutograderTest_StringLenghts

assert 'string_lengths' in globals(), "Did you define 'string_length' in the solution cell?"
assert str(string_lengths.__class__) == "<class 'function'>", f"Did you define 'string_lengths' as a function? There was a {string_lengths.__class__} instead"
assert string_lengths(['abc']) is not None, "Did you forget to return a value?"

assert len(string_lengths(['abc'])) == 1, "Did you return a list of correct length?"
assert len(string_lengths(['abc', 'abcde', 'a'])) == 3, "Did you return a list of correct length?"
assert len(string_lengths([])) == 0, "Did you handle empty list correctly?"

assert string_lengths([]) == [], "Did you handle empty list correctly?"
assert string_lengths(['']) != [1], "Did you computed length of the strings correctly?"
assert string_lengths(['']) == [0], "Did you handle empty string correctly?"
assert string_lengths(['abc']) == [3], "Did you handle single string correctly?"
assert string_lengths(['abc', 'abc']) == [3, 3], "Did you handle single string correctly?"

assert string_lengths(['The', 'quick', 'brown']) == [3, 5, 5], "Did you try the example? Try string_lengths(['The', 'quick', 'brown'])"
# Check the canonical solution
result, log = %autotest AutograderTest_StringLenghts
assert result.results['passed']
report(AutograderTest_StringLenghts, results=result.results)
%%submission
def string_lengths(strings):
    return [len(strings) for s in strings]
result, log = %autotest AutograderTest_StringLenghts
assert not result.results['passed']
report(AutograderTest_StringLenghts, results=result.results)<jupyter_output><empty_output><jupyter_text>練習コンマで区切られた10進数からなる文字列が変数 `str1` に与えられたとき、それぞれの10進数を数に変換して得られるリストを返す内包表記を記述してください。`str1 = '123,45,-3'` のとき、結果は `[123, 45, -3]` となります。なお、コンマで区切られた10進数からなる文字列を、10進数の文字列のリストに変換するには、メソッド `split` を用いることができます。また、10進数の文字列を数に変換するには、**`int`** を関数として用いることができます。``` EXERCISE METADATAexercise_id: "ParseInt"```<jupyter_code>%%solution
str1 = '123,45,-3'
def parse_ints(str1):
    """ # BEGIN PROMPT
    return [ここに内包表記を書く]
    """ # END PROMPT
    # BEGIN SOLUTION
    return [int(x) for x in str1.split(',')]
    # END SOLUTION<jupyter_output><empty_output><jupyter_text>以下のセルを実行して、True が表示されることを確認してください。<jupyter_code>print(parse_ints('123,45,-3') == [123, 45, -3])
%%inlinetest AutograderTest_ParseInts

assert "parse_ints" in globals(), "Did you define a function named 'parse_ints'?"
assert str(parse_ints.__class__) == "<class 'function'>", f"Did you define 'parse_ints' as a function? There was a {parse_ints.__class__} instead"
assert parse_ints('0') is not None, "Did you forget to return a value?"

assert len(parse_ints('0,0')) == 2, "Did you split the string correctly? Try parse_ints('0,0')."
assert len(parse_ints('0,0,0')) == 3, "Did you split the string correctly? Try parse_ints('0,0,0')."
assert parse_ints('0,0') == [0,0], "Did you convert the integers correctly? Try parse_ints('0,0')."
assert len(parse_ints('0')) == 1, "Did you handle a string without commas? Try parse_ints('0')."
assert parse_ints('0') == [0], "Did you convert the integers correctly? Try parse_ints('0')."
assert parse_ints('123') == [123], "Did you hanle bigger numbers correctly? Try parse_ints('123')."
assert parse_ints('123,0,0') == [123,0,0], "Did you hanle bigger numbers correctly? Try parse_ints('123,0,0')."
assert parse_ints('-123') == [-123], "Did you hanle negative numbers correctly? Try parse_ints('-123')."
assert parse_ints('-123,0,0') == [-123,0,0], "Did you hanle negative numbers correctly? Try parse_ints('-123,0,0')."
assert parse_ints('123,45,-3') == [123,45,-3], "Did you tried the example? Try parse_ints('123,45,-3')."
assert parse_ints('1,2,3,4,5,6,7,88,9') == [1,2,3,4,5,6,7,88,9], "Did you handle many elements correctly? Try a longer string"
# Check the canonical solution
result, log = %autotest AutograderTest_ParseInts
assert result.results['passed']
report(AutograderTest_ParseInts, results=result.results)
%%submission
def parse_ints(str):
    result = []
    for s in str.split(','):
        if s:
            result.append(int(s))
    return result
result, log = %autotest AutograderTest_ParseInts
assert result.results['passed']
report(AutograderTest_ParseInts, results=result.results)
%%submission
import re
def parse_ints(str):
    return [int(s) for s in re.findall(r'[0-9]+', str)]
result, log = %autotest AutograderTest_ParseInts
print(result.results)
assert not result.results['passed']
import re
assert re.search(r'negative', str(result.results['error']))
report(AutograderTest_ParseInts, results=result.results)
%%submission
import re
def parse_ints(str):
    return [int(s) for s in re.findall(r'-?[0-9]+', str)]
result, log = %autotest AutograderTest_ParseInts
assert result.results['passed']
report(AutograderTest_ParseInts, results=result.results)<jupyter_output><empty_output><jupyter_text>練習数のリストが与えらえたとき、リストの要素の分散を求める関数 `var` を内包表記と関数 `sum` を用いて定義してください。以下のセルの `...` のところを書き換えて `var` を作成してください。``` EXERCISE METADATAexercise_id: "Variance"```<jupyter_code>%%solution
import math
def var(lst):
    # BEGIN SOLUTION
    ex = sum(lst)/len(lst)
    return sum((x-ex)*(x-ex) for x in lst)/len(lst)
    # END SOLUTION<jupyter_output><empty_output><jupyter_text>上のセルで解答を作成した後、以下のセルを実行し、実行結果が `True` になることを確認してください。<jupyter_code>print(var([3,4,1,2]) == 1.25)
%%inlinetest AutograderTest_Var

assert "var" in globals(), "Did you define a function named 'var'?"
assert str(var.__class__) == "<class 'function'>", f"Did you define 'var' as a function? There was a {var.__class__} instead"
assert var([0,1,2]) is not None, "Did you forget to return a value?"

assert abs(var([1,2]) - 0.25) < 0.0001, "Did you compute variance correctly? Try var([1,2])"
assert abs(var([3,4,1,2]) - 1.25) < 0.0001, "Did you compute variance correctly? Try var([3,4,1,2])"
assert abs(var([3]) - 0) < 0.0001, "Did you handle 1-element list correctly? Try var([3])"
# Check the canonical solution
result, log = %autotest AutograderTest_Var
assert result.results['passed']
report(AutograderTest_Var, results=result.results)
%%submission
def var(lst):
    n = len(lst)
    av = sum(lst)/n
    return sum([(x - av)*(x - av) for x in lst])/n
result, log = %autotest AutograderTest_Var
assert result.results['passed']
report(AutograderTest_Var, results=result.results)
%%submission
def var(lst):
    n = len(lst)
    av = sum(lst)/n
    return sum([x*x for x in lst])/n - av*av
result, log = %autotest AutograderTest_Var
assert result.results['passed']
report(AutograderTest_Var, results=result.results) 
%%submission
import math
def var(lst):
    # Mistake in the E[x]^2 computation.
    return (sum([x*x for x in lst])-sum(lst)*sum(lst))/len(lst)
result, log = %autotest AutograderTest_Var
assert not result.results['passed']
report(AutograderTest_Var, results=result.results)<jupyter_output><empty_output><jupyter_text>練習次のような関数 `sum_lists` を作成してください。- `sum_lists` はリスト `list1` を引数とします。- `list1` の各要素はリストであり、そのリストの要素は数です。- `sum_lists` は、`list1` の各要素であるリストの総和を求め、それらの総和を足し合せて返します。ここでは、内包表記と関数 `sum` を用いて `sum_lists` を定義してください。以下のセルの `...` のところを書き換えて `sum_lists` を作成してください。``` EXERCISE METADATAexercise_id: "SumLists"```<jupyter_code>%%solution
def sum_lists(list1):
    # BEGIN SOLUTION
    return sum([sum(l) for l in list1])
    # END SOLUTION<jupyter_output><empty_output><jupyter_text>上のセルで解答を作成した後、以下のセルを実行し、実行結果が `True` になることを確認してください。<jupyter_code>print(sum_lists([[20, 5], [6, 16, 14, 5], [16, 8, 16, 17, 14], [1], [5, 3, 5, 7]]) == 158)
%%inlinetest AutograderTest_SumLists

assert "sum_lists" in globals(), "Did you define a function named 'sum_lists'?"
assert str(sum_lists.__class__) == "<class 'function'>", f"Did you define 'sum_lists' as a function? There was a {sum_lists.__class__} instead"

try:
    sum_lists([0])
    assert False, "Did you access the list in lists?"
except Exception as e:
    pass

try:
    assert sum_lists([[0,1,2]]) is not None, "Did you forget to return a value?"
except Exception as e:
    assert False, "Did you correctly handled nested lists?"

assert sum_lists([[0]]) == 0, "Did you compute the sum correctly?"
assert sum_lists([[1]]) == 1, "Did you compute the sum correctly? Try sum_lists([[1]])"
assert sum_lists([[1],[1]]) == 2, "Did you compute the sum correctly? Try sum_lists([[1],[1]])"
assert sum_lists([[1,1]]) == 2, "Did you compute the sum correctly? Try sum_lists([[1,1]])"
assert sum_lists([[1],[2,3],[4,5,6],[7,8,9,10]]) == 55, "Did you compute the sum correctly? Try sum_lists([[1],[2,3],[4,5,6],[7,8,9,10]])"
# Check the canonical solution
result, log = %autotest AutograderTest_SumLists
assert result.results['passed']
report(AutograderTest_SumLists, results=result.results)
%%submission
def sum_lists(list1):
    return sum(list1)
result, log = %autotest AutograderTest_SumLists
print(result.results)
assert not result.results['passed']
import re
assert re.search(r'nested lists', str(result.results['error']))
report(AutograderTest_SumLists, results=result.results)<jupyter_output><empty_output><jupyter_text>練習リスト `list1` と `list2` が引数として与えられたとき、次のようなリスト `list3` を返す関数 `sum_matrix` を作成してください。- `list1`, `list2`, `list3` は、3つの要素を持ちます。- 各要素は大きさ 3 のリストになっており、そのリストの要素は全て数です。- `list3[i][j]` （ただし、`i` と `j` は共に、0 以上 2 以下の整数）は `list1[i][j]` と `list2[i][j]` の値の和になっています。ここでは、内包表記を用いて`sum_matrix` を定義してください。以下のセルの `...` のところを書き換えて `sum_matrix` を作成してください。``` EXERCISE METADATAexercise_id: "SumMatrix"```<jupyter_code>%%solution
def sum_matrix(list1, list2):
    # BEGIN SOLUTION
    return [[list1[i][j] + list2[i][j] for j in range(3)] for i in range(3)]
    # END SOLUTION<jupyter_output><empty_output><jupyter_text>上のセルで解答を作成した後、以下のセルを実行し、実行結果が `True` になることを確認してください。<jupyter_code>print(sum_matrix([[1,5,3],[4,5,6],[7,8,9]], [[1,4,7],[2,5,8],[3,6,9]])==[[2, 9, 10], [6, 10, 14], [10, 14, 18]])
%%inlinetest AutograderTest_SumMatrix

assert "sum_matrix" in globals(), "Did you define a function named 'sum_matrix'?"
assert str(sum_matrix.__class__) == "<class 'function'>", f"Did you define 'sum_matrix' as a function? There was a {sum_matrix.__class__} instead"

zero = [[0,0,0], [0,0,0], [0,0,0]]
ones = [[1,1,1], [1,1,1], [1,1,1]]
twos = [[2,2,2], [2,2,2], [2,2,2]]
tens = [[10,10,10], [10,10,10], [10,10,10]]

try:
    assert sum_matrix(zero, zero) is not None, "Did you forget to return a value?"
except Exception as e:
    print(e)
    assert False, "Are you accessing elements outside of 3x3 matrix?"    

assert len(sum_matrix(zero,zero)) != 6, f"Are you adding matrices with '+'? That would create 6x3 matrix instead of element-wise sum in 3x3 matrix."
assert len(sum_matrix(zero,zero)) == 3, f"Do you return a 3x3 matrix? Got {len(sum_matrix(zero,zero))} rows."
row_lens = [len(row) for row in sum_matrix(zero,zero)]
assert row_lens == [3,3,3], f"Do you return a 3x3 matrix? Got rows of sizes {row_lens} instead of [3,3,3]."
assert sum_matrix(zero,zero) == zero, "Do you sum values correctly? Try adding zero matrices"
assert sum_matrix(zero,ones) == ones, "Do you sum values correctly? Try adding all-zero and all-one matrices"
assert sum_matrix(ones,ones) == twos, "Do you sum values correctly? Try adding all-one matrices"
assert sum_matrix([[1,2,3],[4,5,6],[7,8,9]],[[9,8,7],[6,5,4],[3,2,1]]) == tens, "Do you sum values correctly? Try adding [1,2,3],[4,5,6],[7,8,9]] matrix"
assert sum_matrix([[1,5,3],[4,5,6],[7,8,9]], [[1,4,7],[2,5,8],[3,6,9]])==[[2, 9, 10], [6, 10, 14], [10, 14, 18]], "Did you try to run example?"
# Check the canonical solution
result, log = %autotest AutograderTest_SumMatrix
assert result.results['passed']
report(AutograderTest_SumMatrix, results=result.results)
%%submission
def sum_matrix(a,b):
    return a+b
result, log = %autotest AutograderTest_SumMatrix
print(result.results)
assert not result.results['passed']
report(AutograderTest_SumMatrix, results=result.results)<jupyter_output><empty_output><jupyter_text>練習の解答<jupyter_code>strings = ['The', 'quick', 'brown']
[len(x) for x in strings]
str1 = '123,45,-3'
[int(x) for x in str1.split(',')]
def var(lst):
    n = len(lst)
    av = sum(lst)/n
    return sum([(x - av)*(x - av) for x in lst])/n
def var(lst):
    n = len(lst)
    av = sum(lst)/n
    return sum([x*x for x in lst])/n - av*av
def sum_lists(list1):
    return sum([sum(lst) for lst in list1])
def sum_matrix(list1,list2):
    return [[list1[i][j] + list2[i][j] for j in range(3)] for i in range(3)]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16511931251438655, 'fraction_numerical': 0.03790378270544004, 'mean_word_length': 6.452258433390509, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 50, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '187069', 'license': 'MIT', 'n_tokens_mistral': 5632, 'n_tokens_neox': 5278, 'n_words': 1239, 'path': '6/6-1.ipynb', 'repo_name': 'jxta/utpython_lab', 'size': '13033'}