Error when calling a Markov Chain - python

I'm working on a project that calls a Markov Chain module. I've scraped data and composed a basic text generating file, but keep getting an error that I don't understand. My code looks like:
from markov_python.cc_markov import MarkovChain
mc = MarkovChain()
mc.add_file('C:\EclipseWorkspaces\csse120\markov_chain\src\lyrics.txt')
mc.add_string('shape')
print mc.generate_text(10)
The error I get is:
Traceback (most recent call last):
File "C:\EclipseWorkspaces\csse120\markov_chain\src\run.py", line 14, in <module>
print mc.generate_text(10)
File "C:\EclipseWorkspaces\csse120\markov_chain\src\markov_python\cc_markov.py", line 61, in generate_text
idx = random.randint(0, len(self.lookup_dict)-1)
File "C:\Python27\lib\random.py", line 244, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 220, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)
And here is the code it is calling back to:
def generate_text(self, max_length=20):
context = deque()
output = []
if len(self.lookup_dict) > 0:
self.__seed_me(rand_seed=len(self.lookup_dict))
idx = random.randint(0, len(self.lookup_dict)-1)
chain_head = list(self.lookup_dict.keys()[idx])
context.extend(chain_head)
Not sure what to do. Please advise.

Related

ValueError: empty range for randrange() (0, 0, 0)

I try to export random proxy from a webpage with this script:
def randProxy():
url = 'https://free-proxy-list.net/anonymous-proxy.html'
response = requests.get(url)
parser = fromstring(response.text)
proxies = []
for i in parser.xpath('//tbody/tr')[:20]:
if i.xpath('.//td[7][contains(text(),"yes")]'):
proxy = ":".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]])
try:
t = requests.get("https://www.google.com/", proxies={"http": proxy, "https": proxy}, timeout=5)
if t.status_code == requests.codes.ok:
proxies.append(proxy)
except:
pass
proxy = proxies[random.randint(0, len(proxies)-1)]
px={"http": proxy, "https": proxy}
randProxy()
but when i try i get this error
Traceback (most recent call last):
File "C:\Users\natan\OneDrive\Dokumen\Private-Folder\Project\WtD\main.py", line 51, in <module>
randProxy()
File "C:\Users\natan\OneDrive\Dokumen\Private-Folder\Project\WtD\main.py", line 33, in randProxy
proxy = proxies[random.randint(0, len(proxies)-1)]
File "C:\Users\natan\AppData\Local\Programs\Python\Python39\lib\random.py", line 339, in randint
return self.randrange(a, b+1)
File "C:\Users\natan\AppData\Local\Programs\Python\Python39\lib\random.py", line 317, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
Are anyone know how to fix this? i only want to get some random proxy
That happens when the second argument is a negative. Look here.
import random
print(random.randint(0,-1))
output
Traceback (most recent call last):
File "<string>", line 2, in <module>
File "/usr/lib/python3.8/random.py", line 248, in randint
return self.randrange(a, b+1)
File "/usr/lib/python3.8/random.py", line 226, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
So maybe find a fix for changing the last parameter to something positive.
I believe it's actually because the first number has to be smaller than the second number. I just ran a program and had the same issue with random.randint(-50, -100) then switched the numbers and it worked

ValueError with randint

