Merge function in Lua - sorting

Hey, I'm trying to implement the merge function from merge sort in Lua. I know the algorithm pretty well, but I'm new to Lua. I keep getting a "bad argument #1 to 'insert' (table expected, got nil)" I believe the error is pointing at my recursive call. I can't figure it out and I have a feeling it's something pretty trivial. I just need a Lua guru to give me some guidance. Thanks. Here's my function:
function merge(l1, l2)
if # l1 == 0 then
return l2
elseif # l2 == 0 then
return l1
else
if l1[1] <= l2[1] then
tmp = l1[1]
table.remove(l1,1)
return table.insert(merge(l1,l2),tmp)
else
tmp = l2[1]
table.remove(l2,1)
return table.insert(merge(l1,l2),tmp)
end
end
end

I am not completely sure what you want to achieve with the merge function, but a clear problem is that table.insert doesn't return a table, it returns nil.
Storing the result of the merge in table t, using table.insert on t and finally returning t doesn't seem to break as before.
function merge(l1, l2)
if #l1 == 0 then
return l2
elseif # l2 == 0 then
return l1
else
if l1[1] <= l2[1] then
local tmp = table.remove(l1, 1)
local t = merge(l1, l2)
table.insert(t, tmp)
return t
else
local tmp = table.remove(l2, 1)
local t = merge(l1, l2)
table.insert(t, tmp)
return t
end
end
end
A note on the few other modifications I did. table.remove returns the removed element, so you don't have to first access the element and then remove it. I recommend using the keyword local for variables, because in Lua all variables are global by default.

Related

How to compare 1 number to an entire array?

Create a function that takes an array of hurdle heights and a jumper's jump height, and determine whether or not the hurdler can clear all the hurdles. A hurdler can clear a hurdle if their jump height is greater than or equal to the hurdle height.
My code:
def hj (arr, h)
i = 0
while i < arr.length
j = 0
while j < arr.length
if arr[i] > h
return false
end
j += 1
end
return true
i += 1
end
end
puts hj([2, 3, 6, 1, 3, 1, 8], 7)
Desired output: true if h is >= to any number in the array; false if h is < any number in the array (I want true or false to display once)
Where I'm questioning my own code:
Not sure if I need two while statements
the current array being passed should output false
loop seems to only be comparing the first set of numbers, so 7 and 2. Not sure why the loop is stopping.
Not sure if I'm utilizing true and false correctly
Feel like I should be using a block for this, but not sure where to implement it.
Thank you in advance for any feedback.
Some solutions:
Using loop
def hj(arr, h)
for elem in arr
return false if elem > h
end
true
end
See? Only one loop. Actually this is the most unruby implementation.
Using Enumerable#all?
def hj(arr, h)
arr.all?{|elem| elem <= h}
end
This is the most intuitive and most Ruby implementation.
Using Enumerable#max
If one can jump over the highest hurdle, he can jump over all hurdles.
def hj(arr, h)
arr.max <= h
end
Not sure if I need two while statements
You don't. You only need to traverse the list once. You're traversing, not sorting / reordering.
loop seems to only be comparing the first set of numbers, so 7 and 2. Not sure why the loop is stopping.
This is because you are using return true as the second last statement of your outer loop. Return interrupts function execution and returns immediately to the calling function - in this case, the last line of your program.
Feel like I should be using a block for this, but not sure where to implement it.
A block is the idiomatic ruby way to solve this. You are, essentially, wanting to check that your second parameter is larger than any value in the list which is your first parameter.
A solution in idiomatic ruby would be
def hj (arr, h)
# return true if h >= all elements in arr, false otherwise
# given arr = [1, 2, 3] and h = 2,
# returns [ true, true, false ] which all? then returns as false
# (since all? returns the boolean AND of the results of the block evaluation
arr.all? { |elem| elem <= h }
end

Julia: Return early from pmap()

