Hi folks,
I have a set
set(['booklet', '4 sheets', '48 sheets', '12 sheets'])
After sorting I want it to look like
4 sheets,
12 sheets,
48 sheets,
booklet
Any idea please
Is there a way to have any @property definitions passed through to a json serializer when serializing a Django model class?
example:
class FooBar(object.Model)
name = models.CharField(...)
@property
def foo(self):
return "My name is %s" %self.name
Want to serialize to:
[{
'name' : 'Test User',
'foo' : 'My name is Test User',
},]
How can I view and override the full definition for built in classes? I have seen the library docs but am looking for something more.
For e.g. is it possible to override the Array Class such that the base index starts from 1 instead of 0, or to override .sort() of list to a sorting algorithm of my own liking?
Let's say I have a list, and a filtering function. Using something like
>>> filter(lambda x: x > 10, [1,4,12,7,42])
[12, 42]
I can get the elements matching the criterion. Is there a function I could use that would output two lists, one of elements matching, one of the remaining elements? I could call the filter() function twice, but that's kinda ugly :)
Edit: the order of elements should be conserved, and I may have identical elements multiple times.
If I have a string
"this is a string"
How can I shorten it so that I only have one space between the words rather than multiple? (The number of white spaces is random)
"this is a string"
Hi,
My string is
mystring = "<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>"
My problem here is I have to search and get the total amount
test = re.search("(Indian Rupees)(\d{2})(?:\D|$)", mystring)
but my test give me None.
How can I get the values and values can be 10.00, 100.00, 1000.00
Thanks
I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def enter_users_into_dict(userlist):
newusr = {}
newusr.fromkeys(userlist, 0)
return newusr
ul = ['john', 'mabel']
nd = enter_users_into_dict(ul)
print nd
It returns an empty dict {} where I would expect {'john': 0, 'mabel': 0}.
It is probably very simply but I don't see the solution.
Hi there,
I have a funny problem I'd like to ask you guys ('n gals) about.
I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError.
This is what A.py looks like
import B
Now let's import A
>>> import A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/importtest/A.py", line 1, in <module>
import B
ImportError: No module named B
Alright, on to the problem. How can I know if this ImportError results from importing A or from some corrupt import inside A without looking at the error's string representation.
The difference is that either A is not there or does have incorrect import statements.
Hope you can help me out...
Cheers bb
I have a list lets say a=[[1,2],[3,4],[5,6]]. I want to add to each item in a the char 'a'.
when I use a=[x.append('a') for x in a] it return [None,None,None]. But if I use a1=[x.append('a') for x in a] then it do someting odd. a and not a1 is [[1,2,a],[3,4,a],[5,6,a]]. I don't understand why the first return [None, None, None] nor why the second works on a.
Given an array 'a' I would like to sort the array by columns "a.sort(axis=0)" do some stuff to the array and then undo the sort. By that I don't mean re sort but basically reversing how each element was moved. I assume argsort() is what I need but it is not clear to me how to sort an array with the results of argsort() or more importantly apply the reverse/inverse of argsort()
Here is a little more detail
I have an array a, shape(a) = rXc I need to sort each column
aargsort = a.argsort(axis=0) # May use this later
aSort = a.sort(axis=0)
now average each row
aSortRM = asort.mean(axis=1)
now replace each col in a row with the row mean.
is there a better way than this
aWithMeans = ones_like(a)
for ind in range(r) # r = number of rows
aWithMeans[ind]* aSortRM[ind]
Now I need to undo the sort I did in the first step. ????
I have this piece of code that finds words that begin with @ or #,
p = re.findall(r'@\w+|#\w+', str)
Now what irks me about this is repeating \w+. I am sure there is a way to do something like
p = re.findall(r'(@|#)\w+', str)
That will produce the same result but it doesn't, it instead returns only # and @. How can that regex be changed so that I am not repeating the \w+? This code comes close,
p = re.findall(r'((@|#)\w+)', str)
But it returns [('@many', '@'), ('@this', '@'), ('#tweet', '#')] (notice the extra '@', '@', and '#'.
I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n.
Each byte in the string is a single integer (1-byte) representing 0-255. So for each character in the string I want to convert it to an integer.
I can't figure out how to do this. Using ord doesn't seem to be on the right track...
class MyWriter:
def __init__(self, stdout):
self.stdout = stdout
self.dumps = []
def write(self, text):
self.stdout.write(smart_unicode(text).encode('cp1251'))
self.dumps.append(text)
def close(self):
self.stdout.close()
writer = MyWriter(sys.stdout)
save = sys.stdout
sys.stdout = writer
I use self.dumps list to store data obtained from prints. Is there a more convenient object for storing string lines in memory? Ideally I want dump it to one big string. I can get it like this "\n".join(self.dumps) from code above. May be it's better to just concatenate strings - self.dumps += text?
I have two models
class Weather(model.model):
region = models.ForeignKey(Region)
district = models.ForeignKey(District)
temp_max = models.IntegerField(blank=True, null=True, verbose_name='Max temperature (C)')
temp_min = models.IntegerField(blank=True, null=True, verbose_name='Min temperature (C)')
and
class Plan(model.model):
name = tinymce_models.HTMLField(blank=True, null=True)
region = models.ForeignKey(Region)
district = models.ForeignKey(District)
Provided for every region and district have unique row.
I want to combine the result so that i can get all the columns of both tables
These two Models are not related to each other.
'
I need to make the join like
join weather w on w.region = A.region and w.distric = A.district
so that result contains all the columns in everyobject like
obj.temp_max etc
Hi guys! So, I have a dictionary with almost 100,000 (key, values) pairs and the majority of the keys map to the same values. For example imagine something like that:
dict = {'a': 1, 'c': 2, 'b': 1, 'e': 2, 'd': 3, 'h': 1, 'j': 3}
What I want to do, is to reverse the dictionary so that each value in dict is going to be a key at the reverse_dict and is going to map to a list of all the dict.keys that used to map to that value at the dict. So based on the example above I would get:
reversed_dict = {1: ['a', 'b', 'h'], 2:['e', 'c'] , 3:['d', 'j']}
I came up with a solution that is very expensive and I would really want to hear any ideas more efficient than mine.
my expensive solution:
reversed_dict = {}
for value in dict.values():
reversed_dict[value] = []
for key in dict.keys():
if dict[key] == value:
if key not in reversed_dict[value]: reversed_dict[value].append(key)
Output >> reversed_dict = {1: ['a', 'b', 'h'], 2: ['c', 'e'], 3: ['d', 'j']}
I would really appreciate to hear any ideas better and more efficient than than mine.
Thanks!
Is there any possibility to copy variable by reference no matter if its int or class instance?
My goal is to have two lists of the same objects and when one changes, change is visible in second.
In other words i need pointers:/
Is there a way to get the timezone of the connecting user using Pylons, and to adjust the content before rendering accordingly? Or can this only be done by JS?
Thanks.
Suppose that I have two numpy arrays of the form
x = [[1,2]
[2,4]
[3,6]
[4,NaN]
[5,10]]
y = [[0,-5]
[1,0]
[2,5]
[5,20]
[6,25]]
is there an efficient way to merge them such that I have
xmy = [[0, NaN, -5 ]
[1, 2, 0 ]
[2, 4, 5 ]
[3, 6, NaN]
[4, NaN, NaN]
[5, 10, 20 ]
[6, NaN, 25 ]
I can implement a simple function using search to find the index but this is not elegant and potentially inefficient for a lot of arrays and large dimensions. Any pointer is appreciated.
is there a way that if the following class is created; I can grab a list of attributes that exist. (this class is just an bland example, it is not my task at hand)
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
a = new_class(2)
print(', '.join(a.SOMETHING))
* the attempt is that "multi, str" will print. the point here is that if a class object has attributes added at different parts of a script that I can grab a quick listing of the attributes which are defined.
Write two functions, called countSubStringMatch and countSubStringMatchRecursive that take two arguments, a key string and a target string. These functions iteratively and recursively count the number of instances of the key in the target string. You should complete definitions for
def countSubStringMatch(target,key):
and
def countSubStringMatchRecursive (target, key):
For the remaining problems, we are going to explore other substring matching ideas. These problems can be solved with either an iterative function or a recursive one. You are welcome to use either approach, though you may find iterative approaches more intuitive in these cases of matching linear structures.
Hello.
For my project I would be using the argparse library. My question is, how do I distribute it with my project. I am asking this because of the technicalities and legalities involved.
Do I just:
Put the argparse.py file along with
my project. That is, in the tar file for my project.
Create a package for it for my
distro?
Tell the user to install it himself?
Sorry for being such a noob, but I new to all this.
I have a dictionary:
D = { "foo" : "bar", "baz" : "bip" }
and I want to create new dictionary that has a copy of one of it's elements k. So if k = "baz":
R = { "baz" : "bip" }
what I'v got now is:
R = { k : D[k] }
But in my case k is a complex expression and I've got a whole stack of these. Caching k in a temporary looks about as ugly as the original option.
What I'm looking for is a better (cleaner) way to do this.
I have created some program for this.But printed a,b,c values are not correct.Please check this whether it is correct or not?
n=input("Enter the no.of McNuggets:")
a,b,c=0,0,0
count=0
for a in range(n):
if 6*a+9*b+20*c==n:
count=count+1
break
else:
for b in range(n):
if 6*a+9*b+20*c==n:
count=count+1
break
else:
for c in range(n):
if 6*a+9*b+20*c==n:
count=count+1
break
if count>0:
print "It is possible to buy exactly",n,"packs of McNuggetss",a,b,c
else:
print "It is not possible to buy"