How to debug this bug when reversing an array
This is my code in python 3 trying to reverse an array. The code gives output and shows a run time exception.
for N in range(int(input())): arr = str(input()) print(''.join(map(str, reversed(arr))))
Exception I am facing:
File "solution.py", line 2, in <module> arr = str(input()) EOFError: EOF when reading a line
See also questions close to this topic
How do I run unit tests in package directory
I have a python code base where I have refactored a module (file) into a package (directory) as the file was getting a bit large and unmanageable. However, I cannot get my unit tests running as desired with the new structure.
I place my unit test files directly alongside the code it tests (this is a requirement and cannot change - no separate
app/ +-- app.py +-- config.py +-- config_test.py +-- model/ | +-- __init__.py | +-- base.py | +-- base_test.py | +-- square.py | +-- square_test.py +-- test.py +-- web.py +-- web_test.py
modelpackage was the
model.pymodule with a
There is a top-level test runner -
test.pyand that works fine. It finds the test cases inside the
modeldirectory and runs them successfully (it uses the
unittest- see end of post for
$ python test.py
However, I also want to be able to directly run the test cases in the
$ python model/base_test.py
This does not work, because the test is inside the package directory. The imports in the code fail because they are either not in a module when imported directly by the test suite or the search path is wrong.
For instance, in
model/square.py, I can import
base.pyin one of two ways:
from model import Base
from .base import Base
These both work fine when
modelis imported. But when inside the
modeltest suites, I cannot import
square_test.pycontains imports like:
import unittest from square import Square
For the first type of import in
from model import Base), I get the error:
ModuleNotFoundError: No module named 'model'
/home/camh/app/modeland there is no
modelmodule in there.
For the second type of import in
from .base import Base), I get the error:
ImportError: attempted relative import with no known parent package
I cannot figure out how to do my imports that allows me to have tests alongside the unit-under-test and be directly runnable. I want directly runnable test suites as often I do not want to run the entire set of tests, but just target individual tests:
$ python model/square_test.py SquareTest.test_equal_sides
I cannot do that with my test runner because it just uses discovery to run all the tests and discovery is not compatible with specifying individual test suites or test functions.
My test runner (
test.py) is just:
import os, sys sys.argv += ['discover', os.path.dirname(sys.argv), '*_test.py'] unittest.main(module=None)
Pythonic use of properties and exceptions
I have a class called Divider1 which divides a numerator by a denominator, set at initialisation:
class Divider1: def __init__(self, numerator=0, denominator=1): self.numerator = numerator self.denominator = denominator def divide(self): return self.numerator / self.denominator
The class is easily abused by initialising incorrectly, but it is not immediately clear until dividing actually occurs:
>>> x = Divider1('hello', 5) >>> x.divide() TypeError: unsupported operand type(s) for /: 'str' and 'int'
It seems that raising an exception earlier would be beneficial for debugging and maintenance, so here is my next logical step:
class Divider2: def __init__(self, numerator=0, denominator=1): try: numerator = float(numerator) except ValueError: raise ValueError("Numerator must be numeric!") try: denominator = float(denominator) except ValueError: raise ValueError("Denominator must be numeric!") if denominator == 0: raise ValueError("Denominator must be non-zero!") self.numerator = numerator self.denominator = denominator def divide(self): return self.numerator / self.denominator
Now we have some safety:
>>> x = Divider2('hello', 5) ValueError: Numerator must be numeric!
It's very clear to me, immediately what is wrong on initialisation, but it can still be abused by changing the attribute after initialisation:
>>> x = Divider2(10, 5) >>> x.numerator = 'hello' >>> x.divide() TypeError: unsupported operand type(s) for /: 'str' and 'int'
I'm trying to figure out the Pythonic way of dealing with these issues. I could possibly just name the numerator and denominator _numerator and _denominator, to indicate that they should be treated as private.
Or alternatively, I could use properties:
class Divider4: def __init__(self, numerator=0, denominator=1): self.numerator = numerator self.denominator = denominator @property def numerator(self): return self._numerator @numerator.setter def numerator(self, value): try: value = float(value) except ValueError: raise ValueError("Denominator must be numeric!") self._numerator = value @property def denominator(self): return self._denominator @denominator.setter def denominator(self, value): try: value = float(value) except ValueError: raise ValueError("Denominator must be numeric!") if value == 0: raise ValueError("Denominator must be non-zero!") self._denominator = value def divide(self): return self.numerator / self.denominator
>>> x = Divider4(10, 5) >>> x.numerator = 'hello' ValueError: Numerator must be numeric! >>> x = Divider4(10, 0) ValueError: Denominator must be non-zero!
It is clearly much safer, and I know the cause of the error immediately, no matter how the class was used - it's impossible for the Divider to reach an impossible state. But I had to write many more lines of code to achieve this, especially compared to Divider1. But I still think that this sort of safety should always be reached, though I haven't seen people do this all the time when they write Python code. Am I using Python in a way that was unintended? Is it Pythonic to always write such cumbersome properties to ensure safety? Are there times when it should or shouldn't be done?
struct.error: repeat count given without format specifier
I'm trying to understand a network program that implements the selective repeat (SR) protocol. Here's the process:
- Run server.py by specifying a port number, protocol, and window size
- Run client.py by specifying a filename, port number, and number of packets
When I run client.py, I receive this error:
Traceback (most recent call last): File "client.py", line 238, in <module> cs = pack('IHH' + str(len(data)), 's', seqNum, header, data) struct.error: repeat count given without format specifier
Here's the block of code that's tripping me up:
while not sendComplete: toSend = lastInWindow + 1 data = GetMessage() header = int('0101010101010101', 2) cs = pack('IHH' + str(len(data)), 's', seqNum, header, data) checksum = CalculateChecksum(cs) packet = pack('IHH' + str(len(data)) + 's', seqNum, checksum, header, data) if toSend < windowSize: sendBuffer.append(packet) timeoutTimers.append(TIMEOUT) else: sendBuffer[toSend % windowSize] = packet timeoutTimers[toSend % windowSize] = TIMEOUT
I've taken several steps to fix this issue, all of which have failed (obviously), and I'm not sure if I'm getting closer to the light or heading deeper into the woods.
- Using struct.pack(fmt=...) as suggested by PyCharm
- Per PyCharm's advice, I concatenate the arguments using a +
- I run the program again and receive a TypeError: must be str, not int error, which I attempt to fix by implementing str(seqNum), str(header), etc.
- Finally, I get a TypeError: pack() takes no keyword arguments response and throw in the towel.
I'd really appreciate it if someone could explain what's going on here and how I can get this program up and running.
Getting different results running script and by shell
Im currently having a problem when I run a script that I wrote to tell if 2 texts files are identical
a="MyOut1.txt" b="out1.txt" f1=open(a,'r') f2=open(b,'r') l1=f1.readlines() l2=f2.readlines() f1.close() f2.close() print(l2==l1)
when I run the code via terminal I get a False result (even tough I expect the files to be the same) and when I run it through python shell it gives me True as you can see in the image
decorating a function while accessing the for loop variables within decorated function
Currently I have a bunch of functions that loop through images, makes some changes and then plots each image.
def second (images): for image in images: image = imread(image) image = image - 100 plt.subplot(121) plt.imshow(image) plt.show()
Now I wanted to decorate these functions so that for there is another subplot for each image. A subplot with a normal image and a subplot with the transformed image.
However, I need to be able to access the
imagesiteration with the
secondfunction, and for each iteration use this
imagewithin the wrapper.
Is there a clean way to do this? I found a sort of hackish way to do this:
def plt_decorate(func): def func_wrapper(*args, **kwargs): images = args for image in images: im = imread(image) mng = plt.get_current_fig_manager() #this two lines mng.window.state('zoomed') # are just to zoom plot plt.subplot(122),plt.imshow(im) if args[1:]: print( func([image], args[1:], **kwargs)) #can't return as loop ends else: print( func([image], **kwargs)) return func_wrapper @plt_decorate def second (images): for image in images: image = imread(image) image = image - 100 plt.subplot(121) plt.imshow(image) plt.show()
Python 3: detect single string fraction (ex: ½ ) and change it to longer string?
ex: "32 ½ is not very hot " to x = "info: 32, numerator = 1, denominator = 2"
note: it can be 3/9, but it CANNOT be simplified into 1/3 aka literally get what is in the string.
I need to detect the fractional string in a longer string and expand the information to a more usable form.
½ has been given to me decoded and is a string with length one.