Leetcode 刷题
01. 两数之和
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
output = []
for i in range(len(nums)):
for j in range(i + 1,len(nums)):
if nums[i] + nums[j] == target:
output.append(i)
output.append(j)
break
return output
07. 整数反转
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
b = str(x)
if x < 0:
c = -int(b[1::][::-1])
else:
c = int(b[::-1])
if -2 ** 31 <= c <= 2 ** 31 - 1:
return c
else:
return 0
09. 回文数
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
else:
b = str(x)
c = int(b[::-1])
if x == c:
return True
else:
return False
27. 移除元素
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
for i in range(len(nums)-1,-1,-1):
if nums[i] == val:
nums.pop(i)
return(len(nums))
28. 实现 strStr()
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return (0)
else:
if needle[0:len(needle)] not in haystack:
return (-1)
elif len(needle) > len(haystack):
return (-1)
else:
for i in range(0, len(haystack)):
if needle[0:len(needle)] == haystack[i:i + len(needle)]:
return(i)
break
35. 搜索插入位置
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
for i in range(len(nums)):
if nums[i] == target:
return(i)
else:
nums.append(target)
nums.sort()
for i in range(len(nums)):
if nums[i] == target:
return(i)
58. 最后一个单词的长度
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return(len(s.strip( ).split(' ')[-1]))
69. x 的平方根
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return int((int(x)**0.5))
136. 只出现一次的数字
异或:任何数于 0 异或为任何数 0 n => n;相同的数异或为 0: n n => 0
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for num in nums:
a = a ^ num
return a
169. 求众数
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
from collections import Counter
return(Counter(nums).most_common(1)[0][0])
217. 存在重复元素
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
from collections import Counter
result = Counter(nums)
for i in nums:
if result[i] >= 2:
return(True)
break
else:
return (False)
231. 2 的幂
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not (n & n-1)
258. 各位相加
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
a = str(num)
b = 0
c = 0
for i in range(0,len(a)):
b = int(a[i]) + b
if b < 10:
return (b)
else:
for j in range(0,len(str(b))):
c = int(str(b)[j]) + c
if c < 10:
return (c)
else:
return (int(str(c)[0]) + int(str(c)[1]))
344. 反转字符串
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
return s.reverse()
week01
Day01
编译器使用的是 PyCharm,Python 版本为 3.6。
Practice
1、在 Python 交互环境中下面的代码查看结果并将内容翻译成中文。
Python 之蝉
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
2、学习使用 turtle 在屏幕上绘制图形。
turtle.pensize(4)
turtle.pencolor('red')
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.mainloop()
Day02
估计编程过程中,80% 的 bug 是拼写错误造成的。比如大小写的问题、符号中英文的问题,多打或少打一个字符等。
Practice
#! _*_ coding='UTF-8' _*_
# 将华氏温度转换成摄氏温度
# F = 1.8C + 32
f = float(input("请输入华氏温度: "))
c = (f - 32) / 1.8
print("%.1f华氏度 = %.1f摄氏度" %(f,c))
# 输入半径计算圆的周长和面积
import math
radius = float(input("请输入圆的半径:"))
perimeter = 2 * math.pi * radius
area = math.pi * radius * radius
print ('周长:%.2f' %perimeter)
print ('面积:%.2f'%area)
# 输入年份,如果是闰年输出True,否则输出False
year = int(input('请输入年份:'))
is_leap = (year % 4 == 0 and year % 100 != 0 or year % 400 == 0)
print (is_leap)
Day03
Practice
# 英制单位英寸和公制单位厘米互换
value = float(input('请输入长度: '))
unit= input('请输入单位: ')
if unit == 'in' or unit == '英寸':
print ('%f英寸 = %f厘米' %(value, value * 2.54))
elif unit == 'cm' or unit == '厘米':
print ('%f厘米 = %f英寸' %(value, value / 2.54))
else:
print ('请输入有效的单位')
# 掷骰子决定做什么
from random import randint
face = randint(1,6)
if face == 1:
result = '唱首歌'
elif face == 2:
result = '跳个舞'
elif face == 3:
result = '学狗叫'
elif face == 4:
result = '做俯卧撑'
elif face ==5:
result = '念绕口令'
else:
result = '讲冷笑话'
print(result)
# 百分制成绩转等级制
score = float(input('请输入成绩: '))
if score >= 90:
grade = 'A'
elif score >=80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print ('对应的等级是:', grade)
# 输入三条边长如果能构成三角形就计算周长和面积
'''
先判断输入的边长能否构成三角形
如果能则计算出三角形的周长和面积
'''
import math
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
print ('周长: %f' %(a + b + c))
p = (a + b + c)/2
area = math.sqrt(p * (p-a) * (p - b ) * (p - c))
print ('面积: %f' %(area))
else:
print ('不能构成三角形')
# 个人所得税计算器
'''
输入月收入和五险一金计算个人所得税
'''
salary = float(input('本月收入: '))
insurance = float(input('五险一金:'))
diff = salary - insurance - 3500
if diff <= 0:
rate = 0
deduction = 0
elif diff < 1500:
rate = 0.03
deduction = 0
elif diff < 9000:
rate = 0.2
deduction = 555
elif diff < 35000:
rate = 0.25
deduction = 2755
elif diff < 55000:
rate = 0.3
deduction = 2755
elif diff < 80000:
rate = 0.35
deduction = 5505
else:
rate = 0.45
deduction = 13505
tax = abs (diff * rate - deduction)
print ('个人所得税:¥%.2f元' %tax)
print ('实际到手收入:¥%.2f元' %(diff + 3500 - tax))
Day04
Practice
#! _*_ coding='UTF-8' _*_
# 输入一个数判断是不是素数
from math import sqrt
num = int(input('请输入一个正整数: '))
end = int(sqrt(num))
is_prime = True
for x in range(2,end + 1):
if num % x == 0:
is_prime = False
break
if is_prime and num != 1:
print('%d是素数' %num)
else:
print ('%d不是素数' %num)
# 输入两个正整数,计算最大公约数和最小公倍数
x = int(input('x = '))
y = int(input('y = '))
if x > y:
(x, y) = (y, x)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print ('%d和%d的最大公约数是%d' %(x, y, factor))
print ('%d和%d的最小公倍数是%d' %(x, y, x*y // factor))
break
# 打印三角形图案
row = int(input('请输入行数: '))
for i in range(row):
for _ in range(i + 1):
print ('*',end = '')
print ()
for i in range(row):
for j in range(row):
if j < row - i -1:
print(' ',end = '')
else:
print('*',end = '')
print()
for i in range(row):
for _ in range(row -i - 1):
print(' ',end = '')
for _ in range(2 * i + 1):
print('*', end = '')
print()
参考资源
ChangeLog
- 190328 ZAPP Leetcode 刷题。
- 190303 ZAPP 上路。