Python 3.0 Basics

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Return the next random floating point number in the range [0.0, 1.0).

random.random()

How do you sort a list?

my_list.sort()

How would you replace the letters in the_list in one line of code with slices? my_list = [0,1,2,3,4,5,a,b,c,9,10] desired_result = [0,1,2,3,4,5,6,7,8,9,10]

my_list[6:9] = [6,7,8]

To append items from an iterable datatype to a list, use the .____ method on a list.

extend

How would you extract/slice the first 5 characters of a given string?

five_char = my_string[0:6]

How would you delete all integers in a list?

for items in my_list: if type(items) is int: the_list.remove(items) else: continue

How would you slice every other item in a list up to halfway into the list? the_list = (range(0,10)) desired_result = [0,2,4]

my_list = the_list[:(int(len(my_list)/2)):2]

A class constructor / initialization function that is called when a class is created. It's in charge of all the setup work for the class like setting up default variables and running other functions before calling specific functions from the class.

__init__

To control what happens when an object is instantiated, what method do we override?

__init__

What is inheritance?

class BaseClass(object): def printHam(self): print("Ham") class InheritanceClass(BaseClass): pass x = InheritanceClass() x.printHam

How would you return the first and last 4 numbers in a list? the_list = [0,1,2,3,4,5,6,7,8,9,10] desired_result = [0,1,2,3,7,8,9,10]

my_list = the_list[:4] + the_list[-4:]

What does self refer to in a method?

the instance

list(range())

Code: range(stop) range(start, stop, step) Using the provided arguments, range() creates a list of integers. When one argument is provided, it is used as the stop integer: range(5) would be [0,1,2,3,4] When two arguments are provided, it uses the first to determine the start point and the second as the stop point. list(range(0,11)) would be [0,1,2,3,4,5,6,7,8,9,10] When a third argument is provided, it specifies what increment should be used for the given range. list(range(0,11,2) would be [0,2,4,6,8,10]

divider = ' ' divider.join(my_list)

Concatenates list items Uses the divider attribute (' ') to determine what character should be between each list item when concatenating it all into a string. The my_list argument designates what list is to be joined. Only string arguments are allowed! </> Example </> Code: ' '.join(my_list) Explanation: joins a list and separates list items with a space (' ')

To make a module importable, what steps do we have to take?

Create a file

Everything in Python is an object except for functions. True or False?

False

True or False? To change how a class becomes a string, we override the __unicode__ special method.

False

Tuples are mutable... True or False?

False

When replacing a slice with another iterable, they must be the same size. True or False?

False

True or False? You cannot sort by one argument then by another (multiple layers of sorting).

False The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age: >>> >>> sorted(student_tuples, key=itemgetter(1,2)) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] >>> >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

len()

Finds the length of a string and any other data structure. Accepts arguments for almost all data structures. len() of a list or dictionary returns the number of items in the data structure len() of a string returns the number of characters in a string

You define classes with the def keyword. True or Flase?

Flase

my_list.insert()

Inserts data into a list at a specified index. Example: my_list = [0,1,2,3,4,5] my_list.insert(1, 5) print(my_list) [0,5,1,2,3,4,5]

continue

Lets you move on to the next step / iteration in a loop.

break

Makes Python stop whatever loop 'break' is in.

list.append()

This function adds items to the end of a list.

while x==2:

This is a comparison while loop used to run code infinitely as long as the specified condition is met.

for x in my_list:

This is a for loop. It runs whatever code is under it for all items in the specified list.

if x in my_list:

This is an if statement that runs code if the data type, 'x', is or has items that are in my_list.

while True:

This is an infinite while loop. This particular loop must be closed using a 'break' command. This is especially useful when you need user input until a condition is met.

All classes ultimately inherit from object. True or False?

True

An instance is a new copy of a class. True or False?

True

True or False? You can reverse a sorted list in the sorted/sort method.

True Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse age order: >>> >>> sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> >>> sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

Tuples are immutable... True or False?

TrueH

What does this return? my_list = list('apple')

['a','p','p','l','e']

What will 'nums' return? my_list = [0,1,2,3,4,5] nums = my_list[0:len(my_list)]

[0,1,2,3,4,5]

What will 'nums' return? my_list = [0,1,2,3,4,5] nums = my_list[:]

[0,1,2,3,4,5]

What will 'nums' return? my_list = [0,1,2,3,4,5] nums = my_list[:2]

[0,1]

