Python Flashcards

1
Q

any( )

A

The any( ) function returns True if any element of an iterable is True. If not, it returns False.

boolean_list = [‘True’, ‘False’, ‘True’]

# check if any element is true
result = any(boolean_list)
print(result)

=> Output: True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

zip( )

A

The zip( ) function takes iterables (can be zero or more), aggregates them in a tuple, and returns it. [returns zip object => list( ) for array]

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]

result = zip(languages, versions)
print(list(result))

Output: [(‘Java’, 14), (‘Python’, 3), (‘JavaScript’, 6)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

List comprehension

A

fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]

newlist = [x for x in fruits if “a” in x]

print(newlist)
#=> ['apple', 'banana', 'mango']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

arr = [1,2,3]

for i in range( len( arr ) ):
print( i )

A

0
1
2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

for i in range( 5 ):

print( i )

A
0
1
2
3
4
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

for i in range( 6, 10 ):

print( i )

A

6
7
8
9

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

ratio_of_users = { “friends”: 6, “influencers”: 2, “fans”: 1, “strangers”: 1 }

print( type( ratio_of_users.values( )) )
print( ratio_of_users.values( ) )

A

dict_values( [6, 2, 1, 1] )

=> use like: list( ratio_of_users.values( ) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Generate random number

A

import random

random.randrange( 3 )
=> similar to range(int), this outputs a random int from 0, 1, 2 [not 3!!]

# as a result, works great for lists: list[ randrange( len(list) ) ] 
        => random element from list
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Propend character to string

A

BEST:

  • strings are immutable objects: Need to be copied every time changed
  • > Use a mutable object
append_to_this = " :Append here"
pre_in_reverse = list( range( 1, 11 ) )
pre_in_reverse.reverse( )
string_version = "".join( [ str( e ) for e in pre_in_reverse ] )
return string_version + append_to_this

FINE IF ONCE:
s = “48”
s = str(1) + s
=> “148”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Python set

  • initialize
  • operations
A
s1 = set( )
s2 = set( 3, 2, "string", ("a", 2, "c") ) 
s3 = { 3, 2, "string" }

3 in s2 => True // O(1) <=!!!!!!

s. update( (1,) ) => must be a set itself
s. remove( x ) => key error if not present
s. discard( x ) => removes without error if not present
s. pop( ) => removes and returns random element
s. clear( ) => removes all elements from set

s3 = s1.union( s2 )     =>     not a mutation! Doesn't change s1
s3 = s1.intersection( s2 )     =>     not a mutation! Doesn't change s1
s3 = s1.difference( s2 )     =>     // difference: also -> s1 - s2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

dict operations

A

Hash tables:

  • elements allocated through hash function
  • search O( 1 )
h = dict( )
h = { 'a': 1, 'b': 2 }

h. items( ) => Returns a LIST containing a tuple for each key value pair
h. keys( ) => Returns a LIST containing the dictionary’s keys
h. values( ) => Returns a LIST containing the dictionary’s values
h. clear( ) => Removes all the elements from the dictionary
h. copy( ) => Returns a copy of the dictionary
h. popitem( ) => Removes the last inserted key-value pair

h.pop( ‘a’ ) => deletes key value pair of key ‘a’ AND returns Value
h.pop( ‘a’, returnValue ) => deletes key value pair of key ‘a’ AND returns the second parameter ONLY if not found!
del h[ ‘a’ ] => deletes key value pair of key ‘a’,

h. get( ‘a’ ) => Returns the value of the specified key -> same as h[‘a’], but NO KEY ERROR if doesn’t exist
h. get( ‘a’, returnValue ) => Returns the value of the specified key. If doesn’t exist, returns value 2nd param
h. update( { ‘a’: 1 } ) => Updates the value of key a to 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Check if key ‘a’ is in dict h

Check if value 1 is in dict h

A

‘a’ in h

1 in h.values( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Length of dict h

A

len( h )

=> by default, dict refers to the keys.
E.g. ‘a’ in h => bool

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Reverse python iterable

E.g. string, list

A

s = “hallo”
s[ : : -1 ]
=> ollah

Time complexity: O( n )

For list:

list. reverse( )
- > Mutable vs immutable object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Round numbers up or down to ints

A

import math

math. ceil( 5/3 ) => 3
math. floor( 5/3 ) => 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Find greatest common divisor (GCD)

A

import math

math.gcd( 9, 30 ) => 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

type( 15 / 3 )

A

=> float

If you need type int:
int( 15 / 3 )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Create a matrix with m rows and n columns

All zeros

A

matrix = [ [ 0 for j in range( n )] for i in range ( m ) ]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

for j in range(1,5):

print(j)

A

1
2
3
4

20
Q

PEP8 naming convention: Classes

A

Model, MyClass

Start each word with a capital letter. Do not separate words with underscores. This style is called camel case.

21
Q

PEP8 naming convention: Modules

A

module.py, my_module.py

Use a short, lowercase word or words. Separate words with underscores to improve readability.

22
Q

PEP8 naming convention: Package

A

package, mypackage

Use a short, lowercase word or words. Do not separate words with underscores.

23
Q

PEP8 naming convention: Functions, methods, variables

A

my_function, my_variable, class_method

Use a lowercase single letter, word, or words. Separate words with underscores to improve readability.

24
Q

print all odd numbers from 0 to 101 (including)

A

for i in range( 1, 102, 2 ):
print( i )

  • Third argument is skips
  • Choose right start number for odd / even
25
Q

Prepend to list

A

my_list = [ 2, 3 ]

my_list.insert( 0, 1 )

my_list => [ 1, 2, 3 ]

Syntax:
list.insert( idx, element )

26
Q

list the alphabet

A

import string

list( string.ascii_lowercase )

27
Q

Double ended queue Python

A

import collections

normal_list = [ 1, 2, 3, 4 ]
deque_list = collections.deque( normal_list )
METHODS
append( ): This function is used to insert the value in its argument to the right end of the deque.

appendleft( ): This function is used to insert the value in its argument to the left end of the deque.

pop( ): This function is used to delete an argument from the right end of the deque.

popleft( ): This function is used to delete an argument from the left end of the deque.

28
Q

__funcxx__

A

Magic or Dunder methods

invocation happens internally from the class on a certain action. For example, when you add two numbers using the + operator, internally, the __add__() method will be called.

num=10
num + 5 
  => 15
num.\_\_add\_\_(5) 
  => 15
29
Q
arr = [ 1, 2 ]
b = arr.append( 4 )

print( b )

A

None

!! list.append(x) doesn’t return anything !!
It only updates the list

30
Q

print( list( range( 3, 2 ) )

A

[ ]

=> important when iterating n^2 without repeating elements

len_nums = len(nums)
for a in range(len_nums):
for b in range(a+1, len_nums):
sum = nums[a] + nums[b]

                           => works
31
Q

print( [ 1,2 ] == [ 2,1 ] )

A

False

Two different lists - they are ordered

32
Q

print( ( 1,2 ) == ( 2,1 ) )

A

False

Two different tuples - they are ordered

33
Q

word = “w”
print( word[ 1 : ] )

my_list = [ 1 ]
print( my_list[ 1 : ] )

A

=> “”

=> [ ]

(important for recursive algorithms)

34
Q

Parameter vs Argument

A

The terms parameter and argument can be used for the same thing:

Information that are passed into a function. From a function’s perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called.

def foo( x: str ):         # x -> parameter
     pass

foo( “word” ) # “word” -> argument

35
Q

foo

A

‘foo’ is just a general, meaningless placeholder used in coding

def foo( x: int ):
      print( x )
36
Q

merge two lists

l1 = ["a", "b" , "c"]
l2 = [1, 2, 3]
A

merged_list = l1 + l2

=> [‘a’, ‘b’, ‘c’, 1, 2, 3]

37
Q

Remove item from list by index

A

list.pop(idx)

l = [ 1, 2, 3 ]
l.pop( 1 )

38
Q

Iterate through an array or string with index

A

for ele, idx in enumerate( arr ):
print( idx, ele )

for idx in range( len( arr ) ):
print( idx, arr[ idx ] )

39
Q

Iterate through an array / string from back to front

A

for i in range ( len( arr ) - 1, -1, -1 ):

print( i, arr[ i ] )

40
Q

arr_2d = [ [“a”, “b”], [“c”, “d”], [“e”, “f”] ] # assume all sub_arrays hold pairs

Iterate through the pairs

A

for first_val, second_val in arr_2d:
print( first_val )
print( second_val )i

41
Q

Convert string s = “What’s up?” to a list

A

list( s )
=> [‘W’, ‘h’, ‘a’, ‘t’, “’”, ‘s’, ‘ ‘, ‘u’, ‘p’, ‘?’]

note whitespace

42
Q

Create defaultdict with 0 as default value

A

import collections

dd = collections.defaultdict( int )

dd[ ‘new_key’ ] += 1

print( dd )
=> defaultdict( , { ‘new_key’: 1 } )

43
Q

Iterating through list and comparing adjacent elements

A

With a regular iteration, you would run into an index error at the beginning or end.w

Solution:
If comparing each element to prior, start at idx 1 => for i in range(1, len(arr))

If comparing each element to following element +> for in range( 0, len(arr)-1)

44
Q

Make list a string - join elements
l = [‘a’, ‘b’, ‘b’]
Desired output: “abc”

[add other versions: non homogeneous lists etc)
https://www.simplilearn.com/tutorials/python-tutorial/list-to-string-in-python

A

’‘.join( l )

45
Q

continue statement

A

‘continue’ skips an iteration in a for or while loop.

for i in range(4):
    if i == 2:
        continue
    print( i )

=> 0, 1, 3

46
Q

break statement

A

‘break’ stops a for or while loop.

for i in range(4):
    if i == 2:
        break
    print( i )

=> 0, 1

47
Q

Round a number to closest integer

A

round( )

Directly integrated in python.
E.g. round(13/4) == 3