# Python variable operator data structure

Joshua- 2022-01-26 13:26:25 阅读数:683

python variable operator data structure

# python Basic study one

Record learning All references https://github.com/datawhalechina/team-learning-program

## notes

• `#`： Single-line comments
• `''' '''` perhaps `""" """` : Multiline comment

## Operator

### Arithmetic operator

Add (+) reduce (-) ride (*) except (/) to be divisible by (//) Remainder (%) power (**)

### Comparison operator

Greater than (>) Less than (<) be equal to (==) It's not equal to (!=) Greater than or equal to (>=) Less than or equal to (<=)

### Logical operators

And (and) or (or) Not (not)

### An operator

According to the not (~) Bitwise AND (&) Press bit or (|) Bitwise XOR (^) Move left (<<) Move right (>>)

### Ternary operator

``````res = c if a > b else d
# if a>b(true) res = c
# if a>b(false) res = d
``````

Nesting of ternary operators

Python The ternary operator supports nesting , In this way, more complex expressions can be formed . When nesting, you need to pay attention to if and else Pairing of

``````a, b, c, d = 1, 2, 3, 4
res = a if a>b else c if c>d else d # res = 4
res = a if a>b else ( c if c>d else d ) # res = 4
``````

### Other operators

`in` There is `'A' in ['A', 'B', 'C']`

`not in` non-existent `'h' not in ['A', 'B', 'C']`

`is` yes `"hello" is "hello"`

`is not` No `"hello" is not "hello"`

notes :

• is, is not The comparison is between the two variables Memory address

• ==, != The comparison is between the two variables value

• Compare the two variables , All points to addresses Immutable type （str etc. ）, that is,is not and ==,！= It's completely equivalent .

• Compare the two variables , It points to the address Variable types （list,dict,tuple etc. ）, There is a difference between the two .

``````# Both variables point to immutable types
a = "hello"
b = "hello"
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
# Both variables in the comparison point to variable types
a = ["hello"]
b = ["hello"]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
``````

### Operator precedence

• Unary operators are better than binary operators . for example `3 ** -2` Equivalent to `3 ** (-2)`.
• Arithmetic first , Post shift operation , Last bit operation . for example `1 << 3 + 2 & 7` Equivalent to `1 << (3 + 2)) & 7`.
• Logical operations are finally combined with . for example `3 < 4 and 4 < 5` Equivalent to `(3 < 4) and (4 < 5)`.

## Data types and transformations

Simple data type

• integer `<class 'int'>`
• floating-point `<class 'float'>`
• Boolean type `<class 'bool'>`

Container data type

• list `<class 'list'>`
• Tuples `<class 'tuple'>`
• Dictionaries `<class 'dict'>`
• aggregate `<class 'set'>`
• character string `<class 'str'>`

### integer

``````a = 1031
print(a, type(a))
# 1031 <class 'int'>
``````

### floating-point

``````print(1., type(1.))
# 1.0 <class 'float'>
a = 0.00000023
b = 2.3e-7
print(a) # 2.3e-07
print(b) # 2.3e-07
``````

Keep the decimal point after the floating point `n` position

use `decimal` In the bag `Decimal` Objects and `getcontext()` Method to implement :

``````import decimal
from decimal import Decimal
a = decimal.getcontext() # Decimal The default precision value for the object is 28 position (`prec=28`)
print(a)
# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
# capitals=1, clamp=0, flags=[],
# traps=[InvalidOperation, DivisionByZero, Overflow])
# send 1/3 Retain 4 position , use getcontext().prec To adjust the accuracy
b = Decimal(1) / Decimal(3)
print(b) # 0.3333333333333333333333333333
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c) # 0.3333
``````

### Boolean type

Boolean (boolean) Type variable can only take two values ,`True` and `False`. When Boolean variables are used in numerical operations , use `1` and `0` representative `True` and `False`.

determine `bool(X)` The value of is `True` still `False`, Just look `X` Is it empty , Empty words are `False`, If it's not empty, it's `True`.

• For numerical variables ,`0`, `0.0` Can be considered empty .
• For container variables , If there is no element in it, it is empty .
``````print(type(0), bool(0), bool(1)) # <class 'int'> False True
print(type(10.31), bool(0.00), bool(10.31)) # <class 'float'> False True
print(type(True), bool(False), bool(True)) # <class 'bool'> False True
# bool Action on container type variables ：X As long as the variable is not empty ,bool(X) Namely True, The rest is False
print(type(''), bool(''), bool('python')) # <class 'str'> False True
print(type(()), bool(()), bool((10,))) # <class 'tuple'> False True
print(type([]), bool([]), bool([1, 2])) # <class 'list'> False True
print(type(set()), bool(set()), bool({
1, 2})) # <class 'set'> False True
print(type({
}), bool({
}), bool({
'a': 1, 'b': 2})) # <class 'dict'> False True
``````

