Thus spake the master programmer:
``After three days without programming, life becomes meaningless.''
From The Tao Of Programming site, which is new to me. Don't know of the rest of you are already enlightened.
Thus spake the master programmer:
``After three days without programming, life becomes meaningless.''
From The Tao Of Programming site, which is new to me. Don't know of the rest of you are already enlightened.
It should be easier if you use a dictionary pointing to a list of shares. This code assumes that you do not care about order of execution, otherwise you will have to order the dictionary keys and execute in that order.
def get_config():
ip_dict = {}
done = False
deny = 'n'
counter = 1
while not done:
print " Type n or N to exit "
ip = raw_input("Enter IP: ")
print "you entered ", ip
ip=ip.lower()
if ip == 'n':
done = True
flag = True
else:
ip_dict[ip] = []
flag = False
## indent while() loop to this level
## problems with tabs-you can set an IDE to convert to spaces
while not flag:
share = raw_input("Enter Shares : ")
if share.lower() == deny.lower():
flag = True
else:
ip_dict[ip].append(share)
for ip in ip_dict:
print ip
for share in ip_dict[ip]:
print " ", share
This line
db[j][0]=db[j][1]
overlays the English word in the list with the Spanish word. And do not use "sum" as it is already taken by Python for summing numbers, and "i", "l" or "O" are not good choices for single digit variable names as they can look like numbers.
db = [['dog', 'perro'], ['man', 'hombre'], ['woman', 'mujer'], ['house', 'casa'], ['eat',
'comer'], ['speak', 'hablar'], ['walk', 'caminar'], ['black', 'negro'], ['white', 'blanco'],
['large', 'grande'], ['fat', 'gordo'], ['skinny', 'flaca'], ['street', 'calle'], ['from', 'de'],
['to', 'a'], ['in', 'en'], ['the', 'el']]
def toSpanish2(x):
spanish=[]
x_split = x.split() ## don't do the same thing every time through the loop
for word in x_split:
for j in range(len(db)):
## in keyword will return a false positive, i.e. "the" in "they"
if word == db[j][0]:
spanish.append(db[j][1])
return " ".join(spanish)
x=raw_input(" Please type an English sentence: ")
print toSpanish2(x)
and provide us with enlightenment
The wise programmer is told about Tao and follows it. The average programmer is told about Tao and searches for it. The foolish programmer is told about Tao and laughs at it.
If it were not for laughter, there would be no Tao.
The highest sounds are hardest to hear.
Going forward is a way to retreat.
Great talent shows itself late in life.
Even a perfect program still has bugs.
From http://www.canonical.org/~kragen/tao-of-programming.html#book1
It sounds like you would have to alter the perl script to accept input/inputs from some source other than the command line. You could use multiprocessing to run in parallel, or use one of the parallel python programs, especially if you have multiple cores
http://github.com/mattharrison/coreit
http://www.parallelpython.com/content/view/17/31/
random.sample() returns a list (of cards in your case).
import random
x = ["a", "b", "c", "d", "e"]
ret = random.sample(x, 2)
print ret, type(ret)
takes a list of real numbers as input
And how are the numbers input; from a file, or via the keyboard. Whichever it is, that is where you want to start. Read the input from a file or the keyboard into a list, and post that code for further help.
Some modifications to your code
1. Used a list for keywords instead of if() statements
2. Added an indicator that turns on when "description" is found and prints those records. Add whatever to want to process those records instead of the print statement under "if des".
infile = open("books.txt","r")
lines = infile.readlines()
infile.close()
keywords = ("title", "author", "publisher")
print '{'
print ' "books":'
print ' "["'
des = False
for ctr in range(0, len(lines)):
commas = lines[ctr].split('*')
## look in a tuple instead of testing each with an if() statement
if commas[0] in keywords:
print ' {"%s":"%s"' % (commas[0], commas[1])
## some other keyword = set "description" to False
des = False
elif commas[0] == "description":
print "-"*50
des = True
## assuming you want to print the "description" line also
if des:
print lines[ctr]
What GUI toolkit are you using and what type of object is "frame"?
The code works fine for me on Slackware Linux. What are you using for input, and what output do you get?
The limits of floating point numbers
http://www.lahey.com/float.htm
http://docs.python.org/tutorial/floatingpoint.html
Use decimal for more precision.
from decimal import Decimal as dec
# 0.1 + 0.1 + 0.1 - 0.3 = 0.0
x = dec("0.1")
y = dec("0.3")
print x + x + x - y
When the if() statement is not executed, there is no "x" to return. Note also that the statement "return y" will never be reached/executed.
Since there is no code on how or how many items in self.play_hands were declared, and no error message or what happened versus what was expected to happen, there is no way to comment. Generally, you would use list comprehension.
self.player_hands=[["Testcard"] for x in range(self.num_of_players)]
Also, "i" l" and "O" are not good choices for single digit variable names as they can look like numbers.
Well?? What happend to the code? Code to, say, find the lowest divisor to start?
My quick and dirty solution, so I can delete this code.
def find_divisor(input_number):
sq = int(input_number**0.5) + 1
print("-->sq for %d = %d" % (input_number, sq))
for ctr in range(2, sq+1):
if 0 == input_number%ctr:
return ((ctr, input_number/ctr))
return((input_number, 1))
# 252 = 2*2 * 3*3 * 7*1
input_number = 252
divisors = []
found = True
while found:
## hey baby, nice pair (of numbers)
smaller_1, larger_1 = find_divisor(input_number)
print(smaller_1, larger_1)
## do again for the second (larger) number of the pair found
if smaller_1 != input_number: ## divisor found
smaller_2, larger_2 = find_divisor(larger_1)
print(" ", smaller_2, larger_2)
divisors.append((smaller_1, smaller_2))
input_number = larger_2 ## larger number of the 2nd pair
else: # no divisor=(original_number and 1)
## eliminate (1,1); a number like 6 will return (2, 3) and (1, 1)
if smaller_1 != 1:
divisors.append((smaller_1, larger_1))
found = False
print(divisors)
The brute force way to guess would be to generate a list of 50, or 1000, numbers, and delete the guess from the list. Then use random.choice(numbers_list) to generate the next number. You would also want to slice off part of the list when you change the lower or upper number boundaries. But it would indeed be easier to divide (higher-lower) by 2 and guess that until you reach some low number like 5 or 10 for a difference. Then just guess them in order.
it is still guessing the same numbers twice, how do I prevent it from doing so.
## NOT tested
if highlow == 1:
lowest = guess
if highlow == 2:
highest = guess
not_new = True
while not_new: ## keep trying until one is found
guess = random.randint(lowest, highest)
if guess not in already_guessed_set:
not_new = False
already_guesed_set.add(guess) ## I would suggest a set instead of a list
print "Is", guess, "your number?"
answer = input ("1 = yes, 2 = no")
attempts += 1
Some print statements should help. Note that "word" will only contain the final word in a sentence. Once you can get each word, add a counter to count the letters as they are added to the new "word" field or what ever you wish to use.
m = input("Enter a string ")
i = 0
m=m+" "
while m[i]==" ": i=i+1
print("#1 i =", i)
print ()
print("while i<len(m)-1-->", i, "< ", len(m)-1)
while i<len(m)-1 :
print " i in while =", i
word = ""
while m[i]==" ": i=i+1
while m[i] != " " :
word = word + m[i]
i=i+1
print("final print", word, "i =", i)
The answer is simple. Put Some Damn Locks On The Lockers! You have to have a way to keep track of the lockers that you understand. It can be as simple as a list of integers that you set to zero/false for closed, and 1/true for open, that is sent to a function that also receives the "monkey number" and reverses every "monkey number" locker, then returns the list. Print the list and see if it is the same as slate's solution.
## A helpful trick
x = False
for j in range(5):
print x
x = not(x)
## or
x = 0
reverse = [1, 0]
for j in range(5):
print x
x = reverse[x]
print x
First suggestion is do not post 145 lines of untested code and expect your forum servants to wade through all of it. Second, your if/else indentation is screwy, and there is a while() loop in the middle, which may or may not be at the correct indentation level. Third, you should print the following because it is not doing what you expect
print int(opcao == 1)
if int(opcao == 1) :
Break this into functions. If you wrote it and you can't tell what is going on, how can you expect someone else to understand it. So, start with a function that is the "first menu" and test it. Then, write the function(s) that it calls and test each one of those functions. Then go on to the next step. To get you started:
def first_menu():
lit = """ The first menu is the main menu. The options are:
1 - Show read data (and put them in the table)
2 - Show data already in the table
3 - Make the graph
"""
choice = ""
while choice not in ['1', '2', '3']:
print lit
choice = raw_input("Enter your choice: ")
print "\n correct choice entered =", choice
if choice == '1':
get_serial_data()
elif choice == '2':
second_menu()
first_menu()
Post the code as it is now. Note that you should now be using a tuple, so code has to be changed, like this example:
# pick one randomly from the sequence
word_tuple = random.choice(words_and_hints)
# create a variable to use later to see if the guess is correct
word = word_tuple[0]
correct = word
Well?? What happend to the code? Code to, say, find the lowest divisor to start?
Start with the smallest divisor, 2; see if it is a divisor and increase up to the square root + 1. So in this case
252 / 2 = 126
So 2 is a divisor. Then using 126 (divide by 2 up to square root 126 + 1)
126 / 2 = 63 -----> 2*2
Using 63
63 / 2 = False
63/3 is a divisor = 21
21 / 2 = False
21 / 3 = 7 (square root + 1 = 3)
and repeating the process yields no other divisors --> 1
You could use recursion for this, but I don't like recursion so would suggest a while loop. Come up with some code to start us off. I did a sloppy quick try using a while loop to call a function and came up with 25 lines of code.
Since "lst" is used on 5 lines of the code, there is no way to tell where the error is. General comments would be the list "prime" is an exact copy of "lst" and so you return a copy of the initial "lst" list. Also, print len(lst) before this statement
while len(lst) != []:
so you know what is being compared to what. And print "lst", "prime" and anything else along the way so you know what is inside the container. There is a lot of testing to be done here. For future posts, test first and post the complete error message.
To get you started if you want to roll your own, you would iterate over each character and append to a list unless the character is one of the dividers. If it is a divider, you would join and append the sub-list to the final list, initialize sub-list as an empty list, and continue appending until the next divisor.
What happens if the first "Steve" is 7 instead of 1 -----> , , ], etc. Should it be at the end of the first list or at the end of all of the items? Generally, you would flatten the list and then sort if all items are to be sorted equally.
import itertools
import operator
r =[[['steve',7, 40], ['steve',3, 20], ['steve',2, 30]],
[['john',5, 50], ['john',6, 40], ['john',4, 30]]]
r_flat = list(itertools.chain(*r))
r_flat.sort(key=operator.itemgetter(1))
print r_flat
#
#output =[['steve', 2, 30], ['steve', 3, 20], ['john', 4, 30],
# ['john', 5, 50], ['john', 6, 40], ['steve', 7, 40]]
I must fix a code so I can write roman letters (bigger than 3999)
For Arabic, if it is larger than 3999 subtract 1000 and add 1000 to a separate field until it is less than 4000. You would then divide the "thousands" field by 1000, convert and print with parentheses, since 4000=(IV). Do the reverse for Roman, i.e. convert then parens to Arabic and multiply by 1000, then add to the rest of the number.
Rolling your own is the best way to go. Alternatively you could replace "?" and "!" with "." and split on the period, but that requires many loops through the file.
They are called programming __languages__ for a reason. Double check some of the arithmetic as you never zero the numerator or denominator after each month, and make sure the last month of data is in the final list. If it isn't, why not? The Python Sorting Guide (see below). Or do you have do it in a more traditional manner, i.e. a list or sort yourself.
import operator
fileName='table.csv'
dataList=getDataList(fileName)
dataList.pop(0)
monthlyAverageList=getMonthlyAverage(dataList)
#print monthlyAverageList
printInfo(monthlyAverageList)
## assuming you are using Python2.6 or greater
monthlyAverageList.sort(key=operator.itemgetter(-1)) ## sort on last column
print monthlyAverageList
monthlyAverageList.sort(key=operator.itemgetter(-1), reverse=True)
print monthlyAverageList
I'd have to see the complete error message and the line that caused it. Next, check for differences in the month field. Also, you can eliminate splitting the date twice.
for i in dataList:
date = i[0].split("-")
month=date[1]
year=date[0]
We are perhaps seeing this in two different ways. I am storing all of the records for one month and then calculating because I thought it would be easier to understand. You can add close*volume to a field, and add volume to a second field, and then calculate the formula when there is a new month. It is up to you as to how you want to do it.
for i in dataList:
if month != previous_month:
average=close_volume_total/volume_total
a_tuple= (month, year, average)
monthlyAverageList.append(a_tuple)
close_volume_total = 0.0
volume_total = 0.0
close_volume_total += close * volume
volume += total
previous_month = month
Sorry for the delayed responses. I am doing many other things today.
My mistake. It's a csv file so a list of lists. New code:
def get_monthly_average(dataList):
## do 30 records as a test
data_list_short = dataList[1:31]
print data_list_short
close_vol_list = []
for rec in data_list_short:
## the following will yield an error for the header record
close = float(rec[6])
vol = float(rec[5])
junk_list = []
junk_list.append(close)
junk_list.append(vol)
print "appending junk_list =", junk_list
close_vol_list.append(junk_list)
## or
## close_vol_list.append([close, vol])
print "-"*30
print close_vol_list
print "-"*30
## print and example of close X volume used in the numerator of
## the calculations although this is for all records in the
## short list, not for one month
for rec in close_vol_list:
## since it was stored as close, volume, [0]=close, [1]=volume
print rec[0]*rec[1], rec[0], rec[1], rec
You are doing something wrong. Post your code for the creation of "dataList", and print and post the first 10 or so records.
The first thing you have to do is to separate the data by month. The first thing you have to do is separate the data by month.
I dont quite understand what you are trying to do with this part:
junk_list = []
junk_list.append(close)
junk_list.append(vol)
close_vol_list.append(junk_list)
I thought, perhaps wrongly, that this code would make it obvious that you are creating a list of lists. Try the following code as an illustration (untested so there may be typos). But first you have to do is separate the data by month.
def get_monthly_average(dataList):
## do 30 records as a test
data_list_short = dataList[1:31]
print data_list_short
close_vol_list = []
for rec in data_list_short:
substrs = rec.split(",")
if len(substrs) > 6: ## allow for possible malformed records
## the following will yield an error for the header record
close = float(substrs[6].strip())
vol = float(substrs[5].strip())
junk_list = []
junk_list.append(close)
junk_list.append(vol)
print "appending junk_list =", junk_list
close_vol_list.append(junk_list)
## or
## close_vol_list.append([float(substrs[6].strip()), float(substrs[5].strip())])
print "-"*30
print "-"*30
print close_vol_list
## print and example of (close X volume) used in the numerator of
## the calculations although this is for all records in the
## short list, not for one month
for rec in close_vol_list:
print close*vol, close, vol
Use the Date, Volume, and Adj Close fields to calculate the average
monthly prices. Here is a formula for the average price for a month, where Vi is the
volume and Ci is the day i’s adjusted close price (Adj Close).
averagePrice = (V 1
∗ C 1 + V 2 ∗ C 2 + . . . + V n ∗ C n)/(V 1 + V 2 + . . . + V n)
So you want to accumulate [close, volume] in a list of lists, and when the month field changes, calculate the formula, which is just a for() loop, looping through the list.
For each month create a tuple with two items: the average for that month, and the
date (you need only the month and year). Append the tuple for each month to a list
(e.g. monthlyAveragesList), and after calculating all the monthly averages, return
this list.
So now that we have the calculation result, append it to the totals list with the (previous) month and year, and re-initialize the close+volume list as an empty list, and start appending close, volume to the now empty list until the next change in date.
Start by testing the month (this_month != previous_month) and print when a change occurs. Then add code to append close+volume to the list of lists, and send it to a calculation function when the month changes, etc. I got 76 months of data from Yahoo, so …
I get an error because .txt was not in quotes. Also note that you will get an aditional error because "options" is declared after the --output parser statement.
There is at least one other post on this site that already does this. A search should bring it up.
You are going to have to store the widgets in a list or dictionary to do that, and tell remove() which one you want to delete. The following is a program that shows how to associate a button to a specific dictionary member by binding a unique instance of the function handler() to each button. You would use a function like cb_handler to destroy the appropriate widgets. You might also consider using a separate frame for each widget group and then destroying the single frame. Note that since you use the same variable for all widgets, self.l_host, etc. always contains the last widget created.
from Tkinter import *
class ButtonsTest:
def __init__(self, top):
self.button_dic = {}
top.title('Buttons Test')
self.top_frame = Frame(top, width =400, height=400)
self.buttons()
self.top_frame.grid(row=0, column=1)
exit = Button(self.top_frame, text='Exit', command=top.quit).grid(row=10,column=1, columnspan=5)
##-------------------------------------------------------------------
def buttons(self):
b_row=1
b_col=0
for j in range(1, 11):
self.button_dic[j] = "self.cb_button_%d()" % (j)
b = Button(self.top_frame, text = str(j))
b.grid(row=b_row, column=b_col)
def handler ( event, self=self, button_num=j ):
return self.cb_handler( event, button_num )
b.bind ( "<Button-1>", handler )
b_col += 1
if b_col > 4:
b_col = 0
b_row += 1
##----------------------------------------------------------------
def cb_button_1(self):
print "push button 1 and this code is executed"
##----------------------------------------------------------------
def cb_button_2(self):
print "push button 2 and this code is executed"
##----------------------------------------------------------------
def cb_button_3(self):
print "push button 3 and this code is executed"
##----------------------------------------------------------------
def cb_handler( self, event, cb_number ):
print "cb_handler", cb_number, self.button_dic[cb_number]
if cb_number < 4:
exec(self.button_dic[cb_number])
##===================================================================
root = Tk()
BT=ButtonsTest(root)
root.mainloop()
Read up on accessing a list by the index 10.2 Lists are mutable, here, as well as the writing or updating comments in 10.3. Initialize a list (using a for loop to append zero each time) so it has one element equaling zero up to the maximum number+1. Under a new loop, generate a number using randint. The number will correspond to the list. So if the number is 5, add one to element #5 of the list, etc. I can't do it for you, but post back with code for any part that isn't working.
trying to do it with a while loop
Post your code so we have something to comment on. Also, using a dictionary or list is separate from the for() or while() loop.
#repeat
print 'Enter type (string)'
type = str(raw_input())
"type" is reserved by Python as a function name that returns the type of an object; a string, class, integer, etc. Use "category" or some other name that is less confusing. Also, raw_input returns a string so type casting to string is not necessary. And Python is not C, so the use of an orphaned call to main() in the body is not necessary and also confusing. It should be obvious which statements are automatically executed when the program file is executed ("readability counts" and "explicit is better than implicit"). An introduction to forming classes can be found here.
Thanksgiving brought about the creation of T.V. Dinners
Part of the reason that Swanson started creating T.V. Dinners in 1953 was because they needed to find something to do with 260 tons of frozen turkeys that were left over from Thanksgiving. Talk about a lot of Turkey dinners!
Do you want to take each record and print it as a column under the heading?
Good to know that it worked. It is now in my notes for any future questions.
Consider posting this in the tutorials forum also so we can find it later
http://www.daniweb.com/tutorials/forum114.html
Search for something like geometry in Tkinter's winfo, which you would have to call at the time the first window closes. I've never done anything like this so am not sure if it will work or not, so post back with any success or failure for future question.
You should sort both words and compare. Your code will compare "a" to "aa" and find them equal. Note that any anagram program will take "odg" and return "god" and "dog" which is all it can do.
infile = open ("/usr/share/dict/american-english", "r")
## "dict" is a reserved word
words_in = infile.readlines()
scrambled = raw_input("Enter the scrambled word: ")
scrambled = scrambled.lower()
scrambled_list = list(scrambled)
scrambled_list.sort()
for word in words_in:
word_list = list(word.strip().lower())
word_list.sort()
## you don't really have to compare lengths when using lists as the
## extra compare takes about as long as finding the first difference
if word_list == scrambled_list:
print word, scrambled
You still have to have a way to convert distance to fuel used. For that you have to know what the miles/kilometers per gallon/litre is. Note also that the question says that move() receives a distance parameter, not a fuel parameter as you have it, which implies that the function will convert distance to fuel used.