Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c3fabd6

Browse files
committed
recursion exercises
1 parent d5887ca commit c3fabd6

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

PythonDataStructsAndAlgo/Notes.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,9 @@
4141
> To design a good algorithm, it is useful to think of the different ways we might define the subproblems that have the same general structure as the original problem.
4242
4343
>Tail recursion - if any recursive call that is made from one context is the very last operation in that context, with the return value of the recursive call immediately returned by enclosing recursion.
44+
45+
# Array-Base Sequences
46+
> list, tuple and str classes have in common the support of indexing to access individual elements of a sequence, and each uses a low-level concept known as an array to represent that sequence.
47+
48+
> * *Shallow copy* - an array copy of another array that references the same elements as in the first list.
49+
> * With
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""Recursive algorithm to find the product of 2 integers m and n using only addition and subtraction"""
2+
def productRecursion(n, m):
3+
total=0
4+
if m ==0 or n==0:
5+
return 0
6+
elif m >0 and n>0 :
7+
for _ in range(m):
8+
total+=n
9+
elif (m >0 and n<0):
10+
if n%2==0:
11+
for _ in range(m):
12+
total+=abs(n)
13+
else:
14+
total+=n
15+
elif n>0 and m<0:
16+
if m%2==0:
17+
for _ in range(n):
18+
total+=m
19+
else:
20+
total+=m
21+
elif n<0 and m<0:
22+
for _ in range(abs(m)):
23+
total+=abs(n)
24+
return total
25+
26+
print(productRecursion(4,3)) #correct
27+
print(productRecursion(3,0)) #correct
28+
print(productRecursion(-4,-3))#correct
29+
print(productRecursion(3,-4))
30+
print(productRecursion(-2,2))#correct
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def subsetPrint(list):
2+
3+
#If list is equal to an empty list return the empty list as a sublist (subset)
4+
if list == [] :
5+
return [[]]
6+
7+
""" """
8+
return [[list[0]]+y for y in subsetPrint(list[1:])] +subsetPrint(list[1:])
9+
10+
print(subsetPrint([3,2,1]))
11+
12+
#Non recursive LeetCode 78
13+
14+
def subsets(list):
15+
output=[[]]
16+
17+
for i in list:
18+
output+= [lst + [i] for lst in output]
19+
20+
return output
21+
22+
print(subsets([3,2,1]))

0 commit comments

Comments
 (0)