I'm having this really weird error and I have no idea what it is.
This is my code:
def wordChoice():
theme = themechoice
word = theme[randint(0, len(theme) - 1)]
This is the error:
Traceback (most recent call last):
File "C:\Users\Andrei\Documents\USB Backup\Python\Hangman.py", line 31, in wordChoice
word = theme[randint(0, len(theme) - 1)]
File "C:\Users\Andrei\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Users\Andrei\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 196, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
I've searched everywhere but I can't find anything. I'm also kind of a newb so sorry if it was something obvious.
EDIT:
Before i set theme to this:
def themeChoice():
n = 0
for i in themes:
n += 1
print(str(n) + " - " + i)
themechoice = themesToThemes[themes[int(input("Type the number corresponding to your chosen theme: ")) - 1]]
print (themechoice)
This error will occur when theme is empty.
>>> theme = []
>>> random.randint(0, len(theme)-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Programming\Python 3.5\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Programming\Python 3.5\lib\random.py", line 196, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)
Make sure theme actually has elements in it before trying to randomly choose an element from it. Also, consider using random.choice instead of manually generating an index with randint.

KeyError: 0 using multiprocessing in python

I have the following code inwhich I try to call a function compute_cluster which do some computations and write the results in a txt file (each process write its results in different txt files independently), however, when I run the following code:
def main():
p = Pool(19)
p.map(compute_cluster, [(l, r) for l in range(6, 25) for r in range(1, 4)])
p.close()
if __name__ == "__main__":
main()
it crashes with the following errors:
File "RMSD_calc.py", line 124, in <module>
main()
File "RMSD_calc.py", line 120, in main
p.map(compute_cluster, [(l, r) for l in range(6, 25) for r in range(1, 4)])
File "/usr/local/lib/python2.7/multiprocessing/pool.py", line 225, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/local/lib/python2.7/multiprocessing/pool.py", line 522, in get
raise self._value
KeyError: 0
and when I searched online for the meaning of "KeyError: 0" i didn't find anything helpful so any suggestions why this error happens is highly appreciated
KeyError happens in compute_cluster() in a child process and p.map() reraises it for you in the parent:
from multiprocessing import Pool
def f(args):
d = {}
d[0] # <-- raises KeyError
if __name__=="__main__":
p = Pool()
p.map(f, [None])
Output
Traceback (most recent call last):
File "raise-exception-in-child.py", line 9, in <module>
p.map(f, [None])
File "/usr/lib/python2.7/multiprocessing/pool.py", line 227, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 528, in get
raise self._value
KeyError: 0
To see the full traceback, catch the exception in the child process:
import logging
from multiprocessing import Pool
def f(args):
d = {}
d[0] # <-- raises KeyError
def f_mp(args):
try:
return f(args)
except Exception:
logging.exception("f(%r) failed" % (args,))
if __name__=="__main__":
p = Pool()
p.map(f_mp, [None])
Output
ERROR:root:f(None) failed
Traceback (most recent call last):
File "raise-exception-in-child.py", line 10, in f_mp
return f(args)
File "raise-exception-in-child.py", line 6, in f
d[0] # <-- raises KeyError
KeyError: 0
It shows that d[0] caused the exception.

Python - randint() returns empty range, crashing error

I've been able to duplicate this error multiple times in my poker program and tried various unsuccessful solutions. Here's the latest:
Traceback (most recent call last):
File "C:\Users\Pangloss\Desktop\tgchanpoker\poker.py", line 1868, in <module>
if __name__ == '__main__': main()
File "C:\Users\Pangloss\Desktop\tgchanpoker\poker.py", line 1866, in main
mainGame = Game(opponent)
File "C:\Users\Pangloss\Desktop\tgchanpoker\poker.py", line 1443, in __init__
if randint(1,betCheck+(10-handValue[1]))<5 or gameStage == "bettingStay":
File "C:\Python27\lib\random.py", line 241, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 217, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (1,-7, -8)
And here's the relevant code:
handValue = checkHand(opponent.cards.cards)
if gameStage == "betting" or gameStage == "final" or gameStage == "finalresponding":
betCheck = 18-handValue[1]-round(betAmount/(setMax/5))+opponent.brashness
elif gameStage == "extendedFinal":
betCheck = 16-handValue[1]-round(betAmount/(setMax/5))+opponent.brashness-(pot/100)
else:
betCheck = 16-handValue[1]-round(betAmount/(setMax/5))+opponent.brashness
foldCheck = 16-handValue[1]-round(betAmount/(setMax/3))+opponent.brashness+(pot/100)
if randint(1,betCheck+(10-handValue[1]))<5 or gameStage == "bettingStay":
this code
randint(1,betCheck+(10-handValue[1]))
is giving you this
randrange(1,-7,-8)
This means that betCheck+(10-handValue[1]) is giving you -8
That range will not give you any number at all, because betCheck+(10-handValue[1])) is a negative number and the range is invalid
You need to examine the code that sets betcheck and handvalue[1] to see why it is so negative
Check your value of betCheck+(10-handValue[1]). From the traceback, it is -8.

Randint error in Python?

I'm writing up the code for the RSA algorithm as a project. With those who are familiar woth this encryption system,the function below calculates the value of phi(n). However when I run this, it comes up this error:
Traceback (most recent call last):
File "C:\Python27\RSA.py", line 127, in <module>
phi_n()
File "C:\Python27\RSA.py", line 30, in phi_n
prime_f = prime_list[random.randint(0,length)]
File "C:\Python27\lib\random.py", line 241, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 217, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)
I don't fully understand why this error is coming up. Here is my code for the phi_n function:
def phi_n():
global prime_list
length = len(prime_list) - 1
prime_f = prime_list[random.randint(0,length)]
prime_s = prime_list[random.randint(0,length)]
global pq
n = prime_f * prime_s
global phi_n
phi_n = (prime_f -1) * (prime_s -1)
return phi_n
Comment will be appreciated.
Thanks
The problem is prime_list is empty and therefore length will equal -1 resulting in the call random.randint(0, -1) which is invalid for obvious reasons.

Categories