# Python练手题，敢来挑战吗？

### 第一题

```def accum(s):
#写你的代码，代码输出结果
#accum("abcd")  # "A-Bb-Ccc-Dddd"
#accum("cwAt")  # "C-Ww-Aaa-Tttt"```

upper() 所有字母变大写 和lower() 所有字母小写 含有内置函数enumerate 返回值是索引和对应得值

• 对于一个可迭代的（iterable）/可遍历的对象（如列表、字符串），enumerate将其组成一个索引序列，利用它可以同时获得索引和值
• enumerate多用于在for循环中得到计数

```def asuum(s):
return '-'.join(y.upper() + y.lower()* x for x,y in enumerate(s))
a = asuum('abcd')
print(a)```

### 第二题

```def get_sum(a,b):

#写代码, 输出结果

# get_sum(1, 0) == 1   // 1 + 0 = 1
# get_sum(1, 2) == 3   // 1 + 2 = 3
# get_sum(0, 1) == 1   // 0 + 1 = 1
# get_sum(1, 1) == 1   // 1 Since both are same
# get_sum(-1, 0) == -1 // -1 + 0 = -1

# get_sum(-1, 2) == 2  // -1 + 0 + 1 + 2 = 2```

```def get_sum(a,b):
return sum(range(min(a,b),max(a,b)+1))
a = get_sum(2,-9)```

### 第三题

```def duplicate_count():
#写代码,要求实现以下功能给你一串字符串你要返回他的有重复的的字母个数包括大小

# test.assert_equals(duplicate_count("abcde"), 0)
# test.assert_equals(duplicate_count("abcdea"), 1)
# test.assert_equals(duplicate_count("indivisibility"), 1)```

```def duplicate_count(text):
text = text.lower()
texts = set(text)
lists = []
for i in texts:
numbers = text.count(i)
if numbers != 1:
lists.append(numbers)
return len(lists)```

### 第四题

```def likes():
# 输入代码实现以下的内容
#
# likes [] // must be "no one likes this"
# likes ["Peter"] // must be "Peter likes this"
# likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
# likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
# likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"```

```def likes(names):
if names:
if len(names) == 1:
return names[0] + ' likes this'
elif len(names) == 2:
return names[0] + ' and ' + names[1] + ' like this'
elif len(names) == 3:
return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this'
else:
return names[0] + ', ' + names[1] + ' and ' + str(len(names) - 2) + ' others like this'
else:
return 'no one likes this'```

### 第五题

```def Descending_Order(num):
return int("".join(sorted(str(num), reverse=True)))```

```def Descending_Order(num):
#Bust a move right here
nums = list(str(num))
nums.sort(reverse=True)
return int(''.join(nums))```

### 第六题

namelist([]) # returns ''

```def namelist(names):
if len(names) > 1:
return '{} & {}'.format(', '.join(i['name'] for i in names[:-1]), names[-1]['name'])

elif len(names) == 1:
return names[0]['name']
else:
return ''```

### 第七题

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from `a to m`.

The colors used by the printer are recorded in a control string. For example a "good" control string would be `aaabbbbhaijjjm` meaning that the printer used three times color a, four times color b, one time color h then one time color a...

Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. `aaaxbbbbyyhwawiwjjjwwm`.

You have to write a function `printer_error` which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from `a`to `z`.

#Examples:

s="aaabbbbhaijjjm" error_printer(s) => "0/14" s="aaaxbbbbyyhwawiwjjjwwm" error_printer(s) => "8/22"

```def printer_error(s):
a = 0
for i in range(0,len(s)):
if s[i] not in 'abcdefghijklm':
a += 1
return '{}/{}'.format(str(a),len(s)```

```from re import sub
def printer_error(s):
return "{}/{}".format(len(sub("[a-m]",'',s)),len(s))```

#他这里用到了字符串的替换sub

re.sub的各个参数的详细解释

re.sub共有五个参数。

re.sub(pattern, repl, string, count=0, flags=0)

### 第一个参数：pattern

pattern，表示正则中的模式字符串，这个没太多要解释的。

### 第二个参数：repl

repl，就是replacement，被替换，的字符串的意思。

