mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-06 02:13:15 +08:00
Simplify code by dropping support for legacy Python (#1143)
* Simplify code by dropping support for legacy Python * sort() --> sorted()
This commit is contained in:
@ -9,27 +9,26 @@ Find the total no of ways in which the tasks can be distributed.
|
||||
|
||||
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
class AssignmentUsingBitmask:
|
||||
def __init__(self,task_performed,total):
|
||||
|
||||
|
||||
self.total_tasks = total #total no of tasks (N)
|
||||
|
||||
|
||||
# DP table will have a dimension of (2^M)*N
|
||||
# initially all values are set to -1
|
||||
self.dp = [[-1 for i in range(total+1)] for j in range(2**len(task_performed))]
|
||||
|
||||
|
||||
self.task = defaultdict(list) #stores the list of persons for each task
|
||||
|
||||
|
||||
#finalmask is used to check if all persons are included by setting all bits to 1
|
||||
self.finalmask = (1<<len(task_performed)) - 1
|
||||
|
||||
|
||||
|
||||
|
||||
def CountWaysUtil(self,mask,taskno):
|
||||
|
||||
|
||||
# if mask == self.finalmask all persons are distributed tasks, return 1
|
||||
if mask == self.finalmask:
|
||||
return 1
|
||||
@ -48,18 +47,18 @@ class AssignmentUsingBitmask:
|
||||
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks.
|
||||
if taskno in self.task:
|
||||
for p in self.task[taskno]:
|
||||
|
||||
|
||||
# if p is already given a task
|
||||
if mask & (1<<p):
|
||||
continue
|
||||
|
||||
|
||||
# assign this task to p and change the mask value. And recursively assign tasks with the new mask value.
|
||||
total_ways_util+=self.CountWaysUtil(mask|(1<<p),taskno+1)
|
||||
|
||||
|
||||
# save the value.
|
||||
self.dp[mask][taskno] = total_ways_util
|
||||
|
||||
return self.dp[mask][taskno]
|
||||
|
||||
return self.dp[mask][taskno]
|
||||
|
||||
def countNoOfWays(self,task_performed):
|
||||
|
||||
@ -67,17 +66,17 @@ class AssignmentUsingBitmask:
|
||||
for i in range(len(task_performed)):
|
||||
for j in task_performed[i]:
|
||||
self.task[j].append(i)
|
||||
|
||||
|
||||
# call the function to fill the DP table, final answer is stored in dp[0][1]
|
||||
return self.CountWaysUtil(0,1)
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
|
||||
total_tasks = 5 #total no of tasks (the value of N)
|
||||
|
||||
|
||||
#the list of tasks that can be done by M persons.
|
||||
task_performed = [
|
||||
task_performed = [
|
||||
[ 1 , 3 , 4 ],
|
||||
[ 1 , 2 , 5 ],
|
||||
[ 3 , 4 ]
|
||||
|
@ -5,9 +5,6 @@ Can you determine number of ways of making change for n units using
|
||||
the given types of coins?
|
||||
https://www.hackerrank.com/challenges/coin-change/problem
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
def dp_count(S, m, n):
|
||||
|
||||
# table[i] represents the number of ways to get to amount i
|
||||
|
@ -7,7 +7,6 @@ This is a pure Python implementation of Dynamic Programming solution to the edit
|
||||
The problem is :
|
||||
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class EditDistance:
|
||||
@ -67,14 +66,14 @@ def min_distance_bottom_up(word1: str, word2: str) -> int:
|
||||
dp = [[0 for _ in range(n+1) ] for _ in range(m+1)]
|
||||
for i in range(m+1):
|
||||
for j in range(n+1):
|
||||
|
||||
|
||||
if i == 0: #first string is empty
|
||||
dp[i][j] = j
|
||||
elif j == 0: #second string is empty
|
||||
dp[i][j] = i
|
||||
elif j == 0: #second string is empty
|
||||
dp[i][j] = i
|
||||
elif word1[i-1] == word2[j-1]: #last character of both substing is equal
|
||||
dp[i][j] = dp[i-1][j-1]
|
||||
else:
|
||||
else:
|
||||
insert = dp[i][j-1]
|
||||
delete = dp[i-1][j]
|
||||
replace = dp[i-1][j-1]
|
||||
@ -82,21 +81,13 @@ def min_distance_bottom_up(word1: str, word2: str) -> int:
|
||||
return dp[m][n]
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
solver = EditDistance()
|
||||
|
||||
print("****************** Testing Edit Distance DP Algorithm ******************")
|
||||
print()
|
||||
|
||||
print("Enter the first string: ", end="")
|
||||
S1 = raw_input().strip()
|
||||
|
||||
print("Enter the second string: ", end="")
|
||||
S2 = raw_input().strip()
|
||||
S1 = input("Enter the first string: ").strip()
|
||||
S2 = input("Enter the second string: ").strip()
|
||||
|
||||
print()
|
||||
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
|
||||
@ -106,4 +97,4 @@ if __name__ == '__main__':
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -5,7 +5,6 @@
|
||||
This program calculates the nth Fibonacci number in O(log(n)).
|
||||
It's possible to calculate F(1000000) in less than a second.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
"""
|
||||
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class Fibonacci:
|
||||
@ -29,21 +28,16 @@ class Fibonacci:
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
|
||||
try:
|
||||
N = eval(raw_input().strip())
|
||||
N = int(input().strip())
|
||||
fib = Fibonacci(N)
|
||||
print(
|
||||
"\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n")
|
||||
"\n********* Enter different values to get the corresponding fibonacci "
|
||||
"sequence, enter any negative number to exit. ************\n")
|
||||
while True:
|
||||
print("Enter value: ", end=" ")
|
||||
try:
|
||||
i = eval(raw_input().strip())
|
||||
i = int(input("Enter value: ").strip())
|
||||
if i < 0:
|
||||
print("\n********* Good Bye!! ************\n")
|
||||
break
|
||||
|
@ -1,27 +1,15 @@
|
||||
from __future__ import print_function
|
||||
|
||||
try:
|
||||
xrange #Python 2
|
||||
except NameError:
|
||||
xrange = range #Python 3
|
||||
|
||||
try:
|
||||
raw_input #Python 2
|
||||
except NameError:
|
||||
raw_input = input #Python 3
|
||||
|
||||
'''
|
||||
The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts
|
||||
plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts
|
||||
gives a partition of n-k into k parts. These two facts together are used for this algorithm.
|
||||
'''
|
||||
def partition(m):
|
||||
memo = [[0 for _ in xrange(m)] for _ in xrange(m+1)]
|
||||
for i in xrange(m+1):
|
||||
memo = [[0 for _ in range(m)] for _ in range(m+1)]
|
||||
for i in range(m+1):
|
||||
memo[i][0] = 1
|
||||
|
||||
for n in xrange(m+1):
|
||||
for k in xrange(1, m):
|
||||
for n in range(m+1):
|
||||
for k in range(1, m):
|
||||
memo[n][k] += memo[n][k-1]
|
||||
if n-k > 0:
|
||||
memo[n][k] += memo[n-k-1][k]
|
||||
@ -33,7 +21,7 @@ if __name__ == '__main__':
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
try:
|
||||
n = int(raw_input('Enter a number: '))
|
||||
n = int(input('Enter a number: ').strip())
|
||||
print(partition(n))
|
||||
except ValueError:
|
||||
print('Please enter a number.')
|
||||
|
@ -3,7 +3,6 @@ LCS Problem Statement: Given two sequences, find the length of longest subsequen
|
||||
A subsequence is a sequence that appears in the same relative order, but not necessarily continuous.
|
||||
Example:"abc", "abg" are subsequences of "abcdefgh".
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
def longest_common_subsequence(x: str, y: str):
|
||||
@ -80,4 +79,3 @@ if __name__ == '__main__':
|
||||
assert expected_ln == ln
|
||||
assert expected_subseq == subseq
|
||||
print("len =", ln, ", sub-sequence =", subseq)
|
||||
|
||||
|
@ -7,10 +7,8 @@ The problem is :
|
||||
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
|
||||
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
def longestSub(ARRAY): #This function is recursive
|
||||
|
||||
|
||||
ARRAY_LENGTH = len(ARRAY)
|
||||
if(ARRAY_LENGTH <= 1): #If the array contains only one element, we return it (it's the stop condition of recursion)
|
||||
return ARRAY
|
||||
|
@ -1,9 +1,8 @@
|
||||
from __future__ import print_function
|
||||
#############################
|
||||
# Author: Aravind Kashyap
|
||||
# File: lis.py
|
||||
# comments: This programme outputs the Longest Strictly Increasing Subsequence in O(NLogN)
|
||||
# Where N is the Number of elements in the list
|
||||
# Where N is the Number of elements in the list
|
||||
#############################
|
||||
def CeilIndex(v,l,r,key):
|
||||
while r-l > 1:
|
||||
@ -12,30 +11,30 @@ def CeilIndex(v,l,r,key):
|
||||
r = m
|
||||
else:
|
||||
l = m
|
||||
|
||||
|
||||
return r
|
||||
|
||||
|
||||
|
||||
def LongestIncreasingSubsequenceLength(v):
|
||||
if(len(v) == 0):
|
||||
return 0
|
||||
|
||||
return 0
|
||||
|
||||
tail = [0]*len(v)
|
||||
length = 1
|
||||
|
||||
|
||||
tail[0] = v[0]
|
||||
|
||||
|
||||
for i in range(1,len(v)):
|
||||
if v[i] < tail[0]:
|
||||
tail[0] = v[i]
|
||||
elif v[i] > tail[length-1]:
|
||||
tail[length] = v[i]
|
||||
length += 1
|
||||
length += 1
|
||||
else:
|
||||
tail[CeilIndex(tail,-1,length-1,v[i])] = v[i]
|
||||
|
||||
|
||||
return length
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
|
||||
|
@ -6,7 +6,6 @@ This is a pure Python implementation of Dynamic Programming solution to the long
|
||||
The problem is :
|
||||
Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class SubArray:
|
||||
|
@ -1,5 +1,3 @@
|
||||
from __future__ import print_function
|
||||
|
||||
import sys
|
||||
'''
|
||||
Dynamic Programming
|
||||
|
@ -1,7 +1,6 @@
|
||||
"""
|
||||
author : Mayank Kumar Jha (mk9440)
|
||||
"""
|
||||
from __future__ import print_function
|
||||
from typing import List
|
||||
import time
|
||||
import matplotlib.pyplot as plt
|
||||
@ -10,7 +9,7 @@ def find_max_sub_array(A,low,high):
|
||||
if low==high:
|
||||
return low,high,A[low]
|
||||
else :
|
||||
mid=(low+high)//2
|
||||
mid=(low+high)//2
|
||||
left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
|
||||
right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
|
||||
cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
|
||||
@ -30,7 +29,7 @@ def find_max_cross_sum(A,low,mid,high):
|
||||
if summ > left_sum:
|
||||
left_sum=summ
|
||||
max_left=i
|
||||
summ=0
|
||||
summ=0
|
||||
for i in range(mid+1,high+1):
|
||||
summ+=A[i]
|
||||
if summ > right_sum:
|
||||
@ -40,7 +39,7 @@ def find_max_cross_sum(A,low,mid,high):
|
||||
|
||||
def max_sub_array(nums: List[int]) -> int:
|
||||
"""
|
||||
Finds the contiguous subarray (can be empty array)
|
||||
Finds the contiguous subarray (can be empty array)
|
||||
which has the largest sum and return its sum.
|
||||
|
||||
>>> max_sub_array([-2,1,-3,4,-1,2,1,-5,4])
|
||||
@ -50,14 +49,14 @@ def max_sub_array(nums: List[int]) -> int:
|
||||
>>> max_sub_array([-1,-2,-3])
|
||||
0
|
||||
"""
|
||||
best = 0
|
||||
current = 0
|
||||
for i in nums:
|
||||
current += i
|
||||
best = 0
|
||||
current = 0
|
||||
for i in nums:
|
||||
current += i
|
||||
if current < 0:
|
||||
current = 0
|
||||
best = max(best, current)
|
||||
return best
|
||||
return best
|
||||
|
||||
if __name__=='__main__':
|
||||
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
|
||||
@ -68,8 +67,8 @@ if __name__=='__main__':
|
||||
(find_max_sub_array(li,0,len(li)-1))
|
||||
end=time.time()
|
||||
tim.append(end-strt)
|
||||
print("No of Inputs Time Taken")
|
||||
for i in range(len(inputs)):
|
||||
print("No of Inputs Time Taken")
|
||||
for i in range(len(inputs)):
|
||||
print(inputs[i],'\t\t',tim[i])
|
||||
plt.plot(inputs,tim)
|
||||
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
|
||||
@ -77,4 +76,4 @@ if __name__=='__main__':
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user