Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1782254
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2018-04-11 15:46:21

接上文

7.

#given a string, determine if it is comprised of all unique character:

#eg: 'abcde' -> True

# 'abcda' -> False

这个题,第一反应是将list转换成set, 比较length, 结果就很明白了。


点击(此处)折叠或打开

  1. def uni_chars(s):
  2.     return len(s) == len(set(s))

  3. def uni_chars_2(s):
  4.     chars = set()
  5.     
  6.     for letter in s:
  7.         if letter in chars:
  8.             return False
  9.         else:
  10.             chars.add(letter)
  11.     
  12.     return True

  13. print(uni_chars('abcde'))
  14. print(uni_chars('abcda'))
  15. print(uni_chars_2('abcde'))
  16. print(uni_chars_2('abcda'))

8.

#compress string:

#eg: aaabbc -> a3b2c1

#eg: AAAaaa -> A3a3

我记得以前看过某个博文讲压缩的时候讲过这个压缩.

点击(此处)折叠或打开

  1. def string_compress(s):
  2.     r = ''
  3.     l=len(s)
  4.     
  5.     if l == 0:
  6.         return ''
  7.     if l == 1:
  8.         return s+"1"

  9.     cnt = 1
  10.     i = 1
  11.     
  12.     while i < l:
  13.         if s[i] == s[i-1]:
  14.             cnt += 1
  15.         else:
  16.             r = r+s[i-1]+str(cnt)
  17.             cnt = 1
  18.         
  19.         i += 1
  20.     
  21.     r = r+s[i-1]+str(cnt)

  22.     return r

  23. print(string_compress('AAB'))

9.

#given a string of words, reverse all the words

这种题单行脚本就足够了


点击(此处)折叠或打开

  1. def rev_words(s):
  2.     return ' '.join(reversed(s.split()))

  3. def rev_words_2(s):
  4.     return ' '.join(s.split()[::-1])
  5.     
  6. def rev_words_3(s):
  7.     words=[]
  8.     length = len(s)
  9.     spaces = [' ']
  10.     
  11.     i = 0
  12.     while i < length:
  13.         if s[i] not in spaces:
  14.             word_start = i
  15.             while i < length and s[i] not in spaces:
  16.                 i += 1
  17.             words.append(s[word_start:i])
  18.     
  19.         i += 1
  20.     return ' '.join(reversed(words))

  21. print(rev_words('Hi John, are you ready to go?'))
  22. print(rev_words_2('Hi John, are you ready to go?'))
  23. print(rev_words_3('Hi John, are you ready to go?'))

10.

#Given an array of integers (positive and negative) find the largest continuous sum

p, li { white-space: pre-wrap; }

这个题我很喜欢,有点意思,因此放在最后


点击(此处)折叠或打开

  1. def large_cont_sum(arr):
  2.     if len(arr)==0:
  3.         return 0
  4.     
  5.     max_sum = current_sum = arr[0]
  6.     
  7.     for num in arr[1:]:
  8.         current_sum = max(current_sum + num, num)
  9.         max_sum = max(current_sum, max_sum)
  10.         
  11.     return max_sum
  12.     

  13. print(large_cont_sum([1,2,-1,3,4,10,10,-10,-1]))



阅读(690) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~