小编Sir*_*ir 的帖子

有没有办法在 Rust 中获取 C99 数组指示符或替代方案?

我刚刚完成了关于 C 和 Rust元音计数的 CodeWars kata。示例代码简单明了。数组可以用作快速映射。在这里,我将字符映射到逻辑值(0 或 1)。

C实现:

#include <stddef.h>
#include <stdint.h>

// :) This const array design looks smart & IMO-readable. Use of C99 feature.
const uint8_t areVowels[256]= {['a']=1, ['e']=1, ['i']=1, ['o']=1,  ['u']=1};

size_t get_count(const unsigned char *s)
{
  auto size_t count= 0;
  for (;*s!='\0';s++){
    count+= areVowels[*s];
  }
  return count;
}
Run Code Online (Sandbox Code Playgroud)

Rust 实现:

// :( Here is me pain. Unreadable, python3-generated array content.
const ARE_VOWELS:[u8;256]= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

fn get_count(s: &str) -> usize {
  let mut vowels_count: usize …
Run Code Online (Sandbox Code Playgroud)

c arrays mapping initialization rust

6
推荐指数
3
解决办法
210
查看次数

Python 3 `str.__getitem__` 计算复杂度是多少?

''' Set up '''
s= open("Bilion_of_UTF-8_chars.txt",encoding="UTF-8").read()

'''
The following doesn't look like a cheap operation
because Python3 `str`-s are UTF-8 encoded (EDIT: in some implementations only).
'''
my_char= s[453_452_345]
Run Code Online (Sandbox Code Playgroud)

然而,很多人这样写循环:

for i in range(len(s)):
    do_something_with(s[i])
Run Code Online (Sandbox Code Playgroud)

使用索引操作最多n次或更多。

Python3 如何解决这两个代码片段在字符串中索引 UTF-8 字符的问题?

  • 它是否总是对第 n 个字符执行线性查找(这既简单又昂贵的解决方案)?
  • 或者它可能存储一些额外的 C 指针来执行智能索引计算?

python-3.x python-internals

3
推荐指数
1
解决办法
162
查看次数

你知道饱和函数吗?使数字适合给定范围?

在 Rust 中寻找饱和函数。
这里我称之为fit_to_range(range)

  let input:i64= something;
  let saturated:64= input.fit_to_range(7..=4000);
  assert!((7..=4000).contains(saturated));
Run Code Online (Sandbox Code Playgroud)

range rust saturation-arithmetic

0
推荐指数
1
解决办法
337
查看次数