[Tutor] how to delete some quasi-duplicated keys
pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str(k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: Which one do you want to keep? If the order ('66', '69') is unimportant, you should use a frozenset instead of a tuple. In your code, where you set the pairs in the first place, instead of doing: pair = ('66', '69') # however you build the pair pairs[pair] = value (or how ever you set the initial values), change it to this: pair = frozenset(('66', '69')) pairs[pair] = pairs.get(pair, 0) + value -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On 2011/11/25 10:41 AM, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str(k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to in pairs.keys() is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print Key ('%s', '%s') already accumulated) % key Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On Fri, Nov 25, 2011 at 5:05 PM, Christian Witts cwi...@compuscan.co.za wrote: On 2011/11/25 10:41 AM, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str( k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to in pairs.keys() is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') $ python3 dehydron_data_stastic.py | sort -nr Traceback (most recent call last): File dehydron_data_stastic.py, line 44, in module for k in pairs.iterkeys(): AttributeError: 'dict' object has no attribute 'iterkeys' if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print Key ('%s', '%s') already accumulated) % key Hope that helps. -- Christian Witts Python Developer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Do loop in Python
Hi there, I am a new python user. I have a question regarding do loop. This is a simple program that I have written: - N=10 h=10.0 # [micrometer] z=-200.0 # [micrometer] num = 0.05 #m**2/s dz = 1.0 nuh=[] tmax=3600 dt=20. nu=[]height = arange(z*dz,0,dz) outfile=open('nu.dat','w') outfile.write('height, nu, nuh') for z,when in enumerate(height): for h in range(10): for N in range(10): for z in range((N-z)+(N-h)): nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) --- What I like to do with this program is do loop like the fortran version of as follows: do i = 2, N z(i) = z(i-1) +h(i-1) end do write(0,*) 'z ', z(1:N) write(0,*) 'when ', 'nu ','Conc ' do i= 1, N nuh(i)= 0.01d0*exp(-0.005d2*(z(i)+200)) ! turbulence diffusivity m**2/s nu(i)= num(1) + nuh(i) end do -- My problem is I am notable have the curve in the output plot as I have as a result of FORTRAN program. What happens is just having a straight line! the whole problem is in z part, which is supposed to be changed and i do not see it! So, would it be possible to take a look at it please. any suggestion would greatly appreciated. Thank you, Sue ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On 2011/11/25 11:15 AM, lina wrote: On Fri, Nov 25, 2011 at 5:05 PM, Christian Wittscwi...@compuscan.co.za wrote: On 2011/11/25 10:41 AM, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str( k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to in pairs.keys() is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') $ python3 dehydron_data_stastic.py | sort -nr Traceback (most recent call last): File dehydron_data_stastic.py, line 44, inmodule for k in pairs.iterkeys(): AttributeError: 'dict' object has no attribute 'iterkeys' if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print Key ('%s', '%s') already accumulated) % key Hope that helps. -- Christian Witts Python Developer Ah, should have mentioned .iterkeys() / .itervalues() are in Python 2.x and .keys() and .values() have been changed in Py3 to match .iter* from Py2.x. Just change that line to `for key in pairs.keys():` then. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On Fri, Nov 25, 2011 at 5:06 PM, Steven D'Aprano st...@pearwood.info wrote: lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: Which one do you want to keep? It does not matter, the order is not important, If the order ('66', '69') is unimportant, you should use a frozenset instead of a tuple. In your code, where you set the pairs in the first place, instead of doing: pair = ('66', '69') # however you build the pair pairs[pair] = value (or how ever you set the initial values), change it to this: pair = frozenset(('66', '69')) pairs[pair] = pairs.get(pair, 0) + value I don't get this pairs.get part. pairs[pair]=pairs.get(pair,0)+parts[2] TypeError: unsupported operand type(s) for +: 'int' and 'str' or line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 pair=frozenset(('parts[0]','parts[1]')) pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 I upload the file in: https://docs.google.com/open?id=0B93SVRfpVVg3NTg5YTkwMGUtMzdiNi00ZGI2LWE5ZGYtMTFmMTc0OTZhMzZl https://docs.google.com/open?id=0B93SVRfpVVg3NGQwZDRhNDMtMDUzZi00NDIxLWE2MDAtZGM0ZWEzZDczYTMz -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On Fri, Nov 25, 2011 at 5:19 PM, Christian Witts cwi...@compuscan.co.za wrote: On 2011/11/25 11:15 AM, lina wrote: On Fri, Nov 25, 2011 at 5:05 PM, Christian Witts cwi...@compuscan.co.za wrote: On 2011/11/25 10:41 AM, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str( k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to in pairs.keys() is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') $ python3 dehydron_data_stastic.py | sort -nr Traceback (most recent call last): File dehydron_data_stastic.py, line 44, in module for k in pairs.iterkeys(): AttributeError: 'dict' object has no attribute 'iterkeys' if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print Key ('%s', '%s') already accumulated) % key Hope that helps. -- Christian Witts Python Developer Ah, should have mentioned .iterkeys() / .itervalues() are in Python 2.x and .keys() and .values() have been changed in Py3 to match .iter* from Py2.x. Just change that line to `for key in pairs.keys():` then. for key in pairs.keys(): if key[::-1] in pairs: pairs[key] += pairs[key[::-1]] del pairs[key[::-1]] print(pairs) Traceback (most recent call last): File dehydron_data_stastic.py, line 47, in module for key in pairs.keys(): RuntimeError: dictionary changed size during iteration -- Christian Witts Python Developer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
#!/usr/bin/python3 dehydrons={} pairs={} #frozen set way pairs fs_pairs={} occurence={} total=0 dictionary={} candidate_dehydron={} if __name__==__main__: with open(dehydron_refined_data_18.txt,r) as f: for line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 #pair=frozenset(('parts[0]','parts[1]')) #pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 #for k, v in dehydrons.items(): #print(k,v) for k, v in occurence.items(): if v=25: #print(v,k) candidate_dehydron[k]=v #print({:.2f}.format(v/2768*100),k) total+=v print(total) for k, v in candidate_dehydron.items(): pairs[k] = v '''for key in pairs.keys(): if key[::-1] in pairs: pairs[key] += pairs[key[::-1]] del pairs[key[::-1]] print(pairs)''' #for k, v in pairs.items(): #print(v,k) I attached the not working code, Thanks for any advice, best regards, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Do loop in Python
Sue, I'm not familiar with FORTRAN, and since I'm not completely sure what you're trying to accomplish please take this simply as an 'educated guess'. My guess is that you're not getting the curve because Z is only defined to one decimal location (1/10th) precision and probably needs higher precision (and is likely getting it) in the FORTRAN version. http://docs.python.org/tutorial/floatingpoint.html this should help Charles Sent from my iPhone On Nov 25, 2011, at 2:16 AM, stm atoc stm.at...@googlemail.com wrote: Hi there, I am a new python user. I have a question regarding do loop. This is a simple program that I have written: - N=10 h=10.0 # [micrometer] z=-200.0 # [micrometer] num = 0.05 #m**2/s dz = 1.0 nuh=[] tmax=3600 dt=20. nu=[]height = arange(z*dz,0,dz) outfile=open('nu.dat','w') outfile.write('height, nu, nuh') for z,when in enumerate(height): for h in range(10): for N in range(10): for z in range((N-z)+(N-h)): nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) --- What I like to do with this program is do loop like the fortran version of as follows: do i = 2, N z(i) = z(i-1) +h(i-1) end do write(0,*) 'z ', z(1:N) write(0,*) 'when ', 'nu ','Conc ' do i= 1, N nuh(i)= 0.01d0*exp(-0.005d2*(z(i)+200)) ! turbulence diffusivity m**2/s nu(i)= num(1) + nuh(i) end do -- My problem is I am notable have the curve in the output plot as I have as a result of FORTRAN program. What happens is just having a straight line! the whole problem is in z part, which is supposed to be changed and i do not see it! So, would it be possible to take a look at it please. any suggestion would greatly appreciated. Thank you, Sue ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
for key, value in pairs.items(): if key[::-1] in pairs.keys() and pairs[key] != 0: pairs[key] += pairs[key[::-1]] pairs[key[::-1]]=0 for k, v in pairs.items(): if v != 0: print(v,k) Now very trivial, but works. On Fri, Nov 25, 2011 at 5:34 PM, lina lina.lastn...@gmail.com wrote: #!/usr/bin/python3 dehydrons={} pairs={} #frozen set way pairs fs_pairs={} occurence={} total=0 dictionary={} candidate_dehydron={} if __name__==__main__: with open(dehydron_refined_data_18.txt,r) as f: for line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 #pair=frozenset(('parts[0]','parts[1]')) #pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 #for k, v in dehydrons.items(): #print(k,v) for k, v in occurence.items(): if v=25: #print(v,k) candidate_dehydron[k]=v #print({:.2f}.format(v/2768*100),k) total+=v print(total) for k, v in candidate_dehydron.items(): pairs[k] = v '''for key in pairs.keys(): if key[::-1] in pairs: pairs[key] += pairs[key[::-1]] del pairs[key[::-1]] print(pairs)''' #for k, v in pairs.items(): #print(v,k) I attached the not working code, Thanks for any advice, best regards, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Do loop in Python
regarding to the last email: what I am trying to do is seeing the variation of 'nu' over (changes of) 'z'. My concern is how to arrange this! Basically, I am not able to define the variation of nu by z ( 1 to 200). I am looking for a statement to show the changes of 'nu' for each step of z (as height). On the other hand, for each step, 'h' is supposed to be subtracted from 'z' (like: 200-10, 190-10...) as well, at least 10 times (which was trying to be defined as N)! I hope this is somehow clear Thanks in advance, Sue - Show quoted text - On Fri, Nov 25, 2011 at 10:16 AM, stm atoc stm.at...@googlemail.com wrote: Hi there, I am a new python user. I have a question regarding do loop. This is a simple program that I have written: - N=10 h=10.0 # [micrometer] z=-200.0 # [micrometer] num = 0.05 #m**2/s dz = 1.0 nuh=[] tmax=3600 dt=20. nu=[]height = arange(z*dz,0,dz) outfile=open('nu.dat','w') outfile.write('height, nu, nuh') for z,when in enumerate(height): for h in range(10): for N in range(10): for z in range((N-z)+(N-h)): nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) --- What I like to do with this program is do loop like the fortran version of as follows: do i = 2, N z(i) = z(i-1) +h(i-1) end do write(0,*) 'z ', z(1:N) write(0,*) 'when ', 'nu ','Conc ' do i= 1, N nuh(i)= 0.01d0*exp(-0.005d2*(z(i)+200)) ! turbulence diffusivity m**2/s nu(i)= num(1) + nuh(i) end do -- My problem is I am notable have the curve in the output plot as I have as a result of FORTRAN program. What happens is just having a straight line! the whole problem is in z part, which is supposed to be changed and i do not see it! So, would it be possible to take a look at it please. any suggestion would greatly appreciated. Thank you, Sue ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
lina wrote: On Fri, Nov 25, 2011 at 5:06 PM, Steven D'Aprano st...@pearwood.info wrote: pair = frozenset(('66', '69')) pairs[pair] = pairs.get(pair, 0) + value I don't get this pairs.get part. The get method does a look-up on a dict, but instead of failing if the key is missing, it returns a default value: py d = {'a': 2} py d['b'] # fails Traceback (most recent call last): File stdin, line 1, in module KeyError: 'b' py d.get('b', 3) # use 3 as the default 3 pairs[pair]=pairs.get(pair,0)+parts[2] TypeError: unsupported operand type(s) for +: 'int' and 'str' Lina, in your original example, the values of the dict are integers: {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} The error you show above can only happen if they are not integers, but strings. When you show us examples, please get the examples right. If you give us wrong information, how do you expect us to help? You should convert all the strings into ints. or line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 pair=frozenset(('parts[0]','parts[1]')) pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 f = open(some file) dehydrons = {} occurrence = {} pairs = {} for line in f.readlines(): parts = line.split() # convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) # order doesn't matter if pair in dehydrons: occurrence[pair] += 1 else: dehydrons[pair] = parts[2] occurrence[pair] = 1 pairs[pair] = pairs.get(pair, 0) + parts[2] f.close() -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Do loop in Python
stm atoc wrote: Hi there, I am a new python user. I have a question regarding do loop. This is a simple program that I have written: - N=10 h=10.0 # [micrometer] z=-200.0 # [micrometer] You define N, h and z here, but later on you use them as loop variables. So these three values never get used: they are thrown away, and replaced by the values of the loops: h - 0, 1, 2, ... 9 N - 0, 1, 2, ... 9 z is especially troublesome, because it gets used for TWO loop variables, one inside the other. The inner z loop depends on the outer z loop, which makes it tricky to predict what values z will take. num = 0.05 #m**2/s dz = 1.0 nuh=[] tmax=3600 dt=20. nu=[]height = arange(z*dz,0,dz) What is arange? In physics, height is a scalar. But later on, you seen to use height as if it were a collection of values. outfile=open('nu.dat','w') outfile.write('height, nu, nuh') for z,when in enumerate(height): for h in range(10): for N in range(10): for z in range((N-z)+(N-h)): nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) --- What I like to do with this program is do loop like the fortran version of as follows: do i = 2, N z(i) = z(i-1) +h(i-1) end do How is z initialised? What is h? I *think* you are trying to add a small increment to each value, based on the previous value. Am I close? Does this example help? zvalues = [1] # starting value increments = [0.01, 0.01, 0.02, 0.01, 0.01, 0.02, 0.01, 0.01] for h in increments: z = zvalues[-1] + h zvalues.append(z) print(zvalues) (Note: beware of floating point rounding.) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Weird Try..Except Error
Hi All, Please look at the snippet below. When I am running my module its giving me following error. Using : Python 2.7, windows Env. {{{ # User defined modules try: from scripts import precheck from scripts import input from scripts import validate from scripts import logsetup from scripts.constants import * except ImportError, err_msg: == line 38 print(ERROR {0}.format(err_msg)) print(INFO Please verify the presence of above module, and restart the installation) sys.exit(1) }}} {{{ Output: C:\ install.py -f input.xml File C:\install.py, line 38 except ImportError, err_msg: ^ SyntaxError: invalid syntax }}} I checked the comma and spacing and didn't find any problem. Any idea.? Thanks Nikunj ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Weird Try..Except Error
nikunj.badja...@emc.com wrote: Please look at the snippet below. When I am running my module its giving me following error. Using : Python 2.7, windows Env. {{{ # User defined modules try: from scripts import precheck from scripts import input from scripts import validate from scripts import logsetup from scripts.constants import * except ImportError, err_msg: == line 38 print(ERROR {0}.format(err_msg)) print(INFO Please verify the presence of above module, and restart the installation) sys.exit(1) }}} {{{ Output: C:\ install.py -f input.xml File C:\install.py, line 38 except ImportError, err_msg: ^ SyntaxError: invalid syntax }}} I checked the comma and spacing and didn't find any problem. Any idea.? You are likely mistaken about the Python version you are using. The above error will be triggered by Python 3.x which expects try: ... except ImportError as err_msg: ... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On 25/11/11 08:41, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): I don;t think this does what you think it does. k is a key from pairs which looks like ('66', '69') You convert that to a string (with str(k)) which yields : ('66', '69') You then add the first two characters of that string. Those are ( and ' so you get a value of (' and ask whether that appeats in pairs.keys() which it will not because the keys are tuples. So the if block never happens print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str(k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) And you print the original value followed by the tuple key. I'm pretty sure thats not what you want. Maybe you are trying to add the two elements of the tuple? But even that won't disambiguate between (66,69) and (69,66) You would need to sort the tuples first so that both would render 66,69. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano st...@pearwood.info wrote: lina wrote: On Fri, Nov 25, 2011 at 5:06 PM, Steven D'Aprano st...@pearwood.info wrote: pair = frozenset(('66', '69')) pairs[pair] = pairs.get(pair, 0) + value I don't get this pairs.get part. The get method does a look-up on a dict, but instead of failing if the key is missing, it returns a default value: py d = {'a': 2} py d['b'] # fails Traceback (most recent call last): File stdin, line 1, in module KeyError: 'b' py d.get('b', 3) # use 3 as the default 3 pairs[pair]=pairs.get(pair,0)+parts[2] TypeError: unsupported operand type(s) for +: 'int' and 'str' Lina, in your original example, the values of the dict are integers: Ha ... it's me. {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} The error you show above can only happen if they are not integers, but strings. When you show us examples, please get the examples right. If you give us wrong information, how do you expect us to help? Sorry, I was confused at that time. You should convert all the strings into ints. or line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 pair=frozenset(('parts[0]','parts[1]')) pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 f = open(some file) dehydrons = {} occurrence = {} pairs = {} for line in f.readlines(): parts = line.split() # convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) # order doesn't matter if pair in dehydrons: occurrence[pair] += 1 else: dehydrons[pair] = parts[2] occurrence[pair] = 1 pairs[pair] = pairs.get(pair, 0) + parts[2] f.close() for line in f.readlines(): parts = line.split() #pair=set((parts[0],parts[1])) #convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) print(pair) if pair in dehydrons: occurence[pair] += 1 else: dehydrons[pair] = parts[2] pairs[pair] = pairs.get(pair,0) + parts[2] print(pairs) $ python3 dehydron_data_frozenset_version.py frozenset({2, 15}) frozenset({2, 15}) Traceback (most recent call last): File dehydron_data_frozenset_version.py, line 35, in module occurence[pair] += 1 KeyError: frozenset({2, 15}) Thanks, -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Weird Try..Except Error
Hi All, Thanks for the info. I had Python27 and Python32 both installed togethar. In Windows the PATH env variable, I had set Python27 exe and lib path. But When I do C:\ Python [PressEnter] I get 2.7 But when I run C:\ script.py [PressEnter] The script is running with Python3.2 , thts weird because I have set my Path variable with Pytho27 exe and lib. Which was causing the problem. Thanks Nikunj -Original Message- From: tutor-bounces+nikunj.badjatya=emc@python.org [mailto:tutor-bounces+nikunj.badjatya=emc@python.org] On Behalf Of Peter Otten Sent: Friday, November 25, 2011 5:28 PM To: tutor@python.org Subject: Re: [Tutor] Weird Try..Except Error nikunj.badja...@emc.com wrote: Please look at the snippet below. When I am running my module its giving me following error. Using : Python 2.7, windows Env. {{{ # User defined modules try: from scripts import precheck from scripts import input from scripts import validate from scripts import logsetup from scripts.constants import * except ImportError, err_msg: == line 38 print(ERROR {0}.format(err_msg)) print(INFO Please verify the presence of above module, and restart the installation) sys.exit(1) }}} {{{ Output: C:\ install.py -f input.xml File C:\install.py, line 38 except ImportError, err_msg: ^ SyntaxError: invalid syntax }}} I checked the comma and spacing and didn't find any problem. Any idea.? You are likely mistaken about the Python version you are using. The above error will be triggered by Python 3.x which expects try: ... except ImportError as err_msg: ... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] sensing EOF in Python 3.1
From: Steven D'Aprano st...@pearwood.info wrote: Pickle does standard file I/O in the same way that opening a JPEG in an image view does standard file I/O: both programs read data from a file the standard, ordinary way, but expect data of a certain format. If you provide it too little data, you will get an EOF error. If you provide too much data, or messed up data, then you will some other error. But the file I/O is exactly the same. It's just that pickle, or your image viewer, handle it for you. Right, thanks. Pickling won't tell you anything about Python data structures. Pickling takes Python data structures, bashes them with a hammer until they stop wiggling, then runs them through a serialiser turning them into a stream of text or binary codes. I want to include this info in my presentation because it shows how data structures can be externalized. Pickles tell you only about pickles. You won't learn anything about (say) dicts by looking at a pickled dict except the bare fact that dicts can be pickled. Still though, that is important. import pickle # import the pickle module Really? Wow! I thought import pickle meant sort the database!!! *wink* Sarcasm aside, what else could import pickle mean other than import the pickle module? I was trying to put a comment on every line because the audience who will be looking at this will have never seen any Python before. The comment adds absolutely nothing to the code. At best it is superfluous. At worst it is harmful, because code and comments have a regrettable tendency to get out of sync. I know what you mean. The commens could be meaningful at first, then the code gets edited over the years and the comments don't get updated. I've seen that many times. Every comment should carry its weight. If the code is particularly convoluted, you might write comments explaining *how* you do something, but generally the code speaks for itself regarding the how, so comments should explain *why* you do something. If a comment doesn't tell you something that the code doesn't, that you need to know (or at least should know). Otherwise it should be throw out into the back alley for the stray cats to eat. Again, in this specific instance, this simple example code is intended to be looked at not by Python programmers, or even programmers, but rather by database professionals who I am attempting to expose Python to for the first time. pickle_file = open(d:/Work/pickle_file, rb) # open the pickled file read_list = pickle.load(pickle_file) # read the first pickled row And this is what I'm talking about. It does NOT read the first pickled row. Pickles don't have rows. In this case, you are reading the first and only pickled object, which happens to be a dict. You are of course, correct, thanks. I'll be fixing that. Steven thanks for your comments about comments, I'll be doing them over for sure. -- Frank L. Cranky Frankie Palmeri ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Do loop in Python
Thank you so much for your reply. It was very helpful information and I used it in order to improve the program Here is the new version of the program: zvalues = [-200] # starting value hvalues = [10] # starting value increments = [1, 1, 1, 1, 1, 1, 1, 1] for N in increments: h = hvalues[-1] - N hvalues.append(h) z = zvalues[-1] + h zvalues.append(z) height = arange((z)*dz,0,dz) for z,when in enumerate(height): nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) The story is like this: I should define layers and thickness and see how the diffusion profile changes over the z. height (or depth) of the total thickness or 'z'. I basically, define 'z' in 10 layers and each layer is called ' N' . Difference between each layer is 'h', which is equal 10 micrometer. Now, what I like to do is the modification of nu based on each zvalue In fact, for each 'zvalue' o'z' step, I need to calculate a different value for 'nu' based on the available equation in the program. BUT, I am not sure, exactly, how to add the new do loop of z inside another loop of nu. I have done this way as well (the other way around): height = arange((z)*dz,0,dz) for z,when in enumerate(height): for N in increments: h = hvalues[-1] - N hvalues.append(h) z = zvalues[-1] + h zvalues.append(z) nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) but still no sign of 'nu changes' over 'z'! So, would it be possible to check that again? Thanks, Sue On Fri, Nov 25, 2011 at 12:36 PM, Steven D'Aprano st...@pearwood.info wrote: stm atoc wrote: Hi there, I am a new python user. I have a question regarding do loop. This is a simple program that I have written: - N=10 h=10.0 # [micrometer] z=-200.0 # [micrometer] You define N, h and z here, but later on you use them as loop variables. So these three values never get used: they are thrown away, and replaced by the values of the loops: h - 0, 1, 2, ... 9 N - 0, 1, 2, ... 9 z is especially troublesome, because it gets used for TWO loop variables, one inside the other. The inner z loop depends on the outer z loop, which makes it tricky to predict what values z will take. num = 0.05 #m**2/s dz = 1.0 nuh=[] tmax=3600 dt=20. nu=[]height = arange(z*dz,0,dz) What is arange? In physics, height is a scalar. But later on, you seen to use height as if it were a collection of values. outfile=open('nu.dat','w') outfile.write('height, nu, nuh') for z,when in enumerate(height): for h in range(10): for N in range(10): for z in range((N-z)+(N-h)): nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) --- What I like to do with this program is do loop like the fortran version of as follows: do i = 2, N z(i) = z(i-1) +h(i-1) end do How is z initialised? What is h? I *think* you are trying to add a small increment to each value, based on the previous value. Am I close? Does this example help? zvalues = [1] # starting value increments = [0.01, 0.01, 0.02, 0.01, 0.01, 0.02, 0.01, 0.01] for h in increments: z = zvalues[-1] + h zvalues.append(z) print(zvalues) (Note: beware of floating point rounding.) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Weird Try..Except Error
On 25-Nov-11 04:42, nikunj.badja...@emc.com wrote: Hi All, Thanks for the info. I had Python27 and Python32 both installed togethar. In Windows the PATH env variable, I had set Python27 exe and lib path. But When I do C:\ Python [PressEnter] I get 2.7 But when I run C:\ script.py [PressEnter] The script is running with Python3.2 , thts weird because I have set my Path variable with Pytho27 exe and lib. Which was causing the problem. The problem is likely that when you installed Python 3.2, Windows associated the .py extension with the new 3.2 interpreter, PATH notwithstanding. steve -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On 2011-11-25 13:40, lina wrote: On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Apranost...@pearwood.info wrote: f = open(some file) dehydrons = {} occurrence = {} pairs = {} for line in f.readlines(): parts = line.split() # convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) # order doesn't matter if pair in dehydrons: occurrence[pair] += 1 else: dehydrons[pair] = parts[2] occurrence[pair] = 1 pairs[pair] = pairs.get(pair, 0) + parts[2] f.close() for line in f.readlines(): parts = line.split() #pair=set((parts[0],parts[1])) #convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) print(pair) if pair in dehydrons: occurence[pair] += 1 else: dehydrons[pair] = parts[2] pairs[pair] = pairs.get(pair,0) + parts[2] print(pairs) $ python3 dehydron_data_frozenset_version.py frozenset({2, 15}) frozenset({2, 15}) Traceback (most recent call last): File dehydron_data_frozenset_version.py, line 35, inmodule occurence[pair] += 1 KeyError: frozenset({2, 15}) You want to add one to occurence[frozenset({2, 15})] but there is no such key in occurence yet. If you carefully re-read Steven's code snippet you will see that you missed the line occurence[pair] = 1 in the else-branch. Therefore occurence[frozenset({2, 15})] wasn't set in the first iteration and you get the error in the second. You can see that you are already in the second iteration by looking at the output of your program before the error message. Bye, Andreas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code.
from functools import partial I use this kind of explicit import for a few names that I use frequently, namely defaultdict, contextmanager, everything from itertools... I think of these as my personal extended set of builtins ;) As to the actual partial() function, you probably don't see it a lot because it has been in the standard library for only three years. The older idiom for making a function that calls another function with a fixed argument is command = lambda button=button: button_clicked(button) Alright! What is a fixed argument? You can iterate over (row, column) pairs instead of the dummy _ variable: def create_widgets(self): for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: button = tk.Button(self) command = partial(button_clicked, button) button[command] = command button.grid(row=row, column=column) command() Very nice! I didn't know that it was possible. This saves me a lot of space. Am I, as a beginner, supposed to know this? Say that when button one is pressed I want a text file to be created. The text in the file should be the same number as the button I pressed. So if I press button one, once, it should create a text file with the name button_1. The text in the file should also be button_1. If the button is pressed again, it should remove the file. Is this possible to do without any trouble? So if the second button is pressed , it should create a text file with the name button_2 and the text in it should be button_2. If the button is pressed once again, it is supposed to delete that file it created. I don't know if it works with this piece of code you posted earlier: def create_widgets(self): for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: button = tk.Button(self) command = partial(button_clicked, button) button[command] = command button.grid(row=row, Otherwise it might work with the code below this comment? def button_clicked(button): if button[bg] == green: button.configure(bg=red, text=Hi 2) else: button.configure(bg=green, text=Hi 1) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for _ in range(2): button = tk.Button(self) command = partial(button_clicked, button) button[command] = command button.grid() command() I also have one last question. How do I make the first button that is created to be named 1, the second to be created 2, the third 3 and so on? Also, assume that I have a already have a window with a button in it. If you press this button, this window is supposed to open. So, if I press the button, will this window open? Because I created the previous window using from tkinter import* and not import tkinter as tk. You can make the decision what style you want to use on a per-module basis. In that module you can then access (for example) a tkinter button with either tkinter.Button, tk.Button or just Button. You can even mix styles if you put the respective imports at the beginning of the module (not recommended). What approach you take has no consequences on the execution of the program. I didn't know that, thanks. It is strange that this wasn't mentioned in my book. Why is it not recommended to to mix the styles if you put the respective imports at the beginning of the module? Thanks again for your help and insightful suggestions. It is really appreciated :) Mic ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code.
Mic wrote: from functools import partial I use this kind of explicit import for a few names that I use frequently, namely defaultdict, contextmanager, everything from itertools... I think of these as my personal extended set of builtins ;) As to the actual partial() function, you probably don't see it a lot because it has been in the standard library for only three years. The older idiom for making a function that calls another function with a fixed argument is command = lambda button=button: button_clicked(button) Alright! What is a fixed argument? Suppose you have a function add() that calculates the sum of two values def add(a, b): ... return a + b ... add(1, 2) 3 If you want another function that takes one argument and adds 2 to that argument you can either start from scratch def plus_two(b): ... return 2 + b ... plus_two(7) 9 or build on your earlier work from functools import partial plus_two = partial(add, 2) plus_two(3) 5 The effect of wrapping add into partial here is that every time you call plus_two(x) it will in turn call add(2, x). As the first argument is always the same I called it fixed, but it's not a terminus technicus. You can iterate over (row, column) pairs instead of the dummy _ variable: def create_widgets(self): for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: button = tk.Button(self) command = partial(button_clicked, button) button[command] = command button.grid(row=row, column=column) command() Very nice! I didn't know that it was possible. This saves me a lot of space. Am I, as a beginner, supposed to know this? You may read it up somewhere or be shown on a mailinglist ;) Say that when button one is pressed I want a text file to be created. The text in the file should be the same number as the button I pressed. So if I press button one, once, it should create a text file with the name button_1. The text in the file should also be button_1. If the button is pressed again, it should remove the file. Is this possible to do without any trouble? So if the second button is pressed , it should create a text file with the name button_2 and the text in it should be button_2. If the button is pressed once again, it is supposed to delete that file it created. I also have one last question. How do I make the first button that is created to be named 1, the second to be created 2, the third 3 and so on? Here's a modified script: import tkinter as tk from functools import partial def button_clicked(button): if button[bg] == green: button[bg] = red print(deleting file, button.filename) else: button[bg] = green print(creating file, button.filename) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = tk.Button(self, text=Button {}.format(index+1), bg=red) button.filename = button{}.txt.format(index+1) command = partial(button_clicked, button) button[command] = command row, column = divmod(index, 4) button.grid(row=row, column=column) root = tk.Tk() root.title(Test) app = Window(root) root.mainloop() I hope you can infer answers to your questions from the above... To be honest, we've reached the point where I would switch to a tkinter.Button subclass: import tkinter as tk FREE = green OCCUPIED = red class SeatButton(tk.Button): def __init__(self, master, index): text = Button {}.format(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = button{}.txt.format(index+1) self.occupied = False def clicked(self): self.occupied = not self.occupied if self.occupied: self[bg] = OCCUPIED print(creating file, self.filename) else: self[bg] = FREE print(deleting file, self.filename) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root = tk.Tk() root.title(Test) app = Window(root) root.mainloop() Too bad that now you've understood what partial() does it's gone... Why is it not recommended to to mix the styles if you put the respective imports at the beginning of the module? Consistency. Either call the button tk.Button or Button. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Weird Try..Except Error
On 25/11/11 12:42, nikunj.badja...@emc.com wrote: I had Python27 and Python32 both installed togethar. In Windows the PATH env variable, I had set Python27 exe and lib path. But When I do C:\ Python [PressEnter] I get 2.7 But when I run C:\ script.py [PressEnter] The script is running with Python3.2 , thts weird because I have set my Path variable with Pytho27 exe This is one of the annoying ambiguities of Windows. The way it finds the executable for executables(exe, bat cmd etc) is different to how it finds the executable for associations. In the former case it uses PATH, in the latter it relies on the file association set in the file properties. When you install a new Python it tends to set itself as the default interpreter for .py files. Annoying, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code of a finsihed program.
Its usually better to paste long programs into a pastebin web site and give us a link. This saves cluttering up people mail with long messages, and also the pastebin rendering will usually be easier to read with syntax coloring etc. Alright. Sorry if I should know this, but what is a pastebin web site and how do I paste my program into a pastebin web site? While its perfectly legal Python to create a class inside a method its very unusual in practice and very restricting in the use of the class. Its nearly always better to declare all your classes at the top level of the program. Why is it restricting? Because you post lost all the formatting, I'm not sure where this code is supposed to sit... This is again where a pastebin would help. Oh, now I understand why I shouldn't post like this. My apologize, won't happen again. And this is repeating all the bad habits from your original posts. If you adopt the ChairButton class approach all of this becomes much clearer and simpler. I got a really good tip earlier on in the thread how I could make my program dramatically shorter. I have tried to implement a couple of things I need into that piece of code, but I cannot get it to work. So I figured I could post it here (short code) and ask you a couple of questions regarding the code: import tkinter as tk from functools import partial def button_clicked(button): if button[bg] == green: button.configure(bg=red, text=01) else: button.configure(bg=green, text=01) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): list_chair=[(0, 0), (0, 1), (0, 3), (0, 4), (1,0)] for row, column in list_chair: button = tk.Button(self) command = partial(button_clicked, button) button[command] = command button.grid(row=row, column=column) command() root = tk.Tk() root.title(Test) root.geometry(200x200) app = Window(root) root.mainloop() Questions: --I want the first button to be created to have the text 1. The second should have the text 2. The third the text 3 and so on. --When the first button is pressed I want a file to be created with the name Germany_France_1. The text in the file should be Germany_France_1. If/When the button is pressed again it should delete the file. When the second button is pressed I want a file to be created with the name Germany_France_2. The text in the file should be Germany_France_2. If/When the button is pressed again it should delete the file. When the third button is pressed I want a file to be created with the name Germany_France_3. The text in the file should be Germany_France_3. If/When the button is pressed again it should delete the file. Do you have any idea on how I can accomplish this? I reached the conclusion that it should be easy to do so since it was so easy to create so many buttons in so little amount of code. However, to my dismay, I have tried this entire evening without success. It feels like I am so close to shorten my program from 2k+ lines of code to maybe 250 at most, but still so far away. You should only ever have one Tk() object in a Tkinter program. Why is that? And again you should only have one mainloop running, otherwise things would get very confusing with events winding up in the wrong windows event queue etc. Alright, my teacher never mentioned that when he examined my program. Thanks for your input! Your help is as always appreciated and my apologize for making confusing posts! Mic ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code.
On 25/11/11 17:11, Mic wrote: for making a function that calls another function with a fixed argument is command = lambda button=button: button_clicked(button) Alright! What is a fixed argument? Its onre that is the same every time the function is called. The lambda construct above is equivalent to the following which may make it clearer: def button_clicked(aButton): # do something with aButton here # that uses a lot of code and # we want to reuse for any button Now we want to use that function as an event handler, but the function passed as the command in tkinter is not allowed to take an argument. So we create a very short function that takes no arguments but calls button_clicked with a fixed argument. And we do this for two buttons so that they can both use the button_clicked def button1_clicked(): button_clicked(buttonOne) def button2_clicked(): button_clicked(buttonTwo) and we can use these whehn creating our buttons: buttonOne = Button(parent, command=button1_clicked, ) buttonTwo = Button(parent, command=button2_clicked, ) Now a shorter way of doing that, which avoids writing lots of these very small functions is to use lambda, which is an operator that returns a function as a value. Thus def add2(x): return x+2 can be written add2 = lambda x: x+2 And if we don't really care about the name - which is true for the button commands we can put lambda directly into the widget creation: buttonOne = Button(parent, command=lambda b=buttonOne: button_clicked(b), ) buttonTwo = Button(parent, command=lambda b=buttonTwo: button_clicked(b), ) Note that this works because the lambda defines a default argument for the command. Thus Tkinter can call the function with no arguments and Python will insert the default value at runtime. HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Do loop in Python
On 2011-11-25 14:46, stm atoc wrote: Here is the new version of the program: zvalues = [-200] # starting value hvalues = [10] # starting value increments = [1, 1, 1, 1, 1, 1, 1, 1] for N in increments: h = hvalues[-1] - N hvalues.append(h) z = zvalues[-1] + h zvalues.append(z) height = arange((z)*dz,0,dz) There is no arange in python. Could it be that you use numpy and import it with from numpy import *? for z,when in enumerate(height): I'm pretty sure this line doesn't do what you expect it to do. You have a sequence (a numpy array) named height and after calling enumerate you get a list of tuples in the form of [(0, height[0]), (1, height[1]), ...]. Now the for-loop iterates over this list and assigns z to the first value of the tuple (the index-values) and when to the second (the values from height). You later never use when but just use z. If you really want that, the enumerate is completly unnecessary and you could just use for z in range(len(height)). But I'm not sure if numpy arrays work with len(). nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) The story is like this: I should define layers and thickness and see how the diffusion profile changes over the z. height (or depth) of the total thickness or 'z'. I basically, define 'z' in 10 layers and each layer is called ' N' . Difference between each layer is 'h', which is equal 10 micrometer. Now, what I like to do is the modification of nu based on each zvalue In fact, for each 'zvalue' o'z' step, I need to calculate a different value for 'nu' based on the available equation in the program. BUT, I am not sure, exactly, how to add the new do loop of z inside another loop of nu. For me your explanations are still too confusing. Could it be that you are thinking way too complicated? My guess is you want to have a range of material thicknesses (from 1 to 200 micrometers in 10 micrometer-steps) and then you want from each thickness 10 different layers, right? import math # you should always tell us which modules you import num = 0.05 # some constant nu = [] # list of resulting values h = 10.0 # height of one layer thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, 10, 20, ..., 190, 200) layers = range(1,11) # a list from 1 to 10 for t in thickness: for l in layers: z = t + h * l # I'm not sure if you want to add or subtract the layer thickness nu = num + (0.01 * math.exp(-0.05 * (z + 200.0))) This will result in a big one-dimensional list where you calculate for each thickness the nu-value for 10 layers. Am I close? I'm still not sure about the steps and the height of the layers. I also wonder if it wouldn't be better to use a two-dimensional list. I have done this way as well (the other way around): height = arange((z)*dz,0,dz) for z,when in enumerate(height): for N in increments: h = hvalues[-1] - N hvalues.append(h) z = zvalues[-1] + h zvalues.append(z) nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) but still no sign of 'nu changes' over 'z'! As Charles has already mentioned, the values for nu are very similar (they start beginning to differ just at the seventh digit after the comma). How do you further process this values? If you plot them what's your scale? Bye, Andreas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code of a finsihed program.
On 25/11/11 21:14, Mic wrote: Alright. Sorry if I should know this, but what is a pastebin web site and how do I paste my program into a pastebin web site? A web site that you can paste stuff and then provide a link(url) that others can use to view it. You can usually specify the code style and it will apply syntax coloring for you. Try a google search for free pastebin... As an example I've pasted your code from this message at: http://pastebin.com/H3VzaapV Take a look and you will see what I mean. While its perfectly legal Python to create a class inside a method its very unusual in practice and very restricting in the use of the class. Why is it restricting? Because the class is only available inside the function. You cannot create objects of that class anywhere outside the class. So I figured I could post it here (short code) and ask you a couple of questions regarding the code: import tkinter as tk from functools import partial def button_clicked(button): if button[bg] == green: button.configure(bg=red, text=01) else: button.configure(bg=green, text=01) Note you are setting text to '01' in every case. Thats probably not what you want? def create_widgets(self): list_chair=[(0, 0), (0, 1), (0, 3), (0, 4), (1,0)] for row, column in list_chair: button = tk.Button(self) command = partial(button_clicked, button) button[command] = command button.grid(row=row, column=column) command() As stated above this will result in every chair being green and having the text '01' It would be better to put the initial colour and text in your data list and configure each button directly: def create_widgets(self): list_chair=[(0, 0, '01'), (0, 1, '02'), (0, 3, '03'), (0, 4, '04'), (1, 0, '05')] for row, column, name in list_chair: command = partial(button_clicked, button) button = tk.Button(self, color='green', command=command, text=name) button.grid(row=row, column=column) Incidentally, This is what I mentioned early on in the discussion about using a data table to create your widgets. root = tk.Tk() root.title(Test) root.geometry(200x200) app = Window(root) root.mainloop() --When the first button is pressed I want a file to be created with the name Germany_France_1. The text in the file should be Germany_France_1. If/When the button is pressed again it should delete the file. Lets get the initial UI set up correctly first. Once we have done that we can worry about adding the functionality. This is one of the good habits in programming. Do it step by step. Get one thing working first before trying to add more features. Its a lot easier to debug code when you know what you changed to stop it working. Do you have any idea on how I can accomplish this? I reached the conclusion that it should be easy to do so since it was so easy to create so many buttons in so little amount of code. Yes, but lets get the UI all done first, then we can add the button features. You should only ever have one Tk() object in a Tkinter program. Why is that? Because thats how Tkinter expects to work! It builds a tree of all the windows and widgets in your program. If you have two trees in the same program it can get very confused about which widget is doing what to which other widgets, especially if they wind up in different trees!. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code of a finsihed program.
Alan Gauld wrote: On 24/11/11 16:20, Mic wrote: and then try to put these parts togheter into a large program, I decided to post my entire program. Its usually better to paste long programs into a pastebin web site and give us a link. This saves cluttering up people mail with long messages, and also the pastebin rendering will usually be easier to read with syntax coloring etc. I'd just like to say that some of us disagree with this advice. Some people (e.g. me) often read their where getting access to a browser is less convenient. More importantly, many pastebin sites are short-term only, after some weeks the bin disappears and the code is lost, which destroys the archival value of the post. If your code snippet is short, say, less than two dozen lines, there's no need to using a pastebin, just include it in your post in-line. More than that, you should attach it to the post as an attachment, as a .txt or .py file. Under no circumstances use your mail client's rich text, colours or multiple fonts. Even a 200 line program isn't that big, it's only about 6K. If your code is so large that syntax highlighting becomes particularly useful, then chances are it's too long and people won't read it regardless. We're volunteers doing free support, but there are limits to how much code we're going to wade through if it doesn't interest us personally. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code of a finsihed program.
Hello Mic, Mic wrote: Its usually better to paste long programs into a pastebin web site and give us a link. This saves cluttering up people mail with long messages, and also the pastebin rendering will usually be easier to read with syntax coloring etc. Please keep a attribution line when quoting people directly. Even something simple like Fred wrote will do. Alright. Sorry if I should know this, but what is a pastebin web site and how do I paste my program into a pastebin web site? Here's one: http://pastebin.com/ But as I've just written in another post, please don't use it :) While its perfectly legal Python to create a class inside a method its very unusual in practice and very restricting in the use of the class. Its nearly always better to declare all your classes at the top level of the program. Why is it restricting? Because generally speaking, if you define a class inside a function (or method), you can't use it *except* inside that function or method. class K: def method(self, x): class Q: pass instance = Q() This doesn't work because Q is not visible from the outside of K.method. Sometimes this is what you want; generally it is not. I don't know much about tkinter, so I will avoid commenting about your code. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code of a finsihed program.
On 26/11/11 00:07, Steven D'Aprano wrote: Its usually better to paste long programs into a pastebin web site and give us a link. I'd just like to say that some of us disagree with this advice. Some people (e.g. me) often read their where getting access to a browser is less convenient. Its true there are downsides to every option. Even a 200 line program isn't that big, it's only about 6K. That adds up if you are reading on a 3G smartphone with a 100M data limit or paying by the byte. And attachments don't help there. Plus many email gateways block all attachments as a security measure. is so large that syntax highlighting becomes particularly useful, then chances are it's too long and people won't read it regardless. I find syntax highlighting useful even in very short snippets of code, but I agree it's better to just keep the code sample short and post it inline. And I do take the point that pastebins are short lived and so unless the replies incorporate the defective code snippets its lost to the archive. Nonetheless I personally prefer a pastebin posting to a long mail listing with no highlighting and often defective indenting. as I say there is no perfect solution to long posts other than to shorten them -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On Sat, Nov 26, 2011 at 12:49 AM, Andreas Perstinger andreas.perstin...@gmx.net wrote: On 2011-11-25 13:40, lina wrote: On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Apranost...@pearwood.info wrote: f = open(some file) dehydrons = {} occurrence = {} pairs = {} for line in f.readlines(): parts = line.split() # convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) # order doesn't matter if pair in dehydrons: occurrence[pair] += 1 else: dehydrons[pair] = parts[2] occurrence[pair] = 1 pairs[pair] = pairs.get(pair, 0) + parts[2] f.close() for line in f.readlines(): parts = line.split() #pair=set((parts[0],parts[1])) #convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) print(pair) if pair in dehydrons: occurence[pair] += 1 else: dehydrons[pair] = parts[2] pairs[pair] = pairs.get(pair,0) + parts[2] print(pairs) $ python3 dehydron_data_frozenset_version.py frozenset({2, 15}) frozenset({2, 15}) Traceback (most recent call last): File dehydron_data_frozenset_version.py, line 35, inmodule occurence[pair] += 1 KeyError: frozenset({2, 15}) You want to add one to occurence[frozenset({2, 15})] but there is no such key in occurence yet. If you carefully re-read Steven's code snippet you will see that you missed the line occurence[pair] = 1 in the else-branch. Thanks, I was so careless. for k, v in occurence.items(): print(v,k) 292 frozenset({66, 69}) 222 frozenset({24, 27}) How can I let the result like: 292 {66,69} 222 {24,27} don't output the frozenset Therefore occurence[frozenset({2, 15})] wasn't set in the first iteration and you get the error in the second. You can see that you are already in the second iteration by looking at the output of your program before the error message. Bye, Andreas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Operation Speed Question
Dear Pythonistas, http://wiki.python.org/moin/PythonSpeed#Takeadvantageofinterpreteroptimizations%E2%80%8C%E2%80%8Bthis is a link I found concerning optimizing the speed of python code. Is anyone familiar with an article or wiki such as this that may cover the changes that took place in Py3K? And I've heard that the Standard Library will discuss the Big O notation for methods etc. Where do I find the comments on this in the docs? A search for O(1) and O(n) returned nothing on python.org, is http://docs.python.org/py3k/library/timeit.html the best bet or is there somewhere else to look? I realize that my code isn't probably going to enter any area where this is important any time soon, but I'm trying to fill in my gaps in CS theory without doing so through school. Thanks! Charles ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor