r/CodingHelp • • Oct 04 '21

[Python] how can I write my code more efficiently?

Post image
79 Upvotes

18 comments sorted by

21

u/icjeremy Oct 04 '21 edited Oct 04 '21

What do you mean by efficiently, exactly?

Like not repeat code so much? Especially since, if you wanted to change something like the range, you'd have to change it in 3 places. In this case, factor commonalities into a function. Something like:

def printRangeFiltered(begin, end, criteria):
  multiples = filter(criteria, range(begin, end))
  print(' '.join(str(e) for e in multiples))

printRangeFiltered(5, 26, lambda x: x % 3 == 0 or x % 5 == 0)
printRangeFiltered(5, 26, lambda x: x % 3 == 0 and x % 5 != 0)
printRangeFiltered(5, 26, lambda x: x % 3 != 0 and x % 5 != 0)

7

u/motelvirginmary Oct 04 '21

Wow thank you! I haven't learned function yet so this is eye opening for me. I'm looking more into function and filter now. Thank you!!

20

u/xelf Oct 04 '21

While we're at it:

You can do:

print(*multiples)

instead of:

print(' '.join(str(e) for e in multiples))

1

u/alpacasb4llamas Oct 04 '21

Whats this doing exactly

2

u/Ninesquared81 Oct 04 '21

The * operator unpacks iterables. This can be used to pass the elements of, say, a list as individual arguments to a function. If we had a function defined as def f(x, y): return x*y + x/y, then f(*[1, 2]) passes the same values as f(1, 2) does. There are other uses of the unpacking operator, but it's this argument unpacking that's going on here.

The print function is variadic, meaning it can take a variable number of arguments. These will be printed out, separated by the sep argument, which is " " (a single space character) by default.

So, print(*[1, 2, 3]) prints 1 2 3, and print(*[1, 2, 3], sep=", ") prints 1, 2, 3.

3

u/BKKBangers Oct 04 '21

Gosh; the logic, knowledge, and implementation makes me green with envy.

1

u/Goobyalus Oct 04 '21

This seems like an unnecessary level of indirection if you're not saving any argument passing by making the range constant.

printRangeFiltered(5, 26, lambda x: x % 3 == 0 or x % 5 == 0)
print(*(x for x in range(5, 26) if x % 3 == 0 or x % 5 == 0))
print(' '.join(x for x in range(5, 26) if x % 3 == 0 or x % 5 == 0))

Not really saving characters either

6

u/ashirviskas Oct 04 '21

I'd work on readability and the lack of whitespace. Also, you're running the loops redundantly. Here's how I'd write it:

multiples_a = []
multiples_b = []
multiples_c = []

for i in range(5, 26):
    if i % 3 == 0 or i % 5 == 0:
        multiples_a.append(i)
    if i % 3 == 0 and i % 5 != 0:
        multiples_b.append(i)
    if i % 3 != 0 and i % 5 == 0:
        multiples_c.append(i)
    
print(*multiples_a)
print(*multiples_b)
print(*multiples_c)

Wish you luck on your programming journey!

1

u/kill-yourself90 Oct 05 '21

Or better yet make a function

2

u/yes_i_relapsed Oct 04 '21

In case you want the code to consume less resources (not usually a concern, since we've already decided to use python) you could compose your list like this:

multiples = [ str(x) for x in range(5,26) if <whatever> ]

It saves you having to generate a second list and makes the following line just

string = ' '.join(multiples)

If you were doing math with the numbers, it would make more sense to keep them as ints and do what you're doing. But you're just printing them out.

1

u/[deleted] Oct 04 '21

Why do you have the same block of code repeated 3 times?

4

u/hollammi Oct 04 '21

The conditions checking x are different each time

1

u/Goobyalus Oct 04 '21 edited Oct 04 '21

Here is an "efficient" way:

>>> print(*(x for x in range(5, 26) if x % 3 == 0 or x % 5 == 0))
5 6 9 10 12 15 18 20 21 24 25
>>> print(*(x for x in range(5, 26) if x % 3 == 0 and x % 5 != 0))
6 9 12 18 21 24
>>> print(*(x for x in range(5, 26) if x % 3 != 0 and x % 5 != 0))
7 8 11 13 14 16 17 19 22 23

You're already using what's called "generator expressions." Generator expressions evaluate to a generator object, and generator objects allow you to iterate through values without storing the whole sequence in memory.

For example, when you do str(e) for e in multiples, that expression evaluates to a generator object, which you pass to join.

We can create the desired generators like this:

>>> (x for x in range(5, 26) if x % 3 != 0 and x % 5 != 0)
<generator object <genexpr> at 0x00000261FAB8DAC0>

If we try to print this, we'll get the string representation of the generator object (like you see above).

print accepts an arbitrary number of arguments, and by default separates them with spaces (similar to join). We can pass each element of our generator to print by unpacking it with the * operator:

>>> print(*(x for x in range(5, 26) if x % 3 == 0 or x % 5 == 0))
5 6 9 10 12 15 18 20 21 24 25

If your generators create very large sequences, this still puts the entire sequence into memory at the point where we call print, so it would not be memory efficient. You would want to print element by element or in chunks. You can adjust the end of a print statement to be something besides a newline.


Here's an example of unpacking.

A function that prints out an enumeration of its arguments:

>>> def f(*args):
...   for i, arg in enumerate(args):
...     print(f"argument {i}:\t{arg}")
...

A simple list:

>>> b = [1, 2, 3]

Passing the list to f:

>>> f(b)
argument 0:     [1, 2, 3]

Passing the unpacked list to f:

>>> f(*b)
argument 0:     1
argument 1:     2
argument 2:     3

-1

u/[deleted] Oct 05 '21

Use a different language, but not Ruby.

-3

u/[deleted] Oct 04 '21

[removed] — view removed comment

9

u/rnike879 Oct 04 '21

Ah man, why you gotta sound so condescending?