Rust vs Go:常用语法对比(八)

news2024/10/7 9:49:22
alt

题目来自 Golang vs. Rust: Which Programming Language To Choose in 2023?[1]


141. Iterate in sequence over two lists

Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element.

依次迭代两个列表 依次迭代列表项1和项2的元素。每次迭代打印元素。

package main

import (
 "fmt"
)

func main() {
 items1 := []string{"a""b""c"}
 items2 := []string{"A""B""C"}

 for _, v := range items1 {
  fmt.Println(v)
 }
 for _, v := range items2 {
  fmt.Println(v)
 }
}

a
b
c
A
B
C

fn main() {
    let item1 = vec!["1""2""3"];
    let item2 = vec!["a""b""c"];
    for i in item1.iter().chain(item2.iter()) {
        print!("{} ", i);
    }
}

1 2 3 a b c


142. Hexadecimal digits of an integer

Assign to string s the hexadecimal representation (base 16) of integer x.
E.g. 999 -> "3e7"

将整数x的十六进制表示(16进制)赋给字符串s。

package main

import "fmt"
import "strconv"

func main() {
 x := int64(999)
 s := strconv.FormatInt(x, 16)

 fmt.Println(s)
}

3e7

or

package main

import (
 "fmt"
 "math/big"
)

func main() {
 x := big.NewInt(999)
 s := fmt.Sprintf("%x", x)

 fmt.Println(s)
}

3e7


fn main() {
    let x = 999;

    let s = format!("{:X}", x);
    println!("{}", s);

    let s = format!("{:x}", x);
    println!("{}", s);
}

{:X} produces uppercase hex. {:x} produces lowercase hex.

3E7
3e7

143. Iterate alternatively over two lists

Iterate alternatively over the elements of the list items1 and items2. For each iteration, print the element.
Explain what happens if items1 and items2 have different size.

交替迭代两个列表

package main

import (
 "fmt"
)

func main() {
 items1 := []string{"a""b"}
 items2 := []string{"A""B""C"}

 for i := 0; i < len(items1) || i < len(items2); i++ {
  if i < len(items1) {
   fmt.Println(items1[i])
  }
  if i < len(items2) {
   fmt.Println(items2[i])
  }
 }
}

a
A
b
B
C

extern crate itertools;
use itertools::izip;

fn main() {
    let items1 = [51525];
    let items2 = [102030];

    for pair in izip!(&items1, &items2) {
        println!("{}", pair.0);
        println!("{}", pair.1);
    }
}

5
10
15
20
25
30

144. Check if file exists

Set boolean b to true if file at path fp exists on filesystem; false otherwise.
Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.

检查文件是否存在

package main

import (
 "fmt"
 "io/ioutil"
 "os"
)

func main() {
 fp := "foo.txt"
 _, err := os.Stat(fp)
 b := !os.IsNotExist(err)
 fmt.Println(fp, "exists:", b)

 fp = "bar.txt"
 _, err = os.Stat(fp)
 b = !os.IsNotExist(err)
 fmt.Println(fp, "exists:", b)
}

func init() {
 ioutil.WriteFile("foo.txt", []byte(`abc`), 0644)
}

There's no specific existence check func in standard library, so we have to inspect an error return value.

foo.txt exists: true
bar.txt exists: false

fn main() {
    let fp = "/etc/hosts";
    let b = std::path::Path::new(fp).exists();
    println!("{}: {}", fp, b);

    let fp = "/etc/kittens";
    let b = std::path::Path::new(fp).exists();
    println!("{}: {}", fp, b);
}

/etc/hosts: true
/etc/kittens: false

145. Print log line with datetime

Print message msg, prepended by current date and time.
Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.

打印带时间的日志

package main

import "log"

func main() {
 msg := "Hello, playground"
 log.Println(msg)

 // The date is fixed in the past in the Playground, never mind.
}

// See http://www.programming-idioms.org/idiom/145/print-log-line-with-date/1815/go

2009/11/10 23:00:00 Hello, playground


fn main() {
    let msg = "Hello";
    eprintln!("[{}] {}", humantime::format_rfc3339_seconds(std::time::SystemTime::now()), msg);
}

[2021-07-17T07:14:03Z] Hello


146. Convert string to floating point number

Extract floating point value f from its string representation s

