Here's my experiment:
$ python
Python 2.7.5 (default, Feb 19 2014, 13:47:28)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 3
>>> while True:
... a = a * a
...
^CTraceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>> a
(seems to go on forever)
I understand that the interpreter looped forever at the "while True: " part, but why did it get stuck evaluating a?
a is now a really large number and it takes a while to print. Print a in the loop and you'll see it gets really big, this is just a fraction of how large it is if you omit the print, because print takes time to execute. Also, note a=1 always quickly returns 1.
Related
This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 1 year ago.
I was looking for something and came across this:
subfolders = [ f.path for f in os.scandir(x) if f.is_dir() ]
I've never seen this type of conditional statement before.
What would you call this type of conditional statement to the right of the = sign? Just asking so I know what to Google.
Also, if I wanted to write the equivalent in another format, would it look something like this?
subfolders = []
x = "c:\\Users\\my_account\\AppData\\Program\\Cache"
for f in os.scandir(x):
if f.isdir():
print(f.x)
Would both of those statements be equivalent?
Can't put code in a comment but here's the small change to your code to create equivalent output:
subfolders = []
for f in os.scandir(path):
if f.is_dir():
subfolders.append(f.path)
Here's the exact thing that worked in the interactive python for me:
Python 3.7.10 (default, Mar 24 2021, 16:34:34)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import os
>>> subfolders = []
>>> for f in os.scandir('.'):
... if f.is_dir():
... subfolders.append(f.path)
...
>>> subfolders
['./the', './.directories', './were', './here']
Checking in a newer python:
Python 3.9.2 (default, Mar 26 2021, 15:28:17)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> subfolders = []
>>> for f in os.scandir('.'):
... if f.is_dir():
... subfolders.append(f.path)
...
>>> subfolders
['./directory']
My understanding is that in Pyside QString has been dropped. One can write a Python string into a QLineEdit, and when the QLineEdit is read, it is returned as a unicode string (16-bits per character).
Trying to write this string from my Gui process to a sub-process started using QProcess does not seem to work and just returns 0L (see below). If one changes the unicode string back to a Python string using the str() function, then self.my_process.write(str(u'test')) now returns 4L. This behaviour does not seem correct to me.
Would it be possible for someone to explain why QProcess.write() does not seem to work on unicode strings?
(Pdb) PySide.QtCore.QString()
*** AttributeError: 'module' object has no attribute 'QString'
(Pdb) self.myprocess.write(u'test')
0L
(Pdb) self.myprocess.write(str(u'test'))
4L
(Pdb)
PySide has never provided classes like QString, QStringList, QVariant, etc. It has always done implicit conversion to and from the equivalent python types - that is, in PyQt terminology, it only implements the v2 API (see PSEP 101 for more details).
However, the behaviour of QProcess when attempting to write unicode strings seems somewhat broken in PySide compared with PyQt4. Here's a simple test in PyQt4:
Python 2.7.8 (default, Sep 24 2014, 18:26:21)
[GCC 4.9.1 20140903 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt4 import QtCore
>>> QtCore.PYQT_VERSION_STR
'4.11.2'
>>> p = QtCore.QProcess()
>>> p.start('cat'); p.waitForStarted()
True
>>> p.write(u'fóó'); p.waitForReadyRead()
3L
True
>>> p.readAll()
PyQt4.QtCore.QByteArray('f\xf3\xf3')
So it seems that PyQt will implicitly encode unicode strings as 'latin-1' before passing them to QProcess.write() (which of course expects either const char * or a QByteArray). If you want a different encoding, it must be done explicitly:
>>> p.write(u'fóó'.encode('utf-8')); p.waitForReadyRead()
5L
True
>>> p.readAll()
PyQt4.QtCore.QByteArray('f\xc3\xb3\xc3\xb3')
Now let's see what happens with PySide:
Python 2.7.8 (default, Sep 24 2014, 18:26:21)
[GCC 4.9.1 20140903 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PySide import QtCore, __version__
>>> __version__
'1.2.2'
>>> p = QtCore.QProcess()
>>> p.start('cat'); p.waitForStarted()
True
>>> p.write(u'fóó'); p.waitForReadyRead()
0L
^C
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
So: no implicit encoding, and the process just blocks instead of raising an error (which would seem to be a bug). However, re-trying with explicit encoding works as expected:
>>> p.start('cat'); p.waitForStarted()
True
>>> p.write(u'fóó'.encode('utf-8')); p.waitForReadyRead()
5L
True
>>> p.readAll()
PySide.QtCore.QByteArray('fóó')
I'm trying to sample 1e7 items from 1e5 strings but getting a memory error. It's fine sampling 1e6 items from 1e4 strings. I'm on a 64bit machine with 4GB RAM and don't think I should be reaching any memory limit at 1e7. Any ideas?
$ python3
Python 3.3.3 (default, Nov 27 2013, 17:12:35)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> K = 100
Works fine with 1e6 :
>>> N = int(1e6)
>>> np.random.choice(["id%010d"%x for x in range(N//K)], N)
array(['id0000005473', 'id0000005694', 'id0000004115', ..., 'id0000006958',
'id0000009972', 'id0000003009'],
dtype='<U12')
Error with N=1e7 :
>>> N = int(1e7)
>>> np.random.choice(["id%010d"%x for x in range(N//K)], N)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 1092, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:8229)
MemoryError
>>>
I found this question but it seems to be about catching an error like this rather than solving it.
Python not catching MemoryError
I'd be happy with either a solution still using random.choice or a different method to do this. Thanks.
You can work round this using a generator function:
def item():
for i in xrange(N):
yield "id%010d"%np.random.choice(N//K,1)
This avoids needing all the items in memory at once.
This is my first day learning programming. I'm following Python Programming: An introduction to computer science 2nd ed. by John Zelle, and so far things have been going smoothly.
The only trouble is that when I try and import a saved program I get a syntaxerror. I write the program and save it before executing, but then when I try to import it I get the error. I tried opening a fresh instance of the shell but no cigar. I'm using OSX Lion 10.8 and Python 2.7.3. Any help is appreciated. This is what the problem looks like:
>>> #File: chaos.py
>>> #A simple program illustrating chaotic behavior.
>>> def main():
print "This program illustrates a chaotic function"
x=input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1-x)
print x
>>> main()
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>> import chaos
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
import chaos
File "chaos.py", line 1
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
^
SyntaxError: invalid syntax
My guess is that you are copying the contents of the terminal to the file, verbatim. And there are a lot of thing that should not be there, that includes the version prompt.
The file should have just something like:
#File: chaos.py
#A simple program illustrating chaotic behavior.
def main():
print "This program illustrates a chaotic function"
x=input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1-x)
print x
No >>>, no ..., no tabulators and certainly do not copy the version information:
Python 2.7.3 (default, Dec 22 2012, 21:27:36)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
File "chaos.py", line 1
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
^
SyntaxError: invalid syntax
It looks like the first line of your chaos.py script has a line which is not python:
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
It should be removed or commented-out by starting the line with a # sign.
Some tips to keep in mind:
In Python, whitespace is important -- they indicate indentation
level. Do not mix spaces and tabs lest Python raise IndentationErrors.
In texts or web pages, you may see transcripts of interactive
sessions which include >>> or ... indicating the Python prompt or
indentation level. If you transfer the code to a script, you must
remove those.
I want to call msvcrt functions from 64-bit python using the ctypes package. I'm obviously doing it wrong. Is the right way to do it obvious?
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> libc = ctypes.cdll.msvcrt
>>> fp = libc.fopen('text.txt', 'wb') #Seems to work, creates a file
>>> libc.fclose(ctypes.c_void_p(fp))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: exception: access violation reading 0xFFFFFFFFFF082B28
>>>
If this code did what I want, it would have opened and closed a text file without crashing.
The default ctypes result type is a 32 bit integer but a file handle is pointer width, i.e. 64 bits. You are therefore losing half of the information in the file pointer.
Before you call fopen you must state that the result type is a pointer:
libc.fopen.restype = ctypes.c_void_p
fp = libc.fopen(...)
libc.fclose(fp)