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',
},]
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
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"
Is there an object that acts like array.array, yet can handle strings (or character arrays) as its data type?
It should be able to convert the string array to binary and back again, preferably with null terminated strings, however fixed length strings would be acceptable.
>>> my_array = stringarray(['foo', 'bar'])
>>> my_array.tostring()
'foo\0bar\0'
>>> re_read = stringarray('foo\0bar\0')
>>> re_read[:]
['foo', 'bar']
I will be using it with arrays that contain a couple million strings.
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.
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.
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!
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.
I would like to slice random letters from a string.
Given
s="howdy"
I would like to pick elements from 's' without replacement but keep the index number.
For example
>>> random.sample(s,len(s))
['w', 'h', 'o', 'd', 'y']
is close to what I want, but I would actually prefer something like
[('w',2), ('h',0), ('o',1), ('d',3), ('y',4)]
with letter-index pairs. This is important because the same letter appears in 's' more than once. ie) "letter" where 't' appears twice but I need to distinguish the first 't' from the 'second'.
Ideally I actually only need to pick letters as I need them but scrambling and calculating all the letters in a list (as shown above) is ok.
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
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 the following script which identifies lines in a file which I want to remove, based on an array but does not remove them.
What should I change?
sourcefile = "C:\\Python25\\PC_New.txt"
filename2 = "C:\\Python25\\PC_reduced.txt"
offending = ["Exception","Integer","RuntimeException"]
def fixup( filename ):
print "fixup ", filename
fin = open( filename )
fout = open( filename2 , "w")
for line in fin.readlines():
for item in offending:
print "got one",line
line = line.replace( item, "MUST DELETE" )
line=line.strip()
fout.write(line)
fin.close()
fout.close()
fixup(sourcefile)
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...
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"
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.
I have a huge file (with around 200k inputs). The inputs are in the form:
A B C D
B E F
C A B D
D
I am reading this file and storing it in a list as follows:
text = f.read().split('\n')
This splits the file whenever it sees a new line. Hence text is like follows:
[[A B C D] [B E F] [C A B D] [D]]
I have to now store these values in a dictionary where the key values are the first element from each list. i.e the keys will be A, B, C, D.
I am finding it difficult to enter the values as the remaining elements of the list. i.e the dictionary should look like:
{A: B C D; B: E F; C: A B D; D: 0}
I have done the following:
inlinkDict = {}
for doc in text:
adoc= doc.split(' ')
docid = adoc[0]
inlinkDict[docid] = inlinkDict.get(docid,0) + {I do not understand what to put in here}
Please help as to how should i add the values to my dictionary. It should be 0 if there are no elements in the list except for the one which will be the key value. Like in example for 0.
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?
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:/
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.
I been hitting a wall thats been keeping me from tinkering on a game.
class Damage:
def shortsword():
shortsword=randint(1,6)+1
shortsword=int(shortsword)
return shortsword
I been wanting this number to pop up as part of a message on print and then use the same number as part of another function to help with subtracting of health on the target. Though each time I grab this it is always going to change.