Python VS Java

作者 QIFAN 日期 2016-10-21
Python VS Java

CMU 11601 Coding BootCamp


General 比较

JavaPython
编译运行无需编译
静态输入动态输入
区块间用{}区分由缩进区分
规矩多,编写规范比较自由,不用声明变量类型,多个public类可以写在同一文件
List和哈希表需要importList和哈希表是原生类型

相似处

  • 多平台支持
  • 面向对象
  • 编译成机器码在虚拟机中运行
  • 自动垃圾回收系统

变量

JavaPython
boolean x = true;x = True;
int x = 1;x = 1
float x = 1.0;x = 1.0
String x = new String(“s”);x = ‘s’
List x;x = [1, ‘2’, [3.5, 4], 5]
HashTable x;x = {}

区块

  • Java

    // using braces:
    if (x < y) { ... } else
    { ... }
    if (y.equals(z))
    {
    conditional1();
    conditional2();
    }
    common();
  • Python

    # using indentation:
    if x < y:
    ...
    else:
    ...
    if y == z:
    conditional1()
    conditional2()
    common()

JavaPython
import library;
import library.;
import library
import library as alias
from library import obj, obj
from library import

方法声明

  • Java

    rettype funcname
    ( argtype argname, ... )
    {
    rettype result = X;
    // body
    return result;
    }
  • Python

    def funcname( argname, ... ):
    result = X
    //body
    return result

类声明

  • Java

    class cl extends X {
    type data = defvalue;
    type func(type N) {
    return N * data;
    }
    static int fact(int N) {
    if (N < 2) return 1;
    return N * fact(N-1);
    }
    }
  • Python

    class cl(X):
    data = defvalue
    def func(self, N):
    return N * self.data
    @staticmethod
    def fact(N):
    if N < 2:
    return 1
    return N * cl.fact(N-1)

异常处理

  • Java

    class E extends Exception;
    void foo() throws E {
    throw new E();
    }
    void bar() {
    try {
    foo();
    } catch (E err) {
    System.out.print(“Err”);
    } finally {
    System.out.print(“Always”);
    }
    return;
    }
  • Python

    class MyErr(RuntimeError):
    pass
    def foo():
    raise MyErr(“msg”)
    def bar():
    try:
    foo()
    except MyErr as err:
    print “Err: ”, err
    else:
    print “Success”
    finally:
    print “Always”

String

# can use single or double quotes
s1='foo'
s2='bar'
# access individual characters and subsequences as for lists
print s2[1] ==> 'a'
print s1[1:3] ==> 'oo'
# strings are immutable, so you need to create a new string:
s2[1] = 'u' ==> ERROR
s3 = s2[:1]+'u'+s2[2:] ==> 'bur'
# concatenation operators
s4 = s1 + s2 ==> 'foobar'
s5 = 3 * s1 ==> 'foofoofoo'
s='abccde'; sub='cd'
# string length
print len(s) ==> 6
# find substring index
print s.index(sub) ==> 3
# count occurrences of a substring
print s.count('c') ==> 2
# substring test
print sub in s ==> True

List, Tuple, HashTable

List
# instantiate an empty list
l1 = []
# instantiate list with heterogenous values
l2 = [1,'foo',3.5, 2]
# instatiate list of 100 references to an item
l3 = 100*['item']
# list comprehension
l4 = [x * 2 for x in range(10)]
# print sub-list, from index i to (but not including) index j
print l2[1:2] ==> ['foo']
print l2[1:3] ==> ['foo', 3.5]
# negative indices count from end of list
print l2[-2:] ==> [3.5, 2]
# stride
print l2[::2] ==> [1, 3.5]
# reverse
print l2[::-1] ==> [2, 3.5, 'foo', 1]
# lambda
print filter(lambda x: x == 'foo', l2) ==> ['foo']
Tuple
# tuples are immutable lists
# instantiate a tuple
t1 = (1, 2, 3)
# optionally leave out the parentheses
t2 = 1, 2, 3
# commonly used to return multiple values:
x = 0.125
num, denom = x.as_integer_ratio()
print num ==> 1
print denom ==> 8
HashTable
# instantiate an empty hash table
ht = {}
# insert values
ht[5] = [1,2,3,4,5]
ht['foo'] = 'Yes'
print ht ==> {'foo': 'Yes', 5: [1, 2, 3, 4, 5]}
# retrieve a value
print ht[5] ==> [1, 2, 3, 4, 5]
print ht['foo'] ==> Yes
# remove lookup key
del ht['foo']
# attempting to access removed key generates an error:
print ht['foo'] ==> KeyError: 'foo'
# each pair
print ht.item() ==> [(5, [1,2,3,4,5]), ('foo','Yes')]

运算符

  • a // b 整除
  • a ** b $a^b$
  • a and b
  • a or b
  • not a
  • a is b a,b值相等
  • a is not b a,b是不同对象
  • a == b a, b相等
  • a in b a是b的成员

位运算

Bit Manipulation
// start with '0b' to represent number in binary format
print 0b1 ==> 1
print 0b10 ==> 2
// convert int to binary format
print bin(2) ==> 0b10
print int("110", 2) ==> 6
// flip bits
print bin(0b1010 ^ 0b1111) ==> 0b101

Input/Output

I/O
f = open('input', 'r')
print f.readline()
with open('text.txt', 'w') as my_file:
my_file.write('something writed')
f.close()