Say I have something like the following:
function f(x)
some_test ? true : false
end
If I do pmap(f,some_array) I'll get some array of Bools. I'd like to do something if contains(==,p,false). However, I'd like to do this thing if there is at least just one false. I.e. if some_array is very very large I would like pmap to stop once it finds its first false.
some_test may be quite involved so I've read that a parallel for loop is not the way to go.
E.g if I have
p = pmap(f,some_array,[N for i = 1:some_large_value])
if contains(==,p,false)
return false
else
return true
end
and a false appears when i=100, how can I stop pmap from checking 101:some_large_value?
As another example of the behavior I'd like to do, take this example from ?pmap.
julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=ex->0)
4-element Array{Int64,1}:
1
0
3
0
Instead of on_error=ex->0 I'd like pmap to return on the first even. Something like
pmap(x->iseven(x) ? return : x, 1:4)
which would ideally result in only a 1-element Array{Int64,1}.
This is generally hard to do, since other tasks may have already started. If you're not that worried about doing a few extra runs, one way is to modify the pmap example from the parallel computing docs
function pmap_chk(f, lst)
np = nprocs() # determine the number of processes available
n = length(lst)
results = Vector{Any}(n)
i = 0
nextidx() = (i+=1; i)
done = false
isdone() = done
setdone(flag) = (done = flag)
#sync begin
for p=1:np
if p != myid() || np == 1
#async begin
while !isdone()
idx = nextidx()
if idx > n
break
end
r, flag = remotecall_fetch(f, p, lst[idx])
results[idx] = r
if flag
setdone(flag)
end
end
end
end
end
end
resize!(results, i)
end
Here f should return a tuple containing the result and whether or not it is done, e.g.
julia> pmap_chk(1:100) do f
r = rand()
sleep(r)
(r, r>0.9)
end
15-element Array{Any,1}:
0.197364
0.60551
0.794526
0.105827
0.612087
0.170032
0.8584
0.533681
0.46603
0.901562
0.0894842
0.718619
0.501523
0.407671
0.514958
Note that it doesn't stop immediately.

Max and Min Value ... Need method to return two variable values