字符串转换为浮点型

package main

import (
 "fmt"
 "strconv"
)

func main() {
 s := "3.1415926535"

 f, err := strconv.ParseFloat(s, 64)
 fmt.Printf("%T, %v, err=%v\n", f, f, err)
}

//
// http://www.programming-idioms.org/idiom/146/convert-string-to-floating-point-number/1819/go
//

float64, 3.1415926535, err=<nil>


fn main() {
    let s = "3.14159265359";
    let f = s.parse::<f32>().unwrap();
    
    println!("{}² = {}" , f, f * f);
}

3.1415927² = 9.869605

or

fn main() {
    let s = "3.14159265359";
    let f: f32 = s.parse().unwrap();

    println!("{}² = {}", f, f * f);
}

3.1415927² = 9.869605


147. Remove all non-ASCII characters

Create string t from string s, keeping only ASCII characters

移除所有的非ASCII字符

package main

import (
 "fmt"
 "regexp"
)

func main() {
 s := "dæmi : пример : příklad : thí dụ"

 re := regexp.MustCompile("[[:^ascii:]]")
 t := re.ReplaceAllLiteralString(s, "")

 fmt.Println(t)
}

dmi : : pklad : th d

or

package main

import (
 "fmt"
 "strings"
 "unicode"
)

func main() {
 s := "5#∑∂ƒ∞645eyfu"
 t := strings.Map(func(r rune) rune {
  if r > unicode.MaxASCII {
   return -1
  }
  return r
 }, s)
 fmt.Println(t)
}

5#645eyfu


fn main() {
    println!("{}""do👍ot".replace(|c: char| !c.is_ascii(), ""))
}

doot

or

fn main() {
    println!("{}""do👍ot".replace(|c: char| !c.is_ascii(), ""))
}

doot


148. Read list of integers from stdin

Read a list of integer numbers from the standard input, until EOF.

从stdin(标准输入)中读取整数列表

package main

import (
 "bufio"
 "fmt"
 "log"
 "strconv"
 "strings"
)

func main() {
 var ints []int
 s := bufio.NewScanner(osStdin)
 s.Split(bufio.ScanWords)
 for s.Scan() {
  i, err := strconv.Atoi(s.Text())
  if err == nil {
   ints = append(ints, i)
  }
 }
 if err := s.Err(); err != nil {
  log.Fatal(err)
 }
 fmt.Println(ints)
}

// osStdin simulates os.Stdin
var osStdin = strings.NewReader(`
11
22
33  `
)

[11 22 33]


use std::{
    io::{self, Read},
    str::FromStr,
};

// dummy io::stdin
fn io_stdin() -> impl Read {
    "123
456
789"

    .as_bytes()
}

fn main() -> io::Result<()> {
    let mut string = String::new();
    io_stdin().read_to_string(&mut string)?;
    let result = string
        .lines()
        .map(i32::from_str)
        .collect::<Result<Vec<_>, _>>();
    println!("{:#?}", result);
    Ok(())
}
Ok(
    [
        123,
        456,
        789,
    ],
)

150. Remove trailing slash

Remove last character from string p, if this character is a slash /.

去除末尾的 /

package main

import (
 "fmt"
 "strings"
)

func main() {
 p := "/usr/bin/"

 p = strings.TrimSuffix(p, "/")

 fmt.Println(p)
}

/usr/bin


fn main() {
    let mut p = String::from("Dddd/");
    if p.ends_with('/') {
        p.pop();
    }
    println!("{}", p);
}

Dddd


151. Remove string trailing path separator

Remove last character from string p, if this character is the file path separator of current platform.
Note that this also transforms unix root path "/" into the empty string!

删除字符串尾部路径分隔符

package main

import (
 "fmt"
 "io/ioutil"
 "os"
 "strings"
)

func main() {
 p := somePath()
 fmt.Println(p)

 sep := fmt.Sprintf("%c", os.PathSeparator)
 p = strings.TrimSuffix(p, sep)

 fmt.Println(p)
}

