2,646 Posted Topics

Member Avatar for Number1000

The general rule is that a list is always preferable to variables with numbered names, so don't hesitate and use a list.

Member Avatar for WolfShield
0
145
Member Avatar for vlady

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" …

Member Avatar for vlady
0
130
Member Avatar for AdampskiB

[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 …

Member Avatar for AdampskiB
0
120
Member Avatar for Flames91

hm, your class can't represent [icode]2x^3 + 2x^5[/icode]. There must be something wrong...

Member Avatar for TrustyTony
0
517
Member Avatar for petergeng

Did you check this part of the documentation ? [url]http://docs.python.org/release/2.3.2/ext/link-reqs.html[/url]

Member Avatar for Gribouillis
0
162
Member Avatar for ryan461

[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 …

Member Avatar for Gribouillis
0
185
Member Avatar for giancan

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.

Member Avatar for giancan
0
193
Member Avatar for RM@Bowdoin

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, …

Member Avatar for Gribouillis
0
2K
Member Avatar for as3g

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 …

Member Avatar for Gribouillis
0
153
Member Avatar for eternalcomplex

Reccurrent question. See this snippet [url]http://www.daniweb.com/software-development/python/code/257449[/url]

Member Avatar for Gribouillis
0
51
Member Avatar for sofia85

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 …

Member Avatar for Gribouillis
0
236
Member Avatar for felix001

I think [icode]except socket.error[/icode] will catch all errors from module socket.

Member Avatar for Gribouillis
0
223
Member Avatar for ERINY

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 …

Member Avatar for TrustyTony
0
1K
Member Avatar for sofia85

[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 …

Member Avatar for Gribouillis
0
151
Member Avatar for debasishgang7

This may help [code=python] >>> import string >>> print "Aa" + "Aa".join(string.digits) Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9 [/code]

Member Avatar for debasishgang7
0
261
Member Avatar for usdblades

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 …

Member Avatar for Gribouillis
0
263
Member Avatar for python12345

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 …

Member Avatar for Rick345
0
12K
Member Avatar for sofia85

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.

Member Avatar for sofia85
0
99
Member Avatar for hughesadam_87

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.

Member Avatar for hughesadam_87
0
222
Member Avatar for konnara
Member Avatar for Emred_Skye

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, …

Member Avatar for Gribouillis
0
282
Member Avatar for Gribouillis

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).

Member Avatar for Gribouillis
2
572
Member Avatar for vegaseat
Member Avatar for Gribouillis
1
7K
Member Avatar for sys73r

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 …

Member Avatar for sys73r
0
200
Member Avatar for hemant_rajput

I can't explain, but perhaps you could try to browse the site with the mechanize module which offers more browsing options.

Member Avatar for Gribouillis
0
461
Member Avatar for A.D.M.I.N
Member Avatar for sofia85

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.

Member Avatar for Gribouillis
0
156
Member Avatar for hemant_rajput
Member Avatar for as3g

[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 …

Member Avatar for TrustyTony
0
94
Member Avatar for ao_py

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 …

Member Avatar for Gribouillis
0
2K
Member Avatar for Creatinas

[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 …

Member Avatar for Creatinas
0
155
Member Avatar for eikonal

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): …

Member Avatar for eikonal
0
183
Member Avatar for sofia85

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') …

Member Avatar for sofia85
0
107
Member Avatar for Lzaochi

Here is the solution [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url]

Member Avatar for Gribouillis
0
28
Member Avatar for ChristianOncken

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.

Member Avatar for Gribouillis
0
257
Member Avatar for king_koder

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 …

Member Avatar for Gribouillis
0
11K
Member Avatar for arindam31

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 …

Member Avatar for Gribouillis
0
406
Member Avatar for mjohnson

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]

Member Avatar for mjohnson
0
1K
Member Avatar for M09

[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 …

Member Avatar for M09
0
549
Member Avatar for SamarthWiz

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 …

Member Avatar for nezachem
0
1K
Member Avatar for Gribouillis

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.

Member Avatar for Gribouillis
0
268
Member Avatar for sofia85

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.

Member Avatar for Gribouillis
0
128
Member Avatar for 1337RAM1337

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]

Member Avatar for 1337RAM1337
0
593
Member Avatar for kwajo

Here is the link given by google [url]http://www.cplusplus.com/forum/articles/12974/[/url]

Member Avatar for kwajo
0
487
Member Avatar for psvpython

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") …

Member Avatar for Gribouillis
0
2K
Member Avatar for Gribouillis

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 …

Member Avatar for Gribouillis
2
1K
Member Avatar for bigredaltoid

[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 …

Member Avatar for bigredaltoid
0
138
Member Avatar for spunkywacko

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]

Member Avatar for Gribouillis
0
206
Member Avatar for as3g

This perhaps [icode]print(sum(str1.count(c) for c in ".!"))[/icode] or [icode]sum(c in ".!" for c in str1)[/icode]

Member Avatar for as3g
0
171
Member Avatar for RoqueyB

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]

Member Avatar for TrustyTony
0
158

The End.