xiyoulaoyuanjia / blog Goto Github PK
View Code? Open in Web Editor NEW记录与总结 and else?
记录与总结 and else?
一个整型数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。 例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,那么最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18, 请完成函数int MaxSum(int* a,int n)。
#include <stdio.h>
#include <string.h>
int MaxSum(int* a,int n)
{
int i=0;
int initSum=a[0];
int aSum=0;
for(i=0;i<n;i++){
aSum=aSum+a[i];
if(aSum<0 && i != n-1){
aSum=a[i+1];
i++;
}
if(aSum>initSum){
initSum=aSum;
}
}
return initSum;
}
//start 提示:本行为自动阅卷起始唯一标识,请勿删除或增加。
//完成下面main函数,自行测试下
int main()
{
//wirte your code here;
int a[]={1,-2,3,10,-4,7,2,-5};
printf("%d",sumMax(a,8));
return 0;
}
//end 提示:本行为自动阅卷结束唯一标识,请勿删除或增加。
为什么输出换行都会消耗很多时间?
我们知道对于一些语言是行缓冲的 当输出中有 "\n" 时发发生与io之间的交互 当然会消耗更多的时间了。
字符串匹配算法
kmp 算法
sunday 算法
后缀树 算法
basestirng 是什么?
assertMatch 如何使用?
注意哪里开哪里闭区间?
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual(['peanut'], noms[0:1])
self.assertEqual([], noms[2:2])
这些都是空?
self.assertEqual([], noms[4:0])
self.assertEqual([], noms[4:100])
self.assertEqual([], noms[5:0])
这些都是对的。。
self.assertEqual([0,1,2,3,4], range(5))
self.assertEqual([5,6,7,8], range(5, 9))
搞错意思了。。。。
stack = [10, 20, 30, 40]
popped_value = stack.pop(1)
from collections import deque
queue = deque([1, 2])
queue.append('last')
self.assertEqual([1,2,'last'], list(queue))
popped_value = queue.popleft()
self.assertEqual(1, popped_value)
self.assertEqual([2,'last'], list(queue))
list 的 fromkeys 用法,这里需要注意
cards = {}.fromkeys(
('red warrior', 'green elf', 'blue valkyrie', 'yellow dwarf',
'confused looking zebra'),
42)
这种用法确实不常用呀
value1 = 'one'
value2 = 2
string = "The values are {0} and {1}".format(value1, value2)
self.assertEqual("The values are one and 2", string)
def test_any_python_expression_may_be_interpolated(self):
import math # import a standard python module with math functions
decimal_places = 4
string = "The square root of 5 is {0:.{1}f}".format(math.sqrt(5), \
decimal_places)
self.assertEqual('The square root of 5 is 2.2361', string)
self.assertEqual(97, ord('a'))
string = "the,rain;in,spain"
pattern = re.compile(',|;')
words = pattern.split(string)
string = r'\n'
self.assertEqual("Guido", 'guido'.capitalize())
self.assertEqual("Guido Van Rossum", 'guido van rossum'.title())
self.assertEqual((), tuple()) # Sometimes less confusing
self.assertEqual(("S","u","r","p","r","i","s","e","!"), tuple("Surprise!"))
对于 truple 而言 顺序很重要呀
lat = (37, 14, 6, 'N')
lon = (115, 48, 40, 'W')
place = ('Area 51', lat, lon)
self.assertEqual(('Area 51',(37, 14, 6, 'N'),(115, 48, 40, 'W')), place)
私有变量会在代码生成之前被转换为长格式(变为公有)。转换机制是这样的:在变量前端插入类名,再在前端加入一个下划线字符。这就是所谓的私有变量轧压(Private name mangling)。
class Dog(object):
def name(self):
return "Fido"
def _tail(self):
# Prefixing a method with an underscore implies private scope
return "wagging"
def __password(self):
return 'password' # Genius!
# But this still is!
self.assertEqual(__, rover._Dog__password())
python 中 set 模块的使用
set(["a","b"])
set(['a', 'b'])
可以看成 去重复的 其作用也可以从下面看出来
def test_convert_the_set_into_a_list_to_sort_it(self):
self.assertEqual(['1','2','3','4','5'], sorted(set('13245')))
python 中的 与 或等运算
scotsmen = set(['MacLeod', 'Wallace', 'Willie'])
warriors = set(['MacLeod', 'Wallace', 'Leonidas'])
self.assertEqual(set(["Willie"]), scotsmen - warriors)
self.assertEqual(set(['MacLeod','Wallace','Willie','Leonidas']), scotsmen | warriors)
self.assertEqual(set(['MacLeod','Wallace']), scotsmen & warriors)
self.assertEqual(set(['Willie','Leonidas']), scotsmen ^ warriors)
集合运算 还听有意思哈
def test_we_can_compare_subsets(self):
self.assertEqual(True, set('cake') <= set('cherry cake'))
self.assertEqual(True, set('cake').issubset(set('cherry cake')))
self.assertEqual(False, set('cake') > set('pie'))
~
range(1,6) 没有6 奥,这个很容易错
stages = iter(['alpha', 'beta', 'gamma']) next 迭代器中next的用法
def test_generator_expressions_are_a_one_shot_deal(self):
dynamite = ('Boom!' for n in range(3))
attempt1 = list(dynamite)
attempt2 = list(dynamite)
self.assertEqual(['Boom!','Boom!','Boom!'], list(attempt1))
self.assertEqual([], list(attempt2))
下面的这段用法还是很诡异的?
generator.send()
继续执行一个generator函数。value这个参数变成了当前的yield表达式的值。send返回下一个yield产生的值,如果后面没有yield了,会抛出StopIteration异常。当调用send()来启动generator的时候,value这个参数必须是None,因为这个时候没有yield表达式来接受参数
def generator_with_coroutine(self):
result = yield
yield result
def test_generators_can_take_coroutines(self):
generator = self.generator_with_coroutine()
# THINK ABOUT IT:
# Why is this line necessary?
#
# Hint: Read the "Specification: Sending Values into Generators"
# section of http://www.python.org/dev/peps/pep-0342/
next(generator)
self.assertEqual(__, generator.send(1 + 2))
def test_you_can_also_access_the_value_out_using_getattr_and_dict(self):
self.assertEqual('Fido', fido.__dict__["_name"])
确实使用property函数 可以简单不少..
使用装饰器同样可以达到上述的效果..
class Dog4(object):
def __init__(self):
self._name = None
@property
def name(self):
return self._name
@name.setter
def name(self, a_name):
self._name = a_name
assertRaises 用来检测 self.Dog5 失败抛出的错误类型
def test_args_must_match_init(self):
self.assertRaises(TypeError, self.Dog5) # Evaluates self.Dog5()
built_in_classes_can_be_be_monkey_patched 这种方法也很好用
class MyInt(int):
pass
def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self):
self.MyInt.is_even = lambda self: (self % 2) == 0
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj = Class()
self.assertEqual(__, obj.method.im_self == obj)
call() 函数会在绑定实例的时候调用
# Animal
# / \
# Pig Spider Nameable
# \ | /
# Spiderpig
def test_left_hand_side_inheritance_tends_to_be_higher_priority(self):
jeff = self.Spiderpig()
self.assertEqual("pink", jeff.color())
加入上面有的各个class 方法有重合的 该使用哪个呢?
MRO = Method Resolution Order
每一个class 都有一个 MRO 属性.里面存放的各个类的顺序即为各个方法的优先级
例如上面图所示的模型中
mro = type(self.Spiderpig()).__mro__
self.assertEqual('Spiderpig', mro[0].__name__)
self.assertEqual('Pig', mro[1].__name__)
self.assertEqual('Spider', mro[2].__name__)
self.assertEqual('Animal', mro[3].__name__)
self.assertEqual('Nameable', mro[4].__name__)
self.assertEqual('object', mro[5].__name__)
def __init__(self):
self._name = None
def get_name_from_instance(self):
return self._name
def set_name_from_instance(self, name):
self._name = name
@classmethod
def get_name(cls):
return cls._name
@classmethod
def set_name(cls, name):
cls._name = name
self.assertEqual("Fido", fido.get_name_from_instance())
self.assertEqual("Rover", self.Dog3.get_name())
def test_classes_and_instances_do_not_share_instance_attributes(self):
fido = self.Dog3()
fido.set_name_from_instance("Fido")
fido.set_name("Rover")
self.assertEqual("Fido", fido.get_name_from_instance())
self.assertEqual("Rover", self.Dog3.get_name())
def test_classes_and_instances_do_share_class_attributes(self):
fido = self.Dog3()
fido.set_name("Fido")
self.assertEqual("Fido", fido.get_name())
self.assertEqual(__, self.Dog3.get_name())
class MinimalCatcher(object):
class DuffObject(object):
pass
def __init__(self):
self.no_of_getattr_calls = 0
def __getattr__(self, attr_name):
self.no_of_getattr_calls += 1
return self.DuffObject
def my_method(self):
pass
def __delattr__(self, attr_name):
self.last_deletion = attr_name
del sale.jellies
self.assertEqual("jellies", sale.last_deletion)
jinja2 convert int to string ?
Jinja2 also defines the ~ operator, which automatically converts arguments to string first, as an alternative to the + operator.
Example:
{% set p = year ~ '/' ~ month ~ '/' ~ day ~ '/' ~ post.slug %}
how can i test jinja2 template in console ?
here is an example:
import jinja2
t = jinja2.Template("{% for i in items[:3] %}{{ i }}\n{% endfor %}")
items = range(10)
print(t.render(items=items))
0
1
2
about 评论系统
这里采用 disqus 第三方评论系统。。。
关于其它的第三方 评论系统可以考虑看这篇文章
谈一下对堆与栈的理解?
说说此 宏定义的作用?
char a[]="abcdef" char *p="abcdef"
sizeof(a) sizeof(p)
4. 0x12345678 big-dian 与 little-dian 的转换
判断是否为 big-dian 的函数
int main() { short one = 1; char cp = (char)&one; if ( *cp == 0 ) return(1); else return(0); }
这个答案应该为 0x78563412
主要分为四章
- 游戏之乐--游戏中碰到的题目
- 数字之魅--- 数字中的技巧
- 结构之法---字符串及链表的探索
- 数学之趣-- 数学游戏中的乐趣
注意原文答案有一些错误
_第6题目:^ 表示异或_
_第7题:二叉树是一种树形结构,每个节点至多有两颗子树,下列一定是二叉树的是()_
A. 红黑树
B. B树
C. AVL树
D. B+树
红黑树是一种自平衡的二叉树 它是在1972年由鲁道夫.贝尔 发明的..他称它为 "对称二叉B树" (由这里我们可以看出B树不是对称的也不是二叉的...) 它可以在O(log n)时间内插入,查找,和删除..这里n是树中元素的数目 参考 wiki
B树 概括起来说是一个节点可以有多余2个子节点的二叉排序树 wiki
B+树 wiki上面解释的不清楚.有时间在看呀..
AVL树 AVL 数是最先发明的自平衡二叉树 在AVL数中任何相邻的两个子树的高度相差不超过1.
通过上面简短的分析可知..上面的答案显而易见..AC
_第8题: a[m][n] == ((a+m)+n)
python 中如何修改 元组..
今天找到了这个 线索
python 如何写一个单例模式.. 哪里会应用到单例模式..
装饰器 确实是一个好办法..
linux 中如何查看cpu阻塞到哪个程序中了?
百兆网的速度有多少?
原文
感谢原作者..
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.