2014年3月26日 星期三

[Python][CheckIO] Solve Ghosts age

莫名其妙一個簡單的題目寫了兩天於是紀念一下


 def is_fibonacci(num):  
   cur = 0  
   prev1 = 1  
   prev2 = 0  
   while cur < num:  
     cur = prev1 + prev2  
     prev2 = prev1  
     prev1 = cur  
   if num == cur:  
     return True  
   else:  
     return False  
 def checkio(opacity):  
   if opacity == 10000:  
     return 0  
   cur = 10000  
   last_fibonacci = 1  
   for yrs in range(1, 5000):  
     if is_fibonacci(yrs) == True:  
       if cur - yrs == opacity:  
         return yrs  
       else:  
         cur -= yrs  
         last_fibonacci = yrs  
     else:  
       if cur + 1 == opacity:  
         return yrs  
       else:  
         cur += 1  

2014年3月22日 星期六

[Python] Formatted Binary

>>> '{0:08b}'.format(6)
00000110
Just to explain the parts of the formatting string:
  • {} places a variable into a string
  • 0 takes the variable at argument position 0
  • : adds formatting options for this variable (otherwise it would represent decimal 6)
  • 08 formats the number to eight digits zero-padded on the left
  • b converts the number to its binary representation
ref. http://stackoverflow.com/questions/10411085/converting-integer-to-binary-in-python 

2014年3月16日 星期日

[Python] key function for sorting

Example
 def checkio(numbers_array):  
   list_num = list(numbers_array)  
   list_num = sorted(list_num, key=abs)  
   return list_num  


[Note]

1. The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes

2. A common pattern is to sort complex objects using some of the object's indices as a key
Example 
>>> student_tuples = [  
     ('john', 'A', 15),  
     ('jane', 'B', 12),  
     ('dave', 'B', 10),  
 ]  
 >>> sorted(student_tuples, key=lambda student: student[2])  # sort by age  
 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]  

[Ref]

https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions

2014年3月8日 星期六

[Python] Roman Numerals Converter

Speedy solution:

1:  def checkio(input):  
2:    ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)  
3:    nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')  
4:     
5:    result = ""  
6:    
7:    for i in range(len(ints)):  
8:       count = int(input / ints[i])  
9:       result += nums[i] * count  
10:      input -= ints[i] * count  
11:     
12:    return result  


ref . http://www.rapidtables.com/math/symbols/roman_numerals.htm

--

人家寫12行我寫108行,真 他媽的