func somePath() string {
 dir, err := ioutil.TempDir("""")
 if err != nil {
  panic(err)
 }
 p := fmt.Sprintf("%s%c%s%c", dir, os.PathSeparator, "foobar", os.PathSeparator)
 return p
}

/tmp/067319278/foobar/
/tmp/067319278/foobar

or

package main

import (
 "fmt"
 "io/ioutil"
 "os"
 "path/filepath"
 "strings"
)

func main() {
 p := somePath()
 fmt.Println(p)

 sep := fmt.Sprintf("%c", filepath.Separator)
 p = strings.TrimSuffix(p, sep)

 fmt.Println(p)
}

func somePath() string {
 dir, err := ioutil.TempDir("""")
 if err != nil {
  panic(err)
 }
 p := fmt.Sprintf("%s%c%s%c", dir, os.PathSeparator, "foobar", os.PathSeparator)
 return p
}
/tmp/065654753/foobar/
/tmp/065654753/foobar

fn main() {
    {
        let p = "/tmp/";

        let p = if ::std::path::is_separator(p.chars().last().unwrap()) {
            &p[0..p.len() - 1]
        } else {
            p
        };

        println!("{}", p);
    }
    
    {
        let p = "/tmp";

        let p = if ::std::path::is_separator(p.chars().last().unwrap()) {
            &p[0..p.len() - 1]
        } else {
            p
        };

        println!("{}", p);
    }
}
/tmp
/tmp

or

fn main() {
    {
        let mut p = "/tmp/";

        p = p.strip_suffix(std::path::is_separator).unwrap_or(p);

        println!("{}", p);
    }
    
    {
        let mut p = "/tmp";

        p = p.strip_suffix(std::path::is_separator).unwrap_or(p);

        println!("{}", p);
    }
}
/tmp
/tmp

152. Turn a character into a string

Create string s containing only the character c.

将字符转换成字符串

package main

import (
 "fmt"
 "os"
)

func main() {
 var c rune = os.PathSeparator
 fmt.Printf("%c \n", c)

 s := fmt.Sprintf("%c", c)
 fmt.Printf("%#v \n", s)
}


"/" 

fn main() {
    let c = 'a';
    
    let s = c.to_string();
    
    println!("{}", s);
}

a


153. Concatenate string with integer

Create string t as the concatenation of string s and integer i.

连接字符串和整数

package main

import (
 "fmt"
)

func main() {
 s := "Hello"
 i := 123

 t := fmt.Sprintf("%s%d", s, i)

 fmt.Println(t)
}

Hello123


fn main() {
    let s = "Foo";
    let i = 1;
    let t = format!("{}{}", s, i);
    
    println!("{}" , t);
}

Foo1


154. Halfway between two hex color codes

Find color c, the average between colors c1, c2.
c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # . Assume linear computations, ignore gamma corrections.

求两个十六进制颜色代码的中间值

package main

import (
 "fmt"
 "strconv"
 "strings"
)

// For concision, halfway assume valid inputs.
// Caller must have explicitly checked that c1, c2 are well-formed color codes.
func halfway(c1, c2 string) string {
 r1, _ := strconv.ParseInt(c1[1:3], 160)
 r2, _ := strconv.ParseInt(c2[1:3], 160)
 r := (r1 + r2) / 2

 g1, _ := strconv.ParseInt(c1[3:5], 160)
 g2, _ := strconv.ParseInt(c2[3:5], 160)
 g := (g1 + g2) / 2

 b1, _ := strconv.ParseInt(c1[5:7], 160)
 b2, _ := strconv.ParseInt(c2[5:7], 160)
 b := (b1 + b2) / 2

 c := fmt.Sprintf("#%02X%02X%02X", r, g, b)
 return c
}

func main() {
 c1 := "#15293E"
 c2 := "#012549"

 if err := checkFormat(c1); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c1, err))
 }
 if err := checkFormat(c2); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c2, err))
 }

 c := halfway(c1, c2)
 fmt.Println("The average of", c1, "and", c2, "is", c)
}

func checkFormat(color string) error {
 if len(color) != 7 {
  return fmt.Errorf("Hex colors have exactly 7 chars")
 }
 if color[0] != '#' {
  return fmt.Errorf("Hex colors start with #")
 }
 isNotDigit := func(c rune) bool { return (c < '0' || c > '9') && (c < 'a' || c > 'f') }
 if strings.IndexFunc(strings.ToLower(color[1:]), isNotDigit) != -1 {
  return fmt.Errorf("Forbidden char")
 }
 return nil
}

