String Index Out Of Range (Python) I have made bounds too - python

import time
password=input("What's your password?")
ans = ""
password=password.lower()
alpha = "abcdefghijklmnopqrstuvwxyz"
n = 0
a=0
starttime=time.time()
while ans !=password:
print(a)
for i in range(len(password)):
letter=alpha[n]
ans+=letter
if ans[a] != password[a]:
print(ans)
ans = ans.replace(ans[a],"")
n+=1
break
else:
a+=1
print(ans)
n=0
break
print("Password Found!")
endtime=time.time()
time=endtime-starttime
print("It took " + str(time) + " seconds!")
This is my code, sorry if i'm not posting it right (first time here). But let's digress, It seems i get an error of string index out of range
Traceback (most recent call last):
File "C:\Users\admin\Documents\Letter word cracker.py", line 15, in <module>
if ans[a] != password[a]:
IndexError: string index out of range
I was wondering how to fix this, because its been eating at my brain for days. Any help would be appreciated, thanks!

Ok, I don't know why you are trying to do this, what you are trying to do, the error is here due to this line
ans = ans.replace(ans[a],"") ---> X
what replace will do, is replace all the occurrences of a particular character from the array, while you only need to remove the last.
For example :-
If ans = "naa",
now replace will replace both 'a' while based on your logic you only want to remove the last element. because you have already matched till "na" and now in process of matching the third element.
You could probably do :-
ans = ans[:-1]
But again, this is a very very bad way to do this, because strings are immutable so you are basically creating and destroying strings every iteration.
One advice I would give is using list of characters instead of a string, it would not give a significant boost to the runtime for your program, for whatever reason you are using this.
EDIT:-
Also the for loop is unnecessary, as it is always breaking after first iteration. thanks #TigerHawk
import time
password=input("What's your password?")
ans = []
password=password.lower()
alpha = "abcdefghijklmnopqrstuvwxyz"
n = 0
a=0
starttime=time.time()
while "".join(ans) !=password:
letter=alpha[n]
ans.append(letter)
if ans[a] != password[a]:
ans.pop()
n+=1
else:
a+=1
n=0
print("Password Found!")
endtime=time.time()
time=endtime-starttime

This is a little better and more condensed version. From what I understand, you want to brute force a character string to compare it to a password.
import time
password=input("What's your password?")
password=password.lower()
alpha = "abcdefghijklmnopqrstuvwxyz"
starttime=time.time()
for letter in range(len(password)):
for index in range(len(alpha)):
if alpha[index] == password[letter]:
print "Letter",letter,"Found."
next
print "Password Found!"
endtime=time.time()
time=endtime-starttime
print "It took",time,"seconds!"

There are a few issues per the previous post, but the IndexError is happening because you are comparing each element of each list, and when one list runs out, it raises the IndexError exception. Wrap that part of the code in an if() that checks to see whether there are any more elements left over.
This will not fix the entire program, and in fact, you'll likely need a better way to do this comparison... I'm just explaining why the IndexError is happening.
if (ans[a] and password[a]):
if ans[a] != password[a]:
print(ans)
ans = ans.replace(ans[a],"")
n+=1
break

You should really go through your logic to understand why it isn't working, but there are many improvements you can make to your code. I have implemented a working version with a few improvements below.
from time import time
import string
#this will only work for a-z no whitespace, caps, numbers, etc.
pwd = raw_input("What is your password? ")
pwd = pwd.lower()
#create list of password for easier iterability
password = list(pwd)
#alphabet will have a-z lowercase
alphabet = list(string.ascii_lowercase)
#empty list to start
guess = []
#start timer
start = time()
#outer loop through password
for char in password:
#inner loop through alphabet
for letter in alphabet:
if letter == char:
guess.append(letter)
break
#print correct guess as string
end = time()
print "It took " + str(end - start) + " seconds to solve this password."
#verify correctness
print "".join(guess)
print pwd

Related

How to get next n[0:1] letter after each loop cycle in Python?

