2,646 Posted Topics
Re: The general rule is that a list is always preferable to variables with numbered names, so don't hesitate and use a list. | |
Re: You can also capture the data interactively with your function add_mark(), then save the dictionary to a file and read the dictionary from this file the next time you run your program [code=python] from cPickle import dump, load marks = {"alice" : "A+", "smith" : "A", "daemon" : "B+", "lily" … | |
Re: [QUOTE=pyTony;1699850][CODE]from __future__ import print_function def drawBlocks(a,b,c,d,height): print((a * " " + b * " *" + c * " " + d * " *" + "\n") * height, end='') def drawLetterA(): drawBlocks(1,8,1,0,2) drawBlocks(0,2,6,2,2) drawBlocks(0,10,0,0,2) drawBlocks(0,2,6,2,3) drawLetterA() [/CODE][/QUOTE] Why don't you post your output with your code ? It makes … | |
Re: hm, your class can't represent [icode]2x^3 + 2x^5[/icode]. There must be something wrong... | |
Re: Did you check this part of the documentation ? [url]http://docs.python.org/release/2.3.2/ext/link-reqs.html[/url] | |
Re: [b]Always[/b] use raw literal strings with regexes (with the r prefix): [code=python] pattern = re.compile(r'\s\d+\s') [/code] it's the only serious way to ensure that backslashes are preserved. You could use a [icode]found.findall()[/icode] which returns a list of string results, or [icode]found.finditer()[/icode] which return an iterable of match objects. Otherwise your … | |
Re: Another way is [code=python] from itertools import islice with open(filename) as lines: for line in islice(lines, 0, 150): # ... [/code] When you want to write [:150] and you can't, use islice(., 0, 150), that's the trick. | |
Re: I suggest a non recursive function [code=python] from collections import deque def getDegrees(target, base): "Return the distance from actor base to actor target (-1 on failure)" if target == base: return 0 else: enqueued = set([base]) fifo = deque(((base, 0),)) while fifo: actor, depth = fifo.popleft() for other in actedWith.get(actor, … | |
Re: There is no difference. The variable 'new' serves no purpose. The recommended style is [code=python] num = 3 * num + 1 if num % 2 else num // 2 print(num) count += 1 [/code] The other highly recommended thing is to [b]indent python code with 4 spaces[/b]. Your editor … | |
Re: Reccurrent question. See this snippet [url]http://www.daniweb.com/software-development/python/code/257449[/url] | |
Re: For almost all my path manipulations, I use a module with a path class. This path class was originaly written by developpers of the python language, I added a few useful features. Here is the attached module. Save it as whatever.py and use it. Here is an example: [code=python] from … | |
Re: I think [icode]except socket.error[/icode] will catch all errors from module socket. | |
Re: There are mathematical formulas for combination [code=text] # this is not python code comb(n, r) = n!/(r! * (n-r)!) = [n*(n-1)*...*(n-r+1)]/[r*(r-1)*...*1] comb(n,r) = comb(n, n-r) [/code] you can compute this recursively or not. You could also use the fraction module and compute the product of r terms [code=text] # again … | |
Re: [QUOTE=pyTony;1694446][icode]prob=[start:end][/icode][/QUOTE] This is meaningless, but you can write [code=python] >>> prob = slice(3, 7) >>> L = list(i**i for i in range(10)) >>> L[prob] [27, 256, 3125, 46656] [/code] I doubt this use of slicing was the OP's intention. @sofia85 The problem (and this may be why your code is … | |
Re: This may help [code=python] >>> import string >>> print "Aa" + "Aa".join(string.digits) Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9 [/code] | |
Re: The part 'if guess == secret ...' must run only after the while loop is finished [code=python] import random secret = random.randint(1,99) guess = 0 tries = 0 print "AHOUY! I'm the Dread Pirate Roberts, and I have a secret!" print "It is a number from 1 to 99. I'll … | |
Re: The mathematical result is the logarithm of base 2 of n. It seems to work also for python: [code=python] >>> from math import log >>> n = 444444444444444448888888888888888888888888883333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333336666666666666666666666666666666666666666666666666666666666666666666666666666666666666666677777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777774 >>> k = int(log(n, 2)) >>> n >> k 1L >>> k 1374 [/code] One could expect that this technique fails if … | |
Re: Make a string with [icode]' '.join(thelist)[/icode] (or '\t'.join(), or 'foo'.join()). The list must contain strings. There are other methods, you can write the list items one by one in the file. | |
Re: In principle, you can inspect the static members, either with dir(Test) or inspect.getmembers(Test), but you can't inspect instance attributes because they are usually created by __init__(). If the Test class, and/or classes in its mro implement __slots__ attributes, you can have some instances attribute names. | |
Re: You could perhaps run your code as administrator. | |
Re: I suggest traversing the file and building a list and a dictionary like [code=python] thelist = [ ('A', 1, 10), ('B', 1, 203), ('C', 2, 805), ] thedict = { 'B': 0.7, 'A': 0.98, 'C': 0,99, } [/code] Then traverse the list and read the third value in the dict, … | |
This snippet defines a simple decorator to post-process a function's return value through a sequence of filters. As a first application, the decorator can transform a generator function into a function returning a sequence type (list, tuple, dict). | |
Re: See also [url=http://www.daniweb.com/code/snippet231676.html]this other snippet[/url] | |
Re: 1) QUOTE_NONNUMERIC doesn't work in the reader because your input file contains unquoted non numeric fields. 2) writerow() expects a sequence and separates its items with the delimiter. If you give it a string, it will separate single characters. The correct way to use it is to pass a list … | |
Re: I can't explain, but perhaps you could try to browse the site with the mechanize module which offers more browsing options. | |
| |
Re: The following works for me [code=python] import numpy as ny data = list(ny.loadtxt(filename) for filename in ("data1.txt", "data2.txt")) result = ny.array(zip(*data)) print result print result.shape [/code] If there is a numpy way to do the zip(*data), it would probably be faster. You can also time itertools.izip() for comparison. | |
Re: I think easy_install supports multiple versions of python. | |
Re: [QUOTE=woooee;1686044]Can't you just take the difference between price and priceW, and then multiply by rate. If you want to print out every increment, then some kind of loop is necessary, and should be in a function that you pass the prices, rate, and literal to print, since both calculations are … | |
Re: If you choose [code=python] if random()*probA > random()*probB: scoreA = scoreA + 1 else: scoreB = scoreB + 1 [/code] you can compute the probability that each team wins the point like this: take 2 random variables X, Y uniformly distributed in [0, 1], the probability p that team A … | |
Re: [QUOTE=pyTony;1685520]Learn about generators and yield statement.[/QUOTE] I don't quite agree with Tony on this. The problem here seems to be that the function filest() takes time to complete, and wether you are using yield statements or not does not change this. When a function is busy with a long task … | |
Re: Here is a pure "itertool style" solution [code=python] from itertools import islice, repeat, takewhile def blocks(fileobj, size=4): blank = " " * 10 lines = (line for line in fileobj if not line.startswith(blank)) return takewhile(len, (list(islice(lines, 0, size)) for x in repeat(None))) with open("blocks.txt") as ifh: for b in blocks(ifh): … | |
Re: File objects have no append() method. To add lines to a file, you must open it in append mode (mode 'a') and use the write() method. If you want to create a new file, it's the same code with mode 'w'. [code=python] f = open('filename', 'r') new = open('other_filename', 'a') … | |
Re: Here is the solution [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url] | |
Re: Nobody seems to know, it's your third thread with the same question. If your goal is to write microsoft word files with python, I found this link [url]https://github.com/mikemaccana/python-docx[/url] . Hope it helps. | |
Re: In a terminal: [code=text] $ pydoc xrange class xrange(object) | xrange([start,] stop[, step]) -> xrange object | | Like range(), but instead of returning a list, returns an object that | generates the numbers in the range on demand. For looping, this is | slightly faster than range() and more … | |
Re: The easiest way is to open a [b]cmd[/b] shell and type [code=text] pydoc tkinter > tkinterhelp.txt [/code] or [code=text] pydoc -w tkinter [/code] which creates a file tkinter.html The best way, however is to type [code=text] pydoc -p 9999 [/code] and then direct your web browser to [url]http://localhost:9999[/url] . From … | |
Re: Without a 'break' or 'return' statement, a 'while True' loop is always infinite (unless one of its lines raises an exception, which is not the case here). Also there is a hidden error, try to understand this: [code=python] >>> "1000" < 9999 False [/code] | |
Re: [QUOTE=M09;1681563]Sorry Can you explain, by my code previous to be more clearly[/QUOTE] Imagine a student's record like a box containing 4 items: name, age and the 2 marks n1 and n2. The role of the __init__ method is to fill the box initially. It is called when you create the … | |
Re: The telnet protocol includes special characters to send telnet control sequences between the client and the server. Your 'telnet' command most likely sends these characters. You may be able to see them by printing repr(username), repr(password) instead of username and password for example. I don't think you can succeed without … | |
This snippet defines a decorator to automate attributes setting in class instances at creation time. It can be seen as a gadget feature but it can also be handy especially for fast class prototyping. | |
Re: Also you will get better answers if you post your code instead of pseudo code. This issue was already mentioned a few days ago, and it's not a difficult one. | |
Re: Ah ah! recurrent question. I once started a thread with same issue. The best solution I know is [code=python] def iround(x): return int(x + (0.5 if x > 0 else -0.5)) [/code] | |
Re: Here is the link given by google [url]http://www.cplusplus.com/forum/articles/12974/[/url] | |
Re: I think you could try and use my brand new module 'adaptstrings', see here [url]http://www.daniweb.com/software-development/python/code/389929[/url] . The following code works from me [code=python] from adaptstrings import adapt_as_opener import sys @adapt_as_opener def redirected_input(ifh, filename): with open(filename, "w") as ofh: while True: line = ifh.readline() ofh.write(line) yield line sys.stdin = redirected_input(sys.stdin, "foo.txt") … | |
Any sequence of python strings can be disguised to look like a file opened for reading, which can then be passed on the fly to functions expecting such an input file. This code snippet defines the necessary adapter class. The obtained file-like objects store only one string of the sequence … | |
Re: [QUOTE=bigredaltoid;1681150]I made the corrections I believe but the code still returns 0 even though there are 19 periods in the document. Help? [CODE]def percount(myFile): periods = 0 for char in myFile.read(): if char == '.': periods +=1 return periods myFile = open("inn.txt", "r") p = percount(myFile) print p [/CODE][/QUOTE] Carefully … | |
Re: As you wrote your class, i is a static variable (a class member and not an instance member). You can update it with [icode]App.i += 1[/icode] | |
Re: This perhaps [icode]print(sum(str1.count(c) for c in ".!"))[/icode] or [icode]sum(c in ".!" for c in str1)[/icode] | |
Re: You must also validate input: [code=python] total = 0.0 while True: reply = input("Enter a number: ") try: number = float(reply) except ValueError: print("Invalid value") else: if 0 <= number <= 100: total += number else: break print("The sum is {0:.2f}.".format(total)) [/code] |
The End.