python中怎么将字母倒着写_Python:将句⼦中的单词全部倒排过来,但单词的字母顺序。。。
早上看到好友未央的⼀篇博⽂《⼀道google的测试⼯程师笔试题》,内容如下:
这是去年⾯试google测试⼯程师的⼀道题,题⽬如下:
设计⼀个函数,使⽤任意语⾔,完成以下功能:
⼀个句⼦,将句⼦中的单词全部倒排过来,但单词的字母顺序不变。⽐如,This is a real world,输出结果为world real a is this.  他⽤
C++很好的封装了⼀个函数实现了此功能,如下,更多信息请访问:
C++版本:
#include
#include
using namespace std;
const char *Reverse(char *src);
char *pDst=NULL;
int main(int argc,char **argv)
{
cout << "please input your sentense:" << endl;
char pSrc[100];
memset(pSrc,0,100);
cout << Reverse(pSrc) << endl;
if (pDst != NULL)delete pDst;
return 0;
}
const char *Reverse(char *pSrc)
{
char *pPos = pSrc;
int iLen=strlen(pSrc);
pDst = new char[iLen + 1];
memset(pDst,0,iLen+1);
int iCurrentPos = 0;
int iPrePos = 0;
while (pPos)
{
if (pSrc[iCurrentPos] <= 'z' && pSrc[iCurrentPos] >= 'A')
{
iCurrentPos++;
pPos ++;
continue;
}
else
{
int iDistance =iCurrentPos-iPrePos;
for (int i=0;i < iDistance;i++)
{
pDst[iLen - iCurrentPos+i] = pSrc[iPrePos+i];
}
pDst[iLen-iCurrentPos-1]=pSrc[iCurrentPos]; iCurrentPos ++;
}
iPrePos = iCurrentPos;
if (*pPos == '\0')
{
break;
}
else
{
pPos ++;
}
}
return pDst;
}
memset(pDst,0,iLen+1);
int iCurrentPos = 0;
int iPrePos = 0;
while (pPos)
{
if (pSrc[iCurrentPos] <= 'z' && pSrc[iCurrentPos] >= 'A') {
iCurrentPos++;
pPos ++;
continue;
}
else
{
int iDistance =iCurrentPos-iPrePos;
for (int i=0;i < iDistance;i++)
{
pDst[iLen - iCurrentPos+i] = pSrc[iPrePos+i];
}
pDst[iLen-iCurrentPos-1]=pSrc[iCurrentPos];
iCurrentPos ++;
}
iPrePos = iCurrentPos;
if (*pPos == '\0')
{
break;
}
else
{
pPos ++;
}
}
return pDst;
}
想了⼀下,如果此功能使⽤python来实现的话,可能⽐较⽅便,⼤致思路如下:
1. 将语句中的单词提取出来放⼊list中;
2. 将list反转;python怎么读的
3. 将反转后的list输出。
实现如下:
python版本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def str_reverse(str_src):
'''
Function:返转单词,以空格或TAB键为间隔符
Input:NONE
Output: NONE
author: socrates
date:2012-02-18
'''
#以空格为分隔符,将各单词取出来存放在list中
str_dst = str_src.split()
#反转list
verse()
#返回反转后的list对象
return str_dst
if __name__ == '__main__':
#遍历list,输出内容
for str_out in str_reverse(raw_input("please input your sentense:")): print str_out,
测试:
[root@kevin python_test]# ./str_test.py
please input your sentense:This is a real world
world real a is This
[root@kevin python_test]# ./str_test.py
please input your sentense:中国 陕西 西安
西安 陕西 中国
[root@kevin python_test]#