【问题标题】:How to write and run more than one code in Python IDLE?如何在 Python IDLE 中编写和运行多个代码?
【发布时间】:2014-07-31 20:35:17
【问题描述】:

您如何获得在 IDLE 中运行的代码(见下文)?我现在被困在课程中,找不到解释。 我知道如何在 IDLE 中只运行一个“def”或代码,按 F5,编写例如 shell 中的 hash_string('udacity', 3),“Enter”,结果。当然,在该代码中,如果有多个代码,它将无法正常工作。为了更深入地了解我想在 Python Online Tutor 中运行它,条件是它可以在 IDLE 中运行,反之亦然。 此外,我想知道,为什么输入 #print hashtable_get_bucket(table, "Zoe") 结果:#>>> [['Bill', 17], ['Zoe', 14]] 为什么 'Bill', 17 会出现在列表中?

# Define a procedure, hashtable_get_bucket,
# that takes two inputs - a hashtable, and
# a keyword, and returns the bucket where the
# keyword could occur.

def hashtable_get_bucket(htable,keyword):
     return htable[hash_string(keyword,len(htable))]


def hash_string(keyword,buckets):
     out = 0
     for s in keyword:
        out = (out + ord(s)) % buckets
     return out

def make_hashtable(nbuckets):
     table = []
     for unused in range(0,nbuckets):
        table.append([])
     return table


#table = [[['Francis', 13], ['Ellis', 11]], [], [['Bill', 17],
#['Zoe', 14]], [['Coach', 4]], [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]]

#print hashtable_get_bucket(table, "Zoe")
#>>> [['Bill', 17], ['Zoe', 14]]

#print hashtable_get_bucket(table, "Brick")
#>>> []

#print hashtable_get_bucket(table, "Lilith")
#>>> [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]

感谢您抽出宝贵时间阅读该帖子并提出您的建议!

【问题讨论】:

  • 请描述您的期望和功能应该做什么。
  • 这是来自 MIT 6.00x 的吗?
  • @Tichodroma:请参考代码的最后一部分(#...)。例如。 #print hashtable_get_bucket(table, "Zoe") #>>> [['Bill', 17], ['Zoe', 14]]
  • @PadraicCunningham:CS101,它是“计算机科学入门”.. Udacity,第 5 课,查找桶等。
  • 这个问题是关于如何编写一个具有多个函数的Python程序。它与 Idle 无关,如果使用任何其他编辑器编写程序也是一样的。

标签: python python-idle


【解决方案1】:

首先回答您的最后一个问题:table 是一个三元组列表,因此是一个包含列表的列表。其中之一是[['Bill', 17], ['Zoe', 14]]。由于hash_string 返回一个索引,它从table 中检索一个列表,恰好是Bill 和Zoe 的列表。

此外,要在 IDLE 中运行多个函数,您必须创建一个调用其他函数的新函数(新的 def my_assignment 或其他东西)。

希望这会有所帮助。

【讨论】:

  • 你将如何编写那个新函数,以便调用提到的其他函数?
  • 你可能想再次运行 Python 教程,尤其是定义函数的部分,docs.python.org/2.7/tutorial/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
  • 2010-11-20
  • 2018-05-05
  • 1970-01-01
  • 2018-10-11
  • 2022-01-19
  • 2013-07-17
相关资源
最近更新 更多