-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursions
More file actions
83 lines (63 loc) · 1.94 KB
/
Recursions
File metadata and controls
83 lines (63 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#Завдання 1:
def reverse_string(string):
if not string:
return ""
return string[-1] + reverse_string(string[:-1])
print(reverse_string("tiger"))
###############################################################################################
#Завдання 2:
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def print_linked_list(head):
while head:
print(head.value, end=" -> ")
head = head.next
print("None")
def swap_pairs(head):
if head is None or head.next is None:
return head
new_head = head.next
next_pair = head.next.next
head.next.next = head
head.next = swap_pairs(next_pair)
return new_head
linked_list = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
new_head = swap_pairs(linked_list)
print_linked_list(new_head)
###############################################################################################
#Завдання 3:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = 20
result = fibonacci(n)
print(f"F({n}) = {result}")
###############################################################################################
#Завдання 4:
def count_ways_to_climb_stairs(n):
if n <= 1:
return 1
else:
return count_ways_to_climb_stairs(n - 1) + count_ways_to_climb_stairs(n - 2)
n = 15
result = count_ways_to_climb_stairs(n)
print(f"Кількість унікальних комбінацій для {n} сходинок: {result}")
###############################################################################################
#Завдання 5:
def custom_pow(x, n):
if n == 0:
return 1
elif n > 0:
return x * custom_pow(x, n - 1)
else:
return 1 / custom_pow(x, -n)
x = 2
n = 8
result = custom_pow(x, n)
print(f"{x}^{n} = {result}")