-1
x = [1, 3, 2, 5, 7]

Starting from the first value of a list:

if the next value is greater, it prints "\nthe value x is greater than y"

if the next value is equal, it prints "\nthe value x is equal to y"

if the next value is smaller, it prints "\nthe value x is smaller than y"

How do I translate this into the exact Python code? I'm actually working with a pandas data frame, I just simplified it by using a list as an example.

x = [1, 3, 2, 5, 7]

With the given above, the output should be like this:

the value 3 is greater than 1
the value 2 is smaller than 3
the value 5 is greater than 2
the value 7 is greater than 5
R. Trading
  • 165
  • 1
  • 1
  • 8
  • 3
    What if the values are equal? What if there are fewer than two values in the list? What code have you tried, and just where are you stuck? Shouldn't the last line in your example output be `the value 7 is greater than 5`? – Rory Daulton Jun 03 '17 at 12:24
  • Related: https://stackoverflow.com/q/5434891/1639625 – tobias_k Jun 03 '17 at 12:30
  • I've edited out the typos, sorry for that. I'm stuck at everything, I tried thinking it out and doing it by myself but I don't even know where to start. – R. Trading Jun 03 '17 at 12:34

8 Answers8

6

Directly generate the output using str.join and a list comprehension zipping the list with a shifted version of itself for comparing inside the comprehension:

x = [1, 3, 2, 5, 7]

output = "\n".join(["the value {} is {} than {}".format(b,"greater" if b > a else "smaller",a) for a,b in zip(x,x[1:])])

print(output)

(note that "greater than" or "smaller than" isn't strict and applies to equal values even if it's confusing, so maybe a third alternative could be created to handle those cases as Benedict suggested, if the case can happen)

result:

the value 3 is greater than 1
the value 2 is smaller than 3
the value 5 is greater than 2
the value 7 is greater than 5

you can fiddle with the linefeeds with those variants:

