2017年阿里校招一道题

菜鸟仓库是一个很大很神奇的地方,各种琳琅满目的商品整整齐齐地摆放在一排排货架上,通常一种品类(sku)的商品会放置在货架的某一个格子中,格子设有统一的编号,方便工人们拣选。 有一天沐哲去菜鸟仓库参观,无意中发现第1个货架格子编码为1,第2-3个分别为1,2,第4-6个格子分别是1,2,3,第7-10个格子编号分别是1,2,3,4,每个格子编号都是0-9中的一个整数,且相邻格子的编号连在一起有如下规律 1|12|123|1234|...|123456789101112131415|...|123456789101112131415……n 这个仓库存放的商品品类非常丰富,共有1千万多个货架格子。沐哲很好奇,他想快速知道第k个格子编号是多少?

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 import math
 5 """
 6 题意就是找规律
 7 输入:1   2   3   4   5   6   7   8   9   10  11 ...  
 8 输出:1   1   2   1   2   3   1   2   3   4   1  ...
 9 
10 输入:51  52  53  54  55  56  57  58  ... 
11 输出:6   7   8   9   1   0   1   2   ... 
12 
13 输入:92  93  94  95  96  97  98  99  100
14 输出:8   9   1   0   1   1   1   2   1
15 
16 """
17 
18 
19 def _process(y):
20     if y < 1 or y is None or not isinstance(y, int):
21         return None
22     delta = math.sqrt(0.25 + 2*y) / 2
23     bottom = int(2 * (-0.25 + delta))
24     r = bottom*(bottom+1)/2
25 
26     if r == y:
27         c = bottom
28     else:
29         c = y - r
30 
31     if y - r - c == 0:
32         round_num = bottom + 1
33     else:
34         round_num = bottom
35     return c, round_num
36 
37 
38 def process(y):
39     # c 是真实值, round_num 是轮次
40     c, round_num = _process(y)
41     _y = y
42     _rich = 0
43     for x in range(10, round_num+1):
44         for z in range(10, x+1):
45             if x == round_num and z > c:
46                 break
47             true_pos = calc(z, x)
48             l = len(str(z)) - 1
49             if _y > true_pos + l:
50                 _y -= l
51             elif _y > true_pos:
52                 _rich = _y - true_pos
53                 _y -= l
54                 break
55             elif _y <= true_pos:
56                 break
57     return int(str(_pro(_y)[0])[_rich])
58 
59 
60 def calc(index, round_num):
61     return round_num*(round_num-1)/2 + index
62 
63 for _ in range(50, 100):
64     print process(_)
原文地址:https://www.cnblogs.com/Fadinglemon/p/7435061.html