so here's some code i have that is supposed to take text entered by the user and create a dictionary. Can anyone tell me why I get a traceback error when I call the function main()?
def build_index(text):
index = {}
words = text.split()
position = 0
for x in text:
if x.isalpha() == False and x.isdigit() == False:
text.join(x)
else:
text.replace(x,'')
while position < len(words):
nextword = words[position]
if nextword in index:
ref = index[nextword]
ref.append(position)
index[nextword] = ref
else:
list = []
list.append(position)
index[nextword] = list
position += 1
def displayindex(index):
keys = sorted(index.keys())
for key in keys:
print(key + ':' + str(index[key]))
def main():
text = input("enter text")
build_index(text)
displayindex(index)
main()
The traceback error contents depends on which version of Python you're running your code in. In Python 3.x, the traceback explains why it's producing the error:
Traceback (most recent call last):
File "./prog.py", line 37, in
File "./prog.py", line 36, in main
NameError: name 'index' is not defined
TLDR: Need to add/change only 3 lines of code. See comments in code below
The NameError is telling us that it doesn't know what the name index refers to, because it's out of the scope of the main method and hasn't gotten defined yet. You could create the global instance of the index variable as mentioned in MeterLongCat's answer, but since index does get created and defined when we call build_index, we can just return index after that method call, save its return value, then pass it to the displayindex function, as follows.
OTOH, in Python 2, as MeterLongCat points out, you're wanting to get a string from the user, which is not what input is for, you want raw_input.
def build_index(text):
index = {}
words = text.split()
position = 0
for x in text:
if x.isalpha() == False and x.isdigit() == False:
text.join(x)
else:
text.replace(x,'')
while position < len(words):
nextword = words[position]
if nextword in index:
ref = index[nextword]
ref.append(position)
index[nextword] = ref
else:
list = []
list.append(position)
index[nextword] = list
position += 1
return index # Return the index
def displayindex(index):
keys = sorted(index.keys())
for key in keys:
print(key + ':' + str(index[key]))
def main():
text = raw_input("enter text") # Use raw_input
index = build_index(text) # Assign the index
displayindex(index)
main()
I was able to get rid of the traceback error by changing input to raw_input (for Python 2.7). You have other errors though, for example index in method main isn't defined. The following works:
index = {}
def build_index(text):
global index
words = text.split()
position = 0
for x in text:
if x.isalpha() == False and x.isdigit() == False:
text.join(x)
else:
text.replace(x,'')
while position < len(words):
nextword = words[position]
if nextword in index:
ref = index[nextword]
ref.append(position)
index[nextword] = ref
else:
list = []
list.append(position)
index[nextword] = list
position += 1
def displayindex(index):
keys = sorted(index.keys())
for key in keys:
print(key + ':' + str(index[key]))
def main():
global index
text = raw_input("enter text")
build_index(text)
displayindex(index)
main()
Related
So in VSCode, I'm receiving this error...
Given the input
2
21 22
We have variables saying
best_choice = '22'
a: ['21', '22']
However, a.remove(best_choice) returns an error.
I am completely confounded... please help.
I checked for this problem on stacks and found that remove() doesn't work when iterating through a list, so I changed my loop to while(True). However, I'm still receiving the same error.
Here is the code:
import sys
def best_option(a):
iterator = 0
while(len(a)>1):
previous_best_digit = 0
current_best_digit = 0
best_short_option = []
return_list = []
for item in a:
if len(item)-1 < iterator:
char_previous = item[iterator-1:iterator]
dig_previous = ord(char_previous)
previous_best_digit = dig_previous
best_short_option = item
continue
char = item[iterator:iterator+1]
dig = ord(char)
if dig > current_best_digit:
current_best_digit = dig
return_list.clear()
return_list.append(item)
elif dig == current_best_digit:
return_list.append(item)
if (current_best_digit < previous_best_digit):
return_list.clear()
return_list.append(best_short_option)
a = return_list
iterator+=1
return a
def largest_number(a):
#write your code here
res = ""
while (True):
best_choice = best_option(a)
print(best_choice)
a.remove(best_choice)
res += best_choice
if (len(a)==1):
break
res.append(a)
print(res)
return res
if __name__ == '__main__':
input = sys.stdin.read()
data = input.split()
a = data[1:]
print(largest_number(a))
It's purpose create a string with the greatest possible value from a list of strings.
your best_choice is ['22'], not '22'
This is my code. I'm new to python and I have defenitely messed up. I'm trying to create a program that calculates the frequency of words in a text file called 'romeoandjuliet.txt'. When I run it, nothing happens and the f1 and f2 files are not created. When type 'listofwords' or 'freq' in the console I get a NameError. I have already taken care of the stopwords situation. I appreciate any help.
def main():
listofwords = formlistofwords('romeoandjuliet.txt')
def formlistofwords(filename):
global listofwords
listofwords = formlistofwords("romeoandjuliet.txt")
infile = open(filename)
originalline = (infile.readline().lower() for line in infile)
line = " "
for ch in originalline:
if ('a' <= ch <= 'z') or (ch == " "):
line += ch
listofwords = line.split()
listofwords = [i.strip('.,?!:;') for i in listofwords]
listofwords = [words for words in listofwords if words not in stopwords]
return listofwords
def createfrequencydict(listofwords):
global freq
freq = [listofwords.count(p) for p in listofwords]
return dict(list(zip(listofwords, freq)))
def displaywordcount(listofwords, freq):
print('romeoandjuliet contains: ', len(listofwords), 'words')
print('romeoandjuliet contains: ', len(freq), 'different words')
print()
def displaymostcommon(freq):
file1 = open('f1.txt', 'w')
file2 = open('f2.txt', 'w')
print('most common words and frequencies are: ')
listofmostcommonwords = []
for word in freq.keys():
if freq[word] >= 30:
listofmostcommonwords.append((word, freq[word]))
listofmostcommonwords.sort(key = lambda x: x[1], reverse=True)
for item in listofmostcommonwords:
print(item[0] + ':', item[1])
for item in listofmostcommonwords:
file1.write(str(item[1]) + ',')
file2.write(str(item[0]) + ',')
file1.close()
file2.close()
I studied your code. I noticed following points:
You need to call each function in order to execute
You have some global variables such as listofwords,freq. Declare them and assign None to them. Then call the functions at then end passing these variable. This way code is working
Following return statement
return dict(list(zip(listofwords, freq)))
Here the return statement is not returning dictionary. It is returning list. Instead of this, first try this using for loop. Here is the code that worked for me
def createfrequencydict(listofword):
global freq
freq = [listofwords.count(p) for p in listofwords]
#print(dict(list(zip(listofwords, freq))))
for key in listofwords:
for value in freq:
res[key] = value
freq.remove(value)
break
return res
I am writing a cryptosystem program in python that involves to shift left the key
I get "IndexError: string index out of range" when I compile the code.
Below is the function of left shifting
def shift_left(key):
s = ""
for i in range(1,len(key)):
print(i)
s = s + key[i]
s = s + key[0]
key = s
s = ""
return key
I added the command print(i) to know for which value of i the index is out of range
It always print 1 and 2
So the problem occurs when i = 2
I have no idea why it's out of range
def shift_left(key):
s = ""
for i in key:
print(i)
s = s + i
s = s + key[0]
key = s
s = ""
return key
Hi guys i got my code to work by putting everything in one function which is this
spam = ''
def enterList (names):
newList = []
while True:
names = raw_input('list a series of items and press blank when finished: ')
if names == '':
break
newList = newList + [names]
a = ''
finalText = ''
listOfStuff = []
item = 0
for i in newList:
if item < len(newList)-2:
a = (i + ', ')
listOfStuff.append(a)
item +=1
elif item == len(newList)-2:
a = (i + ' and ')
listOfStuff.append(a)
item +=1
else:
a = i
listOfStuff.append(a)
break
finalText = finalText.join(listOfStuff)
return finalText
print enterList(spam)
So the above code works as i want it to. However i was trying to do the same thing by having two separate functions, the issue that i was having was that i couldn't take the return value of one function and use it in the next function.
This is the old code
spam = ''
def enterList (names):
newList = []
while True:
names = raw_input('list a series of items and press blank when finished: ')
if names == '':
break
newList = newList + [names]
return newList
print enterList(spam)
def newFunc(Addand):
a = ''
finalText = ''
listOfStuff = []
item = 0
for i in spam:
if item < len(spam)-2:
a = (i + ', ')
listOfStuff.append(a)
item +=1
elif item == len(spam)-2:
a = (i + ' and ')
listOfStuff.append(a)
item +=1
else:
a = i
listOfStuff.append(a)
break
finalText = finalText.join(listOfStuff)
return finalText
newFunc(spam)
print newFunc (spam)
I'm not sure what I was doing wrong doing it this way.
Thanks for any help to get my head around the error with this approach.
In your first function make the return statement
return newFunc(newlist)
It's not working because the second function is never actually called.
I am trying to push elements from a list to a stack. Here is the code:
#!/usr/bin/python
class Stack :
def __init__(self) :
self.items = []
def push(self, item) :
self.items.append(item)
def pop(self) :
return self.items.pop()
def isEmpty(self) :
if self.items == []:
return true
def InsertIntostacks(lst1):
X = Stack() #for each expression a stack is defined
Y = Stack()
for words in lst1:
if (ord(words) >= 48 and ord(words) <= 57) or (ord(words) >=65 and ord(words) <= 90):
X.push(words)
else:
Y.push(words)
print X.pop()
if __name__ == '__main__':
a = open("testinput1.txt","r+")
wordList = [line.strip() for line in a];
#print wordList[1]
lst=list()
for words in wordList:
if words == '#':
print "End of file"
else:
lst = list(words)
lst1 = list()
print lst
for x1 in lst:
if x1 != ' ':
lst1.append(x1)
InsertIntostacks(lst1)
So X is getting populated and I need Y to contain the operators, but apparently none of the elements are getting in Y ( input like A=B=C, so Y should contain = = ).
If i remove the constraints and just push all the elements in one stack the operators are there.
What am I doing wrong here?
I suspect maybe your indentation is wrong for InsertIntostacks(lst1), and that's the problem.
Try ensuring that InsertIntostacks(lst1) is properly aligned with the for loop, meaning it executes after the loop, not within it. Right now it's executing during every iteration of the loop, including the first one, where lst is indeed empty.