Get type information

• Get type information `type(object)`, `type()` A subclass is not considered a superclass type , Do not consider inheritance relationships .
• Get type information `isinstance(object, classinfo)` ,`isinstance()` Think of a subclass as a superclass type , Consider inheritance relationships .

It is recommended if you want to determine whether two types are the same `isinstance()`.

``````print(type(1)) # <class 'int'>
print(type(5.2)) # <class 'float'>
print(type(True)) # <class 'bool'>
print(type('5.2')) # <class 'str'>
print(isinstance(1, int)) # True
print(isinstance(5.2, float)) # True
print(isinstance(True, bool)) # True
print(isinstance('5.2', str)) # True
``````

Type conversion

• Convert to integer `int(x, base=10)`
• Convert to string `str(object='')`
• Convert to floating point `float(x)`
``````print(int('520')) # 520
print(int(520.52)) # 520
print(float('520.52')) # 520.52
print(float(520)) # 520.0
print(str(10 + 10)) # 20
print(str(10.1 + 5.2)) # 15.3
``````

## print() function

``````print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
``````
• Put the object in character string Format the output to the stream file object in the way of representation file in . All non keyword parameters are pressed `str()` Method to convert to string output ;
• Key parameters `sep` It's the implementation separator , For example, when multiple parameters are output, you want to output the middle separator character ;
• Key parameters `end` Is the character at the end of the output , The default is line break `\n`;
• Key parameters `file` Is the file that defines the output of the stream , Can be standard system output `sys.stdout`, It can also be redefined as another file ;
• Key parameters `flush` Is to output the content to the stream file immediately , No caching .
``````citylist = ['Shanghai', 'Beijing', 'Chengdu', 'Wuhan']
print("This is printed without 'end'and 'sep'.")
for item in citylist:
print(item)
''' This is printed without 'end'and 'sep'. Shanghai Beijing Chengdu Wuhan '''
citylist = ['Shanghai', 'Beijing', 'Chengdu', 'Wuhan']
print("This is printed with 'end='&''.")
for item in citylist:
print(item,end='&')
''' This is printed with 'end='&''. Shanghai&Beijing&Chengdu&Wuhan& '''
citylist = ['Shanghai', 'Beijing', 'Chengdu', 'Wuhan']
print("This is printed with 'sep='--''.")
for item in citylist:
print("welcome",item,sep='--')
''' This is printed with 'sep='--''. welcome--Shanghai welcome--Beijing welcome--Chengdu welcome--Wuhan '''
``````

## Exercises ：

1. How to python Comment on the code in ？

``````# Single-line comments
''' Multiline comment Multiline comment '''
""" Multiline comment Multiline comment """
``````
2. python What operators are there , What is the priority of these operators ？ 3. python in `is`, `is not` And `==`, `!=` What's the difference ？

• is, is not The comparison is between the two variables Memory address

• ==, != The comparison is between the two variables value

• When the pointing addresses are immutable types is,is not and ==,！= It's completely equivalent

4. python What operators are there , What is the priority of these operators ？ How to convert between these data types ？

`````` 6 Standard data types
*Number( Numbers )
*True=1
*False=0
* Division of values （/） Always return a floating point number , To get integer usage // The operator
* In mixed calculation ,python Will convert the integer to a floating point number
*String( character string )
* String use ' or " Cover up , Use at the same time \ Escape special string
* If you don't want the backslash to escape , You can prefix the string with r Represents the original string
* Index value to 0 For the beginning ,-1 Is the beginning of the end
* plus + Is the concatenator of a string , asterisk * Means to copy the current string , The number that follows is the number of copies
*List( list )
*list Write between square brackets , The elements are separated by commas
* Just like a string ,list Can be indexed and sliced
*list The elements in can be changed
*Tuple( Tuples )
* Tuples are similar to lists , The difference is that the elements of a tuple cannot be modified , Tuples are written in parentheses . The elements are separated by commas
* Tuples can also be indexed and sliced , The method is the same
* Notice that the construction contains 0 or 1 Special syntax rules for tuples of elements
* Tuples can also be used + Operators are spliced
*Sets( aggregate )
*set Is a sequence that does not need to be repeated , The basic function is to test membership and delete duplicate elements
Dictionary( Dictionaries )
* A dictionary is a mapping type , Dictionary use {} identification , It is a disorderly building (key): value (value) The collection
* build (key) Immutable type must be used . Build... In the same dictionary (key) Must be unique
* Create an empty dictionary to use {}
``````
`````` *int(x,base=10)x String or number ,base Hexadecimal number , Default decimal Floating point to integer
*float Convert integer to floating point
*complex(1,2) Convert to plural
*str(10) Convert objects to strings
*repe() Convert an object to an expression string
*repr(dict) Convert an object to an expression string
*eval(str) Used to calculate the valid in the string python expression , Return an object
*tuple(listi) Convert the list to tuples
*list() Converts a tuple to a list
*set Convert sets
``````

