given the following code (in python):
import random
import sys
import collections
commandStr = ["addClan", "addPlayer",
"clanFight", "getMinClan"]
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
INVALID_INPUT = "INVALID_INPUT"
ClanID = dict()
playersID = dict()
ClanScore = collections.defaultdict(list)
playersClan = dict()
LosingClans = set()
Clans_count = 0;
players_count = 0;
def initline():
global ClanID, Clans_count
inLine = "init 2 0 1"
outLine = "init done."
ClanID[0] = {}
ClanID[1] = {}
Clans_count += 2
return inLine, outLine
# addClan clanID
def addClan():
global ClanID, Clans_count
clanID = random.randint(-2, 8)
inLine = "addClan %d" % (clanID)
outLine = "addClan: "
if clanID < 0:
outLine += INVALID_INPUT
elif clanID in ClanID.keys():
outLine += FAILURE
else:
ClanID[clanID] = {}
Clans_count += 1
outLine += SUCCESS
return inLine, outLine
# addPlayer playerID score clanID
def addPlayer():
global playersID, ClanID, ClanScore, playersClan, players_count
playerID = random.randint(-10, 1000)
score = random.randint(-10, 1000)
clanID = random.randint(-2, 8)
inLine = "addPlayer %d %d %d" % (playerID, score, clanID)
outLine = "addPlayer: "
if playerID < 0 or clanID < 0 or score <0:
outLine += INVALID_INPUT
elif playerID in playersID.keys() or clanID not in ClanID.keys():
outLine += FAILURE
else:
playersID[playerID] = playerID
if clanID in ClanScore.keys():
ClanScore[clanID].append(score)
else:
ClanScore[clanID] = [score]
playersClan[playerID] = clanID
ClanID[clanID][playerID] = (playersID[playerID], clanID)
players_count += 1
outLine += SUCCESS
return inLine, outLine
# getMinClan
def getMinClan():
global ClanID, LosingClans
inLine = "getMinClan"
outLine = "getMinClan: "
for Clan_id in sorted(ClanID):
if Clan_id not in LosingClans:
outLine += SUCCESS + " %d" % Clan_id
break
return inLine, outLine
def sum_n_strongest(Clan, num):
sortedClan = sorted(Clan, reverse=True)
topNum = sortedClan[:num]
Sum = 0
for element in topNum:
Sum += element
return Sum
# clanFight clan1 clan2 k1 k2
def clanFight():
global ClanID, ClanScore, LosingClans
clan1 = random.randint(-1, 8)
clan2 = random.randint(-1, 8)
k1 = random.randint(-1, 10)
k2 = random.randint(-1, 10)
inLine = "clanFight %d %d %d %d" % (clan1, clan2, k1, k2)
outLine = "clanFight: "
if k1 <= 0 or k2 <= 0 or clan1 < 0 or clan2 < 0:
outLine += INVALID_INPUT
elif clan1 not in ClanID.keys() or clan2 not in ClanID.keys() or clan1 == clan2 or len(ClanID[clan1]) < k1 or len(ClanID[clan2]) < k2:
outLine += FAILURE
elif clan1 in LosingClans or clan2 in LosingClans:
outLine += FAILURE
else:
sum1 = sum_n_strongest(ClanScore[clan1], k1)
sum2 = sum_n_strongest(ClanScore[clan2], k2)
if sum1 == sum2:
if clan1 < clan2:
LosingClans.add(clan2)
else:
LosingClans.add(clan1)
elif sum1 < sum2:
LosingClans.add(clan1)
else:
LosingClans.add(clan2)
outLine += SUCCESS
return inLine, outLine
def main():
if len(sys.argv) < 3:
print("Usage %s <lines>" % sys.argv[0])
exit(0)
lines = int(sys.argv[1])
infname = "%s.in" % sys.argv[2]
outfname = "%s.out" % sys.argv[2]
functions = [addClan, addPlayer,
getMinClan, clanFight]
with open(infname, 'wb') as infhandler:
with open(outfname, 'wb') as outfhandler:
inLine, outLine = initline()
infhandler.write(inLine + "\n")
outfhandler.write(outLine + "\n")
while lines > 0:
f = random.randint(0, len(functions)-1)
func = functions[f]
inLine, outLine = func()
if inLine is not "":
infhandler.write(inLine + "\n")
outfhandler.write(outLine + "\n")
lines -= 1
infhandler.write("quit\n")
outfhandler.write("quit done.\n")
main()
This code should create a new file while I need to give as parameters filename and numberOfLines.
But, while I trying to run this script, opened to me a black window (like a cmd) and it's closed immediately.
How can I fix it? someone know what is the problem?
Note: this code written me in a file which his name is "Test.py" , and I trying to run it with this line command: python ./Test.py <Number of Lines> <Test Name> (at least, I trying to do it while I double-click about "Test.py" but like that I said, the window closed immediately..
Follow-up question: Are you using an IDE, or are you trying to run this from the command line/command prompt?
First, check if the files exist after you run the program. It might just be that the program is running quickly enough that it only takes a couple milliseconds, and the command prompt goes away once the program terminates. If it does create a file, the program wouldn't outwardly notify you; look in your file directory and see if it did.
Second, instead of just calling main() at the end of your file, maybe try:
if __name__ == "__main__":
main()
and see if anything different happens. This bit of code is executed whenever the file is run as specifically as a script (as you're doing with the command % python Test.py <num> <fname>).
Related
When I run the main or eqparse file, the python terminal will not show any output. This applies to both the command prompt and visual studio code.
Here is my code from the main file. I am including some of the likely unrelated stuff just in case. It is labeled so you can skip all the potentially unrelated stuff.
from graphics import *
from eqparse import *
# NOTE: For equation mapping, it will input a string and convert the data to a table.
# After, you take in the table coords and map each point
# dump vars here #
xypm = 0
global patternFind
global count
global indexlist
# profile initialization #
def init(name, nxsize, nysize, noffset, nzoom):
global zoom
zoom = nzoom
global xsize
xsize = nxsize
global eqtype
eqtype = bool(1)
global ysize
ysize = nysize
global win
win = GraphWin(name, nxsize, nysize)
global offset
offset = noffset
global xymark
xymark = (nzoom * -1)/2
global txsize
txsize = nxsize/2
global tysize
tysize = nysize/2
global txymark
txymark = xymark * -1 + 1
global xp1
xp1 = Point(xypm,(txsize) + offset)
global yp1
yp1 = Point((tysize) + offset, xypm)
global xp2
xp2 = Point(xypm,(txsize) - offset)
global yp2
yp2 = Point((tysize) - offset, xypm)
# starting procedure #
def startUp():
# xy lines #
global xymark
global xp1
global xp2
global yp1
global yp2
global xypm
xtrace = Line(Point(0,tysize), Point(xsize,tysize))
ytrace = Line(Point(txsize,0), Point(txsize,ysize))
xtrace.draw(win)
ytrace.draw(win)
# grid drawer #
while xymark < txymark:
txline = Line(xp1, xp2)
tyline = Line(yp1, yp2)
txline.draw(win)
tyline.draw(win)
xypm = xypm + xsize/zoom
xp1 = Point(xypm,(tysize) + offset)
yp1 = Point((txsize) + offset, xypm)
xp2 = Point(xypm,(tysize) - offset)
yp2 = Point((txsize) - offset, xypm)
xymark = xymark + 1
# code for ending mark #
Line(Point(txsize - offset, ysize - 1), Point(txsize + offset, ysize - 1)).draw(win)
Line(Point(xsize - 1,tysize - offset), Point(xsize - 1, tysize + offset)).draw(win)
# point drawing #
def drawCo(nx, ny):
pCircle = Circle(Point(xsize/zoom * (nx) + xsize/2, ysize - (ysize/zoom * (ny) + ysize/2)), 3)
pCircle.setFill("black")
pCircle.draw(win)
# main #
print("Checkpoint 1")
init("test",500, 500, 10, 20)
print("Checkpoint 2")
startUp()
print("Checkpoint 3")
drawCo(3,5)
print("Checkpoint 4")
patternFind("Dung","DungBeatlesbeingadungbeetle")
print("Checkpoint 5")
print(count)
print("Checkpoint 6")
for x in range(len(indexlist)):
print(indexlist[x])
print("Checkpoint 7")
# exit function #
win.getMouse()
win.close()
and the eqparse file:
# eqparse will look for certain patterns in strings, generate an equation,
# and create a table that a drawing function can read
from main import *
global indexlist
global count
global patternFind
global convStr
# convert string to valid equation data
def convStr(input):
if input[0] == 'y':
print("Linear")
elif input[0] == 'r':
print("Polar")
else:
print("Use Equation type on left side")
# subroutine that will be used to find patterns in a sequence #
def patternFind(pattern, input):
indexlist = []
count = 0
l = len(pattern)
tstr =""
if l > len(input):
pass
else:
i = 0
j = len(input) - len(pattern) + 1
k=0
while j > 0:
tstr = ""
i=0
while len(tstr) < l:
tstr = tstr + input[i + k]
i = i + 1
if tstr == pattern:
count = count + 1
indexlist.append(i+k)
else:
continue
j = j - 1
k=k+1
The output when I run main:
Checkpoint 1
Checkpoint 2
Checkpoint 3
Checkpoint 4
(also the window that I run lags out)
On a related note: When I use the standard import syntax nothing happens. I have to use from (file) import * for it to work.
Yor problem is in def patternFind()
in Your second while loop your counter k and j is never increasing.
So you have a infinite loop.
your code never go beyond the continue statement and stuck there forever.
But maybe you can replace that whole function with a python built-in:
def patternFind(pattern, input):
return pattern in input #true if pattern is in the input
I just got into python a few weeks ago and I've been learning the language using the PyCharm software.
I was hoping to use the following code for a project:
https://github.com/eohomegrownapps/markov-music
I installed the required library, and inserted a midi file in the mentioned folder (the input folder). I'm using the following midi file:
http://www.bachcentral.com/invent/invent1.mid
Once I run the code, nothing appears in the 'compositions' folder. Can anyone tell me what I'm doing wrong? I'll post a screenshot of the code below.
Thanks a million in advance
Updated Screenshot
import random
import midi
import datetime
class Markov(object):
"""docstring for Markov"""
def __init__(self, order=2):
super(Markov, self).__init__()
self.order = order
self.chain = {}
def add(self, key, value):
if self.chain.has_key(key):
self.chain[key].append(value)
else:
self.chain[key] = [value]
def load(self, midifile):
pattern = midi.read_midifile(midifile)
# track = pattern[1]
for track in pattern:
noteslist = []
curoffset = 0
for i in track:
if i.name == "Note On" and i.data[1] != 0:
note = (i.data[0], i.data[1], i.tick + curoffset)
# note = (i.data[0],i.data[1],i.tick)
noteslist.append(note)
curoffset = 0
else:
curoffset += i.tick
if len(noteslist) > self.order:
for j in range(self.order, len(noteslist)):
t = tuple(noteslist[j - self.order:j])
print t
print noteslist[j]
self.add(t, noteslist[j])
else:
print "Corpus too short"
def generate(self, length, filename):
pattern = midi.Pattern()
# Instantiate a MIDI Track (contains a list of MIDI events)
track = midi.Track()
# Append the track to the pattern
pattern.append(track)
tick = 0
currenttuple = random.choice(self.chain.keys())
prevnote = False
for i in range(0, self.order):
if prevnote != False:
on = midi.NoteOnEvent(tick=tick, velocity=0, pitch=prevnote)
track.append(on)
on = midi.NoteOnEvent(tick=0, velocity=currenttuple[i][1], pitch=currenttuple[i][0])
track.append(on)
tick = currenttuple[i][2]
prevnote = currenttuple[i][0]
result = random.choice(self.chain[currenttuple])
# print currenttuple
for i in range(1, length):
for j in range(0, self.order):
if prevnote != False:
if tick > 5000:
tick = 5000
on = midi.NoteOnEvent(tick=tick, velocity=0, pitch=prevnote)
track.append(on)
on = midi.NoteOnEvent(tick=0, velocity=currenttuple[j][1], pitch=currenttuple[j][0])
track.append(on)
tick = currenttuple[j][2]
prevnote = currenttuple[j][0]
currenttuple = list(currenttuple)
currenttuple.pop(0)
currenttuple.append(result)
currenttuple = tuple(currenttuple)
if self.chain.has_key(currenttuple):
result = random.choice(self.chain[currenttuple])
else:
result = random.choice(self.chain[random.choice(self.chain.keys())])
# Add the end of track event, append it to the track
eot = midi.EndOfTrackEvent(tick=1)
track.append(eot)
# Print out the pattern
print pattern
# Save the pattern to disk
midi.write_midifile(filename + ".mid", pattern)
if __name__ == '__main__':
directory = "compositions"
musicdir = "input"
musicdir += "/"
logname = directory + "/" + "{:%Y-%m-%d-%H:%M:%S}_genmusic".format(datetime.datetime.now())
m = Markov(3)
print "Loading music"
inp = raw_input('Name of midi file to load or g to generate: ')
while inp != "g":
try:
m.load(musicdir + inp)
except Exception as e:
print "File not found or corrupt"
inp = raw_input('Name of midi file to load or g to generate: ')
print "Done"
print m.chain
m.generate(1000, logname)
In the code below I get the following error:
"local variable 'moodsc' referenced before assignment"
I'm new to programming and python. I'm struggling with interpreting other questions on the similar topic. Any context around this specific code would be helpful.
import re
import json
import sys
def moodScore(sent, myTweets):
scores = {} # initialize an empty dictionary
new_mdsc = {} # intitalize an empty dictionary
txt = {}
for line in sent:
term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character"
scores[term] = int(score) # Convert the score to an integer.
data = [] # initialize an empty list
for line in myTweets:
tweet = json.loads(line)
if "text" in tweet and "lang" in tweet and tweet["lang"] == "en":
clean = re.compile("\W+")
clean_txt = clean.sub(" ", tweet["text"]).strip()
line = clean_txt.lower().split()
moodsc = 0
pos = 0
neg = 0
count = 1
for word in range(0, len(line)):
if line[word] in scores:
txt[word] = int(scores[line[word]])
else:
txt[word] = int(0)
moodsc += txt[word]
print txt
if any(v > 0 for v in txt.values()):
pos = 1
if any(v < 0 for v in txt.values()):
neg = 1
for word in range(0, len(line)): # score each word in line
if line[word] not in scores:
if str(line[word]) in new_mdsc.keys():
moodsc2 = new_mdsc[str(line[word])][0] + moodsc
pos2 = new_mdsc[str(line[word])][1] + pos
neg2 = new_mdsc[str(line[word])][2] + neg
count2 = new_mdsc[str(line[word])][3] + count
new_mdsc[str(line[word])] = [moodsc2, pos2, neg2, count2]
else:
new_mdsc[str(line[word])] = [moodsc, pos, neg, count]
def new_dict():
for val in new_mdsc.values():
comp = val[0] / val[3]
val.append(comp)
for key, val in new_mdsc.items():
print (key, val[4])
def main():
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
moodScore(sent_file, tweet_file)
# new_dict()
if __name__ == '__main__':
main()
Ok #joshp, I think you need to globalise some variables, because the error is 'moodsc referenced before assignment', I think the code only gets as far as moodsc += txt[word] but you may also have trouble with pos and neg.
Try global moodsc and pos etc. before you define moodsc and pos etc. If this doesn't work try global moodsc before moodsc += txt[word] and so forth, you may need to use global in both places for it to work, I often find that this is needed in my code, to globalise it at definition and wherever else you use it (at the start of each function and statement where it is used).
I need to code a program that can get values from this
Very interesting question. Actually, in your case, it is very simple. You can parse the entire source string with ast module, like this
import ast
import operator
functions = {
"add": operator.add,
"abs": operator.abs,
"multiply": operator.mul
}
def recursive_evaluation(current_element):
if isinstance(current_element, ast.Module):
return recursive_evaluation(current_element.body[0].value)
elif isinstance(current_element, ast.Call):
function = functions[current_element.func.id]
args = [recursive_evaluation(item) for item in current_element.args]
return function(*args)
elif isinstance(current_element, ast.Num):
return current_element.n
else:
raise ValueError("Unknown Element " + str(current_element))
source = "abs(add(add(9465,38),multiply(add(63303,146),46)))"
print recursive_evaluation(ast.parse(source))
source = "add(1, -2)"
print recursive_evaluation(ast.parse(source))
source = "abs(add(1, -2))"
print recursive_evaluation(ast.parse(source))
Output
2928157
-1
1
Interesting problem, here is a potential solution. No doubt you could make a much more elegant solution using libraries or lambdas etc. as thefourtheye did in their answer, but this seems to work.
I have done a few test cases at the bottom, set the global verbose to True if you want debug info:
# globals
verbose = False # set to True if you want debug info printed
max_iter = 1000 # this stops infinate loops incase the code does not allow for some input
def solve(problem_str):
def multiply(arg_list):
x = 1
for i in arg_list:
x *= i
return x
def find_innermost(x_str):
a, b, c, i = [0], [0], 0, 0
while True:
i += 1
start = a[-1]+1
a.append(x_str.find('(', start)) # find next (
b.append(x_str.find(',', start)) # find next ,
c = x_str.find(')', start) # find next )
if (a[-1] > c) or (a[-1] == -1):
if (b[-2] > a[-3]) and (b[-2] < a[-2]):
return x_str[b[-2]+1:c+1]
else:
return x_str[a[-3]+1:c+1]
if i >= max_iter:
raise Exception("Infinite loop")
def do_sum(x_str):
args = [int(x) for x in x_str[x_str.find('(')+1:x_str.find(')')].split(',')]
task = x_str[:3].lower()
if task == 'add':
return sum(args)
elif task == 'sub':
return args[0] - sum(args[1:])
elif task == 'abs':
return abs(args.pop())
elif task == 'mul':
return multiply(args)
else:
print x_str + ': Task not recognised, please modify program or input'
raise Exception("Invalid input")
i = 0
while True:
i += 1
if verbose: print 'debug: problem_str:', problem_str
if problem_str.count('(') > 1:
x_str = find_innermost(problem_str)
else:
x_str = problem_str
if verbose: print '.'*6, 'x_str:\t', x_str
x = do_sum(x_str)
if verbose: print '.'*6, 'x:\t', x, '\n'
problem_str = problem_str.replace(x_str, str(x))
if problem_str.count('(') == 0:
return int(problem_str)
if i >= max_iter:
raise Exception("Infinite loop")
if __name__ == '__main__':
p1 = 'abs(add(add(9465,38),multiply(add(63303,146),46)))'
p2 = 'abs(add(multiply(95,multiply(-1,multiply(13,18875))),multiply(-1,add(18293,26))))'
p3 = 'abs(add(subtract(add(add(151,26875),122),254),subtract(237,multiply(-1,56497))))'
r1, r2, r3 = solve(p1), solve(p2), solve(p3)
print 'p1 evaluates to:', r1
print 'p2 evaluates to:', r2
print 'p3 evaluates to:', r3
Let me know if you have any questions about the code.
The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fetch data from or something else? Thanks!!
import sgmllib
class MyParser(sgmllib.SGMLParser):
"A simple parser class."
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.divs = []
self.descriptions = []
self.inside_div_element = 0
def start_div(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "id":
self.divs.append(value)
self.inside_div_element = 1
def end_div(self):
"Record the end of a hyperlink."
self.inside_div_element = 0
def handle_data(self, data):
"Handle the textual 'data'."
if self.inside_div_element:
self.descriptions.append(data)
def get_div(self):
"Return the list of hyperlinks."
return self.divs
def get_descriptions(self, check):
"Return a list of descriptions."
if check == 1:
self.descriptions.pop(0)
return self.descriptions
def rm_descriptions(self):
"Remove all descriptions."
self.descriptions.pop()
import urllib
import linecache
import sgmllib
tempLine = ""
tempStr = " "
tempStr2 = ""
myparser = MyParser()
count = 0
user = ['']
oldUser = ['none']
oldoldUser = [' ']
array = [" ", 0]
index = 0
found = 0
k = 0
j = 0
posIndex = 0
a = 0
firstCheck = 0
fCheck = 0
while a < 1000:
print a
f = urllib.urlopen("SITE")
a = a+1
for i, line in enumerate(f):
if i == 187:
print i
tempLine = line
print line
myparser.parse(line)
if fCheck == 1:
result = oldUser[0] is oldUser[1]
u1 = oldUser[0]
u2 = oldUser[1]
tempStr = oldUser[1]
if u1 == u2:
result = 1
else:
result = user is oldUser
fCheck = 1
user = myparser.get_descriptions(firstCheck)
tempStr = user[0]
firstCheck = 1
if result:
array[index+1] = array[index+1] +0
else:
j = 0
for z in array:
k = j+2
tempStr2 = user[0]
if k < len(array) and tempStr2 == array[k]:
array[j+3] = array[j+3] + 1
index = j+2
found = 1
break
j = j+1
if found == 0:
array.append(tempStr)
array.append(0)
oldUser = user
found = 0
print array
elif i > 200:
print "HERE"
break
print array
f.close()
Perhaps the number of lines on that web page are fewer than you think? What does this give you?:
print max(i for i, _ in enumerate(urllib.urlopen("SITE")))
Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of your code.
enumerate is not broken. Instead of such speculation, inspect your data. Suggestion: replace
for i, line in enumerate(f):
by
lines = list(f)
print "=== a=%d linecount=%d === % (a, len(lines))
for i, line in enumerate(lines):
print " a=%d i=%d line=%r" % (a, i, line)
Examine the output carefully.