#๐Ÿ”’ I might be overcomplicating this codewar task

121 messages ยท Page 1 of 1 (latest)

crystal helm
#

Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.

Examples(Operator, value1, value2) --> output
('+', 4, 7) --> 11
('-', 15, 18) --> -3
('*', 5, 5) --> 25
('/', 49, 7) --> 7

novel vineBOT
#

@crystal helm

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

crystal helm
#

im given 3 parameters and i dont know how to work with them

#

do i just use a bunch of if statements to check for operator

#

import math

#

and then go from there?

open sable
#

You don't actually need the math library for this, but yeah, one way of going about it is a bunch of ifs.

crystal helm
#
def basic_op(operator, value1, value2):
    #your code here
    if operator == "+":
        return (value1 + value2)
    elif operator == "-":
        return (value1 - value2)
    elif operator == "*":
        return (value1 * value2)
    elif operator == "/":
        return (value1 / value2)
``` this is uglyyyyy
#

it passed but its soo ugly

wooden coral
#

Eh. It's simple and it gets the job done. ๐Ÿ™‚
There are some minor things to freshen it up a little, though.

magic valley
#

You can use a dictionary as well...

crystal helm
#
def basic_op(operator, value1, value2):
    #your code here
    if operator == "+":
        return (value1 + value2)
    elif operator == "-":
        return (value1 - value2)
    elif operator == "*":
        return (value1 * value2)
    elif operator == "/":
        return (value1 / value2)
    else:
        return ValueError("Invalid operator")

print(basic_op('+', 4, 7))
#

how would i use a dictionary

#

lemme try

wooden coral
#

The brackets around the operations are not needed:

return value1 + value2
``` works just as well.
crystal helm
#

does it not help with readability?

#

how would i do it with a dict?

wooden coral
#

And when an if results in a return, there's no real need to use an else or elif afterward, since you can't reach the next if after the return is called.

This pattern is common:

if something:
    return blah
if something_else:
    return whatever
# and the final else can be omitted
return final_thing
magic valley
wooden coral
#

You would need to pull in the operator module in that case. It has functions for each of the basic operations for this use case.

#

!d operator

#

๐Ÿค” Python bot, where you at? (Think it's having some issues)

magic valley
#

Poor python.

magic valley
crystal helm
#

operators = {"+": +, "-": -}

#

python doesnt let me do this

#

never worked much with dict btw

magic valley
#

Or lambda x,y: x + y

wooden coral
#

Using operator stuff is a neat trick especially if you want to expand to other operations in a more complex calculator program.
This codewar kata doesn't need that complexity, but it can be achieved.
It's fun to experiment with it, at least. ๐Ÿ™‚

abstract orbit
crystal helm
#
def basic_op(operator, value1, value2):
    operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}
magic valley
crystal helm
#

i need to import operatror?

#

but the parameter is already operator

#

wont that have a naming confliction

wooden coral
#
import operator

ops = {
    "+": operator.add,
    "-": operator.sub,
    ...
}
...
result = ops["+"](8, 9)

As a toy example.

wooden coral
#
import operator as op
#

Exercise for the reader. ๐Ÿ™‚

crystal helm
#
import operator as op
def basic_op(operator, value1, value2):
    operators = {"+": op.add, "-": op.sub, "*": op.mul, "/": op.div}
ebon summit
#

Just use eval /s ๐Ÿ˜œ

wooden coral
#

Some of those codewar solutions do use eval. It hurts me.

crystal helm
#

i heard eval has security issues

magic valley
crystal helm
#

mod?

#

modulus?

magic valley
#

no

crystal helm
#

thats the thing, i dont know how to use what i just created to get the output i want

magic valley
#

ok, let's break it into a couple steps, how do you reference the correct function?

crystal helm
#

by calling it?

magic valley
#

not for a dictionary.

wooden coral
magic valley
#

how do you look up something in a dictionary?

crystal helm
#

.get()

magic valley
#

theres a more idiomatic way.

crystal helm
#

or similar to a list

magic valley
#

yeah.

#

what do you want to look up?

crystal helm
#

square bracket

magic valley
#

yeah, but what do you want to put in the square bracket?

