python實現面試程序

之前面試的時候,面試官出了一道程序題,當時沒答上來,後來仔細想了想,發現還挺簡單的。

要求如下:

對一段話(這裏估計用英文字符),要求順序輸出排序後的字符。

例如:it is a test for this interview,i hope you can create a program to sort this to a file

要求得到的結果如下,不限編程語言:字母及其出現次數。

(1, 'can')

(1, 'sort')

(1, 'interview,i')

(1, 'create')

(1, 'test')

(1, 'file')

(1, 'hope')

(1, 'it')

(1, 'program')

(1, 'for')

(1, 'you')

(1, 'is')

(2, 'to')

(2, 'this')

(3, 'a')


python代碼如下:

 cat sort.py 

#!/usr/bin/env python

#-*- coding: utf-8 -*-

import sys,os

import MySQLdb


a=file('a.txt')

for i in a.readlines():

     list=i.split()

     print list


n=len(list)

#將a.txt文件放入到list中,並已空格作爲分隔符


conn=MySQLdb.connect(host='192.168.3.10',user='root',passwd='Xp29at5F37',db='test')

cur=conn.cursor()

cur.execute("drop table  if exists sort;")

cur.execute("create table sort(id int default 1, name char(20))")

cur.close()

n=len(a)

for i in range(n):

      print a[i]

      num=a[i]

      cur=conn.cursor()

      print "insert into sort (name) values('%s');" % (num)

      cur.execute("insert into sort (name) values('%s');" % (num))

      cur.execute("commit;")

      cur.close()

#鏈接到數據庫,創建一個新表,id默認值爲1,name 兩個列。將list中的每個字符都插入到name列中。


cur=conn.cursor()

cur.execute("select count(*) num, name from sort group by name order by num;")

result = cur.fetchall()

for i in result:

     print i

cur.close()

#最後用group by來排序,並輸出結果。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章