i got this python script:
The problem is i would like this loop to repeat but each time, it checks the next letter of the input, so loop1: n[0:1] loop2: n[1:2] and so on...
import time
while True:
n = input("Ltr:")
h = n[0:1]
if h==' ':
print(" ")
time.sleep(0.001)
if h=='a':
print("01100001")
time.sleep(0.001)
if h=='b':
print("01100010")
time.sleep(0.001)
if h=='c':
print("01100011")
time.sleep(0.001)
if h=='d':
print("01100100")
time.sleep(0.001)
So it basically goes on from a to z, also counts spaces and only supports lowercase letters.
If you already got it, it's an english-to-binary translator i'm trying to make, i dont want to import anything like plusgins and stuff, i want t make it by myself but i struggling with this... :(
Is there anyway to make it work ?
As explained here you can simply do the following:
test = input("enter text")
res = ''.join(format(ord(i), '08b') for i in test)
and res will contain your converted text.
If you are insisting on iterating through the string you can do the following:
string = input("enter string")
res = ''
for char in string:
res += format(ord(char), '08b')

String Index out of Range - Python 3.x.x with swapcase() function

I am trying to capitalize every other letter of a string which is given by and input. For some reason it give me the error 'string index out of range' and i have no idea why! the range is set from 0 to the length of the string so that cant be possible i thought!
s = input('Please enter a string: ')
p=s.lower()
o=s.upper()
q=p
k=len(s)
l=1
for x in range(0,k):
if l%2==0:
q=q[x].swapcase()
l+=1
else:
l+=1
print(q)
When you do this:
q=q[x].swapcase()
q becomes a single letter.
The next time around you try:
q[1]
but there is no q[1] because you made it a single letter.
This is one of several reasons why python encourages you to avoid creating index variables and instead looping over the items themselves. If you do that and give your variables more descriptive names, these kind of error are easier to catch. For example:
s = input('Please enter a string: ')
lower_case = s.lower()
new_string = ""
for index, letter in enumerate(lower_case):
if index % 2 == 0:
new_string += letter.swapcase()
else:
new_string += letter
print(new_string)

Syntax error python, not sure how to write the code

I am trying to write a code that tests a word to see if it is a palindrome or not. It is working but it prints NO in a loop before it gives the correct answer. I want it to just print the correct answer once.
I haven't really done anything, just checked the internet for some answers
x = str(input("enter the word:"))
w = ""
for i in x:
w = i + w
if x == w:
print("YES")
else:
print("NO")
It should print YES or NO once, now it prints many times before giving the correct answer.
indent the w= i + w line
x = str(input("enter the word:"))
w = ""
for i in x:
w = i + w
if (x==w):
print("YES")
else:
print("NO")
Please correct your indentation to make it possible to trouble shoot.
At first glance it appears your “if” statement is nested in side your “for” loop, thus checking for the palindrome after each letter is added.
If you put the if else inside the loop, its bound to print the result multiple times. Keep it out of the loop and it will print just once.
Welcome to the Community!
A shorter way to do this could be:`
x = str(input("enter the word:"))
if (x==x[::-1]):
print("YES")
else:
print("NO")
You may want to look into string slicing in python :)
Mark B already solved your issue but here is an additional method out of interest.
word = input("Enter word")
reverse = word[::-1]
if word == reverse:
print("Yes, plaindrome")
else:
print("No, not palindrome")
Use your for loop to create a new string ( reverse of string x ). Use conditional outside the for loop. Also, check for uppercase entry.

python if answer is correct display a well done message?

I'm trying to set a memory word game where the program reads a text file with 10 words. The program reads the file and creates a list of 9 out of the words .pop() the last word no.10. The words are randomly shuffled and then displayed again with a 2nd list of the same words randomly shuffled with the last word .pop() and the 1st removed is replacing the word (removed / substituted) - hope that sort of explains it.
I an having an issue regarding feeding back the right response whenter code hereen the user guesses the correct answer (it nots) everything else appears to be working.
import time
from random import shuffle
file =open('Words.txt', 'r')
word_list = file.readlines()
word_list [0:9]
shuffle(word_list)
extra_word=(word_list.pop())
print (extra_word)#substitute word for 2nd question (delete this line)
print '...............'
print (word_list)
print ('wait and now see the new list')
time.sleep(3)
print ('new lists')
word_list [0:9]
shuffle(word_list)
newExtra_word=(word_list.pop())
print (newExtra_word)#replace word for 1st question (delete this line)
word_list.insert(9,extra_word)# replace word
print (word_list)
This code above works fine (for what i want it to do..) The section below however:
#ALLOW FOR 3 GUESSES
user_answer = (raw_input('can you guess the replaced word: ')).lower()
count = 0
while count <=1:
if user_answer == newExtra_word:
print("well done")
break
else:
user_answer = (raw_input('please guess again: ')).lower()
count+=1
else:
print ('Fail, the answer is' + extra_word)
The code does allow for three guesses, but will not accept the removed list item. Does anyone have any ideas why?
Well, because your code above DOESN'T work the way you want it to.
file = open('Words.txt', 'r')
word_list = file.readlines()
# you should do file.close() here
word_list[0:9]
That last line doesn't actually do anything. It returns the first 10 elements in word_list but you never assign them to anything, so it's essentially a NOP. Instead do
word_list = word_list[0:9] # now you've removed the extras.
Probably better is to shuffle first so you have a truly random set of 10. Why 10? Why are we restricting the data? Oh well, okay...
# skipping down a good ways
word_list.insert(9, extra_word) # replace word
Why are we doing this? I don't really understand what this operation is supposed to do.
As for allowing three guesses:
count = 0
while count < 3:
user_answer = raw_input("Can you guess the replaced word: ").lower()
count += 1
if user_answer == newExtra_word:
print("well done")
break
else:
print("Sorry, the answer is " + extra_word)
Wait, did you catch that? You're checking the user input against newExtra_word then you're reporting the correct answer as extra_word. Are you sure your code logic works?
What it SOUNDS like you want to do is this:
with open("Words.txt") as inf:
word_list = [next(inf).strip().lower() for _ in range(11)]
# pull the first _11_ lines from Words.txt, because we're
# going to pop one of them.
word_going_in = word_list.pop()
random.shuffle(word_list)
print ' '.join(word_list)
random.shuffle(word_list)
word_coming_out = word_list.pop()
# I could do word_list.pop(random.randint(0,9)) but this
# maintains your implementation
word_list.append(word_going_in)
random.shuffle(word_list)
count = 0
while count < 3:
user_input = raw_input("Which word got replaced? ").lower()
count += 1
if user_input == word_coming_out:
print "Well done"
break
else:
print "You lose"

Cannot get simple while loop working in Python

LETTERS = "abc"
correct = "cab "
guess = ""
while guess != correct:
for i in LETTERS:
position = random.randrange(len(LETTERS))
guess += LETTERS[position]
LETTERS = LETTERS[:position] + LETTERS[(position + 1):]
print(guess)
I'm new in Python and I want to make this simple program:
With the letters "abc", jumble them and create a new three-lettter word randomly.
Print that jumble
Continue doing this loop until the computer jumbles "cab".
Then stop.
I came up with this code, and it gives me an infinite loop. I can't figure out why is doing it. I'm sure it's something easy but I can't see it. Need some help! Thanks!
You have three problems that I can see:
"cab " has a space in it, and LETTERS does not have a space. So you'll never be able to guess a space
You don't reset guess. You simply keep adding to it
You change LETTERS in your for-loop, so in the second iteration of your while-loop, it will be completely empty.
This is how I would go about doing what you're trying to do (with minimal modification):
_LETTERS = "abc"
correct = "cab"
guess = ""
while guess != correct:
LETTERS = _LETTERS[:]
guess = ""
for i in LETTERS:
position = random.randrange(len(LETTERS))
guess += LETTERS[position]
LETTERS = LETTERS[:position] + LETTERS[(position + 1):]
print(guess)
Here's how I would do a random search (which is what you're trying to do):
guess = "abc"
correct = "cab"
while guess != correct:
guess = list(guess)
random.shuffle(guess)
guess = ''.join(guess)
print(guess)
print(guess)
Of course, there are better techniques to correctly guess "cab". If you really want to try an exhaustive search, then you could use a backtracking DFS:
def DFS(letters, correct, sofar=None)
if sofar is None:
sofar = ''
if not letters:
if sofar == correct:
print("Yay! I found it")
else:
print("Oops! I found %s instead" %sofar)
else:
for i,char in enumerate(letters):
DFS(letters[:i]+letters[i+1:], correct, sofar+char)
Your correct value contains a space, but your loop never generates spaces:
correct = "cab "
Remove that space:
correct = "cab"
Next, your loop reduces LETTERS to an empty string, so only once does your loop produce a random guess, but afterwards, you forever are stuck with LETTERS = '', so no for loop is run.
You'd be better off using random.shuffle to produce guesses:
LETTERS = list("abc")
correct = "cab"
while True:
random.shuffle(LETTERS)
guess = ''.join(LETTERS)
if guess == correct:
print(guess)
break

Categories