"".join(["the value {} is {} than {}\n" ...

or

"".join(["\nthe value {} is {} than {}" ...
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
4

Python 2 one liner:

[print(str(l[i+1])+" is greater than" + str(l[i])) if l[i+1]>l[i] else print(str(l[i+1])+" is smaller than" + str(l[i])) for i in range(len(l)-1)]
Ganesh Kathiresan
  • 2,068
  • 2
  • 22
  • 33
2

Another Python 2 one-liner. This one handles equal items.

x = [1, 3, 2, 5, 5, 7]
print '\n'.join('the value %s is %s %s'%(u,['equal to','greater than','less than'][cmp(u,v)],v)for u,v in zip(x[1:],x))

output

the value 3 is greater than 1
the value 2 is less than 3
the value 5 is greater than 2
the value 5 is equal to 5
the value 7 is greater than 5

Can be made runnable with python 3 by defining cmp as:

cmp = lambda x,y : 0 if x==y else -1 if x < y else 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • @PM2Ring nice use of `cmp` but that works only in python 2. However you can emulate `cmp` using `cmp = lambda x,y : 0 if x==y else -1 if x < y else 1` in python 3. I wouldn't recommend python-2 only code. – Jean-François Fabre Jun 03 '17 at 15:02
  • @Jean-FrançoisFabre Well, I did say it was a Python 2 answer. I don't normally write Python 2 only code these days (unless the question is Python 2 specific), I was just having a bit of "code golf" fun. – PM 2Ring Jun 03 '17 at 15:15
  • @PM2Ring I know you know :) I took the liberty of editing your answer to make it python 3 compliant I hope you don't mind. – Jean-François Fabre Jun 03 '17 at 15:16
  • @Jean-FrançoisFabre I don't mind in this case, although normally I prefer a comment suggesting an edit, especially when the answer is still fresh. FWIW, I almost added a `cmp` definition myself, but I wanted to keep the code minimal, in the spirit of code golf. – PM 2Ring Jun 03 '17 at 15:21
  • I agree it's difficult to make it shorter. you can remove the space between `print` and quote, though :) – Jean-François Fabre Jun 03 '17 at 15:35
1

One could just use a for-loop and ternary operators, as follows;

x = [1, 3, 2, 5, 7]
for i in range(len(x)-1):
    comparison = "greater than" if x[i+1]>x[i] else ("equal to" if x[i+1]==x[i] else "less than")
    print("The value {0} is {1} {2}.".format(x[i+1],comparison,x[i]))
  • thanks for your edit, but there's a conflict with another edit of mine. It's generally better to comment on the answer rather than editing it directly, though (no offence taken!) – Jean-François Fabre Jun 03 '17 at 12:41
1
def cmp(item1, item2):
    if item2 == item1:
        return "{} is equal to {}".format(item2, item1)
    elif item2 >= item1:
        return "{} is greater than {}".format(item2, item1)
    elif item2 <= item1:
        return "{} is less than {}".format(item2, item1)
    else:
        return "Invalid item(s)."


x = [1, 3, 2, 5, 7]

for i in range(len(x)-1):
    print(cmp(x[i],x[i+1]))
Gahan
  • 4,075
  • 4
  • 24
  • 44
1
x = [1,4,5,3,4]

for i in range(0, len(x) - 1):
    out = "is equal to"
    if (x[i] < x[i + 1]):
        out = "is greater than"
    elif (x[i] > x[i + 1]):
        out = "is less than"

    print ("%s %s %s" % (x[i + 1], out, x[i]))

Do you want an explanation also?

Edit: Oops, and it would output:
4 is greater than 1
5 is greater than 4
3 is less than 5
4 is greater than 3

Polymer
  • 1,108
  • 1
  • 9
  • 17
  • Okay so it's pretty simple. (excuse my, accidentally pressed enter!) – Polymer Jun 03 '17 at 12:44
  • 1
    We define x We iterate through the list using range, range is similar to a for loop and will iterate x times from the beginning point y as output i (see link for more help with range). By default we set out to "is equal to", because if the condition isn't less than or greater to, it must be equal. Then literally all we're checking is if the i index in the array is less than/greater than the next one! Then outputting in the correct format. If you're new to arrays in python, http://www.i-programmer.info/programming/python/3942-arrays-in-python.html, best tute there. (goes into range, too) – Polymer Jun 03 '17 at 12:48
  • 1
    Oh, and in addition, the string format "%s %s %s" % (x[i + 1], out, x[i]) is used (python stole it from c) for quick formatting. At it's most basic level, "%s world" % "hello" would output "hello world". Just an easy way to inject variables into strings. – Polymer Jun 03 '17 at 12:50
  • Thanks for the explanation man, really appreciate your detailed explanation! I'll be studying your answer and others as I'm not familiar with these! – R. Trading Jun 03 '17 at 12:55
1

Example using lambda function

x = [1, 3, 2, 5, 7]

greater = lambda a, b: a > b

old_i = x[0]
for i in x[1::]:
    if old_i :
        print(i,"is", 
              "greater" if greater(i, old_i) else "smaller","than",old_i)
    old_i = i

Output

3 is greater than 1
2 is smaller than 3
5 is greater than 2
7 is greater than 5
sylvain1811
  • 74
  • 1
  • 3
  • This will fail if you have only 2 elements in the list – gipsy Jun 03 '17 at 13:00
  • @gipsy It won't, it will loop once and exit. For `x=[1,3]` it will print `3 is greater than 1`. What made you think it will fail ? – sylvain1811 Jun 03 '17 at 13:11
  • @sylvain1811 Before your edit it was. https://gist.github.com/gipsy86147/0db105070aa188a8b9c873f5f7613598 – gipsy Jun 03 '17 at 13:18
  • @gipsy Yes, I forgot to refactor variable `previous_i` to `old_i`. It wasn't a list size problem. – sylvain1811 Jun 03 '17 at 13:29
  • Yes you are right. But that faulty code will work fine for list with size greater than 2 . That's the reason I wanted to point that out. – gipsy Jun 03 '17 at 13:38
  • It wont, because of `if old_i : `. Variable `old_i` wasn't initialized, so it would throws a NameError exception. :) – sylvain1811 Jun 03 '17 at 13:51
1

Using recursion:

def foo(n, remaining):
  if not remaining:
    return
  if n < remaining[0]:
    print('the value {} is greater than {}'.format(remaining[0], n))
  else:
    print('the value {} is smaller than {}'.format(remaining[0], n))
  foo(remaining[0], remaining[1:])


def the_driver(num_list):
  foo(num_list[0], num_list[1:])


if __name__ == '___main__':
  x = [1, 3, 2, 5, 7]
  the_driver(x)
gipsy
  • 3,859
  • 1
  • 13
  • 21