3,386 Posted Topics
| |
Re: The OP obviously learns about recursion as programming technique. The code is against the Python-do, but let it be... Grib gave good answer, let him learn style in peace after. | |
Re: And OP must add the recursion? To only check if things are palindrome is by the way enough to: [code]def ispalindrome(x): return x == x[::-1][/code] (The recursive version can be written with same amount of lines) | |
Re: And who is forcing you to use XML? It is generally considered more as part of the problem rather than solution. | |
Re: I do not know what you want to accomplish, but one guess: [CODE]array2D = [[0 for i in range(10)]for j in range(10)] for i in range(len(array2D)): array2D[i][0] = 2 print array2D [/CODE] or [CODE]array2D = [[0 for i in range(10)]for j in range(10)] for row in array2D: row[0] = 2 … | |
Re: Can you show what you mean by 2d array as there are many alternatives. Looks from tags that you are using numpy. I am not very familiar with it. I know general way of ziping items together with their indexes and sorting the tuples, but numpy should have optimized functions … | |
Re: Read this [url]http://www.daniweb.com/forums/post319401.html#post319401[/url] especially the response with pseudo-prime test. | |
Re: That is just normal sort. What is your problem? What you mean by big dictionary? Gigabytes? | |
Re: This is not really training/programming service for free. Those exist separately, including mine. Here however simple code for what you requested replace with appropriate URLs: [CODE]import time import urllib2 files = ['http://www.daniweb.com/forums/attachment.php?attachmentid=16112&d=1280133590', 'http://ysisoft.com/daniwebforum_anagrams.txt'] for download in files: t0=time.time() print('\nDownload: %s\nsize: %i bytes, time: %s s' % (download, len(urllib2.urlopen(download).read()), time.time()-t0)) [/CODE] | |
Re: column 5 has words like TAKE AWAY and CREDIT CARD. I have not used csv lot but would you not need to set separator to comma. If the reader part works, you end up with unique items in column 5 of file in itemlist, but you need to do line … | |
Re: You have backslashed ending quote at line 4, replace '' with r'' | |
Re: Also you should not use coloring or other own formats in your text or automatic Python formatting is lost. | |
Re: I have not time to debug for you, but I quickly hacked together this my version from my archive, at least it got under 100 cases right even it took over 8 seconds for case 1000000 to get 55 cases: [CODE]import time def numrotator(number): string_number=str(number) return [int(string_number[place:]+string_number[:place]) for place in … | |
With this code you can explore the functions of math module interactively seeing the docstrings automatically for each function. EDIT: The docstring was unfortunately from old code, this version copes with values like 'e' and multiple parameter functions. | |
Re: Where is a comming? Also value of n is lost after exit from function at line 3, better to do: [CODE]a=int(raw_input('a: ')) if a == 1: print 'string' else: print 5+int(raw_input('> ')) [/CODE] And that simpler: [CODE]print 'string' if int(raw_input('a: ')) == 1 else 5+int(raw_input('> ')) [/CODE] | |
Re: My suggestion: [CODE]#! /usr/bin/python import sys, os, string, re # input/output for filenames filename = 'data.txt' newfilename = 'data_out.txt' # read file if os.path.exists(filename): data = open(filename,'r') dataInput = data.read() else: print "File not found." raise SystemExit numPattern = r'\s+([\+\-]?\d*\.?\d*)' r = re.compile(r''' ^\s* # Skip whitespace at start of … | |
Re: This is latch circuit, I do not think it is possible to simulate by only boolean logic from basic input the way the circuit works. You should extract logic of function and code that as program. That is my impression on information from net, I do not know this subject … | |
Re: Sum does work, but it is not method of array: [CODE]>>> from array import * >>> myarray=array('i',range(10)) >>> myarray array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> sum(myarray) 45 [/CODE] | |
Re: woooee's code brought name error on name1, so here running slightly simplified and only raw_input using version: [CODE]dict1={} for i in range(int(raw_input("Enter the number of contacts : "))): name=raw_input("Enter your name: ") num=raw_input("Enter your phone number: ") if name not in dict1: dict1[name] = num else: print name, "already on … | |
Re: richieking: No it is not reserved: [CODE]IDLE 2.6.6 >>> dir(new) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> dir(new) NameError: name 'new' is not defined >>> [/CODE] | |
Re: String is not mutable, transform string to list by doing word = list(word) | |
Re: You are not entering to the mainloop. Can you explain the purpose of 21 onwards setting string again to value it has allready? | |
Re: I would suggest [URL="http://docs.python.org/library/gettext.html"]gettext[/URL]. | |
Re: Stupid demonstration of meaning of mutability of lists. [CODE]import plugin mydata = ['very', 'important', 'thing'] plugin.plug(mydata, 'more to put') print mydata """Output: ['very', 'important', 'thing', 'more to put'] """[/CODE] plugin: [CODE]def plug(change, something): change.append(something) [/CODE] | |
Re: You are not allowed to use list or collections.deque for the queue? | |
Re: I can not see rational rule between wished result and input. | |
Re: You could be more specific, maybe this helps? [CODE]this_dict = {5:'ada', 3:'pascal', 4:'lisp', 1:'Python', 2:'Icon', 3:'Visual Basic'} print('The programming languages in key order are:') print(', '.join(repr(this_dict[key]) for key in sorted(this_dict))) [/CODE] | |
Re: Do you want sorting by duration between times? | |
Re: That is one style of looking that picture, I see set of overlapping squares with same center location (+-x, +-y), alternating color overlapping drawn biggest first. So take your pick. | |
Re: And the problem and error messages? | |
Re: [QUOTE=dragonstear;1418236] I got the sorting and the median done.. [/QUOTE] I do not see any sorting and median, so I am confused of what you want. [CODE]def elements(score_file): return [int(score) for score_line in open(score_file) for score in score_line.split(",")] print sorted(elements('score.txt'))[/CODE] | |
Re: Griswolf is right, I got mixed up. I remembered that you wanted union, but you want to take out common elements, like in this not recursive version: [CODE] def diff(a,b): return list(item for item in a if item not in b)[/CODE] | |
Re: [CODE]KEYWORDS = ['Blues', 'Bossa'] counterline = [] counter = 0 for line in song: for word in line.split() counter+=1 if word in KEYWORDS: counterline.append(counter) x=random.sample(line,10) print x, [/CODE]I'm expecting once it found the selection, from that selection it will randomly select 10 of the lines that had the KEYWORDS in … | |
Re: I understand him to be using: [url]http://vpython.org/index.html[/url] | |
Re: Edit the end tag to be [/CODE] not [ICODE] This community has [not been very enthusiast on outdated livewires library](http://www.daniweb.com/forums/post1201915.html#post1201915) in the past, so I do not know if anybody wants to help. | |
Re: You are maybe not giving any parameters for your script. In order for it to work you need the script to have exactly one parameter, the name (without spaces in it). Put as line 3 print argv to confirm your assumptions on contents of it. | |
Re: I would not use open as variable name, as it hides file open command, maybe change to open_ones or something. You can replace 7 to 9 lines with [code]while open_ones: x = open_ones.pop(0)[/code] | |
Re: You are correct woooee, but the style of lines 12-13 I would like to write: [CODE] optimism = raw_input(""" On a scale of 1-5.. [/CODE] | |
Re: Easiest way to look in columns is to do transposing of the grid and search second time in rows. You can transpose list by doing [CODE]trasposed = list(zip(*grid))[/CODE] You can keep count in the for loop by using enumerate on lines/colums. | |
Re: I would do something like: [CODE]import random from graphics import * class DeckOfCards(object): def __init__(self, *cards): """Make a deck of cards with variable suit and value""" if not cards: self.make_deck() random.shuffle(self.deck) else: self.deck = cards def deal(self, num=1): for count in range(num): yield self.deck.pop(0) def make_deck(self): """Prepare deck""" self.values=["1","2","3","4","5","6","7","8","9","10","j","q","k"] self.suits … | |
Re: Here my version, I used though more simple format of username,password and standard lowercase Python function names: [CODE]import time import os import hashlib FILENAME = 'users/users.txt' def user_creation(): while True: try: userfile = open(FILENAME, 'r') except IOError: # create file if it does not exist path = os.path.dirname(os.path.abspath(FILENAME)) try: # … | |
Re: [CODE]dic = {'Dog' :10, 'Cat' :50, 'Boat' :35,} print ' I have the following items for sale ' print ', '.join(dic) [/CODE] | |
Re: You are not using split(). | |
Re: I am not sure what you mean, but to decode the neighbour matrix you loop over it and print the True value's indexes: [CODE]neighbour_matrix= [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, … | |
Re: You should use proper xml module to read xml data [url]http://wiki.python.org/moin/PythonXml[/url] | |
Re: Character seems to be inside class ie namespace. So you must use Character.Character instead of only Character if you use the class from outside of the namespace. | |
Re: Here we sort with reverse frequency, and show ten most common: [CODE]import string def read_book(): word_freq = {} f = open("alice.txt", "r") for l in f.readlines()[10:3340]: book_line = l.strip().translate(None, string.punctuation).lower() for w in book_line.split(" "): if w != "": word_freq[w] = word_freq.get(w, 0) + 1 return sorted(word_freq.items(), reverse=True, key=lambda x: … | |
Re: I keep graphics.py in my debug directory, I do not mind that it is visible in that one directory. I just save code using that module to exclusively that directory. I never use it for my own code anyway. | |
Re: Another post is [URL="http://stackoverflow.com/questions/4417869/why-changing-global-does-not-give-error"]mine to StackOverflow[/URL] as I got suprized why append works. Normally the rule is simple: if you have global variable on left side of assignment (and only then method call does not count), you must write global variable at beginning of function in order for code to … | |
Re: Some first mistakes: 0) You hijacked old thread 1) Your main is not int (and does not signal success or failure) 2) Case of your variables is inconsistent and unclear 3) Your indention is bad or you did not use [CODE] tags 4) ma in first printf is not inside … |
The End.