## An operation

Original code ： Is its binary representation （ Be careful , There is a sign bit ）.

Inverse code ： The inverse of a positive number is the original code , The inverse of a negative number is a sign bit invariant , The rest of the bits are reversed （ The corresponding positive number is negated by bit ）.

Complement code ： The complement of a positive number is the original code , The complement of a negative number is the inverse +1.

Sign bit ： The highest bit is the sign bit ,0 It means a positive number ,1 A negative number . In the in place operation, the symbol bit also participates in the operation .

• Bitwise non operation ~ `~ 1 = 0 ~ 0 = 1`

• Press bit and operate & whole `1` by `1`

• To press or operate | Yes `1` by `1`

• Operate by bitwise exclusive or ^ Different for `1`

• Shift left by bit operation <<

• Shift right by bit operation >>

### Using bit operation to realize fast calculation

adopt `<<`,`>>` Fast calculation 2 The multiple problem of

``````n << 1 -> Calculation n*2
n >> 1 -> Calculation n/2, Negative odd operations are not available
n << m -> Calculation n*(2^m), That's multiplied by 2 Of m Power
n >> m -> Calculation n/(2^m), Divided by 2 Of m Power
1 << n -> 2^n
``````

adopt `^` Quickly swap two integers .

``````a = 5 # 0000 0101
b = -5 # 1111 1011
a ^= b # 1111 1110
b ^= a # 0000 0101 5
a ^= b # 1111 1011 -5
``````

adopt `a & (-a)` Get... Quickly `a` The last is 1 Integer of position

``````00 00 01 01 -> 5
&
11 11 10 11 -> -5
---
00 00 00 01 -> 1
00 00 11 10 -> 14
&
11 11 00 10 -> -14
---
00 00 00 10 -> 2
``````

### Using bit operation to realize integer set

The binary representation of a number can be regarded as a set （0 Not in the set ,1 In a set ）.

For example, a collection `{1, 3, 4, 8}`, It can be expressed as `01 00 01 10 10` The corresponding bit operation can also be regarded as the operation on the set .

``````a | (1<<i) -> hold i Insert into collection
a & ~(1<<i) -> hold i Remove from collection
a & (1<<i) -> Judge i Whether it belongs to the collection （ Zero does not belong to , Nonzero belongs to ）
``````

Operations between collections ：

``````a repair -> ~a
a hand over b -> a & b
a and b -> a | b
a Bad b -> a & (~b)
``````

Python Of `bin()` Output .

``````print(bin(3)) # 0b11
print(bin(-3)) # -0b11
print(bin(-3 & 0xffffffff))
# 0b11111111111111111111111111111101
print(bin(0xfffffffd))
# 0b11111111111111111111111111111101
print(0xfffffffd) # 4294967293
``````
• Python in `bin` A negative number （ Decimal means ）, The output is the binary representation of its original code plus a minus sign **, crater **.
• Python Integers in are stored as complements .
• Python The integer is unlimited in length and will not overflow .

So in order to get negative numbers （ Decimal means ） Complement , You need to manually combine it with a hexadecimal number `0xffffffff` Do bit and operation , Give it back `bin()` For the output , What you get is the complement of a negative number .

## Exercises ：leetcode exercises 136. A number that appears only once

Given a Non empty An array of integers , Except that an element only appears once , Each of the other elements occurs twice . Find the element that only appears once .

Try to solve this problem with bit operation .

``````class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for num in nums:
res^=num
return res
''' The result of an integer XOR with itself is 0 An integer and 0 The result of XOR is itself XOR operation satisfies the exchange law , namely a^b^c^d^a^b^d == a^a^b^b^d^d^c == c '''
``````