[LeetCode] Two Sum

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        num_list = []

        for i in range(len(nums)):
            for j in nums:
                if nums[i] + j == target and i != nums.index(j):
                if len(num_list) < 2:
                    num_list.append(nums[i])
                    num_list.append(j)

        index = 0
        nums_ind = []
        for j in nums:
            if nums[index] in num_list:
                nums_ind.append(index)
            index+=1

        return nums_ind

未命名

閱讀更多»

【Python 網頁爬蟲入門實戰】ch2 HW

目標 1:
・找出範例網頁一 總共有幾篇 blog 貼文
找出範例網頁一 總共有幾張圖片網址含有 ‘crawler’ 字串

import requests
from bs4 import BeautifulSoup
import re

resp = requests.get("http://blog.castman.net/web-crawler-tutorial/ch2/blog/blog.html")
soup = BeautifulSoup(resp.text, "html5lib")

titles = []
for t in soup.find_all("h4"):
    titles.append(t)
    print(t.text.strip())

print("此部落格共有 " + str(len(titles)) + " 篇文章")

img_len = 0
#若沒有使用這方法,最後會輸出那一行有幾個字元
#而不是原本目標的幾篇or幾張

for img in soup.find_all("img", {"src": re.compile(".*crawler")}):
   print(img["src"])
   img_len += 1

print("此部落格共有 " + str(img_len) + " 張網址含有 'crawler' 字串的圖片")

閱讀更多»

【Python 網頁爬蟲入門實戰】ch1 HW

目標

1. 取出範例網頁的標題 (title) 與段落 (p) 文字
2. 讓程式試著取出範例網頁中不存在的標籤文字 (如 button.text), 並且在標籤不存在時, 程式能正常結束

程式碼

import requests
from bs4 import BeautifulSoup

def get_text(url, tag):
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text, "html5lib")
    try:
        if resp.status_code == 200:
            return soup.find(tag).text
    except:
        return None

def main():
    t = get_text("http://blog.castman.net/web-crawler-tutorial/ch1/connect.html", "title")
    print(t)
    p = get_text("http://blog.castman.net/web-crawler-tutorial/ch1/connect.html", "p")
    print(p)
    b = get_text("http://blog.castman.net/web-crawler-tutorial/ch1/connect.html", "botton")
    print(b)

main()

閱讀更多»

2017.9.3 Dictionaries

Dictionaries

1.

# 在 dictionary 中創造新的 key

dict_name[new_key] = new_value

2.

# 改變其中一個 key 的 value

dict_name[key] = new_value

3.

# 刪除一個 key

del dict_name[key_name]

 


stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

del stock['banana']
print(stock)

{‘apple’: 0, ‘orange’: 32, ‘pear’: 15}

閱讀更多»

2017.9.2 List / Slices

List

# 使用 for loop 定義 number 為 my_list 中的各項數據
# 使 my_list 不被變更,可重複使用

my_list = [1,9,3,8,5,7]
  for number in my_list:
    print(2 * number)

2
18
6
16
10
14


# 也可另外創一個 empty list
# 視情況去增加 .append() 或 排列 .sort()

start_list = [5, 3, 1, 2, 4]
square_list = []
  for number in start_list:
    square_list.append(number ** 2)
    square_list.sort()

print (square_list)

[1, 4, 9, 16, 25]

閱讀更多»