The average of #15293E and #012549 is #0B2743

package main

import (
 "fmt"
 "strconv"
 "strings"
)

// For concision, halfway assume valid inputs.
// Caller must have explicitly checked that c1, c2 are well-formed color codes.
func halfway(c1, c2 string) string {
 var buf [7]byte
 buf[0] = '#'
 for i := 0; i < 3; i++ {
  sub1 := c1[1+2*i : 3+2*i]
  sub2 := c2[1+2*i : 3+2*i]
  v1, _ := strconv.ParseInt(sub1, 160)
  v2, _ := strconv.ParseInt(sub2, 160)
  v := (v1 + v2) / 2
  sub := fmt.Sprintf("%02X", v)
  copy(buf[1+2*i:3+2*i], sub)
 }
 c := string(buf[:])

 return c
}

func main() {
 c1 := "#15293E"
 c2 := "#012549"

 if err := checkFormat(c1); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c1, err))
 }
 if err := checkFormat(c2); err != nil {
  panic(fmt.Errorf("Wrong input %q: %v", c2, err))
 }

 c := halfway(c1, c2)
 fmt.Println("The average of", c1, "and", c2, "is", c)
}

func checkFormat(color string) error {
 if len(color) != 7 {
  return fmt.Errorf("Hex colors have exactly 7 chars")
 }
 if color[0] != '#' {
  return fmt.Errorf("Hex colors start with #")
 }
 isNotDigit := func(c rune) bool { return (c < '0' || c > '9') && (c < 'a' || c > 'f') }
 if strings.IndexFunc(strings.ToLower(color[1:]), isNotDigit) != -1 {
  return fmt.Errorf("Forbidden char")
 }
 return nil
}

The average of #15293E and #012549 is #0B2743


use std::str::FromStr;
use std::fmt;

#[derive(Debug)]
struct Colour {
    r: u8,
    g: u8,
    b: u8
}

#[derive(Debug)]
enum ColourError {
    MissingHash,
    InvalidRed,
    InvalidGreen,
    InvalidBlue
}

impl fmt::Display for Colour {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "#{:02x}{:02x}{:02x}"self.r, self.g, self.b)
    }
}

impl FromStr for Colour {
    type Err = ColourError;
    
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !s.starts_with('#') {
            Err(ColourError::MissingHash)
        } else {
            Ok(Colour {
                r: u8::from_str_radix(&s[1..3], 16).map_err(|_| ColourError::InvalidRed)?,
                g: u8::from_str_radix(&s[3..5], 16).map_err(|_| ColourError::InvalidGreen)?,
                b: u8::from_str_radix(&s[5..7], 16).map_err(|_| ColourError::InvalidBlue)?
            })
        }
    }
}