crystal helm
#
import operator as op
def basic_op(operator, value1, value2):
    operators = {"+": op.add, "-": op.sub, "*": op.mul, "/": op.div}
    return operator[op[value1, value2]]
magic valley
#

not quite there. what thing is operator?

#

i should say what kind of thing is operator

crystal helm
#

i dont know

#

string?

magic valley
#

yes.

#

but do you want to get a substring for the problem?

wooden coral
#

The problem uses operator for a string such as "+".

magic valley
#

what do you want to return? What type in particular?

wooden coral
#

I know having op, operator, and operators all in the same spot is confusing here.
It might help to rename something to an unrelated name?

magic valley
#

also what kind of thing is op? Think about the types and what you can (and cannot) do with them.

crystal helm
#

i give up

#

my first solution was ugly but loved

#
def basic_op(operator, value1, value2):
    if operator=='+':
        return value1+value2
    if operator=='-':
        return value1-value2
    if operator=='/':
        return value1/value2
    if operator=='*':
        return value1*value2
#

this is the most viewed solution

magic valley
#

return operators[...]... what goes in the brackets?

#

even as more of a hint:

return operators[...](...)
crystal helm
#

its ok man i appreciate your help

#

i need to verify myself on upwork but its charging me

#

to do that

#

is this new?

magic valley
#

I don't know. Never used.

crystal helm
#

thank you for everyone's help! im done for today! i just wanted to solve at least 1 problem

wooden coral
#

Play around with that operators part on your own time, it can show you a bunch about using functions as objects, get you more into the internals so you can pull off more interesting tricks. ๐Ÿ™‚

vagrant light
#

extra computation, i suppose? but seems weird to care about in this example. and theres a way to get around that, too

crystal helm
#

how so karma?

vagrant light
#

instead of mapping the string to functions and then calling those functions to get the result.. just map the string to the result

#
def basic_op(operator, value1, value2):
  return { 
    "+": value1 + value2,
    "-": value1 - value2,
    "*": value1 * value2,
    "/": value1 / value2
  }[operator]
#

done

wooden coral
#

Yeah, that does the job. If it were any larger of a problem than this, the extra calculations would probably be wasteful. But it works. shrug

magic valley
vagrant light
#
def basic_op(operator, value1, value2):
  return { 
    "+": lambda: value1 + value2,
    "-": lambda: value1 - value2,
    "*": lambda: value1 * value2,
    "/": lambda: value1 / value2
  }[operator]()
crystal helm
tribal totem
#
def basic_op(operator, value1, value2):
    return eval(f'{value1}{operator}{value2}')``` The eval function could be used to great effect here as well
vagrant light
#

until someone inputs ;__import__('os').system('evil command');

abstract orbit
crystal helm
ornate totem
vagrant light
#

you can

ornate totem
#

pretty sure semicolon must be part of a statement

vagrant light
#

!e

print(eval(f'1;print("hello!");2'))
novel vineBOT
# vagrant light !e ```py print(eval(f'1;print("hello!");2')) ```

:x: Your 3.13 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print(eval(f'1;print("hello!");2'))
004 |           ~~~~^^^^^^^^^^^^^^^^^^^^^^^^
005 |   File "<string>", line 1
006 |     1;print("hello!");2
007 |      ^
008 | SyntaxError: invalid syntax
vagrant light
#

oh

ornate totem
#

๐Ÿ™‚

#

exec takes statements

vagrant light
#

i thought it works as substitute for newline

ornate totem
vagrant light
#

well its still easy

#

replace ; with +

#

code will error but itll run the evil stuff first

ornate totem
#

indeed

vagrant light
#

!e

print(eval(f'1+print("hello!")+2'))
novel vineBOT
# vagrant light !e ```py print(eval(f'1+print("hello!")+2')) ```

:x: Your 3.13 eval job has completed with return code 1.

001 | hello!
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 1, in <module>
004 |     print(eval(f'1+print("hello!")+2'))
005 |           ~~~~^^^^^^^^^^^^^^^^^^^^^^^^
006 |   File "<string>", line 1, in <module>
007 | TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
novel vineBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.