What will 'nums' return? my_list = [0,1,2,3,4,5] nums = my_list[2:]

[2,3,4,5]

Please fill in the correct answer in each blank provided below. Name the three parts of the slice syntax: [____:____:____] (hint, they all start with 'st') Submit answer as [part:part:part]

[start:stop:step]

What is a Python class?

A collection of methods and attributes that can be instantiated.

Tuples use what special operator to unpack: for example, when using str.format( _____ my_tuple).

*

Dictionaries use what special operator to unpack: for example, when using str.format( _____ my_dictionary ).

**

What function is used to run code when a class is called upon in a print function? Called by the str(object) and the built-in functions format() and print() to compute the "informal" or nicely printable string representation of an object. The return value must be a string object. Example: print(my_class)

__str__

How would you simultaneously assign two variables ('a' and 'b') in a single line of code? Assign the numbers one and two.

a, b = 1, 2

What does a_tuple.sort() return, assuming a_tuple is a tuple?

an exception

How do you delete an instance?

del

How would you delete the first two items in my_list with only one line of code? my_list = [0,1,2,3,4,5,6,7,8,9,10] desired_result = [2,3,7,8,9,10]

del my_list[:1]

DRY stands for:

don't repeat yourself

Fill in the blank: from operator import ________ , ________

itemgetter, attrgetter

A function that belongs to a class is called a ______.

method

Everything in python is an ______.

object

What class do all classes extend from, even if you don't explicitly state it?

object

What method do we use for this: Random float x, 1.0 <= x < 10.0

random.uniform(1, 10)

Used to attach variables and functions to a class

self

What method of dictionaries are used to add multiple key/value pairs and merge dictionaries at once?

update

Please fill in the correct answer in each blank provided below. Name the two parts of the dictionary syntax: {____:____} Submit answer as {part:part}

{key:value}

my_list.append()

Appends a given argument to my_list. Example: my_list = [0,1,2] my_list.append(range(3,6)) print(my_list) [0,1,2,[3,4,5]] my_list.append(6) print(my_list) [0,1,2,[3,4,5],6] You cannot append items in an iterable using append. The entire data-type is left intact and added to the end of the specified list.

my_list.extend()

Appends the specified datatype, provided as the argument, to the end of a list. When provided a list as the argument, the items within the list are merged into the specified list. Example: my_list = [0,1,2] my_list2 = [6,7,8] my_list.extend(range(3,6)) print(my_list) [0,1,2,3,4,5] my_list.extend(my_list2) print(my_list) [0,1,2,3,4,5,6,7,8]

What is enumerate?

Enumerate returns a tuple with the first variable being the index, and the second being the value. for index, letter in enumerate(alphabet_list) print("{}: {}".format(index,letter)) for step in enumerate(alphabet_list): print("{}: {}".format(step[0],step[1])) for step in enumerate(alphabet_list): print("{}: {}".format(*step)) def combo(list1, list2): my_list = [] for index, item2 in enumerate(list2): my_list.append( (list1[index],item2) ) return my_list

Assign variables ('d' and 'e') for each value in the tuple: c = (3, 4)

d, e = c

What does this do? enumerate(iterable, start=0)

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable. >>> >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] Equivalent to: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1

arg = ' ' my_sentence.split(arg)

Splits a sentence (my_sentence) and uses the argument (' ') to determine at what character it should split the string. This example splits the string whenever it finds a space (' ') in the string. When split, the separated parts of the string are placed into a list. </> Example </> Code: my_string.split(' ') Explanation: separates elements of a string into list items whenever a space is found between a given cluster of characters or otherwise known as a word.

What is setattr()

The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123. Example: class Example: stats = {'one':1, 'two': 2} for key, value in stats.items(): setattr(self, key, value) In this case, we have a for loop that loops through each dictionary item (key,value) and for each item, brings the key, value pair into the classes namespace using the key as the variable's name and the value as the variable's value. In the example, we now have one = 1 and two = 2 in the namespace. So when we call, Example.one, it returns 1.

How do you delete an item from a list?

del my_list[index] Deletes the item at the specified index Example: --------------------- my_list = [0,1,2,3,4,5] del my_list[2] print my_list --------------------- [0,1,3,4,5]

How do you delete a variable?

del my_variable Deletes a variable and since it does not exist, calling it would result in an error.

How do you check to see if a variable exists?

if my_variable: Explanation: Runs the code under the if statement only if my_variable exists/ True.

How do you make an if statement that runs code if the data type is an integer?

