您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python練手題有哪些,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
第一題
def accum(s):
#寫你的代碼,代碼輸出結(jié)果
#accum("abcd") # "A-Bb-Ccc-Dddd"
#accum("cwAt") # "C-Ww-Aaa-Tttt"
這到題用到了字符串的所有字母大寫和所有字母小寫和字符串拼接,復(fù)制,用到的函數(shù)有 json 將列表中的內(nèi)容按照指定字符連接成一個(gè)字符串,upper() 所有字母變大寫 和lower() 所有字母小寫,含有內(nèi)置函數(shù)enumerate 返回值是索引和對(duì)應(yīng)得值。
對(duì)于一個(gè)可迭代的(iterable)/可遍歷的對(duì)象(如列表、字符串),enumerate將其組成一個(gè)索引序列,利用它可以同時(shí)獲得索引和值
enumerate多用于在for循環(huán)中得到計(jì)數(shù)
具體代碼如下
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):
#寫代碼, 輸出結(jié)果
# 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
這里面用到了最小值和最大值min(),max()
還有求和函數(shù)sum()
具體實(shí)現(xiàn)由以下代碼
def get_sum(a,b):
return sum(range(min(a,b),max(a,b)+1))
a = get_sum(2,-9)
第三題
def duplicate_count():
#寫代碼,要求實(shí)現(xiàn)以下功能給你一串字符串你要返回他的有重復(fù)的的字母個(gè)數(shù)包括大小
# test.assert_equals(duplicate_count("abcde"), 0)
# test.assert_equals(duplicate_count("abcdea"), 1)
# test.assert_equals(duplicate_count("indivisibility"), 1)
這里面用到了將所有字母都轉(zhuǎn)成小寫還有集合,和列表
代碼具體如下
def duplicate_count(text):
# Your code goes here
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():
#
輸入代碼實(shí)現(xiàn)以下的內(nèi)容
#
# 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"
這個(gè)方法有點(diǎn)魯,主要運(yùn)用的只是點(diǎn)就是列表和len()函數(shù)
具體代碼如下
def likes(names):
# your code here
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'
第五題
你的任務(wù)是創(chuàng)建一個(gè)函數(shù),它可以將任何非負(fù)整數(shù)作為參數(shù),并以降序的數(shù)字返回它?;旧?,重新排列數(shù)字以創(chuàng)建盡可能高的數(shù)字。
例子:
輸入:21445 輸出:54421
輸入:145263 輸出:654321
輸入:1254859723 輸出:9875543221
里面用到列表的排序,從大到小,還有類型轉(zhuǎn)換
大神代碼
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))
第六題
給定:一個(gè)包含名稱散列的數(shù)組
返回:格式為由逗號(hào)分隔的名稱列表的字符串,除了最后兩個(gè)名稱之外,應(yīng)該用連字符分隔。
例:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'
namelist([ {'name': 'Bart'} ])
# returns 'Bart'
namelist([])
# returns ''
這個(gè)主要用到列表和字符串的相關(guān)知識(shí)
def namelist(names):
# your code here
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 ato z.
#Examples:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
簡單的說也就是說你就是讓你證明這些字符串在不在‘a(chǎn)bcdefghijkml’里.
我的代碼如下
def printer_error(s):
# your code
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
我們講一下sub 的用法
re.sub的各個(gè)參數(shù)的詳細(xì)解釋
re.sub共有五個(gè)參數(shù)。
re.sub(pattern, repl, string, count=0, flags=0)
其中三個(gè)必選參數(shù):pattern, repl, string
兩個(gè)可選參數(shù):count, flags
第一個(gè)參數(shù):pattern
pattern,表示正則中的模式字符串,這個(gè)沒太多要解釋的。
第二個(gè)參數(shù):repl
repl,就是replacement,被替換,的字符串的意思。
repl可以是字符串,也可以是函數(shù)。
repl是字符串
如果repl是字符串的話,其中的任何反斜杠轉(zhuǎn)義字符,都會(huì)被處理的。
即:
\n:會(huì)被處理為對(duì)應(yīng)的換行符;
\r:會(huì)被處理為回車符;
其他不能識(shí)別的轉(zhuǎn)移字符,則只是被識(shí)別為普通的字符:
比如\j,會(huì)被處理為j這個(gè)字母本身;
反斜杠加g以及中括號(hào)內(nèi)一個(gè)名字,即:\g,對(duì)應(yīng)著命了名的組,named group
第三個(gè)參數(shù):string
string,即表示要被處理,要被替換的那個(gè)string字符串。
沒什么特殊要說明。
第八題
轉(zhuǎn)為二進(jìn)制
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.
要求輸出結(jié)果
Test.assert_equals(add_binary(1,1),"10")
Test.assert_equals(add_binary(0,1),"1")
Test.assert_equals(add_binary(1,0),"1")
Test.assert_equals(add_binary(2,2),"100")
Test.assert_equals(add_binary(51,12),"111111")
具體實(shí)現(xiàn)代碼如下
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)
首先給數(shù)字轉(zhuǎn)成字符串
然后建一個(gè)空列表
循環(huán)這個(gè)字符串的長度
然后進(jìn)行判斷判斷他這個(gè)字符串有沒有0
沒有0 就進(jìn)行計(jì)算讓他的位數(shù)根據(jù)字符的長度進(jìn)行想成 好比78 就要輸出 7* 10**1 8*10**0
最后添加到列表中
然后進(jìn)行字符串的拼接 要注意字符串的空格.
第十題
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.
到題主要是說數(shù)字的重權(quán)
也就是說數(shù)字的累加和
order_weight("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234000 44444444 9999")
好比2000 就是2 10003就是4 也就是這串?dāng)?shù)字的累加和
我的思路是用sorted()這個(gè)函數(shù) 根據(jù)這組數(shù)的
代碼如下
def order_weight(strng):
# your code
return ' '.join(sorted(sorted(strng.split(' ')),key = lambda x:sum(int(c) for c in x)))
首先把這個(gè)數(shù)進(jìn)行切割,然后用lambda算出這個(gè)數(shù)的累加和,在根據(jù)累加和進(jìn)行排序。
第十一題
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
#這道題是計(jì)算二進(jìn)制數(shù)。1出現(xiàn)的次數(shù)
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
#括號(hào)問題判斷是否是有效空號(hào)
def valid_parentheses(string):
#your code here
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
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Python練手題有哪些”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。