When I run the following code in IDLE Python 3.9 the expected output was coming but when I run the code in code playground (Online IDE) the code was not showing expected output but instead throwing some error.
The error:
Traceback (most recent call last):
File "main.py", line 28, in <module>
non_adjacent(input())
EOFError: EOF when reading a line
The code:
def non_adjacent(words:str):
words_list = words.split()
result = []
l = len(words_list)
for i in range(l-2):
for j in range(i+2, l):
tmp1 = words_list[i]
tmp2 = words_list[j]
index_tmp1 = [k for k in range(l) if words_list[k]==tmp1]
index_tmp2 = [m for m in range(l) if words_list[m]==tmp2]
not_adj = True
for el1 in index_tmp1:
for el2 in index_tmp2:
if abs(el1 - el2) == 1:
not_adj = False
tmp = sorted([tmp1, tmp2])
if tmp not in result and not_adj:
result.append(tmp)
for el in sorted(result):
print(*el)
while True:
non_adjacent(input())
To host it online, you will need to use repl.it, I dont know if code playground supports input(), anyways goto repl.it and create an account. then a new repl. Then choose "Python" and give it a name. then post this code:
def non_adjacent(words:str):
words_list = words.split()
result = []
l = len(words_list)
for i in range(l-2):
for j in range(i+2, l):
tmp1 = words_list[i]
tmp2 = words_list[j]
index_tmp1 = [k for k in range(l) if words_list[k]==tmp1]
index_tmp2 = [m for m in range(l) if words_list[m]==tmp2]
not_adj = True
for el1 in index_tmp1:
for el2 in index_tmp2:
if abs(el1 - el2) == 1:
not_adj = False
tmp = sorted([tmp1, tmp2])
if tmp not in result and not_adj:
result.append(tmp)
for el in sorted(result):
print(*el)
while True:
non_adjacent(input("Please enter words sperated by a space: "))
Working Example:
https://replit.com/#craftit7/EmailHelp1#main.py
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box.
Code playground is an online IDE.
Related
I am trying to get the frequency distribution of the word in a phrase according to its degree using nltk. It is showing "TypeError: unhashable type: 'list'" though. Don't understand what the problem is. Please help.
P.S: The code has a whole lot of bugs so don't mind that. I am trying to build a keyword extractor using code snippets from many many programs as I am a noob to python. If anyone wants to shed some light on the other bugs are also welcome.
Code:
from __future__ import division
import operator
import nltk
import string
def isPunct(word):
return len(word) == 1 and word in string.punctuation
def isNumeric(word):
try:
float(word) if '.' in word else int(word)
return True
except ValueError:
return False
class KeyExt:
def __init__(self):
self.stopwords = set(nltk.corpus.stopwords.words())
self.top_fraction = 1
def _generate_candidate_keywords(self, sentences):
phrase_list = []
for sentence in sentences:
words = map(lambda x: "|" if x in self.stopwords else x, nltk.word_tokenize(sentence.lower()))
phrase = []
for word in words:
if word == "|" or isPunct(word):
if len(phrase) > 0:
phrase_list.append(phrase)
phrase = []
else:
phrase.append(word)
return phrase_list
def _calculate_word_scores(self, phrase_list):
word_freq = nltk.FreqDist()
word_degree = nltk.FreqDist()
for phrase in phrase_list:
degree = [x for x in phrase if not isNumeric(x)]
for word in phrase:
word_freq[word]=word_freq[word]+1
word_degree[word, degree]=word_degree[word, degree]+1
for word in word_freq.keys():
word_degree[word] = word_degree[word] + word_freq[word]
word_scores = {}
for word in word_freq.keys():
word_scores[word] = word_degree[word] / word_freq[word]
return word_scores
def _calculate_phrase_scores(self, phrase_list, word_scores):
phrase_scores = {}
for phrase in phrase_list:
phrase_score = 0
for word in phrase:
phrase_score += word_scores[word]
phrase_scores[" ".join(phrase)] = phrase_score
return phrase_scores
def extract(self, text, incl_scores=False):
sentences = nltk.sent_tokenize(text)
phrase_list = self._generate_candidate_keywords(sentences)
word_scores = self._calculate_word_scores(phrase_list)
phrase_scores = self._calculate_phrase_scores(phrase_list, word_scores)
sorted_phrase_scores = sorted(phrase_scores.items(), key=operator.itemgetter(1), reverse=True)
n_phrases = len(sorted_phrase_scores)
if incl_scores:
return sorted_phrase_scores[0:int(n_phrases/self.top_fraction)]
else:
return map(lambda x: x[0],
sorted_phrase_scores[0:int(n_phrases/self.top_fraction)])
def test():
search=input("Enter Text: ")
ke = KeyExt()
keywords = ke.extract(search, incl_scores=True)
print (keywords)
if __name__ == "__main__":
test()
Full Traceback:
Traceback (most recent call last): File "C:\Users\SAURAV
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
81, in <module>
test() File "C:\Users\SAURAV DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
77, in test
keywords = ke.extract(search, incl_scores=True) File "C:\Users\SAURAV
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
64, in extract
word_scores = self._calculate_word_scores(phrase_list) File "C:\Users\SAURAV
DAS\AppData\Local\Programs\Python\Python35\projects\nlpproj.py", line
44, in _calculate_word_scores
word_degree[word, degree]=word_degree[word, degree]+1 TypeError: unhashable type: 'list'
This error occurs when you are trying to use a list as a dict key. lists are not hashable and can't be used for keys (e.g. tuples can be used).
In your case in this line
word_degree[word, degree]=word_degree[word, degree]+1
you are using degree as an index for word_degree that doesn't make sense cause degree itself is a list.
# coding=utf-8
def compare(arr1, arr2):
arr1 = arr1.strip()
arr2 = arr2.strip()
arr1 = arr1.split('\t')
arr2 = arr2.split('\t')
# print arr1[0], arr1[1]
arr1min = min(long(arr1[0]), long(arr1[1]))
arr1max = max(long(arr1[0]), long(arr1[1]))
arr2min = min(long(arr2[0]), long(arr2[1]))
arr2max = max(long(arr2[0]), long(arr2[1]))
# print arr1max, arr2max, arr1min, arr1min
if (arr1min < arr2min):
return -1
elif (arr1min > arr2min):
return 1
else:
if (arr1max < arr2max):
return -1
elif (arr1max > arr2max):
return 1
else:
return 0
f = open('er1000000new.txt')
fwrite = open('erzhesorted.txt', 'w')
lines = f.readlines()
lines.sort(compare)
for line in lines:
# fwrite.write(str(line))
print line
f.close()
fwrite.close()
the compare is custom sort function.
for example, when the result printed on screen, the result is
752555452697747457\t752551879448547328\t1468258301659\n
752563934733873152\t752561055289577472\t1468260508664\n
but the result printed on file is
6782762\t12\t1468248110665\n
2660899225\t12\t1468229395665\n
The two results are different, why?
The wb option when you open a file, makes python waiting for a byte object to write in that file.
Your (commented) line fwrite.write(str(line)) sends a string object.
Doesn't it produce the following error?
TypeError: a bytes-like object is required, not 'str'
Also it may come from your compare attribute in sort method.
What is it?
→ Removing the b option and removing the compare attribute produces the same outputs in term and file outputs.
This code is appearing to give me an error to my arguments i don't know what i have done wrong in this code. When attempting to run a binary search inside tkinter using python 2.7 The programs works fine if i don't use the gui just line code. This is the code I have based my program on
http://www.pythonschool.net/data-structures-algorithms/binary-search/
The error is: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in call return self.func(*args) TypeError: binarySearch() takes exactly 2 arguments (0 given)
from Tkinter import *
import csv
with open('scoresRecord.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
root = Tk()
root.resizable(0,0)
root.title("Score Board")
def binarySearch(myitem,myList):
found = False
bottom = 0
top = len(myList)-1
while bottom<=top and not found:
middle = (bottom+top)//2
if myList[middle]== myitem:
found = True
elif myList[middle] < myitem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
Scorelist = [row[0] for row in your_list]
Dismissallist =[row[1] for row in your_list] # create a list of only the dismissal
Venuelist =[row[2] for row in your_list] # create a list of only the venue
item = int(input(entScore.get()))
Scorelist = map(int, Scorelist)
rowPos = Scorelist.index(item)
isitFound = binarySearch(item,Scorelist)
if isitFound:
Score= Scorelist[rowPos]
Dismissal= Dismissallist[rowPos]
Venue= Venuelist[rowPos]
else:
Score= ("Not Found")
Dismissal= ("Not Found")
Venue= ("Not Found")
numScoreLbl.configure(text=Score)
numDismissal.configure(text=Dismissal)
outVenue.configure(text=Venue)
#==========GUI Section==================#
First of all, make sure your list is ordered, otherwise the results may be wrong.
Second, do this
Scorelist = list(map(int, Scorelist))#convert to list
isitFound = binarySearch(item,Scorelist)
Although, if you are using .index method, then you can do something like this for better performance:
try:
index = Scorelist.index(item)
isitFound = True
except ValueError:
isitFound = False
It takes out the binary search part, but you were using .index anyways. So this is better. Hope it helps :)
So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.
I'm having this error:
File "zzz.py", line 70
else:
^
SyntaxError: invalid syntax
The line which causes the problem is marked with a comment in the code:
def FileParse(self, table_file):
vars={}
tf = open(table_file, 'r')
for line in tf:
if line.startswith("#") or line.strip() == "": pass
elif line.startswith("n_states:"):
self.n_states = str(line[9:].strip())
elif line.startswith("neighborhood:"):
self.neighborhood = str(line[13:].strip())
elif line.startswith("symmetries:"):
self.symmetries = str(line[11:].strip())
elif line.startswith("var "):
line = line[4:]
ent = line.replace('=',' ').\
replace('{',' ').\
replace(',',' ').\
replace(':',' ').\
replace('}',' ').\
replace('\n','').split()
vars[ent[0]] = []
for e in ent[1:]:
if e in vars: vars[ent[0]] += vars[e]
else:
vars[ent[0].append(int(e))]
else:
rule = line.strip().split(",")
for k in vars.keys():
if k in rule:
for i in vars[k]:
change = rule.replace(k, i)
change = [int(x) for x in change]
w.rules.append(Rule(change[:5],change[5])
else: # line which causes the problem
rule = [int(x) for x in rule]
w.rules.append(Rule(rule[:5],rule[5]))
tf.close()
self.parse_status "OK"
return w.rules
w.rules is variable which is assigned to "World" class.
To be honest I have no idea why I get this. Before everything was fine and now that error shows up after adding some extra instructions in other indented blocks.
Any ideas?
Because you left out a closing brace
w.rules.append(Rule(change[:5],change[5]) )
The previous line, w.rules.append(Rule(change[:5],change[5]), is missing a close paren.
While you're at it, there is another typo. You probably want:
self.parse_status "OK"
To be:
self.parse_status = "OK"
Remove extra spaces/lines and re-indent the if/else statements. This worked for me.
(I tried the other solutions here but none worked. My braces were fine.)