1

I am writing in Python2.7 and need to figure out how to make ">" a variable that I send in when I call for the directions. I need to call this function several times and sometimes it needs to be "<".

sentiment_point = giving_points(index_focus_word, 1, sentence, -2)

def giving_points(index_focus_word, index_sentiment_word, sentence, location):
    if index_focus_word > index_sentiment_word:
        sentiment_word = sentence[index_focus_word + location]

I tried showing below what I want to do, but it does not work.

sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2)

def giving_points(index_focus_word, sign, index_sentiment_word, sentence, location):
    if index_focus_word sign index_sentiment_word:
        sentiment_word = sentence[index_focus_word + location]
cromod
  • 1,721
  • 13
  • 26
  • Please format your code by highlighting it and pressing the `{}` on the top of the in line editor. – Oisin Apr 23 '16 at 23:04

2 Answers2

4

The operator module provides functions that implement Python operators. In this case, you want operator.gt.

import operator
sentiment_point = giving_points(index_focus_word, operator.gt, 1, sentence, -2)

def giving_points(index_focus_word, cmp, index_sentiment_word, sentence, location):
    if cmp(index_focus_word, index_sentiment_word):
        sentiment_word = sentence[index_focus_word + location]
chepner
  • 497,756
  • 71
  • 530
  • 681
1
sentiment_point = giving_points(index_focus_word, ">", 1, sentence, -2)
... if index_focus_word sign index_sentiment_word:

This won't work, because you are passing ">" as a simple String and Python does not recognize you're intending to pass it as an Operator.

If your problem is binary ('<' or '>') a very simple solution would be, to pass not a String but a Bool value to determine which operator to use:

sentiment_point = giving_points(index_focus_word, True, 1, sentence, -2)

def giving_points(index_focus_word, greater, index_sentiment_word, sentence, location):
    if greater:
        if index_focus_word > index_sentiment_word:
            sentiment_word = sentence[index_focus_word + location]
        else: #....
    else:
        if index_focus_word < index_sentiment_word:
Mad Matts
  • 1,118
  • 10
  • 14