作者 主題: 急)python改寫  (閱讀 9996 次)

0 會員 與 1 訪客 正在閱讀本文。

ilvicco

  • 可愛的小學生
  • *
  • 文章數: 1
    • 檢視個人資料
急)python改寫
« 於: 2009-12-06 18:51 »
阿我是初學者
老師給了些作業
可是我實在不懂怎麼寫
想請大家幫幫我

幫我打出程式碼 和解釋一下好嗎 謝謝 :)


1)
import my_utilities
k = my_utilities.invoke_at_line
listB=range(2); listB[0]=k; listB[1]=k;
a= listB[0](10, “test 0”); print type(a)
a= listB[1](10, “test 1”); print type(a)
用 for loop 改寫 3.1 (請注意傳入的字串 “test 0” 有變成 “test 1”)

2)
def my_problem4_1(a):
        if a==1:
                return "one"
        elif a==2:
                return "two"
        elif a==3:
                return "three"
        else:
                return "larger than three"

Q: 不要用 if-else statement, 改用 list 來達到相同的功能

我:
def my_problem4_1(a):
    listA=['one','two','three','larger than three']
    if a>4:
        print listA[3]
    else:
        print listA[a-1]


可是這樣還是用到 if-else  怎麼樣可以直接用list達到相同功能??

redjack

  • 活潑的大學生
  • ***
  • 文章數: 426
    • 檢視個人資料
回覆: 急)python改寫
« 回覆 #1 於: 2009-12-18 16:45 »
第二題用list 的index 來做就可以了。
至於第一題用熱血來做就可以了。
Knowledge is Power

gdx

  • 可愛的小學生
  • *
  • 文章數: 1
    • 檢視個人資料
回覆: 急)python改寫
« 回覆 #2 於: 2010-04-12 05:36 »
第二題可以用 try XD

owenemma

  • 可愛的小學生
  • *
  • 文章數: 1
    • 檢視個人資料
回覆: 急)python改寫
« 回覆 #3 於: 2010-05-19 13:29 »
代碼: [選擇]
def my_fun(index):
listA=['oen', 'two', 'three']
try:
return listA[index]
except:
return 'out of range'

參考一下

littleq0903

  • 可愛的小學生
  • *
  • 文章數: 11
    • 檢視個人資料
回覆: 急)python改寫
« 回覆 #4 於: 2010-07-19 23:57 »
建議在寫程式的時候不要利用分號把兩行或以上寫成同一行

程式可讀性佳的,對自己的除錯或是邏輯思考會很有幫助唷!

yarco

  • 可愛的小學生
  • *
  • 文章數: 2
  • 性別: 男
    • 檢視個人資料
    • 垃圾回收站
回覆: 急)python改寫
« 回覆 #5 於: 2010-08-11 20:00 »
没用if-else哦...

代碼: [選擇]
>>> def p(n):
...   l = ['Zero', 'One', 'Two', 'Error']
...   return l[ n > len(l) - 1 and len(l) - 1 or n]
...
>>> p(4)
'Error'
>>> p(5)
'Error'
>>> p(-1)
'Error'
>>> p(-1)
'Error'
>>> p(1)
'One'

...大陆人到此(台湾论坛)一游...