开发者

python -Weird Print... HW

Write a function called exactly weird() which takes three strings as arguments and prints the longest one backwards. (In the case of a tie, the string whic开发者_开发问答h is the earlier argument should be selected.

The function call:

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

Should result in the following terminal output:

nohtyP

This is what I have done so far.. am not getting the scratch part right ...

running = True

while running:

    word = raw_input("Enter word:")

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


A faster approach (and it works for an arbitrary number of strings) is:

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


Unfortunately I'm somewhat of a novice myself with python, but the simplest way I see to do this is refer to this Reverse a string in Python to see a simple way to reverse a string. For the logic of picking which string to reverse, it would be easiest to create a list and store a max string based on length.

Here's a possible solution, using the reverse method on the other thread. Ideally, this method would just take one list as an argument, since then it would work for all sizes of input.

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")


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