0%

Matplotlib

  • Scatter graph is used to represent the relationship between variables
  • 折线图体现变化, 散点图体现x和y的关系,条形图统计离散数据,直方图统计连续数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import random

from matplotlib import pyplot as plt

x = range(0, 120)
y = [random.randint(20, 35) for i
in range(120)]

plt.figure(figsize=(20, 8), dpi=80)
plt.plot(x, y)

# adjust x
#_x = list(x)
_xtick_labels = ["10:{} min"
.format(i) for i in range(60)]
_xtick_labels += ["11:{}".format(i) for i in range(60)]
plt.xticks(list(x)[::3], _xtick_labels[::3], rotation=45)

plt.xlabel("Time")
plt.ylabel('Temperatur unit(C)')
plt.title('Temprature from 10:12')
plt.show()

x, y and grid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from matplotlib import pyplot as plt

y = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]


x = range(11, 31)

plt.figure(figsize=(20, 8), dpi=80)
plt.plot(x, y)

_xtick_labels = ["{} years old".format(i) for i in x]
plt.xticks(x, _xtick_labels, rotation=45)
plt.yticks(range(0, 9))
# grid
plt.grid(alpha=0.4) # alpha is opacity

plt.show()

Read more »

For loop

  1. Print 4 rows 4 columns rectangle
1
2
3
4
5
l = 4
for i in range(4):
for j in range(4):
print('*', end="")
print(' ')
  1. Print traiangle

    1
    2
    3
    4
    row = int(input('Type a number'))
    for i in range(1, row+1):
    print((row - i) * " ", end="") # 打印空格
    print(i * "* ") # 打印星号
  1. Print upside-down triangle

    1
    2
    3
    4
    l = 4
    for i in range(1, l + 1):
    print((i - 1) * " ", end="") # 打印空格
    print((4 - i + 1) * "* ") # 打印星号
  2. Diamond

1
2
3
4
5
6
7
row = int(input('Type a number'))
for i in range(1, row+1):
print((row - i) * " ", end="") # 打印空格
print(i * "* ") # 打印星号
for i in range(1, row + 1):
print(i * " ", end="") # 打印空格
print((row - i) * "* ") # 打印星号

While loop

  1. Number guessing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random

flag = False
random_num = random.randint(1, 100)
while not flag:
guess = int(input('Please type a number you want to guess\n'))
print(random_num)
if guess < random_num:
print('Your number is too small')
elif guess > random_num:
print('Your number is too big')
else:
print('perfect')
flag = True
  1. 正序乘法表

    1
    2
    3
    4
    5
    6
    7
    8
    i = 1
    while i <= 9:
    j = 1
    while j <= i:
    print('%d*%d = %2d\t' % (i, j, i * j), end='')
    j += 1
    i += 1
    print()
  2. 逆序乘法表

    1
    2
    3
    4
    5
    6
    7
    8
    i = 9
    while i >= 1:
    j = 1
    while j <= i:
    print('%d*%d = %2d\t'%(j, i, i * j), end='')
    j += 1
    i -= 1
    print()
    1. triangle

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      row = 1
      while row <= 5:
      j = 1
      while j <= 5 - row:
      print(' ', end='')
      j += 1
      k = 1
      while k <= 2 * row - 1:
      print('*', end='')
      k += 1
      print()
      row += 1
  1. pramid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
*
**
***
****
*****
'''
i = 1
while i <= 5:
j = 1
while j <= i:
print('*', end='')
j += 1
i += 1
print()

  1. Rectangular Spotted Graph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
i = 1
while i <= 5:
j = 1
while j <= 5:
if i == j:
print('X', end='')
elif j == 5 - i + 1:
print('X', end='')
else:
print('*', end='')
j += 1
i += 1
print()

"""
x00000x
0x00x00
000x000
00x0x00
0x000x0
x00000x
"""

Function

  1. Pass info from
1
2
3
4
5
6
def greet_user(username):
print("hello, " + username.title() + "!")


greet_user(input())

day04_课后练习

第一题

  • 语法点:运算符,while,if
  • 编写步骤:

    1. 定义类 Test1
    2. 定义 main方法
    3. 定义变量i为0,i2为10
    4. 使用第一个while循环,当条件为i小于5 时,则进入循环
    5. 循环内,i自增,i2自增
    6. 循环内,使用if判断,当i大于等于 2 并且 i2小于15 时,同时输出i和i2的值
    7. 使用第二个while循环,当条件为i2小于20 时,则进入循环
    8. 循环内,i自增,i2自增
    9. 循环内,使用if判断,当i大于8 或者i2小于等于18 时,同时输出i和i2的值
Read more »

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.*;
public class SpringPractice01
{
public static void main(String[] args)
{
System.out.println(max(1,4));
System.out.println(max(1.3,4.2, 5.6));
}

public static int max(int a, int b)
{
return Math.max(a, b);
}
//Java doesn't care return value
//As long as parameter list not equal, that is overload
// public static int max(double a, double b, double c)
// {
// return Math.max(Math.max(a, b), c);
// }
public static double max(double a, double b, double c)
{
return Math.max(Math.max(a, b), c);
}
}

Java doesn’t care return value(public static double…) (public static int…)
As long as parameter list not equal, that is overload

Read more »

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*;

class Program {
public static int[] twoNumberSum(int[] array, int targetSum) {
for(int i = 0; i < array.length; i++)
{
for(int j = i + 1; j < array.length; j++)
{
if(array[i] + array[j] == targetSum)
{
return new int[]{array[i], array[j]};
}
}
}
return new int[0];
}
}

Time complexity O(n^2)


HashMap Time complexity O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.*;

class Program {
public static int[] twoNumberSum(int[] array, int targetSum) {
HashMap<Integer, Integer> nums = new HashMap<>();
for(int num : array)
{
int ans = targetSum - num;
if(nums.containsKey(ans))
{
return new int[] {ans, num};
}
else
{
nums.put(num,num);
}
}
return new int[0];
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution
{
public int[][] merge(int[][] intervals)
{

Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
LinkedList<int[]> merged = new LinkedList<>();
for (int[] interval : intervals) {
// if the list of merged intervals is empty or if the current
// interval does not overlap with the previous, simply append it.
if (merged.isEmpty() || merged.getLast()[1] < interval[0]) {
merged.add(interval);
}
// otherwise, there is overlap, so we merge the current and previous
// intervals.
else {
merged.getLast()[1] = Math.max(merged.getLast()[1], interval[1]);
}
}
return merged.toArray(new int[merged.size()][]);
}
}


Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

  • First, initialize end is 0, it makes sure that we jump to max position later.
  • Initialize maxPosition = 0, it keep looking for max position
  • Traverse the nums array
  • if we ever found end is smaller than current index, that means nums[end] is 0, we return false
  • Updating maxPostion, find max between maxPosition and current index + current number
  • let end = maxPosition if we reach end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public boolean canJump(int[] nums) { 
int end = 0;
int maxPosition = 0;
for(int i = 0; i < nums.length - 1; i++){
//当前更新超过了边界,那么意味着出现了 0 ,直接返回 false
if(end < i){
return false;
}
//找能跳的最远的
maxPosition = Math.max(maxPosition, nums[i] + i);//现在的数加上现在的index,表示了最远可以到第几步

if( i == end){ //遇到边界,就更新边界,并且步数加一
end = maxPosition;
}
}
//最远的距离是否到答末尾
return maxPosition>=nums.length-1;
}


Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Read more »

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Read more »

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Read more »