Python練手題,敢來挑戰嗎?
第一題
def accum(s):
#
寫你的程式碼,程式碼輸出結果
#accum("abcd") # "A-Bb-Ccc-Dddd"
#accum("cwAt") # "C-Ww-Aaa-Tttt"
這到題用到了字串的所有字母大寫和所有字母小寫和字串拼接,複製,用到的函式有 json 將列表中的內容按照指定字元連線成一個字串,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
這裡面用到了最小值和最大值min(),max()
還有求和函式sum()
具體實現由以下程式碼
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):
# 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():
#
輸入程式碼實現以下的內容
#
# 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"
這個方法有點魯,主要運用的只是點就是列表和len()函式
具體程式碼如下
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'
第五題
你的任務是建立一個函式,它可以將任何非負整數作為引數,並以降序的數字返回它。基本上,重新排列數字以建立儘可能高的數字。
例子:
輸入:21445 輸出:54421
輸入:145263 輸出:654321
輸入:1254859723 輸出:9875543221
裡面用到列表的排序,從大到小,還有型別轉換
大神程式碼
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([ {'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 ''
這個主要用到列表和字串的相關知識
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 ''
第七題
I n 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"
簡單的說也就是說你就是讓你證明這些字串在不在‘abcdefghijkml’裡.
我的程式碼如下
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 的各個引數的詳細解釋
re.sub 共有五個引數。
re.sub(pattern, repl, string, count=0, flags=0)
其中三個必選引數:pattern, repl, string
兩個可選引數:count, flags
第一個引數:pattern
pattern ,表示正則中的模式字串,這個沒太多要解釋的。
第二個引數:repl
repl ,就是replacement,被替換,的字串的意思。
repl 可以是字串,也可以是函式。
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.
要求輸出結果
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")
具體實現程式碼如下
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)
首先給數字轉成字串
然後建一個空列表
迴圈這個字串的長度
然後進行判斷判斷他這個字串有沒有0
沒有0 就進行計算讓他的位數根據字元的長度進行想成 好比78 就要輸出 7* 10**1 8*10**0
最後新增到列表中
然後進行字串的拼接 要注意字串的空格.
第十題
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")
好比2000 就是2 10003就是4 也就是這串數字的累加和
我的思路是用sorted()這個函式 根據這組數的
程式碼如下
def order_weight(strng):
# your code
return ' '.join(sorted(sorted(strng.split(' ')),key = lambda x:sum(int(c) for c in x)))
首先把這個數進行切割,然後用lambda算出這個數的累加和,在根據累加和進行排序。
第十一題
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):
#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
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29829936/viewspace-2168952/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 敢挑戰這3道 JavaScript 題嗎JavaScript
- 蘋果、谷歌等大廠的AI面試題被我們搞到手了,你敢來挑戰嗎?蘋果谷歌AI面試題
- 20個高階Java面試題,你要來挑戰嗎?Java面試題
- 挑戰Python題解-019Python
- 一人一python挑戰題解Python
- 智慧手機行業裁員大潮襲來 挑戰還在後面行業
- 行,Python終於跌神壇了!程式設計師:活該!你敢來評論嗎...Python程式設計師
- 十個Python練手的實戰專案,學會這些Python就基本沒問題了Python
- Python練手例子(16)Python
- Python練手例子(14)Python
- Python練手例子(13)Python
- Python練手例子(6)Python
- 4個Python經典專案實戰,練手必備哦Python
- Python 練習題Python
- 快來參加學習.NET 挑戰賽
- 併發程式設計帶來的挑戰程式設計
- 新手練習:Python練習題目Python
- 雲原生程式設計挑戰賽火熱開賽,51 萬獎金等你來挑戰!程式設計
- 用VR技術學車 你敢嗎?VR
- 挑戰演算法題:四數之和演算法
- 【題目全解】ACGO挑戰賽#8Go
- python怎麼讀_4個Python經典專案實戰,練手必備哦!Python
- python練習題解析Python
- 10個Python練手專案Python
- YT14-先來練練手之絕對值排序排序
- 人工智慧:未來的機遇與挑戰人工智慧
- 聊聊全站HTTPS帶來的技術挑戰HTTP
- 解決構建全球社群帶來的挑戰
- 挑戰高薪機會哦 大家快來看啊高薪
- 手機上的大資料:手機大資料的挑戰大資料
- 挑戰高薪!學習人工智慧,你準備好了嗎?高薪人工智慧
- 【Python學習實踐教程】10個Python經典專案實戰,練手必備Python
- 社群Task挑戰賽開啟,階梯式任務等你來戰
- 最近大火的直播答題系統在技術上難實現嗎?挑戰有多大?
- 挑戰系統 / 進入區域挑戰怪物
- 玩轉 Cgroup 系列之三:挑戰手動管理 Cgroup
- 中國程式設計師真的過多了嗎?你還敢入行嗎?程式設計師
- 在Python中使用OpenCV訓練神經網路來檢測手勢!PythonOpenCV神經網路