@@ -216,38 +216,50 @@ nltk.download('averaged_perceptron_tagger')
216216
217217### Anagrams
218218An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
219- ```
219+ ``` python
220220from collections import Counter
221221def anagram (first , second ):
222222 return Counter(first) == Counter(second)
223223anagram(" abcd3" , " 3acdb" ) # True
224224```
225225### Memory
226226This snippet can be used to check the memory usage of an object.
227- ```
227+ ``` python
228228import sys
229229
230230variable = 30
231231print (sys.getsizeof(variable)) # 24
232232```
233233### Print a string N times
234234This snippet can be used to print a string n times without having to use loops to do it.
235- ```
235+ ``` python
236236n = 2
237237s = " Programming"
238238print (s * n) # ProgrammingProgramming
239239```
240240### Chunk
241241This method chunks a list into smaller lists of a specified size.
242- ```
242+ ``` python
243243def chunk (list , size ):
244244 return [list[i:i+ size] for i in range (0 ,len (list ), size)]
245245```
246246### Get vowels
247247This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
248- ```
248+ ``` python
249249def get_vowels (string ):
250250 return [each for each in string if each in ' aeiou' ]
251251get_vowels(' foobar' ) # ['o', 'o', 'a']
252252get_vowels(' gym' ) # []
253+ ```
254+ ### Write to file
255+ This method takes in the `` name of file `` and `` content `` then write the content into the file. If the file doesn't exist then it creates the file.
256+ ``` python
257+ def write_to_file (filename , content ):
258+ try :
259+ with open (filename, " w+" ) as f:
260+ f.write(content)
261+ print (" Written to file successfully." )
262+ except Exception as e:
263+ print (" Failed to write to file with error: " )
264+ print (e)
253265```
0 commit comments