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)