if type(my_data) is int: print("Print run this code")

How would you write/export a dictionary to a csv file?

import csv with open('output.csv', 'wb') as output: writer = csv.writer(output) for key, value in dict1.iteritems(): writer.writerow([key, value])

How would you create an instance (jubjub) of a class (Monster)?

jubjub = Monster()

What does this do? max(iterable, *[, key, default]) max(arg1, arg2, *args[, key])

max(iterable, *[, key, default]) max(arg1, arg2, *args[, key]) Return the largest item in an iterable or the largest of two or more arguments. If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised. If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc). New in version 3.4: The default keyword-only argument.

Functions inside of classes are called:

methods

What does this do? min(iterable, *[, key, default]) min(arg1, arg2, *args[, key])

min(iterable, *[, key, default]) min(arg1, arg2, *args[, key]) Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned. There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised. If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc). New in version 3.4: The default keyword-only argument.

How do you add multiple key/value pairs to a dictionary?

my_dict.update = {'key':'value'}

How do you add a single key/value pair to a dictionary?

my_dict['key'] = ['value']

How would you reverse the order of items in a list and only slice every other item from 3 to 8 using a single slice function? the_list = [0,1,2,3,4,5,6,7,8,9,10] desired_result = [8,7,6,5,4,3]

my_list = [8:2:-1]

How would you assign the values in a dictionary to a list?

my_list = [] for values in my_dict.values: my_list.append(values)

How would you make a list containing numbers between 0 and 50?

my_list = list(range(0,51))

How would you slice the item '10' without using 10 as the index? the_list = [0,1,2,3,4,5,6,7,8,9,10] desired_result = [10]

my_list = the_list[-1]

How would you slice the item '8' without using 8 as the index? the_list = [0,1,2,3,4,5,6,7,8,9,10] desired_result = [8]

my_list = the_list[-3]

How would you only slice the odd numbers in a list? the_list = [0,1,2,3,4,5,6,7,8,9,10] desired_result = [1,3,5,7,9]

my_list = the_list[1::2]

How would you slice every other item in a list? the_list = (range(0,10)) desired_result = [0,2,4,6,8,10]

my_list = the_list[::2]

How would you add the number 1 through 2o to a list?

my_list.extend(range(1,21))

How do you remove an item from a list and assign it a variable?

my_list.pop(index) Example: --------------------------- my_list = [1,2,3,4,5] five = my_list.pop(0) print(my_list) --------------------------- [2,3,4,5]

How do you delete a list item by referring not to an index, but to the data itself (string, int, or float)?

my_list.remove(data) Example: ----------------------------------- my_list = ['apples', 'grapes'] my_list.remove('apples') print(my_list) ----------------------------------- ['grapes']

How would you unpack all dictionary values into string placeholders?

my_string.format(**my_dict)

How would you reverse the order of characters in a string? my_string = 'ted' desired_result = 'det'

my_string[::-1]

Make a tuple with the variable 1 and 2.

my_tuple = 1, 2

What method do we use for this: Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

random.choice(seq)

What method do we use for this: Random float x, 0.0 <= x < 1.0

random.random()

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn't actually build a range object.

random.randrange([start], stop[, step])

How would you choose 3 random items of a list containing the numbers 1 through 5?

random.sample([1, 2, 3, 4, 5], 3)

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample from a range of integers, use an range() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60).

random.sample(population, k)

Initialize the basic random number generator. Optional argument x can be any hashable object. If x is omitted or None, current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability). If x is not None or an int, hash(x) is used instead. If x is an int, x is used directly.

random.seed([x])

What method do we use for this: Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated.

random.shuffle(x[,random])

By convention, what is the name of the first argument for all instance methods?

self

class Store: open = 9 close = 6 def hours(self): [How would you call the 'open' variable from Store in this function?]

self.open

Sorts my_list in-place

sort()

Builds a new sorted list called my_list2 from my_list

sorted()

Return a new sorted list from the items in iterable. Has two optional arguments which must be specified as keyword arguments.

sorted(iterable[, key][, reverse]) key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly). reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed. Use functools.cmp_to_key() to convert an old-style cmp function to a key function. The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).


संबंधित स्टडी सेट्स

OB Cumulative Review II (Quiz 8-13)

View Set

Chapter 16: Social Responsibility and Sustainability

View Set

Chapter 23: Gene Pools Evolve of Populations

View Set

Ch. 6 Evolution - Biol3620-ECU-Summers

View Set