Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Suma listy dwoma metodami
- def sum_recursive(lst):
- if not lst:
- return 0
- else:
- return lst[0] + sum_recursive(lst[1:])
- def sum_tail_recursive(lst, acc=0):
- if not lst:
- return acc
- else:
- return sum_tail_recursive(lst[1:], acc+lst[0])
- # przykładowe wywołania funkcji
- lst1 = [1, 2, 3, 4]
- lst2 = []
- print("Suma dla listy {}: {}".format(lst1, sum_recursive(lst1)))
- print("Suma dla listy {}: {}".format(lst1, sum_tail_recursive(lst1)))
- print("Suma dla listy {}: {}".format(lst2, sum_recursive(lst2)))
- print("Suma dla listy {}: {}".format(lst2, sum_tail_recursive(lst2)))
- Wariancja rekurencyjnie
- def mean_var_recursive(lst, length, total):
- if not lst:
- mean = total / length
- return mean, 0
- else:
- new_total = total + lst[0]
- new_length = length + 1
- mean, var = mean_var_recursive(lst[1:], new_length, new_total)
- new_mean = (total + mean) / new_length
- new_var = ((length - 1) * var + (lst[0] - new_mean)**2) / length
- return new_mean, new_var
- # przykładowe wywołania funkcji
- lst1 = [3, 3, 3, 3]
- lst2 = [5, 6, 7, 8, 9]
- mean1, var1 = mean_var_recursive(lst1, len(lst1), 0)
- mean2, var2 = mean_var_recursive(lst2, len(lst2), 0)
- print("Średnia i wariancja dla listy {}: {}, {}".format(lst1, mean1, var1))
- print("Średnia i wariancja dla listy {}: {}, {}".format(lst2, mean2, var2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement