Having trouble with an index Error - python

I am doing an assignment for my first computer programming course, and I am running into a problem. Basically this program is supposed to take a phonetically Hawaiian word, and produce a string that shows how to prounce it. However when I run the program, this happens:
stopProgram = 1
while stopProgram == 1:
validWord = 0
while validWord == 0:
#this while loop is has the user enter a word until it means Hawaiian syntax.
userWord = input("Please enter a valid hawaiian word.")
userWordEval = userWord.lower()
#changed the case for easier comparisons
validInput = 0
for j in range (len(userWordEval)):
#Test every character in the word to see if it meets the requirements. If it does, valid word is added 1.
if userWordEval[j] == "a" or userWordEval[j] == "e" or userWordEval[j] == "i" or userWordEval[j] == "o" or userWordEval[j] == "u" or userWordEval[j] == "p" or userWordEval[j] == "k" or userWordEval[j] == "h" or userWordEval[j] == "l" or userWordEval[j] == "m" or userWordEval[j] == "n" or userWordEval[j] == "w" or userWordEval[j] == "'" or userWordEval[j] == " ":
validInput += 1
if validInput == len(userWordEval):
#if the number in validWord is equal to the length of the word the user put in, that means that all the charaters were accepted. Otherwise, that means that something wasn't allowed, and will have to be reentered.
validWord = 1
else:
print("Invalid input. The accepted characters are: a, e, i, o, u, p, k, h, l, m, n, w, and '")
proWord = "" #Using this for the pronunciation string.
q = 0
while q <= len(userWordEval):
if userWordEval[q] == "a":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-eye"
q += 2
elif userWordEval[q+1] == "e":
proWord += "-eye"
q += 2
elif userWordEval[q+1] == "o":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-ah"
q += 2
else:
proWord += "-ah"
q += 1
else:
proWord += "-ah"
q += 1
elif userWordEval[q] == "e":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-ay"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-eh"
q += 2
else:
proWord += "-eh"
q += 1
else:
proWord += "-eh"
q += 1
elif userWordEval[q] == "i":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "u":
proWord += "-ay"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-ee"
q += 2
else:
proWord += "-ee"
q += 1
else:
proWord += "-ee"
q += 1
elif userWordEval[q] == "o":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-oy"
q += 2
elif userWordEval[q+1] == "u":
proWord += "-ow"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-oh"
q += 2
else:
proWord += "-oh"
q += 1
else:
proWord += "-oh"
q += 1
elif userWordEval[q] == "u":
if len(userWordEval[q:]) > 1:
if userWordEval[q+1] == "i":
proWord += "-ooey"
q += 2
elif userWordEval[q+1] == "'":
proWord += "-oo"
q += 2
else:
proWord += "-oo"
q += 1
else:
proWord += "-oo"
q += 1
else:
q + 1
print(proWord)
stopProgram = 0
Output:
Please enter a valid hawaiian word.aeae Traceback (most recent call last):
File "C:/Users/Kristopher/Documents/Programming HW/Program
3.py", line 26, in <module>
if userWordEval[q] == "a": IndexError: string index out of range

string's index is from 0 to length-1. So change the while loop condition in line 24 to:
while q < len(userWordEval):

Your problem is that you are looping while q <= len(userWordEval). First of all, it is important to know that in python lists use zero-based indexing (see description on Wikipedia). This means that if there are 5 elements in a list, the last element will have index 4. The function len returns the number of elements in a list, so if you use that number as an index it will be too large. You can easily fix this by changing to q < len(userWordEval).

Remember list, string, tuple or other types which support indexing will raise IndexError if you try to access element past the index.
>>> a = 'apple'
>>> a[0]
'a'
>>> a[4]
'e'
>>> a[5]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a[5]
IndexError: string index out of range
So always use len(s)-1
>>> a[len(a)-1]
'e'
>>>
One nice bit of gotcha here. However during slicing you won't get that error. It will simple return an empty string/list.
>>> a[5:]
''
>>> a[:11]
'apple'

Related

How can you check if brainf*ck program is in an loop more than 5 seconds in python?

