python -Weird Print ... HW

时间:2011-04-07 20:45:17

标签: python

编写一个名为exact weird()的函数,该函数将三个字符串作为参数并向后打印最长的字符串。 (如果是平局,则应选择前一个参数的字符串。

函数调用:

weird("I", "Love", "Python")

应该导致以下终端输出:

nohtyP

这是我到目前为止所做的事情......我没有把刮擦部分弄好......

running = True

while running:

    word = raw_input("Enter word:")

    if word[0] in "aeiou":
        print word + "yay"
    else:
        print word[1:] + word[0] + "ay"

3 个答案:

答案 0 :(得分:4)

更快的方法(适用于任意数量的字符串)是:

def weird(*s):
    return sorted(s,key=len,reverse=True)[0][::-1]

答案 1 :(得分:1)

不幸的是我自己对python有点新手,但我看到这样做的最简单的方法是参考这个Reverse a string in Python来看一个简单的方法来反转字符串。对于选择哪个字符串反转的逻辑,最简单的方法是创建一个列表并根据长度存储最大字符串。

这是一个可能的解决方案,在另一个线程上使用反向方法。理想情况下,这种方法只需要一个列表作为参数,因为它可以适用于所有大小的输入。

def weird(strOne, strTwo, strThree):
    strings = [strOne, strTwo, strThree]
    max = ""
    for x in strings:
        if len(max) < len(x):
            max = x
    print max[::-1]

weird("I", "Love", "Python")

答案 2 :(得分:0)

def weird(str1, str2, str3):
    # sort them according to length
    # guaranteed stable sort
    strings= sorted( (str1, str2, str3), key=len)
    # maximum_length is the length of the last one
    maximum_length= len(strings[-1])

    # now return the earliest (str1 < str2 < str3)
    # having len() == maximum_length
    for a_string in reversed(strings):
        if len(a_string) < maximum_length:
            break
        result= a_string

    return result[::-1]
相关问题