@@ -216,38 +216,50 @@ nltk.download('averaged_perceptron_tagger')
216
216
217
217
### Anagrams
218
218
An 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
220
220
from collections import Counter
221
221
def anagram (first , second ):
222
222
return Counter(first) == Counter(second)
223
223
anagram(" abcd3" , " 3acdb" ) # True
224
224
```
225
225
### Memory
226
226
This snippet can be used to check the memory usage of an object.
227
- ```
227
+ ``` python
228
228
import sys
229
229
230
230
variable = 30
231
231
print (sys.getsizeof(variable)) # 24
232
232
```
233
233
### Print a string N times
234
234
This snippet can be used to print a string n times without having to use loops to do it.
235
- ```
235
+ ``` python
236
236
n = 2
237
237
s = " Programming"
238
238
print (s * n) # ProgrammingProgramming
239
239
```
240
240
### Chunk
241
241
This method chunks a list into smaller lists of a specified size.
242
- ```
242
+ ``` python
243
243
def chunk (list , size ):
244
244
return [list[i:i+ size] for i in range (0 ,len (list ), size)]
245
245
```
246
246
### Get vowels
247
247
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
248
- ```
248
+ ``` python
249
249
def get_vowels (string ):
250
250
return [each for each in string if each in ' aeiou' ]
251
251
get_vowels(' foobar' ) # ['o', 'o', 'a']
252
252
get_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)
253
265
```
0 commit comments