-1

The code with if-else statements:

def sqrtt(argument):
    if type(argument) == tuple or list or dict or set:
        result = [int(numpy.sqrt(i)) for i in argument]
    else:
        result = int(numpy.sqrt(argument))
    return result

The Response when I pass an integer as an argument:

Traceback (most recent call last):
  File "C:\Users\anees\PycharmProjects\p5\main.py", line 39, in <module>
    l2 = sqrtt(1)
  File "C:\Users\anees\PycharmProjects\p5\main.py", line 33, in sqrtt
    result = [int(numpy.sqrt(i)) for i in argument]
TypeError: 'int' object is not iterable
halfer
  • 19,824
  • 17
  • 99
  • 186
Aneesh
  • 3
  • 2
  • Please, edit your question to include your response and code as text, not image – PTomasz Jun 24 '22 at 11:50
  • Added code as requested, plz review it. Thanks. – Aneesh Jun 24 '22 at 12:15
  • Instead of making the function figure out if `argument` is a single value or an iterable, just require the caller to wrap a single value in the iterable container of their choice, and likewise return a possibly singleton container (which the caller can unpack). – chepner Jun 24 '22 at 23:07
  • @chepner Thanks mate, however I'm not sure I fully understand what you mean here when you say wrapping. Can you kindly show me how to do that with an example? Thanks. – Aneesh Jun 24 '22 at 23:25
  • Don't let the caller do something like `y = sqrtt(5)`. Make them create a list like `y, = sqrrt([5])`, and now your function can *assume* the argument is iterable instead of trying to detect it. – chepner Jun 25 '22 at 16:24

1 Answers1

0

You are checking if type(argument) is tuple, and after that you are checking if list or dict or set is True. If you would like to check if argument is one of those types you should do something like this:

def sqrtt(argument):
    if type(argument) == tuple or type(argument) == list or type(argument) == dict or type(argument) == set:
        result = [int(numpy.sqrt(i)) for i in argument]
    else:
        result = int(numpy.sqrt(argument))
    return result

Or you can check if argument is in iterable types

def sqrtt(argument):
    iterable_types = (tuple, list, dict, set)
    if type(argument) in iterable_types:
        result = [int(numpy.sqrt(i)) for i in argument]
    else:
        result = int(numpy.sqrt(argument))
    return result

Sadly, your code won't work for dict objects

PTomasz
  • 1,330
  • 1
  • 7
  • 23
  • That solved the problem, thanks mate. Just one quick question: Why won't it work for dict objects? – Aneesh Jun 24 '22 at 16:03
  • 1
    Don't compare to `type(argument)` at all, though. Use `isinstance(argument, (tuple, list, dict))` instead. (Or `isinstance(argument, collections.abc.Iterable)` for full generality). – chepner Jun 24 '22 at 23:05
  • Yes, you are right. I wanted to keep answer in same "style" as OP code, but feel free to edit my answer if you think that would be better. – PTomasz Jun 27 '22 at 09:54