1

I have recently started learning Python in the MIT class on edX.

However, I have been having some trouble with certain exercises. Here is one of them:

"Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). "

The correct code, according to the lecture, is the following:

def oddTuples(aTup):
   '''
   aTup: a tuple

   returns: tuple, every other element of aTup.
   '''
    # a placeholder to gather our response
    rTup = ()
    index = 0

    # Idea: Iterate over the elements in aTup, counting by 2
    #  (every other element) and adding that element to
    #  the result
    while index < len(aTup):
        rTup += (aTup[index],)
        index += 2

    return rTup

However, I have tried to solve it myself in a different way with the following code:

def oddTuples(aTup):
    '''
   aTup: a tuple

   returns: tuple, every other element of aTup.
   '''
    # Your Code Here
    bTup=()
    i=0
    for i in (0,len(aTup)-1):
        if i%2==0:
            bTup=bTup+(aTup[i],)
            print(bTup)
        print(i)
        i+=1
    return bTup

However, my solution does not work and I am unable to understand why (I think it should do essentially the same thing as the code the tutors provide).

4

5 回答 5

3

我只想补充一点,这个问题的 pythonic 解决方案使用具有步宽的切片,并且是:

newTuple = oldTuple[::2]

oldTuple[::2]含义:从 start(省略值)到 end(省略)获取 oldtuple 的副本,spepwidth 为 2。

于 2012-10-16T18:27:24.317 回答
2

我想我在这里得到了问题。

在您的 for 循环中,您为 指定两个固定值i

0
len(aTup)-1

您真正想要的是从0到的值范围len(aTup)-1

0
1
2
...
len(aTup)-1

为了将开始值和结束值转换为范围内的所有值,您需要使用 Python 的range方法:

for i in range(0,len(aTup)-1):

(实际上,如果您查看range 的文档,您会发现有第三个参数称为skip。如果您使用它,您的函数就会变得无关紧要:))

于 2012-10-16T18:24:07.217 回答
1

您的代码应为:

for i in range(0,len(aTup)):
# i=0, 1, 2 ..., len(aTup)-1.

而不是

for i in (0,len(aTup)-1):
# i=0 or i=len(aTup)-1.
于 2012-10-16T18:24:03.063 回答
1

线条for i in (0,len(aTup)-1):i+=1没有完全按照您的意愿行事。与其他答案一样,您可能想要for i in range(0,len(aTup)-1):(insert range),但您也想要 remove i+=1,因为for-in构造i依次为迭代中的每个项目设置值。

于 2012-10-16T18:25:30.110 回答
0

好的,运行代码时,输​​出如下:

('I', 'tuple')

这是因为您编写的代码中的问题是您实现 for 循环的方式。而不是使用:

for i in (0,len(aTup)-1):

您应该将其更改为以下内容,您的代码将起作用:

for i in range(len(aTup)):

range 函数基本上创建了一个整数列表,范围从 0 到元组的长度 - 1。

因此,您的代码在编辑后应如下所示:

def oddTuples(aTup):
    bTup=()
    for i in range(len(aTup)):
        if i%2==0:
            bTup=bTup+(aTup[i],)
    return bTup
于 2017-01-20T08:03:23.123 回答