mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-03-11 17:19:48 +00:00
Compare commits
8 Commits
f4e63ab90f
...
22bff1d8b9
Author | SHA1 | Date | |
---|---|---|---|
|
22bff1d8b9 | ||
|
338cbafe0d | ||
|
455749a9eb | ||
|
297da1f274 | ||
|
5a61613dd0 | ||
|
0de43acf24 | ||
|
0175a2be86 | ||
|
db38f0e514 |
@ -1,4 +1,4 @@
|
||||
def actual_power(a: int, b: int):
|
||||
def actual_power(a: int, b: int) -> int:
|
||||
"""
|
||||
Function using divide and conquer to calculate a^b.
|
||||
It only works for integer a,b.
|
||||
@ -19,10 +19,12 @@ def actual_power(a: int, b: int):
|
||||
"""
|
||||
if b == 0:
|
||||
return 1
|
||||
half = actual_power(a, b // 2)
|
||||
|
||||
if (b % 2) == 0:
|
||||
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
|
||||
return half * half
|
||||
else:
|
||||
return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
|
||||
return a * half * half
|
||||
|
||||
|
||||
def power(a: int, b: int) -> float:
|
||||
@ -43,9 +45,9 @@ def power(a: int, b: int) -> float:
|
||||
-0.125
|
||||
"""
|
||||
if b < 0:
|
||||
return 1 / actual_power(a, b)
|
||||
return 1 / actual_power(a, -b)
|
||||
return actual_power(a, b)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(power(-2, -3))
|
||||
print(power(-2, -3)) # output -0.125
|
||||
|
30
dynamic_programming/brige_torch_problem.py
Normal file
30
dynamic_programming/brige_torch_problem.py
Normal file
@ -0,0 +1,30 @@
|
||||
person_pace = [1, 2, 5, 10, 12, 16]
|
||||
person_pace.sort() # Sort the array for optimal pairing
|
||||
people = len(person_pace)
|
||||
|
||||
# Base cases
|
||||
if people == 1:
|
||||
print("Min Time to Cross is:", person_pace[0])
|
||||
elif people == 2:
|
||||
print("Min Time to Cross is:", person_pace[1])
|
||||
else:
|
||||
total_time = 0
|
||||
while people > 3:
|
||||
# Strategy 1: Send the two fastest first, then the fastest returns
|
||||
option1 = person_pace[1] + person_pace[0] + person_pace[-1] + person_pace[1]
|
||||
# Strategy 2: Send the two slowest, then the fastest returns
|
||||
option2 = person_pace[-1] + person_pace[0] + person_pace[-2] + person_pace[0]
|
||||
|
||||
# Choose the minimum of the two strategies
|
||||
total_time += min(option1, option2)
|
||||
|
||||
# Remove the two slowest people who have crossed
|
||||
person_pace = person_pace[:-2]
|
||||
|
||||
# Handle the last 2 or 3 people
|
||||
if len(person_pace) == 3:
|
||||
total_time += person_pace[2] + person_pace[0] + person_pace[1]
|
||||
elif len(person_pace) == 2:
|
||||
total_time += person_pace[1]
|
||||
|
||||
print("Min Time to Cross is:", total_time)
|
Loading…
x
Reference in New Issue
Block a user