I am making a program that makes a random Brainf*ck program in python and runs it. I have an interpreter and I need it to check for long loops (more than 5 seconds).
The interpreter is:
while i < len(code):
if code[i] == '<':
if pointerLocation > 0:
pointerLocation -= 1
elif code[i] == '>':
pointerLocation += 1
if len(array) <= pointerLocation:
array.append(0)
elif code[i] == '+':
array[pointerLocation] += 1
elif code[i] == '-':
if array[pointerLocation] > 0:
array[pointerLocation] -= 1
elif code[i] == '.':
print(array[pointerLocation], chr(array[pointerLocation]))
result += chr(array[pointerLocation])
elif code[i] == ',':
#x = input("Input (1 CHARACTER!):")
x = 'h'
#increase time if user inputs
t1 += 5
try:
y = int(x)
except ValueError:
y = ord(x)
array[pointerLocation] = y
elif code[i] == '[':
if array[pointerLocation] == 0:
open_braces = 1
while open_braces > 0 and i+1 < len(code):
i += 1
if code[i] == '[':
open_braces += 1
elif code[i] == ']':
open_braces -= 1
elif code[i] == ']':
# you don't need to check array[pointerLocation] because the matching '[' will skip behind this instruction if array[pointerLocation] is zero
open_braces = 1
while open_braces > 0:
if t > 5:
return [result,code,t]
print(123)
i -= 1
if code[i] == '[':
open_braces -= 1
elif code[i] == ']':
open_braces += 1
# i still gets incremented in your main while loop
i -= 1
i += 1
Sorry for the long snippet, but I do believe it is all neccessary.
Set up an alarm when you enter the loop for 5 seconds. Cancel it when you exit. If the signal triggers then you handle it.
A weaker version of this is to obtain the time when you enter the loop, then check on each iteration to see if it's more than 5 seconds on each iteration.

Getting wrong result when adding random values in string format

I'm trying to make a script that receives a number of desired random numbers as input, and then generates and prints them.
However, my script adds the numbers instead of joining the strings. I would like for the strings to join so it would generate the pins like:
Enter the amount of lunch pins to generate:
10
26141
128111
937502
2436
56516
83623
246317
My code:
import random
PTG = int(input("Enter the amount of pins to generate: \n"))
PG = 0
PS = ""
while PTG > PG:
RN1 = random.randint(0, 9)
RN2 = random.randint(0, 9)
RN3 = random.randint(0, 9)
RN4 = random.randint(0, 9)
RN5 = random.randint(0, 10)
RN6 = random.randint(0, 10)
if RN1 == 0:
PS += "0"
elif RN1 == 1:
PS += "1"
elif RN1 == 2:
PS += "2"
elif RN1 == 3:
PS += "3"
elif RN1 == 4:
PS += "4"
elif RN1 == 5:
PS += "5"
elif RN1 == 6:
PS += "6"
elif RN1 == 7:
PS += "7"
elif RN1 == 8:
PS += "8"
elif RN1 == 9:
PS += "9"
elif RN2 == 0:
PS += "0"
elif RN2 == 1:
PS += "1"
elif RN2 == 2:
PS += "2"
elif RN2 == 3:
PS += "3"
elif RN2 == 4:
PS += "4"
elif RN2 == 5:
PS += "5"
elif RN2 == 6:
PS += "6"
elif RN2 == 7:
PS += "7"
elif RN2 == 8:
PS += "8"
elif RN2 == 9:
PS += "9"
if RN3 == 0:
PS += "0"
elif RN3 == 1:
PS += "1"
elif RN3 == 2:
PS += "2"
elif RN3 == 3:
PS += "3"
elif RN3 == 4:
PS += "4"
elif RN3 == 5:
PS += "5"
elif RN3 == 6:
PS += "6"
elif RN3 == 7:
PS += "7"
elif RN3 == 8:
PS += "8"
elif RN3 == 9:
PS += "9"
elif RN4 == 0:
PS += "0"
elif RN4 == 1:
PS += "1"
elif RN4 == 2:
PS += "2"
elif RN4 == 3:
PS += "3"
elif RN4 == 4:
PS += "4"
elif RN4 == 5:
PS += "5"
elif RN4 == 6:
PS += "6"
elif RN4 == 7:
PS += "7"
elif RN4 == 8:
PS += "8"
elif RN4 == 9:
PS += "9"
elif RN5 == 0:
PS += "0"
elif RN5 == 1:
PS += "1"
elif RN5 == 2:
PS += "2"
elif RN5 == 3:
PS += "3"
elif RN5 == 4:
PS += "4"
elif RN5 == 5:
PS += "5"
elif RN5 == 6:
PS += "6"
elif RN5 == 7:
PS += "7"
elif RN5 == 8:
PS += "8"
elif RN5 == 9:
PS += "9"
elif RN5 == 10:
PS += ""
elif RN6 == 0:
PS += "0"
elif RN6 == 1:
PS += "1"
elif RN6 == 2:
PS += "2"
elif RN6 == 3:
PS += "3"
elif RN6 == 4:
PS += "4"
elif RN6 == 5:
PS += "5"
elif RN6 == 6:
PS += "6"
elif RN6 == 7:
PS += "7"
elif RN6 == 8:
PS += "8"
elif RN6 == 9:
PS += "9"
print(PS)
PG += 1
PS = ""
Python version: 3.7.4
import random
# PTG = int(input("Enter the amount of pins to generate: \n"))
PTG = 10
PG = 0
PS = ""
while PTG > PG:
RN1 = random.randint(0, 9)
RN2 = random.randint(0, 9)
RN3 = random.randint(0, 9)
RN4 = random.randint(0, 9)
RN5 = random.randint(0, 10)
RN6 = random.randint(0, 10)
PS = str(RN1) + str(RN2) + str(RN3) + str(RN4) + str(RN5) + str(RN6)
print(int(PS))
PG += 1
When I understand your code right, you want to generate n pins with 6 digits. You can do that a lot easier than you want to:
number_of_pins = int(input("Enter the amount of pins to generate: \n"))
pins = []
for i in range(number_of_pins):
pins.append(str(random.randint(100_000, 999_999)))
print(" ".join(pins))
Explaination:
pins = [] makes a new empty list to store the pins
for i in range(n): executes the following indented block n times.
pins.append(random.randint(100_000, 999_999)) generates a random number and adds it to the list. 100000 is the first number with 6 digits and 999999 is the last. (The _ is just for readability). str() converts it to a string.
print(" ".join(pins)) joins all the pins and puts a space between.
Let's go through your code step by step:
First, notice that random.randint returns an int. Therefore you need to convert it to a String.
You can use the str() function in order to convert it to a string, for example:
str(random.randint(0, 9))+"9"
will return a string like 59 (for example).
Therefore, when initializing each random number, you need to do it the following way, for example:
RN1 = str(random.randint(0, 9))
Then, instead of checking the value of each random variable, you can just add them up:
PS = RN1 + RN2 + RN3 + RN4 + RN5 + RN6
Furthermore, instead of using six different variables to handle the random values, you can use a for loop for the first four which are from 0 to 9:
for x in range(4):
RN = str(random.randint(0, 9))
PS += RN
And then add the remaining two that are between 0 and 10:
PS += str(random.randint(0, 10))
PS += str(random.randint(0, 10))

Using if statements

I am attempting to make a simple Python code that replaces numbers with roman numerals. In order to do this, I need to get the position of each number to replace it with the roman numeral equivalent. However, my code doesn't seem to work.
number = range(1,21)
number = list(number)
number = str(number)
for i in number:
for x in i:
if i.index(x) == 0:
if x == "1":
x.replace(x, "X")
elif x == "2":
x.replace(x, "XX")
else:
if x == 1:
x.replace(x, "I")
elif x == 2:
x.replace(x, "II")
elif x == 3:
x.replace(x, "III")
elif x == 4:
x.replace(x, "IV")
elif x == "5":
x.replace(x, "V")
elif x == "6":
x.replace(x, "VI")
elif x == "7":
x.replace(x, "VII")
elif x == "8":
x.replace(x, "VIII")
elif x == "9":
x.replace(x, "IX")
else:
x.replace(x, "")
print number
I suspect that it has to do with the way that my if statements work, but I'm not sure. Any advice would be appreciated.
A long sequence of if and elif clauses is usually a sign that one should be using one or more dicts.
numstrings = [str(i) for i in range(1, 100)]
d0 = {'0':'', '1':'I', '2':'II', '3':'III', '4':'IV',
'5':'V', '6':'VI', '7':'VII', '8':'VIII', '9':'IX'}
d10 = {'0':'', '1':'X', '2':'XX', '3':'XXX', '4':'XL',
'5':'L', '6':'LX', '7':'LXXX', '8':'LXXX', '9':'XC'}
for s in numstrings:
if len(s) == 1:
r = d0[s]
elif len(s) == 2:
r = d10[s[0]] + d0[s[1]]
else:
r = '??'
print(r)

Logic Error in Most Common Letter Finder

