Hi so I am trying to write a function hack() that takes no arguments and returns an iterator over all possible passwords.
Basically, I have to user an iterator to brute force a password. All I know from the question is that:
The password consists of three segments.
The first segment of the password is a concatenation of two words in the following list of words: ["hello", "BEGONE", "dog", "MrCool"]
The middle segment is "Donkey20"
And the last segment consists of two digits that together (i.e. 1 and 7 = 17), are no larger than 38. (And at least 0)
My method of thinking is this:
Find all the possible combinations of POSSIBLE_WORDS by using permutations(). (Find all segment 1 possibilities)
For each combination in the new list, add "Donkey20" to the end. (For example: helloBEGONEDonkey20)
Find all possible combinations between the elements in THAT list and POSSIBLE_NUMBERS.
Create an iterator that iterates over all these possible passwords, and return it
My current code only is able to do step 2, but instead of Donkey20 being at the end of each combination it's at the start. (e.g. Donkey20helloBEGONE instead of helloBEGONEDonkey20)
POSSIBLE_WORDS = ["hello", "BEGONE", "dog", "MrCool"]
MIDDLE = "Donkey20"
possible_numbers1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
possible_numbers2 = [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
possible_numbers3 = [29, 30, 31, 32, 33, 34, 35, 36, 37, 38]
POSSIBLE_NUMBERS = possible_numbers1 + possible_numbers2 + possible_numbers3
from itertools import permutations, combinations
def hack():
first_words = [''.join(word) for word in permutations(POSSIBLE_WORDS, 2)]
first_words.append(MIDDLE)
first_half = [''.join(word) for word in permutations(first_words, 2)]
Any way to fix this issue? How do I finish the remainder of the steps? Is there a different approach I could use to code this program?
Any help would be very much appreciated!
First of all, there is no reason to build up POSSIBLE_NUMBERS like that. Just use range(39) or list(range(39)) instead.
Your intention in
first_words.append(MIDDLE)
was almost certainly not to tack the single word "Donkey20" onto the end of the list of all possible first parts but was instead to tack it onto the end of each first word. I think that your intention in that part of the code can be better expressed by getting rid of that line as well as the following line and just use the single line
first_half = [word + MIDDLE for word in first_words]
When you are putting together the final possible passwords, you are going to need to turn the numbers into strings. Doubtless you already know about str() but that function has the drawback that str(1) is '1' whereas you probably want '01'. In this context, you might want to use format() since format(1,'02') returns '01'.
This should be enough of a hint to get you going. Since this seems to be homework I don't want to say any more.
Related
I have an int list such as {18, 18, 18, 18, 22, 21}, I want to use Applescript to get the maximum value of this list, and get the maximum index, please teach me
There are two stages to this:
Identifying the maximum value in the list;
Once the maximum value is known, determining the index of the last occurrence of this value in the list.
I'll use a sample list I generated myself in the examples I demonstrate below. However, you can simply substitute your list for mine, and the processes described will work just as well, and produce the results specific to your input.
1. Retrieving the maximum value in a numerical list
A quick-and-dirty way to get the maxium value in the list is to use a bash numeric sort command, and pick the last item:
set L to {4, 24, 78, 32, 1.5, 32, 78, 4, 19, 78}
set text item delimiters to linefeed
do shell script "sort -n <<<" & quoted form of (L as text) & "| tail -n 1"
--> 78
But, in the spirit of problem solving, the computer scientist's approach would be to iterate through the items in the list and perform these operations:
Store the first item's value.
If the next item is of greater value, then replace the currently stored value with the item we just assessed as being greater in value.
If the next item is not of greater value, retain the currently stored value.
Once you reach the end of the list, the stored value must be equal to the greatest value item in the list. At this point, we don't know its position in the list, but we know its value.
Here's the AppleScript that performs this process:
set L to {4, 24, 78, 32, 1.5, 32, 78, 4, 19, 78}
set max to L's first item
repeat with x in L
if x > max then set max to x's contents
end repeat
return max
--> 78
2. Determining the index of a given item in a list
Putting aside the maximum value for now, the second half of the problem involves being able to determine the position of any given item in an ordered list.
The most obvious solution to this is, as before, iterating through each item in the list and performing this operation:
If the current item is equal to the target item, then append its index to the end of a list reserved for storing matching indices.
Once you reach the end of the list, your matched indices list will contain all the positions of the items whose value equal your target item's value; or the matched indices list will be an empty list, indicating that the main list does not contain the value we sought out.
The index of the first item in an AppleScript list is 1. Use the length property of a list to obtain the number of items in the whole list.
Here's a basic AppleScript:
set L to {4, 24, 78, 32, 1.5, 32, 78, 4, 19, 78}
set matches to {}
set target to 78
repeat with i from 1 to L's length
if item i of L = the target then set end of matches to i
end repeat
return the matches
--> {3, 7, 10}
3. The combined process
Combining these two halves of the problem is as simple as running each half in sequence, being mindful to use the result from the first half of the process—the maximum value—as the target value to be sought out in the list:
set L to {4, 24, 78, 32, 1.5, 32, 78, 4, 19, 78}
set max to L's first item
# Get maximum value
repeat with x in L
if x > max then set max to x's contents
end repeat
set matches to {}
set target to max
# Get index of maximum value
repeat with i from 1 to L's length
if item i of L = the target then set end of matches to i
end repeat
return the matches
--> {3, 7, 10}
Finally, as you only want the maximum index, this is simply the last value in the matches list, i.e. 10, which you obtain by replacing return the matches with this line:
return the last item in matches
--> 10
4. Efficiency improvements
Having outlined the basic methods in each process, these aren't necessarily the fastest methods. With lists containing only 10 items, inefficiency is not a noticeable concern. If you had a list of 10,000 items, you would want to be able to reduce the time to get your result.
I think I'm correct in stating that there's no discernible way to speed up the first process in terms of algorithmic improvements: retrieving the maximum value necessitates comparing every item's magnitude and retaining the largest.
Determining the index, however, can be sped up given that we only need to determine the last occurrence of an item in the list.
Therefore, we can run the process as before, but making two changes:
Start from the end of the list instead the beginning.
Stop the process once we find the first match.
Here's the script:
set L to {4, 24, 78, 32, 1.5, 32, 78, 4, 19, 78}
set max to L's first item
# Get maximum value
repeat with x in L
if x > max then set max to x's contents
end repeat
set target to max
# Get index of maximum value
repeat with i from L's length to 1 by -1
if item i of L = the target then exit repeat
end repeat
return i
--> 10
Note here the second repeat loop now runs backwards from the highest index down to 1; and, we no longer require the matches list, so instead we simply exit the loop when a match is found, and see what value of i we were at.
One further improvement to the algorithm here would be to test for the null case to determine whether or not we really need to run through the list at all: the null case is the case where the list doesn't contain the value we seek. AppleScript provides a builtin way to check this:
if the target is not in L then return 0
and this line would sit immediately after set target to max and immediately before repeat with i....
5. Advanced improvements
Another way to improve efficiency, after addressing efficiency of the algorithms themselves, is to address the efficiency of the way the script is written. This is more advanced than you need to concern yourself with now, but here's how I'd probably implement the algorithms if I were writing the script for my own use:
I would define a handler called maximum() that takes a list as its argument and returns the greatest value, and I would implement the scripting of this handler like so:
on maximum(L as list)
local L
if L is {} then return {}
if L's length = 1 then return L's first item
script Array
property x0 : L's first item
property xN : rest of L
property fn : maximum(xN)
property predicate : x0 > fn
end script
tell the Array
if its predicate is true then return its x0
its fn
end tell
end maximum
This uses something called a script object to process the items of the list, which is much, much quicker in AppleScript than conventional iterative repeat loop.
Next, I would define a second handler called lastIndexOf() that takes a supplied value and a list as its two arguments, and returns the highest index at which the supplied value occurs in the given list. My handler would look like this:
on lastIndexOf(x, L as list)
local x, L
if x is not in L then return 0
if L = {} then return
script Array
property x0 : L's last item
property xN : reverse of rest of reverse of L
property predicate : x0 ≠ x
end script
# For the last match only:
if Array's predicate is false then return (Array's xN's length) + 1
# For a match list (comment out line above):
tell the Array
if its predicate is false then ¬
return the lastIndexOf(x, its xN) ¬
& (its xN's length) + 1
return lastIndexOf(x, its xN)
end tell
end lastIndexOf
Then, all I need to do to obtain the result is:
set L to {4, 24, 78, 32, 1.5, 32, 78, 14, 19, 78}
get the lastIndexOf(maximum(L), L)
--> 10
But, don't try and understand what I've done here just yet, and concentrate on understanding the repeat loop algorithms.
I've included these more advanced versions for completeness and for readers who may have wondered, had I left this out, why I didn't provide the most optimal solution I could have.
Whilst the algorithm used in these advanced versions remains the same (it doesn't look like it, but it is), the way the code is written makes these incredibly efficient for large itemed lists.
Note, however, I haven't included any error handling, so if you were to pass those handlers a list that contained non-numerical items, at least one of them would complain.
The maximum value can be determined quite easy with help of AppleScriptObjC and Key-Value Coding
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use framework "Foundation"
set numberList to {18, 18, 18, 18, 22, 21, 22}
set nsNumberList to current application's NSArray's arrayWithArray:numberList
set maxValue to nsNumberList's valueForKeyPath:"#max.intValue") as integer -- 22
If there is only one occurrence of that value of if you want only the index of the first occurrence write
set maxIndex to ((nsNumberList's indexOfObject:maxValue) as integer) + 1 -- AppleScript's lists are 1-based
If there are multiple occurrences of that value and you need all indexes use a loop (unfortunately the efficient native Cocoa API indexesOfObjectsPassingTest: is not available in AppleScriptObjC)
set maxIndexes to {}
repeat with i from 0 to (count numberList) - 1 -- Cocoa's lists are 0-based
if (maxValue's isEqualToNumber:(nsNumberList's objectAtIndex:i)) then
set end of maxIndexes to i + 1
end if
end repeat
maxIndexes -- {5, 7}
I need to make a list of numbers. These numbers represent binary masks. The first 100 or so masks are all included in this range. In the next group of masks only certain masks are included. I need a list similar to the following.
[1,2,3,5,6,7,8,9,10,30,34,48,53,62]
Can I do something like [range(1,10),30,34,48,53,62]
or do I need to create my list using range(1,10) and then append the next list to it?
Thanks
Python 3 actually allow you to build a list literal prepending an * to any iterable objects - which are in turn expanded in place:
>>> [1,2, *range(10), *range(2)]
[1, 2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
If you need this n older Pythons, or if you'd prefer to keep readability for people not too proeficient in Python who might have to walk through your code, an option is just to concatenate your different list fragments using the + operator:
a = list(range(1,10)) + [ 30,34,48,53,62]
Looks like I had to use the list(range(1,10)+[47,34,57]
solution
I don't really understand why regular indexing can't be used for np.delete. What makes np.s_ so special?
For example with this code, used to delete the some of the rows of this array..
inlet_names = np.delete(inlet_names, np.s_[1:9], axis = 0)
Why can't I simply use regular indexing and do..
inlet_names = np.delete(inlet_names, [1:9], axis = 0)
or
inlet_names = np.delete(inlet_names, inlet_names[1:9], axis = 0)
From what I can gather, np.s_ is the same as np.index_exp except it doesn't return a tuple, but both can be used anywhere in Python code.
Then when I look into the np.delete function, it indicates that you can use something like [1,2,3] to delete those specific indexes along the entire array. So whats preventing me from using something similar to delete certain rows or columns from the array?
I'm simply assuming that this type of indexing is read as something else in np.delete so you need to use np.s_ in order to specify, but I can't get to the bottom of what exactly it would be reading it as because when I try the second piece of code it simply returns "invalid syntax". Which is weird because this code works...
inlet_names = np.delete(inlet_names, [1,2,3,4,5,6,7,8,9], axis = 0)
So I guess the answer could possibly be that np.delete only accepts a list of the indexes that you would like to delete. And that np._s returns a list of the indexes that you specify for the slice.
Just could use some clarification and some corrections on anything I just said about the functions that may be wrong, because a lot of this is just my take, the documents don't exactly explain everything that I was trying to understand. I think I'm just overthinking this, but I would like to actually understand it, if someone could explain it.
np.delete is not doing anything unique or special. It just returns a copy of the original array with some items missing. Most of the code just interprets the inputs in preparation to make this copy.
What you are asking about is the obj parameter
obj : slice, int or array of ints
In simple terms, np.s_ lets you supply a slice using the familiar : syntax. The x:y notation cannot be used as a function parameter.
Let's try your alternatives (you allude to these in results and errors, but they are buried in the text):
In [213]: x=np.arange(10)*2 # some distinctive values
In [214]: np.delete(x, np.s_[3:6])
Out[214]: array([ 0, 2, 4, 12, 14, 16, 18])
So delete with s_ removes a range of values, namely 6 8 10, the 3rd through 5th ones.
In [215]: np.delete(x, [3:6])
File "<ipython-input-215-0a5bf5cc05ba>", line 1
np.delete(x, [3:6])
^
SyntaxError: invalid syntax
Why the error? Because [3:4] is an indexing expression. np.delete is a function. Even s_[[3:4]] has problems. np.delete(x, 3:6) is also bad, because Python only accepts the : syntax in an indexing context, where it automatically translates it into a slice object. Note that is is a syntax error, something that the interpreter catches before doing any calculations or function calls.
In [216]: np.delete(x, slice(3,6))
Out[216]: array([ 0, 2, 4, 12, 14, 16, 18])
A slice works instead of s_; in fact that is what s_ produces
In [233]: np.delete(x, [3,4,5])
Out[233]: array([ 0, 2, 4, 12, 14, 16, 18])
A list also works, though it works in different way (see below).
In [217]: np.delete(x, x[3:6])
Out[217]: array([ 0, 2, 4, 6, 8, 10, 14, 18])
This works, but produces are different result, because x[3:6] is not the same as range(3,6). Also the np.delete does not work like the list delete. It deletes by index, not by matching value.
np.index_exp fails for the same reason that np.delete(x, (slice(3,6),)) does. 1, [1], (1,) are all valid and remove one item. Even '1', the string, works. delete parses this argument, and at this level, expects something that can be turned into an integer. obj.astype(intp). (slice(None),) is not a slice, it is a 1 item tuple. So it's handled in a different spot in the delete code. This is TypeError produced by something that delete calls, very different from the SyntaxError. In theory delete could extract the slice from the tuple and proceed as in the s_ case, but the developers did not choose to consider this variation.
A quick study of the code shows that np.delete uses 2 distinct copying methods - by slice and by boolean mask. If the obj is a slice, as in our example, it does (for 1d array):
out = np.empty(7)
out[0:3] = x[0:3]
out[3:7] = x[6:10]
But with [3,4,5] (instead of the slice) it does:
keep = np.ones((10,), dtype=bool)
keep[[3,4,5]] = False
return x[keep]
Same result, but with a different construction method. x[np.array([1,1,1,0,0,0,1,1,1,1],bool)] does the same thing.
In fact boolean indexing or masking like this is more common than np.delete, and generally just as powerful.
From the lib/index_tricks.py source file:
index_exp = IndexExpression(maketuple=True)
s_ = IndexExpression(maketuple=False)
They are slighly different versions of the same thing. And both are just convenience functions.
In [196]: np.s_[1:4]
Out[196]: slice(1, 4, None)
In [197]: np.index_exp[1:4]
Out[197]: (slice(1, 4, None),)
In [198]: np.s_[1:4, 5:10]
Out[198]: (slice(1, 4, None), slice(5, 10, None))
In [199]: np.index_exp[1:4, 5:10]
Out[199]: (slice(1, 4, None), slice(5, 10, None))
The maketuple business applies only when there is a single item, a slice or index.
I'm trying to reproduce the filters logic in csharp and was wondering what do the following filters mean?
As a start, I created a parsing tree having LogicalOperator Node, ComparisonOperator Node, Variable Node, Value Node.
The idea is that I could create a tree like this
=
/ \
COST_CENTRE 12456
I'm not sure how to interpret these theorical filters
8*..9*
8?..?12
>A*
>12?A*
Any ideas?
Thank you,
What is the problem Entering Criteria in Filters?
8*..9* result contains all records in which the field has values from (starting with digit 8) to (starting with digit 9), e.g. 8, 88, 838, 9, 91, 9034234 and so on.
8?..?12 result contains all records in which the field has values from (two-digit numbers starting with digit 8) to (three-digit numbers ending with digit 12), e.g. 80, 81, 89, 312, 412, 912 and so on.
>A* result contains all records in which the field has text values that is greater than A*, where A* is any string that starts with "A".
>12?A* result contains all records in which the field has text values that is greater than 12?A*, where 12?A* is any string that starts with "12" then it has any random symbol, then goes "A" and than any number of any symbols.
The most stupid filters I've ever seen!
I want to multiply every item in a list. But this example just returns every item:
list = 1..10
println list.each{it*2}
Use collect().
i.e.
list = 1..10
println list.collect{it*2}
Gives
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Only the syntax of Groovy is pegged to be standardized, not the default methods, so different implementations of Groovy have different names for the specific method to use.
In Codehaus Groovy (v 2.1.9 at groovy.codehaus.org) use collect...
list = 1..10
println list.collect{it*2}
In Real Groovy (v 0.10.0 at realgroovy.codeplex.com) use the more standardly named map...
test{
is [1,2,3,].map{it*7} == [7,14,21]
}
I'm not sure how GrooScript (at www.grooscript.org) does it.