Basics Flashcards
lst = ["a", "b", "c", "d", "e"] lst[1:3] lst[:4] lst[3:] del(lst[0])
lst = ["a", "b", "c", "d", "e"] lst[1:3] --> ["b", "c"] lst[:4] --> ["a", "b", "c", "d"] lst[2:] --> ["c", "d", "e"] del(lst[0]) --> lst = ["b", "c", "d", "e"]
import numpy as np
arr = np.array([[1,2,3,4,5], [4,5,6,7,8]]) print (arr.shape) --> (2, 5) print (arr[0][2]) --> 3 print (arr[:, 1:3]) --> [[2, 3], [5,6]] print (arr[1, :]) --> [4,5,6,7,8]
arr = np.array([[1.27, 2.16, 3.32], [7.45, 6.12, 5.34]])
print (np.mean(arr[:,1]))
print (np.median(arr[:,1]))
arr = np.array([[1.27, 2.16, 3.32], [7.45, 6.12, 5.34]])
print (np.mean(arr[:,1])) –> 4.14
print (np.median(arr[:,1])) –> 4.14
in ruby –> a = []
3.times{|x| 3.times{|y| a «_space;[x,y] if x != y }}
a = (0..2).to_a.permutation(2).reject { |x| x[0] == x[1] }
–> [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
–> [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
in python --> a = [] for x in range(3): for y in range(3): if x != y: a += [(x,y)]
[(x,y) for x in xrange(3) for y in xrange(3) if x != y]
print(count_vowels(‘aertewrweroe uerue eiiera gf’))
–> 15
print(count_vowels(‘aertewrweroe uerue eiiera gf’))
import re
def count_vowels(s = ''): if isinstance(s, str): return sum(1 for _ in re.finditer(r'[aeoui]', s))
return sum(1 for val in s if val in “aeouiAEOUI”)
in ruby –> [(1,1), (2,4), (4,16)]
[1,2,3,4].select {|x| x != 3} . map! {|x| [x, x*x]}
in python –> [(1,1), (2,4), (4,16)]
[(x, x*x) for x in [1,2,3,4] if x != 3]
disemvowel(“This website is for losers LOL!”),”Ths wbst s fr lsrs LL!”)
in ruby –>
def disemvowel(str)
str.chars.select {|v| v.match(/[^aeouiAEOUI]/) }.join
end
return str.gsub(/[aeouiAEOUI]/, ‘’)
disemvowel(“This website is for losers LOL!”),”Ths wbst s fr lsrs LL!”)
in python --> import re def disemvowel(string): re.sub(r'[aeouiAEOUI]', '', string) # re.sub(r'[aeoui]', '', string, flags=re.IGNORECASE)
return ““.join(c for c in string if c.lower() not in “aeoui”)
is_square(-1)#, "Negative numbers cannot be square numbers") (is_square( 3) is_square( 4) is_square(25) is_square(86)
ruby –>
def is_square(n)
n < 0 ? false : Math.sqrt(n) % 1 == 0
end
is_square(-1)#, "Negative numbers cannot be square numbers") (is_square( 3) is_square( 4) is_square(25) is_square(86)
python --> def is_square(n): n > 0 and (n**0.5).is_integer()
print(make_int(“123”))
print(make_int(“00123”))
print(make_int(“1.23”))
print(make_int(“-123”))
Output
#123 #123 #-1 #-1
print(make_int(“123”))
print(make_int(“00123”))
print(make_int(“1.23”))
print(make_int(“-123”))
Output
#123 #123 #-1 #-1
using ternary operator for Python3
def make_int(string): return string.isdigit() and string or -1
Tests
print(make_nametag(“Scott”, “Python”))
print(make_nametag(“Joe”, “games”))
print(make_nametag(“John”, “programming tips”))
Output
#Hi! My name is Scott. This lecture covers Python. #Hi! My name is Joe. This lecture covers games. #Hi! My name is John. This lecture covers programming tips.
Output
#Hi! My name is Scott. This lecture covers Python. #Hi! My name is Joe. This lecture covers games. #Hi! My name is John. This lecture covers programming tips.
def make_nametag(first_name, topic):
“””
Given two strings first_name and topic,
return a string of the form ““Hi! My name
is XXX. This lecture covers YYY.” where
XXX and YYY are first_name and topic.
“””
return (“Hi! My name is {}. This lecture covers {}.”).format(first_name, topic)
Tests
example_string = “It’s just a flesh wound.”
print(is_substring(example_string, “just”))
print(is_substring(example_string, “flesh wound”))
print(is_substring(example_string, “piddog”))
print(is_substring(example_string, “it’s”))
print(is_substring(example_string, “It’s”))
Output
#True #True #False #False #True
Tests
example_string = “It’s just a flesh wound.”
print(is_substring(example_string, “just”))
print(is_substring(example_string, “flesh wound”))
print(is_substring(example_string, “piddog”))
print(is_substring(example_string, “it’s”))
print(is_substring(example_string, “It’s”))
Output
#True #True #False #False #True
is_substring(example_string, test_string):
return test_string in example_string
#return example_string.find(test_string) >= 0
# Enter code here primes = [2,3,5,7,11,13]
# Output #3 7 13
# Enter code here primes = [2,3,5,7,11,13]
# Output #3 7 13
for i in range(1, len(primes), 2):
print(primes[i])
count given word in text
print(word_count(“this pigdog is a fine pigdog”, “pigdog”))
print(word_count(“this pigdog is not a dog”, “dog”))
print(word_count(“this pigdog is not a pig”, “pigdog”))
# Output #2 #1 #1
print(word_count(“this pigdog is a fine pigdog”, “pigdog”))
print(word_count(“this pigdog is not a dog”, “dog”))
print(word_count(“this pigdog is not a pig”, “pigdog”))
# Output #2 #1 #1
def word_count(text, word): return text.split().count(word)
list(range(0,5))
list(range(0,5) –> [0,1,2,3,4]
write a function which calculates the sum of the numbers in a list which are NOT divisible by 3)
print(strange_sum([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]))
print(strange_sum(list(range(123)) + list(range(77))))
print(strange_sum([1, 2, 3, 4, 5, 1, 2, 3, 4, 5])) –> 24
print(strange_sum(list(range(123)) + list(range(77)))) –> 6994
def strange_sum(numbers): return sum([x for x in numbers if x % 3 != 0])
lst = list(range(0,5)) --> [0,1,2,3,4] lst2 = [11,12,13] lst.insert(2, 10) lst.extend(lst2) lst.pop() lst.pop(3) lst.remove(0) lst[1:3] = [0, 0, 0]
lst = list(range(0,5)) --> [0,1,2,3,4] lst2 = [11,12,13] lst.insert(2, 10) --> lst = [0,1,10,3,4] lst.extend(lst2) --> lst = [0,1,10,3,4,11,12,13] lst.pop() --> lst = [0,1,10,3,4,11,12] lst.pop(3) --> lst = [0,1,10,4,11,12] lst.remove(0) --> lst = [1,10,4,11,12] lst[1:3] = [0, 0, 0] --> lst = [1, 0, 0, 0, 11, 12]
Solution - Shuffle the items in a list
example_list = [2, 3, 5, 7, 11, 13]
print(example_list)
# Enter update code here ? print(example_list)
#[2, 3, 5, 7, 11, 13] #[11, 2, 7, 5, 13, 3]
import random
example_list = [2, 3, 5, 7, 11, 13]
print(example_list)
random.shuffle(example_list)
print(example_list)
#[2, 3, 5, 7, 11, 13] #[11, 2, 7, 5, 13, 3]
Template - Flatten a nested list
# Test code print(flatten([])) print(flatten([[]])) print(flatten([[1, 2, 3]])) print(flatten([["cat", "dog"], ["pig", "cow"]])) print(flatten([[9, 8, 7], [6, 5], [4, 3, 2], [1]]))
# Output #[] #[] #[1, 2, 3] #['cat', 'dog', 'pig', 'cow'] #[9, 8, 7, 6, 5, 4, 3, 2, 1]
# Test code print(flatten([])) print(flatten([[]])) print(flatten([[1, 2, 3]])) print(flatten([["cat", "dog"], ["pig", "cow"]])) print(flatten([[9, 8, 7], [6, 5], [4, 3, 2], [1]]))
# Output #[] #[] #[1, 2, 3] #['cat', 'dog', 'pig', 'cow'] #[9, 8, 7, 6, 5, 4, 3, 2, 1]
def flatten(nested_list): new = [] for lst in nested_list: for i in range(len(lst)): new.append(lst[i]) return new
or
def flatten(nested_list): flattened_list = [] for sub_list in nested_list: flattened_list.extend(sub_list) return flattened_list
Writing fibonacci serie for 20 element.
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946]
fib = [0,1]
for i in range(20):
fib.append(fib[-1] + fib[-2])
print(fib)
def accum(s): # your code here
print(accum(‘abcd’))
print(accum(“ZpglnRxqenU”))#, “Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu”))
def accum(s): return [x.upper() + x * i for i,x in enumerate(s)]
print(accum(‘abcd’))
print(accum(“ZpglnRxqenU”))#, “Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu”))
return square of each digit as integer
print(square_digits(9119))#, 811181)
print(square_digits(9119))#, 811181)
def square_digits(num): string = '' for x in str(num): string += str(int(x) ** 2) return string
#return ““.join([str(i) for i in [int(char) ** 2 for char in str(num)]])
print(Descending_Order(0))#, 0)
print(Descending_Order(15736))#, 51)
print(Descending_Order(123456789))#, 987654321)
print(Descending_Order(0))#, 0)
print(Descending_Order(15736))#, 51)
print(Descending_Order(123456789))#, 987654321)
def Descending_Order(num): return int("".join(list(reversed(sorted([ x for x in str(num)])))))
or return int("".join(sorted(list(str(num)), reverse=True)))
check the number of x and o’s are equal or not
print(xo(‘xo’)) –> true
print(xo(‘xoOM’)) –> false
print(not xo(‘xxxoo’)) –> true
print(xo(‘xo’)) –> true
print(xo(‘xoOM’)) –> false
print(not xo(‘xxxoo’)) –> true
import re def xo(s): return len(re.findall('[oO]', s)) == len(re.findall('[xX]', s))
without regex –>
s = s.lower()
return s.count(‘o’) == s.count(‘x’)
for a = 1 … z = 26
print(words_to_marks(‘attitude’))#, 100)
print(words_to_marks(‘friends’))#, 75)
print(words_to_marks(‘attitude’))#, 100)
print(words_to_marks(‘friends’))#, 75)
def words_to_marks(s): res = 0 lst = [chr(i) for i in range(ord('a'), ord('z')+1)] for x in range(len(s)): res += lst.index(s[x]) + 1 return res
alternative solutions –>
return sum(‘_abcdefghijklmnoqprstuvyz’.index(e) for e in s)
return sum(ord(c)-96 for c in s)
remove the wovels and count the max of sum of index of letters upto any wovel.
print(solve(“zodiac”))#,26)
print(solve(“cautchphrase”))#,73)
print(solve(“zodiac”))#,26)
print(solve(“cautchphrase”))#,73)
def solve(s): lst = list(s) num = list('_abcdefghijklmnopqrstuvwxyz') count = 0 arr = [] for x in lst: for first in "aeiou": if x == first: lst[lst.index(x)] = '' arr.append(count) count = 0 if x.lower() not in "aeoui": count += num.index(x)
return max(arr)
remove the wowels
print(solve(“zodiac”)) –> [‘z’, ‘d’, ‘c’]
print(solve(“chruschtschov”)) –> [‘chr’, ‘schtsch’, ‘v’]
print(solve(“zodiac”)) –> [‘z’, ‘d’, ‘c’]
print(solve(“chruschtschov”)) –> [‘chr’, ‘schtsch’, ‘v’]
import re def solve(s): return re.split('[aeoui]+', s)
print(persistence(39))#, 3)
39 = 27 –> 27 = 14 –> 1*4 = 4 –> 3 times
print(persistence(4))#, 0)
print(persistence(25))#, 2)
print(persistence(39))#, 3)
print(persistence(4))#, 0)
print(persistence(25))#, 2)
import numpy as np
def persistence(num): arr = [int(x) for x in str(num)] count = 0 while len(arr) > 1: data = np.multiply.reduce(arr) arr = [int(x) for x in str(data)] count += 1 return count
check the number is Prime?
print(is_prime(0))#, False, ‘0 is not prime’)
print(is_prime(1))#, False, ‘1 is not prime’)
print(is_prime(17))#, True, ‘17 is prime’)
print(is_prime(0))#, False, ‘0 is not prime’)
print(is_prime(1))#, False, ‘1 is not prime’)
print(is_prime(17))#, True, ‘17 is prime’)
def is_prime(num) if num < 2: return False for i in range(2,num): if num % i == 0: return False return True
print(alphabet_position(“The sunset sets at twelve o’ clock.”))#, “20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11”))
def alphabet_position(text): lst = [] for c in text.lower(): if c.isalpha(): lst.append(ord(c)-96)
return lst
or shortly
return [str(ord(c)-96) for c in text.lower() if c.isalpha()]
Programming language popularity, from www.tiobe.com/tiobe-index
popularity = [[“Language”, 2017, 2012, 2007, 2002, 1997, 1992, 1987],
[“Java”, 1, 2, 1, 1, 15, 0, 0],
[“C”, 2, 1, 2, 2, 1, 1, 1],
[“C++”, 3, 3, 3, 3, 2, 2, 5],
[“C#”, 4, 4, 7, 13, 0, 0, 0],
[“Python”, 5, 7, 6, 11, 27, 0, 0],
[“Visual Basic .NET”, 6, 17, 0, 0, 0, 0, 0],
[“PHP”, 7, 6, 4, 5, 0, 0, 0],
[“JavaScript”, 8, 9, 8, 7, 23, 0, 0],
[“Perl”, 9, 8, 5, 4, 4, 10, 0]]
format_string = “ {:>4} {:>4} {:>4} {:>4} {:>4} {:>4} {:>4}”
# Display langauges table headers = popularity[0] header_row = format_string.format(*headers) print(header_row) print("-" * len(header_row))
for language in popularity[1:]:
print(format_string.format(*language))
print(“”)
difference between range() vs xrange?
for i in range(0, 20):
for i in xrange(0, 20):
range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.
xrange is a sequence object that evaluates lazily.
in python3, range does the equivalent of python’s xrange
Pascal’s triangle - 5 level
Binary search tree algorithm
class Solution(object): def generate(self, num_rows): """ :type numRows: int :rtype: List[List[int]] """ res = [] if num_rows == 0: return res tmp = [] for j in range(num_rows): tmp = [1] + tmp for i in range(1, len(tmp)-1): tmp[i] += tmp[i+1]
return tmp
sol = Solution()
print sol.generate(5)
–> [1, 4, 6, 4, 1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
For example, if condition checks bool(item%2) should return:
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] –> [None, 1, None, 3, None, 5, None, 7, None, 9, None]
new_items = [x if x % 2 else None for x in items]
Given an integer n, write a function that returns count of trailing zeroes in n!.
Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.
def zeros(n): from functools import reduce if n == 0: return 0 fac = [x for x in range(1, n+1)] res = reduce(lambda x, y: x*y, fac) return len(str(res)) - len(str(res).rstrip('0'))
# faster def findTrailingZeros(n):
# Initialize result count = 0
# Keep dividing n by # powers of 5 and # update Count i=5 while (n/i>=1): count += int(n/i) i *= 5
return int(count)
# recursive def zeros(n): x = n//5 return x + zeros(x) if x else 0
print(zeros(0))#, 0, “Testing with n = 0”)
print(zeros(6))#, 1, “Testing with n = 6”)
print(zeros(30000))#, 7, “Testing with n = 30”)
Warrior game!
class Warrior: def \_\_init\_\_(self): self.health = 50 self.attack = 5
@property def is_alive(self) -> bool: return self.health >= 0
class Knight(Warrior): def \_\_init\_\_(self): super().\_\_init\_\_() self.attack = 7
def fight(unit_1, unit_2):
while unit_1.is_alive and unit_2.is_alive:
unit_2.health -= unit_1.attack
if unit_2.is_alive:
unit_1.health -= unit_2.attack
return unit_1.is_alive
chuck = Warrior() chucky = Warrior() bruce = Knight()
print(fight(chuck, chucky)) # == True
print(chuck.is_alive) #== True
print(chucky.is_alive) #== False
isinstance() issubclass() type() \_\_class\_\_ \_\_class\_\_.\_\_name\_\_
isinstance(‘a’, str) –> True
isinstance(5.2, (int, float)) –> True
issubclass(bool, int) –> True
issubclass(str, int) –> False
class Car: def \_\_init\_\_(self, name): self.name = name
mycar = Car(name="audi") type(mycar) --> (python 3) type(mycar) --> (python 2.7) mycar.\_\_class\_\_ --> mycar.\_\_class\_\_.\_\_name\_\_ --> 'Car'
a python generator –> yield definition
def square1(data): arr = [] for i in data: arr.append(i*i) return arr
def square2(data): for i in data: yield i*i
data = [1,2,3,4,5] nums = square2(data) == [x*x for x in data]
print square1(data) –> [1, 4, 9, 16, 25]
print next(nums) --> 1 print next(nums) --> 4 print next(nums) --> 9 print next(nums) --> 16 print next(nums) --> 25
for num in nums: print num --> 1 4 9 16 25
find max x, y with lambda function
find max x, y
def max(x,y): if x > y: return x else: return y
max = lambda x,y: x if x>y else y
print max(8, 5) –> 8
use map to calculate the square of items in a list
n = [1, 2, 3, 4, 5]
print square(n) –> [1, 4, 9, 16, 25]
n = [1, 2, 3, 4, 5]
def square(arr): return [x*x for x in arr]
print square(n)# –> [1, 4, 9, 16, 25]
map(function(x), list)
print list(map(lambda x: x*x, n))# --> [1, 4, 9, 16, 25] print list(map(square, n))# --> [1, 4, 9, 16, 25]
calculate the multiplication of the elements
n = [1, 2, 3, 4, 5] –> 120
reduce(function(x,y), list)
from functools import reduce
n = [1, 2, 3, 4, 5]
print reduce(lambda x,y: x*y, n)# –> 120
def mult(n): prod = n[0] for i in range(1,len(n)): prod = prod * n[i] return prod
print mult(n)# –> 120
reverse a string
reverse a string
name = ‘hello’
print name[::-1] –> ‘olleh’
class @property and setter method application
class Circle():
def \_\_init\_\_(self, diameter): self.diameter = diameter
@property def radius(self): return self.diameter / 2
@radius.setter def radius(self, radius): self.diameter = radius * 2
circ = Circle(20) print(circ.diameter) --> 20 # print circ.radius circ.radius = 30 print(circ.diameter) --> 60
Python isbetween two numbers check?
if 1000 <= number <= 3000:
pass
if not number in range( 1000, 3001):
pass
print anagrams(‘abba’, [‘aabb’, ‘abcd’, ‘bbaa’, ‘dada’])#, [‘aabb’, ‘bbaa’])
print anagrams(‘racer’, [‘crazer’, ‘carer’, ‘racar’, ‘caers’, ‘racer’])#, [‘carer’, ‘racer’])
print anagrams(‘abba’, [‘aabb’, ‘abcd’, ‘bbaa’, ‘dada’])#, [‘aabb’, ‘bbaa’])
print anagrams(‘racer’, [‘crazer’, ‘carer’, ‘racar’, ‘caers’, ‘racer’])#, [‘carer’, ‘racer’])
def anagrams(word, words): final = [] sorted_word = ''.join(sorted(word)) for wo in words: if ''.join(sorted(wo)) == sorted_word: final.append(wo) return final
def anagrams(word, words): return [item for item in words if sorted(item) == sorted(word)]
def anagrams(word, words): return filter(lambda x: sorted(word) == sorted(x), words)
form will be a matrix like [[A1, A2, A3, ..], [B1, B2, B3, ..]] until AA, AB,…ZY, ZZ
to be called with class directly
print SpreadSheetHelper()..convert_to_display((2, 1))#, "C2") print SpreadSheetHelper()..convert_to_internal("C2")#, (2, 1)) print SpreadSheetHelper().convert_to_display((0,0))#, (2, 1))
form will be a matrix like [[A1, A2, A3, ..], [B1, B2, B3, ..]] until AA, AB,…ZY, ZZ
print SpreadSheetHelper()..convert_to_display((2, 1))#, "C2") print SpreadSheetHelper()..convert_to_internal("C2")#, (2, 1))
import string
class SpreadSheetHelper(object): arr = []
@classmethod def convert_to_display(cls, internal): """ Converts an internal coordinate into a display coordinate internal is in the form (row, column) returns a string in the form "CR" where C is the column display name, and R is the row display name """ # form will be a matrix like [[A1, A2, A3, ..], [B1, B2, B3, ..]] alp = string.ascii_uppercase[:] ar2 = [] for l in alp: for idx, val in enumerate(alp): ar2.append(l + val) final = list(alp) + ar2 nums = [str(i) for i in list(range(1,len(final)+1))] for a in final: cls.arr.append([a + x for x in nums]) return cls.arr[internal[0]][internal[1]] # return list(alp).zip(list(len(alp))) # return "A1" @classmethod def convert_to_internal(cls, display): """ Converts a display coordinate into an internal coordinate internal is in the form string "CR" where C is the column display name, and R is the row display name returns a tuple in the form (row, column) """ for idx, set in enumerate(cls.arr): for i, letnum in enumerate(set): if letnum == display: return (idx, i)
Python tricks
if not – for strings
regex usage
set multiple variables by splitting a string
if not – for strings (means if empty)
result = [””, “”]
if not result[0]: print False –> False
regex usage
cell = ‘Z9’
pat = re.compile(r”^([A-Z]+)([1-9]\d*)$”)
print pat.match(cell).groups() –> (‘Z’, ‘9’)
set multiple variables by splitting a string
cell = ‘Z9’
col, row = cell
print col, row –> Z 9
if __name__ == ‘__main__’:
if __name__ == ‘__main__’:
when you run a.py from command line it starts from the first line reading the code.
If this .py file are imported by other .py files, the code under “the if statement” will not be executed.
If this .py are run by python this_py.py under shell, or double clicked in Windows. the code under “the if statement” will be executed.
It is usually written for testing. print \_\_name\_\_ --> \_\_main\_\_ when called as a module from another .py file, it writes the name of the file called.
Closest numbers sorting algo
print(closest([1, 3, 5, 12, 56, 76])) –> [1,3,3,5]
print(closest([-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854])) –> [-20, 30]
print(closest([1, 3, 5, 12, 56, 76])) –> [1,3,3,5]
print(closest([-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854])) –> [-20, 30]
def closest(arr): s = sorted(arr) new = [] result = [] pairs = list(zip(s, s[1:])) for i in pairs: new.append(abs(i[1] - i[0])) count_arr = [x for x in new if x == min(new)] for c in count_arr: idx = new.index(c) new[idx] = 0 result.append(pairs[idx])
new_list = [] for el in result: new_list.extend([*el]) return new_list
The idea behind big O notation?
Big O notation is the language we use for talking about how long an algorithm takes to run.
With Big O notation, we use the size of the input, which we call “nn.” So we can say things like the runtime grows “on the order of the size of the input” O(n) or “on the order of the square of the size of the input” O(n^2)
brute force algorithm
A brute force algorithm finds a solution by trying all possible answers and picking the best one.
Say you’re a cashier and need to give someone 67 cents (US) using as few coins as possible. How would you do it?
You could try running through all potential coin combinations and pick the one that adds to 67 cents using the fewest coins. That’s a brute force algorithm, since you’re trying all possible ways to make change.
Brute force solutions are usually very slow since they involve testing a huge number of possible answers.
Python list reverse iteration
Python list reverse iteration
arr = [3, 6, 8, 9]
for i in range(len(arr), 0, -1):
print(arr[i-1]) –> 9 8 6 3
for i in arr[::-1]:
print(i) –> 9 8 6 3
print(nextnum([9,9,8,7,9]))# –> [9, 9, 8, 8, 0]
print(nextnum([1, 9, 9, 9]))# –> [2, 0, 0, 0]
print(nextnum([9,9,8,7,9]))# –> [9, 9, 8, 8, 0]
print(nextnum([1, 9, 9, 9]))# –> [2, 0, 0, 0]
def nextnum(arr): carry = 1 result = [] for i in arr[::-1]: sum = i + carry result.append(sum%10) carry = sum//10 if carry: result.append(1)
return result[::-1]
find first n fibonacci numbers
print(fibs(10)) –> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print(fibs) –> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
a,b = 1,1 fibs = [] for i in range(0,10): fibs.append(a) a, b = b, a+b
recursive def fibs(n): if n == 0: return 0 elif n == 1: return 1 else: return fibs(n-2) + fibs(n-1)
using timeit for a method definition
import timeit
setup = ''' def fib(n): a,b = 1,1 for i in range(n-1): a,b = b, a+b return a '''
print min(timeit.Timer(‘fib(10)’, setup=setup).repeat(7, 1000))
timeit direct in py file
import timeit
def fibs(n): if n == 0: return 0 elif n == 1: return 1 else: return fibs(n-2) + fibs(n-1)
print fibs(10)
if __name__ == ‘__main__’:
import timeit
t1 = timeit.Timer(“fibs(5)”, “from __main__ import fibs”)
print (“it ran:”, t1.timeit(number=1000), “miliseconds”)
method assertion for testing?
def fac(n): assert n>=0, "n asla negatif bir sayi olamaz" if n == 1: return 1 else: return fac(n-1) * n
print fac(-5) –> AssertionError: n asla negatif bir sayi olamaz
create an array consisting of 0’s and 1’s randomly
create an array consisting of 0’s and 1’s randomly
import numpy as np
arr = np.hstack((np.ones(5),np.zeros(6)))
np.random.shuffle(arr)
print arr # [ 0. 0. 0. 1. 0. 1. 0. 0. 1. 1. 1.]
# alternative a = np.ones(5+7) a[:7] = 0 np.random.shuffle(a) print a # [ 0. 0. 0. 1. 0. 0. 1. 1. 1. 0. 1. 0.]
# pythonic ar = np.array([0]*5 + [1]*7) np.random.shuffle(ar) print ar # [0 1 1 1 0 0 1 1 0 1 0 1]
Timeit with using partial and scatter a plot
import timeit
from functools import partial
fig_size = plt.rcParams['figure.figsize'] fig_size[0] = 12 fig_size[1] = 12 plt.rcParams['figure.figsize'] = fig_size
def maxi(arr): maxi = [] for i in range(len(arr)): for j in range(1,len(arr)): maxi.append(arr[i]*arr[j]) return maxi
if __name__==’__main__’:
complexity = []
size = []
for i in range(2,10):
arr = [n for n in np.random.rand(i)] n = arr[-1] t1 = timeit.Timer(partial(maxi, arr)) timespent = t1.timeit(number=1000) complexity.append(timespent) size.append(i) print ("it ran:", timespent, "miliseconds") plt. scatter(size, complexity, color='black', marker='^') plt. show()
Lowercase Alphabet in Python
A = string.ascii_lowercase[:]
print A –> ‘abcdefghijklmnopqrstuvwxyz’
use of *, also in def as argument like *args, **kwargs
use of *, also in def as argument like *args, **kwargs
def foo(bar, lee): print bar, lee
arr = [1, 2]
foo(*arr) –> 1 2
def new(*args): for i in args: print i
new(1,2,3)
- -> 1
- -> 2
- -> 3
def new2(**kwargs): for i in kwargs: print i, kwargs[i]
new2(name=’one’, age=27)
- -> age 27
- -> name one
Python string manipulation
sentence = “To be or not to be”
sentence = “To be or not to be”
splitted = sentence.split(“ “)
set(splitted) –> [“To”, “be”, “or”, “not”, “to”] (find the unique words in text)
x.istitle() –> if first letter is capital
x.startswith(‘s’)
x.endswith(‘s’)
text.isupper()
text.islower()
text.capitalize()
text.swapcase()
text.isalpha() – check for alphanumeric (cons. of alphabet onyl)
text.isdigit() – consisting of number as strings?
text.isalnum() – consisting of numbers and alphabet
text.strip(), text.lstrip(), text.rstrip() –> clean text
text.find(s) – find a substring –> gives the index
text.rfind(s) – reverse find (count from right side)
text.replace(u, t)
t = ‘ozzy’ –> list(t) –> [‘o’, ‘z’, ‘z’, ‘y’]
Python read a long txt file
Python read a long txt file
f = open(‘UNDR.txt”, ‘r’)
f.readlines() –> return first line
f.seek(0) –> reset reading position
text = f.read() –> store whole txt in text variable
f.read(n) –> read n characters
text.splitlines() –> split all lines in a list
f.write() –> if opened in ‘w’ mode