Python-nowcoder Zero-complexity Transposition

題目描述

You are given a sequence of integer numbers. Zero-complexity transposition of the sequence is the reverse of this sequence. Your task is to write a program that prints zero-complexity transposition of the given sequence.

輸入描述:
For each case, the first line of the input file contains one integer n-length of the sequence (0 < n ≤ 10 000). The second line contains n integers numbers-a1, a2, …, an (-1 000 000 000 000 000 ≤ ai ≤ 1 000 000 000 000 000).
輸出描述:
For each case, on the first line of the output file print the sequence in the reverse order.

輸入
5
-3 4 6 -8 9
輸出
9 -8 6 4 -3

原思路:將首部和尾部元素進行調換,直至到中間元素爲止(使用了列表輸出,不符合題意)
在這裏插入圖片描述

錯誤之處有:
1、replace函數使用錯誤,會導致做元素替換事把11當作“1”,“1”來進行處理
2、使用列表對輸出進行處理,即最後一行不應該爲list類型,這樣輸出就有中括號,來瞅瞅這樣就對了👇
在這裏插入圖片描述

  • replace 和 split的區別
  • replace()是替換函數,兩個參數,第一個參數是被替換內容,第二個參數是替換內容。即第二個替換第一個。
  • split() 是分割函數,操作:a=a.split(’,’),a變成了列表[‘1’,‘2’,‘3’]

他人解答,看別人的解決辦法也是一種學習的途徑
如:直接利用Python的語法特性

try:
    while 1:
        n = input()
        print(' '.join(input().split()[::-1]))
except:
    pass

👆但是輸入n根本沒有任何意義

如:使用一些內置函數

while True:
    try:
        n = int(input())
        num = [int(i) for i in input().split(" ")]
        num.reverse()
        for i in range(0, n):
            print(num[i], end=" ")
    except:
        break

知識點:

Python字符串與列表的相互轉換
1、字符串轉列表 split
2、列表轉字符串 join

>>> str1 = "hi hello world"
>>> print(str1.split(" "))
['hi', 'hello', 'world']
>>> list1 = ['hi', 'hello', 'world']
>>> print(" ".join(list1))
hi hello world
>>> 

Python實現字符串反轉的幾種方法
1、使用字符串切片
result = s[::-1]

s = 1, 2, 3, 4, 5
result = s[::-1]
print(result)

2、使用列表的reverse方法
l = list(s)
result = “”.join(l.reverse)

同理
l = list(s)
result = “”.join(l[::-1])

s = 1, 2, 3, 4, 5
l = list(s)
print(l)
l.reverse()
print(l)
result = " ".join('%s' %id for id in l)
print(result)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章