Hackerrank刷題筆記-Algorithm (1)
阿新 • • 發佈:2018-12-24
Problem 5: Plus Minus
strip() - 刪除 string 字串末尾的指定字元(預設為空格)
format - print(format(0.5,”.6f”)) –> 0.500000
Problem 7: Mini-Max Sum
format - print(“{:d} {:d}”.format(MIN,MAX))
Problem 16: Divisible Sum Pairs
def divisibleSumPairs(n, k, ar):
m=0
for i in ar:
ar2=ar.copy()
for j in ar2.remove(i):
if (i+j)\%k==0:
m+=1
return m
為什麼不對? 報錯資訊是: for j in ar2.remove(i):TypeError: 'NoneType' object is not iterable
ar2.remove(i) 這個操作的返回值是None
def divisibleSumPairs(n, k, ar):
count = 0
for i in range(n-1):
for j in range(i+1,n):
if 0 == (ar[i] + ar[j]) % k:
count += 1
return count
Problem 26: Picking Numbers
- map(f,list): list 中每個元素都輸入到f得到結果;
- reduce(f,list): list前兩個元素
- from collections import Counter:
a = Counter([1,2,3,1]) –> a[1] = 2
Problem 27: Climbing the Leaderboard
def climbingLeaderboard (scores, alice):
scores = list(set(scores))
scores.sort(reverse = True)
l = len(scores)
rank = []
for a in alice:
while (l > 0) and (a >= scores[l-1]):
l -= 1
rank.append(l+1)
return rank
Problem 28: The Hurdle Race
def hurdleRace(k, height):
maxhurdle = max(height)
if k >= maxhurdle:
return 0
else:
return maxhurdle - k
Problem 29: Designer PDF Viewer
def designerPdfViewer(h, word):
alpha = 'abcdefghijklmnopqrstuvwxyz'
maxheight = 0
for w in word:
height = h[alpha.index(w)]
if height > maxheight:
maxheight = height
return maxheight * len(word)
Problem 30: Utopian Tree
def utopianTree(n):
height = 1
for i in range(1,n+1):
# if i % 2 == 0:
# height = height + 1
# else:
# height = height * 2
height = height + 1 if i % 2 == 0 else height * 2
return height
Problem 31:
return 'YES' if len([x for x in a if x <= 0]) < k else 'NO'
Problem 32:Beautiful Days at the Movies
def beautifulDays(i, j, k):
count = 0
for num in range(i,j+1):
if 0 == abs(num-int(str(num)[::-1])) % k:
count += 1
return count
Problem 33:Viral Advertising
def viralAdvertising(n):
shared = 5
plike = 2
for i in range(2,n+1):
shared = math.floor(shared / 2) * 3
plike += math.floor(shared / 2)
return plike
Problem 34:Save the Prisoner!
return s + m % n - 1
這個為啥不行???
Problem 35: Circular Array Rotation
def circularArrayRotation(a, k, queries):
for i in queries:
yield (a[(i-k)%n])
Problem 36: Sequence Equation
def permutationEquation(p):
for i in range(len(p)):
yield p.index(p.index(i+1) + 1) + 1