Brute Force Hacker Concept in Python 3 - python-3.x

The code that i currently have will list all possible combinations
from itertools import product
password = "hr"
chars = 'abcdefghijklmnopqrstuvwxyz' #characters to look for, can have letters added
for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
print(''.join(attempt))
What i need it to do is take each tried attempt and compare it with the variable "password", if it matches break out of the for loop else carry on, any ideas?

One thing you could do to solve this would be to move your whole for length in range code block into a function:
def brute_force(chars, password):
for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
to_attempt = product(chars, repeat=length)
for attempt in to_attempt:
if ''.join(attempt) == password:
print("Found the password!")
return
The problem you're having is that you can only break out of a single loop. There's no built-in solution to say "break out of this loop, and its parent, and nothing else." I find that if you're unable to be using break or continue to move your control flow in the desired direction, just break it off into a function and use return.
This isn't really a problem, necessarily, but chars you're using right now will only ever be able to brute-force an all-letters, all-lower-case string, so it'll go through every single attempt and fail if the password is "Hr".

Related

Problem when printing output in Python (with easyinput)

So I'm having trouble with enters and line breaks in my code. I must use easyinput library (and import read).
My code stands for:
Input: Input consists of several cases separated by an empty line. Every case has three parts ('lines'). The first one is a line with the translation table: 26 different characters (with no spaces nor ‘_’), the first one corresponding to ‘a’, the second one to ‘b’, …, and the last one to ‘z’. The second part is a number n > 0 in a line. The third part consists of n encrypted lines of text.
Output: For each case, write the original text, also with n lines. Change each ‘_’ of the encrypted text for a space. Write an empty line at the end of each case.
So I figured out how to solve the problem, the things is that my code prints 'well' entering line by line in input. But the problem input must be entered the whole entire. I put an example for better understanding:
Some input should be:
52-!813467/09*+.[();?`]<:>
6
5_3++!_305))_6*_;48_26)4+.)_4+);80_6*_;48_!8`60)_)85;
;]8*;:_+*8_!83(88)_5*!_;46(;88*_96*?;8)
*+(;485);_5*!_2:_*+(;4
956*_2(5*-4_)8`8*;4_0692_85);_)6!8
)4++;_1(+9_;48_081;_8:8_+1_;48_!85;4)_485!
5_288_06*8_1(+9_;48_;(88_;4(+?34_;48_)4+;_161;:_188;_+?;
bcdefghijklmnopqrstuvwxyza
3
cfxbsf_pg_cvht_jo_uif_bcpwf_dpef
j_ibwf_pomz_qspwfe_ju_dpssfdu
opu_usjfe_ju
And its output must be:
a good glass in the bishops hostel in the devils seat
twenty one degrees and thirteen minutes
northeast and by north
main branch seventh limb east side
shoot from the left eye of the deaths head
a bee line from the tree through the shot fifty feet out
beware of bugs in the above code
i have only proved it correct
not tried it
My code far now is:
from easyinput import read
abc = 'abcdefghijklmnopqrstuvwxyz'
values = [letter for letter in abc]
old_abc = read(str)
while old_abc is not None:
keys = [old_letter for old_letter in old_abc]
dict_abc = dict(zip(keys, values))
num_lines = read(int)
for i in range(num_lines):
line = read(str)
for j in line:
if j == '_':
print(' ', end = '')
else:
print(dict_abc[str(j)], end = '')
print('\n')
old_abc = read(str)
I do not find a way of making my code easier, I just want some help to finally print the desired output. Thanks

How do I achieve this following function only using while loop?

I'm currently working on this problem that ask me to generate an arrow pattern using loops function that looks something like this:
"How many columns? 3"
*
*
*
*
*
I know I can do this with for loop(probably more efficient too), but that is not what I aimed for. I wanted to achieve this only using while loop.
I have some ideas:
1. I set up a control variable and an accumulator to control the loop
2. I then write 2 separate loops to generate the upper and lower part of the pattern. I was thinking about inserting the space before the asterisks using method like this:
(accumulator - (accumulator - integer)) * spaces.
#Ask the user how many column and direction of column
#they want to generate
Keep_going = True
Go = 0
while keep_going:
Column_num = int(input("How many columns? "))
if Column_num <= 0:
print("Invalid entry, try again!")
else:
print()
Go = 1
#Upper part
while Keep_going == True and Go == 1:
print("*")
print(""*(Column_num - (Column_num - 1) + "*")
...but I soon realized it wouldn't work because I don't know the user input and thus cannot manually calculate how many spaces to insert before asterisks. Now everything on the internet tells me to use for loop and range function, I could do that, but I think that is not helpful for me to learn python since I couldn't utilize loops very well yet and brute force it with some other method just not going to improve my skills.
I assume this is achievable only using while loop.
#Take your input in MyNumber
MyNumber = 5
i = 1
MyText = '\t*'
while i <=MyNumber:
print(MyText.expandtabs(i-1))
i = i+1
i = i-1
while i >=1:
print(MyText.expandtabs(i-1))
i = i-1
Python - While Loop
Well first you have to understand that a while loop loops until a requirement is met.
And looking at your situation, to determine the number of spaces before the * you should have an ongoing counter, a variable that counts how many spaces are needed before you continue. For example:
###Getting the number of columns###
while True:
number=int(input('Enter number of rows: '))
if number<=0:
print('Invalid')
else:
###Ending the loop###
break
#This will determine the number of spaces before a '*'
counter=0
#Loops until counter equals number
while counter!=number:
print(" "*counter + "*")
#Each time it loops the counter variable increases by 1
counter=counter+1
counter=counter-1
#Getting the second half of the arrow done
while counter!=0:
counter=counter-1
print(" "*counter + "*")
Please reply if this did not help you so that i can give a more detailed response

Multiplication table in Python with # on all even numbers

I am trying to create a python multiplication table from 2 - 10. If you enter an invalid number it will tell you that it is an invalid entry and ask you to input a number again. It is also supposed to put a # on all even numbers. I am having trouble continuing after an invalid entry and also putting a # on all even numbers. My current code is below
def main():
rows = int(input("What size multiplication table would you like (2-10): "))
if rows <=1 or rows >10:
print (" Invalid Entry - Enter a number between 2 - 10 ")
else:
counter = 0
multiplicationTable(rows,counter)
def multiplicationTable(rows,counter):
size = rows + 1
for i in range (1,size):
for nums in range (1,size):
value = i*nums
print(value,sep=' ',end="\t")
counter += 1
if counter%rows == 0:
print()
else:
counter
main()
I am typing this on my phone so bear with me.
Since you are trying to only get a certain input, you want to have a loop so that we can keep asking the user to enter a number if it is outside the range we want.
So in a generic example where we repeatedly ask a user for a certain input:
While True:
rows = int(input(“enter size: “))
if 1 <= rows < 10:
multiplicationTable(rows, 0)
break
else:
print(“Invalid”)
continue
While True: will run infinitely naturally. However, the magic is in the continue and break statements. continue will make it restart at the top of the loop and break will make it exit the loop after the process is done.
note:
Some programmers consider it bad practice to use the loops in this fashion because it could imply poor logic.
If you need help with an alternate solution I can try and help when I get to my computer.
Best of luck!

Python Counting the exchanges in a selection sort

I apologize as this is my first question on this site and it is extremely basic, but I am somewhat lost in a current lab I am trying to complete.
Currently I am attempting to count the amount of exchanges(Or swaps? Not sure on the right word there!) during a selection sort throughout the passes.
Now according to my current understanding, the replacement section of our formula is traversing my list. However, it doubles the amount of swaps it is actually supposed to be spitting back at me. Now this would lead me to believe an if statement might need to be operating in the outer loop, but that doesn't seem quite right to me.
An example of what I have done to cause this problem below. I am curious if I am on the right path or should I slash and burn or go back to the drawing board.
The reason I am counting them independently is I am displaying when there is a swap then a grand total of all the swaps. Which I find to be a bit ironic as with a selection sort you can only have 1 swap per pass?
Any case, I apologize for the rather basic question, but I seem to be missing something so I was hoping someone could point me in the right direction of if I should be focusing on the outer loop to determine the exchanges?
print( "Original list:" , a_list, "\n" )
count =1
n = len(a_list)
comp = n -1
exchanges=1
comp_total=0
exch_total=0
for end in range(n, 1, -1): # Each pass starts here
#Setting our running total to adjust for previous value.
comp_total +=comp-(count-1)
print("Pass", count, ":", "Comparisons:",comp-(count-1), "\tExchanges:", exchanges,"\n", end="\t ")
count += 1
# --- Search for Largest ---
min_position = 0
for i in range(1, end):
if a_list[i] > a_list[min_position]: # Perform n
min_position = i
exchanges = 0
exch_total +=1
else:
exchanges = 1
# --------------------------
temp = a_list [end - 1] # Perform exchange
a_list [end - 1] = a_list [min_position]
a_list [min_position] = temp
print(a_list)
print()
print("\tTotal Comparisons:",comp_total, "Total Exchanges:", exch_total)
selection_sort(a_list)
In this case,
My issue was the the fact my print statement was before the actual loop, this was throwing off my count, by placing the if statement past this point, I was able to get an accurate running total!
Cheers!

using a looop to add user input to the set and dict in order discovered

So I'm trying to write a small program that does a few things. First is:
Write a while loop that repeatedly creates a list of words from a line of input from the user. So I did this:
s = input("Please enter a sentence: ")
while True:
pos = 0
for c in s:
if c == " ":
print(s[:pos])
s = s [pos+1:]
break
pos += 1
else:
print(s)
break
I need to add the user inputted words to the set and dict and then display their value in the order in which the program discovered them. I believe I need another loop but I'm not sure. I'm pretty lost at this point and the above is as far as I can seem to come on this program. Any help is appreciated as I am (obviously)new at python.

Resources