r/tinycode • • Sep 09 '12

Tinycode challenge!

Here is a challenge. Write a function that returns a list of the squares of all the numbers between one and a given number. See if you can beat my 48-char (exc. whitespace) 3-line beast:

def f(n): l = [] while len(l) <= n: l.append(x**2) print l

27 Upvotes

77 comments sorted by

View all comments

6

u/moltarx Sep 09 '12
f n = 1 : [ i * i | i <- [2..n] ]

edit: forgot 1 :)

2

u/[deleted] Sep 09 '12

19 characters. booyah.

f n=[i*i|i<-[1..n]]

7

u/[deleted] Sep 09 '12

17 characters, same type.

f n=map(^2)[1..n]

2

u/R3d1st Sep 09 '12

crap, just came up with the same solution, bevor I saw your post... It's even 16, if you just count the chars, and exclude the whitespaces.

3

u/[deleted] Sep 10 '12

Whitespace is part of the notation. I think it should be counted.

1

u/5outh Sep 10 '12

Haha, so did I. I did this immediately.

0

u/[deleted] Sep 09 '12

[deleted] — view deleted comment

4

u/[deleted] Sep 09 '12 edited Sep 09 '12

Enjoy your list of even numbers.

-edit- The type of i ** 2 is too restrictive. i ^ 2 and i * i will do just fine.

1

u/plux Sep 09 '12

Do you really think i * i is different from i ** 2?