Python Basics for Data Science Flashcards Preview

Data Science from Scratch with Python > Python Basics for Data Science > Flashcards

Flashcards in Python Basics for Data Science Deck (18)
Loading flashcards...
1
Q

What can be used as a shortcut for a function with return? Give an example with 2 variables.

A

lambda. Example: lambda x,y: x+9-y
x,y= 3,2 #10
Note:
- lambda function doesn´t have a return statement

2
Q

What are exceptions, why and how are they helpful?

A

try/except.
prevent the origram from crashing
difficult part is placed into try statement, alternative in except

3
Q

How do you check the existance of an element in a list?

A

4 in [3,6,7] #gives booleons back

also possible when list is a variable like a. 2 in a …

4
Q

How do you unpack a list of 3 digits?

How do you proceed if you only want two of the digits?

A

x,y,z=[8,9,1]. Now x=8 …

_,y,z=[8,9,1]: underscore marks what gets out

5
Q

How do you swap 2 variables?

A

y,x=5,6

y,x=x,y # now x=6 and y=5

6
Q

You want to get a pair out of a dic?

A

dicname.get(“key”) # value is optional

returns None when no key is found(other methods produce errors)

7
Q

How to add a new entry or replace in a dic?

A

dicname[“keyname”]= value

8
Q

What to do if you want to see the keys, values and key-value tuples of a dic?

A

dicname.keys()/.vales()/.items()

9
Q

Counting word appearances in a text with a dic. How? Code it.

Also name a shortcut if you look up a key, it´s not in, so it directly creates one. How would you code the same example?

Give an even shorter shortcut and the code.
Then, tell me how do I get the 10 most occuring values of that dic? How do you code it?

A
word_count={}
for word in text:
    if word in word_count:
        word_count["word"] +=1
    else:
         word_count["word"] =1

Shortcut= defaultdict

word_count=defaultdict(int) # int creates a 0
for word in text:
word_counts[“word”] +=1

shorter shortcut= counter

from collections import counter

word_counts=Counter(document)

for word, count in word_counts.most_common(10)
print word, count

10
Q

How to test a condition faster than with if-else? Give a code example.

A

Ternary Operators

good_weather=true
forecast= “sun” if good_weather else “rain”

11
Q

sorted(x) vs x.sort(). Tell me the similarities and differences.

A

x.sort() only sorts list, other sorts everythin iterable, p.e. also dics.

sorted(x) is used to make a new list with variable y and not overwrite it like x.sort()

Both take additional arguments. y=(sorted, dic, key=lambda actors: actors[2], reverse=) #key now sorts by points and not age. A key changes a variable before its get compared and listed

12
Q

What is a generator good for? Give a code example. What has yield to do with that?

A

loops go often over iterable objects and therefore the memory shrinkens. To prevent this, we use a generator, who goes over it once. Only the generator gets back to you.

1st example:

def firstn(n):
   3     num = 0
   4     while num < n:
   5         yield num
   6         num += 1

yield works like the return statement

2nd example (with list comprehension)

doubles = [2 * n for n in range(50)]
 # same as the list comprehension above
 doubles = list(2 * n for n in range(50))
13
Q

What does …

  1. random.random()
  2. random.randrange()
  3. random.shuffle(listname)
  4. random.choice([…,…,…])
  5. random.sample(listname, number of wanted elements)
A
  1. produces random number between 0-1
  2. takes random number of given range
  3. reorders list
  4. picks random element out of list
  5. easy
14
Q

What is functools.partial. Code an example!

A

Because def gets treated like an object in Python, f.p. calls another definition, with providing 1 argument where 2 are needed.

def sum(a,b)
       return a+b
incr=functools.partial(sum,1)
incr(3)          
#ergibt 4         

# incr behaves like sum, yet misses one argument. Thus it takes the one from functools.partial.

15
Q

Code an alternative to list comprehension with the map() function. # double the numbers of a list with a self created function.

A

ys=map(double,xs)

16
Q

What is enumerate helpfull for? Code an example. Then code an example if you only want the indices.

A

with enumerate you loop over sth and automatically count.

for counter, value in enumerate(listname)
print(counter, value)

and

# in this example index is counter
for i,_ in enumerate(listname) 
     do_sth_with(i)       #p.e. print()
17
Q

What can you do with zip()? And how to unzip?

A
putting lists together.
xs=[a,b,c]
ys=[1,2,3]
tip(xs,ys)
= [("a",1),...]

unzip:

zip((“a”,1),…)

18
Q

What do args do? Give a code example!

What does kwargs do? Give an example!

A

With args you can out as many arguments as you wish into a function, which is helpful if the number of arguments is defined in the process.

Code example:

def sum(*args)  # asteriks important 
result=0
for x in args
result+=X
return result
print(sum(34,6,7,3,2))   # give a tuple instead of a list

kwargs maps keywords with arguments.
def: my_fun(**kwargs)
for key, value in kwargs.items():

my_fun(first="I", mid="am", last="good")
print
first==I
mid==am
last==good