This is very simple to do.
print len(set([1,2,4,2,7]))
This is very simple to do.
print len(set([1,2,4,2,7]))
Google came up with this site which has a link to download source code. I hope you didn't pay $99.95 for the book! http://www.jbpub.com/catalog/9780763746025/
First, you have to decide which GUI toolkit you want to use. Here's an example Google found using Tkinter http://code.activestate.com/recipes/124894/
When validating, you want to include, not exclude. So you want a list of data that is acceptable, and the input has to be in the list. That way, when another unit or type of data is introduced it is automatically an error. If your program excludes, then the new unit would be automatically included, since you did not explicitly exclude it, which is not a good idea.
Does anyone have a good synonym for exclude or include. This post could certainly use one.
Always use absolute path+file names.
filePath = "Dataset/parameter feature vectors"
for fname in os.listdir(filePath):
complete_name = os.path.join(filePath, fname)
data_str = open(complete_name).read()
index = data_str.find("female")
if index != -1:
females.append(index)
print fname
else:
print "append the ones that aren't female to a males"
Since you are testing 6 letters total, you want to use "len(w)-5" so you won't run out of letters. To set up an example using "aabbcc" as the simplest example, you only want the for loop to test the first letter. It will test a->a, b->b, and c->c. If you go beyond the first letter in this example, then you will run out of letters before you are done testing, so obviously it will not satisfy the conditions. So, the length of "aabbcc" is 6 and we want to test the first element, or 0 offset, so we want to stop at 6-6 or zero. If there were seven letters, "xaabbcc", we would test length=7 minus 6 = 1, so would test the first 2 letters, (or the zero and 1 offset), against the next 6 and not run out of letters. The for loop goes up to, but does not include the upper number, so it is len(w)-5.
def td(w):
for num in range(0, len(w)-5):
print "first test =", w[num], w[num+1]
print "2nd test =", w[num+2], w[num+3]
print "3rd test =", w[num+4], w[num+5]
if w[num] == w[num+1] and \
(w[num+2] == w[num+3]) and \
(w[num+4] == w[num+5]):
return True
return False
You want to use a class structure for this, so each player can be an instance of the same class, and divide the code into several small functions.
Also, I don't know why but I can't input more than 3 armies for the attacking army, and more than 2 for the defending army in the beginning.
if numatt not in [1,2,3]:
raise ValueError("Number of attackers dice must be 1, 2 or 3.")
if numdef not in [1,2]:
raise ValueError("Number of defenders dice must be 1 or 2.")
Here is some redundant code that you can put into one function that returns the result. And, sort() can sort in reverse, avoiding the extra statement,
attl.sort(reverse=True) http://wiki.python.org/moin/HowTo/Sorting
attl = []
for i in range(numatt):
attl.append(chr(int(random.random() * 6.0) + 1 + ord('0')))
attl.sort()
attl.reverse()
atts = "".join(attl)
## same as above
defl = []
for i in range(numdef):
defl.append(chr(int(random.random() * 6.0) + 1 + ord('0')))
defl.sort()
defl.reverse()
defs = "".join(defl)
I still don't understand why not 1 and not 2 and not 3 is the proper way to do this
Alternatives would be:
while (play_choice < 1) or (play_choice > 3):
while play_choice not in [1, 2, 3]:
# Also, you can use .lower instead of 2 compares
while play_again.lower() == 'y'':
You can set the encoding for the file
fp = codecs.open('test', encoding='utf-8', mode='w')
Or you can change the default encoding for the system
sys.setdefaultencoding('utf-8')
You may have to use encode/decode, see here
http://farmdev.com/talks/unicode/
You'll have to post your code as no one can tell what to do without code (Doh). If you are using a function, the function would return the length which would then be compared with the existing longest length, and if larger, would become the new longest length.
Using for() loops is easier. This is somewhat of a brute force method but works fine for smaller lists.
L1=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
L2=[1,2,3,4,11]
L3=[]
for number in L2:
for a_list in L1:
if (number in a_list) and (a_list not in L3):
L3.append(a_list)
print L3
##
## You can also delete from the list of lists as you add it
## to L3 so you don't search through it again, but deleting
## can cause problems in some cases
print "-" * 50
L1=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
L1_copy = L1[:]
L2=[1,2,3,4,11]
L3=[]
for number in L2:
for a_list in L1:
if (number in a_list) and (a_list not in L3):
L3.append(a_list)
L1.remove(a_list)
print "-----> L1 =", L1
print L3
This is a modified version of your program that prints what you expect. I am not sure if it is what you want or not.
def tryit(start, end):
number = start
## number >= start
## number <= end
length = 1
print number, '->',
## end+1 because length starts at 1, not zero.
while (number != 1) and (length < end+1):
## for i in range (start,end):
if number %2 == 0:
number = number/2
else:
number = (number*3)+1
length= length+1
print number, '->',
print '; length = ',length,
start = input("Enter the starting number ( 1 - 10000 ) ")
print "Enter maximum number of repetitions ",
end = input()
tryit(start, end)
The problem with your original code was that the for() loop could end before number == 1, which resulted in and infinite loop. Whenever you use a while() loop, it is a good idea to limit the number of cycles, at least when testing, to avoid an infinite loop.
Roman to integer. Note that it will take something like XXIXV and convert it. If someone already has a routine to check for valid input, please post it. And I'm afraid we've just eliminated one standard homework question. Oh well, nothing lasts forever.
roman_to_decimal = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, \
'D': 500, 'M': 1000 }
roman = raw_input("Enter the roman numeral to convert to arabic: ").upper()
converted = True
arabic = 0
for n in range(0, len(roman)-1):
this_char = roman[n]
next_char = roman[n+1]
if (this_char in roman_to_decimal) and \
(next_char in roman_to_decimal):
this_number = roman_to_decimal[this_char]
next_number = roman_to_decimal[next_char]
print "converting %s to %d....." % (this_char, this_number),
if this_number < next_number:
arabic -= this_number
else:
arabic += this_number
print "Total now =", arabic
else:
print "\nthis chr (%s) or next chr (%s) is not a valid roman numeral" \
% (this_char, next_char)
converted = False
break
if converted:
## add last roman numeral
arabic += roman_to_decimal[roman[len(roman)-1]]
print "\nThe roman numeral", roman, "is equal to",arabic
I hope pun not intended:
Please ass "Solved"...
I'll save the pun for one of your posts. And it's now too late to change it. Oh well, we'll just have to let this thread wind down the list into obscurity.
You can pipe top to a file on Linux and then read the file.
Apparently you can use WMI for MS WIndows but I have not used it http://timgolden.me.uk/python/wmi_cookbook.html#running_processes
Please ass "Solved" to the thread title so no one else wastes their time on this.
Dictionaries are indexed via a hash and so make it easy to look up things, in this case the stock symbol, without going through the sub-strings in each list. Also, they provide a convenient way to validate the data entered. In this example, "while rmv not in pf_dict:" will keep asking for an entry until one is entered that is in the dictionary. A simple example using the stock symbol as key, and a list with all of the other data as the item associated with the key.
stock1 = ["Google","GOOG", 100, 24.00, 21.98]
stock2 = ["Microsoft", "MCST", 300, 56.00, 54.00]
stock3 = ["Yahoo", "YHOO", 90, 20.00, 14.00]
stock4 = ["Apple", "AAPL", 289, 50.00, 46.99]
## assume the four lists were entered into a dictionary instead
pf_dict = {}
## indexed on symbol
for stock in [stock1, stock2, stock3, stock4 ]:
pf_dict[stock[1]] = [stock[0], stock[2], stock[3]]
print stock[1], pf_dict[stock[1]]
stChoice = 2
if stChoice == 2:
rmv = ""
while rmv not in pf_dict:
print
for key in pf_dict.keys():
print "symbol = %s for %s" % (key, pf_dict[key][0])
rmv = raw_input("Type in the ticker name for the stock you wish to remove. ")
rmv = rmv.upper()
if rmv not in pf_dict:
print rmv, "is not a valid symbol"
## valid symbol entered
del pf_dict[rmv]
print "\n", rmv, "deleted\n"
print pf_dict
Would somebody explain to me the stock_list and how it's working. I'm kind of confused because stock_list wasn't defined
for stock_list in portfolio:
print "stock_list =", stock_list
# …
return an error message if the values entered aren't either the strings 'on' or 'off'
Can you use a list instead of all of those variables? Otherwise, try the code below which tests each button individually instead of the confusing and, and, or, etc. in your code. Speaking of testing each button individually, it would be better to test each one as it is entered.
error_switch = False
for button in [b1, b2, b3, b4]:
button = button.lower()
if button != 'on' and button != 'off':
error_switch = True
if error_switch:
print 'You must enter either "on" or "off" for the button states.'
Edit: Do you know how and why
for button in [ b1, b2, b3, b4]:
works? Post any ideas. You can not really use anything like this unless you understand it.
Doug Hellmann has excellent write ups. http://www.doughellmann.com/PyMOTW/
As far as books go, I like "Dive into Python" http://diveintopython.org/native_data_types/index.html#odbchelper.dict
This is a forum for the Python programming language. Your question should be asked at the swarmplayer site, or on a board for the distro that you are using.
This will get you started, but a dictionary would work much better for this.
elif stChoice == 2:
for stock_list in portfolio:
print "symbol = %s for %s" % (stock_list[1], stock_list[0])
rmv = raw_input("Type in the ticker name for the stock you wish to remove. ")
for stock_list in portfolio:
ticker = stock_list[1]
if ticker == rmv:
portfolio.remove(stock_list)
print portfolio
longLength = 0
for i in range(startNum, stopNum + 1):
longLength = hailstone(i)
if i >= longLength:
longLength = i
print longLength
You are using "i", the incremented value in the for loop and copying it to longLength. Since we don't know what hailstone is, I am assuming it is a list. When you get some time, please read the coding conventions/style guide for Python http://www.python.org/dev/peps/pep-0008/
long_length = -1
length_num = -1
for n in range(startNum, stopNum + 1):
if hailstone[n] > long_length:
long_length = hailstone[n]
length_num = n
print long_length, length_num
#
# also you can use
elif choice.upper() == 'L':
# for
elif choice == 'L' or choice == 'l':
This appears to work, but is still rough and just a proof of concept. It adds the unit to a dictionary as it's arrive time is reached, so that any finished units can be deleted from the dictionary as well. So a unit is processed until it is finished or until the next arrive time is reached. At the end the remaining units are processed in the order received but can be sorted and processed in any other order. The toughest part of this is to break it into small enough pieces that can be easily coded.
import datetime
import time
""" Results Should Be The Following:
arrive=[0,3,6,7,7,10,15,16]
exe=[12,3,11,1,4,5,20,7]
Num Process Time Time
Time Remaining Now
0 12 0 added
0 3 9 3
1 3 added
1 3 0 6 #1 Finished
2 11 added
0 1 8 7
3 1 added
4 4 added
3 1 0 8 #3 Finished
4 2 2 10
5 5 added
4 2 0 12 #4 Finished
5 5
5 3 2 15
6 20 added
5 1 1
"""
class ProcessUnit:
def __init__(self, arrive, exe):
unit_to_process = {}
ctr = 0
unit_number = 0
time_now = 0
next_start_time = 0
add_ctr = 0
stop = len(arrive) - 2
## add first unit to start the process
unit_to_process[add_ctr] = [ arrive[add_ctr], exe[add_ctr] ]
while add_ctr < stop:
ctr += 1
if ctr > 500: ## limit to 500 cycles
add_ctr = stop +1
print "\n", "-"*60
## add next unit to …
You would have to step through the unicode and count the number of actual letters, and then add enough spaces to the string to make it the length you want. This appears to work, but you'll have to test for yourself.
def print_rec(rec):
print rec
substrs = rec.split()
greek_str = " ".join(substrs[1:])
num_chr = 0
for chr in greek_str:
print ord(chr),
if ord(chr) not in [206, 207]:
num_chr += 1
print "\n", num_chr
fp = open("./origDict.txt", "r")
## skip heading
fp.readline()
print_rec(fp.readline())
print_rec(fp.readline())
print_rec(fp.readline())
Also, write to the odd numbers file at the same time. Plus, do you want to test for zero or negative integers?
def write_evens():
even_file = open("evens.txt", "w")
odds_file = open("odds.txt", "w")
the_file = open_read("integers.txt", "r")
for rec in the_file:
rec = rec.strip()
try :
num = int(rec)
if num % 2 == 0:
output_fp = even_file
else:
output_fp = odds_file
output_fp.write( ("%d\n" % (num) )
## conversion to an integer failed
except:
print rec, "is not a valid integer"
even_file.close()
odds_file.close()
It appears that the problem is here
while sum(waitToExe) != 0: #while the sum of waiting's execution duration is NOT zero...
You subtract from waitToExe, but not until it reaches zero. It appears that you only subtract once for each "n".
while n<len(waitToExe): #for length of waiting...
sortWaitToExe = sorted(waitToExe) #sort to get smallest job duration
if waitToExe[n] == sortWaitToExe[0] and waitToExe[n]!=0: #if current item = the lowest item in the sorted list
print "Processing item! Time: ",msCount #"process"
print arrived
print waitToExe
waitToExe[n] = waitToExe[n]-1 #subtract one "ms" from waiting duration
Also, you do not return arrived or waitToExe from the function, so they should be returned or should just be defined by the function. I would suggest using a few functions instead on one long block of code to pinpoint the errors to a small function.
You want to keep all of the sqlite stuff in Database.py and call the add, change, delete functions from the WX program. An example using addition.
import sqlite3
##import addnew
class DBClass:
def __init__(self):
#Creating a connection to the database.
self.connection = sqlite3.connect('contacts.db')
#Creating a cursor object to interact with the databae
self.db = self.connection.cursor()
#creating tables
self.db.execute("CREATE TABLE IF NOT EXISTS contacts (fname VARCHAR, lname VARCHAR NOT NULL PRIMARY KEY, phonenumber VARCHAR, address VARCHAR, email VARCHAR)")
self.connection.commit()
##................................................................................................
def __del__(self):
self.db.close()
##................................................................................................
def add_record(self, add_tuple):
""" receives a tuple and adds it to the database
does not do any checking of data, so will add
duplicate records, or malformed data
to call this: self.database.add_record(tuple_to_add)
"""
self.db.execute("insert into contacts (fname, lname, phonenumber, address, email) values (?, ?, ?, ?, ?)", add_tuple)
self.connection.commit()
##................................................................................................
def print_all(self):
""" Retrieves all rows as a sequence and prints that sequence:
"""
self.db.execute("select * from contacts")
for rec in self.db.fetchall():
print rec
##====================================================================
## simulate calling this from the wxpython program
##====================================================================
class WXProgram:
def __init__(self):
self.database = DBClass()
f_name = "abc.txt"
last_name = "Smith"
phone="555-5555"
address="123 Main St."
email="Smith@gmail.com"
self.database.add_record( (f_name, last_name, phone, address, email) )
f_name = "def.txt"
last_name = "Jones"
phone="555-1111"
address="345 First St."
email="Jones@gmail.com"
to_add = (f_name, last_name, phone, address, email)
self.database.add_record(to_add)
print "printing records"
self.database.print_all()
## we don't have to explictly close the class, but it can be
## done by assigning self.database some other value
self.database = None
##====================================================================
if __name__ == "__main__":
WX=WXProgram()
If you didn't close the database
connection.commit()
db.close()
you sould be able to access it via Database.db from the second program so try substituting that for self.database and see if it works, or just use
self.database = Database.db
Is this logic correct?
arrive=[0, 3, 6, 7, 7, 10, 15, 16]
exe= [12, 3, 11, 1, 4, 5, 20, 7]
The first piece arrives at 0 and takes 12 units to complete, so if we add completion time, we have
arrive=[0]
exe=[12]
completion=[12]
arrive=[0, 3]
exe=[12, 3]
completion=[12, 6]
The second piece arrives at 3, and takes 3 units to complete=completes at 6. Since it's completion time is less than the first piece, work is done on it. So at the completion of the second piece, that is at "6", we have for this first piece:
arrive=[6] ## time now
exe=[9] ## units left --> 12-3
completion=[15]
etc.
So you would use a function to compute completion whenever a piece is added, or when one piece completes and take the lowest completion time?
It's defined in a external file called Database.py. That is the reason I imported Database at the top. Do you want to see that file. I haven't fixed my problem yet. More help would be greatly appreciated. Thanks!
Post the code. You have to access the variable from the class in Database.py It would roughly be something along the lines of
DB = Database.database() ## create instance of database class
self.database = DB.connection.cursor()
Does anyone know how to change border colour of a widget
Border colors, AFAIK, are the same as the widget color, so you would have to use an outside, empty widget of one color, and an inside widget of another color, although that is not quite what you want. The PMW toolkit extension does have a bordercolor key word but I have never tried it.
A simple example using ".get()". The print button calls the getit function when it is pushed. Note the use of "self" to create an object variable that belongs to that class object, so it can be accessed anywhere within the class as well as accessing it as a member of that class instance, in this case the __main__ print statement. Also note that label_2 and entry_1 both share the same StringVar. Two good references
http://effbot.org/tkinterbook/
http://infohost.nmt.edu/tcc/help/pubs/tkinter/index.html
import Tkinter
class EntryTest:
def __init__(self):
self.top = Tkinter.Tk()
self.str_1 = Tkinter.StringVar()
label_lit = Tkinter.StringVar()
label_1 = Tkinter.Label(self.top, textvariable = label_lit )
label_1.pack()
label_lit.set( "Test of Label")
label_2 = Tkinter.Label(self.top, textvariable = self.str_1 )
label_2.pack()
entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1)
entry_1.pack()
self.str_1.set( "Entry Initial Value" )
print_button = Tkinter.Button(self.top, text='PRINT CONTENTS',
command=self.getit, bg='blue', fg='white' )
print_button.pack(fill=Tkinter.X, expand=1)
exit_button = Tkinter.Button(self.top, text='EXIT',
command=self.top.quit, bg='red', fg='white' )
exit_button.pack(fill=Tkinter.X, expand=1)
entry_1.focus_set()
self.top.mainloop()
##-----------------------------------------------------------------
def getit(self) :
print "getit: variable passed is", self.str_1.get()
##===============================================================
if "__main__" == __name__ :
ET=EntryTest()
print "under __main__ =", ET.str_1.get()
That's not a good example to copy (although the book ultimately solves that problem if memory serves.). Find one using the canvas widget as it uses a top left corner (x,y) and a bottom right corner. A starting point
http://effbot.org/tkinterbook/canvas.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/create_rectangle.html
You would generally use a for loop to iterate through a list. I'm creating one output string, but you could also print within the for loop. Also, please do not use "i", "l" or "o" as single letter variable names as they look too much like numbers.
test_list1 = [1,2,3]
test_list2 =['blah',50]
output_str = "%d" %(test_list1[0])
for n in range(1, len(test_list1)):
output_str += " isn't %d" % (test_list1[n])
output_str += " which isn't %d" % (test_list2[1])
print(output_str)
self.database.execute('INSERT INTO contacts (fname) VALUES (null,?),' [fname])
AttributeError: 'contact' object has no attribute 'database'
It means that you have not declared "self.database" anywhere in your program, and the interpreter does not know if it is a variable, file pointer, another class, etc.
A Python list will hold something like 2 trillion items, but is going to be pretty slow with a very large number or records in it. If your list is going to be 100 million records or more, then consider an SQLite database instead. If it's a paltry one million records (we now live in a gigabyte world), then there should not be a problem, but you might want to consider using a dictionary or set as they are both indexed via a hash and would be much faster on lookups.
Test your code. It doesn't print anything. Also, please use no more than 4 spaces for indents. Finally, it is bad practice to use "i", "l", or "o" as single letter variable names as they can look like numbers. There are at least 3 ways to solve the problem.
st = "abcd123"
for ch in st:
if ch.isdigit():
print ch
print "----------------------------------------------"
for ch in st:
if (ch >= "0") and (ch <= "9"):
print ch
print "---------"
for ch in st:
try:
print int(ch)
except:
pass
so how would I get it to print Odd
def isOdd(n):
if firstNum % 2 == 0:
return False
else:
return True
for num in range( 97, 100 ):
is_odd_returned = isOdd(num)
print num, "is",
if is_odd_returned == True: ## or just if is_odd_returned:
print "Odd"
else: ## "False' returned
print "Not odd"
could anyone help me find out the error in my isPrime() function
You get a return on the first pass through the for() loop. A True if the first divide has a remainder, a False if the first divide has no remainder. You want the True after the for() loop, not within it.
def isPrime(n):
if n == 2:
return True
for divisor in range(3, int(math.sqrt(n)), 2):
if n % divisor == 0:
return False
## did not return 'False' during the for() loop so it is prime
return True
And this code will never print "Deficient". I'll let you figure out why.
def checkForPerfect(n):
sum = 0
if n % == 0:
sum +=
if sum == n:
return 'Perfect'
elif sum > n:
return 'Abundant'
else:
return 'Abundant'
else:
return 'Deficient'
but i am interested multi process
This is an example of multiprocessing/pyprocessing running 2 threads and passing variables back and forth via a dictionary.
import time
from multiprocessing import Process, Manager
def test_f(test_d):
""" frist process to run
exit this process when dictionary's 'QUIT' == True
"""
test_d['2'] = 2 ## change to test this
while not test_d["QUIT"]:
print "test_f", test_d["QUIT"]
test_d["ctr"] += 1
time.sleep(1.0)
def test_f2(name):
""" second process to run. Runs until the for loop exits
"""
for j in range(0, 10):
print name, j
time.sleep(0.5)
print "second process finished"
if __name__ == '__main__':
##--- create a dictionary via Manager
manager = Manager()
test_d = manager.dict()
test_d["ctr"] = 0
test_d["QUIT"] = False
##--- start first process and send dictionary
p = Process(target=test_f, args=(test_d,))
p.start()
##--- start second process
p2 = Process(target=test_f2, args=('P2',))
p2.start()
##--- sleep 2 seconds and then change dictionary
## to exit first process
time.sleep(2.0)
print "\nterminate first process"
test_d["QUIT"] = True
print "test_d changed"
print "data from first process", test_d
##--- may not be necessary, but I always terminate to be sure
time.sleep(5.0) ## let 2nd process finish
p.terminate()
p2.terminate()
No one has posted this because it is so obvious, and you probably know about it, but to eliminate the obvious...
class EffectIllusion:
second_variable = "second test variable"
def __init__(self):
self.illusionRace = "***"
def change_variable(self):
self.illusionRace = "test of variable named illusionRace"
class SecondFile:
def __init__(self):
EI = EffectIllusion()
print EI.illusionRace
EI.change_variable()
print EI.illusionRace
print "\n", EffectIllusion.second_variable
SF = SecondFile()
And if you don't know about this, Google for class variable vs. object variable.
Is there some way I can display the 'escape characters'
Escape characters are generally < decimal 32 and > decimal 127 (in English), but you may have to adjust for your character set. This works for me.
# -*- coding: utf-8 -*-
test_file = [ "about, approximately περίπου cinema σινεμά (το)", \
"after μετά cinema σινεμά/κινηματογράφος", \
"afternoon απόγευμα (το) city πόλη (η)" ]
escape_min = 32
escape_max = 127
for rec in test_file:
printed = 0
for num, character in enumerate(rec):
ord_chr = ord(character)
if (ord_chr < escape_min) or (ord_chr > escape_max):
if not printed:
print "\n", rec
printed = 1
print " ", num, ord_chr
I've added some print statements to give a hint about what is being processed
number_of_courses = input ('Number of course to enter... ')
for number_of_courses in range (0, number_of_courses):
major = raw_input('\nEnter class type ') #cmsc, math, etc..
coursenum = input('Enter course number ')
print "input was", major, coursenum
print ("\nA Requirements") #for cmsc
print "comparing", major, coursenum
##------------- my test ---------------------------------------
Number of course to enter... 3
Enter class type csmc
Enter course number 101
input was csmc 101
Enter class type math
Enter course number 201
input was math 201
Enter class type junk
Enter course number 301
input was junk 301
A Requirements
comparing junk 301
there must be an easier way to do this than using a million if statements.
Start with a dictionary to store the requirements, etc. which you can then use to look up classes taken. What is left over is what they have yet to take.
A dictionary with the letter as the key is the straight forward way to do this. Otherwise use a function with a for loop to pass the letter and the string to the function.
import string
letter_dict = {}
for letter in string.ascii_uppercase:
letter_dict[letter] = 0
f = [ "abc def\n",
"ghi abc def\n",
"mno stuvw abc\n" ]
for line in f:
for word in line.strip().split():
letter = word[0].upper()
letter_dict[letter] += 1
for letter in string.ascii_uppercase:
print "letter %s = %d" % (letter, letter_dict[letter])
That's fine if you have a nice increment like 0.1, otherwise note that a for loop is just a special case of a while loop.
r = 0.0
while r < 6.4:
print r
r += 0.1
print
##
## and if you have an unusual series of numbers, use a list
iterate_list = [0.0, 0.2, 0.3, 0.5, 0.6]
for r in iterate_list:
print r
Just remove the spaces between the classes not between CMSC 201
Since these are all in the handy form of abbreviation-space-number, you can just split and combine them in pairs of two. I would suggest a for loop with a step of two to iterate through the resulting list, and combine this element and the next element.
Some ideas. First, tkinter does not display all image types. I do not think that it will display a JPG but am not sure. Convert some pictures to a gif and see it that works. Second, "file" is a reserved word and so should not be a variable name, Third, you are not iterating through the entire list of files because of the delete in the for loop. Append the names you want to keep to a second list. Also, you don't have to create a list of n elements, just append as you go along (see below). Finally, if you don't know about effbot, it is a good reference. http://effbot.org/tkinterbook/label.htm
label_list = []
for k, fname in enumerate(files):
image = Image.open(filedir+"/"+fname)
##((width, height))
image.thumbnail((160, 240))
photo = ImageTk.PhotoImage(image)
this_label = Label(root, image=photo)
this_label.pack() # pack when you want to display it
label_list.append( this_label )
picSet.mainloop()
Your problem is here
for n in range(num_iterations):
print "n before =", n
n = B*10
print "n after =", n
You use "n" twice and are always multiplying the same number, "B". Something like this should give you the idea of how to go about it. Also, I've introduced divmod which is just another way to get the whole integer and the remainder (not decimal). Your main problem is that you haven't tried including print statements to see what is happening, so can not tell that you are getting the remainder as an integer and not as a float/decimal.
def rationalnum(n, d, num_iterations):
whole, remain = divmod(n, d)
print "divmod =", whole, remain
print "% =", n%d, n, d
## convert to decimal
dec = float(remain) / d
print "dec =", dec
##--- you could also use this to convert
number = float(n) / d
number_int = int(number)
number_decimal = number - number_int
for n in range(num_iterations):
dec *= 10
print dec
print "\nthe decimal multiplied %d times = %d\n" % \
(num_iterations, int(dec))
def main():
num = input('Please Enter a numerator to the rational number: ')
denom = input('Please Enter a denominator to the rational number: ')
num_iterations = input('Please Enter a number of decimal places to show: ')
rationalnum(num, denom, num_iterations)
main()
Finally, there is no reason to have the main() function, with one orphaned statement that calls it, unless you want to call it from another program, in which case it should be named …
Use a dictionary to store the class instances.
class ClassTest :
def __init__ (self, desc2="***") :
self.field1 = "*"
self.field2 = 0
self.field3 = desc2
def chg_field1(self, value):
self.field1 = value
#==========================================================================
class_dict = {}
class_dict[1]=ClassTest("First Class")
class_dict[2]=ClassTest()
for key in class_dict:
print "%d %15s, %3d, %s" % (key, class_dict[key].field1, \
class_dict[key].field2, class_dict[key].field3)
print
class_dict[2].field2=99
class_dict[1].chg_field1("Field 1 changed")
for key in class_dict:
print "%d %15s, %3d, %s" % (key, class_dict[key].field1, \
class_dict[key].field2, class_dict[key].field3)