def sub_lists(my_list): subs = [] for i in range(0, len(my_list)+1): temp = [list(x) for x in combinations(my_list, i)] if len(temp)>0: subs.extend(temp) return subs
def all_submodels(self): - return sorted(zip(self.submodels, self.submodels) + - self.submodel_aliases.items(), + return sorted([(k,k) for k in self.submodels] + + [k for k in list(self.submodel_aliases.items())], key = lambda k: len(k[0]), reverse = True) def defines(self, target_submodel, with_endian): @@ -574,13 +574,26 @@ for feat in self.target_features] def canon_processor(archinfo, proc):
def find_friends(lst): dct = {} for element1 in lst: for element2 in element1: if len(element1) != 1: dct[element2] = dct.get(element2,0) + 1 else: dct[element2] = 0 return dct Can you do the following without using subquery?: {1,None,1,2,None} --> [1,1,1,2,2] Ensure you take care of case input[None] which means None object Def replace_none (dict): ls=list(dict) For i in ls: If ls[i] is none: ls[i]=dic[i-1]
def nth_highest(inp,n): b=list(sorted(set(inp.values()), reverse=True)) o={k for k,v in inp.items() if v==b[n-1]} return min(o) You have a 2-D array of friends like [[A,B],[A,C],[B,D],[B,C],[R,M], [S],[P], [A]]. Write a function that creates a dictionary of how many friends each person has. People can have 0 to many friends. However, there won't be repeat relationships like [A,B] and [B,A] and neither will there be more than 2 people in a relationship What is a loop that goes on forever? Infinite loop Recursively parse a string for a pattern that can be either 1 or 2 characters long Write a simple spell-checking engine Given two sentences, you have to print the words those are not present in either of the sentences.(If one word is present twice in 1st sentence but not present in 2nd sentence then you have to print that word too) Question: Find overlapping interval: A = [[1,3],[5,7], [8,12]] B = [[2,3],[4,9], [10,15]] # return [(2, 3), (5, 7), (8, 9), (10, 12)] m = len(A) n = len(B) ans = [] i, j = 0,0 while i < m and j < n: # left bound for intersecting segment l = max(A[i][0], B[j][0]) # right bound for intersecting segment r= min(A[i][1], B[j][1]) if l <= r: ans.append((l,r)) if A[i][1] < B[j][1]: i += 1 else: j += 1 print(ans)
areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50] # Add poolhouse data to areas, new list is areas_1 areas_1=areas+["poolhouse",24.5] print(areas_1) # Add garage data to areas_1, new list is areas_2 areas_2=areas_1+["garage",15.45] print(areas_2) #-------Inner workings of lists----# At the end of the video, Hugo explained how Python lists work behind the scenes. In this exercise you'll get some hands-on experience with this. The Python code in the script already creates a list with the name areas and a copy named areas_copy. Next, the first element in the areas_copy list is changed and the areas list is printed out. If you hit Run Code you'll see that, although you've changed areas_copy, the change also takes effect in the areas list. That's because areas and areas_copy point to the same list. If you want to prevent changes in areas_copy from also taking effect in areas, you'll have to do a more explicit copy of the areas list. You can do this with list() or by using [:]. #Change the second command, that creates the variable areas_copy, such that areas_copy is an explicit copy of areas. After your edit, changes made to areas_copy shouldn't affect areas. Hit Submit Answer to check this. # Create list areas areas = [11.25, 18.0, 20.0, 10.75, 9.50] # Create areas_copy areas_copy = list(areas) # Change areas_copy areas_copy[0] = 5.0 # Print areas print(areas)
name = 'Zophie a cat' newName = name[0:7] + 'the' + name[8:12] print(name) print(newName) # TUPLES son listas que no se pueden modificar newTuple = ('hola', 40, 0.5) type(('hola',)) # con esto mostramos que el valor es un tuple, al poner una coma(,) al final del string type(('hola')) # indica el valor del string en este caso -> str # Converting Types with the list() and tuple() Functions tuple(['cat', 'dog', 5]) # ('cat', 'dog', 5) list(('cat', 'dog', 5)) # ['cat', 'dog', 5] list('hello') # ['h', 'e', 'l', 'l', 'o'] # Converting a tuple to a list is handy if you need a mutable version of a tuple value. # References # Pasamos la lista spam a cheese, pero ambas quedan con el mismo ID, son la misma lista, al modificar una, se modifican ambas spam = [0, 1, 2, 3, 4, 5] cheese = spam cheese[1] = 'Hola!' print(spam) print(cheese) # Passing References deff eggs(someParameter):
def printTuple(): li=list()
print(dup_items) 6.Write a Python program to check a list is empty or not. a=[] if not a: print ('This list is empty') 7.Write a Python program to clone or copy a list. org_list=[10,22,4353,32,1] new_list=list(org_list) print(org_list) print(new_list) 8.Write a Python program to print a specied list after removing the 0th, 4th and 5th elements. Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] Expected Output : ['Green', 'White', 'Black'] colo=['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] colo = [x for (i,x) in enumerate(colo) if i not in (0,4,5)] print(colo) 9.Write a Python program to get the difference between the two lists.
q)/xkey - Set key on table q)`sym xkey trade q)deltas 2 3 5 7 9 2 1 2 2 2 q)/maxs - takes scalar, list, dictionary or table and returns the cumulative maximum of the source items. q)maxs 1 2 4 3 9 13 2 1 2 4 4 9 13 13 q)1 2 3 4 3 1 except 1 2 3 4 3 q)/fill (^) - takes an atom as its first argument and a list(target) as its second argument and return a list obtained by substituting the first argument for every occurrence of null in target q)42^ 9 18 0N 27 0N 36 9 18 42 27 42 36 update t set [a] [where c] sym:asc`AIG`CITI`CSCO`IBM`MSFT; ex:"NASDAQ" dst:`$":c:/q/test/data/"; /database destination @[dst;`sym;:;sym]; n:1000000; trade:([]sym:n?`sym;time:10:30:00.0+til
In contrast, adding one to every element of a NumPy array is far simpler: myarray = np.array([3, 6, 1, 0, 10, 22]) myarray_plus1 = myarray + 1 myarray_plus1 This won't work with normal lists. For example, if you ran `mylist + 1`, you'd get an error like this: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-19-5b3951a16990> in <module>() ----> 1 mylist + 1 TypeError: can only concatenate list (not "int") to list ``` We can do the same thing for subtraction, multiplication, etc.: print("Subtraction: \t" + str(myarray - 2)) print("Multiplication:\t" + str(myarray * 10)) print("Squared: \t" + str(myarray ** 2)) print("Square root: \t" + str(np.sqrt(myarray))) print("Exponential: \t" + str(np.exp(myarray))) ### Working with multiple arrays We can also easily do these operations for multiple arrays. For example, let's say we want to add the corresponding elements of two lists together. Here's how we'd do it with regular lists: list_a = [1, 2, 3, 4, 5]
if x[i] is None: x[i] = x[i-1] print(x) x =[None, None, 1, 2, None, None, 3, 4, None, 5, None, None] for i in range(len(x)): if x[i] is None: x[i] =x[i-1] Print (x) # Python Question 13: given two lists output the words that don't exist in both lists new_list = list(set(list1).difference(list2)) new_list = list(set(list1).intersection(list2)) # Python Question 14: Python to find N largest elements from a list Def top_n_elements (list1,N) l=list1.sort() Print (l[-n:]) # Python Question 15: Python to find second largest number in a list list1=[10,20,5,9,30] l=list1.sort() print(l[-2])
g = (n*2 for n in range(1000)) # Generator expression Type The type of resulting values are list and generator respectively: print(type(l)) # 'list' print(type(g)) # 'generator' ''' #Lambda and Map 1>>Celsius = [39.2, 36.5, 37.3, 37.8] Convert this python list to Fahrenheit using map and lambda expression:- Celsius = [39.2, 36.5, 37.3, 37.8] Fahrenheit = [ x*(9/5) + 32 for x in Celsius ] print(Fahrenheit) 2>>Apply an anonymous function to square all the elements of a list using map and lambda:- y=[2,5,7,8,9] z=list(map(lambda x:x**2,y)) print(z) #FILTER & REDUCE 1>>Filter out all the primes from a list:- listPri = [1,2,3,4,7,9,11,14,15,17,18,19,22,27] def isPrime(x): c=0 for i in range(2,x): if x%i==0: c=1 break if c!=1: return True else:
In the previous exercise, you used lambda functions to anonymously embed an operation within map(). You will practice this again in this exercise by using a lambda function with filter(), which may be new to you! The function filter() offers a way to filter out elements from a list that don't satisfy certain criteria. Your goal in this exercise is to use filter() to create, from an input list of strings, a new list that contains only strings that have more than 6 characters. Instructions 100 XP In the filter() call, pass a lambda function and the list of strings, fellowship. The lambda function should check if the number of characters in a string member is greater than 6; use the len() function to do this. Assign the resulting filter object to result. Convert result to a list and print out the list. ------------------------------------------------------------------------ # Create a list of strings: fellowship fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf'] # Use filter() to apply a lambda function over fellowship: result result = filter(lambda fellowship : len(fellowship) > 6, fellowship) # Convert result to a list: result_list result_list = list (result) # Print result_list print(result_list)
As we store more items (piecies of information) in a variable, we need a way to get specific pieces of information back out of that list. To obtain a specific item or specific set of items from a list, we will use the process of **indexing**. <div class="alert alert-success"> Indexing refers to selecting an item from within a collection. Indexing is done with square brackets. </div> For example, what if we had a class with 5 students in it. We could store their first names in a list called `students`: # Define a list students = ['Julian', 'Amal', 'Richard', 'Juan', 'Xuan'] If we wanted to know who the first student in our list was, we could **index** that value from the list. To do so, we would use square brackets after the variable name and specify the position from the list that we want to index. If we want the first item in the list, we'll use the number '0'. This is because Python is zero-based. This means that counting starts with 0. The second item in the list could be accessed with the number '1'. Thus, to return the first student in the list ('Julian'), we would index `students[0]`: # Indexing: Count forward, starting at 0, with positive numbers print(students[0]) Similarly, if we wanted the second student in the list, we would index with `students[1]`: # Indexing second student in list print(students[1]) ### Negative Indexing **Negative indexing** is also possible - you *can* count backward from the end of the list. In this case '-1' refers to the last item in the list and indexing counts from there. So, the second to last item in the list would be '-2'. Thus, to return the last student in the list, we would use `students[-1]`:
-You can access items via their index list_name[1] --> item2 -You can change values at will zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"] zoo_animals[2] = "hyena" -->["pangolin", "cassowary", "hyena", "tiger"] -Manipulate the list -.append() -adds value to end of list -.pop() -removes value at certain index -.removes(x) -removes x if it's in a list' -del(n[1]) -deletes but doesn't return anything' -You can directly add to a list by append variables -x = list("a") x.append("b","g") --> ["a","b","g"] -Insert items into list at certain index using .insert animals = ["ant", "bat", "cat"] animals.insert(1, "dog") --> ["ant", "dog", "bat", "cat"] Take a portion of a list using slice. Includes 1st, excludes 2nd value letters = ['a', 'b', 'c', 'd', 'e'] slice = letters[1:3] --> ['b', 'c'] -You can even include all data before or after a certain index -my_list[:2] -Includes all indices before position 2
arr = ["a", "b", "c", "d"] arr2 = ["x", "y", "z"] arr3 = arr + arr2 arr3 #> ["a", "b", "c", "d", "x", "y", "z"] Sort a list: arr = [6,3,8] arr.sort() # this is mutating arr #> [3, 6, 8] arr.reverse() # this is mutating arr #> [8, 6, 3] Remove duplicate values in a list by converting it to another datatype called a "Set" and then converting it back to a "List": arr = [1,2,2,2,3] arr2 = list(set(arr)) arr2 #> [1, 2, 3] list(set(["hello", "hello", "hello"])) #> ['hello'] A list can be iterated, or "looped" using a for ... in ... statement: for letter in ["a", "b", "c", "d"]: print(letter) #> a #> b #> c #> d
'Timothy Davidson', 'Jessica Lee', 'Christopher Miller', 'Lisa Grant', 'Ryan Chan', 'Gary Carson', 'Anthony Mitchell', 'Jacob Turner', 'Jennifer Bonilla', 'Rachel Gonzalez', 'Andrew Clark', 'Richard Pearson', 'Glenn Allen'] # Write your append statement under this comment list(staff) # Prints `staff` in a vertical list format to check that the name was added. The list() function will print our list in an easier to read format than the print() function. We can also add an item to the end of a [list](https://docs.tdm-pilot.org/key-terms/#list) by using an [assignment statement](https://docs.tdm-pilot.org/key-terms/#assignment-statement). # Adding an item to a list using an assignment statement staff = staff + ['Einhorn Finkle'] # Concatenate name_list with the list ['Einhorn Finkle'] list(staff) ## The `insert()` Method The `insert()` [method](https://docs.tdm-pilot.org/key-terms/#method) is similar to `append()` but it takes an [argument](https://docs.tdm-pilot.org/key-terms/#argument) that lets us choose an [index number](https://docs.tdm-pilot.org/key-terms/#index-number) to insert the new item. # Using the insert() method to add an item at a specific index number staff = ['Tara Richards', 'Tammy French', 'Justin Douglas',
Both the ordering and the visualization of the data will be done automatically. #!/usr/bin/python3 import pandas as pd d = {} for i in range(11): user = input("Enter the student's name followed by their final mark: ") data = user.split() d[data[0]] = int(data[1]) marks = pd.DataFrame(list(d.items()), columns=['Student_Name','Final_Mark']) print(marks) print("The class average is", marks.mean()) print(marks.stack()) print(marks.plot(kind='bar', color = 'g')) # 'color' function changes the color of the bar print(marks.plot(kind='barh', stacked=True, alpha=0.5)) =================================================================== Inventory Program ====================================================== This program creates an inventory that allows the user to enter as much information into the inventory as they need. Once the information is entered, it is automatically displayed back to the user in a ordered list. In addition, The program asks the user to enter in their username, If their username contains numbers, the program asks the user to only enter in a username that contains letters.
# single-line if statement (sometimes discouraged) if x > 0: print('positive') # single-line if/else statement (sometimes discouraged), known as a 'ternary operator' 'positive' if x > 0 else 'zero or negative' [<a href="#Python-Quick-Guide">Back to top</a>] ## Lists - **List properties:** ordered, iterable, mutable, can contain multiple data types # create an empty list (two ways) empty_list = [] empty_list = list() # create a list simpsons = ['homer', 'marge', 'bart'] **Examine a list:** # print element 0 simpsons[0] len(simpsons) **Modify a list (does not return the list):** # append element to end simpsons.append('lisa')
def make_deck(n): """ Makes a deck from 1 to n """ return list(range(1, n+1))
a) Some values in the Flight Number column are missing. These numbers are meant to increase by 10 with each row so 10055 and 10075 need to be put in place. Fill in these missing numbers and make the column an integer column df['FlightNumber'] =df['FlightNumber'].interpolate().astype(int) print(df) b) The From_To column would be better as two separate columns! Split each string on the underscore delimiter _ to give a new temporary Data Frame with the correct values. Assign the correct column names to this temporary Data Frame. temp=df.From_To.str.split('_',expand=True) temp.columns=['From','To'] df=df.drop('From_To',axis=1) df=df.join(temp) c) In the Airline column, you can see some extra punctuation and symbols have appeared around the airline names. Pull out just the airline name. E.g. '(British Airways. )' should become 'British Airways'. df['Airline']=df['Airline'].str.extract('([a-zA-Z\s]+)',expand=False).str.strip() print(df) Given the lists letters = ['A', 'B', 'C'] and numbers = list(range(10)),construct a Multi Index object from the product of the two lists. Use it to index a Series of random numbers. Call this Series s. letters = ['A', 'B', 'C'] numbers = list(range(10)) mi=pd.MultiIndex.from_product([letters,numbers]) s=pd.Series(np.random.rand(30),index=mi) print(s) a) Select the labels 1, 3 and 6 from the second level of the Multi Indexed Series. s.loc[:,[1,3,6]] b) Slice the Series s; slice up to label 'B' for the first level and from label 5 onwards for the second level.
###Try and Except (Error Handling): If an error is encountered in try block, then the try block code execution is stopped and transfered down to the except block. You can also add finally block, which will get executed regardless of whether an exception occurs. Example: try: index = moves.find('D') except ValueError: return False ###Built-In Function: 1. enumerate(iterable, start = 0): Example: >>> 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')] 2. convert binary representation back to integers: int(b,2) 3. all(iterable) return True if all elements of the iterable are true example: if all(ch in A for ch in word.lower()): 4. zip(s,t): takes two or more sequences and returns a list of tuples. Most commonly used in a for loop: s = 'abc' t = [0,1,2] for pair in zip(s,t):
def convert(string): a=list(string.split(' ')) return a
Q1. Convert a Tuple t = (1,2,3,4,5) to a list Sol1. t = (1,2,3,4) l = list(t) print(l) ------------------------------------------------------- Q2. WAP to join a list and a tuple: L = [1,3,5,7] T = (8,6,4,2) Store the result in a list LS Sol2. L = [1,3,5,7] T= (8,6,4,2) LT = L + list(T) print(LT) ---------------------------------------------------------- Q3. What is difference between list and tuple. Sol3. List | Tuple - mutable immutable --------------------------------------------------------------
between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: Consider use range(#begin, #end) method Solution: l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) #----------------------------------------# print(list(filter(lambda i :i%7==0 and i%5!=0 ,list(range(2000,3201))))) #----------------------------------------# Question 2 Level 1 Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
['1', '2', '3', '3', '4', '6', '7'] 1 is an smallest number and the largest number is 7 2.Check a list is empty or not In [10]: l=input('enter the list elements') if len(l)==0: print('the list is empty') else: print('the list contains some elements ') enter the list elements the list is empty 3.To clone or copy the list In [17]: a=list(input('enter the list elements')) b=a #b=a.copy() print(b) a.append('h') print(b) print(a) enter the list elements829233992 ['8', '2', '9', '2', '3', '3', '9', '9', '2'] ['8', '2', '9', '2', '3', '3', '9', '9', '2', 'h'] ['8', '2', '9', '2', '3', '3', '9', '9', '2', 'h'] 4.Removing even numbers from a list In [21]: l=list(input('enter the elements of the list')) for i in l: if int(i)%2==0:
def printList(): li=list()
--- configure.py.orig 2011-10-24 19:51:31.000000000 +0000 +++ configure.py 2011-10-24 19:52:25.000000000 +0000 @@ -58,7 +58,7 @@ self.include_dir = os.path.join(self.build_dir, 'include') self.full_include_dir = os.path.join(self.include_dir, 'botan') - all_files = sum([mod.add for mod in modules], []) + all_files = sum([list(mod.add) for mod in modules], []) self.headers = sorted( [file for file in all_files if file.endswith('.h')]) @@ -290,7 +290,7 @@ for group in allowed_groups: to_obj.__dict__[group] = [] - for (key,val) in name_val_pairs.iteritems(): + for (key,val) in list(name_val_pairs.items()): to_obj.__dict__[key] = val def lexed_tokens(): # Convert to an interator @@ -320,7 +320,7 @@ raise LexerError('Group "%s" not terminated' % (group), lexer.lineno) - elif token in name_val_pairs.keys(): + elif token in list(name_val_pairs.keys()): to_obj.__dict__[token] = lexer.get_token() else: # No match -> error raise LexerError('Bad token "%s"' % (token), lexer.lineno) @@ -329,7 +329,7 @@ Convert a lex'ed map (from build-data files) from a list to a dict
dict1 = {} dict2 = {} for word in para: for st in range(len(word)): if word[st] in char_list: dict1[word[st]] = dict1[word[st]] + 1 else: char_list.append(word[st]) dict1[word[st]] = 1 dict2[word] = dict1 dict1 = {} char_list = [] list_dict2 = list(dict2) count = 0 anagrams_list = [] final_anagrams_list = [] for i in range(len(dict2)): for j in range(i+1, len(dict2)): for k in dict2[list_dict2[i]]: if k in dict2[list_dict2[j]]: if dict2[list_dict2[i]][k] == dict2[list_dict2[j]][k]: count += 1 if count == len(dict2[list_dict2[i]]) and count == len(dict2[list_dict2[j]]): anagrams_list.append(list_dict2[i]) anagrams_list.append(list_dict2[j]) count = 0
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. There are ways to make a copy, one way is to use the built-in List method copy(). Example: Make a copy of a list with the copy() method: thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) Another way to make a copy is to use the built-in method list(). Example Make a copy of a list with the list() method: thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist) Join Two Lists There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example Join two list: list1 = ["a", "b" , "c"] list2 = [1, 2, 3]