from-exercises Flashcards
sort an interable
arr.sort() method, applies to list only
A list also has the sort() method which performs the same way as sorted(). The only difference is that the sort() method doesn’t return any value and changes the original list.
———or———-
Python function: sorted()
[returns sorted_list] sorted(_ _ iterable, key=None, reverse=False)
Does not change the original iterable
iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.
key (Optional) - A function that serves as a key for the sort comparison.
reverse (Optional) - If True , the sorted list is reversed
ascii-lowercase
import string
string. ascii_lowercase
- ->returns a string constant ‘abcdefghijklmnopqrstuvwxyz’
string.ascii_uppercase
string.ascii_letters –>both cases, so that:
‘a’ is ascii_letters[0], and ‘A’ is ascii_letters[26]…
zip()
The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
(nothing to do with compresion, e.g. zip up a file, or archive.zip!!)
——-
Syntax :
zip(*iterators)
Parameters : Python iterables or containers ( list, string etc )
Return Value : Returns a single iterator object, having mapped values from all the containers.
—————-
Need to convert to list,set before printing!
otherwise print will return
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
import string
string. ascii_letters
- ->a string constant
0123456789
import string
string. ascii_digits
- ->a string constant
0123456789abcdefABCDEF
import string
string. ascii_hexdigits
- ->a string constant
01234567
import string
string. ascii_octdigits
- ->a string constant
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!”#$%&’()*+,-./:;<=>?@[]^_`{|}~
import string
string. printable
- ->a string constant
!”#$%&’()*+,-./:;<=>?@[]^_`{|}~
import string
string. punctuation
- ->a string constant
use:
import string
string.whitespace
–>note this is a string constant
random.choice(sequence)
returns a random element from the non-empty sequence
element type is same as iterable
error if sequence/iterable is empty
*dict must be converted into list (which listifies the key only)
————————–
import random
random.choice(sequence)
————————-
#choose a random movie from your “To Watch” list
import random
movie_list = [‘The Godfather’, ‘The Wizard of Oz’, ‘Citizen Kane’, ‘The Shawshank Redemption’, ‘Pulp Fiction’]
moview_item = random.choice(movie_list)
print (“Randomly selected item from list is - “, moview_item)
——————————–
’‘.join(iterable)
list1 = ['1','2','3','4'] s = "-" print(s.join(list1) --->1-2-3-4 ---------------------------- list1 = ['g','e','e','k', 's'] print("".join(list1)) #can also use single quotes --->geeks --------------------------- import random, string as str pw = ''.join( [random.choice(str.ascii_letters + str.digits) for n in range(size)] ) ---------------------------
list comprehension
???
[random.choice(str.ascii_letters + str.digits) for n in range(size)] -------- #remove empty strings from list strings = ["first", "", "second"] >>> [x for x in strings if x] ['first', 'second'] -----------> !!!!! nice insight If the list must be modified in-place, because there are other references which must see the updated data, then use a slice assignment:
strings[:] = [x for x in strings if x]
using random.choice(iter) with a dictionary iterable
-random.choice does not work with dictionary
-convert dict to list, list(mydict)
-note above saves keys only to the list
—–
import random
weight_dict = { "Kelly": 50, "Red": 68, "Jhon": 70, "Emma" :40 } key = random.choice(list(weight_dict)) print(list(weight_dict)) print ("Random key-value pair from dictonary is ", key, " - ", weight_dict[key])
import random
random functions for integers[expression for item in list]
Functions for integers
random. randrange(stop) #right endpoint not included
- ->print(random.randrange(10))
- -»7
random. randrange(start, stop[, step])
#use this if you want to include the right endpoint (int egers only): random.randint(a, b) Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
random.choices(sequence, size)
#returned sample can contain duplicates list = [20, 30, 40, 50 ,60, 70, 80] sampling = random.choices(list, k=4) print("Randomly selected multiple choices using random.choices() ", sampling)
Syntax of List Comprehension
h_letters = [ letter for letter in ‘human’ ]
——-
above equivalent to:
letters = list(map(lambda x: x, ‘human’))
——
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
–>even numbers
——
num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
—>prints only if both are satisfied
—————-
obj = [“Even” if i%2==0 else “Odd” for i in range(10)]
print(obj)
—>Even, Odd, Even,….]
—————–
can also transpose a matrix :| … see printout
dictionary com-ifprelhension
dictionary = {key: value for vars in iterable} -------------------- # dictionary comprehension example square_dict = {num: num*num for num in range(1, 11)} print(square_dict) -->{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100} ------------------ #item price in dollars old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5}
dollar_to_pound = 0.76
new_price = {item: value*dollar_to_pound for (item, value) in old_price.items()}
print(new_price)
—————-
original_dict = {‘jack’: 38, ‘michael’: 48, ‘guido’: 57, ‘john’: 33}
even_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0}
print(even_dict)
—>{‘jack’: 38, ‘michael’: 48}
find the index of a value in a list, string
mylist.index(element,start(optional),end(optional))
-returns index first occurance of element/substring element (starting from initial character)
-if element not in list, returns error =>use with
if (ele in mylist):
or
if (substr in word):
—–
string.ascii_letters.index(‘k’) –> 10
string.ascii_letters.index(‘k’, 9) –> 10
string.ascii_letters.index(‘k’, 9,11) –> 10
string.ascii_letters.index(‘k’,9,10) –> ValueError: substring not found
string.ascii_letters.index(‘kj’) –>9
rstrip(chars)
rstrip() does not modify original string!!!
must save to new string (strings are immutable)removing empty strings from a list)
————————
(see card 13 for
rstrip() Parameters
chars (optional) - a string specifying the set of characters to be removed.
If chars argument is not provided, all whitespaces on the right are removed from the string.
—–
Example: Working of rstrip()
random_string = ‘ this is good’
# Leading whitepsace are removed print(random_string.rstrip())
# Argument doesn't contain 'd' # No characters are removed. print(random_string.rstrip('si oo'))
print(random_string.rstrip(‘sid oo’))
website = 'www.programiz.com/' print(website.rstrip('m/.')) -->surprising output (reread above descr of chars arg) this is good this is good this is g www.programiz.co
iterate a dictionary: through keys
not items
Python3 code to iterate through all keys in a dictionary
statesAndCapitals = {
‘Gujarat’ : ‘Gandhinagar’,
‘Maharashtra’ : ‘Mumbai’,
‘Rajasthan’ : ‘Jaipur’,
‘Bihar’ : ‘Patna’
}
print(‘List Of given states:\n’)
# Iterating over keys for state in statesAndCapitals: print(state)