【每日一题0611】 给定n个字符串,请对n个字符串按照字典序排列

题目描述: 给定n个字符串,请对n个字符串按照字典序排列。
输入描述: 输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。
输出描述: 数据输出n行,输出结果为按照字典序排列的字符串。

示例1
输入:
9
cap
to
cat
card
two
too
up
boat
boot
输出:
boat
boot
cap
card
cat
to
too
two
up

贡献者:Lee

使用sort方法默认排序

image

‘’
str_a=‘cap\nto\ncat\ncard\ntwo\ntoo\nup\nboat\nboot’
list_a=str_a.split(’\n’)
list_a.sort()
str_b=’\n’.join(list_a)
‘’

num = int(input())
list = []
    while num:
        str = input()
        list.append(str)
        num = num -1
return [i for i in sorted(list)]
"""
题目描述: 给定n个字符串,请对n个字符串按照字典序排列。
输入描述: 输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。
输出描述: 数据输出n行,输出结果为按照字典序排列的字符串。
"""
test_str_ = """9
cap
to
cat
card
two
too
up
boat
boot"""


def test(test_str):
    num, *words = test_str.split("\n")
    num = int(num)
    for i in range(num):
        for j in range(i + 1, num):
            if words[i] > words[j]:
                words[i], words[j] = words[j], words[i]
    return "\n".join(words)


result = """boat
boot
cap
card
cat
to
too
two
up"""

assert test(test_str_) == result

题解:

inp = '9\ncap\nto\ncat\ncard\ntwo\ntoo\nup\nboat\nboot'

def order(li):
    return '\n'.join(sorted(inp.split()[1:]))

assert order(inp) == 'boat\nboot\ncap\ncard\ncat\nto\ntoo\ntwo\nup'
n = int(input())
result = []
for i in range(n):
    ss = input()
    result.append(ss)
    result.sort()
for j in result:
    print(j)