This is a tricky one (note the parens in the statement).
L = [ [4,5,6] , [2,4,5] ]
new_L = [ (y if ctr > 1 else y*y) for x in L for ctr, y in enumerate(x)]
print new_L
This is a tricky one (note the parens in the statement).
L = [ [4,5,6] , [2,4,5] ]
new_L = [ (y if ctr > 1 else y*y) for x in L for ctr, y in enumerate(x)]
print new_L
And suggesting that jogged my memory about pexpect, which you can use for interacting with external programs http://www.noah.org/wiki/Pexpect#Description_of_Pexpect So now you have 2 good options and hopefully one of them will solve the problem.
Q: Why not just use a pipe (popen())?
A: A pipe works fine for getting the output to non-interactive programs. If you just want to get the output from ls, uname, or ping then this works. Pipes do not work very well for interactive programs and pipes will almost certainly fail for most applications that ask for passwords such as telnet, ftp, or ssh.
You will have to include the complete error message, which prints the line where the error was found. We are volunteers so no one will take the time to try and guess which line is causing the error.
A complete error message looks like this:
./test_1.py
File "./test_1.py", line 20
if start > -1
^
SyntaxError: invalid syntax
Yo write what you want to keep to a separate file. Start here http://www.greenteapress.com/thinkpython/html/book015.html#toc154
To find a sub-string within a string, find a sub_string within a string.
st = "VTK/Examples/Test"
to_find = "VTK/Examples/"
start = st.find(to_find)
if start > -1:
print st[start+len(to_find):]
You could probably use subprocess' readline & write. Doug Hellmann has an example here http://blog.doughellmann.com/2007/07/pymotw-subprocess.html
The "standard" way does not use regular expressions. When "<test>" is found, start appending records to a list. When "</test> " is found, print or do whatever with list and re-define it as an empty list, and continue down the line.
I tested your code for n=100,000 and "while(sun!=n and i<100000)" instead of i < 10**30 (you aren't going to do anything in 4 seconds using 10**30). It took 11 seconds for the prime function and one second for the remainder, so < 10 million would take 100 times as long for both parts and < 10**30 would take a lifetime. When testing for primes, you only have to test up to the square root of the number, and if you store the primes found, then you can divide by the primes found, up to the highest prime found (since all the other numbers would be divisible by one of the primes), and continue using odd numbers from there to the square root. For additional help, please comment your code as some people are not familiar with the newer features, like "all", and in fact still use version 2.5 which doesn't contain "all" AFAIK.
I need to change presArray = Table1Builder(60, "STR") to presArray = Table1Builder(60,3, "STR")
You would first have to change the Table1Builder code so it would accept another arg. No offense, but if you are asking this question then you do not want to start changing code.
So you have 2 options that I can see.
1. Use Table1Builder(180, "STR") and have some code to use this like a (60,3) array
2. Call the Table1Buider(60, "STR") function 3 times and store each returned value in a container, again with code to process this so it looks like an array.
You would also have to change these corresponding statements that use presArray
presArray(ptr, name) ## is this doing what you think?
print presArray(indx) ## may have to be modified
Finally, use strip instead of slicing:
# Removes leading blank space from variable...years.
years = years[1:] becomes years = years.strip()
# Removes '\n' character from variable...age.
age = age[1:-1] becomes age = age.strip()
Python is a civilized language so behaves well.
http://www.associatedcontent.com/article/2909956/earthquakes_caused_by_loose_woman_and.html "The Ayatollah Kazem Sedighi related to a group of worshipers in Tehran, Iran what actually causes earthquakes. The cause is not, as one would have suspected having been deceived by infidel science, the movement of tectonic plates.
No, the Ayatollah Kazem Sedighi revealed that earthquakes, at least in Iran, is caused by loose women who dress like tarts. "
And a co-worker wonders what causes volcanoes.
A Google of "Perl to Python" will yield some of the programs that will do this for you. If the translation is incomplete, post the offending code, with an explanation of what it should do, and someone will help. Note that this code appears to call other functions, so just translating this portion will probably not work.
Wait, I see a money making opportunity here. I'll apply for a government grant to study how often people publicly announce that they just took a dump
This could also affect water pressure levels so count me in as a co-conspirator, er co-researcher. In Los Angeles several major water pipes broke because lawn watering was limited to certain days. The pressure on those days was too much for the aging pipes to handle. Could the same thing happen with flushing? We should definitely get a grant and study this. And +1 for wasting dollars storing "tweets". There would have to be a new level of bureaucracy to collect and store them.
Using datetime's timedelta, you would use year, month, and day. See "date objects" here http://docs.python.org/library/datetime.html
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
print tomorrow.day
## etc
You can change completely the effect of your program by modifying only the last line. This is very useful when you're extending, debugging or testing your code. You cannot do this with code at script level.
If you want to use this style of programming then you should use function names more descriptive than "main". It is indeed irritating when you are looking at someone else's code to check what is being run first, and finding a single, orphaned "main()", and then having to hit the page up button until you find the actual code that should have been where the language design designates.
Edit: Anyone want to submit a PEP to throw an error if "main" is used as a function name.
Has anyone mentioned the classics? Your friends are stating to look old, but not you. And
"May I help you __Sir__"
I want to generate seprate log files for every sql files in loop.
You would open a unique file within the loop, before you start reading the SQL file, and close the file after the last record is copied. That's pretty basic so perhaps I am missing something.
but i just cant seem to get it right
Show us what you have tried and we will help make it work. It appears that you copied some simple rock-paper-scissors, and guess-the-number code from somewhere and now want us to modify it for you.
File "./firstpython", line 6, in <module>
input()
File "<string>", line 0
You want to use raw_input() for the Python version you are using, or enter an integer.
It appears that you did not test this code as you only read the first rec. Also you can use
for rec in inFile
instead of the while loop. And string.split() is deprecated, use line.split() instead.
line = inFile.readline()
##---------------------------------------------------------------
## this is an infinite loop unless the 1st rec = ""
##---------------------------------------------------------------
while line != "":
name, num = string.split(line)
total = total + eval(num)
count = count + 1
avg = total/count
outFile.write('%d' %(avg))
A line is more than a single point if you are trying to code a line. I don't know. You didn't say. But if you want a bar graph for example then you have to code for a bar, see this example from the matplotlib docs http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html Take a look at Ene's example here as well http://www.daniweb.com/code/snippet216915.html I'm outta here. Your descriptions are too vague and I'm sorry, but don't have the time to try and intuit what it is you are trying to do.
Can somebody tell me why my programm doesn't work and what i can do
Not without more info. Please include the traceback message at a minimum, with a simple explanation of what isn't working.
For x in row 2, col 1, append to empty list[]. Now look to see if there is an x above it....No? well now is there an x to the left.....No? well now look to right....Yes? right, append it to the list[]. Is there now an x underneath this x.....Tes? right well append it to the list[].
Now look to see if there is an x above it (row-1)
well now is there an x to the left (col-1)
well now look to right (col+1)
Is there now an x underneath this x (row+1)
You should be able to roll your own with something along the lines of this, but you may have to account for carriage returns, etc.
f = text_to_be_found.get()
pos = textarea.search(f, start, stopindex=END)
##
## becomes
f = text_to_be_found.get()
t_area = textarea.get(1.0, END)
pos = t_area.find(f)
if pos > -1:
print "Found", f, pos
Generally speaking, we don't provide complete answers for homework problems, but hints to help the OP figure it out for themselves. Homework is meant to be a learning tool. And usually it is coded
elif 19 < BMI <= 25:
but is at the individual's preference of course.
Using the OP's original code, it would be something like the following, since an and statement is the same as nested if statements (both Gribouillis and I were hinting at separate blocks for each level, i.e. an additional indent).
if BMI < 19:
print " You are currently underweight"
else:
## can only be >= 19 ------------------------------------------
if BMI <= 25: ## else is the >= 19
print "You are still in a healthy weight range"
else:
## can only be > 25 ---------------------------------------
if BMI < 30:
print "You are in the overweight weight range. Please see your doctor"
else:
## can only be >= 30 ----------------------------------
print " You are obese. Please make some changes and see your doctor
def find():
start = 1.0
while 1:
find = text_to_be_found.get()
It could be that you define "find" as a function and a variable. It could also be that "text_to_be_found" is not within the scope of the function. Print the result of text_to_be_found.get() and see if it is returning anything.
I know there is a better way to write that last line,
but I'm too lazy to look into it
I think you could convert to a list and just pass a pair of index counters, but it is more than I want to do as well.
if BMI < 19:
print " You are currently underweight"
elif BMI >= 19:
print " You are in a healthy weight range"
You will never get past these two statements as they cover every possibility. Note also, that the second "elif BMI >= 19:" is not necessary as after the first if statement that is the only remaining possibility. Do this with functions instead as that will be easier to understand, then you can convert back to if statements if you want to.
def less_than_19():
print " You are currently underweight"
def greater_than_19(BMI):
if BMI <= 25:
print "You are still in a healthy weight range"
return
elif BMI < 30:
print "You are in the overweight range. Please see your doctor"
return
else: ## has to be >= 30
print " You are obese. Please make some changes and see your doctor"
if BMI < 19:
less_than_19()
else:
greater_than_19(BMI)
What i am trying to do is take the list of strings, which must be of equal length, and use a nested for loop to go over each character and its neighbours for creation of the relevant equations.
This solution is similar to a tic-tac-toe game, except the board can be any size. One way to do it is to index a dictionary using a tuple containing the row & column number. The neighbors then would be a row, column tuple for row+1, row-1, col+1, and col-1.
shape=[
' ',
'++++',
'xxxx',
'xxxx',
'xxxx',
'----',
' ']
shape_dict = {}
for row, rec in enumerate(shape):
for col, ch in enumerate(rec):
shape_dict[(row, col)] = ch
print shape_dict[(2,2)] ## print one as an example
At the very least you should test a program before posting the code here. If you test the code posted I think you will find that it does not work as one would expect it to.
if a student passes the exam, but fails the unit by not more than 5% of the total assessment,
You are going to find the difference between the student's grade and the total assessment.
See the Student class under "Key Functions" here http://wiki.python.org/moin/HowTo/Sorting if you are talking about a list of classes. Also, see the "The Old Way Using the cmp Parameter" on the same page.
Can you feed HTMLParser one record at a time until the data is found? It would depend on the data type of course (i;m not an HTMLParser user either).
while not myparser.found:
ctr += 1
myparser.feed(info[ctr])
There is something terribly wrong if a 200 element list (10x20) takes that long to run. To answer your question, you can use a dictionary of tuples to get better performance. For example:
medium[k[0]][k[1]] = time
becomes
medium_dict[ (k[0], k[1]) ] = time
The simpliest way to time something is to use datetime. You would probably start by timing a suspect function. There is also the timeit module but that slows things down by a factor of 10 or more.
def newCoords(tup):
now = datetime.datetime.now() ## start time
newtup = ()
for k in tup:
## the following if statement does nothing, unless you want to exclude these records.
## if you do want to exclude them, place this if() under the next "if medium [k[0]][k[1]] == 'e':"
## there is no point testing every record
if k[0] >= xSize or k[1] >= ySize or k[0] < 0 or k[1] < 0:
pass
elif medium[k[0]][k[1]] == 'e':
newtup += k,
print datetime.datetime.now() - now ## print elapsed time
return newtup
And this is the code that I ran.
import datetime
now = datetime.datetime.now()
#Define size of matrix
xSize, ySize = 10, 20
#Define sources
s1x, s1y = 0, 0
s2x, s2y = 1, 1
# create a 10 x 10 matrix of zeroes
medium = [['e' for y in range(ySize)] for x in range(xSize)]
#Return the tuple of points that is the moore neighbourhood
def moorePoints(tup):
coords = ()
for x1 in range(-1,2):
for …
Start by reading the input file (and printing some or all of it's contents to make sure). Post the code used to read and print the file here and we will help you format the output file. Generally speaking, word questions yield word responses and questions with code yield code responses.
You can use a one to one dictionary
"Ä…" --> "a"
or use the ord/decimal value if there are codec conversion problems. A decimal value conversion dictionary would be something like:
conv_dict = {}
conv_dict[ord("Ä…")] = "a"
#
# and to convert
test_ch = "Ä…"
if ord(test_ch) in conv_dict:
test_ch = conv_dict[ord(test_ch)]
Note the name of the function:
num_even_digits
It works correctly. You are calling the wrong function.
Use a function.
def download_url(channel_num):
url = 'http://192.168.1.6:8008/schedule.html?channel=%s' % (channel_num)
texto = urllib.urlopen(url).read()
index = texto.find('<td class="topaligned "><div class="withmargin nowrap"')
h1 = index+55
index = texto[h1:].find('><span class="title">')
pi1 = h1 + index + 21
index = texto[pi1:].find('</span><br')
pf1 = pi1 + index
index = texto[pf1:].find('<td class="topaligned "><div class="withmargin nowrap"')
h2 = pf1+index+55
index = texto[h2:].find('><span class="title">')
pi2 = h2 + index + 21
index = texto[pi2:].find('</span><br')
pf2 = pi2 + index
print texto[h1:h1+19]+' '+texto[pi1:pf1]+'\n'+texto[h2:h2+19]+' '+texto[pi2:pf2]
if __name__ == '__main__':
download_url("120")
download_url("121")
tracking.objects() returns a list of objects
If it does return a list then you would use
allobjs.append(obj[0])
allobjs.append(obj[1])
or allobjs.append(tacking.objects[0])
etc. We here have no way of knowing what obj[0] contains. A little more info is necessary as you seem to be using a list of classes but that is just a guess.
def main():
maze= open('maze.txt','r+')
for line in maze:
line = line.strip()
print line
maze.close()
print
start(maze,x,y)
print maze[y][x]
This code won't run. You don't call main() and neither maze, x, or y are defined before calling the start(maze, x, y) function. "How To Think Like A Computer Scientist" is a good learning tool; "Functions" Chapter (3.5) = http://www.greenteapress.com/thinkpython/html/book004.html
You should use Python's sort() function for lists. In any case, "doesn't work" is not descriptive enough. Include some test input, your output, and the desired output if you want to write the sort code yourself.
In addition to what Gribouillis said, you have it backwards. (Please don't use "i", "l", or "o" as single digit variables as they can look like numbers.)
for j in range (len(myList-1)):
for k in range (j+1, len(myList)):
Check itertools' product.
import itertools
list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
x = itertools.product(list_1, list_2)
for y in x:
print y
""" My result
(1, 4)
(1, 5)
(1, 6)
(2, 4)
(2, 5)
(2, 6)
(3, 4)
(3, 5)
(3, 6)
"""
Use some kind of a switch that you turn on after the first instance is found.
import fileinput
string_found = False
for line in fileinput.FileInput("text.txt", inplace=1):
if (not string_found) and ("hello" in line):
line=line.replace("hello","hello2")
print line
string_found = True
String formatting is a tool you want to get to know. http://diveintopython.org/native_data_types/formatting_strings.html
import datetime
now = datetime.datetime.today()
url = 'http://samplewebsite/example/example&startdate='
url += '%d%02d%02d&enddate=%d%02d%02d&market_id=X' % \
(now.year, now.month, now.day, now.year, now.month, now.day)
print url
i want to get this:
using :
word = '1000011100001110001101010111111001110000'
But you could also get '10' & '000' for the first two, as '000' is also one of the dictionary values. You will have to weight the values and check in that order. So, to check with the length of the value as the weight, you would check for a two byte match; if not found, add a third byte and check for a three byte match; and if not found, check for a four byte match. How ever you do it you will have to use some kind of algorithm to decide a double match like the one in the example above. Then you would probably call functions in the appropriate order until a match is found, using slicing to reduce the original string.
You'll have to post the code for my_function(a, b, c, d) or whatever it is called. This statement
file.write(my_function(a, b, c, d))
would write the return value. Does the function return a value, and if so, what does it return?
This is where you run hit() for every square.
for i in range(self.y):
for j in range(self.x):
self.square[i][j]['command'] = self.hit(i, j)
Print i and j if you want to check it. Also, self.hit(i, j) does not return anything so self.square[j] will always be 'None'.
The second while/break statements in displayMenu() does nothing. You can delete them. And just use another function to write to the file.
def displayMenu(self):
while True:
print self.menu
input = raw_input("");
if input.upper() == "V":
## while input.upper() == "V":
fileHandle = open ( 'scores.txt', 'r' )
str1 = fileHandle.read()
fileHandle.close()
print str1
## break
def to_file(self):
print "\nWould you like to save your score? (Y)es or (N)o:"
save_it = raw_input()
if save_it.upper() in ["Y", "Yes"]:
fp = open(fname, "w")
fp.write(all_the_stuff)
fp.close()
Generally, you use an increasing counter, increasing every time a prime number is found, until it reaches n. For how to find primes, there are literally thousands of posts on the web. http://www.daniweb.com/code/snippet216880.html
It is simpler to use loops. This should get you started. It has an example of using one list to hold all of the entrants, and how to print them using a loop.
import random
import time
def predict():
A=['SOUTH AFRICA','MEXICO','URUGUAY','FRANCE']
B=['ARGENTINA','NIGERIA','KOREA REPUBLIC','GREECE']
C=['ENGLAND','USA','ALGERIA','SLOVENIA']
D=['GERMANY','AUSTRALIA','SERBIA','GHANA']
E=['NETHERLANDS','DENMARK','JAPAN','CAMEROON']
F=['ITALY','PARAGUAY','NEW ZEALAND','SLOVAKIA']
G=['BRAZIL','KOREA DPR','IVORY COAST','PORTUGAL']
H=['SPAIN','SWITZERLAND','HONDURAS','CHILE']
print "* groups *"
time.sleep(2)
group_list = [ A, B, C, D, E, F, G, H ]
start_dec = ord('A')
for group in group_list:
print "group %s" %(chr(start_dec)), group
start_dec += 1
time.sleep(1)
##--------------------------------------------------------
## you can use randint or random shuffle
##--------------------------------------------------------
first_round = []
for group in group_list:
random.shuffle(group)
## print group ## uncomment if you want to see the results of random.shuffle
first_round.append([ group[0], group[1] ])
## print first_round
print "\n* ROUND OF 16 *"
time.sleep(1)
## letters corresponding to the lists
letters = ["A", "B", "C", "D", "E", "F", "G", "H"]
## numbers formatted for printing
numbers = ["1st", "2nd", "3rd"]
for j in range(4, 9):
numbers.append("%dth" % (j))
ctr = 0
for x in range(4):
print "%s eighth finals: winners 1%s vs 2%s" % \
(numbers[ctr], letters[ctr], letters[ctr+1])
print "%s eighth finals: winners 1%s vs 2%s" % (\
numbers[ctr+1], letters[ctr+1], letters[ctr])
ctr += 2
##--------------------------------------------------------
## note that your statement
## print "1st eighth finals: winners 1A vs 2B",I
## uses "I" before it is defined
##--------------------------------------------------------
predict()
You want to return the string found from each of the functions, instead of writing it to a file. Then, if conditions are met, write them all to the file. So readfiles() would be similar to the following using your existing structure.
def readfiles(filename):
filelist = open(filename)
write_owner = ""
write_name = ""
for line in filelist:
files = line[:-1]
print files
owner = add_ownerid(filename)
if len(owner): ## owner was found in the line
write_owner = owner
name = add_ownername(files)
if len(name):
write_name = name
user = add_userid(files)
## assumes that user id is the cut off point
if len(user) and len(write_owner):
write_data(write_owner, write_name, user)
write_owner = ""
write_name = ""
i have 2 list contaning 4 element
= 8 elements total
I must create 2 new list which contain 2 element
= 4 elements total. What happens to the other 4 elements?