Archive

Posts Tagged ‘Python’

Python One-liner

April 20th, 2010 Fu4ny 2 comments

Dạo này cứ thấy đề nào đơn giản là máu viết = python one-liner (code python chỉ trên 1 dòng). Lang thang trên diễn đàn thì gặp flamebait, mình thì chả care đề bài mấy, nhưng mà tự nhiên máu viết bằng python =)).

Luyện one-liner để hiểu thêm về các cách code bài toán thôi, chứ ko phải là practice để dùng nó =))

Viết chương trình nhập vào số nguyên dương n, hãy tính tổng và tích các chữ số của nó.

1
reduce(lambda x,y:(x[0]*y,x[1]+y),[(1,0)]+[int(i) for i in list(str(raw_input('->')))])
Categories: Post Tags: ,

Python factorial handbook

January 10th, 2010 Fu4ny No comments

Here is a small code-snippet I found and collected.

It takes extract 1 argument and return its factiorial ( n! )

Read more...

Categories: Post Tags: ,

Reading number from file in Python

December 10th, 2009 Fu4ny No comments

Err, that was  a long time since my last tutorial. I'm learning Python now, and I decided to write some tutorials for it.

As you know, there's a simple concept about Python: "You have plenty of way to do things". This is, sometime, a advantages, but sometimes it's hard to decide the way you do "your things".

Today, I'll show you some ways to read number from file input, The good, the bad, and the ugly

The good, tradition, easy:

1
2
3
4
5
6
fin = open("input.txt","r")
for line in fin.readlines():
   #unpack with line.split()
   p = line.split()
   #Get your variable
   n = int(p[0])

Why it's good: it's easy to understand, easy to maintain, easy to write (but slow as hell ).

It's just do the job: read line one by one, split and pack number in to a tuple

The bad, tradition, and still works

1
2
3
4
5
fin = open("input.txt","r")
t = fin.read()
inputTuple = t.split()
for i in inputTuple:
    print i

Thingy: it's just read all the file, split and store all the number into a tuple, whenever you want them or not. It's just eating you RAM, *yum yum*

The ugly, if you want one-liner

1
[i for x in [x.split() for x in open('input.txt')] for i in x]

It's just very good, do all the thing in "The bad" ways, but with only one-line. Do it if you don't want anyone to understand your code.

The IDK, if you just want to read 1 number

1
2
3
4
fin = open("input.txt",'r')
n = ''
while ( n[-1] != ' ' ): n += fin.read(1)
n = int(n[:-1])

Another, just works, easy to understand code.

Is there any other ways that you know ;)

Categories: Post Tags: , ,