Advertisement
Rementai

Rekurencja

Apr 20th, 2023 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. Suma listy dwoma metodami
  2.  
  3. def sum_recursive(lst):
  4.     if not lst:
  5.         return 0
  6.     else:
  7.         return lst[0] + sum_recursive(lst[1:])
  8.  
  9. def sum_tail_recursive(lst, acc=0):
  10.     if not lst:
  11.         return acc
  12.     else:
  13.         return sum_tail_recursive(lst[1:], acc+lst[0])
  14.  
  15. # przykładowe wywołania funkcji
  16. lst1 = [1, 2, 3, 4]
  17. lst2 = []
  18.  
  19. print("Suma dla listy {}: {}".format(lst1, sum_recursive(lst1)))
  20. print("Suma dla listy {}: {}".format(lst1, sum_tail_recursive(lst1)))
  21. print("Suma dla listy {}: {}".format(lst2, sum_recursive(lst2)))
  22. print("Suma dla listy {}: {}".format(lst2, sum_tail_recursive(lst2)))
  23.  
  24.  
  25. Wariancja rekurencyjnie
  26.  
  27. def mean_var_recursive(lst, length, total):
  28.     if not lst:
  29.         mean = total / length
  30.         return mean, 0
  31.     else:
  32.         new_total = total + lst[0]
  33.         new_length = length + 1
  34.         mean, var = mean_var_recursive(lst[1:], new_length, new_total)
  35.         new_mean = (total + mean) / new_length
  36.         new_var = ((length - 1) * var + (lst[0] - new_mean)**2) / length
  37.         return new_mean, new_var
  38.  
  39. # przykładowe wywołania funkcji
  40. lst1 = [3, 3, 3, 3]
  41. lst2 = [5, 6, 7, 8, 9]
  42. mean1, var1 = mean_var_recursive(lst1, len(lst1), 0)
  43. mean2, var2 = mean_var_recursive(lst2, len(lst2), 0)
  44. print("Średnia i wariancja dla listy {}: {}, {}".format(lst1, mean1, var1))
  45. print("Średnia i wariancja dla listy {}: {}, {}".format(lst2, mean2, var2))
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement