def cipherText():
text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = int(input("Enter numerical key--"))
word = str(input("Type word to be ciphered--"))
i = 0
k = 0
n = len(word)
print(n)
while n >= 0:
letter = word[i]
i = i + 1
while k <= 25:
textLetter = text[k]
if textLetter == letter:
givenLetter = letter
if k < (25 - key):
cipherLength = k + key
else:
cipherLength = k + key - 25
print(text[cipherLength])
k = k + 1
n = n - 1
cipherText()
WHEN I RUN THIS FOLLOWING MESSAGE POPS OUT:
Traceback (most recent call last): File "main.py", line 23, in
cipherText() File "main.py", line 10, in cipherText
letter=word[i] IndexError: string index out of range
You need to modify condition while n>=0:, as list starts with 0th index.
this line,
while n>=0:
should be,
while n-1>=0:
Related
I'm developing a function that returns the longest word from a string, my code is :
def longestWord(sen):
max = 1
i = 0
ind = 1
while ind != 0 :
if sen[i] == " ":
i = i+1
word = ""
lenth = 0
while(sen[i] != " " and i < len(sen)):
word = word + sen[i]
lenth = lenth+1
if(lenth > max):
max = lenth
longestword = word
i = i+1
if i == len(sen)-1:
ind = 0
return longestword
print(longestWord("ceci est un texte"))
When I try to run it an error shows up saying that "string index out of range"
The error message:
Traceback (most recent call last):
File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 25, in <module>
print(longestWord("ceci est un texte"))
File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 11, in longestWord
while(sen[i] != " " and i < len(sen)):
IndexError: string index out of range
Seems like a very complicated way. A simple pythonic way would be:
def longest_word(s):
return max(s.split(), key=len)
Output:
>>> longest_word("ceci est un texte")
"texte"
You can do this in one line
def longest_word(sentence):
return sorted(sencente.split(), key = lambda x: len(x))[-1]
print(longest_word("ceci est un texte"))
If you want to capture the results in a list, because multiple words may be the same length.
def longest_words(sentence):
words = sentence.split()
maxlen = max(len(w) for w in words)
return [w for w in words if len(w) == maxlen]
Or in one pass:
def longest_words(sentence):
words = sentence.split()
results = []
maxlen = 0
for w in words:
curlen = len(w)
if curlen > maxlen:
results = [w]
maxlen = curlen
elif curlen == maxlen:
results.append(w)
return results
Replace your function with this one :
def longestWord(string) :
lettersCounter = 0
result = ""
for word in string.split() :
if(len(word) > lettersCounter) :
lettersCounter = len(word)
result = word
return result
print(longestWord("ceci est un texte"))
I get an index -1 is out of bounds for axis 0 with size 0 error from scipy when trying to implement a text generator with ngrams.
Traceback (most recent call last):
File "C:\Users\hp\PycharmProjects\N-gram poems\trigram_model.py", line 125, in <module>
generate()
File "C:\Users\hp\PycharmProjects\N-gram poems\trigram_model.py", line 118, in generate
singleverse(int(c))
File "C:\Users\hp\PycharmProjects\N-gram poems\trigram_model.py", line 80, in singleverse
result = stats.multinomial.rvs(1, word_probabilities)
File "C:\Users\hp\PycharmProjects\N-gram poems\venv\lib\site-packages\scipy\stats\_multivariate.py", line 3242, in rvs
n, p, npcond = self._process_parameters(n, p)
File "C:\Users\hp\PycharmProjects\N-gram poems\venv\lib\site-packages\scipy\stats\_multivariate.py", line 3036, in _process_parameters
p[..., -1] = 1. - p[..., :-1].sum(axis=-1)
IndexError: index -1 is out of bounds for axis 0 with size 0
It's in a for loop and when the error occurs changes each time. Some times it does not occur at all. It mostly occur close to the end of the program.
This is the code where the error occurs:
def singleverse(num):
TrTrigrams = [((filtered_tokens[i], filtered_tokens[i + 1]), filtered_tokens[i + 2]) for i in
range(len(filtered_tokens) - 2)]
TrTrigramCFD = nltk.ConditionalFreqDist(TrTrigrams)
TrTrigramPbs = nltk.ConditionalProbDist(TrTrigramCFD, nltk.MLEProbDist)
rand = random.choice(random_choice_list)
start_word = ('<s>', rand)
data = []
for i in range(10):
probable_words = list(TrTrigramPbs[start_word].samples())
word_probabilities = [TrTrigramPbs[start_word].prob(word) for word in probable_words]
result = stats.multinomial.rvs(1, word_probabilities)
index_of_probable_word = list(result).index(1)
start_word = (start_word[1], (probable_words[index_of_probable_word]))
data.append(start_word[1])
line = []
for i in data:
if i != "<s>" and i != "</s>":
line.append(i)
poem_line = ' '.join([str(i) for i in line]).capitalize()
print(poem_line)
def generate():
"""Generates the final poem with user input of structure."""
print("What structure do you want?(e.g., 3 x 4, 2 x 4, 2 x 5): ")
while True:
try:
x, y, z = input().split()
except:
print("Enter the structure as shown above.")
continue
break
while True:
try:
for stanza in range(1):
for first_verse in range(1):
b = random.randint(7, 12)
firstverse(int(b))
for verse in range(int(z) - 1):
a = random.randint(7, 12)
singleverse(int(a))
print('\n')
for stanza in range(int(x) - 1):
for verse in range(int(z)):
c = random.randint(7, 12)
singleverse(int(c))
print('\n')
except KeyError:
print("This was not a valid seed word please try again.")
continue
break
generate()
I don't know why I keep getting the error "string index out of range" and another error on line 47 print_data(data. Can someone please explain why? Thank you
def open_file():
user_input = input('Enter a file name: ')
try:
file = open(user_input, 'r')
return file
except FileNotFoundError:
return open_file()
def read_data(file):
counter = [0 for _ in range(9)]
for line in file.readlines():
num = line.strip()
if num.isdigit():
i = 0
digit = int(num[i])
while digit == 0 and i < len(num):
i += 1
digit = int(num[i])
if digit != 0:
counter[digit - 1] += 1
return counter
def print_data(data):
benford = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 4.1, 4.6]
header_str = "{:5s} {:7s}{:8s}"
data_str = "{:d}:{:6.1f}% ({:4.1f}%)"
total_count = sum(data)
print(header_str.format("Digit", "Percent", "Benford"))
for index, count in enumerate(data):
digit = index + 1
percent = 100 * count / total_count
print(data_str.format(digit, percent, benford[index]))
def main():
file = open_file()
data = read_data(file)
print_data(data)
file.close()
if __name__ == "__main__":
main()
This is the exact error I'm given
Traceback (most recent call last):
File "./lab08.py", line 52, in <module>
main()
File "./lab08.py", line 47, in main
data = read_data(file)
File "./lab08.py", line 26, in read_data
digit = int(num[i])
I believe the error stems from this:
while digit == 0 and i < len(num):
i += 1
digit = int(num[i])
If you swap the second two lines, you will properly index, i.e.:
while digit == 0 and i < len(num):
digit = int(num[i])
i += 1
If, for example, your string num is of length 10, then the final element is at index 9 (indexing from 0). for the first iteration of that loop, you will have digit be num[1], for the tenth iteration you would have it be num[10].
An alternative method would be to use list comprehension like this:
for n in num:
if digit != 0:
break
digit = int(n)
I am trying to make a script where a '-' is put in between all odd digits in a given number (ie 991453 would be 9-9-145-3), but for some reason python wont allow me to insert a str into a list of integers. The error I keep on getting is 'TypeError: not all arguments converted during string formatting'
My code:
def DashInsert(text):
list_int = map(int, list(text))
for i in xrange(len(list_int)-1):
if (list_int[i] % 2 == 1) and (list_int[i+1] % 2 == 1):
print i
list_int.insert(i+1,'-')
return list_int
Here is my actual input and error:
999472
0
Traceback (most recent call last):
File "DashInsert.py", line 17, in
print DashInsert(string)
File "DashInsert.py", line 11, in DashInsert
if (list_int[i] % 2 == 1) and (list_int[i+1] % 2 == 1):
TypeError: not all arguments converted during string formatting
Your error is because you are modifying the list that you are iterating over. When you insert - into the list, that becomes the target of % and you get a TypeError.
In Python, % is an operator for string formatting and '-' is a string; that is why you get a less than clear error:
>>> '-' % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
For strings you use % this way:
>>> 'x %s y %s %i' % ('and', 'is', 13)
'x and y is 13'
The fix to your code is to append to a separate list:
def DashInsert(s):
list_int = map(int, s)
rtr=[]
for i, e in enumerate(list_int[0:-1]):
rtr.append(str(e))
if e % 2 == 1 and list_int[i+1] % 2 == 1:
rtr.append('-')
rtr.append(str(list_int[-1]))
return rtr
You could do this through regex.
>>> import re
>>> s = 991453
>>> re.sub(r'(?<=[13579])(?=[13579])', r'-', str(s))
'9-9-145-3'
I suspect this is horrible code but it works-
number = 991453
number_list = []
for i, item in enumerate(str(number)):
try:
if int(item) % 2 != 0 and int(str(number)[i + 1]) % 2 != 0:
number_list.append(item + '-')
else:
number_list.append(item)
except:
number_list.append(item)
print(''.join(number_list))
Edit: Actually, there's no need to make a list so we can do this-
number = 991453
dash_number = ''
for i, item in enumerate(str(number)):
try:
if int(item) % 2 != 0 and int(str(number)[i + 1]) % 2 != 0:
dash_number += item + '-'
else:
dash_number += item
except:
dash_number += item
print(dash_number)
Edit: Here's how to do it without the try/except.
number = 991453
dash_number = ''
for i, item in enumerate(str(number)[:-1]):
if int(item) % 2 != 0 and int(str(number)[i + 1]) % 2 != 0:
dash_number += item + '-'
else:
dash_number += item
dash_number += str(number)[-1]
print(dash_number)
Hello I am currently getting an index out of range error from the following code: (I will post the code first and then the error)
Main File:
import Knapsack_Test
size = 10
W = 2*size
knapsack = Knapsack_Test.Knapsack_Test()
for i in range(1, 10):
knapsack.greedy_knapsack_test(size, W)
size = size + 10*i
W = 2*size
Class File (Only the greedy function):
def greedy_knap(self, v, w, W):
knap_array = []
for i in range(1, len(v)):
#The index out of range error occurs here:
knap_array[i] = [v[i],w[i]]
sort_order = self.sort.merge_sort(knap_array)
weight = 0
value = 0
knap_sac= []
n = len(knap_array)
j = 0
profit = 0
while weight < W and j < n:
if weight + knap_array[i][1] <= W:
knap_sac.append(knap_array[i])
weight = weight + knap_array[i][1]
profit = profit + knap_array[i][0]
j = j + 1
return profit
The test File (for greedy function):
def greedy_knapsack_test(self, size, W):
v = []
w = []
for i in range(1,size):
v.append(random.randint(1,1000))
for i in range(1,size):
w.append(random.randint(1,1000))
start = time.time()
self.knapsack.greedy_knap(v, w, W)
end = time.time() - start
return end
The Error:
Traceback (most recent call last):
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Main.py", line 10, in <module>
knapsack.greedy_knapsack_test(size, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Test.py", line 31, in greedy_knapsack_test
self.knapsack.greedy_knap(v, w, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 30, in greedy_knap
knap_array[i] = [v[i],w[i]]
IndexError: list assignment index out of range
knap_array = []
for i in range(1, len(v)): #The index out of range error occurs here:
knap_array.append([v[i],w[i]])
you can't create list element by referencing them.