repl可以是字符串，也可以是函数。

repl是字符串

\n：会被处理为对应的换行符； \r：会被处理为回车符； 其他不能识别的转移字符，则只是被识别为普通的字符： 比如\j，会被处理为j这个字母本身； 反斜杠加g以及中括号内一个名字，即：\g，对应着命了名的组，named group

### 第三个参数：string

string，即表示要被处理，要被替换的那个string字符串。

### 第八题

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

```def add_binary(a,b):
return bin(a+b).lstrip('0b')```

```def add_binary(a, b):
return format(a + b, 'b')```

### 第九题

Write Number in Expanded Form You will be given a number and you will need to return it as a string in Expanded Form. For example: expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2'

expanded_form(70304) # Should return '70000 + 300 + 4'

```def expanded_form(num):
nums = str(num)
x = []
for i in range(0,len(nums)):
if int(nums[i]) != 0:
s = str(int(nums[i]) * (10 ** (len(nums) - i - 1)))
x.append(s)
return ' + '.join(x)```

### 第十题

My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest. I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits. For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers? Example: "56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99" When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string. All numbers in the list are positive numbers and the list can be empty.

order_weight("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234000 44444444 9999")

```def order_weight(strng):
return ' '.join(sorted(sorted(strng.split(' ')),key = lambda x:sum(int(c) for c in x)))```

### 第十一题

Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

#这道题是计算二进制数。1出现的次数

```def countBits(n):
s = lambda x: sum(int(z) for z in x)
return s(format(n, 'b'))```

```def countBits(n):
return format(n, 'b').count('1')```

### 第十二题

Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true

#括号问题判断是否是有效空号

```def valid_parentheses(string):
cnt = 0
for i in string:
if i == "(":cnt+=1
if i == ")":cnt-=1
if cnt < 0: return False
return True if cnt == 0 else False```

*声明：推送内容及图片来源于网络，部分内容会有所改动，版权归原作者所有，如来源信息有误或侵犯权益，请联系我们删除或授权事宜。

- END -

0 条评论

• ### alter table锁表，MySQL出现Waiting for table metadata lock的场景浅析及解决方案

在修改/增加表字段的时候，发现很慢， show processlist; 时， Waiting for table metadata lock 能一直锁很久。 ...

• ### Django 1.11官方教程翻译

一直以来由于英语废所以极端抵触看英文文档。感觉人还是要逼一下自己，所以就有了这篇翻译。如果有翻译错误的地方欢迎在评论中指正。 Let’s learn by e...

• ### [来稿]pycharm快捷键、tips、常用设置及版本控制 制

在PyCharm安装目录 /opt/pycharm-3.4.1/help目录下可以找到ReferenceCard.pdf快捷键英文版说明 or 打开pychar...

• ### 关于合并Sharply-Scarf房地产市场(cs.GT)

我们研究合并Sharply-Scarf房地产市场的好的影响。我们为受合并影响的代理商数量与他们遭受的损失程度加上了严格的限界。我们发现在最糟糕的情形下，市场合并...

• ### 从手机拍摄的图片里获取拍摄地点的经纬

We can get the date and phone model information from the photos which are jpg or...

• ### Leetcode solution 680: Valid Palindrome II

https://blog.baozitraining.org/2019/03/leetcode-solution-680-valid-palindrome.ht...

• ### Install ExpressCache for SSD Caching

如果你拥有一个安装SSD的电脑，而且已经安装了Windows操作系统。如果这台电脑在出厂OEM 系统分区但都已经被你改变了或者是全新的硬盘，那么这篇文章可能适合...

• ### 实战|手把手教你训练一个基于Keras的多标签图像分类器

原文链接：https://www.pyimagesearch.com/2018/05/07/multi-label-classification-with-ke...

• ### 从手机拍摄的图片里获取拍摄地点的经纬度

We can get the date and phone model information from the photos which are jpg or...

• ### Maat：自动分析VirusTotal以进行准确标记和有效的恶意软件检测方法（CS CS）

恶意软件分析和检测研究社区依靠在线平台VirusTotal来基于大约60个抗病毒扫描程序的扫描结果标记Android应用程序。不幸的是，目前尚无关于如何最好地解...