So, this program simply lets the user enter a string, and counts the occurrence of each character, then displayed the most frequent.
I enter "AABBCCC", and it tells me that the max is 7, and that the most frequent is "Q".
countList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 \
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
index = 0
for character in userInput:
if character == "Q" or "q":
countList[0] += 1
elif character == "W" or "w":
countList[1] += 1
elif character == "E" or "e":
countList[2] += 1
elif character == "R" or "r":
countList[3] += 1
elif character == "T" or "t":
countList[4] += 1
elif character == "Y" or "y":
countList[5] += 1
elif character == "U" or "u":
countList[6] += 1
elif character == "I" or "i":
countList[7] += 1
elif character == "O" or "o":
countList[8] += 1
elif character == "P" or "p":
countList[9] += 1
elif character == "A" or "a":
countList[10] += 1
elif character == "S" or "s":
countList[11] += 1
elif character == "D" or "d":
countList[12] += 1
elif character == "F" or "f":
countList[13] += 1
elif character == "G" or "g":
countList[14] += 1
elif character == "H" or "h":
countList[15] += 1
elif character == "J" or "j":
countList[16] += 1
elif character == "K" or "k":
countList[17] += 1
elif character == "L" or "l":
countList[18] += 1
elif character == "Z" or "z":
countList[19] += 1
elif character == "X" or "x":
countList[20] += 1
elif character == "C" or "c":
countList[21] += 1
elif character == "V" or "v":
countList[22] += 1
elif character == "B" or "b":
countList[23] += 1
elif character == "N" or "n":
countList[24] += 1
elif character == "M" or "m":
countList[25] += 1
elif character == "`":
countList[26] += 1
elif character == "~":
countList[27] += 1
elif character == "1":
countList[28] += 1
elif character == "!":
countList[29] += 1
elif character == "2":
countList[30] += 1
elif character == "#":
countList[31] += 1
elif character == "3":
countList[32] += 1
elif character == "#":
countList[33] += 1
elif character == "4":
countList[34] += 1
elif character == "$":
countList[35] += 1
elif character == "5":
countList[36] += 1
elif character == "%":
countList[37] += 1
elif character == "6":
countList[38] += 1
elif character == "^":
countList[39] += 1
elif character == "7":
countList[40] += 1
elif character == "&":
countList[41] += 1
elif character == "8":
countList[42] += 1
elif character == "*":
countList[43] += 1
elif character == "9":
countList[44] += 1
elif character == "(":
countList[45] += 1
elif character == "0":
countList[46] += 1
elif character == ")":
countList[47] += 1
elif character == "-":
countList[48] += 1
elif character == "_":
countList[49] += 1
elif character == "=":
countList[50] += 1
elif character == "+":
countList[51] += 1
elif character == "[":
countList[52] += 1
elif character == "{":
countList[53] += 1
elif character == "]":
countList[54] += 1
elif character == "}":
countList[55] += 1
elif character == "\\":
countList[56] += 1
elif character == "|":
countList[57] += 1
elif character == ";":
countList[58] += 1
elif character == ":":
countList[59] += 1
elif character == "'":
countList[60] += 1
elif character == "\"":
countList[61] += 1
elif character == ",":
countList[62] += 1
elif character == "<":
countList[63] += 1
elif character == ".":
countList[64] += 1
elif character == ">":
countList[65] += 1
elif character == "/":
countList[66] += 1
elif character == "?":
countList[67] += 1
mostFrequent = max(countList)
print(mostFrequent)
characterKey = ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A" \
, "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M" \
, "`", "~", "1", "!", "2", "#", "3", "#", "4", "$", "5", "%", "6", "^", "7" \
, "&", "8", "*", "9", "(", "0", ")", "-", "_", "=", "+", "[", "{", "]", "}" \
, "\\", "|", ";", ":", "'", "\"", ",", "<", ".", ">", "/", "?"]
index = 0
for character in countList:
if character == mostFrequent:
print(characterKey[index], "is most frequent.")
index += 1
One of the issues that you are dealing with is that
elif character == "T" or "t"
does not work the way you think it does. You must restate the left-handed side of the expression again, like this:
elif character == "T" or character == "t"
or you can use the in operator:
elif character in ("T,"t")
However, changing this is not going to completely fix your issue.
One thing that would help your code be cleaner and faster would be to look into translating the character value that you receive into an integer value, and then using the integer value as a means of putting the character into the right index of the array. I'll leave that exercise to you :)
I think the use of a dict would save you some code. .lower() can prevent you having to check each as I'm assuming that for your puposes 't is eqivalent to 'T'. Note that helper function is expecting a string that is not Null. Hope this can help
def get_character_frequency(user_input):
'''return dictionary of frequencies to characters'''
char_freq_dict = {}
freq_char_dict = {}
#create dict with characters as keys and freqs as values
for character in user_input:
char_freq_dict[character] = char_freq_dict.get(character, 0) + 1
#invert dict
for character, freq in char_freq_dict.items():
if freq in freq_char_dict.keys():
freq_char_dict[freq].append(character)
else:
freq_char_dict[freq] = [character]
return freq_char_dict
def main():
#you could add some code to ensure some text is entered, or
#modify to error check for this
userInput = input("Enter String: ").lower()
freq_char_dict = get_character_frequency(userInput)
max_freq, max_char = sorted(freq_char_dict.items(), reverse=1)[0]
print('\n{} characters were entered'.format(len(userInput)))
print('Most frequent character(s) {}'.format(max_char), end=" ")
print('Ocurring {} time(s)'.format(max_freq))
main()
This will help you.
import re
import itertools
import operator
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
# print 'SL:', SL
groups = itertools.groupby(SL, key=operator.itemgetter(0))
# auxiliary function to get "quality" for an item
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
# print 'item %r, count %r, minind %r' % (item, count, min_index)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
user_input = [_.lower() for _ in raw_input("Enter String: ")]
frequent = most_common(list(user_input))
print "Most frequent entry:",frequent
print "Number of Occerences:",user_input.count(frequent)
OUTPUT:
Enter String: aAbBBcccC12309u/.,;'/*
Most frequent entry: c
Number of Occerences: 4

Project Euler 22, off by 18,609

I'm working on problem 22 of Project Euler:
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
My code (below) gets the answer 871179673. The correct answer should be 871198282, which makes me off by about 18k.
def score(name, pos):
score = 0
for letter in name:
if letter == "A": score += 1
elif letter == "B": score += 2
elif letter == "C": score += 3
elif letter == "D": score += 4
elif letter == "E": score += 5
elif letter == "F": score += 6
elif letter == "G": score += 7
elif letter == "H": score += 8
elif letter == "I": score += 9
elif letter == "J": score += 10
elif letter == "K": score += 11
elif letter == "L": score += 12
elif letter == "M": score += 13
elif letter == "N": score += 14
elif letter == "O": score += 15
elif letter == "P": score += 16
elif letter == "Q": score += 17
elif letter == "R": score += 18
elif letter == "S": score += 19
elif letter == "T": score += 20
elif letter == "U": score += 21
elif letter == "V": score += 22
elif letter == "W": score += 23
elif letter == "X": score += 24
elif letter == "Y": score += 25
elif letter == "Z": score += 26
else: score += 0
# end for loop.
return score * pos
#end def score.
f = open('names.txt')
string = f.readlines()
f.close()
names = sorted(str(string).split(","))
tscore = 0
pos = 1
for name in names:
tscore += score(name, pos)
pos += 1
#end for loop.
print tscore
If I run the 'Colin' example through my score function, I get the right result. I've tested a few other names from the list, and they score correctly as well. I googled the question and got various solutions, but since I'm new to python I'd like to learn what I did wrong. Thanks for your time!
Change this line:
names = sorted(str(string).split(","))
to:
names = sorted(string[0].split(','))
File contains just one line, so you need to access that line using string[0]. file.readlines returns a list containing all lines from the file, it's better to do something like:
names = f.read().split(',')
names.sort()
A shorter version of your program:
from string import ascii_uppercase
def score(word):
return sum(ascii_uppercase.index(c) + 1 for c in word.strip('"'))
with open('names.txt') as f:
names = f.read().split(',')
names.sort()
print sum(i*score(x) for i, x in enumerate(names, 1))
Note: string is a built-in module, don't use it as a variable name
import string
with open("names.txt",'r') as f:
d=f.read()
d=d.replace('"','')
#print(d)
names=d.split(',')
#print(names)
names.sort()
print(names)
gro=dict()
result=string.ascii_uppercase
count=1
for i in result:
gro[i]=count
count+=1
#print(gro)
sum=0
for ind,value in enumerate(names):
#print(ind,value)
temp=0
for x in value:
temp+=gro[x]
print(temp)
sum+=temp*(ind+1)
print(sum)
my way:
splitted = open('names.txt').read().replace('","',',').replace('"','').split(',')
description:
open the file, then read it, after that remove double qoutes by repalce them with none and at the end split the whole string by comma (,)
good luck

Categories