fn mid_colour(c1: &str, c2: &str) -> Result<String, ColourError> {
    let c1 = c1.parse::<Colour>()?;
    let c2 = c2.parse::<Colour>()?;
    let c = Colour {
        r: (((c1.r as u16) + (c2.r as u16))/2as u8,
        g: (((c1.g as u16) + (c2.g as u16))/2as u8,
        b: (((c1.b as u16) + (c2.b as u16))/2as u8
    };
    Ok(format!("{}", c))
}

fn main() {
    println!("{}", mid_colour("#15293E""#012549").unwrap())
}

#0b2743


155. Delete file

Delete from filesystem the file having path filepath.

删除文件

package main

import (
 "fmt"
 "io/ioutil"
 "os"
)

func main() {
 for _, filepath := range []string{
  "/tmp/foo.txt",
  "/tmp/bar.txt",
  "/tmp/foo.txt",
 } {
  err := os.Remove(filepath)
  if err == nil {
   fmt.Println("Removed", filepath)
  } else {
   fmt.Fprintln(os.Stderr, err)
  }
 }
}

func init() {
 err := ioutil.WriteFile("/tmp/foo.txt", []byte(`abc`), 0644)
 if err != nil {
  panic(err)
 }
}
Removed /tmp/foo.txt
remove /tmp/bar.txt: no such file or directory
remove /tmp/foo.txt: no such file or directory

use std::fs;

fn main() {
    let filepath = "/tmp/abc";

    println!("Creating {}", filepath);
    let _file = fs::File::create(filepath);

    let b = std::path::Path::new(filepath).exists();
    println!("{} exists: {}", filepath, b);

    println!("Deleting {}", filepath);
    let r = fs::remove_file(filepath);
    println!("{:?}", r);

    let b = std::path::Path::new(filepath).exists();
    println!("{} exists: {}", filepath, b);
}
Creating /tmp/abc
/tmp/abc exists: true
Deleting /tmp/abc
Ok(())
/tmp/abc exists: false

156. Format integer with zero-padding

Assign to string s the value of integer i in 3 decimal digits. Pad with zeros if i < 100. Keep all digits if i ≥ 1000.

用零填充格式化整数

package main

import (
 "fmt"
)

func main() {
 for _, i := range []int{
  0,
  8,
  64,
  256,
  2048,
 } {
  s := fmt.Sprintf("%03d", i)
  fmt.Println(s)
 }
}

000
008
064
256
2048

fn main() {
    let i = 1;
    let s = format!("{:03}", i);
    
    println!("{}", s);
    
    
    let i = 1000;
    let s = format!("{:03}", i);
    
    println!("{}", s);
}
001
1000

157. Declare constant string

Initialize a constant planet with string value "Earth".

声明常量字符串

package main

import (
 "fmt"
)

const planet = "Earth"

func main() {
 fmt.Println("We live on planet", planet)
}

We live on planet Earth


fn main() {
    const PLANET: &str = "Earth";
    
    println!("{}", PLANET);
}

Earth


158. Random sublist

Create a new list y from randomly picking exactly k elements from list x.

It is assumed that x has at least k elements. Each element must have same probability to be picked. Each element from x must be picked at most once. Explain if the original ordering is preserved or not.

随机子列表

package main

import (
 "fmt"
 "math/rand"
)

func main() {
 type T string

 x := []T{"Alice""Bob""Carol""Dan""Eve""Frank""Grace""Heidi"}
 k := 4

 y := make([]T, k)
 perm := rand.Perm(len(x))
 for i, v := range perm[:k] {
  y[i] = x[v]
 }

 fmt.Printf("%q", y)
}

["Frank" "Eve" "Carol" "Grace"]


use rand::prelude::*;
let mut rng = &mut rand::thread_rng();
let y = x.choose_multiple(&mut rng, k).cloned().collect::<Vec<_>>();

159. Trie

Define a Trie data structure, where entries have an associated value. (Not all nodes are entries)

前缀树/字典树

package main

import (
 "fmt"
 "unicode/utf8"
)

type Trie struct {
 c        rune
 children map[rune]*Trie
 isLeaf   bool
 value    V
}

type V int

func main() {
 t := NewTrie(0)
 for s, v := range map[string]V{
  "to":  7,
  "tea"3,
  "ted"4,
  "ten"12,
  "A":   15,
  "i":   11,
  "in":  5,
  "inn"9,
 } {
  t.insert(s, v)
 }
 fmt.Println(t.startsWith("te"""))
}

func NewTrie(c rune) *Trie {
 t := new(Trie)
 t.c = c
 t.children = map[rune]*Trie{}
 return t
}

func (t *Trie) insert(s string, value V) {
 if s == "" {
  t.isLeaf = true
  t.value = value
  return
 }
 c, tail := cut(s)
 child, exists := t.children[c]
 if !exists {
  child = NewTrie(c)
  t.children[c] = child
 }
 child.insert(tail, value)
}

func (t *Trie) startsWith(p string, accu string) []string {
 if t == nil {
  return nil
 }
 if p == "" {
  var result []string
  if t.isLeaf {
   result = append(result, accu)
  }
  for c, child := range t.children {
   rec := child.startsWith("", accu+string(c))
   result = append(result, rec...)
  }
  return result
 }
 c, tail := cut(p)
 return t.children[c].startsWith(tail, accu+string(c))
}

func cut(s string) (head rune, tail string) {
 r, size := utf8.DecodeRuneInString(s)
 return r, s[size:]
}

[ten tea ted]


struct Trie {
    val: String,
    nodes: Vec<Trie>
}

160. Detect if 32-bit or 64-bit architecture

Execute f32() if platform is 32-bit, or f64() if platform is 64-bit.
This can be either a compile-time condition (depending on target) or a runtime detection.

检测是32位还是64位架构

package main

import (
 "fmt"
 "strconv"
)

func main() {
 if strconv.IntSize == 32 {
  f32()
 }
 if strconv.IntSize == 64 {
  f64()
 }
}

func f32() {
 fmt.Println("I am 32-bit")
}

func f64() {
 fmt.Println("I am 64-bit")
}

I am 64-bit


fn main() {
    match std::mem::size_of::<&char>() {
        4 => f32(),
        8 => f64(),
        _ => {}
    }
}

fn f32() {
    println!("I am 32-bit");
}

fn f64() {
    println!("I am 64-bit");
}

I am 64-bit


参考资料

[1]

Golang vs. Rust: Which Programming Language To Choose in 2023?: https://www.trio.dev/blog/golang-vs-rust

本文由 mdnice 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/795651.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【linux基础(一)】Linux基本指令(上)

&#x1f493;博主CSDN主页:杭电码农-NEO&#x1f493;   ⏩专栏分类:Linux从入门到开通⏪   &#x1f69a;代码仓库:NEO的学习日记&#x1f69a;   &#x1f339;关注我&#x1faf5;带你学更多操作系统知识   &#x1f51d;&#x1f51d; 这里写目录标题 1. 前言1. 创…

[vulnhub]DC2

文章目录 [vulnhub]DC2信息收集flag1flag2cewlwpscan flag3什么是rbash&#xff1f; flag4flag5git提权 总结 [vulnhub]DC2 信息收集 扫ip&#xff0c;有两种方式&#xff1a;arp、nmap nmap -sP 192.168.56.0/24 -T4arp-scan -l192.168.56.137 扫端口&#xff1a; nmap -…

1312. 让字符串成为回文串的最少插入次数;971. 翻转二叉树以匹配先序遍历

1312. 让字符串成为回文串的最少插入次数 核心思想&#xff1a;最后的回文串有两种情况&#xff0c;一种是奇数回文串&#xff0c;一种是偶数回文串&#xff0c;奇数回文串的中心一定是原来就有的&#xff0c;偶数回文串的中心也是原来就有的。假设除去中心的部分为q,p,最后要…

Debian12中为python3配置虚拟环境及在Pycharm中使用虚拟环境

在Debian 12中&#xff0c;python默认为python 3.11。 基于应用&#xff0c;现需设置虚拟环境。 1.安装venv模块 从python3.3开始&#xff0c;配置python虚拟环境&#xff0c;可用venv模块&#xff0c;更加方便了。 执行命令&#xff1a; #apt install python3.11-venv 2.…

原型模式——对象的克隆

1、简介 1.1、概述 可以通过一个原型对象克隆出多个一模一样的对象&#xff0c;该模式被称为原型模式。 在使用原型模式时&#xff0c;需要首先创建一个原型对象&#xff0c;再通过复制这个原型对象来创建更多同类型的对象。 1.2、定义 原型模式&#xff08;Prototype Patt…

ICASSP 2023说话人识别方向论文合集(一)

ICASSP (International Conference on Acoustics, Speech and Signal Processing) 即国际声学、语音与信号处理会议&#xff0c;是IEEE主办的全世界最大、最全面的信号处理及其应用方面的顶级会议&#xff0c;在国际上享有盛誉并具有广泛的学术影响力。 今年入选 ICASSP 2023 …

【LeetCode每日一题】——946.验证栈序列

文章目录 一【题目类别】二【题目难度】三【题目编号】四【题目描述】五【题目示例】六【题目提示】七【解题思路】八【时间频度】九【代码实现】十【提交结果】 一【题目类别】 栈 二【题目难度】 中等 三【题目编号】 946.验证栈序列 四【题目描述】 给定 pushed 和 p…

【*1900 图论】CF1328 E

Problem - E - Codeforces 题意&#xff1a; 思路&#xff1a; 注意到题目的性质&#xff1a;满足条件的路径个数是极少的&#xff0c;因为每个点离路径的距离<1 先考虑一条链&#xff0c;那么直接就选最深那个点作为端点即可 为什么&#xff0c;因为我们需要遍历所有点…

ChatGPT伦理挑战:人工智能的权利与责任

&#x1f337;&#x1f341; 博主 libin9iOak带您 Go to New World.✨&#x1f341; &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33…

选读SQL经典实例笔记13_case与聚合

1. 识别非小计行 1.1. 结果集 1.2. DB2 1.3. Oracle 1.4. 超级聚合&#xff08;supera ggregate&#xff09;值 1.4.1. sql select deptno, job, sum(sal) sal,grouping(deptno) deptno_subtotals,grouping(job) job_subtotalsfrom empgroup by cube(deptno,job) 1.5. SQ…

十三、数据结构——二叉树的遍历(先序、中序和后序)详细思路和代码

二叉树遍历 在数据结构中&#xff0c;二叉树是一种常用且重要的数据结构。二叉树的遍历是指按照一定顺序访问二叉树的所有节点&#xff0c;常见的遍历方式有前序遍历、中序遍历和后序遍历。本文将详细介绍这三种遍历算法&#xff0c;并介绍最优二叉树。 二叉树的基本定义 首…

网络摄像机·监控摄像机用镜头驱动芯片(内置光圈控制)MS41908M

产品简述 MS41908M 是一款用于网络摄像机和监控摄像机的镜头 驱动芯片。 芯片内置光圈控制功能&#xff1b;通过电压驱动方式以及扭矩纹 波修正技术&#xff0c;实现了超低噪声微步驱动。 主要特点  电压驱动方式&#xff0c;256 微步驱动电路&#xff08;两通道&…

同一份数据,Redis为什么要存两次

Redis作为目前最主流的高性能缓存&#xff0c;里面有很多精妙的设计&#xff0c;其中有一种数据类型&#xff0c;当在存储的时候会同时采用两种数据结构来进行分别存储&#xff0c;那么 Redis 为什么要这么做呢&#xff1f;这么做会造成同一份数据占用两倍空间吗&#xff1f; …

Python中的元类MetaClass

引言 python中的元类MetaClass&#xff1a;本质也是一个类&#xff0c;但和普通类的用法不同&#xff0c;它可以对类内部的定义&#xff08;包括类属性和类方法&#xff09;进行动态的修改。 换句话说&#xff0c;使用元类的主要目的是为了实现在创建类时&#xff0c;能够动态…

数据库架构设计

数据库架构设计 数据库架构分类 介绍 介绍常见的 四种 数据库架构设计模型&#xff1a; 单库架构、分组架构、分片架构和分组分片架构 &#xff0c;以及每种架构的 使用场景、存在的问题和对应的解决方案 。 一、数据模型 我们以 “ 用户中心 ” 数据库作为 数据模型 &…

python核心-面向对象-方法相关-补充

class Person:__age 18def __run(self):print("pao")def _Person__run(self):print("xxx")p Person # p._Person__run()print(Person.__dict__) 内置特殊方法 信息格式化操作 # class Person: # def __init__(self, n, a): # self.name n …

深入理解Linux 内核追踪机制

Linux 存在众多 tracing tools&#xff0c;比如 ftrace、perf&#xff0c;他们可用于内核的调试、提高内核的可观测性。众多的工具也意味着繁杂的概念&#xff0c;诸如 tracepoint、trace events、kprobe、eBPF 等&#xff0c;甚至让人搞不清楚他们到底是干什么的。本文尝试理清…

硬件——PCI-E接口

简介 PCI PCI&#xff08;Peripheral Component Interconnect&#xff09;&#xff0c;外设组件互联标准。 并行方式通信 PCI接口通常是白色的。 PCI接口分为32Bit和64Bit&#xff0c;主流的是32Bit&#xff0c;最大传输速度133MB/s。 适用于网卡、声卡等&#xff1b;现在…

flask中的session介绍

flask中的session介绍 在Flask中&#xff0c;session是一个用于存储特定用户会话数据的字典对象。它在不同请求之间保存数据。它通过在客户端设置一个签名的cookie&#xff0c;将所有的会话数据存储在客户端。以下是如何在Flask应用中使用session的基本步骤&#xff1a; 首先…

Midjourney8种风格极其使用场景(1)

目录 ​编辑 引言 等距动画 场景 分析性绘图 场景 着色书 场景 信息图画 场景 双重曝光 场景 图示性绘画 场景 二维插图 场景 图解式画像 场景 总结&#xff1a; 八种风格箴言&#xff1a; 引言 我相信大家都或多或少玩过Midjourney&#xff0c;但是要形…