946
Its handy to have a collection of useful little snippets when you are using any programming language. This is ours for python– work in progress as we various of them we have used over the years
Reverse a string
#!/usr/bin/python myString = "The string to be reversed" reverse_string = myString[::-1] print(reverse_string)
Is a number even or odd
#!/usr/bin/python def is_even(num): return num % 2 == 0 if (is_even(4)): print("even number") else: print("odd number") if (is_even(5)): print("even number") else: print("odd number")
Get the frequency of elements in a list
#!/usr/bin/python from collections import Counter numberlist = [1, 2, 3, 2, 4, 3, 2, 3, 1, 2, 4, 3, 1, 2, 1, 3, 4, 1, 2] count = Counter(numberlist) print(count)
Average of a list of numbers
#!/usr/bin/python def average(*args): return sum(args, 0.0) / len(args) print (average(5, 8, 2, 9, 7, 12, 6, 4)) print (average(2, 7, 3, 11, 4, 12, 8, 4))
Get the most frequent number in a list
#!/usr/bin/python def most_frequent_number(list): return max(set(list), key = list.count) numbers = [1, 2, 3, 2, 4, 3, 2, 3, 1, 2, 4, 3, 1, 2, 1, 3, 4, 1, 2] print (most_frequent_number(numbers))
Check for vowels in a a string
#!/usr/bin/python def get_vowels(string): return [each for each in string if each in 'aeiou'] print (get_vowels('A test string')) print (get_vowels('myrrh'))
Is a string a palindrome
#!/usr/bin/python def palindrome(a): return a == a[::-1] print (palindrome('anna')) print (palindrome('anne'))
Shuffle a list
#!/usr/bin/python from random import shuffle numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] shuffle(numbers) print(numbers)
Split a string into substrings
#!/usr/bin/python string_1 = "This is a sample string to split up" string_2 = "sample/ string / example/ number /2" # separator ' ' print(string_1.split()) # separator as '/' print(string_2.split('/'))
Combine a list of strings into one string
#!/usr/bin/python list_of_strings = ['This', 'is', 'a', 'sample', 'string'] # Using join with blank space print(' '.join(list_of_strings)) # Using join with the comma separator print(','.join(list_of_strings))