3,386 Posted Topics
Re: This my try seems to work, I do not know if I am overcomplicating things, but you could compare this to your try and maybe debug the problem: [CODE]from __future__ import print_function def match_pat(CH, mystring): print ("%r vs %r" % (CH, mystring)) if not CH: return not mystring elif CH … | |
From [url]http://stackoverflow.com/questions/228181/zen-of-python[/url] Tells you what is Zen of Python Actually this is enough to print the Truth: [CODE]import this[/CODE] Loop version from [url]http://stackoverflow.com/questions/3559124/dissecting-a-line-of-obfuscated-python[/url] [CODE]result = [] for c in this.s: ## fixed tonyjv if c in this.d: result.append(this.d[c]) else: result.append(c) print "".join(result) [/CODE] | |
Re: Maybe you could catch some points from this words haiku code I made recently (reorganizing words in given count pattern to lines): [CODE]from __future__ import print_function bookfile = '11.txt' pattern = (7, 5, 7) def nwords(book, nwords): for dontcare in range(nwords): ## give word from begining (0) and remove from … | |
Re: My favorites are Python, Icon and Lisp, of which I have most used actually used Python, even I learned about (but did not actually program with) Lisp first. 1980's I programed BASIC with z90 ASSEMBLY, so now you know that I am brain damaged, but maybe learning about LISP protected … | |
Re: [CODE]for i in range(min(len(sumprop3), len(x2))): print("%s [%s, %s]" % (x2[i],atomnumber[i], atomnumber[i+8])) [/CODE] | |
Re: Like this: [CODE]binStr = raw_input('Please input a binary number:') if all(c in '10' for c in binStr): print "Good" else: print "must contain only 1's and 0's!" [/CODE] or like this: [CODE]try: bin_num = int(raw_input('Please input a binary number:'),2) except: print "must contain only 1's and 0's!" else: print "Good … | |
Re: in c do from a import * and from b import * You must have good reason to do so, however as this [iCODE]from import *[/iCODE] is generally bad idea poluting your namespace. It has it's uses, though: I have found it usefull to make alternative itertools module which implements … | |
Re: You might find it usefull to use my pretty print function to print out your matrixes: [url]http://www.daniweb.com/code/snippet281208.html[/url] | |
Re: Push (code) button and include what you tried to do. Include complete error message, if any. | |
Re: Your programs are just sequence of actions with fixed constant parameters repeatedly used again and again. Use loops, variables and functions. | |
Re: Just to make it explicit, the correct form for this: [CODE]for file in [f for f in files if f.endswith(".html" or ".htm" or ".txt")]:[/CODE] could be for example: [CODE]import os filenames = os.listdir(os.curdir) for filename in (f for f in filenames if any(f.endswith(extension) for extension in ('.html', '.htm', '.txt'))): print … | |
Re: This post is duplicate of [url]http://www.daniweb.com/forums/thread314835.html[/url] | |
Re: Here is one variation of input, not exactly according to your specification, so it is not direct answer: [CODE]try: input = raw_input except: pass def check_input(low, high): print("Enter an integer number between %d and %d: " % (low, high)) while True: a = input() try: if low <= int(a) <= … | |
| |
I have this 'code' which I wrote as new kind of art form, both as story and code. As program it is little stupid in way of expressing things, because it is writen thinking of human who reads the code. It is supposed to be impressive in that it is … | |
Re: fileIn.next().split(',') or fileIn.readline().split(',') | |
Re: Maybe you are installing the libraries to different version of python, check: [CODE]D:\Python26>easy_install pycrypto Searching for pycrypto Best match: pycrypto 2.3 Processing pycrypto-2.3-py2.6-win32.egg pycrypto 2.3 is already the active version in easy-install.pth Using d:\python26\lib\site-packages\pycrypto-2.3-py2.6-win32.egg Processing dependencies for pycrypto Finished processing dependencies for pycrypto D:\Python26>easy_install pyasn1 Searching for pyasn1 Best match: … | |
Re: Something like this (not able to test without data of your values, but principle should be OK). I use generator instead of lists (sorted produces automatically list). [CODE]sorted_table = sorted(((key, dd[key], ports_name[key]) for key in dd if key in ports_name), key = lambda x: x[1] ) with open('myoutfile.txt', 'w') as … | |
Re: I would say it like this. [CODE]def is_square(num): for x in range(num+1): if x*x >= num: return x*x == num for number in (1, 2, 15, 191, 121, 26, 36, 24, 25): print '%s is %ssquare.' % ( number, '' if is_square(number) else 'not ') [/CODE] | |
Re: You should use routine to draw single h with parameter for size and function repeating to draw h by loop doing total 360 degrees turn with parameter for amount of turn. Your colour alternation routine is fine, even there is many ways to do it. | |
Re: You are using these megawidgets [url]http://pmw.sourceforge.net/[/url] ? | |
Re: What code you got now? What kind of error are you getting and what you did to try to solve it? | |
Re: Here is one functioning print of all sums recursively with generators: [CODE]def rec_sums(x): if x<=1: this_sum = x else: this_sum = x+next(rec_sums(x-1)) print x,'->',this_sum yield this_sum next(rec_sums(10)) [/CODE] | |
Re: You might consider random facility for producing samples: [CODE]import random import string random_count = random.randint(3,len(string.ascii_lowercase)) print('Non-repeating sample of %i items is:\n%s' % (random_count, random.sample(string.ascii_lowercase, random_count))) shuffled_letters = list(string.ascii_lowercase) random.shuffle(shuffled_letters) print('With shuffle and randint, same:\n%s' % (shuffled_letters[:random_count])) [/CODE] | |
Re: Here some more examples: [CODE]## same as Griswolf's and woooee's code: use a loop to replace code below # use tuple, which is generally faster for looping and construction # and automatic continuation inside parenthesis # BTW .remove removes all occurances of items (text1, text2, text3, text4, text5, text6, text7, … | |
Re: How about this: [CODE]amount = 0.0 for kind, value in ( ('Dollar coins', 1.00), ('Quarters', 0.25), ('Dimes', 0.10), ('Nickels', 0.05), ('Pennies', 0.01) ): amount += int(raw_input('Please enter number of %s: ' % kind )) * value print ("You have $%.2f." % amount) [/CODE] | |
Re: I used values separately and coding function, in object oriented approach it could be __str__ method for printing out concise form of hand. | |
Re: This is how I plan to call the function; [CODE]def removeIndexItem(pl, pl_part, item_index):[/CODE] Quite impossible to say without concrete example of content of parameters. What kind arrays are you using? Numpy? Array module? Why you are not using normal lists? Maybe you want to just do [CODE]def removeIndexItem(pl, pl_part, item_index): … | |
Re: How about: [CODE]wordlist = ['England area','Germanic 6th', 'Finnish people'] mysentence = 'The area now called England has been settled by people of various cultures for about 35,000 years, but it takes its name from the Angles, one of the Germanic tribes who settled during the 5th and 6th centuries.' for … | |
Re: You could do: [CODE]string1 = 'actttcttc-dsfsdf-yy' string2 = 'sacttctcpdsfsdfgysy' print ''.join(s2 for s,s2 in zip(string1,string2) if s != '-') [/CODE] | |
Re: This worked for me: [CODE]import smtplib from datetime import date smtpserver = ('smtp.gmail.com',587) fromaddr = "" toaddr = "" password = '' def send_message(addr, to, msg): try: server = smtplib.SMTP(*smtpserver) server.ehlo() server.starttls() server.ehlo() server.login(fromaddr,password) server.sendmail(addr, to, msg) except: raise finally: server.quit() now = date.today().strftime("%d/%m/%y") subject = 'Subject of the message' … | |
Re: Concise version of the code: [CODE]with open('filein.txt') as filein: with open('fileout.txt', 'w') as fileout: for tag, num1, dna, num2 in (thisline.split() for thisline in filein if 'query' in thisline and not(thisline.startswith('@') or thisline.startswith('>'))): fileout.write("%s %s\n" % (num1, dna)) # This will write number and dna sequence [/CODE] | |
Re: You want random words or just re-splitting the lines with word count based line breaks? | |
Re: I think this is best approaced mathematically counting (len(string.lowercase)+1)**len(target) | |
Re: I would prefer to call your nice, little code script, not module. Module I call code, which is imported to other Python code to call useful functions from it. Script is something traditional C coding like stdin to stdout input/output or using command arguments from invocation. | |
Re: This would produce your desired output: [CODE]import itertools as it data="""john steve 0.67588 john matt 1.00 red blue 0.90 yellow steve 0.02""" data_pairs = sorted((first, value) for first,second,value in (d.split() for d in data.splitlines())) limit = 0.6 for name, group in it.groupby(data_pairs, lambda x: x[0]): print name, len([ value for … | |
Re: I do not quite get what is your purpose. Something like this? [CODE]import turtle def square(length): for i in range(4): turtle.forward(length) turtle.right(90) def roll_box(length, num_divisions): turtle.fill(True) turtle.down() for count in range(num_divisions): angle = 360.0/num_divisions square(length) turtle.right(angle) turtle.reset() turtle.setup(width=1000, height=600, startx=0, starty=0) roll_box(100,12) turtle.mainloop() [/CODE] | |
Re: I usually prefer to do [code]filehandle.write('\n'.join(logline for logline in loglines))[/code] You can also just add newline manualy at end of each line with normal addition notation.[code]filehandle.write(logline + '\n') [/code] | |
Re: Can't you return the needed value from telephone.incoming_call() function as return value? | |
Re: This works better: [CODE] def button1Click(self, event): ### (3) # expensive process here # simulated by time.sleep self.lbl.configure(text='Running command...') self.lbl.update() time.sleep(4) self.lbl.configure(text='Finished running command...') [/CODE] | |
Re: You want to do like this? [CODE]import math import random import itertools choices= [(math.sin(z), math.cos(z)) for z in itertools.chain(range(91), range(270,361))] newx, newy = 0, 0 for n in range(1000): sinz, cosz = random.choice(choices) newx, newy = newx + sinz, newy+cosz if n < 100: print newx, newy # print hundred … | |
Re: Your description is too unclear, but generally it is not considered to change file in place as you can mess up your data. Normal pattern is loop over the list of your files, read data preferably line by line and do changes and write them in temporary file or read … | |
Re: Your link is not working. Please post directly to Daniweb. You can attach image in Advanced Editor -> Manage Attachments. I agree it is very unsafe to do like you did conversion by eval. The user can give any command through eval, including wiping out information from computer (by using … | |
Re: This article has little info on __add__: [url]http://linuxgazette.net/issue54/pramode.html[/url] I do not know if it helps you. You have of course read the standard documentation [url]http://docs.python.org/reference/datamodel.html[/url] | |
Re: Maybe you are using Python 2, where integer division 506/730 makes 0, when you do not want that but actually 506.0/730 float division? Better to get used to write in beginning of your programs: [CODE]from __future__ import division[/CODE] So you get what you expect and must use // for integer … | |
Re: Now that you got it working consider this radical rearrangement of your code. [CODE]def main(): assessment_value = to_assessment_value(input ("Enter the actual value of the property: $")) print """The assessment value is: $%1.2f The property tax is: $%1.2f""" % (assessment_value, property_tax(assessment_value)) def to_assessment_value(actual_value): """ takes assesment value returning assesment value """ … | |
Re: Looks familiar, I posted to similar question earlier in Stackoverflow: [CODE]base = ord('A') - 1 mystring = 'ABC' print sum(ord(char) - base for char in mystring)[/CODE] That has best score, but is not accepted answer in [url]http://stackoverflow.com/questions/3711303/how-do-i-assign-a-numerical-value-to-each-uppercase-letter[/url] That can adapt to simply joining the letters also: [CODE]base = ord('a')-1 for … | |
Re: To get it work you need of course change file1.py to say [CODE]import file2 file2.x = 6 file2.file2Funct()[/CODE] | |
Re: I think you must read the files ones and generate index for seek positions in the file for each file and save the index. Do use snippsat's suggested way of reading file, not readlines. Once you have index finding the line is instantanous. | |
Re: Please push (CODE) button before pasting code: import maze import graphics h = 20 w = 20 cellsize = 20 startpos = maze.Index(1,1) curindex = startpos # stage 5 endpos = maze.Index(h, w) win = graphics.GraphWin("my Maze", w*cellsize, h*cellsize) mymaze = maze.Maze(win, h, w, cellsize,startpos ,endpos ) person = graphics.Circle(graphics.Point(cellsize/2+2, … |
The End.