2,646 Posted Topics
Re: The issue with your txt file filter is that you are removing items in targetdir while iterating on targetdir. This does not work. Look at this example [code=python] >>> L = range(20) >>> for item in L: ... print item, ... if item % 3: ... L.remove(item) # DONT DO … | |
Re: You must first find a way to split the text into a list of paragraphs, each containing a principle. | |
Re: You can also define your own bins limits for the numpy histogram by passing a sequence, like in [icode]bins = range(1, 7)[/icode]. Matplotlib's histograms also use numpy's histogram() method. Here is the same example with the plotted histogram [code=python] import matplotlib.pyplot as plt data = ''' 5.639792 1.36 4.844813 1.89 … | |
Re: The identation of 'else' must be exactly the same as the corresponding 'if' [code=python] import re words = ['cats', 'cates', 'dog', 'ship'] for l in words: m = re.search( r'cat..', l) if m: print l else: print 'none' [/code] | |
Re: Here is another way [code=python] def raw_inputs(msg): while True: yield raw_input(msg) def ask_depth(): for attempt in raw_inputs("Enter depth in meters:- "): try: d = int(attempt) if d < 0 or d > 50: raise ValueError return d except ValueError: print("Invalid value: depth is a number in [0, 50]") if __name__ … | |
Re: [QUOTE=tommygee100;1639599]Actually I'm still stuck I guess I need to take it one step further, but I don't know how.. In reality this is my situation, I've got a dictionary containing dictionaries by position which indicate the distribution of nucleotides, in this case for the combination of ['ACGT', 'GTAC']. So position … | |
Re: Perhaps you could take your input file test2.inp and write another file by hand with your exact expected output so that we understand what your program is supposed to do. | |
Re: Another module may be hiding your module risar. Add [icode]print risar.__file__[/icode] after the 'import risar' in module turtle to see if it's importing from the expected file. | |
Re: [QUOTE=imGhostofYou;1636051]Why do I want "protect" my code.. I really don't know, Just not comfortable with giving my raw coded work... and thanks for the distulis link, I'm looking at it now[/QUOTE] The best programmers give their raw coded work :) visit [url]http://www.gnu.org/gnu/gnu.html[/url] and [url]http://www.linuxlinks.com/[/url] Publish your work with an open … | |
Re: If it stops working, there must be a traceback or something. Can you post the traceback ? Also your code doesn't show what is db nor its content, perhaps you could attach the shelve file in a zipped form. The 'global db' statements are suspicious. At best, they serve no … | |
Re: The simplest tool is regular expressions (the re module). For example [code=python] >>> import re >>> state_re = re.compile(r"i am (?P<state>\w+)") >>> match = state_re.match("i am hungry") >>> print match.group("state") hungry [/code] This has serious limitations and you may need a real parser for your grammar rules. With a learning … | |
Re: I get an IndexError at line 58, meaning that the list self.cards is empty. This happens in a sequence of nested calls of give() and decide(). There should be a for loop somewhere. I don't like the self.decide(self) at line 42 in give(). Perhaps you should describe the intended progress … | |
Re: The problem is that you call kcinput() instead of return kcinput(). Use a loop for such problems instead of recursion [code=python] from __future__ import print_function import sys if sys.version_info < (3,): input = raw_input # these lines were for python before 3.0 def kcinput(): for i in range(2): try: return … | |
Re: Here are a few hints: first try to use python's library functions instead of calls to os.system. The following works for me [code=python] import os, pwd, time def whoami(): return pwd.getpwuid(os.getuid())[0] def become_user(name): # this seems to work when I'm root and want to become somebody else uid = pwd.getpwnam(name).pw_uid … | |
Re: [QUOTE=pyTony;1637074]I did not find exact match as round rounds numbers, does not cut. It is simple to write small function though: [CODE]>>> def cut(n, decimals): return int(n*10**decimals)/10**decimals >>> cut(7339520/(1024.0*1024), 3) 6.999 >>> cut(7339520/(1024.0*1024), 2) 6.99 >>> [/CODE][/QUOTE] you can use math.trunc() instead of int(). | |
Re: Read this first [url]http://www.daniweb.com/software-development/python/threads/366794/1574021#post1574021[/url] and this too [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url] | |
Re: It is very easy indeed, you can use lists of courses as values in the dictionary [code=python] # python 2 table = { "Joe" : [ "MATH101", "COMP202", ], "Jenny" : [ "COMP202", "BIO101", ], "Tom" : [ "MATH101", "BIO101", ], } print "The students in COMP202 are:", print sorted(k … | |
Re: You never [i]need[/i] to use lambda. Here, use functools.partial [code=python] from Tkinter import * from functools import partial fields = 'Name', 'Job', 'Pay' def fetch(entries, event = None): for entry in entries: print 'Input => "%s"' % entry.get() # get text if event: print event.widget def makeform(root, fields): entries = … | |
Re: Did you try this ? [code=python] BASECFLAGS= -fno-strict-aliasing -Wno-long-double [/code] | |
Re: Perhaps this example could help you [url]http://www.blog.pythonlibrary.org/2010/06/16/wxpython-how-to-switch-between-panels/[/url] | |
Re: [QUOTE=pyguy62;1633712]I'm guessing the only way to do this is with some third party modules?[/QUOTE] You can use them with the GUI toolkits (eg Tkinter). | |
Re: Consider the following class hierarchy [code=python] import inspect class A(object): def func(self): return "A.func" class B(A): def func(self): return "B.func" class C(A): def func(self): return "C.func" class D(B, C): def func(self): return "D.func" class E(D): def func(self): return "E.func" if __name__ == "__main__": def printmro(k): print "mro({0}): {1}".format(k.__name__, ", ".join(klass.__name__ … | |
Re: The body of Evolve_ms(), which is called by Evolve_m1() and Evolve_mv(), uses the global E and not the local E wich is updated in each iteration in F(). A solution is to pass E as a parameter and define Evolve_ms(m, E), Evolve_m1(m, E) and Evolve_mv(m, E). There may be other … | |
Re: Perhaps you could first secure the fact that all the files are properly closed by using [i]only[/i] with statements [code=python] with open(...) as fh: ... # do something with fh # now we're certain that fh is closed [/code] Otherwise, perhaps the SSH process uses the few too many file … | |
Re: You only need to read the spreadsheet file in sys.argv and use the module xlrd [code=python] #!/usr/bin/env python import sys import xlrd if __name__ == "__main__": assert len(sys.argv) == 2 spreadsheet = sys.argv[-1] wb = xlrd.open_workbook(spreadsheet) sh = wb.sheet_by_index(0) my_variable = sh.cell_value(0,0) # access a cell [/code] Get xlrd from … | |
Re: [QUOTE=g_amanu;1631350][CODE]x y z 0.045 0.45 0.0002 0.004 0.0001 0.0005678[/CODE][/QUOTE] I also suggest a hand made solution [code=python] import csv from math import sqrt import os class MaxiAverageCalculator(object): def __init__(self): self.ncols = 3 self.nrows = 0 self.s = [0.0, 0.0, 0.0] self.s2 = [0.0, 0.0, 0.0] def run(self, fullpath): with open(fullpath, … | |
Re: It may slow down things, but you could also define your own string class for turkish words, with a specific comparison function [code=python] # -*-coding: utf8-*- # tested with python 2.6 from random import shuffle from heapq import merge class turkish(unicode): def __new__(cls, *args): return unicode.__new__(cls, *args) def key(self, n … | |
Re: Ok, now since peter_budo closed the other thread with the same question, see my answer here [url]http://www.daniweb.com/software-development/python/threads/377865/1627143#post1627143[/url] | |
Re: To see if your files are in excel format, try to open them with excel or openoffice. The extension means nothing.Did you write these files yourself with one of your programs ? Then post the code used to create them. | |
Re: A part of the question is what do you want to do when a user is busy using the telnet connection. Should other users receive an error message, or should they wait ? If your server runs in a posix environment, your cgi script could perhaps acquire a system's semaphore … | |
Re: If the query is a valid python expression, you can simply use eval: [icode]result = eval(ask)[/icode]. Be careful that this will evaluate any python expression (like the expression which erases all your hard disk). You could add some validating routine to eliminate dangerous expressions (for example you could check the … | |
Re: It's difficult to help you since we don't know how your excel files are formatted nor the format of the output files that you want. Assuming you have a function all_files() which lists your excel files and a function find_patient(filename) which extracts the patient identification from a file, you can … | |
Re: In a traditional implementation of linked lists, one distinguishes lists and list elements, so you will have 2 classes like this [code=python] class Element(object): __slots__ = ("numb", "next") def __init__(self, numb): self.numb = numb self.next = None class List(object): __slots__ = ("first", "last") def __init__(self): self.first = self.last = None … | |
Re: [QUOTE=samuel16;1623630]how can we use the same condition by using the iteration for the numbers automatically? Like 1 after 2. 2 after 3. till 50?[/QUOTE] This thread is 3 years old and it is solved. Why don't you start your own thread ? Also please expose your question in details. It's … ![]() | |
How to create a png image containing a fragment of source code ? Well, don't do it yourself, the [url=http://pygments.org]pygments module[/url] contains all the necessary tools. The example below shows how to produce a png image from python code, but pygments supports lexers for many other languages and its formatter … | |
![]() | Re: It's always difficult to set the value of [i]global[/i] variables in functions. It can be done with the global statement, but it is usually simpler when the values are attributes of an existing object instead of global variables. If there is no such object, you can create one artificially [code=python] … |
Re: Well, writing [code=python] key = lambda x, y, z: expression(x, y, z) [/code] has the same effect as [code=python] def dummy(x, y, z): return expression(x, y, z) key = dummy [/code] It means that lambda is only a way to write small, anonymous functions. The main restriction is that the … ![]() | |
Re: The common idiom is [code=python] thelist[:] = (x for x in thelist if not criteria(x)) # for example thelist[:] = (x for x in thelist if not 'a' in x) [/code] ![]() | |
Re: [QUOTE=M.S.;1608154]Is "d" here stands for "digit"? this bellow code does the same but instead of 0's it prints empty spaces" [code=python]print('%0*s' % (3, 7))[/code] what about "s" here? does it mean "string"?[/QUOTE] Yes, 's' means string. In principle, the str() method is applied to the argument. Better learn to use … | |
Re: As a first hint, look at line 248 for example. [icode]Evolve_rho_ss(rho)[/icode] is called [b]8 times[/b] in the same expression. I assume that all these calls involve arrays of real numbers. Obviously you should call the function only once [icode]temp = Evolve_rho_ss(rho)[/icode] and then use the variable temp 8 times in … | |
A functor, or function object is sometimes a convenient way to encapsulate helper functions and data needed to achieve a small task, and also to share data between calls to the same function. This snippet defines a base class [b]functor[/b] which permits an easy functor creation for python 2. | |
Re: [QUOTE=pyTony;1617617]You should use at least os.path.join at line 61 an 67 to make your code cleaner. Also I would use 4 spaces instead of tab indention, as code commes out terrible in posts, even editor shows it OK. I would prefer to use also open instead of file Looks like … | |
Re: [QUOTE=heavy.is.happy;1619250]But test this. >>> new = "18,33" >>> a = new.replace(",",".") >>> a '18.33' >>> a = float(a) >>> a 18.329999999999998 >>> It must be 18.33.[/QUOTE] It's impossible to have a float exactly equal to the mathematical 18.33 because 18.33 has too many (or an infinity of) binary digits when … | |
Re: Go to [url]www.google.com[/url] and type 'set the path in windows 7' (or vista, or XP, etc). Follow the instructions of one of the first links on how to set the path in windows. Once you're at the step of editing the path, simply add [icode];C:\python27[/icode] to your path. Do this … | |
Re: [QUOTE=noobprogrammer;1618282]Can someone correct me on my code below??? How am i suppose to display the book titles published in 1954? 1) Display all the book titles 2) Display the book titles published in 1954 3) Display the 3 most recently published book titles 4) Display the author of “The Hobbit” … | |
Re: If you are ready to use python 2, you can write it very easily using a class I wrote in this code snippet [url]http://www.daniweb.com/software-development/python/code/258640[/url] . Here is a possible code [code=python] from optcmd import OptCmd AB = dict() class AddressBookCmd(OptCmd): def emtpyline(self): pass def do_add(self, name, email, phone): """ usage: … | |
Re: You must use a helper function which takes a match object as argument [code=python] def sub_helper(match): return SOME_FUNCTION(match.group(1)) output = re.sub(r'blah blah blah(\d+)', sub_helper, string) [/code] | |
Re: The code [code=python] @is_val_pos def sqrt(val): print 'Entering sqrt method' import math return math.pow(val, (1.0/2)) [/code] is equivalent to [code=python] def sqrt(val): print 'Entering sqrt method' import math return math.pow(val, (1.0/2)) sqrt = is_val_pos(sqrt) [/code] This show that is_val_pos() is only called once after the definition of sqrt(), and then, … | |
Re: glob.glob() does not accept url arguments, read the documentation. If the site doesn't give you an url to list the directory, I don't think it can be done. | |
Re: [url=http://lmgtfy.com/?q=ATL_dsyreflect]The solution is here...[/url] |
The End.