title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How can I read an imported object's code?
39,936,673
<p>I don't know what attributes an object supports. How can I open up the module and figure out what's going on "under the hood"?</p> <p>For example, I want to figure out what attributes the <code>datetime</code> object from the <code>datetime</code> module has in its <code>__init__</code>:</p> <pre><code>import datetime curtime = datetime.datetime.now() print(curtime[0]) </code></pre> <p>But, since <code>datetime</code> has no <code>__getitem__</code> method, there must be a different way of accessing each part of the time (<code>day</code>, <code>month</code>, <code>year</code>, etc.)</p> <p>I have found (by trial and error) that you can do this:</p> <pre><code>datetime.datetime.now().time() datetime.datetime.now().date() </code></pre> <p>but I'm not sure what the proper name for what I'm doing here is, and how I can find other methods that belong to this object/class.</p>
-2
2016-10-08T19:46:52Z
39,936,722
<p>I find the <code>dir</code> function to be the most useful when dealing with unknown and undocumented objects (<a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>datetime</code> is well documented</a>, btw).</p> <p>But if it weren't documented:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; &gt;&gt;&gt; dir(datetime) ['MAXYEAR', 'MINYEAR', '__doc__', '__name__', '__package__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'tzinfo'] &gt;&gt;&gt; datetime.date &lt;type 'datetime.date'&gt; &gt;&gt;&gt; dir(datetime.date) ['__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year'] </code></pre> <p>and so on...</p>
0
2016-10-08T19:52:28Z
[ "python" ]
How can I read an imported object's code?
39,936,673
<p>I don't know what attributes an object supports. How can I open up the module and figure out what's going on "under the hood"?</p> <p>For example, I want to figure out what attributes the <code>datetime</code> object from the <code>datetime</code> module has in its <code>__init__</code>:</p> <pre><code>import datetime curtime = datetime.datetime.now() print(curtime[0]) </code></pre> <p>But, since <code>datetime</code> has no <code>__getitem__</code> method, there must be a different way of accessing each part of the time (<code>day</code>, <code>month</code>, <code>year</code>, etc.)</p> <p>I have found (by trial and error) that you can do this:</p> <pre><code>datetime.datetime.now().time() datetime.datetime.now().date() </code></pre> <p>but I'm not sure what the proper name for what I'm doing here is, and how I can find other methods that belong to this object/class.</p>
-2
2016-10-08T19:46:52Z
39,936,813
<p>In your terminal, type <code>pydoc (whatever)</code> and you should be able to see all the variables and functions it has. If it's undocumented, <code>dir([whatever])</code> is the way to go. In any situation, obviously Google. BTW, to clarify the terms in your question, <code>datetime</code> is a <em>module</em>. You have to understand modules, classes, and objects are different things. You can learn more about modules and the <code>dir()</code> function <a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">here</a>.</p>
0
2016-10-08T20:01:51Z
[ "python" ]
What is the equivalent of matlab's wkeep in Python?
39,936,676
<p>If I want to extract a vector of certain size from a matrix, how do I do it?</p> <p>I'm looking for something that does exactly the same thing as <a href="http://in.mathworks.com/help/wavelet/ref/wkeep.html" rel="nofollow"><code>wkeep</code></a> in matlab</p>
0
2016-10-08T19:47:30Z
39,936,959
<p>It turns out that a lot of the use-cases of <code>wkeep</code> can be written more idomatically:</p> <pre><code>X[1:3,1:4] # wkeep(X, [2, 3]) </code></pre> <p>If you don't actually need it to be centered, you could use:</p> <pre><code>X[:2, :4] # wkeep(X, [2, 3], 'l') X[-2:, -4:] # wkeep(X, [2, 3], 'r') </code></pre> <p>Or if the real reason you're using wkeep is to trim off a border:</p> <pre><code>X[2:-2,2:-2] # wkeep(X, size(X) - 2) </code></pre> <p><em>If you really want a direct translation</em> of <code>wkeep(X,L)</code>, here's what <code>wkeep</code> seems to do:</p> <pre><code># Matlab has this terrible habit of implementing general functions # in specific packages, and naming after only their specific use case. # let's pick a name that actually tells us what this does def centered_slice(X, L): L = np.asarray(L) shape = np.array(X.shape) # verify assumptions assert L.shape == (X.ndim,) assert ((0 &lt;= L) &amp; (L &lt;= shape)).all() # calculate start and end indices for each axis starts = (shape - L) // 2 stops = starts + L # convert to a single index idx = tuple(np.s_[a:b] for a, b in zip(starts, stops)) return X[idx] </code></pre> <p>So for example:</p> <pre><code>&gt;&gt;&gt; X = np.arange(20).reshape(4, 5) &gt;&gt;&gt; centered_slice(X, [2, 3]) array([[ 6, 7, 8], [11, 12, 13]]) </code></pre>
4
2016-10-08T20:18:46Z
[ "python", "matlab", "numpy" ]
How to compute a hash of a sqlite database file without causing harm
39,936,697
<p>I have a function like the following that I want to use to compute the hash of a sqlite database file, in order to compare it to the last backup I made to detect any changes.</p> <pre> def get_hash(file_path): # http://stackoverflow.com/a/3431838/1391717 hash_sha1 = hashlib.sha1 with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha1.update(chunk) return hash_sha1.hexdigest() </pre> <p>I plan on locking the database, so no one can write to it while I'm computing the hash. Is it possible for me to cause any harm while doing this?</p> <pre> // http://codereview.stackexchange.com/questions/78643/create-sqlite-backups connection = sqlite3.connect(database_file) cursor = connection.cursor() cursor.execute("begin immediate") db_hash = get_hash(args.database) </pre>
0
2016-10-08T19:49:55Z
39,938,696
<p>The sqlite3 database files, can and may be read by many different readers at the same time. There is no problem with concurrency in that respect with sqlite3. The problems which is native to sqlite3 concerns writing to the file, only one writer is allowed. </p> <p>So if you only read your fine. </p> <p>If you are planning to lock the database and succeed with that, while you compute the hash, you become a writer with exclusive access. </p>
0
2016-10-09T00:09:34Z
[ "python", "sqlite", "sqlite3" ]
how to view encrypted image as is without decryption
39,936,706
<pre><code>#encrypting an image using AES import binascii from Crypto.Cipher import AES def pad(s): return s + b"\0" * (AES.block_size - len(s) % AES.block_size) filename = 'path to input_image.jpg' with open(filename, 'rb') as f: content = f.read() #converting the jpg to hex, trimming whitespaces and padding. content = binascii.hexlify(content) binascii.a2b_hex(content.replace(' ', '')) content = pad(content) #16 byte key and IV #thank you stackoverflow.com obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456') ciphertext = obj.encrypt(content) #is it right to try and convert the garbled text to hex? ciphertext = binascii.hexlify(ciphertext) print ciphertext #decryption obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456') plaintext = obj2.decrypt(ciphertext) #content = content.encode('utf-8') print plaintext #the plaintext here matches the original hex input file as it should with open('path to - AESimageDecrypted.txt', 'wb') as g: g.write(plaintext) </code></pre> <p>My question is two fold, 1) how would i go about converting the encrypted file (which is garbled before hexlify) which is basically a text file of hex strings, back into an image? i'd like the output to be viewable as a jpg on any viewer. </p> <p>I've tried a few things out , came across Pillow, except i can't seem to grasp if it can do what i want. </p> <p>Any help would be appreciated thanks.</p> <p>PS: i want to try this with other ciphers too. so i think it'd be helpful if anyone can help clear out if this understanding is right:</p> <p>jpg -> convert to binary/hex -> encrypt -> garbled output -> convert to bin/hex -> convert to jpg</p> <p>2) is the above possible? and should they be converted to hex or bin? </p>
-1
2016-10-08T19:51:32Z
39,937,726
<p>The question here is how to display encrypted image as an image without decrypting it.</p> <p>The encrypted contents are not an image and cannot be unambiguously represented as an image. The best that can be done is to treat it as a bitmap, i.e. each binary value represents the intensity of some color at some coordinate.</p> <p>It seems logical to treat the data as 3 bytes per pixel: RGB RGB RGB...</p> <p>Images are 2D and encrypted data is just a list of bytes. Again, several options are valid. Let's say it is a square image (NxN pixels).</p> <p>To create the image, I would use <a href="https://python-pillow.org/" rel="nofollow">PIL / Pillow</a>:</p> <pre><code>from PIL import Image # calculate sizes num_bytes = len(cyphertext) num_pixels = int((num_bytes+2)/3) # 3 bytes per pixel W = H = int(math.ceil(num_pixels ** 0.5)) # W=H, such that everything fits in # fill the image with zeros, because probably len(imagedata) &lt; needed W*H*3 imagedata = cyphertext + '\0' * (W*H*3 - len(cyphertext)) image = Image.fromstring('RGB', (W, H), imagedata) # create image image.save('C:\\Temp\\image.bmp') # save to a file </code></pre> <p>BTW, this can be done with absolutely any string of bytes, not just encrypted images.</p>
2
2016-10-08T21:51:11Z
[ "python", "cryptography", "pillow", "pycrypto" ]
My Code failed with error "AttributeError: 'NoneType' object has no attribute 'add'"
39,936,831
<p>I have this pieces of code that crawled a site, extract all the needed url from the site, format the url into required format, then at a point where i am suppose to add it to a set for further proccessing. I encounter the following error, "AttributeError: 'NoneType' object has no attribute 'add'" The part of the code is as follow</p> <pre><code>class Finder(bs4.BeautifulSoup): def __init__(self, m, page_url): super().__init__(m, 'html.parser') self.page_url = page_url self.pdf_url_links = set() def handle_starttag(self, name, namespace, nsprefix, attrs): if name == 'a': for (attributes, value) in attrs.items(): if ('.pdf&amp;') not in value: pass else: list_of_links = search_queue_url(value) print(list_of_links) </code></pre> <p>I got the following url on my screen when I print the variable 'list_of_links' above:</p> <pre><code>https://julianoliver.com/share/free-science-books/basic_math_and_algebra.pdf https://www.math.ksu.edu/~dbski/writings/further.pdf http://www.math.harvard.edu/~shlomo/docs/Advanced_Calculus.pdf http://www.textbooksonline.tn.nic.in/Books/Std10/Std10-Maths-EM-1.pdf http://www.corestandards.org/wp-content/uploads/Math_Standards.pdf https://www.ets.org/s/gre/pdf/gre_math_review.pdf https://www.math.ust.hk/~machas/differential-equations.pdf </code></pre> <p>However, when I attempt to add each of the above url to my set with below code, </p> <pre><code>self.pdf_url_links.add(list_of_links) </code></pre> <p>I got the following error bellow,</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'add' </code></pre> <p>Traceback (most recent call last):</p> <pre><code> File "C:\Projects\BookScapie\BookScrapie\BookScrapie\link_finders.py", line 7, in __init__ super().__init__(m, 'html.parser') File "C:\python-3.5.1.amd64\lib\site-packages\bs4\__init__.py", line 228, in __init__ self._feed() File "C:\python-3.5.1.amd64\lib\site-packages\bs4\__init__.py", line 289, in _feed self.builder.feed(self.markup) File "C:\python-3.5.1.amd64\lib\site-packages\bs4\builder\_htmlparser.py", line 167, in feed parser.feed(markup) File "C:\python-3.5.1.amd64\lib\html\parser.py", line 111, in feed self.goahead(0) File "C:\python-3.5.1.amd64\lib\html\parser.py", line 171, in goahead k = self.parse_starttag(i) File "C:\python-3.5.1.amd64\lib\html\parser.py", line 345, in parse_starttag self.handle_starttag(tag, attrs) File "C:\python-3.5.1.amd64\lib\site-packages\bs4\builder\_htmlparser.py", line 65, in handle_starttag self.soup.handle_starttag(name, None, None, attr_dict) File "C:\Projects\BookScapie\BookScrapie\BookScrapie\link_finders.py", line 22, in handle_starttag self.pdf_url_links.add(list_of_links) </code></pre> <p>AttributeError: 'NoneType' object has no attribute 'add'</p> <p>I will appreciate any good ideas on what I am doing right. I am using python 3.5</p>
-2
2016-10-08T20:03:20Z
39,954,813
<p>Do not inherit from <code>BeautifulSoup</code>; rather, use aggregation and its query interface instead! The <code>BeautifulSoup.__init__</code> will call your overridden <code>handle_starttag</code>, before <code>self.pdf_url_links</code> is initialized.</p> <p>The <code>BeautifulSoup</code> class has a <code>__getattr__</code> implementation that does <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigating-using-tag-names" rel="nofollow">sub-tag navigation</a>, returning <code>None</code> if no match found; in this case, there is no <code>&lt;pdf_url_links&gt;</code> tag in the soup, so <code>self.pdf_url_links</code> returns <code>None</code>.</p> <hr> <p>Instead try something like</p> <pre><code>def find_links(m): soup = bs4.BeautifulSoup(m, 'html.parser') links = set() for a in soup.find_all('a'): href = a.get('href') if href and '.pdf&amp;' in href: links.add(href) return links </code></pre>
3
2016-10-10T09:05:47Z
[ "python" ]
My Code failed with error "AttributeError: 'NoneType' object has no attribute 'add'"
39,936,831
<p>I have this pieces of code that crawled a site, extract all the needed url from the site, format the url into required format, then at a point where i am suppose to add it to a set for further proccessing. I encounter the following error, "AttributeError: 'NoneType' object has no attribute 'add'" The part of the code is as follow</p> <pre><code>class Finder(bs4.BeautifulSoup): def __init__(self, m, page_url): super().__init__(m, 'html.parser') self.page_url = page_url self.pdf_url_links = set() def handle_starttag(self, name, namespace, nsprefix, attrs): if name == 'a': for (attributes, value) in attrs.items(): if ('.pdf&amp;') not in value: pass else: list_of_links = search_queue_url(value) print(list_of_links) </code></pre> <p>I got the following url on my screen when I print the variable 'list_of_links' above:</p> <pre><code>https://julianoliver.com/share/free-science-books/basic_math_and_algebra.pdf https://www.math.ksu.edu/~dbski/writings/further.pdf http://www.math.harvard.edu/~shlomo/docs/Advanced_Calculus.pdf http://www.textbooksonline.tn.nic.in/Books/Std10/Std10-Maths-EM-1.pdf http://www.corestandards.org/wp-content/uploads/Math_Standards.pdf https://www.ets.org/s/gre/pdf/gre_math_review.pdf https://www.math.ust.hk/~machas/differential-equations.pdf </code></pre> <p>However, when I attempt to add each of the above url to my set with below code, </p> <pre><code>self.pdf_url_links.add(list_of_links) </code></pre> <p>I got the following error bellow,</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'add' </code></pre> <p>Traceback (most recent call last):</p> <pre><code> File "C:\Projects\BookScapie\BookScrapie\BookScrapie\link_finders.py", line 7, in __init__ super().__init__(m, 'html.parser') File "C:\python-3.5.1.amd64\lib\site-packages\bs4\__init__.py", line 228, in __init__ self._feed() File "C:\python-3.5.1.amd64\lib\site-packages\bs4\__init__.py", line 289, in _feed self.builder.feed(self.markup) File "C:\python-3.5.1.amd64\lib\site-packages\bs4\builder\_htmlparser.py", line 167, in feed parser.feed(markup) File "C:\python-3.5.1.amd64\lib\html\parser.py", line 111, in feed self.goahead(0) File "C:\python-3.5.1.amd64\lib\html\parser.py", line 171, in goahead k = self.parse_starttag(i) File "C:\python-3.5.1.amd64\lib\html\parser.py", line 345, in parse_starttag self.handle_starttag(tag, attrs) File "C:\python-3.5.1.amd64\lib\site-packages\bs4\builder\_htmlparser.py", line 65, in handle_starttag self.soup.handle_starttag(name, None, None, attr_dict) File "C:\Projects\BookScapie\BookScrapie\BookScrapie\link_finders.py", line 22, in handle_starttag self.pdf_url_links.add(list_of_links) </code></pre> <p>AttributeError: 'NoneType' object has no attribute 'add'</p> <p>I will appreciate any good ideas on what I am doing right. I am using python 3.5</p>
-2
2016-10-08T20:03:20Z
39,982,020
<p>The problem was caused by the way BeautifulSoup constructor works.</p> <pre><code>class Finder(bs4.BeautifulSoup): def __init__(self, m, page_url): super().__init__(m, 'html.parser') self.page_url = page_url self.pdf_url_links = set() </code></pre> <p>As soon as <code>BeautifulSoup.__init__</code> is called, the parsing begins, which eventually calls <code>handle_starttag</code> method.</p> <p>Here, the overridden version of <code>handle_starttag</code> tried to access <code>self.pdf_url_links</code>, which was not initialized.</p> <p>The solution is to initialize everything that is needed for parsing before calling the super constructor:</p> <pre><code> def __init__(self, m, page_url): self.page_url = page_url self.pdf_url_links = set() super().__init__(m, 'html.parser') </code></pre>
1
2016-10-11T16:21:01Z
[ "python" ]
Matplotlib "pick_event" not working in embedded graph with FigureCanvasTkAgg
39,936,869
<p>I'm trying to handle some events to perform user interactions with embedded subplots into a Tkinter frame. Like in this <a href="http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html" rel="nofollow">example</a></p> <p>Works fine with "key_press_event" and "button_press_event", but does not work with "pick_event".</p> <p>I modified that example from the link, just adding the following piece of code after the <code>mpl_connect</code> calling:</p> <pre><code>def on_button_press(event): print('you pressed mouse button') canvas.mpl_connect('button_press_event', on_button_press) def on_pick(event): print('you picked:',event.artist) canvas.mpl_connect('pick_event', on_pick) </code></pre> <p>Why "pick_event" doesn't work into embedded graphs? And how do get it to work?</p> <p>My configurations detailed:</p> <ul> <li>Windows 10</li> <li>Python 3.5 (conda version)</li> <li>Matplotlib 1.5.3 installed via pip</li> </ul> <p>Thanks in advance!</p>
0
2016-10-08T20:08:02Z
39,938,402
<p>Well, I solved it...</p> <p>Most events we just need to use <code>mpl_connect</code> method to the magic happen. My mistake is that I didn't notice that we need to say explictly that our plot is "pickable" putting a argument <code>picker=True</code> to only triggers the event if clicked exacly into the artist, and <code>picker=x</code> where <code>x</code> is an integer that is the pixel tolerance for the trigger. So beyond the changes I inserted for pick in the question, we should replace</p> <p><code>a.plot(t, s)</code> for <code>a.plot(t, s,picker=True)</code> or <code>a.plot(t, s,picker=10)</code>, e.g.</p>
0
2016-10-08T23:20:48Z
[ "python", "events", "matplotlib", "tkinter" ]
Stepping into RFE and getting 'DataFrame object is not callable" error
39,936,914
<p>I'm trying to use RFE for the first time and banging my head against a "DataFrame object is not callable" error.</p> <p>Here is my code</p> <pre><code>X, y = df5(n_samples=875, n_features=10, random_state=0) estimator = SVR(kernel="linear") selector = RFE(LinearRegression, step=1, cv=5) selector = selector.fit(X, y) df5([ True, True, True, True, True, False, False, False, False, False], dtype=bool) selector.ranking_ df5([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) </code></pre> <p>I'm looking at a dataset with 49 Features and the output I'm looking for is which of these features should be kept and which kicked out.</p> <p>Bonus points if anyone can help me figure out how to get this into an RFECV!</p>
0
2016-10-08T20:13:49Z
39,971,197
<p>If you want select columns first figure out the information about your dataframe then select required features.</p> <pre><code># the next 2 lines is to initialize DataFrame object (just for the example) &gt;&gt;&gt; from pandas import DataFrame &gt;&gt;&gt; df = DataFrame.from_dict({'one': range(10), 'two': range(10, 0, -1), 'three': [3 for x in range(10)]}) # now figure out what columns you df has: &gt;&gt;&gt; df.head() one three two 0 0 3 10 1 1 3 9 2 2 3 8 3 3 3 7 4 4 3 6 5 5 3 5 6 6 3 4 7 7 3 3 8 8 3 2 9 9 3 1 # Now you can slice specific columns (features in your case): &gt;&gt;&gt; df[['one', 'two']] one two 0 0 10 1 1 9 2 2 8 3 3 7 4 4 6 5 5 5 6 6 4 7 7 3 8 8 2 9 9 1 </code></pre> <p>Are your feature names numerical? I'm not sure. Check it.</p>
0
2016-10-11T05:55:04Z
[ "python", "scikit-learn", "rfe" ]
Python 3 permutations Scrabble
39,936,976
<p>I'm struggling a bit with an effective way of debugging Python, and the consequent lack of understanding and optimization.</p> <p>I'm in the process of writing a Scrabble game in Python as an experiment, and I suspect I'm going about it all wrong. Namely, I'm failing to understand how to handle the blank tiles (represented by question marks below). I've bungled the code as follows:</p> <pre><code>import itertools import string rack = 'rstlena??' blank_count = rack.count('?') letters = rack.split(',') word_set = set() if blank_count &gt; 0: rack = rack.replace('?', '') if blank_count == 1: for l in string.ascii_lowercase: letters.append(rack + l) elif blank_count == 2: for l in string.ascii_lowercase: letters.append(rack + l + l) for l_combo in rack: for i in range(3, 9): for permutation in itertools.permutations(l_combo, i): word_to_check = ''.join(permutation) if word_to_check in word_list: # word_list is some dictionary word_set.add(word_to_check) </code></pre> <p>...</p> <p>It works when there's one blank, but with two it just adds the same letter and produces undesired results (obviously).</p> <p>I apologize in advance for the ugly code I've subjected you to cringe at.</p>
0
2016-10-08T20:21:08Z
39,937,280
<p>This should work, and be acceptably fast. I tried to comment the tricky parts, do not hesitate to ask if there are some bits of the code you do not understand. </p> <pre><code>import itertools import string import numpy as np #takes a list of words as input ['door', 'chair', 'wall'], and returns the words alphabetically sorted [['door', 'door'], ['achir', 'chair'], ['allw', 'wall']] def sortWordList(word_list): return np.array([["".join(sorted(word)), word] for word in word_list]) #recursive function to get all unordered n-letter subsets of `letters`, without repetition. NLetterSubsets(2, "fly") == ["fl", "fy", "ly"]; NLetterSubsets(2, "foo") == ["fo", "fo", "oo"] def NLetterSubsets(n, letters): if n == len(letters): return [letters] if n &gt; len(letters) or len(letters) == 0: return [] return [letters[0] + x for x in NLetterSubsets(n-1, letters[1:])] + NLetterSubsets(n, letters[1:]) #loads word_list from a newline-separated file def loadWordList(filename): with open(filename, 'r') as f: return [line.rstrip('\n') for line in f] word_list = loadWordList('words.txt') word_list = sortWordList(word_list) print(word_list) rack = 'trackable' blank_count = rack.count('?') if blank_count: rack = rack.replace('?','') word_set = set() #possible letters is the list of all possible values taken by the blank(s) possibleLetters = [''] if blank_count &gt;= 1: possibleLetters += [l for l in string.ascii_lowercase] if blank_count == 2: possibleLetters += [l+m for l in string.ascii_lowercase for m in string.ascii_lowercase] for blanks in possibleLetters: for i in range(3-len(blanks), 9-len(blanks)): #gets a subset of letters from rack, to which we will add the blank values to form a word of length in range(3,9) for setOfLetter in NLetterSubsets(i-blank_count, rack): sortedWordToSearchFor = ''.join(sorted(setOfLetter + blanks)) #if the sorted list of letters we have is also present in the word_set, then take the associated word for index in np.where(word_list[:,0] == sortedWordToSearchFor)[0]: word_set.add(word_list[index][1]) print(word_set) </code></pre>
0
2016-10-08T20:55:56Z
[ "python", "python-3.x" ]
Pandas plot dataframe by index, how it works?
39,936,983
<p>Given the data:</p> <pre><code>Column1; Column2; Column3 1; 4; 6 2; 2; 6 3; 3; 8 4; 1; 1 5; 4; 2 </code></pre> <p>With the following code I get the following graphic:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(0,0) plt.savefig('fig0.png') </code></pre> <p><a href="http://i.stack.imgur.com/tEQ6A.png" rel="nofollow"><img src="http://i.stack.imgur.com/tEQ6A.png" alt="enter image description here"></a></p> <p>And, with the following code I get the following graphic:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(0,1) plt.savefig('fig1.png') </code></pre> <p><a href="http://i.stack.imgur.com/dAtwA.png" rel="nofollow"><img src="http://i.stack.imgur.com/dAtwA.png" alt="enter image description here"></a></p> <p>What's the logic in <code>df.plot(m,n)</code>? Let's say I want to plot <code>Column2 X Column3</code> what's <code>m</code> and <code>n</code>(<code>df.plot(2,3)</code>) ? </p>
0
2016-10-08T20:21:44Z
39,937,159
<p>When you specify <code>x</code> and <code>y</code> by ordinal position, you'll reach <a href="https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py#L2449" rel="nofollow">this bit of code</a> when calling <code>df.plot(x, y)</code>:</p> <pre><code> if isinstance(data, DataFrame): if x is not None: if com.is_integer(x) and not data.columns.holds_integer(): x = data.columns[x] data = data.set_index(x) </code></pre> <p>This converts <code>x</code> from an ordinal value (e.g. 0) to a column label name (e.g. <code>'Column1'</code>). Notice that <code>data.set_index(x)</code> is called. So if <code>x</code> equals 0, the first column gets set as the index. Next, when <code>y</code> is similarly converted into a column label, the 0th column is now <code>'Column2'</code>. Hence, <code>df.plot(0,0)</code> plots Column2 versus Column1.</p> <p>To plot Column3 versus Column2 you would therefore use <code>df.plot(1,1)</code>, since <code>data.columns[1]</code> is <code>'Column2'</code>, and then once it is set as the index, <code>data.columns[1]</code> is then <code>'Column3'</code>.</p> <hr> <p>As <a href="http://stackoverflow.com/questions/39936983/pandas-plot-dataframe-by-index-how-it-works/39937159#comment67156153_39936983">BrenBarn points out</a> in the comments, a much less error-prone way of specifying the columns is by label name. Or, if you really want to use ordinal values, pass them to <code>df.columns</code> explicitly:</p> <pre><code>df.plot(x=df.columns[x], y=df.columns[y]) </code></pre> <p>Since <code>df.columns[x]</code> and <code>df.columns[y]</code> are column label names, their meaning is not affected by <code>set_index</code>, so there is less confusion.</p>
1
2016-10-08T20:40:41Z
[ "python", "python-2.7", "pandas", "matplotlib", "dataframe" ]
Pandas plot dataframe by index, how it works?
39,936,983
<p>Given the data:</p> <pre><code>Column1; Column2; Column3 1; 4; 6 2; 2; 6 3; 3; 8 4; 1; 1 5; 4; 2 </code></pre> <p>With the following code I get the following graphic:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(0,0) plt.savefig('fig0.png') </code></pre> <p><a href="http://i.stack.imgur.com/tEQ6A.png" rel="nofollow"><img src="http://i.stack.imgur.com/tEQ6A.png" alt="enter image description here"></a></p> <p>And, with the following code I get the following graphic:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(0,1) plt.savefig('fig1.png') </code></pre> <p><a href="http://i.stack.imgur.com/dAtwA.png" rel="nofollow"><img src="http://i.stack.imgur.com/dAtwA.png" alt="enter image description here"></a></p> <p>What's the logic in <code>df.plot(m,n)</code>? Let's say I want to plot <code>Column2 X Column3</code> what's <code>m</code> and <code>n</code>(<code>df.plot(2,3)</code>) ? </p>
0
2016-10-08T20:21:44Z
39,937,162
<p>Whatever column is used as <code>x</code> is removed from the DataFrame before <code>y</code> is looked up. (Or, more technically, <code>x</code> is set as the index, which means its no longer available as a column.) So if you do <code>.plot(x=0, y=0)</code>, the <code>x=0</code> means "use the first positional column", and the <code>y=0</code> means "use whatever will be the first positional column after the x column is removed".</p> <p>Needless to say this could get confusing, because whether <code>y</code> shifts in position depends on whether it was before or after <code>x</code>. So if you do <code>.plot(x=3, y=1)</code>, then y really is column #1, but if you do <code>.plot(x=0, y=1)</code>, then y is actually column #2 (it becomes number 1 after column 0 is removed).</p>
3
2016-10-08T20:40:47Z
[ "python", "python-2.7", "pandas", "matplotlib", "dataframe" ]
Pandas plot dataframe by index, how it works?
39,936,983
<p>Given the data:</p> <pre><code>Column1; Column2; Column3 1; 4; 6 2; 2; 6 3; 3; 8 4; 1; 1 5; 4; 2 </code></pre> <p>With the following code I get the following graphic:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(0,0) plt.savefig('fig0.png') </code></pre> <p><a href="http://i.stack.imgur.com/tEQ6A.png" rel="nofollow"><img src="http://i.stack.imgur.com/tEQ6A.png" alt="enter image description here"></a></p> <p>And, with the following code I get the following graphic:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(0,1) plt.savefig('fig1.png') </code></pre> <p><a href="http://i.stack.imgur.com/dAtwA.png" rel="nofollow"><img src="http://i.stack.imgur.com/dAtwA.png" alt="enter image description here"></a></p> <p>What's the logic in <code>df.plot(m,n)</code>? Let's say I want to plot <code>Column2 X Column3</code> what's <code>m</code> and <code>n</code>(<code>df.plot(2,3)</code>) ? </p>
0
2016-10-08T20:21:44Z
39,937,408
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">documentation</a>, you can define <em>m</em> and <em>n</em> (<em>x</em> and <em>y</em> in the documentation) like this:</p> <pre><code>df.plot(df.columns[1],df.columns[2]) </code></pre> <ul> <li>'m' should be -> <code>df.columns[1]</code> ,i.e., the column name of the position 1</li> <li>'n' should be -> <code>df.columns[2]</code> ,i.e., the column name of the position 2</li> </ul> <p>If you want to use the positions, would be:</p> <pre><code>df.plot(1,1) </code></pre> <p>The logic using position is: when we put <em>1</em> in the horizontal axis, this column is removed from the options for the vertical axis, so there is only two options available (with new indexes). Thats why <code>df.plot(0,0)</code> actually sets first and the next column as the data and <code>df.plot(1,1)</code> uses the second and last columns. I didn't found it in the documentation, I discovered it testing.</p> <p>I think the idea is: makes no sense plot the same columns in axis x and y, so the first column given is not available for the other axis. I hope it help! =)</p> <p><em>PS:It will plot in a weird zoom and position, but if you zoom out and move through the plot you will confirm that the values matches with the data of each column</em></p>
1
2016-10-08T21:08:34Z
[ "python", "python-2.7", "pandas", "matplotlib", "dataframe" ]
Is aiopg supprted for python 3.6 now?
39,937,084
<p>Today I tried to use new version of Python (3.6). I installed <code>aiopg</code> by pip (via PyCharm interpreter section tool). And after I tried to import <code>aiopg</code>, exception was happend:</p> <pre><code>from aiopg.sa import create_engine File "C:\Python36\lib\site-packages\aiopg\__init__.py", line 5, in &lt;module&gt; from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT File "C:\Python36\lib\site-packages\aiopg\connection.py", line 4, in &lt;module&gt; import fcntl ModuleNotFoundError: No module named 'fcntl' </code></pre> <p>What is <code>fcntl</code>? It's linux python native module? In any case it does not work. Any solutions?</p>
1
2016-10-08T20:32:03Z
39,944,760
<p><code>aiopg==0.11</code> has a regression but brand new <code>aiopg==0.12</code> should work on Windows.</p>
1
2016-10-09T14:34:04Z
[ "python", "python-asyncio" ]
Seaborn boxplot: TypeError: unsupported operand type(s) for /: 'str' and 'int'
39,937,140
<p>I try to make vertical seaborn boxplot like this</p> <pre><code>import pandas as pd df = pd.DataFrame({'a' : ['a', 'b' , 'b', 'a'], 'b' : [5, 6, 4, 3] }) import seaborn as sns import matplotlib.pylab as plt %matplotlib inline sns.boxplot( x= "b",y="a",data=df ) </code></pre> <p>i get </p> <p><a href="http://i.stack.imgur.com/7mzYW.png" rel="nofollow"><img src="http://i.stack.imgur.com/7mzYW.png" alt="enter image description here"></a></p> <p>i write orient </p> <pre><code>sns.boxplot( x= "c",y="a",data=df , orient = "v") </code></pre> <p>and get</p> <pre><code>TypeError: unsupported operand type(s) for /: 'str' and 'int' </code></pre> <p>but </p> <pre><code>sns.boxplot( x= "c",y="a",data=df , orient = "h") </code></pre> <p>works coreect! what's wrong?</p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-16-5291a1613328&gt; in &lt;module&gt;() ----&gt; 1 sns.boxplot( x= "b",y="a",data=df , orient = "v") C:\Program Files\Anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, fliersize, linewidth, whis, notch, ax, **kwargs) 2179 kwargs.update(dict(whis=whis, notch=notch)) 2180 -&gt; 2181 plotter.plot(ax, kwargs) 2182 return ax 2183 C:\Program Files\Anaconda3\lib\site-packages\seaborn\categorical.py in plot(self, ax, boxplot_kws) 526 def plot(self, ax, boxplot_kws): 527 """Make the plot.""" --&gt; 528 self.draw_boxplot(ax, boxplot_kws) 529 self.annotate_axes(ax) 530 if self.orient == "h": C:\Program Files\Anaconda3\lib\site-packages\seaborn\categorical.py in draw_boxplot(self, ax, kws) 463 positions=[i], 464 widths=self.width, --&gt; 465 **kws) 466 color = self.colors[i] 467 self.restyle_boxplot(artist_dict, color, props) C:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1816 warnings.warn(msg % (label_namer, func.__name__), 1817 RuntimeWarning, stacklevel=2) -&gt; 1818 return func(ax, *args, **kwargs) 1819 pre_doc = inner.__doc__ 1820 if pre_doc is None: C:\Program Files\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in boxplot(self, x, notch, sym, vert, whis, positions, widths, patch_artist, bootstrap, usermedians, conf_intervals, meanline, showmeans, showcaps, showbox, showfliers, boxprops, labels, flierprops, medianprops, meanprops, capprops, whiskerprops, manage_xticks, autorange) 3172 bootstrap = rcParams['boxplot.bootstrap'] 3173 bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap, -&gt; 3174 labels=labels, autorange=autorange) 3175 if notch is None: 3176 notch = rcParams['boxplot.notch'] C:\Program Files\Anaconda3\lib\site-packages\matplotlib\cbook.py in boxplot_stats(X, whis, bootstrap, labels, autorange) 2036 2037 # arithmetic mean -&gt; 2038 stats['mean'] = np.mean(x) 2039 2040 # medians and quartiles C:\Program Files\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in mean(a, axis, dtype, out, keepdims) 2883 2884 return _methods._mean(a, axis=axis, dtype=dtype, -&gt; 2885 out=out, keepdims=keepdims) 2886 2887 C:\Program Files\Anaconda3\lib\site-packages\numpy\core\_methods.py in _mean(a, axis, dtype, out, keepdims) 70 ret = ret.dtype.type(ret / rcount) 71 else: ---&gt; 72 ret = ret / rcount 73 74 return ret TypeError: unsupported operand type(s) for /: 'str' and 'int' </code></pre>
1
2016-10-08T20:37:52Z
39,937,451
<p>For seaborn's boxplots it is important to keep an eye on the x-axis and y-axis assignments, when switching between horizontal and vertical alignment:</p> <pre><code>%matplotlib inline import pandas as pd import seaborn as sns df = pd.DataFrame({'a' : ['a', 'b' , 'b', 'a'], 'b' : [5, 6, 4, 3] }) # horizontal boxplots sns.boxplot(x="b", y="a", data=df, orient='h') # vertical boxplots sns.boxplot(x="a", y="b", data=df, orient='v') </code></pre> <p>Mixing up the columns will cause seaborn to try to calculate the summary statistics of the boxes on categorial data, which is bound to fail.</p>
2
2016-10-08T21:14:38Z
[ "python", "seaborn" ]
What's the most efficient way to find factors in a list?
39,937,160
<h2>What I'm looking to do:</h2> <p>I need to make a function that, given a list of positive integers (there can be duplicate integers), counts all triples (in the list) in which the third number is a multiple of the second and the second is a multiple of the first:</p> <p>(The same number cannot be used twice in one triple, but can be used by all other triples)</p> <p>For example, <code>[3, 6, 18]</code> is one because <code>18</code> goes evenly into <code>6</code> which goes evenly into <code>3</code>.</p> <p>So given <code>[1, 2, 3, 4, 5, 6]</code> it should find:</p> <pre><code>[1, 2, 4] [1, 2, 6] [1, 3, 6] </code></pre> <p>and return <code>3</code> (the number of triples it found)</p> <h2>What I've tried:</h2> <p>I made a couple of functions that work but are not efficient enough. Is there some math concept I don't know about that would help me find these triples faster? A module with a function that does better? I don't know what to search for...</p> <pre><code>def foo(q): l = sorted(q) ln = range(len(l)) for x in ln: if len(l[x:]) &gt; 1: for y in ln[x + 1:]: if (len(l[y:]) &gt; 0) and (l[y] % l[x] == 0): for z in ln[y + 1:]: if l[z] % l[y] == 0: ans += 1 return ans </code></pre> <p>This one is a bit faster:</p> <pre><code>def bar(q): l = sorted(q) ans = 0 for x2, x in enumerate(l): pool = l[x2 + 1:] if len(pool) &gt; 1: for y2, y in enumerate(pool): pool2 = pool[y2 + 1:] if pool2 and (y % x == 0): for z in pool2: if z % y == 0: ans += 1 return ans </code></pre> <p>Here's what I've come up with with help from y'all but I must be doing something wrong because it get's the wrong answer (it's really fast though):</p> <pre><code>def function4(numbers): ans = 0 num_dict = {} index = 0 for x in numbers: index += 1 num_dict[x] = [y for y in numbers[index:] if y % x == 0] for x in numbers: for y in num_dict[x]: for z in num_dict[y]: print(x, y, z) ans += 1 return ans </code></pre> <p>(<code>39889</code> instead of <code>40888</code>) - oh, I accidentally made the index var start at 1 instead of 0. It works now.</p> <h1>Final Edit</h1> <p>I've found the best way to find the number of triples by reevaluating what I needed it to do. This method doesn't actually find the triples, it just counts them.</p> <pre><code>def foo(l): llen = len(l) total = 0 cache = {} for i in range(llen): cache[i] = 0 for x in range(llen): for y in range(x + 1, llen): if l[y] % l[x] == 0: cache[y] += 1 total += cache[x] return total </code></pre> <p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p> <pre><code>def bar(l): list_length = len(l) total_triples = 0 cache = {} for i in range(list_length): cache[i] = 0 for x in range(list_length): print("\n\nfor index[{}]: {}".format(x, l[x])) for y in range(x + 1, list_length): print("\n\ttry index[{}]: {}".format(y, l[y])) if l[y] % l[x] == 0: print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x])) cache[y] += 1 total_triples += cache[x] print("\t\tcache[{0}] is now {1}".format(y, cache[y])) print("\t\tcount is now {}".format(total_triples)) print("\t\t(+{} from cache[{}])".format(cache[x], x)) else: print("\n\t\tfalse") print("\ntotal number of triples:", total_triples) </code></pre>
4
2016-10-08T20:40:43Z
39,937,284
<p>Right now your algorithm has O(N^3) running time, meaning that every time you double the length of the initial list the running time goes up by 8 times.</p> <p>In the worst case, you cannot improve this. For example, if your numbers are all successive powers of 2, meaning that every number divides every number grater than it, then every triple of numbers is a valid solution so just to print out all the solutions is going to be just as slow as what you are doing now.</p> <p>If you have a lower "density" of numbers that divide other numbers, one thing you can do to speed things up is to search for pairs of numbers instead of triples. This will take time that is only O(N^2), meaning the running time goes up by 4 times when you double the length of the input list. Once you have a list of pairs of numbers you can use it to build a list of triples.</p> <pre><code># For simplicity, I assume that a number can't occur more than once in the list. # You will need to tweak this algorithm to be able to deal with duplicates. # this dictionary will map each number `n` to the list of other numbers # that appear on the list that are multiples of `n`. multiples = {} for n in numbers: multiples[n] = [] # Going through each combination takes time O(N^2) for x in numbers: for y in numbers: if x != y and y % x == 0: multiples[x].append(y) # The speed on this last step will depend on how many numbers # are multiples of other numbers. In the worst case this will # be just as slow as your current algoritm. In the fastest case # (when no numbers divide other numbers) then it will be just a # O(N) scan for the outermost loop. for x in numbers: for y in multiples[x]: for z in multiples[y]: print(x,y,z) </code></pre> <p>There might be even faster algorithms, that also take advantage of algebraic properties of division but in your case I think a O(N^2) is probably going to be fast enough.</p>
3
2016-10-08T20:56:33Z
[ "python", "algorithm" ]
What's the most efficient way to find factors in a list?
39,937,160
<h2>What I'm looking to do:</h2> <p>I need to make a function that, given a list of positive integers (there can be duplicate integers), counts all triples (in the list) in which the third number is a multiple of the second and the second is a multiple of the first:</p> <p>(The same number cannot be used twice in one triple, but can be used by all other triples)</p> <p>For example, <code>[3, 6, 18]</code> is one because <code>18</code> goes evenly into <code>6</code> which goes evenly into <code>3</code>.</p> <p>So given <code>[1, 2, 3, 4, 5, 6]</code> it should find:</p> <pre><code>[1, 2, 4] [1, 2, 6] [1, 3, 6] </code></pre> <p>and return <code>3</code> (the number of triples it found)</p> <h2>What I've tried:</h2> <p>I made a couple of functions that work but are not efficient enough. Is there some math concept I don't know about that would help me find these triples faster? A module with a function that does better? I don't know what to search for...</p> <pre><code>def foo(q): l = sorted(q) ln = range(len(l)) for x in ln: if len(l[x:]) &gt; 1: for y in ln[x + 1:]: if (len(l[y:]) &gt; 0) and (l[y] % l[x] == 0): for z in ln[y + 1:]: if l[z] % l[y] == 0: ans += 1 return ans </code></pre> <p>This one is a bit faster:</p> <pre><code>def bar(q): l = sorted(q) ans = 0 for x2, x in enumerate(l): pool = l[x2 + 1:] if len(pool) &gt; 1: for y2, y in enumerate(pool): pool2 = pool[y2 + 1:] if pool2 and (y % x == 0): for z in pool2: if z % y == 0: ans += 1 return ans </code></pre> <p>Here's what I've come up with with help from y'all but I must be doing something wrong because it get's the wrong answer (it's really fast though):</p> <pre><code>def function4(numbers): ans = 0 num_dict = {} index = 0 for x in numbers: index += 1 num_dict[x] = [y for y in numbers[index:] if y % x == 0] for x in numbers: for y in num_dict[x]: for z in num_dict[y]: print(x, y, z) ans += 1 return ans </code></pre> <p>(<code>39889</code> instead of <code>40888</code>) - oh, I accidentally made the index var start at 1 instead of 0. It works now.</p> <h1>Final Edit</h1> <p>I've found the best way to find the number of triples by reevaluating what I needed it to do. This method doesn't actually find the triples, it just counts them.</p> <pre><code>def foo(l): llen = len(l) total = 0 cache = {} for i in range(llen): cache[i] = 0 for x in range(llen): for y in range(x + 1, llen): if l[y] % l[x] == 0: cache[y] += 1 total += cache[x] return total </code></pre> <p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p> <pre><code>def bar(l): list_length = len(l) total_triples = 0 cache = {} for i in range(list_length): cache[i] = 0 for x in range(list_length): print("\n\nfor index[{}]: {}".format(x, l[x])) for y in range(x + 1, list_length): print("\n\ttry index[{}]: {}".format(y, l[y])) if l[y] % l[x] == 0: print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x])) cache[y] += 1 total_triples += cache[x] print("\t\tcache[{0}] is now {1}".format(y, cache[y])) print("\t\tcount is now {}".format(total_triples)) print("\t\t(+{} from cache[{}])".format(cache[x], x)) else: print("\n\t\tfalse") print("\ntotal number of triples:", total_triples) </code></pre>
4
2016-10-08T20:40:43Z
39,937,498
<p>the key insight is:</p> <p>if <strong>a</strong> divides <strong>b</strong>, it means <strong>a</strong> "fits into <strong>b</strong>". if <strong>a</strong> doesn't divide <strong>c</strong>, then it means "<strong>a</strong> doesn't fit into <strong>c</strong>". And if <strong>a</strong> can't fit into <strong>c</strong>, then <strong>b</strong> cannot fit into <strong>c</strong> (imagine if <strong>b</strong> fitted into <strong>c</strong>, since <strong>a</strong> fits into <strong>b</strong>, then <strong>a</strong> would fit into all the <strong>b</strong>'s that fit into <strong>c</strong> and so <strong>a</strong> would have to fit into <strong>c</strong> too.. (think of prime factorisation etc))</p> <p>this means that we can optimise. If we sort the numbers smallest to largest and start with the smaller numbers first. First iteration, start with the smallest number as <strong>a</strong> If we partition the numbers into two groups, group <strong>1</strong>, the numbers which <strong>a</strong> divides, and group <strong>2</strong> the group which <strong>a</strong> doesn't divide, then we know that no numbers in group <strong>1</strong> can divide numbers in group <strong>2</strong> because no numbers in group <strong>2</strong> have <strong>a</strong> as a factor.</p> <p>so if we had [2,3,4,5,6,7], we would start with 2 and get: [2,4,6] and [3,5,7] we can repeat the process on each group, splitting into smaller groups. This suggests an algorithm that could count the triples more efficiently. The groups will get really small really quickly, which means its efficiency should be fairly close to the size of the output.</p>
3
2016-10-08T21:19:31Z
[ "python", "algorithm" ]
What's the most efficient way to find factors in a list?
39,937,160
<h2>What I'm looking to do:</h2> <p>I need to make a function that, given a list of positive integers (there can be duplicate integers), counts all triples (in the list) in which the third number is a multiple of the second and the second is a multiple of the first:</p> <p>(The same number cannot be used twice in one triple, but can be used by all other triples)</p> <p>For example, <code>[3, 6, 18]</code> is one because <code>18</code> goes evenly into <code>6</code> which goes evenly into <code>3</code>.</p> <p>So given <code>[1, 2, 3, 4, 5, 6]</code> it should find:</p> <pre><code>[1, 2, 4] [1, 2, 6] [1, 3, 6] </code></pre> <p>and return <code>3</code> (the number of triples it found)</p> <h2>What I've tried:</h2> <p>I made a couple of functions that work but are not efficient enough. Is there some math concept I don't know about that would help me find these triples faster? A module with a function that does better? I don't know what to search for...</p> <pre><code>def foo(q): l = sorted(q) ln = range(len(l)) for x in ln: if len(l[x:]) &gt; 1: for y in ln[x + 1:]: if (len(l[y:]) &gt; 0) and (l[y] % l[x] == 0): for z in ln[y + 1:]: if l[z] % l[y] == 0: ans += 1 return ans </code></pre> <p>This one is a bit faster:</p> <pre><code>def bar(q): l = sorted(q) ans = 0 for x2, x in enumerate(l): pool = l[x2 + 1:] if len(pool) &gt; 1: for y2, y in enumerate(pool): pool2 = pool[y2 + 1:] if pool2 and (y % x == 0): for z in pool2: if z % y == 0: ans += 1 return ans </code></pre> <p>Here's what I've come up with with help from y'all but I must be doing something wrong because it get's the wrong answer (it's really fast though):</p> <pre><code>def function4(numbers): ans = 0 num_dict = {} index = 0 for x in numbers: index += 1 num_dict[x] = [y for y in numbers[index:] if y % x == 0] for x in numbers: for y in num_dict[x]: for z in num_dict[y]: print(x, y, z) ans += 1 return ans </code></pre> <p>(<code>39889</code> instead of <code>40888</code>) - oh, I accidentally made the index var start at 1 instead of 0. It works now.</p> <h1>Final Edit</h1> <p>I've found the best way to find the number of triples by reevaluating what I needed it to do. This method doesn't actually find the triples, it just counts them.</p> <pre><code>def foo(l): llen = len(l) total = 0 cache = {} for i in range(llen): cache[i] = 0 for x in range(llen): for y in range(x + 1, llen): if l[y] % l[x] == 0: cache[y] += 1 total += cache[x] return total </code></pre> <p>And here's a version of the function that explains the thought process as it goes (not good for huge lists though because of spam prints):</p> <pre><code>def bar(l): list_length = len(l) total_triples = 0 cache = {} for i in range(list_length): cache[i] = 0 for x in range(list_length): print("\n\nfor index[{}]: {}".format(x, l[x])) for y in range(x + 1, list_length): print("\n\ttry index[{}]: {}".format(y, l[y])) if l[y] % l[x] == 0: print("\n\t\t{} can be evenly diveded by {}".format(l[y], l[x])) cache[y] += 1 total_triples += cache[x] print("\t\tcache[{0}] is now {1}".format(y, cache[y])) print("\t\tcount is now {}".format(total_triples)) print("\t\t(+{} from cache[{}])".format(cache[x], x)) else: print("\n\t\tfalse") print("\ntotal number of triples:", total_triples) </code></pre>
4
2016-10-08T20:40:43Z
39,947,574
<p>This is the best answer that I was able to come up with so far. It's fast, but not quite fast enough. I'm still posting it because I'm probably going to abandon this question and don't want to leave out any progress I've made.</p> <pre><code>def answer(l): num_dict = {} ans_set = set() for a2, a in enumerate(l): num_dict[(a, a2)] = [] for x2, x in enumerate(l): for y2, y in enumerate(l): if (y, y2) != (x, x2) and y % x == 0: pair = (y, y2) num_dict[(x, x2)].append(pair) for x in num_dict: for y in num_dict[x]: for z in num_dict[y]: ans_set.add((x[0], y[0], z[0])) return len(ans_set) </code></pre>
0
2016-10-09T19:20:12Z
[ "python", "algorithm" ]
Matplotlib - contour and quiver plot in projected polar coordinates
39,937,249
<p>I need to plot contour and quiver plots of scalar and vector fields defined on an uneven grid in (r,theta) coordinates.</p> <p>As a minimal example of the problem I have, consider the contour plot of a <em><a href="https://en.wikipedia.org/wiki/Stream_function" rel="nofollow">Stream function</a></em> for a magnetic dipole, contours of such a function are streamlines of the corresponeding vector field (in this case, the magnetic field). </p> <p>The code below takes an uneven grid in (r,theta) coordinates, maps it to the cartesian plane and plots a contour plot of the stream function.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt r = np.logspace(0,1,200) theta = np.linspace(0,np.pi/2,100) N_r = len(r) N_theta = len(theta) # Polar to cartesian coordinates theta_matrix, r_matrix = np.meshgrid(theta, r) x = r_matrix * np.cos(theta_matrix) y = r_matrix * np.sin(theta_matrix) m = 5 psi = np.zeros((N_r, N_theta)) # Stream function for a magnetic dipole psi = m * np.sin(theta_matrix)**2 / r_matrix contour_levels = m * np.sin(np.linspace(0, np.pi/2,40))**2. fig, ax = plt.subplots() # ax.plot(x,y,'b.') # plot grid points ax.set_aspect('equal') ax.contour(x, y, psi, 100, colors='black',levels=contour_levels) plt.show() </code></pre> <p>For some reason though, the plot I get doesn't look right: <a href="http://i.stack.imgur.com/v0nxU.png" rel="nofollow"><img src="http://i.stack.imgur.com/v0nxU.png" alt="Contour plot of a stream function for a magnetic dipole."></a></p> <p>If I interchange x and y in the contour function call, I get the desired result: <a href="http://i.stack.imgur.com/MPRX0.png" rel="nofollow"><img src="http://i.stack.imgur.com/MPRX0.png" alt="enter image description here"></a></p> <p>Same thing happens when I try to make a quiver plot of a <em>vector field</em> defined on the same grid and mapped to the x-y plane, except that interchanging x and y in the function call no longer works. </p> <p>It seems like I made a stupid mistake somewhere but I can't figure out what it is.</p>
0
2016-10-08T20:51:03Z
39,937,952
<p>If <code>psi = m * np.sin(theta_matrix)**2 / r_matrix</code> then psi increases as theta goes from 0 to pi/2 and psi decreases as r increases.</p> <p>So a contour line for psi should increase in r as theta increases. That results in a curve that goes counterclockwise as it radiates out from the center. This is consistent with the first plot you posted, and the result returned by the first version of your code with</p> <pre><code>ax.contour(x, y, psi, 100, colors='black',levels=contour_levels) </code></pre> <hr> <p>An alternative way to confirm the plausibility of the result is to look at a surface plot of <code>psi</code>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as axes3d r = np.logspace(0,1,200) theta = np.linspace(0,np.pi/2,100) N_r = len(r) N_theta = len(theta) # Polar to cartesian coordinates theta_matrix, r_matrix = np.meshgrid(theta, r) x = r_matrix * np.cos(theta_matrix) y = r_matrix * np.sin(theta_matrix) m = 5 # Stream function for a magnetic dipole psi = m * np.sin(theta_matrix)**2 / r_matrix contour_levels = m * np.sin(np.linspace(0, np.pi/2,40))**2. fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') ax.set_aspect('equal') ax.plot_surface(x, y, psi, rstride=8, cstride=8, alpha=0.3) ax.contour(x, y, psi, colors='black',levels=contour_levels) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/E4IjS.png" rel="nofollow"><img src="http://i.stack.imgur.com/E4IjS.png" alt="enter image description here"></a></p>
1
2016-10-08T22:19:52Z
[ "python", "numpy", "matplotlib", "contour", "polar-coordinates" ]
requests.exceptions.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)
39,937,288
<p>I have a script that's made in python as below</p> <pre><code>#!/bin/env python2.7 # Run around 1059 as early as 1055. # Polling times vary pick something nice. # Ghost checkout timer can be changed by # adjusting for loop range near bottom. # Fill out personal data in checkout payload dict. import sys, json, time, requests, urllib2 from datetime import datetime qty='1' def UTCtoEST(): current=datetime.now() return str(current) + ' EST' print poll=raw_input("Polling interval? ") poll=int(poll) keyword=raw_input("Product name? ").title() # hardwire here by declaring keyword as a string color=raw_input("Color? ").title() # hardwire here by declaring keyword as a string sz=raw_input("Size? ").title() # hardwire here by declaring keyword as a string print print UTCtoEST(),':: Parsing page...' def main(): global ID global variant global cw req = urllib2.Request('http://www.supremenewyork.com/mobile_stock.json') req.add_header('User-Agent', "User-Agent','Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25") resp = urllib2.urlopen(req) data = json.loads(resp.read()) ID=0 for i in range(len(data[u'products_and_categories'].values())): for j in range(len(data[u'products_and_categories'].values()[i])): item=data[u'products_and_categories'].values()[i][j] name=str(item[u'name'].encode('ascii','ignore')) # SEARCH WORDS HERE # if string1 in name or string2 in name: if keyword in name: # match/(es) detected! # can return multiple matches but you're # probably buying for resell so it doesn't matter myproduct=name ID=str(item[u'id']) print UTCtoEST(),'::',name, ID, 'found ( MATCHING ITEM DETECTED )' if (ID == 0): # variant flag unchanged - nothing found - rerun time.sleep(poll) print UTCtoEST(),':: Reloading and reparsing page...' main() else: print UTCtoEST(),':: Selecting',str(myproduct),'(',str(ID),')' jsonurl = 'http://www.supremenewyork.com/shop/'+str(ID)+'.json' req = urllib2.Request(jsonurl) req.add_header('User-Agent', "User-Agent','Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25") resp = urllib2.urlopen(req) data = json.loads(resp.read()) found=0 for numCW in data['styles']: # COLORWAY TERMS HERE # if string1 in numCW['name'] or string2 in numCW['name']: if color in numCW['name'].title(): for sizes in numCW['sizes']: # SIZE TERMS HERE if str(sizes['name'].title()) == sz: # Medium found=1; variant=str(sizes['id']) cw=numCW['name'] print UTCtoEST(),':: Selecting size:', sizes['name'],'(',numCW['name'],')','(',str(sizes['id']),')' if found ==0: # DEFAULT CASE NEEDED HERE - EITHER COLORWAY NOT FOUND OR SIZE NOT IN RUN OF PRODUCT # PICKING FIRST COLORWAY AND LAST SIZE OPTION print UTCtoEST(),':: Selecting default colorway:',data['styles'][0]['name'] sizeName=str(data['styles'][0]['sizes'][len(data['styles'][0]['sizes'])-1]['name']) variant=str(data['styles'][0]['sizes'][len(data['styles'][0]['sizes'])-1]['id']) cw=data['styles'][0]['name'] print UTCtoEST(),':: Selecting default size:',sizeName,'(',variant,')' main() session=requests.Session() addUrl='http://www.supremenewyork.com/shop/'+str(ID)+'/add.json' addHeaders={ 'Host': 'www.supremenewyork.com', 'Accept': 'application/json', 'Proxy-Connection': 'keep-alive', 'X-Requested-With': 'XMLHttpRequest', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-us', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'http://www.supremenewyork.com', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257', 'Referer': 'http://www.supremenewyork.com/mobile' } addPayload={ 'size': str(variant), 'qty': '1' } print UTCtoEST() +' :: Adding product to cart...' addResp=session.post(addUrl,data=addPayload,headers=addHeaders) print UTCtoEST() +' :: Checking status code of response...' if addResp.status_code!=200: print UTCtoEST() +' ::',addResp.status_code,'Error \nExiting...' print sys.exit() else: if addResp.json()==[]: print UTCtoEST() +' :: Response Empty! - Problem Adding to Cart\nExiting...' print sys.exit() print UTCtoEST() +' :: '+str(cw)+' - '+addResp.json()[0]['name']+' - '+ addResp.json()[0]['size_name']+' added to cart!' checkoutUrl='https://www.supremenewyork.com/checkout.json' checkoutHeaders={ 'host': 'www.supremenewyork.com', 'If-None-Match': '"*"', 'Accept': 'application/json', 'Proxy-Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-us', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'http://www.supremenewyork.com', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257', 'Referer': 'http://www.supremenewyork.com/mobile' } ################################# # FILL OUT THESE FIELDS AS NEEDED ################################# checkoutPayload={ 'store_credit_id': '', 'from_mobile': '1', 'cookie-sub': '%7B%22'+str(variant)+'%22%3A1%7D', # cookie-sub: eg. {"VARIANT":1} urlencoded 'same_as_billing_address': '1', 'order[billing_name]': 'anon mous', # FirstName LastName 'order[email]': 'anon@mailinator.com', # email@domain.com 'order[tel]': '999-999-9999', # phone-number-here 'order[billing_address]': '123 Seurat lane', # your address 'order[billing_address_2]': '', 'order[billing_zip]': '90210', # zip code 'order[billing_city]': 'Beverly Hills', # city 'order[billing_state]': 'CA', # state 'order[billing_country]': 'USA', # country 'store_address': '1', 'credit_card[type]': 'visa', # master or visa 'credit_card[cnb]': '9999 9999 9999 9999', # credit card number 'credit_card[month]': '01', # expiration month 'credit_card[year]': '2026', # expiration year 'credit_card[vval]': '123', # cvc/cvv 'order[terms]': '0', 'order[terms]': '1' } # GHOST CHECKOUT PREVENTION WITH ROLLING PRINT for i in range(5): sys.stdout.write("\r" +UTCtoEST()+ ' :: Sleeping for '+str(5-i)+' seconds to avoid ghost checkout...') sys.stdout.flush() time.sleep(1) print print UTCtoEST()+ ' :: Firing checkout request!' checkoutResp=session.post(checkoutUrl,data=checkoutPayload,headers=checkoutHeaders) try: print UTCtoEST()+ ' :: Checkout',checkoutResp.json()['status'].title()+'!' except: print UTCtoEST()+':: Error reading status key of response!' print checkoutResp.json() print print checkoutResp.json() if checkoutResp.json()['status']=='failed': print print '!!!ERROR!!! ::',checkoutResp.json()['errors'] print </code></pre> <p>When I want to run it everything goes correctly but at the end it's giving me this error:</p> <pre><code>Traceback (most recent call last): File "/Users/"USERNAME"/Desktop/supreme.py", line 167, in &lt;module&gt; checkoutResp=session.post(checkoutUrl,data=checkoutPayload,headers=checkoutHeaders) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 522, in post return self.request('POST', url, data=data, json=json, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/adapters.py", line 497, in send raise SSLError(e, request=request) SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590) </code></pre>
-1
2016-10-08T20:56:53Z
39,937,538
<p>As can be seen from <a href="https://www.ssllabs.com/ssltest/analyze.html?d=www.supremenewyork.com" rel="nofollow">the SSLLabs report</a> the server supports only TLS 1.2 and supports only very few ciphers. Given a path like <code>/Users/...</code> in your error output I assume that you are using Mac OS X. The version of OpenSSL shipped with Mac OS X and probably used by your Python is 0.9.8, which is too old to support TLS 1.2. This means that the server will not accept the SSL 3.0 or TLS 1.0 request from your client.</p> <p>For information on how to fix this problem by updating your OpenSSL version see <a href="http://stackoverflow.com/questions/18752409/updating-openssl-in-python-2-7">Updating openssl in python 2.7</a>.</p>
0
2016-10-08T21:24:01Z
[ "python", "ssl", "handshake", "sslv3" ]
How to save a list of words and the positions of these words in the sentence as a file
39,937,357
<p>My Code: (Python: v3.5.2)</p> <pre><code>import time import sys def Word_Position_Finder(): chosen_sentence = input("Make a simple sentence: ").upper() print("") print(chosen_sentence) print("") sentence_list = chosen_sentence.split() if len(chosen_sentence) == 0: print("Your sentence has no words.") time.sleep(1) Choose_To_Restart() print(sentence_list) print("") time.sleep(1) users_choice = input("Press '1' to make a new sentence or press '2' keep current sentence: ") print("") if users_choice == "1": print("Restarting Program.") time.sleep(1) Restarting_Program() elif users_choice == "2": print("") print("'" + chosen_sentence + "'" + " --- " + "Is your current sentence.") print("") time.sleep(1) position = [] for word in sentence_list: postions = position.append(sentence_list.index(word) + 1) print(position) with open("Positions.txt", "w") as text_file: print(chosen_sentence, position) else: print("That isn't a valid answer") Choose_To_Restart() </code></pre> <p>What the code is trying to achieve:</p> <p>The code above takes a sentence of the users choice, makes that sentence into a list and then prints the position of each of those words in that list and then is meant to save the user's sentence and the positions of the user's sentence into a simple .txt file.</p> <p>Question:</p> <p>How do I make my code create .txt file that saves the user's sentence and the positions of each word in the user's sentence into that .txt file?</p> <p>The current problem I am having with the code is that the code does create a .txt file but nothing is saved in that file.</p>
-1
2016-10-08T21:04:31Z
39,937,436
<p>Iterate over the list containing the words of sentence. For each word, check that whether it exists in the other list containing words for finding the positions. Use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> to store the <code>index</code> of each word. Below is the sample code:</p> <pre><code>from collections import defaultdict my_sentence = 'this is my sentence where this content is supposed to be checked' sentence_words = my_sentence.split() my_dict = defaultdict(list) for i, item in enumerate(sentence_words): my_dict[item].append(i) # content of 'my_dict': # {'this': [0, 5], 'is': [1, 7], 'where': [4]} </code></pre> <p>Refer <a href="http://stackoverflow.com/questions/5214578/python-print-string-to-text-file">Python Print String To Text File</a> regarding how to write content to a a file.</p>
1
2016-10-08T21:12:05Z
[ "python" ]
Adding Specific Value to Nested Lists
39,937,428
<p>I'm having a comprehension issue on a specific problem. I have a preexisting nested list, and I want to match and append one value from a different list to the end of each nested list. A quick example of what I've tried, but where I'm stuck: </p> <pre><code> initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for sublist in initial_values: for i in other_values: sublist.append(i) print initial_values </code></pre> <p>This returns <code>[['First', 1, 1, 2, 3, 4], ['Second', 2, 1, 2, 3, 4], ['Third', 3, 1, 2, 3, 4], ['Fourth', 4, 1, 2, 3, 4]]</code></p> <p>I want it it to ideally return <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:10:53Z
39,937,449
<p>It seems like you want to go through both lists with a single iteration. You could achieve that using zip:</p> <pre><code>for sublist, i in zip(initial_values, other_values): sublist.append(i) </code></pre>
1
2016-10-08T21:14:21Z
[ "python", "list" ]
Adding Specific Value to Nested Lists
39,937,428
<p>I'm having a comprehension issue on a specific problem. I have a preexisting nested list, and I want to match and append one value from a different list to the end of each nested list. A quick example of what I've tried, but where I'm stuck: </p> <pre><code> initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for sublist in initial_values: for i in other_values: sublist.append(i) print initial_values </code></pre> <p>This returns <code>[['First', 1, 1, 2, 3, 4], ['Second', 2, 1, 2, 3, 4], ['Third', 3, 1, 2, 3, 4], ['Fourth', 4, 1, 2, 3, 4]]</code></p> <p>I want it it to ideally return <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:10:53Z
39,937,452
<p>You can use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to match elements of the same index from different lists. From there on, you're a simple list concatenation away:</p> <pre><code>[a + [b] for a,b in zip(initial_values, other_values)] </code></pre>
2
2016-10-08T21:14:39Z
[ "python", "list" ]
Adding Specific Value to Nested Lists
39,937,428
<p>I'm having a comprehension issue on a specific problem. I have a preexisting nested list, and I want to match and append one value from a different list to the end of each nested list. A quick example of what I've tried, but where I'm stuck: </p> <pre><code> initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for sublist in initial_values: for i in other_values: sublist.append(i) print initial_values </code></pre> <p>This returns <code>[['First', 1, 1, 2, 3, 4], ['Second', 2, 1, 2, 3, 4], ['Third', 3, 1, 2, 3, 4], ['Fourth', 4, 1, 2, 3, 4]]</code></p> <p>I want it it to ideally return <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:10:53Z
39,937,463
<p>Built-in function <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">zip</a> will match first item in first list with first item in second list etc.</p> <pre><code>initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for initials, other in zip(initial_values, other_values): initials.append(other) </code></pre>
0
2016-10-08T21:15:34Z
[ "python", "list" ]
Adding Specific Value to Nested Lists
39,937,428
<p>I'm having a comprehension issue on a specific problem. I have a preexisting nested list, and I want to match and append one value from a different list to the end of each nested list. A quick example of what I've tried, but where I'm stuck: </p> <pre><code> initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for sublist in initial_values: for i in other_values: sublist.append(i) print initial_values </code></pre> <p>This returns <code>[['First', 1, 1, 2, 3, 4], ['Second', 2, 1, 2, 3, 4], ['Third', 3, 1, 2, 3, 4], ['Fourth', 4, 1, 2, 3, 4]]</code></p> <p>I want it it to ideally return <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:10:53Z
39,937,472
<p>Your double for-loop takes each sublist in turn (the outer for-loop) and appends every element of <code>other_values</code> to it (the inner for-loop). What you want instead is to add each element of <code>other_values</code> to the corresponding sublist (i.e. the sublist at the same position/index). Therefore, what you need is only one for-loop:</p> <pre><code>initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for i in range(len(initial_values)): # get all the valid indices of `initial_values` initial_values[i].append(other_values[i]) </code></pre> <p>Here's are some simpler ways to do it:</p> <pre><code>for i,subl in enumerate(initial_values): subl.append(other_values[i])) </code></pre> <p>Or</p> <pre><code>for subl, val in zip(initial_values, other_values): subl.append(val) </code></pre>
1
2016-10-08T21:16:44Z
[ "python", "list" ]
Adding Specific Value to Nested Lists
39,937,428
<p>I'm having a comprehension issue on a specific problem. I have a preexisting nested list, and I want to match and append one value from a different list to the end of each nested list. A quick example of what I've tried, but where I'm stuck: </p> <pre><code> initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for sublist in initial_values: for i in other_values: sublist.append(i) print initial_values </code></pre> <p>This returns <code>[['First', 1, 1, 2, 3, 4], ['Second', 2, 1, 2, 3, 4], ['Third', 3, 1, 2, 3, 4], ['Fourth', 4, 1, 2, 3, 4]]</code></p> <p>I want it it to ideally return <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:10:53Z
39,937,537
<p>If you want to use for loop you can try </p> <pre><code>initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for i in range(0,len(other_values)): initial_values[i].append(other_values[i]) print initial_values </code></pre> <p>output:<br> <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:24:01Z
[ "python", "list" ]
Adding Specific Value to Nested Lists
39,937,428
<p>I'm having a comprehension issue on a specific problem. I have a preexisting nested list, and I want to match and append one value from a different list to the end of each nested list. A quick example of what I've tried, but where I'm stuck: </p> <pre><code> initial_values = [["First", 1], ["Second", 2], ["Third", 3], ["Fourth", 4]] other_values = [1,2,3,4] for sublist in initial_values: for i in other_values: sublist.append(i) print initial_values </code></pre> <p>This returns <code>[['First', 1, 1, 2, 3, 4], ['Second', 2, 1, 2, 3, 4], ['Third', 3, 1, 2, 3, 4], ['Fourth', 4, 1, 2, 3, 4]]</code></p> <p>I want it it to ideally return <code>[['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]]</code></p>
1
2016-10-08T21:10:53Z
39,937,561
<p>One of the alternative to achieve it using <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map()</code></a> as:</p> <pre><code>&gt;&gt;&gt; map(lambda x: x[0] + [x[1]], zip(initial_values, other_values)) [['First', 1, 1], ['Second', 2, 2], ['Third', 3, 3], ['Fourth', 4, 4]] </code></pre>
1
2016-10-08T21:26:47Z
[ "python", "list" ]
Iam having trouble with Python command “ cascPath = sys.argv[1] ” i get error IndexError: list index out of range
39,937,634
<p>I am using a Raspberry Pi 3 Model B, with Raspbian, opencv 2.x and Python 3 installed.</p> <p>I want to access my USB Webcam and take a picture with it. I've found tons of code but none are of any use. I found one which is better but when I run the command</p> <pre><code>cascPath = sys.argv[1] </code></pre> <p>I get the error</p> <blockquote> <p>Traceback (most recent call last):</p> <p>File "/home/pi/test.py", line 4, in</p> <p><code>cascPath = sys.argv[1]</code></p> </blockquote> <p>IndexError: list index out of range</p> <p>I simply need to access my webcam to take a picture.</p> <p>Iam using the following code : </p> <pre><code>import cv2 import sys cascPath = sys.argv[1] faceCascade = cv2.CascadeClassifier(cascPath) video_capture = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display the resulting frame cv2.imshow('Video', frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break #When everything is done, release the capture video_capture.release() </code></pre> <p>If somebody knows an exact python code for taking picture it would be best too, I have tried many different ways but all in vain. <strong>PLEASE RESPOND ASAP i quote again <em>I simply want to take Picture using my "webcam"</em></strong> </p> <p>Regards</p>
0
2016-10-08T21:36:18Z
39,937,737
<p>This code try to recognize faces on image and <code>sys.argv[1]</code> expects you run script with path to XML file which help recognize faces.</p> <p>If you don't want to recognize faces then you need only this code to display on monitor video from camera.</p> <pre><code>import cv2 import sys video_capture = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = video_capture.read() # Display the resulting frame cv2.imshow('Video', frame) # exit if you press key `q` if cv2.waitKey(1) &amp; 0xFF == ord('q'): break #When everything is done, release the capture video_capture.release() </code></pre> <p>Or this to save image </p> <pre><code>import cv2 video_capture = cv2.VideoCapture(0) # Capture frame ret, frame = video_capture.read() # Write frame in file cv2.imwrite('image.jpg', frame) # When everything is done, release the capture video_capture.release() </code></pre>
0
2016-10-08T21:52:59Z
[ "python", "opencv", "debian", "webcam", "raspberry-pi3" ]
Pandas plot without specifying index
39,937,650
<p>Given the data:</p> <pre><code>Column1; Column2; Column3 1; 4; 6 2; 2; 6 3; 3; 8 4; 1; 1 5; 4; 2 </code></pre> <p>I can plot it via:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') titles = list(df) for title in titles: if title == titles[0]: continue df.plot(titles[0],title, linestyle='--', marker='o') plt.savefig(title+'.png') </code></pre> <p>But if, instead, data was missing <code>Column1</code> like:</p> <pre><code>Column2; Column3 4; 6 2; 6 3; 8 1; 1 4; 2 </code></pre> <p>How do I plot it?</p> <p>May be, something like <code>df.plot(title, linestyle='--', marker='o')</code>?</p>
0
2016-10-08T21:39:29Z
39,937,721
<p>I am not sure what you are trying to achieve but you could reset index and set it as you would like:</p> <pre><code>In[11]: df Out[11]: Column1 Column2 Column3 0 1 4 6 1 2 2 6 2 3 3 8 3 4 1 1 4 5 4 2 </code></pre> <p>so if you want to plot col 2 as X axis and 3 as Y axis you could do something like:</p> <pre><code>df.set_index('Column2')['Column3'].plot() </code></pre>
0
2016-10-08T21:50:09Z
[ "python", "python-2.7", "pandas", "matplotlib", "dataframe" ]
Infinite Loop Exits Automatically while Using multithreading and Queues
39,937,666
<p>I'm trying to run a function that has an infinite loop (to check data after few seconds of delay) using multithreading. Since I read data from a csv file, I'm also using Queues.</p> <p>My current function fine when I do not use multithreading/queues but when I use them, the function only loops once and then stops.</p> <p>Here's my function that has a infinite loop. Please note that the first while True loop is for threads (in case I use less number of threads than rows in csv) , the function only requires the second while True loop.</p> <pre><code>def doWork(q): while True: #logging.info('Thread Started') row=q.get() url = row[0] target_price = row[1] #logging.info('line 79') while True: delay=randint(5,10) headers = {'User-Agent': generate_user_agent()} print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')+': '+'Sleeping for ' + str(delay) + ' seconds' #logging.info('line 81') eventlet.sleep(delay) try: #logging.info('line 85') with requests.Session() as s: #logging.info('line 87') with eventlet.Timeout(10, False): page = s.get(url,headers=headers,proxies=proxyDict,verify=False) #logging.info('line 89') tree = html.fromstring(page.content) #logging.info('line 91') price = tree.xpath('//div[@class="a-row a-spacing-mini olpOffer"]/div[@class="a-column a-span2 olpPriceColumn"]/span[@class="a-size-large a-color-price olpOfferPrice a-text-bold"]/text()')[0] title = tree.xpath('//h1/text()')[0] #logging.info('line 93') new_price = re.findall("[-+]?\d+[\.]?\d+[eE]?[-+]?\d*", price)[0] #logging.info('line 95') old_price = new_price #logging.info('line 97') #print price print new_price print title + 'Current price:' + new_price if float(new_price)&lt;float(target_price): print 'Lower price found!' mydriver = webdriver.Chrome() send_simple_message() login(mydriver) print 'Old Price: ' + old_price print 'New Price: ' + new_price else: print 'Trying again' q.task_done() except Exception as e: print e print 'Error!' q.task_done() </code></pre> <p>And here is my thread driver function;</p> <pre><code>q = Queue(concurrent * 2) if __name__ == "__main__": for i in range(concurrent): t = Thread(target=doWork,args=(q,)) t.daemon = True t.start() try: with open('products.csv','r') as f: reader = csv.reader(f.read().splitlines()) for row in reader: q.put((row[0],row[1])) q.join() except KeyboardInterrupt: sys.exit(1) </code></pre>
0
2016-10-08T21:41:12Z
39,961,822
<p>For anyone that is facing the same issue, here's how I solved it.</p> <p>I removed q.task_done() from the while loop and put it outside the while loop. This is working as intended but I'm not sure if this is the right approach.</p>
0
2016-10-10T15:36:05Z
[ "python", "multithreading" ]
Get Text from Span returns empty string
39,937,692
<p>I'm trying to get the text from the span inside this div with python and selenium:</p> <pre><code>&lt;div class="product-name"&gt; &lt;span class="h1" itemprop="name"&gt;TEXT&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I've tried this, however, this returns an empty string:</p> <pre><code>line = dr.find_element_by_class_name('product-name').find_element_by_xpath('.//span').text </code></pre> <p>Thanks in advance,</p>
0
2016-10-08T21:46:11Z
39,938,510
<p>You should try using <code>css_selector</code> to find desire element in one find statement as below :-</p> <pre><code>line = dr.find_element_by_css_selector('div.product-name &gt; span').text </code></pre> <p>If you're still getting empty string try using <code>get_attribute("textContent")</code> as :-</p> <pre><code>line = dr.find_element_by_css_selector('div.product-name &gt; span').get_attribute("textContent") </code></pre> <p>Or using <code>get_attribute("innerHTML")</code> as :-</p> <pre><code>line = dr.find_element_by_css_selector('div.product-name &gt; span').get_attribute("innerHTML") </code></pre> <p><strong>Note</strong> :- You can also use above operation to getting innerText on parent <code>&lt;div&gt;</code> element using <code>class_name</code> if there is only desire text as :-</p> <pre><code>line = dr.find_element_by_class_name('product-name').text </code></pre> <p>Or</p> <pre><code>line = dr.find_element_by_class_name('product-name').get_attribute("textContent") </code></pre>
1
2016-10-08T23:41:45Z
[ "python", "selenium", "web-scraping", "phantomjs" ]
Get Text from Span returns empty string
39,937,692
<p>I'm trying to get the text from the span inside this div with python and selenium:</p> <pre><code>&lt;div class="product-name"&gt; &lt;span class="h1" itemprop="name"&gt;TEXT&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I've tried this, however, this returns an empty string:</p> <pre><code>line = dr.find_element_by_class_name('product-name').find_element_by_xpath('.//span').text </code></pre> <p>Thanks in advance,</p>
0
2016-10-08T21:46:11Z
39,938,549
<p>I find bs4 more intuitive, prehaps this would suite better? </p> <pre><code> from bs4 import BeautifulSoup as bs4 def main(): html = """&lt;div class="product-name"&gt; &lt;span class="h1" itemprop="name"&gt;TEXT&lt;/span&gt; &lt;/div&gt;""" soup = bs4(html, "html.parser") print(soup.find_all('div', {"class": "product-name"})) if __name__ == '__main__': main() </code></pre> <p>Concerning your code.. </p> <pre><code>line = dr.find_element_by_class_name('product-name').find_element_by_xpath('.//span').text </code></pre> <p>Maybe supposed to be something more inline with:</p> <pre><code>line = dr.find_element_by_classname('product-name') </code></pre> <p>Might remember wrong. </p>
0
2016-10-08T23:47:20Z
[ "python", "selenium", "web-scraping", "phantomjs" ]
Resample 2d coordinates with values in pandas
39,937,695
<p>I have a data frame in pandas containing x coordinates, y coordinates, and values. I would like to "downsample" my coordinates and add the values appropriately.</p> <pre><code>df = pd.DataFrame({'x': [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4], 'y': [1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4], 'v': [1,1,1,1,1,1,1,1,1,1,1,2,1,2,1,1] }) </code></pre> <p>Visualizing this data frame with a scatter plot looks like:</p> <p><a href="http://i.stack.imgur.com/bvAZe.png" rel="nofollow"><img src="http://i.stack.imgur.com/bvAZe.png" alt="enter image description here"></a></p> <p>and I want to resample my data to something like this: <a href="http://i.stack.imgur.com/Tb9BC.png" rel="nofollow"><img src="http://i.stack.imgur.com/Tb9BC.png" alt="enter image description here"></a></p> <p>The v values should simply be added together. I also would like to choose the factor of the sampling.</p> <p>I first looked into df.resample but this only applies to time series data. I assume this can be achieved with groupby() somehow but it seems I just can't figure it out. Any hints are highly appreciated.</p>
1
2016-10-08T21:46:32Z
39,938,725
<p>Try this</p> <pre><code>g = df.groupby([df.x.sub(1) // 2 * 2 + 1.5, df.y.sub(1) // 2 * 2 + 1.5]) g.v.sum().reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/NDeOt.png" rel="nofollow"><img src="http://i.stack.imgur.com/NDeOt.png" alt="enter image description here"></a></p>
1
2016-10-09T00:16:58Z
[ "python", "python-3.x", "pandas" ]
How to use another function to get point values from a list
39,937,798
<p>So I am not sure how I am to go about doing this problem, but from my understanding I am suppose to use another function to get points from a list of 52 numbers and then I am suppose to return a list that contains the sum of the points from the different integers from the list.</p> <p>What the question asks:</p> <p>write a function that takes, as an argument, a list of natural numbers between 1 and 52, inclusive, and uses Practice Problem 3 to return a list containing all of the distinct possible sums of the point values of all of the cards corresponding to the numbers in the list.</p> <p>So to start practice problem 3 assigns point values to a list of 52 integers. It's code:</p> <pre><code>def getPoints(n): n = (n-1) % 13 + 1 if n == 1: return [1,11] if 2 &lt;= n &lt;= 10: return [n] if 11 &lt;= n &lt;= 13: return [10] </code></pre> <p>Now I am to make a new function utilizing function 3 to obtain points for a list of numbers I choose from the 52 numbers.</p> <p>Here is my code for the new function:</p> <pre><code>def getPointTotal(aList): for i in aList: points = getPoints(i) return aList, points </code></pre> <p>It isn't complete because I am stuck. Right now as it sits I get.</p> <pre><code>&gt;&gt;&gt;getPointTotal([10, 1]) &gt;&gt;&gt;[12, 1], [10] # 12 is worth 10 points </code></pre> <p>So I noticed it was only taking one integer from the list of 52 numbers, but I don't know how to make to get more than one of the integers from the list.</p> <p>I've tried moving the return inside the loop but then it gives me:</p> <pre><code>&gt;&gt;&gt;getPointTotal([8, 11]) &gt;&gt;&gt;[8, 11], [10] #11 is worth 10 points </code></pre> <p>How do I get the called function to go over more than one item?</p>
1
2016-10-08T22:01:20Z
39,937,817
<p>you need to append the results of the inside of your loop, not overwrite:</p> <pre><code>def getPointTotal(aList): points = [] for i in aList: points += getPoints(i) return aList, points </code></pre>
1
2016-10-08T22:03:37Z
[ "python", "list", "python-3.x" ]
find the numerical index of a list of characters in ascending alphabetical order
39,937,805
<p>I am writing a cryptography program that does columnar transposition. a person enters a key as a string, eg, key = 'ZEBRAS' I need to determine the numerical index corresponding to each letter, in ascending alphabetical order. for example, </p> <ul> <li><strong>Z E B R A S</strong></li> <li><strong>6 3 2 4 1 5</strong></li> </ul> <p>A is the highest, so its rank 1. z is the lowest, so its rank 6. I want to store this value into an appropriate data structure, so when i go to encrypt a message, i will read off the column corresponding to position 1 first, and 6 last. </p>
0
2016-10-08T22:02:06Z
39,937,846
<p>Create a temp list to store the sorted word, and extract the position from the temp list. Below is the sample code:</p> <pre><code>&gt;&gt;&gt; word = 'ZEBRAS' &gt;&gt;&gt; sorted_word = sorted(word) &gt;&gt;&gt; sorted_word ['A', 'B', 'E', 'R', 'S', 'Z'] &gt;&gt;&gt; index_string = [sorted_word.index(a)+1 for a in word] &gt;&gt;&gt; index_string [6, 3, 2, 4, 1, 5] </code></pre>
0
2016-10-08T22:07:35Z
[ "python", "sorting", "cryptography" ]
find the numerical index of a list of characters in ascending alphabetical order
39,937,805
<p>I am writing a cryptography program that does columnar transposition. a person enters a key as a string, eg, key = 'ZEBRAS' I need to determine the numerical index corresponding to each letter, in ascending alphabetical order. for example, </p> <ul> <li><strong>Z E B R A S</strong></li> <li><strong>6 3 2 4 1 5</strong></li> </ul> <p>A is the highest, so its rank 1. z is the lowest, so its rank 6. I want to store this value into an appropriate data structure, so when i go to encrypt a message, i will read off the column corresponding to position 1 first, and 6 last. </p>
0
2016-10-08T22:02:06Z
39,937,860
<p>Create a dictionary from sorted &amp; unique group of letters &amp; indices from 1 to length of the string (you need unicity or several indexes will be generated if there are several occurrences of a letters (as shown below, I have added an S to the word):</p> <pre><code>s="ZEBRASS" us=set(s) sl=dict(zip(sorted(us),range(1,len(us)+1))) print(sl) </code></pre> <p><code>sl</code> contains:</p> <pre><code>{'Z': 6, 'A': 1, 'E': 3, 'R': 4, 'S': 5, 'B': 2} </code></pre> <p>To "encrypt", apply the dictionary to your string:</p> <pre><code>sc = [sl[c] for c in s] print(sc) </code></pre> <p>result:</p> <pre><code>[6, 3, 2, 4, 1, 5, 5] </code></pre>
1
2016-10-08T22:08:40Z
[ "python", "sorting", "cryptography" ]
Isolating pandas columns using boolean logic in python
39,937,810
<p>I am trying to grab the rows of a data frame that satisfy one or both of the following boolean statements:</p> <pre><code>1) df['colName'] == 0 2) df['colName'] == 1 </code></pre> <p>I've tried these, but neither one works (throws errors):</p> <pre><code>df = df[df['colName']==0 or df['colName']==1] df = df[df['colName']==0 | df['colName']==1] </code></pre> <p>Any other ideas?</p>
1
2016-10-08T22:02:57Z
39,937,861
<p>you are missing <code>()</code></p> <pre><code>df = df[(df['colName']==0) | (df['colName']==1)] </code></pre> <p>this will probably raise a copy warning but will still works.</p> <p>if you don't want the copy warning, use an indexer such has:</p> <pre><code>indexer = df[(df['colName']==0) | (df['colName']==1)].index df = df.loc[indexer,:] </code></pre>
1
2016-10-08T22:08:43Z
[ "python", "pandas", "dataframe" ]
Isolating pandas columns using boolean logic in python
39,937,810
<p>I am trying to grab the rows of a data frame that satisfy one or both of the following boolean statements:</p> <pre><code>1) df['colName'] == 0 2) df['colName'] == 1 </code></pre> <p>I've tried these, but neither one works (throws errors):</p> <pre><code>df = df[df['colName']==0 or df['colName']==1] df = df[df['colName']==0 | df['colName']==1] </code></pre> <p>Any other ideas?</p>
1
2016-10-08T22:02:57Z
39,938,562
<p>You could clean up what you've done using <code>eq</code> instead of <code>==</code></p> <pre><code>df[df.colName.eq(0) | df.colName.eq(1)] </code></pre> <p>For this case, I recommend using <code>isin</code></p> <pre><code>df[df.colName.isin([0, 1])] </code></pre> <p>Using <code>query</code> also works but is slower</p> <pre><code>df.query('colName in [0, 1]') </code></pre> <hr> <p><strong><em>Timing</em></strong><br> <code>isin</code> is quickest on <code>df</code> defined below<br> <code>df = pd.DataFrame(np.random.randint(3, size=10000), columns=['colName'])</code></p> <p><a href="http://i.stack.imgur.com/tS95z.png" rel="nofollow"><img src="http://i.stack.imgur.com/tS95z.png" alt="enter image description here"></a></p>
1
2016-10-08T23:49:47Z
[ "python", "pandas", "dataframe" ]
How to encode flickr short url (base58) in python?
39,937,823
<p>How to encode short URLs of Flickr photos? There is no documentation about the <code>base58</code> method on the <a href="https://www.flickr.com/services/api/misc.urls.html" rel="nofollow">official API page about urls</a>.</p> <p>I can't find examples in Python that are just a function, there are only complicated classes.</p>
0
2016-10-08T22:04:58Z
39,937,824
<pre><code>def b58encode(fid): CHARS = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' CHAR_NUM = len(CHARS) encoded = '' fid = int(fid) while fid &gt;= CHAR_NUM: div, mod = divmod(fid, CHAR_NUM) encoded = CHARS[mod] + encoded fid = div return CHARS[fid] + encoded print(b58encode(2222223333333)) </code></pre> <p>Answer based on <a href="https://gist.github.com/mursts/2247355" rel="nofollow">https://gist.github.com/mursts/2247355</a></p>
0
2016-10-08T22:04:58Z
[ "python", "url", "flickr", "flickr-api" ]
Trying to understand how to use the any() function
39,937,873
<p>I want to pick many given numbers and compare them to a number I chose, how do i do this using the <code>any</code> or <code>all</code> command , I tried this and it didn't work, any input would be appreciated: </p> <pre><code>import random v = int(input("What number are you looking for ?")) a1 = int(input("What is the first number")) a2 = int(input("What is the second number")) a3 = int(input("What is the third number")) a = random.choice([a1,a2,a3]) b = random.choice([a1,a2,a3]) c = random.choice([a1,a2,a3]) if any ([a, b, c]) == v: print('We got a hit') </code></pre> <p>Entering the following, I can't get the <code>if</code> to evaluate to <code>True</code>: </p> <pre><code>What number are you looking for ?5 What is the first number1 What is the second number2 What is the third number5 &gt;&gt;&gt; </code></pre> <p>How am I using <code>any</code> wrong here ? Since the last number is <code>5</code> I should of gotten a hit but I get nothing.</p>
0
2016-10-08T22:10:57Z
39,937,929
<p>Because you're using <code>any</code> wrong. To achieve what you want, supply the condition to <code>any</code>:</p> <pre><code>if any(v == i for i in [a, b, c]): print('We got a hit') </code></pre> <p>This will check that there's a value in the list <code>[a, b, c]</code> which equals <code>v</code>.</p> <p>Your approach:</p> <pre><code>any([a, b, c]) == v </code></pre> <p>Will first use <code>any</code> to check if any of the elements inside the iterable (<code>[a, b, c]</code>) supplied has a truthy value (and it does, all of them do if they're positive integers) and returns the appropriate result <code>True</code> indicating that. So:</p> <pre><code>any([a, b, c]) </code></pre> <p>will return <code>True</code>. Your condition then becomes:</p> <pre><code>True == v </code></pre> <p>which obviously evaluates to <code>False</code>.</p>
2
2016-10-08T22:17:21Z
[ "python", "python-3.x" ]
How can I compare 2 dictionaries?
39,937,876
<p>I have two dictionaries</p> <pre><code>dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4} dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']} </code></pre> <p>I want to compare the two dictionaries and create a new one with the keys from <code>dict_b</code> and values from <code>dict_a</code>if the values from <code>dict_b</code> match. I would expect to see:</p> <pre><code>new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]} </code></pre> <p>I have tried the following code:</p> <pre><code>for name, guess in dict_b.items(): if guess == i in dict_a.values(): new_dict[name].append(i) print(new_dict) </code></pre> <p>I get the error <code>NameError: name 'i' is not defined</code>but I'm not sure how to define 'i'.</p> <p>Thanks for any help</p>
0
2016-10-08T22:11:14Z
39,937,906
<p>This can be done with a simple dict comprehension:</p> <pre><code>&gt;&gt;&gt; {k: [dict_a.get(x,x) for x in v] for k, v in dict_b.items()} {'bob': [2, 3.5], 'john': [4, 2], 'bill': [3.5]} </code></pre> <p>This replaces values with those from <code>dict_a</code> if they exist. Otherwise, keeps those from <code>dict_b</code> (the second argument in <code>.get(x,x)</code>).</p> <p>Alternatively, fix the original code this way:</p> <pre><code>new_dict = {} for name, guess in dict_b.items(): new_dict[name] = [] for value in guess: if value in dict_a: new_dict[name].append(dict_a[value]) print(new_dict) </code></pre>
1
2016-10-08T22:15:18Z
[ "python", "if-statement", "dictionary" ]
How can I compare 2 dictionaries?
39,937,876
<p>I have two dictionaries</p> <pre><code>dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4} dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']} </code></pre> <p>I want to compare the two dictionaries and create a new one with the keys from <code>dict_b</code> and values from <code>dict_a</code>if the values from <code>dict_b</code> match. I would expect to see:</p> <pre><code>new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]} </code></pre> <p>I have tried the following code:</p> <pre><code>for name, guess in dict_b.items(): if guess == i in dict_a.values(): new_dict[name].append(i) print(new_dict) </code></pre> <p>I get the error <code>NameError: name 'i' is not defined</code>but I'm not sure how to define 'i'.</p> <p>Thanks for any help</p>
0
2016-10-08T22:11:14Z
39,937,916
<p>well like so:</p> <pre><code>new_dict = {name: [dict_a[k] for k in dict_b[name]] for name in` dict_b.keys()} </code></pre>
4
2016-10-08T22:16:21Z
[ "python", "if-statement", "dictionary" ]
How can I compare 2 dictionaries?
39,937,876
<p>I have two dictionaries</p> <pre><code>dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4} dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']} </code></pre> <p>I want to compare the two dictionaries and create a new one with the keys from <code>dict_b</code> and values from <code>dict_a</code>if the values from <code>dict_b</code> match. I would expect to see:</p> <pre><code>new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]} </code></pre> <p>I have tried the following code:</p> <pre><code>for name, guess in dict_b.items(): if guess == i in dict_a.values(): new_dict[name].append(i) print(new_dict) </code></pre> <p>I get the error <code>NameError: name 'i' is not defined</code>but I'm not sure how to define 'i'.</p> <p>Thanks for any help</p>
0
2016-10-08T22:11:14Z
39,937,979
<pre><code>if guess == i in dict_a.values(): </code></pre> <p>This does not do what you expect it to do. Python here chains the operators, so your test is equivalent to the following:</p> <pre><code>(guess == i) and (i in dict_a.values()) </code></pre> <p>So it’s not like executing a for loop here where you iterate a variable <code>i</code> in the dictionary values.</p> <p>Furthermore, you actually need to collect the values from those multiple keys, so what you would want to do here is the following:</p> <pre><code>new_dict = {} for name, guesses in dict_b.items(): result = [] for guess in guesses: if guess in dict_a: result.append(dict_a[guess]) new_dict[name] = result </code></pre> <p>Then, you can also use list comprehensions to shorten this:</p> <pre><code>new_dict = {} for name, guesses in dict_b.items(): new_dict[name] = [dict_a[guess] for guess in guesses if guess in dict_a] </code></pre> <p>And finally, you could even combine this with a dict comprehension:</p> <pre><code>new_dict = { name: [dict_a[guess] for guess in guesses if guess in dict_a] for name, guesses in dict_b.items() } </code></pre>
2
2016-10-08T22:22:51Z
[ "python", "if-statement", "dictionary" ]
Understand vim in pyvmomi
39,937,883
<p>I would like to understand vim in pyvmomi.<br> I understand that vim is imported like this: <code>from pyvmomi import vim</code><br> I tried to find where vim is defined in pyvmomi, but I have not found it yet. </p> <p>I tried the following steps:</p> <pre><code>&gt;&gt;&gt; inspect.getfile(vim) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python2.7/inspect.py", line 420, in getfile 'function, traceback, frame, or code object'.format(object TypeError: &lt;pyVmomi.VmomiSupport.LazyModule object at 0xb50690&gt; is not a module, class, method, function, traceback, frame, or code object &gt;&gt;&gt; globals()['vim'] &lt;pyVmomi.VmomiSupport.LazyModule object at 0xb50690&gt; &gt;&gt;&gt; locals()['vim'] &lt;pyVmomi.VmomiSupport.LazyModule object at 0xb50690&gt; &gt;&gt;&gt; vim </code></pre> <p></p> <p>However, I did not get how vim is defined in LazyModule</p> <p>I'd like to understand where the data objects listed in<br> <a href="https://github.com/vmware/pyvmomi/tree/master/docs/vim" rel="nofollow">https://github.com/vmware/pyvmomi/tree/master/docs/vim</a> are defined initially in pyVmomi. </p>
0
2016-10-08T22:12:28Z
39,971,735
<p>For the most part those objects are found here: <a href="https://github.com/vmware/pyvmomi/blob/master/pyVmomi/ServerObjects.py" rel="nofollow">https://github.com/vmware/pyvmomi/blob/master/pyVmomi/ServerObjects.py</a> and <a href="https://github.com/vmware/pyvmomi/blob/master/pyVmomi/QueryTypes.py" rel="nofollow">https://github.com/vmware/pyvmomi/blob/master/pyVmomi/QueryTypes.py</a> and <a href="https://github.com/vmware/pyvmomi/blob/master/pyVmomi/CoreTypes.py" rel="nofollow">https://github.com/vmware/pyvmomi/blob/master/pyVmomi/CoreTypes.py</a></p> <p>Recently SMS support was added and those SMS objects are here: <a href="https://github.com/vmware/pyvmomi/blob/master/pyVmomi/SmsObjects.py" rel="nofollow">https://github.com/vmware/pyvmomi/blob/master/pyVmomi/SmsObjects.py</a></p> <p>And SPBM objects are here: <a href="https://github.com/vmware/pyvmomi/blob/master/pyVmomi/PbmObjects.py" rel="nofollow">https://github.com/vmware/pyvmomi/blob/master/pyVmomi/PbmObjects.py</a></p> <p>These objects are dynamically created and the contents of this file should not be edited because it is auto-generated by VMWare with their internal build system. The objects are created using tools in VmomiSupport which is here: <a href="https://github.com/vmware/pyvmomi/blob/master/pyVmomi/VmomiSupport.py" rel="nofollow">https://github.com/vmware/pyvmomi/blob/master/pyVmomi/VmomiSupport.py</a></p> <p>To expand further about where and how vim is defined lets look in ServerObjects.py:</p> <pre><code>CreateDataType("vim.AboutInfo", "AboutInfo", "vmodl.DynamicData", "vim.version.version1", [("name", "string", "vim.version.version1", 0), ("fullName", "string", "vim.version.version1", 0), ("vendor", "string", "vim.version.version1", 0), ("version", "string", "vim.version.version1", 0), ("build", "string", "vim.version.version1", 0), ("localeVersion", "string", "vim.version.version1", F_OPTIONAL), ("localeBuild", "string", "vim.version.version1", F_OPTIONAL), ("osType", "string", "vim.version.version1", 0), ("productLineId", "string", "vim.version.version1", 0), ("apiType", "string", "vim.version.version1", 0), ("apiVersion", "string", "vim.version.version1", 0), ("instanceUuid", "string", "vim.version.version5", F_OPTIONAL), ("licenseProductName", "string", "vim.version.version5", F_OPTIONAL), ("licenseProductVersion", "string", "vim.version.version5", F_OPTIONAL)]) </code></pre> <p>Here the <code>CreateDataType</code> method is used which is imported from VmomiSupport. This method takes a few parameters: </p> <ol> <li>vmodlName (VMware Managed Object Design Language Name)</li> <li>wsdlName (the WSDL name of the type)</li> <li>parent (the VMODL name of the parent type. ie does it extend some other class)</li> <li>version (the version of the type. this is not the vSphere version more the API version. these versions are found in the WSDL) </li> <li>props (properties of the type)</li> </ol> <p>So far for our example we have <code>vim.AboutInfo</code> for the vmodlName. The <code>vim</code> part of this is just the namespace of the <code>AboutInfo</code> object.</p> <p>Next we have <code>AboutInfo</code> for the WSDL name. This is just the name of the object.</p> <p>Next is the <code>vmodl.DynamicData</code>. This is the class that <code>AboutInfo</code> extends. See the SOAP documentation here: <a href="http://www.yavijava.com/docs/vim.AboutInfo.html" rel="nofollow">http://www.yavijava.com/docs/vim.AboutInfo.html</a> </p> <p>Next up is the <code>vim.version.version1</code> for the version of the API supported. </p> <p>Finally is the props section. This is a list of tuples that describe the various properties of the object with their types and if they are optional or not. These can also but seen in the documentation link above where properties are defined for the object.</p> <p>The parser uses all of this information to dynamically build objects for you and to build your XML payloads that go to the server.</p> <p>So to answer what is vim and how is it defined: vim is just a namespace for the server side objects that vSphere knows about, and its defined in pyVmomi using the <code>vmodlName</code> which corresponds to the SOAP WSDL/Documentation (see in that link the <code>vim.AboutInfo.html</code>)</p>
0
2016-10-11T06:45:37Z
[ "python", "vim", "pyvmomi" ]
Creating cdata of type `REAL (* vertices)[DIM]` in CFFI
39,937,895
<p>I'm trying to build a python interface around some existing <a href="http://www.cs.ox.ac.uk/stephen.cameron/distances/" rel="nofollow">C code</a> with CFFI. As usual with C code trimmed for performance, it is fraught with extensive macros and typedefs.</p> <p>ATM I am working on replicating following struct</p> <pre><code>#define DIM 3 typedef double REAL; struct Object_structure { int numpoints; REAL (* vertices)[DIM]; int * rings; }; typedef struct Object_structure * Object; </code></pre> <p>The function I'm trying to call expects an argument of type <code>Object</code>.</p> <pre><code>REAL gjk_distance( Object obj1, REAL (* tr1)[DIM+1], Object obj2, REAL (* tr2)[DIM+1], REAL wpt1[DIM], REAL wpt2[DIM], struct simplex_point * simplex, int use_seed ); </code></pre> <p>I have written the following python class for representing such an object/struct, but I'm having trouble converting it into the expected cdata object. (For now I just considering a UnitCube, but ultimately I'll want to generalize that.)</p> <pre><code>class Box: def __init__(self, pos): self._weakkeydict = weakref.WeakKeyDictionary() self.numpoints = 8 self.rings = [ 8, 12, 16, 20, 24, 28, 32, 36, 3, 1, 4, -1, 0, 2, 5, -1, 1, 3, 6, -1, 2, 0, 7, -1, 7, 5, 0, -1, 4, 6, 1, -1, 5, 7, 2, -1, 6, 4, 3, -1] x, y, z = pos self.vertices = [ [x+0, y+0, z+0], [x+1, y+0, z+0], [x+1, y+1, z+0], [x+0, y+1, z+0], [x+0, y+0, z+1], [x+1, y+0, z+1], [x+1, y+1, z+1], [x+0, y+1, z+1], ] @property def cdata(self): self._weakkeydict.clear() #ptr_numpoints = ffi.new("int", self.numpoints) ptr_rings = ffi.new("int[]", self.rings) vertices = [ffi.new("REAL[3]", v) for v in self.vertices] ptr_vertices = ffi.new("REAL *[3]", vertices ) ptr_obj = ffi.new("Object", { 'numpoints': self.numpoints, 'rings': ptr_rings, 'vertices': ptr_vertices}) self._weakkeydict[ptr_obj] = (ptr_rings, ptr_vertices, vertices) return ptr_obj </code></pre> <p>With the above I'm getting <code>IndexError: too many initializers for 'double *[3]' (got 8)</code> in line <code>ptr_vertices = ffi.new("REAL *[3]", vertices )</code> when calling:</p> <pre><code>box1 = Box((0,0,0)) box2 = Box((10,0,0)) d = lib.gjk_distance( [box1.cdata], ffi.NULL, [box2.cdata], ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL, 0 ) </code></pre> <p>To me it seems as if the dimensions got switched somehow. As it should be an 8 element array with 3 element items. I'm hoping someone can point me in the right direction here.</p>
0
2016-10-08T22:14:21Z
39,938,016
<p>Apparently <code>ptr_vertices = ffi.new("REAL[][3]", self.vertices )</code> is the way to go. For now it appears to work.</p>
0
2016-10-08T22:27:29Z
[ "python", "c", "cffi" ]
Creating cdata of type `REAL (* vertices)[DIM]` in CFFI
39,937,895
<p>I'm trying to build a python interface around some existing <a href="http://www.cs.ox.ac.uk/stephen.cameron/distances/" rel="nofollow">C code</a> with CFFI. As usual with C code trimmed for performance, it is fraught with extensive macros and typedefs.</p> <p>ATM I am working on replicating following struct</p> <pre><code>#define DIM 3 typedef double REAL; struct Object_structure { int numpoints; REAL (* vertices)[DIM]; int * rings; }; typedef struct Object_structure * Object; </code></pre> <p>The function I'm trying to call expects an argument of type <code>Object</code>.</p> <pre><code>REAL gjk_distance( Object obj1, REAL (* tr1)[DIM+1], Object obj2, REAL (* tr2)[DIM+1], REAL wpt1[DIM], REAL wpt2[DIM], struct simplex_point * simplex, int use_seed ); </code></pre> <p>I have written the following python class for representing such an object/struct, but I'm having trouble converting it into the expected cdata object. (For now I just considering a UnitCube, but ultimately I'll want to generalize that.)</p> <pre><code>class Box: def __init__(self, pos): self._weakkeydict = weakref.WeakKeyDictionary() self.numpoints = 8 self.rings = [ 8, 12, 16, 20, 24, 28, 32, 36, 3, 1, 4, -1, 0, 2, 5, -1, 1, 3, 6, -1, 2, 0, 7, -1, 7, 5, 0, -1, 4, 6, 1, -1, 5, 7, 2, -1, 6, 4, 3, -1] x, y, z = pos self.vertices = [ [x+0, y+0, z+0], [x+1, y+0, z+0], [x+1, y+1, z+0], [x+0, y+1, z+0], [x+0, y+0, z+1], [x+1, y+0, z+1], [x+1, y+1, z+1], [x+0, y+1, z+1], ] @property def cdata(self): self._weakkeydict.clear() #ptr_numpoints = ffi.new("int", self.numpoints) ptr_rings = ffi.new("int[]", self.rings) vertices = [ffi.new("REAL[3]", v) for v in self.vertices] ptr_vertices = ffi.new("REAL *[3]", vertices ) ptr_obj = ffi.new("Object", { 'numpoints': self.numpoints, 'rings': ptr_rings, 'vertices': ptr_vertices}) self._weakkeydict[ptr_obj] = (ptr_rings, ptr_vertices, vertices) return ptr_obj </code></pre> <p>With the above I'm getting <code>IndexError: too many initializers for 'double *[3]' (got 8)</code> in line <code>ptr_vertices = ffi.new("REAL *[3]", vertices )</code> when calling:</p> <pre><code>box1 = Box((0,0,0)) box2 = Box((10,0,0)) d = lib.gjk_distance( [box1.cdata], ffi.NULL, [box2.cdata], ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL, 0 ) </code></pre> <p>To me it seems as if the dimensions got switched somehow. As it should be an 8 element array with 3 element items. I'm hoping someone can point me in the right direction here.</p>
0
2016-10-08T22:14:21Z
39,938,023
<p>If you are creating a single item, use <code>ffi.new('REAL(*)[3]', [1, 2, 3])</code>. The parenthesis around the <code>*</code> is important.</p> <p>In C, the type <code>REAL(*)[3]</code> means a pointer to array (size=3) of REAL, while <code>REAL*[3]</code> means an array (size=3) of pointer to real. See <a href="http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation">C pointer to array/array of pointers disambiguation</a> for detail.</p> <p>Now, you are creating an array of items, CFFI <a href="http://cffi.readthedocs.io/en/latest/ref.html#ffi-new" rel="nofollow">expects an array type</a> instead, <a href="http://stackoverflow.com/a/39938016/224671">as you have already discovered</a>. This can be compared as:</p> <pre><code>ffi.new('int*', 1) # ok ffi.new('int[]', 1) # wrong ffi.new('int*', [1, 2, 3]) # wrong ffi.new('int[]', [1, 2, 3]) # ok ffi.new('REAL(*)[3]', [0.1, 0.2, 0.3]) # ok ffi.new('REAL[][3]', [0.1, 0.2, 0.3]) # wrong ffi.new('REAL(*)[3]', [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) # wrong ffi.new('REAL[][3]', [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) # ok </code></pre>
1
2016-10-08T22:27:56Z
[ "python", "c", "cffi" ]
Scrapy doesn`t make POST-requests
39,937,918
<p>I write my Scrapy spider which should handle some site with AJAX. In theory it should work OK and moreover it works OK when I use it manually with fetch() in Scrapy shell, but when I run "scrapy crawl ..." I don`t see any POST requests in log and no items are scraped. What can it be and what is the source of the problem?</p> <pre><code> import scrapy from scrapy import Request, FormRequest import json class ExpertSpider(scrapy.Spider): name = "expert" allowed_domains = ["expert.fi"] start_urls = ( 'http://www.expert.fi/', ) def parse(self, response): categories = response.xpath('//div[@id="categories-navigation"]//a/@href').extract() for cat in categories: yield Request(response.urljoin(cat), callback=self.parseCat) def parseCat(self, response): catMenu = response.xpath('//div[@id="category-left-menu"]') if catMenu: subCats = catMenu.xpath('.//a[@class="category"]/@href').extract() for subCat in subCats: yield Request(response.urljoin(subCat), callback=self.parseCat) else: self.parseProdPage(response) print "I`ve reached this point" # debug def parseProdPage(self, response): catId = response.css... url = 'https://www.expert.fi/Umbraco/Api/Product/ProductsByCategory' data = dict() ... jsonDict = json.dumps(data) heads = dict() heads['Content-Type'] = 'application/json;charset=utf-8' heads['Content-Length'] = len(jsonDict) heads['Accept'] = 'application/json, text/plain, */*' heads['Referer'] = response.url return Request(url=url, method="POST", body=jsonDict, headers=heads, callback=self.startItemProc) def startItemProc(self, response): resDict = json.loads(response.body) item = dict() for it in resDict['Products']: # Product data ... item['Category Path'] = it['Breadcrumb'][-1]['Name'] + ''.join([' &gt; ' + crumb['Name'] for crumb in it['Breadcrumb'][-2::-1]]) # Make the new request for delivery price url = 'https://www.expert.fi/Umbraco/Api/Cart/GetFreightOptionsForProduct' data = dict() ... jsonDict = json.dumps(data) heads = dict() heads['Content-Type'] = 'application/json;charset=utf-8' heads['Content-Length'] = len(jsonDict) heads['Accept'] = 'application/json, text/plain, */*' heads['Referer'] = item['Product URL'] req = Request(url=url, method="POST", body=jsonDict, headers=heads, callback=self.finishItemProc) req.meta['item'] = item yield req def finishItemProc(self, response): item = response.meta['item'] ansList = json.loads(response.body) for delivery in ansList: if delivery['Name'] == ... item['Delivery price'] = delivery['Price'] return item </code></pre> <p>The log is:</p> <pre><code>2016-10-09 01:11:16 [scrapy] INFO: Dumping Scrapy stats: {'downloader/exception_count': 9, 'downloader/exception_type_count/twisted.internet.error.DNSLookupError': 1, 'downloader/exception_type_count/twisted.internet.error.TimeoutError': 8, 'downloader/request_bytes': 106652, 'downloader/request_count': 263, 'downloader/request_method_count/GET': 263, 'downloader/response_bytes': 5644786, 'downloader/response_count': 254, 'downloader/response_status_count/200': 252, 'downloader/response_status_count/301': 1, 'downloader/response_status_count/302': 1, 'dupefilter/filtered': 19, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 10, 8, 22, 11, 16, 949472), 'log_count/DEBUG': 265, 'log_count/INFO': 11, 'request_depth_max': 3, 'response_received_count': 252, 'scheduler/dequeued': 263, 'scheduler/dequeued/memory': 263, 'scheduler/enqueued': 263, 'scheduler/enqueued/memory': 263, 'start_time': datetime.datetime(2016, 10, 8, 22, 7, 7, 811163)} 2016-10-09 01:11:16 [scrapy] INFO: Spider closed (finished) </code></pre>
0
2016-10-08T22:16:24Z
39,950,062
<p>The request returned by the <code>parseProdPage</code> method is not used inside the <code>parseCat</code> method. You should start by <em>yielding</em> that: <code>yield self.parseProdPage(response)</code></p> <p>Also, you probably want to set <code>dont_filter=True</code> in that same request, otherwise most of them will be filtered out (because all of them have the same URL).</p>
0
2016-10-10T01:03:47Z
[ "python", "ajax", "scrapy" ]
My PyQt app runs fine inside Idle but throws an error when trying to run from cmd
39,937,950
<p>So I'm learning PyQt development and I typed this into a new file inside IDLE:</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def window(): app = QApplication(sys.argv) win = QDialog() b1 = QPushButton(win) b1.setText("Button1") b1.move(50,20) b1.clicked.connect(b1_clicked) b2=QPushButton(win) b2.setText("Button2") b2.move(50,50) QObject.connect(b2,SIGNAL("clicked()"),b2_clicked) win.setGeometry(100,100,200,100) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) def b1_clicked(): print("Button 1 clicked") def b2_clicked(): print("Button 2 clicked") if __name__ == '__main__': window() </code></pre> <p>The app does what is supposed to, which is to open a dialog box with two buttons on it, when run inside IDLE. When I try to run the same program from cmd I get this message:</p> <p>Traceback (most recent call last): File "C:\Python34\Basic2buttonapp.py", line 2, in from PyQt4.QtCore import * ImportError: No module named 'PyQt4'</p> <p>I've already tried typing python.exe inside cmd to see if Im running the correct version of python from within the cmd, but this does not seem to be the problem. I know it has to do with the communication between python 3.4 and the module, but it seems weird to me that it only happens when trying to run it from cmd. </p> <p>If anyone has the solution I'll be very thankful. </p>
0
2016-10-08T22:19:30Z
39,974,456
<p>This is because when running from the command line you're using a different version of Python to the one in IDLE (with different installed packages). You can find which Python is being used by running the following from the command line:</p> <pre><code>python -c "import sys;print(sys.executable)" </code></pre> <p>...or within IDLE:</p> <pre><code>import sys print(sys.executable) </code></pre> <p>If those two don't match, there is your problem. To fix it, you need to update your <code>PATH</code> variable to put the <em>parent folder</em> of the Python executable referred to by IDLE at the front. You can get instructions of how to do this on Windows <a href="http://stackoverflow.com/questions/9546324/adding-directory-to-path-environment-variable-in-windows">here</a>.</p>
0
2016-10-11T09:41:02Z
[ "python", "cmd", "pyqt", "pyqt4", "python-3.4" ]
Given a Dictionary and a list of letters, find all possible words that can be created with the letters
39,937,958
<p>The function scoreList(Rack) takes in a list of letters. You are also given a global variable Dictionary: <code>["a", "am", "at", "apple", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"]</code>. </p> <p>Using a list of letters find all possible words that can be made with the letters that are in the Dictionary. For each word that can be made also find the score of that word using scrabbleScore.</p> <p>scrabbleScore = </p> <pre><code> [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ] </code></pre> <p>I can use expressions made up of list comprehensions(map, filter, reduce, etc.), if statements, and for loops but only if they are in the context of a list comprehension.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; scoreList(["a", "s", "m", "t", "p"]) [['a', 1], ['am', 4], ['at', 2], ['spam', 8]] &gt;&gt;&gt; scoreList(["a", "s", "m", "o", "f", "o"]) [['a', 1], ['am', 4], ['foo', 6]] </code></pre> <p>The order in which they are presented does not matter. It also must remain a list and not a dic. Would love some help with this problem or if you could give me a better understanding of how to use map or filter in this problem.</p> <p>MyCode:</p> <pre><code>def scoreList(Rack): test = [x for x in Dictionary if all(y in Rack for y in x)] return test </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; scoreList(["a", "s", "m", "t", "p"]) ['a', 'am', 'at', 'spam'] </code></pre> <p>As you can see I was able to find the words, but not the score. How could I find it without using dict?</p>
0
2016-10-08T22:20:47Z
39,938,119
<p>Below is the sample code to achieve this:</p> <pre><code>score = [["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10]] my_list = ["a", "am", "at", "apple", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"] score_dict = dict(score) # Storing score value as dict def get_word_score(my_list): return [(item, sum(score_dict[a] for a in item)) for item in my_list] get_word_score(my_list) # returns: [('a', 1), ('am', 4), ('at', 2), ('apple', 9), ('bat', 5), ('bar', 5), ('babble', 12), ('can', 5), ('foo', 6), ('spam', 8), ('spammy', 15), ('zzyzva', 39)] </code></pre>
0
2016-10-08T22:41:22Z
[ "python", "list", "dictionary" ]
Given a Dictionary and a list of letters, find all possible words that can be created with the letters
39,937,958
<p>The function scoreList(Rack) takes in a list of letters. You are also given a global variable Dictionary: <code>["a", "am", "at", "apple", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"]</code>. </p> <p>Using a list of letters find all possible words that can be made with the letters that are in the Dictionary. For each word that can be made also find the score of that word using scrabbleScore.</p> <p>scrabbleScore = </p> <pre><code> [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ] </code></pre> <p>I can use expressions made up of list comprehensions(map, filter, reduce, etc.), if statements, and for loops but only if they are in the context of a list comprehension.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; scoreList(["a", "s", "m", "t", "p"]) [['a', 1], ['am', 4], ['at', 2], ['spam', 8]] &gt;&gt;&gt; scoreList(["a", "s", "m", "o", "f", "o"]) [['a', 1], ['am', 4], ['foo', 6]] </code></pre> <p>The order in which they are presented does not matter. It also must remain a list and not a dic. Would love some help with this problem or if you could give me a better understanding of how to use map or filter in this problem.</p> <p>MyCode:</p> <pre><code>def scoreList(Rack): test = [x for x in Dictionary if all(y in Rack for y in x)] return test </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; scoreList(["a", "s", "m", "t", "p"]) ['a', 'am', 'at', 'spam'] </code></pre> <p>As you can see I was able to find the words, but not the score. How could I find it without using dict?</p>
0
2016-10-08T22:20:47Z
39,938,259
<p>You can use <code>itertools</code> to generate all possible permutations of words from a set of characters, but note if your input list becomes large this will become a lengthy and memory consuming process.</p> <pre><code>import itertools d = dict([ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ]) words = ["a", "am", "at", "apple", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"] def scoreList(l): perms = itertools.chain.from_iterable(list(itertools.permutations(l,r)) for r in range(1,len(l))) return [["".join(x),sum(d[c] for c in "".join(x))] for x in set(perms) if "".join(x) in words] print(scoreList(["a", "s", "m", "t", "p"])) # Outputs: [['at', 2], ['a', 1], ['spam', 8], ['am', 4]] print(scoreList(["a", "s", "m", "o", "f", "o"])) # Outputs: [['a', 1], ['foo', 6], ['am', 4]] </code></pre>
1
2016-10-08T23:01:02Z
[ "python", "list", "dictionary" ]
Adding values to JSON in Python2.7
39,937,986
<p>I have been tasked with combining data from two different sources into one JSON to be used by a web service. I decided to go with flask which I have found to be so easy to use. Anyway, I am retrieving JSON that looks like this ( via urlib2 )....</p> <pre><code>[ [{ "timestamp": 1474088400000, "errors": 1018831, "errorTotal": 72400021, "errorTotal2": 0.013022892930509898, "business": 4814994, "breakdown": [{ "type": "type1", "count": 603437 }, { "type": "type2", "count": 256187 }] }] ] </code></pre> <p>All I am trying to do is add a new key pair under "breakdown", specifically "type3", so the JSON object looks like this...</p> <pre><code>[ [{ "timestamp": 1474088400000, "errors": 1018831, "errorTotal": 72400021, "errorTotal2": 0.013022892930509898, "business": 4814994, "breakdown": [{ "type": "type1", "count": 603437 }, { "type": "type2", "count": 256187 }, { "type": "type3", "count": 4533 }] }] ] </code></pre> <p>I thought treating it like key pairs in a list would be the way to go but it doesn't seem to be working. Can anyone point me in the right direction ? Many thanks in advance!</p>
-2
2016-10-08T22:23:50Z
39,938,054
<p>First, you should read the json into Python objects:</p> <pre><code>data = json.loads(jsonstring) </code></pre> <p>Then get to the object to be modified. The data looks like <code>[ [ {... 'breakdown': ...} ] ]</code>, so it is a list of lists of dictionaries. I guess you want all of them:</p> <pre><code>for d in data: for dd in d: d['breakdown'].append({"type": "type3", "count": 4533}) </code></pre> <p>Then convert it back to json:</p> <pre><code>update_json = json.dumps(data) </code></pre>
1
2016-10-08T22:33:54Z
[ "python", "json", "python-2.7" ]
Adding values to JSON in Python2.7
39,937,986
<p>I have been tasked with combining data from two different sources into one JSON to be used by a web service. I decided to go with flask which I have found to be so easy to use. Anyway, I am retrieving JSON that looks like this ( via urlib2 )....</p> <pre><code>[ [{ "timestamp": 1474088400000, "errors": 1018831, "errorTotal": 72400021, "errorTotal2": 0.013022892930509898, "business": 4814994, "breakdown": [{ "type": "type1", "count": 603437 }, { "type": "type2", "count": 256187 }] }] ] </code></pre> <p>All I am trying to do is add a new key pair under "breakdown", specifically "type3", so the JSON object looks like this...</p> <pre><code>[ [{ "timestamp": 1474088400000, "errors": 1018831, "errorTotal": 72400021, "errorTotal2": 0.013022892930509898, "business": 4814994, "breakdown": [{ "type": "type1", "count": 603437 }, { "type": "type2", "count": 256187 }, { "type": "type3", "count": 4533 }] }] ] </code></pre> <p>I thought treating it like key pairs in a list would be the way to go but it doesn't seem to be working. Can anyone point me in the right direction ? Many thanks in advance!</p>
-2
2016-10-08T22:23:50Z
39,938,242
<ol> <li><p>Load the <code>json</code> string</p> <pre><code>json_data = json.loads(json_string) </code></pre></li> <li><p>Iterate over the object and <code>append</code> to the <code>"breakdown"</code> key</p> <pre><code>for item in json_data: for json_dict in item: json_dict["breakdown"].append({"type": "type3", "count": 4533}) </code></pre></li> <li><p>Convert it back to the <code>JSON</code> string</p> <pre><code>json_string = json.dumps(json_data) </code></pre></li> </ol>
1
2016-10-08T22:59:15Z
[ "python", "json", "python-2.7" ]
Python Composite Desing Pattern - RecursionError: maximum recursion depth exceeded
39,938,021
<p>so i was a bit going trough some design patterns books and i decided to make my own in python (the book is for Java), and i stumbled on this issue which i cannot solve,what am i missing here?</p> <p>So why do i get here recursion error?</p> <pre><code>class Component: _components = [] def __init__(self, value): self.value = value def add(self, *components): self._components.extend(components) def remove(self, *components): self._components = list(set(self._components).difference(set(components))) def get_components(self): return self._components def __repr__(self): return "Component value: {}".format(self.value) class ComputerComponent(Component): def turn_on(self): self.on = True for component in self.get_components( ): component.turn_on( ) print("{} turned on".format(self.value)) class Computer(ComputerComponent): pass class LCDScreen(ComputerComponent): pass class Mouse(ComputerComponent): pass class Keyboard(ComputerComponent): pass computer = Computer("computer") lcd_screen = LCDScreen("lcd_screen") mouse = Mouse("mouse") keyboard = Keyboard("keyboard") computer.add(lcd_screen,mouse,keyboard) computer.turn_on( ) </code></pre>
0
2016-10-08T22:27:42Z
39,938,051
<p><code>_components</code> should be an instance variable, not a class variable. As it is, adding the components to the computer adds them to <em>all</em> the other components. That is, every component is a component of every other component, which results in an infinite loop.</p> <pre><code>class Component: def __init__(self, value): self.value = value self._components = [] def add(self, *components): self._components.extend(components) def remove(self, *components): self._components = list(set(self._components).difference(set(components))) def get_components(self): return self._components def __repr__(self): return "Component value: {}".format(self.value) </code></pre>
1
2016-10-08T22:33:38Z
[ "python", "recursion", "composite" ]
Ziping files with python. Windows cant unzip
39,938,077
<p>I have this ziping script in python :</p> <pre><code> def zipdir(self,path, ziph): # ziph is zipfile handle paths = os.listdir(path) for p in paths: p = os.path.join(path, p) # Make the path relative if os.path.isfile(p): # Recursive case ziph.write(p) # Write the file to the zipfile #needs to be closed after use def createZipHandler(self,name): zipf = zipfile.ZipFile(name+'.zip', 'w') return zipf </code></pre> <p>The Plan is to call this class and create a zip which should be opened on windows maschines. When running this script on windows everything work fine. zip created and accessable. But when calling this in my code on a raspberry I cant open the zip on my windows maschine.</p> <p>Does anybody know why? </p>
0
2016-10-08T22:36:26Z
39,995,888
<p>Found the Problem. The zipping went fine. I send the zip over email and set a wrong header-element.</p>
0
2016-10-12T10:05:27Z
[ "python", "zip" ]
How to generate random number with a large number of decimals in Python?
39,938,080
<p>How it's going?</p> <p>I need to generate a random number with a large number of decimal to use in advanced calculation.</p> <p>I've tried to use this code:</p> <pre><code>round(random.uniform(min_time, max_time), 1) </code></pre> <p>But it doesn't work for length of decimals above 15.</p> <p>If I use, for e.g:</p> <pre><code>round(random.uniform(0, 0.5), 100) </code></pre> <p>It returns 0.586422176354875, but I need a code that returns a number with 100 decimals. </p> <p><strong>Can you help me?</strong></p> <p>Thanks!</p>
1
2016-10-08T22:36:42Z
39,938,147
<h2>100 decimals</h2> <p>The first problem is how to create a number with 1000 decimals at all.</p> <p>This won't do:</p> <pre><code>&gt;&gt;&gt; 1.23456789012345678901234567890 1.2345678901234567 </code></pre> <p>Those are floating point numbers which have limitations far from 100 decimals.</p> <p>Luckily, in Python, there is the <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code> built-in module</a> which can help:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901') Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901') </code></pre> <p>Decimal can have any precision you need and it won't introduce <a href="http://stackoverflow.com/q/19473770/389289">floating point errors</a>, but it will be much slower.</p> <h2>random</h2> <p>Now you just have to create a string with 100 decmals and give it to <code>Decimal</code>.</p> <p>This will create one random digit:</p> <pre><code>random.choice('0123456789') </code></pre> <p>This will create 100 random digits and concatenate them:</p> <pre><code>''.join(random.choice('0123456789') for i in range(100)) </code></pre> <p>Now just create a <code>Decimal</code>:</p> <pre><code>Decimal('0.' + ''.join(random.choice('0123456789') for i in range(100))) </code></pre> <p>This creates a number between 0 and 1. Multiply it or divide to get a different range.</p>
1
2016-10-08T22:45:36Z
[ "python", "random", "numbers" ]
python class import issue
39,938,100
<p>I am new to python and doing some programming for school I have written code for a roster system and I am supposed to use dictionaries. I keep getting error No module named 'players_Class' Can someone tell me what I am doing wrong</p> <pre><code>class Players: def __init__(self, name, number, jersey): self.__name = name self.__number = number self.__jersey = jersey def setname(self, name): self.__name = name def setnumber(self, number): self.__number = number def setjersey(self, jersey): self.__jersey = jersey def getname(self): return self.__name def getnumber(self): return self.__number def getjersey(self): return self.__jersey def displayData(self): print("") print("Player Information ") print("------------------------") print("Name:", self.__name) print("Phone Number:", self.__number) print("Jersey Number:", self.__jersey) import players_Class def displayMenu(): print("1. Display Players") print("2. Add Player") print("3. Remove Player") print("4. Edit Player") print("9. Exit Program") print("") return int(input("Selection&gt; ")) def printPlayers(players): if len(players) == 0: print("Player not in List.") else: for x in players.keys(): players[x].displayData(self) def addplayers(players): newName = input("Enter new Players Name: ") newNumber = int(input("Players Phone Number: ")) newJersey = input("Players Jersey Number: ") players[newName] = (newName, newNumber, newJersey) return players def removeplayers(players): removeName = input("Enter Player Name to be removed: ") if removeName in players: del players[removeName] else: print("Player not found in list.") return players def editplayers(players): oldName = input("Enter the Name of the Player you want to edit: ") if oldName in players: newName = input("Enter the player new name: ") newNumber = int(input("Players New Number: ")) newJersey = input("Players New Jersey Number: ") players[oldName] = petClass.Pet(newName, newNumber, newJersey) else: print("Player Not Found") return players print("Welcome to the Team Manager") players = {} menuSelection = displayMenu() while menuSelection != 9: if menuSelection == 1: printPlayers(players) elif menuSelection == 2: players = addplayers(players) elif menuSelection == 3: players = removeplayers(players) elif menuSelection == 4: players = editplayers(players) menuSelection = displayMenu() print ("Exiting Program...") </code></pre>
0
2016-10-08T22:38:46Z
39,938,154
<p>you have unused </p> <pre><code>import players_Class </code></pre> <p>statement in your code. just erase it!</p>
0
2016-10-08T22:46:45Z
[ "python", "python-3.x" ]
python wsgi pymorphy2 error iternal
39,938,122
<p>trying to return value of pymorphy2 using apache with wsgi module &amp; getting error 500 log says TypeError: sequence of byte string values expected, value of type Parse found</p> <p>i dont know what to do! in Python im rookie</p> <p>my python code is</p> <pre><code>import pymorphy2 import cgi morph = pymorphy2.MorphAnalyzer() morphid = morph.parse(u'конь') def app(environ, start_response): words = morphid start_response('200 OK', [('Content-Type', 'text/html')]) return [words] </code></pre> <hr> <p>but in shell it works... :(<br> please help i dont understand what is form or type of var words need to me.</p> <p>or may be that is all wrong</p> <p>in shell result is</p> <blockquote> <blockquote> <blockquote> <p>morph = pymorphy2.MorphAnalyzer()</p> <p>words = morph.parse(u'конь')</p> <p>print "words"</p> </blockquote> </blockquote> </blockquote> <pre><code>[Parse(word=u'\xf1\xf2\xe0\xeb\xe8', tag=OpencorporaTag('LATN'), normal_form=u'\xf1\xf2\xe0\xeb\xe8', score=1.0, methods_stack=((&lt;LatinAnalyzer&gt;, u'\xf1\xf2\xe0\xeb\xe8'),))] </code></pre> <p>Thanks to everyone!</p>
-2
2016-10-08T22:41:45Z
39,938,844
<p>As you can see, you need to return sequence of byte string but you are returning word which is of type <code>Parse</code>. if you want the response to be exactly the same as the thing you get from the console, try</p> <pre><code>words = str(morphid[0]).encode() </code></pre> <p>It will return the string of the result which is <code>encoded()</code> thus can be used as a response.</p>
0
2016-10-09T00:42:44Z
[ "python", "wsgi" ]
Python: Ending line every N characters when writing to text file
39,938,160
<p>I am reading the webpage at "<a href="https://google.com" rel="nofollow">https://google.com</a>" and writing as a string to a notepad file. In the notepad file, I want to break and make a newline every N characters while writing, so that I don't have to scroll horizontally in notepad. I have looked up a number of solutions but none of them do this so far. Thanks for any suggestions.</p> <pre><code>import urllib.request page = urllib.request.urlopen("http://www.google.com") webfile = page.readlines() with open("file01.txt", 'w') as f: for line in webfile: f.write(str(line)) f.close() </code></pre>
1
2016-10-08T22:47:22Z
39,938,187
<p>This will split each line at 100 characters:</p> <pre><code>for line in webfile: while len(line) &gt; 100: # split the line f.write(line[:100]) # write the first 100 characters f.write('\n') # write the newline character line = line[100:] # remember the remainder of the line f.write(str(line)) </code></pre>
0
2016-10-08T22:50:50Z
[ "python" ]
Python: Ending line every N characters when writing to text file
39,938,160
<p>I am reading the webpage at "<a href="https://google.com" rel="nofollow">https://google.com</a>" and writing as a string to a notepad file. In the notepad file, I want to break and make a newline every N characters while writing, so that I don't have to scroll horizontally in notepad. I have looked up a number of solutions but none of them do this so far. Thanks for any suggestions.</p> <pre><code>import urllib.request page = urllib.request.urlopen("http://www.google.com") webfile = page.readlines() with open("file01.txt", 'w') as f: for line in webfile: f.write(str(line)) f.close() </code></pre>
1
2016-10-08T22:47:22Z
39,938,217
<p>Better yet, use the <a href="https://docs.python.org/2.7/library/textwrap.html" rel="nofollow">textwrap</a> library. Then you can use</p> <pre><code>textwrap.fill(str(line)) </code></pre> <p>and get breaks on whitespace and other useful additions.</p>
2
2016-10-08T22:55:16Z
[ "python" ]
Regular Expression to replace some dots with commas in customers' comments
39,938,210
<p>I need to write a Regular Expression to replace <code>'.'</code> with <code>','</code> in some patients' comments about drugs. They were supposed to use comma after mentioning a side effect, but some of them used dot. for example: </p> <pre><code>text = "the drug side-effects are: night mare. nausea. night sweat. bad dream. dizziness. severe headache. I suffered. she suffered. she told I should change it." </code></pre> <p>I wrote a regular expression code to detect one word (such as, headache) or two words (such as, bad dream) surround by two dots:</p> <h1>detecting a word surrounded by two dots:</h1> <pre><code>text= re.sub (r'(\.)(\s*\w+\s*\.)',r',\2 ', text ) </code></pre> <h1>detecting two words surrounded by two dots:</h1> <pre><code>text = re.sub (r'(\.)(\s*\w+\s\w+\s*\.)',r',\2 ', text11 ) </code></pre> <p>This is the output:</p> <pre><code>the drug side-effects are: night mare, nausea, night sweat. bad dream, dizziness, severe headache. I suffered, she suffered. she told I should change it. </code></pre> <p>But it should be: </p> <pre><code>the drug side-effects are: night mare, nausea, night sweat, bad dream, dizziness, severe headache. I suffered. she suffered. she told I should change it. </code></pre> <p>My code did not replace <code>dot</code> after <code>night sweat to ','</code>. I addition, <code>if a sentence starts with a subject pronoun (such as I and she) I do not want to change dot to comma after it, even if it has two words (such as, I suffered)</code>. I do not know how to add this condition to my code. </p> <p>Any suggestion? Thank you !</p>
1
2016-10-08T22:54:25Z
39,939,223
<p>You can use the following pattern:</p> <pre><code>\.(\s*(?!(?:i|she)\b)\w+(?:\s+\w+)?\s*)(?=[^\w\s]|$) </code></pre> <p>This matches a dot, then captures one or two words where the first one is none of your mentioned pronouns (you will need to expand that list most likely). This has to be followed by a character that is neither a word character nor a space (e.g. <code>.</code> <code>!</code> <code>:</code> <code>,</code>) or the end of the string.</p> <p>You will then have to replace it with <code>,\1</code></p> <p>In python</p> <pre class="lang-py prettyprint-override"><code>import re text = "the drug side-effects are: night mare. nausea. night sweat. bad dream. dizziness. severe headache. I suffered. she suffered. she told I should change it." text = re.sub(r'\.(\s*(?!(?:i|she)\b)\w+(?:\s+\w+)?\s*)(?=[^\w\s]|$)', r',\1', text, flags=re.I) print(text) </code></pre> <p>Outputs</p> <pre><code>the drug side-effects are: night mare, nausea, night sweat, bad dream, dizziness, severe headache. I suffered. she suffered. she told I should change it. </code></pre> <p>This is likely not absolutely failsafe and you might have to expand the pattern for some edge cases.</p>
1
2016-10-09T02:01:18Z
[ "python", "regex" ]
Error with useing .split() with user input in python
39,938,294
<p>So I am trying to make a basic address book in python that can save contacts and load them using pickle, but for some reason I get an error when I try to put in a contact My code is:</p> <pre><code>import pickle class Contact: def __init__(self, firstname, lastname, phonenumber, adress): self.firstname = firstname self.lastname = lastname self.phonenumber = phonenumber self.adress = adress print('Welcome to your adress book, would you like to:\n1. Add a contact\n2. Look at a contact\n3. Close the program') while True: choice = int(input()) if choice == 1: print('Type in their information, with the format\nfirstname lastname phonenumber adress') info = input().split() pickle.dump(info, open(info[0].lower() + '.pkl' , 'w+')) continue elif choice == 2: print('What is their first name?') fn = input().lower() x = pickle.load(open(fn + '.pkl', 'rb')) print(x[0] + x[1] + x[2] + x[3]) continue elif choice == 3: break else: print('Invalid input.') continue </code></pre> <p>The error says: </p> <pre><code>Traceback (most recent call last): File "C:\Users\keith\Desktop\adress_book.py", line 13, in &lt;module&gt; info = input().split() File "&lt;string&gt;", line 1 Bob Smith 123456789 123street ^ SyntaxError: invalid syntax </code></pre> <p>Any help would be greatly appreciated, thanks.</p>
0
2016-10-08T23:05:15Z
39,938,371
<p>I think you're looking for <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>raw_input</code></a>. Unlike in Python 3, in Python 2.x, <a href="https://docs.python.org/2/library/functions.html#input" rel="nofollow"><code>input</code></a> parses and evaluates the string as a Python expression.</p> <p>From the <code>input</code> docs:</p> <blockquote> <p>This function does not catch user errors. If the input is not syntactically valid, a <code>SyntaxError</code> will be raised.</p> </blockquote>
0
2016-10-08T23:15:36Z
[ "python", "python-2.7" ]
How can I get this Python function to return a string instead of a list containing one string?
39,938,296
<p>How can I get this Python function to return a string instead of a list containing one string?</p> <pre><code>def num_vowels(s): """ returns the number of vowels in the string s input: s is a string of 0 or more lowercase letters """ if s == '': return 0 else: num_in_rest = num_vowels(s[1:]) if s[0] in 'aeiou': return 1 + num_in_rest else: return 0 + num_in_rest #most vowels returns a list not a string def most_vowels(wordlist): '''Takes a list of strings called wordlist and returns the string in the list with the most vowels.''' list_of_num_vowels = [num_vowels(x) for x in wordlist] max_val = max(list_of_num_vowels) return [x for x in wordlist if num_vowels(x) == max_val] </code></pre> <p>Some test cases:</p> <pre><code>most_vowels(['vowels', 'are', 'amazing', 'things']) </code></pre> <p>output: <code>'amazing'</code></p> <pre><code>most_vowels(['obama', 'bush', 'clinton']) </code></pre> <p>output: <code>'obama'</code></p> <p>Thanks!</p>
-2
2016-10-08T23:05:23Z
39,938,336
<p>your <code>most_vowels()</code> function is using a <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a> to filter out matching values and return a new list. You could output the string directly in two ways.</p> <p>The first way is to index the first result from the result of the comprehension.</p> <pre><code>return [x for x in wordlist if num_vowels(x) == max_val][0] </code></pre> <p>The other option, if you think you may get multiple results but still want a string, is to join any results with a comma (or other separator) into a string.</p> <pre><code>return ','.join([x for x in wordlist if num_vowels(x) == max_val]) </code></pre> <p>This will convert <code>['first', 'second']</code> to <code>'first,second'</code>.</p>
1
2016-10-08T23:09:52Z
[ "python", "string" ]
How can I get this Python function to return a string instead of a list containing one string?
39,938,296
<p>How can I get this Python function to return a string instead of a list containing one string?</p> <pre><code>def num_vowels(s): """ returns the number of vowels in the string s input: s is a string of 0 or more lowercase letters """ if s == '': return 0 else: num_in_rest = num_vowels(s[1:]) if s[0] in 'aeiou': return 1 + num_in_rest else: return 0 + num_in_rest #most vowels returns a list not a string def most_vowels(wordlist): '''Takes a list of strings called wordlist and returns the string in the list with the most vowels.''' list_of_num_vowels = [num_vowels(x) for x in wordlist] max_val = max(list_of_num_vowels) return [x for x in wordlist if num_vowels(x) == max_val] </code></pre> <p>Some test cases:</p> <pre><code>most_vowels(['vowels', 'are', 'amazing', 'things']) </code></pre> <p>output: <code>'amazing'</code></p> <pre><code>most_vowels(['obama', 'bush', 'clinton']) </code></pre> <p>output: <code>'obama'</code></p> <p>Thanks!</p>
-2
2016-10-08T23:05:23Z
39,938,338
<p>You can get the answer straight from <a href="https://docs.python.org/2/library/functions.html#max" rel="nofollow"><strong><code>max</code></strong></a> by comparing the number of vowels instead of the usual ordering for strings, by passing <code>num_vowels</code> as <code>key</code>:</p> <pre><code>def most_vowels(wordlist): return max(worldlist, key=num_vowels) </code></pre> <p>Alternatively, the way you've found the most number of vowels as <code>max_val</code> you could use <a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><strong><code>next</code></strong></a> with a comprehension filter:</p> <pre><code> return next(word for word in wordlist if num_vowels(word) == max_val) </code></pre>
0
2016-10-08T23:10:06Z
[ "python", "string" ]
How can I get this Python function to return a string instead of a list containing one string?
39,938,296
<p>How can I get this Python function to return a string instead of a list containing one string?</p> <pre><code>def num_vowels(s): """ returns the number of vowels in the string s input: s is a string of 0 or more lowercase letters """ if s == '': return 0 else: num_in_rest = num_vowels(s[1:]) if s[0] in 'aeiou': return 1 + num_in_rest else: return 0 + num_in_rest #most vowels returns a list not a string def most_vowels(wordlist): '''Takes a list of strings called wordlist and returns the string in the list with the most vowels.''' list_of_num_vowels = [num_vowels(x) for x in wordlist] max_val = max(list_of_num_vowels) return [x for x in wordlist if num_vowels(x) == max_val] </code></pre> <p>Some test cases:</p> <pre><code>most_vowels(['vowels', 'are', 'amazing', 'things']) </code></pre> <p>output: <code>'amazing'</code></p> <pre><code>most_vowels(['obama', 'bush', 'clinton']) </code></pre> <p>output: <code>'obama'</code></p> <p>Thanks!</p>
-2
2016-10-08T23:05:23Z
39,938,360
<p>Your <code>most_vowels</code> function sort of reinvents the wheel. Python already given you a much simpler facility for this this - using <a href="https://docs.python.org/2/library/functions.html#max" rel="nofollow"><code>max</code></a> with an optional <code>key</code> argument, and just picking the word with the most vowels outright:</p> <pre><code>def most_vowels(wordlist): return max(wordlist, key=num_vowels) </code></pre>
0
2016-10-08T23:13:28Z
[ "python", "string" ]
Iterating over Dataframe
39,938,299
<p>I'm trying to iterate over a dataframe where the "Filename" column is consisted of strings. I have the following, however, I get the following Error.</p> <p>result is a different Dataframe</p> <pre><code>k = 1 l = 0 for row in df.iterrows(): if k % 3 == 0: result.loc[l, 'H2'] = row['Filename'] l += 1 elif k % 2 == 0: result.loc[l, 'H1'] = row['Filename'] else: result.loc[l, 'V'] = row['Filename'] k += 1 </code></pre> <p>The error I get is:</p> <pre><code>TypeError: tuple indices must be integers or slices, not str </code></pre> <p>Any idea of a fix?</p>
1
2016-10-08T23:05:45Z
39,938,362
<p>when you iter through df with <code>df.iterrows()</code> it will return a tuple for each row where row[0] is the index of the row and row[1] is a Series.</p> <p>so you could do:</p> <pre><code>row[1]['Filename'] </code></pre> <p>personally I like to iter using <code>.itertuples()</code> which returns named tuple :</p> <pre><code>for row in df2.itertuples(): print row.Filename </code></pre>
3
2016-10-08T23:13:37Z
[ "python", "pandas", "dataframe" ]
Iterating over Dataframe
39,938,299
<p>I'm trying to iterate over a dataframe where the "Filename" column is consisted of strings. I have the following, however, I get the following Error.</p> <p>result is a different Dataframe</p> <pre><code>k = 1 l = 0 for row in df.iterrows(): if k % 3 == 0: result.loc[l, 'H2'] = row['Filename'] l += 1 elif k % 2 == 0: result.loc[l, 'H1'] = row['Filename'] else: result.loc[l, 'V'] = row['Filename'] k += 1 </code></pre> <p>The error I get is:</p> <pre><code>TypeError: tuple indices must be integers or slices, not str </code></pre> <p>Any idea of a fix?</p>
1
2016-10-08T23:05:45Z
39,938,482
<p>The simple fix to your problem is to unpack the tuple coming from <code>iterrows</code></p> <pre><code>k = 1 l = 0 for i, row in df.iterrows(): if k % 3 == 0: result.loc[l, 'H2'] = row['Filename'] l += 1 elif k % 2 == 0: result.loc[l, 'H1'] = row['Filename'] else: result.loc[l, 'V'] = row['Filename'] k += 1 </code></pre> <hr> <p>An improvement on this would be to use <code>enumerate</code> to capture <code>k</code> without having to track it yourself.</p> <pre><code>l = 0 for k, (i, row) in enumerate(df.iterrows(), 1): if k % 3 == 0: result.loc[l, 'H2'] = row['Filename'] l += 1 elif k % 2 == 0: result.loc[l, 'H1'] = row['Filename'] else: result.loc[l, 'V'] = row['Filename'] </code></pre> <hr> <p>However, I'm not quite sure what you're doing. If by chance you're trying to capture every 3rd elements starting with the first, second, and third entries, then you aren't accomplishing that. If you're sure of this logic then disregard the following suggestion.</p> <pre><code>pd.concat([df.Filename.iloc[0::3].reset_index(drop=True), df.Filename.iloc[1::3].reset_index(drop=True), df.Filename.iloc[2::3].reset_index(drop=True)], axis=1, keys=['V', 'H1', 'H2']) </code></pre> <p>Or</p> <pre><code>df.Filename.groupby(np.arange(df.shape[0]) % 3) \ .apply(pd.Series.reset_index, drop=True) \ .unstack(0).rename(columns={0: 'V', 1: 'H1', 2: 'H2'}) </code></pre>
3
2016-10-08T23:37:45Z
[ "python", "pandas", "dataframe" ]
Jinja convert string to integer
39,938,323
<p>I am trying to convert a string that has been parsed using a regex into a number so I can multiply it, using Jinja2. This file is a template to be used within an ansible script.</p> <p>I have a series of <code>items</code> which all take the form of <code>&lt;word&gt;&lt;number&gt;</code> such as <code>aaa01</code>, <code>aaa141</code>, <code>bbb05</code>.</p> <p>The idea was to parse the word and number(ignoring leading zeros) and use them later in the template.</p> <p>I wanted to manipulate the number by multiplication and use it. Below is what I have done so far ```</p> <pre><code>{% macro get_host_number() -%} {{ item | regex_replace('^\D*[0]?(\d*)$', '\\1') }} {%- endmacro %} {% macro get_host_name() -%} {{ item | regex_replace('^(\D*)\d*$', '\\1') }} {%- endmacro %} {% macro get_host_range(name, number) -%} {% if name=='aaa' %} {{ ((number*5)+100) | int | abs }} {% elif name=='bbb' %} {{ ((number*5)+200) | int | abs }} {% else %} {{ ((number*5)+300) | int | abs }} {% endif %} {%- endmacro %} {% set number = get_host_number() %} {% set name = get_host_name() %} {% set value = get_host_range(name, number) %} Name: {{ name }} Number: {{ number }} Type: {{ value }} </code></pre> <p>With the above template I am getting an error <code>coercing to Unicode: need string or buffer, int found</code> which i think is telling me it cannot convert the string to integer, however i do not understand why. I have seen examples doing this and working.</p>
0
2016-10-08T23:08:27Z
39,940,452
<p>You need to cast string to int after regex'ing number:</p> <pre><code>{% set number = get_host_number() | int %} </code></pre> <p>And then there is no need in <code>| int</code> inside <code>get_host_range</code> macro.</p>
2
2016-10-09T05:48:14Z
[ "python", "ansible", "jinja2" ]
delete pixel from the raster image with specific range value
39,938,330
<p><strong>update :</strong> any idea how to delete pixel from specific range value raster image with using <code>numpy/scipy</code> or <code>gdal</code>?</p> <p><strong>or how to can create new raster with some class using raster calculation expressions</strong>(better)</p> <p>for example i have a raster image with the 5 class : </p> <pre><code>1. 0-100 2. 100-200 3. 200-300 4. 300-500 5. 500-1000 </code></pre> <p>and i want to delete class 1 range value or maybe class <code>1,2,4,5</code> </p> <p>i begin with this script :</p> <pre><code>import numpy as np from osgeo import gdal ds = gdal.Open("raster3.tif") myarray = np.array(ds.GetRasterBand(1).ReadAsArray()) #print myarray.shape #print myarray.size #print myarray new=np.delete(myarray[::2], 1) </code></pre> <p>but i cant to complete</p> <p>the image <a href="http://i.stack.imgur.com/S4bk4.jpg" rel="nofollow">White in class 5 and black class 1</a></p>
0
2016-10-08T23:09:15Z
39,945,591
<p>Rasters are 2-D arrays of values, with each value being stored in a pixel (which stands for picture element). Each pixel must contain some information. It is not possible to delete or remove pixels from the array because rasters are usually encoded as a simple 1-dimensional string of bits. Metadata commonly helps explain where line breaks are and the length of the bitstring, so that the 1-D bitstring can be understood as a 2-D array. If you "remove" a pixel, then you break the raster. The 2-D grid is no longer valid.</p> <p>Of course, there are many instances where you do want to effectively discard or clean the raster of data. Such an example might be to remove pixels that cover land from a raster of sea-surface temperatures. To accomplish this goal, many geospatial raster formats hold metadata describing what are called NoData values. Pixels containing a NoData value are <strong>interpreted</strong> as not existing. Recall that in a raster, each pixel must contain some information. The NoData paradigm allows the structure and format of rasters to be met, while also giving a way to <strong>mask</strong> pixels from being displayed or analyzed. There is still data (bits, 1s and 0s) at the masked pixels, but it only serves to identify the pixel as invalid.</p> <p>With this in mind, here is an example using <code>gdal</code> which will mask values in the range of 0-100 so they are NoData, and "do not exist". The NoData value will be specified as 0. </p> <pre><code>from osgeo import gdal # open dataset to read, and get a numpy array ds = gdal.Open("raster3.tif", 'r') myarray = ds.GetRasterBand(1).ReadAsArray() # modify numpy array to mask values myarray[myarray &lt;= 100] = 0 # open output dataset, which is a copy of original driver = gdal.GetDriverByName('GTiff') ds_out = driver.CreateCopy("raster3_with_nodata.tif", ds) # write the modified array to the raster ds_out.GetRasterBand(1).WriteArray(myarray) # set the NoData metadata flag ds_out.GetRasterBand(1).SetNoDataValue(0) # clear the buffer, and ensure file is written ds_out.FlushCache() </code></pre>
1
2016-10-09T16:00:00Z
[ "python", "numpy", "image-processing", "scipy", "gdal" ]
Why is are the dicts in this list of dicts empty?
39,938,350
<p>As the title implies; I'm unsure as to why the dictionaries in this list of dictionaries are empty. I print the dictionaries out before I append them to the list and they all have 4 keys/values. </p> <p>Please ignore the 'scrappiness' of the code- I always go through a process of writing it out basically and then refining! </p> <p>Code:</p> <pre><code>import ntpath, sys, tkFileDialog, Tkinter import xml.etree.ElementTree as ET class Comparison: def __init__(self, file): self.file = ET.parse(file) self.filename = self.get_file_name(file) self.root = self.file.getroot() self.file_length = len(self.root) self.data_dict = dict() self.master_list = list() self.parse_xml(self.root) print self.master_list def get_file_name(self, file): filename_list = list() for char in ntpath.basename(str(file)): filename_list.append(char) if ''.join(filename_list[-4:]) == '.xml': return ''.join(filename_list) def parse_xml(self, tree): for child in tree: if tree == self.root: self.step_number = child.attrib['id'] self.data_dict['Step'] = self.step_number if len(child.tag) &gt; 0: self.data_dict['Tag'] = child.tag else: self.data_dict['Tag'] = "" if len(child.attrib) &gt; 0: self.data_dict['Attrib'] = child.attrib else: self.data_dict['Attrib'] = "" if child.text is not None: self.data_dict['Text'] = child.text else: self.data_dict['Text'] = "" print self.data_dict print "Step: "+str(self.data_dict['Step']) try: print "Tag: "+str(self.data_dict['Tag']) except: pass try: for key,value in self.data_dict['Attrib'].iteritems(): print "Attrib: "+str(key) print "Attrib Value: "+str(value) except: pass try: if len(str(self.data_dict['Text'])) &gt; 0: print "Text Length: "+str(len(str(self.data_dict['Text']))) print "Text: "+str(self.data_dict['Text']) except: pass print "" print len(self.data_dict) self.master_list.append(self.data_dict) print self.data_dict self.data_dict.clear() if len(child) &gt; 0: self.parse_xml(child) if __name__ == "__main__": root = Tkinter.Tk() root.iconify() if sys.argv[1] != "": file_a = Comparison(sys.argv[1]) else: file_a = Comparison(tkFileDialog.askopenfilename()) </code></pre>
0
2016-10-08T23:11:27Z
39,938,406
<p>I presume you mean this:</p> <pre><code> print len(self.data_dict) self.master_list.append(self.data_dict) print self.data_dict self.data_dict.clear() </code></pre> <p>The <code>dict</code> is empty because <em>you clear it</em>. Everything is a reference in Python.</p> <pre><code>&gt;&gt;&gt; d = {k:v for k,v in zip(range(5),'abcde')} &gt;&gt;&gt; id(d) 140199719344392 &gt;&gt;&gt; some_list = [] &gt;&gt;&gt; some_list.append(d) &gt;&gt;&gt; some_list [{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}] &gt;&gt;&gt; id(some_list[0]) 140199719344392 &gt;&gt;&gt; d.clear() &gt;&gt;&gt; some_list [{}] &gt;&gt;&gt; </code></pre> <p>If you want a copy to be appended, then you need to explicitely copy it. If a shallow copy will do, then simply use <code>your_dict.copy()</code>:</p> <pre><code>&gt;&gt;&gt; d = {k:v for k,v in zip(range(5),'abcde')} &gt;&gt;&gt; d {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'} &gt;&gt;&gt; id(d) 140199686153480 &gt;&gt;&gt; some_list = [] &gt;&gt;&gt; some_list.append(d.copy()) &gt;&gt;&gt; id(some_list[0]) 140199719344392 &gt;&gt;&gt; d.clear() &gt;&gt;&gt; some_list [{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}] &gt;&gt;&gt; </code></pre>
2
2016-10-08T23:22:55Z
[ "python", "python-2.7" ]
Using strip() method and punctuation in Python
39,938,435
<p>I've been trying to solve this problem for a few hours now and can't come with the right solution, this is the question:</p> <p>Write a loop that creates a new word list, using a string method to strip the words from the list created in Problem 3 of all leading and trailing punctuation. Hint: the string library, which is imported above, contains a constant named punctuation. Three lines of code.</p> <p>Here is my code:</p> <pre><code> import string def litCricFriend(wordList, text): theList = text.lower().replace('-', ' ').split() #problem 3 #problem below for word in theList: word.strip(string.punctuation) return theList </code></pre>
0
2016-10-08T23:29:29Z
39,938,622
<p>You've got a couple bits in your code that... well, I'm not really sure why they're there, to be honest, haha. Let's work through this together!</p> <p>I'm assuming you have been given some text: <code>text = "My hovercraft is full of eels!"</code>. Let's split this into words, make the words lowercase, and remove all punctuation. We know we need <code>string.punctuation</code> and <code>str.split()</code>, and you've also figured out that <code>str.replace()</code> is useful. So let's use these and get our result!</p> <pre><code>import string def remove_punctuation(text): # First, let's remove the punctuation. # We do this by looping through each punctuation mark in the # `string.punctuation` list, and then replacing that mark with # the empty string and re-assigning that to the same variable. for punc in string.punctuation: text = text.replace(punc, '') # Now our text is all de-punctuated! So let's make a list of # the words, all lowercased, and return it in one go: return text.lower().split() </code></pre> <p>Looks to me like the function is only three lines, which is what you said you wanted!</p> <hr> <p>For the advanced reader, you could also use <code>functools</code> and do it in one line (I split it into two for readability, but it's still "one line"):</p> <pre><code>import string import functools def remove_punctuation(text): return functools.reduce(lambda newtext, punc: newtext.replace(punc, ''), punctuation, text).lower().split() </code></pre>
0
2016-10-09T00:00:02Z
[ "python", "strip" ]
how do you add values from a list separately if one variable has two possible outcomes
39,938,449
<p>This assignment calls another function:</p> <pre><code>def getPoints(n): n = (n-1) % 13 + 1 if n == 1: return [1] + [11] if 2 &lt;= n &lt;= 10: return [n] if 11 &lt;= n &lt;= 13: return [10] </code></pre> <p>So my assignment wants me to add the sum of all possible points from numbers from a list of 52 numbers. This is my code so far.</p> <pre><code>def getPointTotal(aList): points = [] for i in aList: points += getPoints(i) total = sum(points) return aList, points, total </code></pre> <p>However the issue is that the integer 1 has two possible point values, 1 or 11. When I do the sum of the points it does everything correctly, but it adds 1 and 11 together whereas I need it to compute the sum if the integer is 1 and if the integer is 11.</p> <p>So for example:</p> <pre><code>&gt;&gt;&gt;getPointTotal([1,26, 12]) # 10-13 are worth 10 points( and every 13th number that equates to 10-13 using n % 13. &gt;&gt;&gt;[21,31] # 21 if the value is 1, 31 if the value is 11. </code></pre> <p>Another example:</p> <pre><code>&gt;&gt;&gt;getPointTotal([1,14]) # 14 is just 14 % 13 = 1 so, 1 and 1. &gt;&gt;&gt;[2, 12, 22] # 1+1=2, 1+11=12, 11+11=22 </code></pre> <p>My output is:</p> <pre><code>&gt;&gt;&gt;getPointTotal([1,14]) &gt;&gt;&gt;[24] #It's adding all of the numbers 1+1+11+11 = 24. </code></pre> <p>So my question is, is how do I make it add the value 1 separately from the value 11 and vice versa. So that way when I do have 1 it would add all the values and 1 or it would add all the values and 11.</p>
3
2016-10-08T23:31:25Z
39,938,882
<p>You make a mistake in storing all the values returned from <code>getPoints()</code>. You should store only the possible totals for the points returned so far. You can store all those in a set, and update them with the all the possible values returned from <code>getPoints()</code>. A set will automatically remove duplicate scores, such as 1+11 and 11+1. You can change the set to a sorted list at the end. Here is my code:</p> <pre><code>def getPointTotal(aList): totals = {0} for i in aList: totals = {p + t for p in getPoints(i) for t in totals} return sorted(list(totals)) </code></pre> <p>I get these results:</p> <pre><code>&gt;&gt;&gt; print(getPointTotal([1,26, 12])) [21, 31] &gt;&gt;&gt; print(getPointTotal([1,14])) [2, 12, 22] </code></pre>
4
2016-10-09T00:50:11Z
[ "python", "list", "python-3.x", "sum" ]
how do you add values from a list separately if one variable has two possible outcomes
39,938,449
<p>This assignment calls another function:</p> <pre><code>def getPoints(n): n = (n-1) % 13 + 1 if n == 1: return [1] + [11] if 2 &lt;= n &lt;= 10: return [n] if 11 &lt;= n &lt;= 13: return [10] </code></pre> <p>So my assignment wants me to add the sum of all possible points from numbers from a list of 52 numbers. This is my code so far.</p> <pre><code>def getPointTotal(aList): points = [] for i in aList: points += getPoints(i) total = sum(points) return aList, points, total </code></pre> <p>However the issue is that the integer 1 has two possible point values, 1 or 11. When I do the sum of the points it does everything correctly, but it adds 1 and 11 together whereas I need it to compute the sum if the integer is 1 and if the integer is 11.</p> <p>So for example:</p> <pre><code>&gt;&gt;&gt;getPointTotal([1,26, 12]) # 10-13 are worth 10 points( and every 13th number that equates to 10-13 using n % 13. &gt;&gt;&gt;[21,31] # 21 if the value is 1, 31 if the value is 11. </code></pre> <p>Another example:</p> <pre><code>&gt;&gt;&gt;getPointTotal([1,14]) # 14 is just 14 % 13 = 1 so, 1 and 1. &gt;&gt;&gt;[2, 12, 22] # 1+1=2, 1+11=12, 11+11=22 </code></pre> <p>My output is:</p> <pre><code>&gt;&gt;&gt;getPointTotal([1,14]) &gt;&gt;&gt;[24] #It's adding all of the numbers 1+1+11+11 = 24. </code></pre> <p>So my question is, is how do I make it add the value 1 separately from the value 11 and vice versa. So that way when I do have 1 it would add all the values and 1 or it would add all the values and 11.</p>
3
2016-10-08T23:31:25Z
39,939,038
<p>Rory Daulton's answer is a good one, and it efficiently gives you the different totals that are possible. I want to offer another approach which is not necessarily better than that one, just a bit different. The benefit to my approach is that you can see the sequence of scores that lead to a given total, not only the totals at the end.</p> <pre><code>def getPointTotal(cards): card_scores = [getPoints(card) for card in cards] # will be a list of lists combos = {sorted(scores) for scores in itertools.product(*card_scores)} return [(scores, sum(scores)) for scores in combos] </code></pre> <p>The key piece of this code is the call to <code>itertools.product(*card_scores)</code>. This takes the lists you got from <code>getPoints</code> for each of the cards in the input list and gets all the combinations. So <code>product([1, 11], [1, 11], [10])</code> will give <code>(1, 1, 10)</code>, <code>(1, 11, 10)</code>, <code>(11, 1, 10)</code>, and <code>(11, 11, 10)</code>.</p> <p>This is probably a bit overkill for blackjack scoring where there are not going to be many variations on the scores for a given set of cards. But for a different problem (i.e. a different implementation of the <code>getPoints</code> function), it could be very interesting.</p>
1
2016-10-09T01:23:00Z
[ "python", "list", "python-3.x", "sum" ]
Checking if a sequence has consecutive identical characters
39,938,475
<p>For this function I'm trying to have it return "True" when a sequence has consecutive identical characters and have it return "False" when a sequence doesn't. For example, <code>neighboring_twins(1,2,1,4,1)</code> should return <code>False</code> while <code>neighboring_twins(1,2,3,3,5)</code> should return <code>True</code> because there are two identical characters directly next to each other (the two 3's). </p> <p>This is the code I have so far. I don't think having Python search for <code>"ii"</code> is the right way to do it as I keep getting syntax errors. I wasn't sure how I would instruct Python to search for consecutive identical characters but assumed I should use a for loop.</p> <pre><code>def neighboring_twins(xs): for i in xs: if ii = True return True elif ii = False return False </code></pre> <p>Edit: I'd like to accomplish this without importing from other modules and in the simplest way possible.</p>
1
2016-10-08T23:36:12Z
39,938,531
<p>The <code>pairwise</code> function from <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow">itertools' recipies</a> will return a list of pairs of consecutive items. From here on, you're just a list comprehension away of what you need:</p> <pre><code>from itertools import tee, izip def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b) def neighboring_twins(xs): return any([x for x in pairwise(xs) if x[0]==x[1]]) </code></pre> <p>Or, directly, without copying <code>pairwise</code>:</p> <pre><code>from itertools import tee, izip def neighboring_twins(xs): a, b = tee(xs) next(b, None) return any([x for x in izip(a, b) if x[0]==x[1]]) </code></pre> <p><strong>EDIT:</strong><br/> You could achieve the same functionality without using itertools, albeit with some performance degradation:</p> <pre><code>def neighboring_twins(xs): return any([x for x in zip(xs, xs[1::]) if x[0]==x[1]]) </code></pre>
0
2016-10-08T23:44:22Z
[ "python", "loops", "character", "sequence" ]
Checking if a sequence has consecutive identical characters
39,938,475
<p>For this function I'm trying to have it return "True" when a sequence has consecutive identical characters and have it return "False" when a sequence doesn't. For example, <code>neighboring_twins(1,2,1,4,1)</code> should return <code>False</code> while <code>neighboring_twins(1,2,3,3,5)</code> should return <code>True</code> because there are two identical characters directly next to each other (the two 3's). </p> <p>This is the code I have so far. I don't think having Python search for <code>"ii"</code> is the right way to do it as I keep getting syntax errors. I wasn't sure how I would instruct Python to search for consecutive identical characters but assumed I should use a for loop.</p> <pre><code>def neighboring_twins(xs): for i in xs: if ii = True return True elif ii = False return False </code></pre> <p>Edit: I'd like to accomplish this without importing from other modules and in the simplest way possible.</p>
1
2016-10-08T23:36:12Z
39,938,545
<p>You are getting syntax errors because <code>if ii</code> is asking the Python interpreter to check the variable <code>ii</code> and see if it's true or not. I would recommend iterating through the list and checking the next element to see if it equals the next. <code>enumerate()</code> will be useful for you.</p> <p>I also noticed that you're using <code>if ii = True</code> which is assigning the value of True to ii instead of checking if <code>ii</code> is True. You probably want <code>if ii == True</code>. The <code>==</code> checks for equality and a single equals sign assigns a value to a variable.</p>
0
2016-10-08T23:47:06Z
[ "python", "loops", "character", "sequence" ]
How to check if number is prime if no divisibles
39,938,694
<p>I'm new to programming, I need to know if it's possible to print a string like "This is a prime number" if there were no results for i</p> <pre><code>n = int(input("Digite um número inteiro positivo: ")) for i in range(2,n): if n % i == 0: print(i) </code></pre> <p>For example if I typed 5 Nothing show up</p> <p>If I typed 8 it would show 2 and 4</p> <p>How can I add a print(n,"is a prime number") if NOTHING shows up in the program? I couldn't find any command for that</p>
0
2016-10-09T00:09:31Z
39,938,721
<pre><code>def isPrime(num): for i in range(2, num): if num % i == 0: return False return True def getFactors(n): myList = [] for i in range(2, n): if n % i == 0: myList.append(i) return myList num = 17 num2 = 20 if isPrime(num): print("prime") else: print(getFactors(17)) if isPrime(num2): print("prime") else: print(getFactors(num2)) </code></pre>
0
2016-10-09T00:15:40Z
[ "python", "python-3.x" ]
How to check if number is prime if no divisibles
39,938,694
<p>I'm new to programming, I need to know if it's possible to print a string like "This is a prime number" if there were no results for i</p> <pre><code>n = int(input("Digite um número inteiro positivo: ")) for i in range(2,n): if n % i == 0: print(i) </code></pre> <p>For example if I typed 5 Nothing show up</p> <p>If I typed 8 it would show 2 and 4</p> <p>How can I add a print(n,"is a prime number") if NOTHING shows up in the program? I couldn't find any command for that</p>
0
2016-10-09T00:09:31Z
39,938,723
<pre><code>n = int(input("Digite um número inteiro positivo: ")) printed = False for i in range(2,n): if n % i == 0: print(i) printed = True if not printed: print(n,"is a prime number") </code></pre> <p>This uses a "flag" variable to show if a value was printed.</p>
3
2016-10-09T00:16:21Z
[ "python", "python-3.x" ]
How to check if number is prime if no divisibles
39,938,694
<p>I'm new to programming, I need to know if it's possible to print a string like "This is a prime number" if there were no results for i</p> <pre><code>n = int(input("Digite um número inteiro positivo: ")) for i in range(2,n): if n % i == 0: print(i) </code></pre> <p>For example if I typed 5 Nothing show up</p> <p>If I typed 8 it would show 2 and 4</p> <p>How can I add a print(n,"is a prime number") if NOTHING shows up in the program? I couldn't find any command for that</p>
0
2016-10-09T00:09:31Z
39,938,741
<p>A crude way to do it would be adding something like a counter which checks the number of factors.</p> <pre><code>n=int(input("Digite um número inteiro positivo:")) counter=0 for i in range(2,n): if(n%i==0): print(i) counter+=1 if(counter==0): print "n is prime" </code></pre>
0
2016-10-09T00:19:51Z
[ "python", "python-3.x" ]
How to check if number is prime if no divisibles
39,938,694
<p>I'm new to programming, I need to know if it's possible to print a string like "This is a prime number" if there were no results for i</p> <pre><code>n = int(input("Digite um número inteiro positivo: ")) for i in range(2,n): if n % i == 0: print(i) </code></pre> <p>For example if I typed 5 Nothing show up</p> <p>If I typed 8 it would show 2 and 4</p> <p>How can I add a print(n,"is a prime number") if NOTHING shows up in the program? I couldn't find any command for that</p>
0
2016-10-09T00:09:31Z
39,940,326
<p>You could also set the range of the loop to only check values from 2 to n//2 because anything past that would be unnecessary for checking if prime. </p> <pre><code>def isPrime(n): for i in range(2,**n//2**): if n % i == 0: return 'This number is not Prime.' else: return 'This number is Prime.' def main(): user = int(input('Enter a number to check primeness: ')) print(isPrime(user)) main() </code></pre>
0
2016-10-09T05:26:21Z
[ "python", "python-3.x" ]
Use two rows from a pandas dataframe to select a location in another dataframe
39,938,821
<p>I Have first dataframe <code>df1</code> as below. Here <code>col_b</code> is any number between h1 and h24 and doesn't contain all of 1 to 24 for each corresponding date: </p> <pre><code>Date col_b 20101101 h1 20101101 h2 20101101 h3 20101102 h1 20101102 h3 20101103 h2 20101104 h1 20101105 h2 20101105 h3 20101106 h6 20101106 h8 20101106 h24 20101107 h15 </code></pre> <p>And second dataframe <code>df2</code> as:</p> <pre><code>date h1 h2 h3 h4 h5 h6 ... h24 20101101 4 6 45 6 7 8 ... 5 20101102 ......................... 20101103 ......................... </code></pre> <p>I need to select values from <code>df2</code> to a list where rows from <code>df1</code> match with the location in <code>df2</code>. </p> <p>Currently, I am using <code>iterrows</code> to select the row values from <code>df1</code> and assigning values in <code>df2</code> as <code>df2.loc[df2['Date] ==row[0], row[1]]</code> for each row in <code>df1</code>.</p> <p>This is hectic and consuming lot of time. Is there a pythonic or Pandas way to do it ?</p>
1
2016-10-09T00:38:24Z
39,939,023
<p>use <code>DataFrame.lookup()</code>:</p> <pre><code>import numpy as np import pandas as pd df2 = pd.DataFrame(np.random.randint(0, 10, (5, 3)), columns=list("ABC"), index=pd.date_range("2016/01/01", "2016/05/01", freq="MS")) df = pd.DataFrame({"date":df2.index[np.random.randint(0, 5, 10)], "key": df2.columns[np.random.randint(0, 3, 10)]}) df["value"] = df2.lookup(df["date"], df["key"]) print(df) </code></pre> <p>the result:</p> <pre><code> date key value 0 2016-01-01 C 2 1 2016-05-01 A 8 2 2016-01-01 A 8 3 2016-04-01 B 1 4 2016-04-01 C 2 5 2016-03-01 A 2 6 2016-03-01 A 2 7 2016-04-01 B 1 8 2016-05-01 A 8 9 2016-03-01 B 5 </code></pre>
1
2016-10-09T01:19:56Z
[ "python", "pandas", "dataframe" ]
Confusing bug with brackets on my function
39,938,830
<pre><code>def cube_of(valz):         '''Returns the cube of values'''         if len(valz) == 0:             return 0         else:             new_val = [valz[0] ** 3]             return  [new_val] + [cube_of(valz[1:])]  </code></pre> <p>So I am making this function for a demonstration which takes a list of values called <code>valz</code> and takes the cube of each value and then returns a list of these cubes.</p> <p>For example, let's say the input is <code>[-1,2,-3,4,-5]</code> - it should return <code>[-1,8,-27,64,-125]</code> but it returns <code>[-1, [8, [-27, [64, [-125, 0]]]]]</code>. What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an <code>int</code> to a <code>list</code>). I tried to debug this and even had my friend take a look but we're both pretty stumped.</p>
1
2016-10-09T00:40:46Z
39,938,853
<p><code>cube_of(valz[1:])</code> is already a list. There's no need to wrap it in brackets.</p> <pre><code>return [new_val] + cube_of(valz[1:]) </code></pre>
2
2016-10-09T00:44:09Z
[ "python", "recursion" ]
Confusing bug with brackets on my function
39,938,830
<pre><code>def cube_of(valz):         '''Returns the cube of values'''         if len(valz) == 0:             return 0         else:             new_val = [valz[0] ** 3]             return  [new_val] + [cube_of(valz[1:])]  </code></pre> <p>So I am making this function for a demonstration which takes a list of values called <code>valz</code> and takes the cube of each value and then returns a list of these cubes.</p> <p>For example, let's say the input is <code>[-1,2,-3,4,-5]</code> - it should return <code>[-1,8,-27,64,-125]</code> but it returns <code>[-1, [8, [-27, [64, [-125, 0]]]]]</code>. What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an <code>int</code> to a <code>list</code>). I tried to debug this and even had my friend take a look but we're both pretty stumped.</p>
1
2016-10-09T00:40:46Z
39,938,857
<p>Your code could be simplified</p> <p>using <em>list comprehension:</em></p> <pre><code>def cube_of(valz): return [item**3 for item in valz] </code></pre> <p><em>Recursive</em> approach:</p> <pre><code>def cube_of(valz): return [valz[0]**3] + cube_of(valz[1:]) if valz else [] </code></pre> <p>Sample run:</p> <pre><code>&gt;&gt;&gt; cube_of([-1,2,-3,4,-5]) [-1, 8, -27, 64, -125] </code></pre>
2
2016-10-09T00:45:12Z
[ "python", "recursion" ]
Confusing bug with brackets on my function
39,938,830
<pre><code>def cube_of(valz):         '''Returns the cube of values'''         if len(valz) == 0:             return 0         else:             new_val = [valz[0] ** 3]             return  [new_val] + [cube_of(valz[1:])]  </code></pre> <p>So I am making this function for a demonstration which takes a list of values called <code>valz</code> and takes the cube of each value and then returns a list of these cubes.</p> <p>For example, let's say the input is <code>[-1,2,-3,4,-5]</code> - it should return <code>[-1,8,-27,64,-125]</code> but it returns <code>[-1, [8, [-27, [64, [-125, 0]]]]]</code>. What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an <code>int</code> to a <code>list</code>). I tried to debug this and even had my friend take a look but we're both pretty stumped.</p>
1
2016-10-09T00:40:46Z
39,938,874
<p>If <code>valz</code> is empty you should return empty list instead of <code>0</code> - <code>return []</code></p> <p><code>new_valz</code> is a list so you don't need brackets. <code>cube_of</code> returns list so you don't need brackets too.</p> <pre><code>def cube_of(valz): '''Returns the cube of values''' if len(valz) == 0: return [] else: new_val = [valz[0] ** 3] return new_val + cube_of(valz[1:]) cube_of([-1,2,-3,4,-5]) # [-1,8,-27,64,-125] cube_of([]) # [] </code></pre>
1
2016-10-09T00:48:45Z
[ "python", "recursion" ]
Confusing bug with brackets on my function
39,938,830
<pre><code>def cube_of(valz):         '''Returns the cube of values'''         if len(valz) == 0:             return 0         else:             new_val = [valz[0] ** 3]             return  [new_val] + [cube_of(valz[1:])]  </code></pre> <p>So I am making this function for a demonstration which takes a list of values called <code>valz</code> and takes the cube of each value and then returns a list of these cubes.</p> <p>For example, let's say the input is <code>[-1,2,-3,4,-5]</code> - it should return <code>[-1,8,-27,64,-125]</code> but it returns <code>[-1, [8, [-27, [64, [-125, 0]]]]]</code>. What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an <code>int</code> to a <code>list</code>). I tried to debug this and even had my friend take a look but we're both pretty stumped.</p>
1
2016-10-09T00:40:46Z
39,938,896
<p><code>cube_of(valz)</code> already returns an initial segment of the list in the <code>else</code> part of the branch, i.e. <code>[new_val]</code>. Therefore, in order for its overall return value to be of type list, it should return lists in all its branches.</p> <p>You should change the function like this:</p> <pre><code>def cube_of(valz): '''Returns the cube of values''' if len(valz) == 0: return [] else: new_val = [valz[0] ** 3] return [new_val] + cube_of(valz[1:]) </code></pre> <p>Note that now, since both branches of the if-else return an initial segment of the final list, <code>cube_of</code> itself now returns a list by induction, thereby making the entire recursive call return a value of list type.</p> <p>However, if you're looking for an elegant and more idiomatic/Pythonic solution, look no further than anonymous'.</p>
0
2016-10-09T00:53:05Z
[ "python", "recursion" ]
Python - Make S3 images public as they are uploaded?
39,938,839
<p>I'm using this code to upload images to S3 from python but I need them to be public right away instead of changing permissions manually.</p> <pre><code>im2.save(out_im2, 'PNG') conn = boto.connect_s3(keys) b = conn.get_bucket('example') k = b.new_key('example.png') k.set_contents_from_string(out_im2.getvalue()) </code></pre> <p>I already tried this code:</p> <pre><code>b.set_acl('public-read-write') </code></pre>
0
2016-10-09T00:42:07Z
39,940,799
<h2>Using ACLs</h2> <p>Try:</p> <pre><code>k.set_acl('public-read') </code></pre> <p>According to <a href="http://boto.cloudhackers.com/en/latest/s3_tut.html#setting-getting-the-access-control-list-for-buckets-and-keys" rel="nofollow">the boto documentation</a> this is how you set a canned ACL on an individual item.</p> <p>Change the acl on the bucket (as you were doing with <code>b.set_acl</code>, will only affecting permissions on bucket operations (such as List Objects in a Bucket), not object operations, such as reading an object (which is what you want). See <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#permissions" rel="nofollow">Amazon S3 ACL Overview - Permissions</a> for more details on what the different permissions mean when applied to buckets and objects.</p> <h2>Using Bucket Policies</h2> <p>However, depending on the key structure for your images, you may find it simpler to setup a bucket policy that grants read access to all keys in a given path. Then you don't have to do anything special with any individual objects.</p> <p><a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-2" rel="nofollow">Here is a sample policy that grants read-only access</a>.</p> <p>And <a href="https://blogs.aws.amazon.com/security/post/TxPOJBY6FE360K/IAM-policies-and-Bucket-Policies-and-ACLs-Oh-My-Controlling-Access-to-S3-Resourc" rel="nofollow">this blog post discusses the differences and combinations between IAM Policies, Bucket Policies and ACLs</a>.</p>
2
2016-10-09T06:43:17Z
[ "python", "amazon-web-services", "amazon-s3", "boto" ]
Lines in a file is not displayed (python)
39,938,862
<p>I'm a python beginner. So I encountered this problem. The file has 100 songs, each song with an id(X), title(T), time sig(M) and key sig(K), the format of the text file is the same throughout the file. However it skipped 8 lines. Some of the tunes in the file has several titles, but only one is to be displayed </p> <pre><code>file = open("musicFile.abc", "r") idNum = "" title = "" timesig = "" keysig = "" total = 0 for line in file: if line[0] == 'X': idNum = line[2:] elif line[0] == 'T': sep = ',' line = line.split(sep, 1)[0] title = line[2:] for i in range(4): if next(file) == 'T': break elif line[0] == 'M': timesig = line[2:] elif line[0] == 'K': keysig = line[2:] fullLine = "Id: " + idNum + " .... " + "Title: " + title + " .... " + \ "Time sig: " + timesig + " .... " + "Key sig: " + keysig fullLine = fullLine.replace("\n", "") print(fullLine) total += 1 print("\n-------------------------------") print("There are ", total, "tunes in the file") print("-------------------------------") </code></pre> <p>This is the compiled result: <a href="http://i.stack.imgur.com/4AEJp.png" rel="nofollow">compiled program</a></p> <p>It should display there are 100 tunes in the file.</p>
2
2016-10-09T00:45:42Z
39,938,949
<p>You use <code>next(file)</code> which reads next line so you skip some lines.</p>
0
2016-10-09T01:03:56Z
[ "python" ]
Display "long" pandas dataframe in jupyter notebook with "foldover"?
39,938,870
<p>Let's say I have a pandas dataframe with many columns:</p> <p><a href="http://i.stack.imgur.com/bjFlz.png" rel="nofollow"><img src="http://i.stack.imgur.com/bjFlz.png" alt="enter image description here"></a></p> <p>I can view all of the columns by scrolling left/right. However, this is a bit inconvenient and I was wondering if there was an elegant way to display the table with "foldover":</p> <p><a href="http://i.stack.imgur.com/2Aten.png" rel="nofollow"><img src="http://i.stack.imgur.com/2Aten.png" alt="enter image description here"></a></p> <p>To generate the above, I manually chopped up the dataframe into chunks and displayed each chunk (which is why the spacing/etc is not perfect).</p> <p>I was wondering if there was a way to do something like the above more cleanly, possibly by changing pandas or jupyter settings?</p>
1
2016-10-09T00:47:55Z
39,939,301
<p>try this:</p> <pre><code>In [135]: df = pd.DataFrame(np.random.rand(3, 30), columns=list(range(30))) In [136]: pd.options.display.expand_frame_repr=True In [137]: pd.options.display.max_columns = None In [138]: pd.options.display.width = 80 In [139]: df Out[139]: 0 1 2 3 4 5 6 \ 0 0.072370 0.388609 0.112033 0.829140 0.700152 0.645331 0.063483 1 0.890765 0.330274 0.900561 0.128318 0.056443 0.239560 0.568522 2 0.295088 0.101399 0.417066 0.657503 0.872717 0.153140 0.909876 7 8 9 10 11 12 13 \ 0 0.497130 0.852824 0.778126 0.710167 0.526406 0.416188 0.154483 1 0.451316 0.409711 0.352989 0.810885 0.540569 0.999328 0.144429 2 0.442140 0.892209 0.150371 0.337189 0.584538 0.152138 0.278306 14 15 16 17 18 19 20 \ 0 0.520901 0.857807 0.969782 0.577220 0.016009 0.809139 0.231900 1 0.561181 0.446312 0.468740 0.076465 0.383884 0.850491 0.815509 2 0.147742 0.957585 0.010312 0.021724 0.572048 0.952412 0.033100 21 22 23 24 25 26 27 \ 0 0.656393 0.823157 0.507222 0.889953 0.076415 0.820150 0.441099 1 0.919607 0.942032 0.586774 0.469604 0.596542 0.156348 0.099294 2 0.978045 0.537873 0.283019 0.582568 0.012389 0.943704 0.028346 28 29 0 0.921219 0.569421 1 0.016056 0.298474 2 0.061831 0.488659 </code></pre>
0
2016-10-09T02:16:20Z
[ "python", "pandas", "ipython", "jupyter", "jupyter-notebook" ]
Display "long" pandas dataframe in jupyter notebook with "foldover"?
39,938,870
<p>Let's say I have a pandas dataframe with many columns:</p> <p><a href="http://i.stack.imgur.com/bjFlz.png" rel="nofollow"><img src="http://i.stack.imgur.com/bjFlz.png" alt="enter image description here"></a></p> <p>I can view all of the columns by scrolling left/right. However, this is a bit inconvenient and I was wondering if there was an elegant way to display the table with "foldover":</p> <p><a href="http://i.stack.imgur.com/2Aten.png" rel="nofollow"><img src="http://i.stack.imgur.com/2Aten.png" alt="enter image description here"></a></p> <p>To generate the above, I manually chopped up the dataframe into chunks and displayed each chunk (which is why the spacing/etc is not perfect).</p> <p>I was wondering if there was a way to do something like the above more cleanly, possibly by changing pandas or jupyter settings?</p>
1
2016-10-09T00:47:55Z
39,939,393
<p>In addition to setting max cols like you did, I'm importing <code>display</code></p> <pre><code>import pandas as pd pd.set_option('display.max_columns', None) from IPython.display import display </code></pre> <p>creating a frame then a simple for loop to display every 30 cols</p> <pre><code>df = pd.DataFrame([range(200)]) cols = df.shape[1] for i in range(0,cols,30): display(df.iloc[:,i:i+30]) </code></pre> <p>EDIT: Forgot to add a pic of the output</p> <p><a href="http://i.stack.imgur.com/UT7ya.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/UT7ya.jpg" alt="enter image description here"></a></p>
1
2016-10-09T02:29:45Z
[ "python", "pandas", "ipython", "jupyter", "jupyter-notebook" ]
get TypeError when i import my own .py file
39,938,890
<p>I am doing a sort program.i have two files called bubble(a bubble sort program) and cal_time(calculate the time),and they are in the same directory.</p> <p>The problem is ,bubble work alone fluently. however,when i import bubble to my cal_time file and callback bubble sort,the interpreter show me the error message,and obviously there is no built_in function or method in my code:</p> <blockquote> <pre><code>Traceback (most recent call last): File "F:/alogrithm/wzysort/cal_time.py", line 13, in &lt;module&gt; bubble.bubble_sort(generate_random_list()) File "F:\alogrithm\wzysort\bubble.py", line 4, in bubble_sort if a[indx] &gt; a[indx+1]: TypeError: unorderable types: builtin_function_or_method() &gt; builtin_function_or_method() </code></pre> </blockquote> <p>cal_time.py:</p> <pre><code>import time from wzysort import bubble import random def generate_random_list(): result = [] for i in range(10): result.append(random.random) return result time_start = time.time() bubble.bubble_sort(generate_random_list()) time_end = time.time() print(time_end - time_start) </code></pre> <p>bubble.py:</p> <pre><code>def bubble_sort(a): for i in range(len(a)-1): for indx in range(len(a[:-i-1])): if a[indx] &gt; a[indx+1]: a[indx], a[indx + 1] = a[indx + 1], a[indx] </code></pre>
2
2016-10-09T00:52:19Z
39,938,941
<p>Your issue lies here:</p> <pre><code>result.append(random.random) </code></pre> <p>You are appending the method <code>random.random</code> onto the list – which has the type <code>builtin_function_or_method</code> (thus resulting in the error you are receiving – how would you compare functions?).</p> <p>Instead, you want to call the method:</p> <pre><code>result.append(random.random()) </code></pre>
2
2016-10-09T01:02:10Z
[ "python", "module" ]
get TypeError when i import my own .py file
39,938,890
<p>I am doing a sort program.i have two files called bubble(a bubble sort program) and cal_time(calculate the time),and they are in the same directory.</p> <p>The problem is ,bubble work alone fluently. however,when i import bubble to my cal_time file and callback bubble sort,the interpreter show me the error message,and obviously there is no built_in function or method in my code:</p> <blockquote> <pre><code>Traceback (most recent call last): File "F:/alogrithm/wzysort/cal_time.py", line 13, in &lt;module&gt; bubble.bubble_sort(generate_random_list()) File "F:\alogrithm\wzysort\bubble.py", line 4, in bubble_sort if a[indx] &gt; a[indx+1]: TypeError: unorderable types: builtin_function_or_method() &gt; builtin_function_or_method() </code></pre> </blockquote> <p>cal_time.py:</p> <pre><code>import time from wzysort import bubble import random def generate_random_list(): result = [] for i in range(10): result.append(random.random) return result time_start = time.time() bubble.bubble_sort(generate_random_list()) time_end = time.time() print(time_end - time_start) </code></pre> <p>bubble.py:</p> <pre><code>def bubble_sort(a): for i in range(len(a)-1): for indx in range(len(a[:-i-1])): if a[indx] &gt; a[indx+1]: a[indx], a[indx + 1] = a[indx + 1], a[indx] </code></pre>
2
2016-10-09T00:52:19Z
39,939,032
<p>In <code>generate_random_list()</code> function, you are doing <code>random.random</code>. Since it is a function, you should write it as <code>random.random()</code>. Hence, the code of your <code>generate_random_list()</code> function should be:</p> <pre><code>def generate_random_list(): result = [] for i in range(10): result.append(random.random()) return result </code></pre>
0
2016-10-09T01:21:31Z
[ "python", "module" ]
Regular Expression removing <![CDATA[
39,938,929
<p>I have this regular expression: </p> <pre><code>&lt;/title&gt;[\s]*&lt;description[^&gt;]*&gt;(.*?)&lt;img </code></pre> <p>which takes the string: </p> <pre><code>&lt;title&gt;Insane price of last Ford Falcon V8s&lt;/title&gt; &lt;description&gt;&lt;![CDATA[FORD dealers are charging a staggering $30,000 more than the recommended retail price — up from $60,000 to $90,000 — for the final Falcon V8 sedans as buyers try to secure a future classic.&lt;img alt="" border="0" src="https://pixel.wp.com/b.gif?host=www.couriermail.com.au&amp;#038;blog=87782261&amp;#038;post=1205849&amp;#038;subd=couriermailatnewscorpau&amp;#038;ref=&amp;#038;feed=1" width="1" height="1" /&gt;]]&gt;&lt;/description&gt; </code></pre> <p>how can i edit this regular expression to also remove <code>&lt;![CDATA[</code></p>
-4
2016-10-09T00:59:58Z
39,939,656
<p>Regular expressions are really mighty tool. This includes a high risk of getting bugs into your code, especially when you do not know how to handle them exactly (it seems this is the case here).</p> <p>You should always go with Python's built-in string class first and <em>only</em> use RegEx, if it is necessary.</p> <p>If you have your string <code>my_str</code>, then the following code replaces a substring in <code>my_str</code>:</p> <pre><code>my_str = "hello world" my_str.replace("lo", "") &gt;&gt;&gt; "hel world" </code></pre> <p><code>str.replace</code> searches for a "lo" in this case and replaces it with "" (nothing, thus deleting it). Of course you can alter this values as you like.</p> <p>Take a look at <a href="https://docs.python.org/2/library/string.html" rel="nofollow">Python's documention for Strings</a>.</p>
0
2016-10-09T03:16:13Z
[ "python", "html", "regex", "cdata" ]
Script to download manually generated excel file on reference website?
39,938,930
<p>I am specifically looking at the ReferenceUSA website. To download information, one has to manually select all the items, then click download, and then on another page click to generate a CSV file. Is there anyway to automate this kind of process?</p>
1
2016-10-09T01:00:14Z
39,939,360
<p>You could try Selenium, here is an example to open a web page, and click a button.</p> <pre><code>&gt;&gt;&gt; from selenium import webdriver &gt;&gt;&gt; browser = webdriver.Chrome() ## now web browser opened &gt;&gt;&gt; browser.get("https://www.python.org") ## now python.org web page opened </code></pre> <p>There is a button "GO", its page source code like this:</p> <pre><code>button type="submit" name="submit" id="submit" class="search-button"... </code></pre> <p>Now, click this button</p> <pre><code>&gt;&gt;&gt; browser.find_element_by_id("submit").click() </code></pre>
0
2016-10-09T02:25:18Z
[ "python", "automation" ]
How to display non-English language gotten by Facebook API
39,938,973
<p>I'm getting some facebook posts that have a mixture of English and and a non-English language (Khmer to be exact). </p> <p>Here's how the non-English is displayed when I print the data to screen or save it to file: \u178a\u17c2\u179b\u1787\u17b6\u17a2\u17d2. I would rather have it display as ឈឹម បញ្ចពណ៌ (Note: this is not a translation of the previous unicode.)</p>
-1
2016-10-09T01:08:25Z
39,939,040
<p>This should be it:</p> <pre><code>print(u'\u1787\u17b6\u17a2\u17d2') #python3 print u'\u1787\u17b6\u17a2\u17d2' #python2.7 </code></pre> <p>Output: ជាអ្</p>
1
2016-10-09T01:23:43Z
[ "python", "facebook", "facebook-graph-api", "translation" ]
How to display non-English language gotten by Facebook API
39,938,973
<p>I'm getting some facebook posts that have a mixture of English and and a non-English language (Khmer to be exact). </p> <p>Here's how the non-English is displayed when I print the data to screen or save it to file: \u178a\u17c2\u179b\u1787\u17b6\u17a2\u17d2. I would rather have it display as ឈឹម បញ្ចពណ៌ (Note: this is not a translation of the previous unicode.)</p>
-1
2016-10-09T01:08:25Z
39,939,064
<p>In pycharm I added:</p> <ol> <li><p>(at top) # -<em>- coding: utf-8 -</em>-</p></li> <li><p>import sys reload(sys) sys.setdefaultencoding('utf8')</p></li> <li>s = json.dumps(posts['data'],ensure_ascii=False)</li> <li>json_file.write(s.decode('utf-8'))</li> </ol>
0
2016-10-09T01:29:02Z
[ "python", "facebook", "facebook-graph-api", "translation" ]
How to display non-English language gotten by Facebook API
39,938,973
<p>I'm getting some facebook posts that have a mixture of English and and a non-English language (Khmer to be exact). </p> <p>Here's how the non-English is displayed when I print the data to screen or save it to file: \u178a\u17c2\u179b\u1787\u17b6\u17a2\u17d2. I would rather have it display as ឈឹម បញ្ចពណ៌ (Note: this is not a translation of the previous unicode.)</p>
-1
2016-10-09T01:08:25Z
39,939,072
<p>Try this if you want to save the info in a file:</p> <pre><code>import codecs string = 'ឈឹម បញ្ចពណ៌' with codecs.open('yourfile', 'w', encoding='utf-8') as f: f.write(string) </code></pre>
0
2016-10-09T01:30:49Z
[ "python", "facebook", "facebook-graph-api", "translation" ]
Command works in CMD but not Subprocess
39,939,027
<p>I have created a VLC command that converts an opus file to mp3. This command works in windows CMD but does not work in a subprocess in Python 3.5. I have tried various configuration of the command but with no success, there is no error message I am just greeted with a VLC dummy command line window with no process. This is the command.</p> <pre><code>p = subprocess.Popen(["C:/Program Files (x86)/VideoLAN/VLC/vlc.exe", "-I dummy -vvv "E:\\some_dir\\a.opus" --sout=#transcode{acodec=mpga,ab=192}:standard{access=file,dst="E:\\some_dir\\a.mp3"]) </code></pre> <p>I can provide any information required. All input would be greatly appreciated.</p>
1
2016-10-09T01:20:42Z
39,939,050
<p>Every argument of the command has to be its own element of the list:</p> <pre><code>p = subprocess.Popen(["C:/Program Files (x86)/VideoLAN/VLC/vlc.exe", "-I", "dummy", "-vvv", "E:\\some_dir\\a.opus", "--", "sout=#transcode{acodec=mpga,ab=192}:standard{access=file,dst=E:\\some_dir\\a.mp3" ]) </code></pre>
1
2016-10-09T01:26:23Z
[ "python", "subprocess", "vlc" ]
Ocatave Symbolic "Python cannot import SymPy"
39,939,093
<p>After installing octave, sympy (through anaconda), and the symbolic package, I'm trying to run this line in octave as part of a script:</p> <pre><code>syms nn nb x </code></pre> <p>When I do I get this message:</p> <pre><code>warning: the 'syms' function belongs to the symbolic package from Octave Forge which you have installed but not loaded. To load the package, run `pkg load symbolic' from the Octave prompt. </code></pre> <p>After:</p> <pre><code>pkg load symbolic syms nn nb x </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "sympy/__init__.py", line 27, in &lt;module&gt; raise ImportError("It appears 2to3 has been run on the codebase. Use " ImportError: It appears 2to3 has been run on the codebase. Use Python 3 or get the original source code. OctSymPy v2.4.0: this is free software without warranty, see source. Initializing communication with SymPy using a popen2() pipe. error: Python cannot import SymPy: have you installed SymPy? error: called from assert_have_python_and_sympy at line 37 column 5 python_ipc_popen2 at line 78 column 5 python_ipc_driver at line 57 column 13 python_cmd at line 166 column 9 sym at line 365 column 5 syms at line 162 column 9 </code></pre> <p>I'm using OSX El Capitan and I installed Octave through homebrew. </p> <p>If I'm being honest, I have no clue what is going on here... Is it that octave is unable to properly communicate with sympy? If so I'm guessing there might be a simple way to fix this? If this isn't it what should I do? I'm open to restarting the process.</p> <p>I'd like to apologize for any formatting issues ahead of time, this is my first time asking. I didn't see any questions covering this but if I missed something obvious, I'm sorry again. </p> <p>Thank you!</p>
3
2016-10-09T01:35:07Z
39,962,759
<p>It looks like you have an old version of SymPy. Try upgrading to the newest version (1.0 at the time of writing). </p>
0
2016-10-10T16:30:59Z
[ "python", "osx", "octave", "sympy" ]
Python transpose sqlite table
39,939,099
<p>I have an sqlite database with a table organized like:</p> <p>itemdata</p> <pre><code>date_time | item_code | value 3/13/2015 12:23 | fridge21 | 345.45 3/13/2015 12:23 | heater12 | 12.34 3/13/2015 12:23 | fan02 | 63.78 3/13/2015 12:24 | fridge21 | 345.47 </code></pre> <p>I would like to retrieve the data in the itemdata table to be like:</p> <pre><code>date_time | fridge21 | heater12 | fan02 3/13/2015 12:23 | 345.45 | 12.34 | 63.78 3/13/2015 12:24 | 345.47 | 12.45 | 63.23 </code></pre> <p>I have tried:</p> <pre><code>conn = sqlite3.connect(DB_NAME) sql = "SELECT * FROM {0}".format(table_name) df = pd.read_sql_query(sql, conn) df1 = pd.DataFrame(df.values.T, columns=df.columns) </code></pre> <p>But I don't want to exactly transpose the itemdata table (which has 1x10^6 rows and 3 columns), I want to a unique item_codes column only as per the desired output above.</p> <p>Any hints on how to do this?</p>
0
2016-10-09T01:36:06Z
39,939,153
<p>Use <code>pivot</code> against a raw dataframe that loads the sqllite table:</p> <pre><code>df.pivot('date_time', 'item_code', 'value') </code></pre>
3
2016-10-09T01:47:49Z
[ "python", "sqlite", "pandas" ]
How to write a table without database in HTML in Django
39,939,156
<p>I just want to write a table in HTML in Django, where the data is not from Database. It seems <a href="https://django-tables2.readthedocs.io/en/latest/" rel="nofollow">django-tables2</a> is a good package that I can use in Django. However, my data is not from Database, so maybe it's not necessary to use Django model. Here comes my code of view.py and HTML page:</p> <pre><code>def device_manager_submit(request): '''Switch manager page''' ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}] return HttpResponse(ret) #return data to HTML </code></pre> <p>I can use for loop in HTML to display this data but I'm not clearly about how to show them:</p> <pre><code> &lt;tbody&gt; {% for item in xx %} //I'm not sure &lt;tr&gt; &lt;td&gt;111&lt;/td&gt; //how to display? &lt;/tr&gt; {% endfor %} </code></pre> <p>Does anyone has any example that I can follow to display the data from view.py in HTML page</p>
0
2016-10-09T01:48:34Z
39,939,391
<p>One way would be to use <a href="http://pandas.pydata.org" rel="nofollow">pandas</a> to load the data, and then use the <code>DataFrame.to_html()</code> to output the data into an html table. See the example below:</p> <pre><code>import pandas as pd data = [{'column1': 1, 'column2': 2}] df = pd.DataFrame(data) html = df.to_html() </code></pre> <p>Html will result in:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table border="1" class="dataframe"&gt; &lt;thead&gt; &lt;tr style="text-align: right;"&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;column1&lt;/th&gt; &lt;th&gt;column2&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;0&lt;/th&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>In a Django view this would be:</p> <pre class="lang-python prettyprint-override"><code>@api_view(['GET']) def showData(request): data = [{'column1': 1, 'column2': 2}] df = pd.DataFrame(data) html = df.to_html() return HttpResponse(html) </code></pre>
0
2016-10-09T02:29:40Z
[ "python", "django", "django-tables2" ]
How to write a table without database in HTML in Django
39,939,156
<p>I just want to write a table in HTML in Django, where the data is not from Database. It seems <a href="https://django-tables2.readthedocs.io/en/latest/" rel="nofollow">django-tables2</a> is a good package that I can use in Django. However, my data is not from Database, so maybe it's not necessary to use Django model. Here comes my code of view.py and HTML page:</p> <pre><code>def device_manager_submit(request): '''Switch manager page''' ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}] return HttpResponse(ret) #return data to HTML </code></pre> <p>I can use for loop in HTML to display this data but I'm not clearly about how to show them:</p> <pre><code> &lt;tbody&gt; {% for item in xx %} //I'm not sure &lt;tr&gt; &lt;td&gt;111&lt;/td&gt; //how to display? &lt;/tr&gt; {% endfor %} </code></pre> <p>Does anyone has any example that I can follow to display the data from view.py in HTML page</p>
0
2016-10-09T01:48:34Z
39,943,562
<p>You don't need to return Django objects to create templates, you can use any data. The <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render" rel="nofollow">render()</a> function allows you to combine context with the regular HttpResponse. You pass it the request which was given to the view calling it, the name of the template you want to render, and then a dictionary of data to provide to the template.</p> <pre><code>def device_manager_submit(request): '''Switch manager page''' ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}] return render(request, 'some_template.html', {'devices': ret}) #return data to HTML </code></pre> <p>Assuming that <code>ret</code> contains some objects with a <code>name</code> and <code>description</code>, we can loop through <code>devices</code> like so:</p> <pre><code>&lt;tbody&gt; {% for device in devices %} &lt;tr&gt; &lt;td&gt;{{ device.name }}&lt;/td&gt; &lt;td&gt;{{ device.description }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre>
1
2016-10-09T12:21:10Z
[ "python", "django", "django-tables2" ]
Dictionary of numpy array in python
39,939,168
<p>I want to create a data structure of empty numpy array something of this sort:</p> <pre><code>d[1].foo = numpy.arange(x) d[1].bar = numpy.arange(x) d[2].foo = numpy.arange(x) d[2].bar = numpy.arange(x) </code></pre> <p>What would be the best option ... a list of dictionaries containing numpy arrays?</p>
0
2016-10-09T01:50:22Z
39,939,252
<p>If I define a simple class like: </p> <pre><code>class MyObj(object): pass . </code></pre> <p>I could create a dictionary with several of these objects:</p> <pre><code>In [819]: d={1:MyObj(), 2:MyObj()} </code></pre> <p>and then assign attributes to each object</p> <pre><code>In [820]: d[1].foo=np.arange(3) In [821]: d[1].bar=np.arange(3) In [822]: d[2].foo=np.arange(3) In [823]: d[2].bar=np.arange(3) In [824]: d Out[824]: {1: &lt;__main__.MyObj at 0xaf20cfac&gt;, 2: &lt;__main__.MyObj at 0xaf20c4cc&gt;} </code></pre> <p>Since I didn't define a <code>repr</code> or <code>str</code> the print display isn't very interesting; </p> <pre><code>In [825]: vars(d[2]) Out[825]: {'bar': array([0, 1, 2]), 'foo': array([0, 1, 2])} </code></pre> <p>I could also made a list with these objects</p> <pre><code>In [826]: dl = [None, d[1], d[2]] In [827]: dl Out[827]: [None, &lt;__main__.MyObj at 0xaf20cfac&gt;, &lt;__main__.MyObj at 0xaf20c4cc&gt;] In [828]: vars(dl[1]) Out[828]: {'bar': array([0, 1, 2]), 'foo': array([0, 1, 2])} </code></pre> <p>So both a list and dictionary can be indexed (so can an array); but the <code>.foo</code> syntax is used to access object attributes.</p> <p>===============</p> <p>An entirely different way of creating a structure with this kind of access is to use a <code>recarray</code> - this is a numpy array subclass that allows you to access dtype fields with attribute names</p> <pre><code>In [829]: R=np.recarray((3,), dtype=[('foo','O'),('bar','O')]) In [830]: R Out[830]: rec.array([(None, None), (None, None), (None, None)], dtype=[('foo', 'O'), ('bar', 'O')]) In [831]: R[1].foo=np.arange(3) In [832]: R[2].bar=np.arange(4) In [833]: R Out[833]: rec.array([(None, None), (array([0, 1, 2]), None), (None, array([0, 1, 2, 3]))], dtype=[('foo', 'O'), ('bar', 'O')]) </code></pre> <p>Here I defined the fields as taking object dtype, which allows me to assign anything, including other arrays to each attribute. But usually the dtype is something more specific like int, float, string.</p> <p>I can view the <code>foo</code> attribute/field for all items in the array <code>R</code>:</p> <pre><code>In [834]: R.foo Out[834]: array([None, array([0, 1, 2]), None], dtype=object) In [835]: R['bar'] Out[835]: array([None, None, array([0, 1, 2, 3])], dtype=object) </code></pre> <p>A <code>recarray</code> has a special method that allows access to the fields via <code>attribute</code> syntax.</p>
1
2016-10-09T02:07:13Z
[ "python", "numpy" ]