I am new to coding and need help understanding what is wrong with my logic and or syntax in the following method... The program is supposed to return the max and min values of an array. My goal was to have two variables (max and min) outside of the method, so that as the method ran through the array the values would get replaced accordingly. thank you for your help...
list=[4,6,10,7,1,2]
max=list[0]
min=list[0]
def maxmin(list)
f=list.shift
if list.empty?then
return max = f
return min = f
end
t=maxmin(list)
if(f>t) then
return max = f
return min = t
else
return max = t
return min = f
end
end
printf("max=#{max}, min=#{min}, method return=%d\n", maxmin(list))
Using 1.9.1, there's minmax
>> list=[4,6,10,7,1,2]
=> [4, 6, 10, 7, 1, 2]
>> list.minmax
=> [1, 10]
Max and Min method are already in Stdlib or ruby
Enumerable#max
Enumerable#min
So use it
list.max
list.min
Edit: is your question just about returning two variable? If so, just separate them with a comma, and they will be returned as an array:
return min_value, max_value
To add to what has already been written (yes, use the built-in libraries), it is generally a bad idea to modify variables outside of the method they are being used in. Note that in framework call, new values are being returned. This lets the person calling the method decide what to do with those values, rather than this method assuming that the variables exist and then changing them all the time.
If I had to write it (and I'm new to Ruby so I might not be doing this as elegantly as possible, but it should be easy to follow), I would write it something like this:
def find_min_max(list)
if (list.nil? || list.count == 0)
return nil, nil
end
min = list.first
max = list.first
list.each do |item|
if item.nil?
next
elsif item < min
min = item
elsif item > max
max = item
end
end
return min, max
end
list = [1, 439, 2903, 23]
min_max = find_min_max list
p min_max
I would agree with the other answers given. There is no point writing this method, other than as a programming exercise.
There are a few problems with the logic which might explain why you are not getting the result you expect.
Firstly there are 3 pairs of return statements, the second of which would never be called because the method has already returned, e.g.
return max = f
return min = f # never gets called
You need to return both the min and max values to make the recursive algorithm work so I guess you need to return a pair of values or an array in a single return statement.
Secondly, your min and max variables initialized on lines 3 and 4 are not in scope within the minmax method body so you are actually defining new local variables there.
If you adapt your code you might end up with something like this, but this is not a method you need to write in production and I'm sure there are better ways to do it:
list = [4,6,10,7,1,2]
def maxmin(list)
f = list.shift
if list.empty?
return f, f
end
max, min = maxmin(list)
return f > max ? f : max, f < min ? f : min
end
max, min = maxmin(list)
puts "min = #{min}, max = #{max}"
The problem is that you try to use global variables (that are called like that : #max, #min) but you want your code to assign the values, that you don't even assign. You'd rather choose local variables over global, if it's possible, because of accessibility.
The second problem is that in the case you use global variable, you don't have to return anything. for exemple :
#value = 0
def test
#value = 1
end
puts #value ==> 0
test # change #value to 1
# it also return 1 because ruby return last statement value
puts #value ==> 1
In the case you use local variables you should return multiple results.
That's where Ruby do the job, Ruby automatically cast multiple return statement to array and array to multiple variables assignment)
list = [4,6,10,7,1,2]
def maxmin(list)
f = list.shift
if list.empty? then
return f, f # f is the minimum and the maximum of a list of one element
end
mi, ma = maxmin(list)
if (f > ma) then
ma = f
elsif (f < mi)
min = f
end
return mi, ma
end
min, max = maxmin(list)
printf("max=#{max}, min=#{min}")
Your way of doing is pretty fun (love recursivity) but it's not really elegant, the performances are not really good and moreover it's a bit confusing, that's far from ruby vision.
list = [4,6,10,7,1,2]
def minmax(list)
max = list[0]
min = list[0]
list.each do |elem|
if elem > max then
max = elem
elsif elem < min
min = elem
end
end
return min, max
end
min, max = minmax(list)
printf("max=#{max}, min=#{min}")
Is a clearer version of your code, even if less cool. You can try those answers with global variables it should be easy.
Obviously because of Ruby vision when you're done with that you're welcome to use Array.max and Array.min.

How to implement MapThread with basic list mapping?

Mathematica has a function MapThread that behaves like this:
MapThread[ f , { {a,b,c} , {d,e,f} } ]
-> { f[a,d] , f[b,e] , f[c,f] }
I'd like to implement this in TeX, which has very primitive programming facilities. I've basic facilities for iterating over lists, but no logical indexing into them. Given this restriction, is there an algorithm for looping synchronously though multiple lists?
I could write something like the following: (pseudocode)
ii = 0; jj = 0;
for elem1 in list1
ii = ii+1
for elem2 in list2
jj = jj+1
if ii == jj
return ( elem1 , elem2 )
fi
end
end
but it seems terribly inefficient. Note that the big restriction is that I can't access elements of lists numerically, so something like the following is too "high level":
for ii = 1:length(list1)
func ( list1(ii) , list2(ii) )
end
The reason this restriction is in place is that in order to implement list1(ii) I'd need to write something like the following in the first place:
jj = 0
for elem1 in list1
jj = jj+1
if ii=jj
return elem1
fi
end
Or is the inefficient case probably the best I'll be able to do with such a primitive language?
In pseudocode, as long as you can test whether a list is empty, you can do it like so:
while (list1 is not empty) and (list2 is not empty)
x1 = first(list1);
x2 = first(list2);
list1 = rest(list1);
list2 = rest(list2);
func(x1, x2);
end while
It's still not going to win any beauty contests, but it'll get the job done without being crushingly inefficient.

Checking if two strings are permutations of each other in Python

I'm checking if two strings a and b are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
sorted(a) == sorted(b)
and
all(a.count(char) == b.count(char) for char in a)
but the first one is slower when (for example) the first char of a is nowhere in b, and the second is slower when they are actually permutations.
Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?
Here is a way which is O(n), asymptotically better than the two ways you suggest.
import collections
def same_permutation(a, b):
d = collections.defaultdict(int)
for x in a:
d[x] += 1
for x in b:
d[x] -= 1
return not any(d.itervalues())
## same_permutation([1,2,3],[2,3,1])
#. True
## same_permutation([1,2,3],[2,3,1,1])
#. False
"but the first one is slower when (for example) the first char of a is nowhere in b".
This kind of degenerate-case performance analysis is not a good idea. It's a rat-hole of lost time thinking up all kinds of obscure special cases.
Only do the O-style "overall" analysis.
Overall, the sorts are O( n log( n ) ).
The a.count(char) for char in a solution is O( n 2 ). Each count pass is a full examination of the string.
If some obscure special case happens to be faster -- or slower, that's possibly interesting. But it only matters when you know the frequency of your obscure special cases. When analyzing sort algorithms, it's important to note that a fair number of sorts involve data that's already in the proper order (either by luck or by a clever design), so sort performance on pre-sorted data matters.
In your obscure special case ("the first char of a is nowhere in b") is this frequent enough to matter? If it's just a special case you thought of, set it aside. If it's a fact about your data, then consider it.
heuristically you're probably better to split them off based on string size.
Pseudocode:
returnvalue = false
if len(a) == len(b)
if len(a) < threshold
returnvalue = (sorted(a) == sorted(b))
else
returnvalue = naminsmethod(a, b)
return returnvalue
If performance is critical, and string size can be large or small then this is what I'd do.
It's pretty common to split things like this based on input size or type. Algorithms have different strengths or weaknesses and it would be foolish to use one where another would be better... In this case Namin's method is O(n), but has a larger constant factor than the O(n log n) sorted method.
I think the first one is the "obvious" way. It is shorter, clearer, and likely to be faster in many cases because Python's built-in sort is highly optimized.
Your second example won't actually work:
all(a.count(char) == b.count(char) for char in a)
will only work if b does not contain extra characters not in a. It also does duplicate work if the characters in string a repeat.
If you want to know whether two strings are permutations of the same unique characters, just do:
set(a) == set(b)
To correct your second example:
all(str1.count(char) == str2.count(char) for char in set(a) | set(b))
set() objects overload the bitwise OR operator so that it will evaluate to the union of both sets. This will make sure that you will loop over all the characters of both strings once for each character only.
That said, the sorted() method is much simpler and more intuitive, and would be what I would use.
Here are some timed executions on very small strings, using two different methods:
1. sorting
2. counting (specifically the original method by #namin).
a, b, c = 'confused', 'unfocused', 'foncused'
sort_method = lambda x,y: sorted(x) == sorted(y)
def count_method(a, b):
d = {}
for x in a:
d[x] = d.get(x, 0) + 1
for x in b:
d[x] = d.get(x, 0) - 1
for v in d.itervalues():
if v != 0:
return False
return True
Average run times of the 2 methods over 100,000 loops are:
non-match (string a and b)
$ python -m timeit -s 'import temp' 'temp.sort_method(temp.a, temp.b)'
100000 loops, best of 3: 9.72 usec per loop
$ python -m timeit -s 'import temp' 'temp.count_method(temp.a, temp.b)'
10000 loops, best of 3: 28.1 usec per loop
match (string a and c)
$ python -m timeit -s 'import temp' 'temp.sort_method(temp.a, temp.c)'
100000 loops, best of 3: 9.47 usec per loop
$ python -m timeit -s 'import temp' 'temp.count_method(temp.a, temp.c)'
100000 loops, best of 3: 24.6 usec per loop
Keep in mind that the strings used are very small. The time complexity of the methods are different, so you'll see different results with very large strings. Choose according to your data, you may even use a combination of the two.
Sorry that my code is not in Python, I have never used it, but I am sure this can be easily translated into python. I believe this is faster than all the other examples already posted. It is also O(n), but stops as soon as possible:
public boolean isPermutation(String a, String b) {
if (a.length() != b.length()) {
return false;
}
int[] charCount = new int[256];
for (int i = 0; i < a.length(); ++i) {
++charCount[a.charAt(i)];
}
for (int i = 0; i < b.length(); ++i) {
if (--charCount[b.charAt(i)] < 0) {
return false;
}
}
return true;
}
First I don't use a dictionary but an array of size 256 for all the characters. Accessing the index should be much faster. Then when the second string is iterated, I immediately return false when the count gets below 0. When the second loop has finished, you can be sure that the strings are a permutation, because the strings have equal length and no character was used more often in b compared to a.
Here's martinus code in python. It only works for ascii strings:
def is_permutation(a, b):
if len(a) != len(b):
return False
char_count = [0] * 256
for c in a:
char_count[ord(c)] += 1
for c in b:
char_count[ord(c)] -= 1
if char_count[ord(c)] < 0:
return False
return True
I did a pretty thorough comparison in Java with all words in a book I had. The counting method beats the sorting method in every way. The results:
Testing against 9227 words.
Permutation testing by sorting ... done. 18.582 s
Permutation testing by counting ... done. 14.949 s
If anyone wants the algorithm and test data set, comment away.
First, for solving such problems, e.g. whether String 1 and String 2 are exactly the same or not, easily, you can use an "if" since it is O(1).
Second, it is important to consider that whether they are only numerical values or they can be also words in the string. If the latter one is true (words and numerical values are in the string at the same time), your first solution will not work. You can enhance it by using "ord()" function to make it ASCII numerical value. However, in the end, you are using sort; therefore, in the worst case your time complexity will be O(NlogN). This time complexity is not bad. But, you can do better. You can make it O(N).
My "suggestion" is using Array(list) and set at the same time. Note that finding a value in Array needs iteration so it's time complexity is O(N), but searching a value in set (which I guess it is implemented with HashTable in Python, I'm not sure) has O(1) time complexity:
def Permutation2(Str1, Str2):
ArrStr1 = list(Str1) #convert Str1 to array
SetStr2 = set(Str2) #convert Str2 to set
ArrExtra = []
if len(Str1) != len(Str2): #check their length
return False
elif Str1 == Str2: #check their values
return True
for x in xrange(len(ArrStr1)):
ArrExtra.append(ArrStr1[x])
for x in xrange(len(ArrExtra)): #of course len(ArrExtra) == len(ArrStr1) ==len(ArrStr2)
if ArrExtra[x] in SetStr2: #checking in set is O(1)
continue
else:
return False
return True
Go with the first one - it's much more straightforward and easier to understand. If you're actually dealing with incredibly large strings and performance is a real issue, then don't use Python, use something like C.
As far as the Zen of Python is concerned, that there should only be one obvious way to do things refers to small, simple things. Obviously for any sufficiently complicated task, there will always be zillions of small variations on ways to do it.
In Python 3.1/2.7 you can just use collections.Counter(a) == collections.Counter(b).
But sorted(a) == sorted(b) is still the most obvious IMHO. You are talking about permutations - changing order - so sorting is the obvious operation to erase that difference.
This is derived from #patros' answer.
from collections import Counter
def is_anagram(a, b, threshold=1000000):
"""Returns true if one sequence is a permutation of the other.
Ignores whitespace and character case.
Compares sorted sequences if the length is below the threshold,
otherwise compares dictionaries that contain the frequency of the
elements.
"""
a, b = a.strip().lower(), b.strip().lower()
length_a, length_b = len(a), len(b)
if length_a != length_b:
return False
if length_a < threshold:
return sorted(a) == sorted(b)
return Counter(a) == Counter(b) # Or use #namin's method if you don't want to create two dictionaries and don't mind the extra typing.
This is an O(n) solution in Python using hashing with dictionaries. Notice that I don't use default dictionaries because the code can stop this way if we determine the two strings are not permutations after checking the second letter for instance.
def if_two_words_are_permutations(s1, s2):
if len(s1) != len(s2):
return False
dic = {}
for ch in s1:
if ch in dic.keys():
dic[ch] += 1
else:
dic[ch] = 1
for ch in s2:
if not ch in dic.keys():
return False
elif dic[ch] == 0:
return False
else:
dic[ch] -= 1
return True
This is a PHP function I wrote about a week ago which checks if two words are anagrams. How would this compare (if implemented the same in python) to the other methods suggested? Comments?
public function is_anagram($word1, $word2) {
$letters1 = str_split($word1);
$letters2 = str_split($word2);
if (count($letters1) == count($letters2)) {
foreach ($letters1 as $letter) {
$index = array_search($letter, $letters2);
if ($index !== false) {
unset($letters2[$index]);
}
else { return false; }
}
return true;
}
return false;
}
Here's a literal translation to Python of the PHP version (by JFS):
def is_anagram(word1, word2):
letters2 = list(word2)
if len(word1) == len(word2):
for letter in word1:
try:
del letters2[letters2.index(letter)]
except ValueError:
return False
return True
return False
Comments:
1. The algorithm is O(N**2). Compare it to #namin's version (it is O(N)).
2. The multiple returns in the function look horrible.
This version is faster than any examples presented so far except it is 20% slower than sorted(x) == sorted(y) for short strings. It depends on use cases but generally 20% performance gain is insufficient to justify a complication of the code by using different version for short and long strings (as in #patros's answer).
It doesn't use len so it accepts any iterable therefore it works even for data that do not fit in memory e.g., given two big text files with many repeated lines it answers whether the files have the same lines (lines can be in any order).
def isanagram(iterable1, iterable2):
d = {}
get = d.get
for c in iterable1:
d[c] = get(c, 0) + 1
try:
for c in iterable2:
d[c] -= 1
return not any(d.itervalues())
except KeyError:
return False
It is unclear why this version is faster then defaultdict (#namin's) one for large iterable1 (tested on 25MB thesaurus).
If we replace get in the loop by try: ... except KeyError then it performs 2 times slower for short strings i.e. when there are few duplicates.
In Swift (or another languages implementation), you could look at the encoded values ( in this case Unicode) and see if they match.
Something like:
let string1EncodedValues = "Hello".unicodeScalars.map() {
//each encoded value
$0
//Now add the values
}.reduce(0){ total, value in
total + value.value
}
let string2EncodedValues = "oellH".unicodeScalars.map() {
$0
}.reduce(0) { total, value in
total + value.value
}
let equalStrings = string1EncodedValues == string2EncodedValues ? true : false
You will need to handle spaces and cases as needed.
def matchPermutation(s1, s2):
a = []
b = []
if len(s1) != len(s2):
print 'length should be the same'
return
for i in range(len(s1)):
a.append(s1[i])
for i in range(len(s2)):
b.append(s2[i])
if set(a) == set(b):
print 'Permutation of each other'
else:
print 'Not a permutation of each other'
return
#matchPermutaion('rav', 'var') #returns True
matchPermutaion('rav', 'abc') #returns False
Checking if two strings are permutations of each other in Python
# First method
def permutation(s1,s2):
if len(s1) != len(s2):return False;
return ' '.join(sorted(s1)) == ' '.join(sorted(s2))
# second method
def permutation1(s1,s2):
if len(s1) != len(s2):return False;
array = [0]*128;
for c in s1:
array[ord(c)] +=1
for c in s2:
array[ord(c)] -=1
if (array[ord(c)]) < 0:
return False
return True
How about something like this. Pretty straight-forward and readable. This is for strings since the as per the OP.
Given that the complexity of sorted() is O(n log n).
def checkPermutation(a,b):
# input: strings a and b
# return: boolean true if a is Permutation of b
if len(a) != len(b):
return False
else:
s_a = ''.join(sorted(a))
s_b = ''.join(sorted(b))
if s_a == s_b:
return True
else:
return False
# test inputs
a = 'sRF7w0qbGp4fdgEyNlscUFyouETaPHAiQ2WIxzohiafEGJLw03N8ALvqMw6reLN1kHRjDeDausQBEuIWkIBfqUtsaZcPGoqAIkLlugTxjxLhkRvq5d6i55l4oBH1QoaMXHIZC5nA0K5KPBD9uIwa789sP0ZKV4X6'
b = 'Vq3EeiLGfsAOH2PW6skMN8mEmUAtUKRDIY1kow9t1vIEhe81318wSMICGwf7Rv2qrLrpbeh8bh4hlRLZXDSMyZJYWfejLND4u9EhnNI51DXcQKrceKl9arWqOl7sWIw3EBkeu7Fw4TmyfYwPqCf6oUR0UIdsAVNwbyyiajtQHKh2EKLM1KlY6NdvQTTA7JKn6bLInhFvwZ4yKKbzkgGhF3Oogtnmzl29fW6Q2p0GPuFoueZ74aqlveGTYc0zcXUJkMzltzohoRdMUKP4r5XhbsGBED8ReDbL3ouPhsFchERvvNuaIWLUCY4gl8OW06SMuvceZrCg7EkSFxxprYurHz7VQ2muxzQHj7RG2k3khxbz2ZAhWIlBBtPtg4oXIQ7cbcwgmBXaTXSBgBe3Y8ywYBjinjEjRJjVAiZkWoPrt8JtZv249XiN0MTVYj0ZW6zmcvjZtRn32U3KLMOdjLnRFUP2I3HJtp99uVlM9ghIpae0EfC0v2g78LkZE1YAKsuqCiiy7DVOhyAZUbOrRwXOEDHxUyXwCmo1zfVkPVhwysx8HhH7Iy0yHAMr0Tb97BqcpmmyBsrSgsV1aT3sjY0ctDLibrxbRXBAOexncqB4BBKWJoWkQwUZkFfPXemZkWYmE72w5CFlI6kuwBQp27dCDZ39kRG7Txs1MbsUnRnNHBy1hSOZvTQRYZPX0VmU8SVGUqzwm1ECBHZakQK4RUquk3txKCqbDfbrNmnsEcjFaiMFWkY3Esg6p3Mm41KWysTpzN6287iXjgGSBw6CBv0hH635WiZ0u47IpUD5mY9rkraDDl5sDgd3f586EWJdKAaou3jR7eYU7YuJT3RQVRI0MuS0ec0xYID3WTUI0ckImz2ck7lrtfnkewzRMZSE2ANBkEmg2XAmwrCv0gy4ExW5DayGRXoqUv06ZLGCcBEiaF0fRMlinhElZTVrGPqqhT03WSq4P97JbXA90zUxiHCnsPjuRTthYl7ZaiVZwNt3RtYT4Ff1VQ5KXRwRzdzkRMsubBX7YEhhtl0ZGVlYiP4N4t00Jr7fB4687eabUqK6jcUVpXEpTvKDbj0JLcLYsneM9fsievUz193f6aMQ5o5fm4Ilx3TUZiX4AUsoyd8CD2SK3NkiLuR255BDIA0Zbgnj2XLyQPiJ1T4fjStpjxKOTzsQsZxpThY9Fvjvoxcs3HAiXjLtZ0TSOX6n4ZLjV3TdJMc4PonwqIb3lAndlTMnuzEPof2dXnpexoVm5c37XQ7fBkoMBJ4ydnW25XKYJbkrueRDSwtJGHjY37dob4jPg0axM5uWbqGocXQ4DyiVm5GhvuYX32RQaOtXXXw8cWK6JcSUnlP1gGLMNZEGeDXOuGWiy4AJ7SH93ZQ4iPgoxdfCuW0qbsLKT2HopcY9dtBIRzr91wnES9lDL49tpuW77LSt5dGA0YLSeWAaZt9bDrduE0gDZQ2yX4SDvAOn4PMcbFRfTqzdZXONmO7ruBHHb1tVFlBFNc4xkoetDO2s7mpiVG6YR4EYMFIG1hBPh7Evhttb34AQzqImSQm1gyL3O7n3p98Kqb9qqIPbN1kuhtW5mIbIioWW2n7MHY7E5mt0'
print(checkPermutation(a, b)) #optional
def permute(str1,str2):
if sorted(str1) == sorted(str2):
return True
else:
return False
str1="hello"
str2='olehl'
a=permute(str1,str2)
print(a
from collections import defaultdict
def permutation(s1,s2):
h = defaultdict(int)
for ch in s1:
h[ch]+=1
for ch in s2:
h[ch]-=1
for key in h.keys():
if h[key]!=0 or len(s1)!= len(s2):
return False
return True
print(permutation("tictac","tactic"))

Resources