blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
975fec797a263f6752b4f4d9cfabf16e910c7279
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/towers_of_hanoi.py
| 1,409 | 3.90625 | 4 |
"""
Proof: http://mathforum.org/library/drmath/view/55956.html
This problem is clearly a recursive problem:
- To move n disks from one pole to another, we must first move n-1 disks to the
helper pole and then move the n'th disk to the target pole. Finally, move the
n-1 disks from the helper pole to the target pole.
- We can see that the process to move n disks from the source to the target
is the same as moving n-1 disks from the source to the helper and the helper to
the source where instead of the target pole being the target, the helper pole
is now the target for the n-1 disks.
-This is why we can use recursion.
- The time complexity is O(2^n-1) as T(n) = 2*T(n-1) + 1 (one operation for
moving the n-th disk from source to target, T(n-1) operations to move the
n-1 disks twice: once from source to helper, once from helper to target)
which we can expand using recurrence relations to obtain (2^n) -1
"""
def towers_of_hanoi(n, source, helper=[], target=[]):
if n > 0:
towers_of_hanoi(n - 1, source, target, helper)
if source:
target.append(source.pop())
towers_of_hanoi(n - 1, helper, source, target)
# print([source, target, helper])
return source, helper, target
def main():
assert towers_of_hanoi(4, [4, 3, 2, 1]) == ([], [], [4, 3, 2, 1])
if __name__ == '__main__':
main()
|
f86543f779c92ba95efd9c5a4ddcab3303bbc82c
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/pascals_triangle.py
| 303 | 3.640625 | 4 |
def pascals(n):
triangle = [[1] * i for i in range(1, n + 1)]
for i in range(n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j]+triangle[i-1][j-1]
return triangle[-1]
def main():
assert pascals(6) == [1,5,10,10,5,1]
if __name__ == '__main__':
main()
|
0269f0236dfa291272c1925b4cf8d50578685e39
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/symmetrical_tree.py
| 1,083 | 3.96875 | 4 |
class Node(object):
def __init__(self, value):
self.value = value
self.children = []
def is_symmetrical(root):
return find_symmetry(root, root)
def find_symmetry(root1, root2):
if not (root1 or root2):
return True
if not (root1 and root2):
return False
if root1.value == root2.value:
if len(root1.children) == len(root2.children):
i = 0
j = len(root1.children)-1
res = True
while i < len(root1.children) and j > -1:
res = res and find_symmetry(root1.children[i], root2.children[j])
if not res:
return False
i += 1
j -= 1
return True
def main():
root = Node(1)
node2 = Node(2)
node22 = Node(2)
root.children.extend([node2, node22])
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node2.children.extend([node3, node4, node5])
node22.children.extend([node5, node4, node3])
assert is_symmetrical(root)
if __name__ == '__main__':
main()
|
5c67866d3212c69d8fb4e40e2fb5ce4e86f953b7
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/generate_all_ip_addresses.py
| 870 | 3.578125 | 4 |
def is_valid(string):
for sub in string.split("."):
if len(sub) > 3 or int(sub) < 0 or int(sub) > 255:
return False
if len(sub) > 1 and int(sub) == 0:
return False
if len(sub) > 1 and int(sub) != 0 and int(sub[0]) == 0:
return False
return True
def generate_ip(string):
temp = string
result = []
for i in range(1, len(string) - 2):
for j in range(i + 1, len(string) - 1):
for k in range(j + 1, len(string)):
temp = temp[:k] + "." + temp[k:]
temp = temp[:j] + "." + temp[j:]
temp = temp[:i] + "." + temp[i:]
if is_valid(temp):
result.append(temp)
temp = string
return result
def main():
assert generate_ip('1592551013') == ['159.255.101.3', '159.255.10.13']
|
92bd751ab4cfffe1d6b9861dc7e087ce9ce830be
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/calculate_angle.py
| 484 | 4.03125 | 4 |
def calculate_angle(hour, minute):
minute_angle = 6 * minute
hour_angle = (30 * hour + (30 * (minute/60))) % 360
print(minute_angle, hour_angle)
return hour_angle - minute_angle if hour_angle >= minute_angle else minute_angle - hour_angle
# each minute = 0.5 degrees
# hour = 30 degrees
# each rotation = 360 degrees = 720 minutes
def main():
assert calculate_angle(3, 30) == 75
assert calculate_angle(12, 30) == 165
if __name__ == '__main__':
main()
|
091d83f7649e680f0c9481bdc6deb6dbb3d21172
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/rearrange_nonadjacent_string.py
| 766 | 3.890625 | 4 |
import heapq
def rearrange(string):
character_count = [(-string.count(char), char) for char in set(string)]
if any([-count for count, char in character_count]) > (len(string) + 1) / 2:
return ""
heapq.heapify(character_count)
result = ""
while len(character_count) >= 2:
count1, char1 = heapq.heappop(character_count)
count2, char2 = heapq.heappop(character_count)
result += "{}{}".format(char1, char2)
if count1 + 1:
heapq.heappush(character_count, (count1 + 1, char1))
if count2 + 1:
heapq.heappush(character_count, (count2 + 1, char2))
print(result)
return result
def main():
assert rearrange("abbccc") == "cbcabc"
if __name__ == '__main__':
main()
|
4436362c69115bdc716fce8713961fc2ebc0c78a
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/all_permutations.py
| 489 | 3.703125 | 4 |
from copy import copy
def find_permutations(numbers, low, high):
if low == high:
return [numbers]
result = []
for i in range(low, high+1):
temp = copy(numbers)
temp[low], temp[i] = temp[i], temp[low]
result.extend(find_permutations(temp, low + 1, high))
return result
def main():
assert find_permutations([1, 2, 3], 0, 2) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
if __name__ == '__main__':
main()
|
6487331730c120c1a15329778306bddc9a9169ae
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/string_compression.py
| 684 | 3.796875 | 4 |
def string_compression(string):
count = 1
current_char = string[1]
result = []
for char in string[1:]:
if char == current_char:
count += 1
else:
if count > 1:
result.extend([current_char, str(count)])
else:
result.append(current_char)
current_char = char
count = 1
if count > 1:
result.extend([current_char, str(count)])
else:
result.append(current_char)
print(result)
return result
def main():
assert string_compression(['a', 'a', 'b', 'c', 'c', 'c']) == ['a', '2', 'b', 'c', '3']
if __name__ == '__main__':
main()
|
f703df8c624a0364c15d2ba43e44b43ea666edc4
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/count_invalid_parenthesis.py
| 560 | 4 | 4 |
def count(parentheses):
p_stack = []
changes = 0
for p in parentheses:
if p == ")":
if not p_stack:
changes += 1
else:
p_stack.pop()
else:
p_stack.append(p)
if p_stack:
if len(p_stack) % 2:
changes += 1+len(p_stack)//2
else:
changes += len(p_stack)//2
return changes
def main():
assert count(")(") == 2
assert count("(())())") == 1
assert count(")(((()(()") == 3
if __name__ == '__main__':
main()
|
c503ba12389dc9f0f2fcdb6ea717308d8f5b4e9e
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/longestKDistinctCharSubstring.py
| 910 | 3.703125 | 4 |
from collections import deque
def longest_substring_with_k_distinct_characters(string, k):
char_dict = dict()
current_sub_string = deque()
largest_substring = ""
for char in string:
current_sub_string.append(char)
try:
char_dict[char] += 1
except:
char_dict[char] = 1
while not is_valid(char_dict, k):
char_dict[current_sub_string.popleft()] -= 1
if len(current_sub_string) > len(largest_substring):
largest_substring = "".join(list(current_sub_string))
return largest_substring
def is_valid(char_count, k):
count = 0
for char in char_count:
if char_count[char] > 0:
count += 1
if count > k:
return False
return True
def main():
assert longest_substring_with_k_distinct_characters("aabcdefff", 3) == "defff"
if __name__ == '__main__':
main()
|
ac4a6030fba4e128077f293875698049ba6af4e3
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/palindromic_linked_list.py
| 957 | 4 | 4 |
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
def is_palindrome(node):
if not (node and node.next):
return True
head = node
current = None
while node.next:
if not node.next.next:
current = node.next.val
node.next = None
break
node = node.next
if current == head.val:
return is_palindrome(head.next)
return False
def main():
node = Node('a')
node.next = Node('b')
node.next.prev = node
node.next.next = Node('b')
node.next.next.prev = node.next
node.next.next.next = Node('a')
node.next.next.next.prev = node.next.next
n = Node('c')
n.next = Node('d')
n.next.next = Node('e')
n.next.next.next = Node('d')
n.next.next.next.next = Node('c')
assert is_palindrome(n)
assert is_palindrome(node)
if __name__ == '__main__':
main()
|
faf6b76ffa2320cc9d7d8d712fa7f828f7bd77f4
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/number_to_column_title.py
| 587 | 3.890625 | 4 |
from string import ascii_uppercase
def convert(number):
alphabet_dict = {number: ascii_uppercase[number - 1] for number in range(0, 26)}
result = ''
while number >= 1:
res = (number % 26)
result = alphabet_dict[res] + result
if res == 0:
number -= 1
number //= 26
return result
def main():
# assert convert(26) == 'Z'
# assert convert(51) == 'AY'
assert convert(52) == 'AZ'
assert convert(676) == 'YZ'
assert convert(702) == 'ZZ'
assert convert(704) == 'AAB'
if __name__ == '__main__':
main()
|
c86b4781187375143c5771f486da0501c2fa7a0e
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/sum_binary.py
| 590 | 3.609375 | 4 |
def sum_binary(bin1, bin2):
carry = 0
result = ""
index = 0
bin1, bin2 = bin1[::-1], bin2[::-1]
while index < len(bin1) or index < len(bin2):
if index < len(bin1):
carry += ord(bin1[index]) - ord('0')
if index < len(bin2):
carry += ord(bin2[index]) - ord('0')
result = str(carry % 2) + result
carry //= 2
index += 1
if carry == 1:
result = '1' + result
print(result)
return result
def main():
assert sum_binary("11101", "1011") == "101000"
if __name__ == '__main__':
main()
|
0eb285820cf4dd56b7b48ca16b3c4b34fe362610
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/simpleCalculator.py
| 1,472 | 3.5625 | 4 |
from collections import deque
def eval(expression):
res = 0
remainingExp = deque()
currentExp = deque()
expression = expression.replace(" ", "")
for exp in expression:
if exp == ")":
for _ in range(len(currentExp)):
remainingExp.pop()
while currentExp:
val1 = currentExp.popleft()
if val1 == '-':
res = -res
break
op = currentExp.popleft()
if currentExp:
val2 = currentExp.popleft()
if op == "+":
res += int(val1) + int(val2)
else:
res += int(val1) - int(val2)
else:
if op == "+":
res = int(val1) + res
else:
res = int(val1) - res
if len(remainingExp) > 1:
currentExp.append(remainingExp.pop())
currentExp.appendleft(remainingExp.pop())
else:
currentExp = remainingExp
elif exp == "(":
currentExp.clear()
else:
currentExp.append(exp)
remainingExp.append(exp)
print(res)
return res
def main():
assert eval('- (3 + ( 2 - 1 ) )') == -4
assert eval('-((3+4)+(2-1))') == -8
assert eval('-(-(4+5))') == 9
if __name__ == '__main__':
main()
|
2834f29adbc341bf822e5418c96212f08954ad07
|
DeepakSunwal/Daily-Interview-Pro
|
/solutions/product_all_other_values.py
| 1,568 | 3.8125 | 4 |
from collections import deque
def get_values(numbers):
temp = 1
result_array = [1 for _ in numbers]
# Each index has the accumulative product shifted one place to the right
for index, number in enumerate(numbers):
result_array[index] = temp
temp *= number
temp = 1
# From right to left, the number at that index is missing progressively more values to be multiplied. Starting
# from the last value in numbers.
for index in range(len(numbers) - 1, -1, -1):
result_array[index] *= temp
temp *= numbers[index]
return result_array
def get_values2(numbers):
left_to_right = []
right_to_left = deque()
accumulative_product = 1
for number in numbers:
accumulative_product *= number
left_to_right.append(accumulative_product)
accumulative_product = 1
for number in numbers[::-1]:
accumulative_product *= number
right_to_left.appendleft(accumulative_product)
for index in range(len(numbers)):
if 0 < index < len(numbers) - 1:
numbers[index] = left_to_right[index - 1] * right_to_left[index + 1]
elif index == 0:
numbers[index] = right_to_left[1]
else:
numbers[index] = left_to_right[len(left_to_right) - 2]
return numbers
def main():
assert get_values([2, 3, 4, 1, 3, 4, 6, 7]) == [6048, 4032, 3024, 12096, 4032, 3024, 2016, 1728]
assert get_values2([2, 3, 4, 1, 3, 4, 6, 7]) == [6048, 4032, 3024, 12096, 4032, 3024, 2016, 1728]
if __name__ == '__main__':
main()
|
553d54eea3d072a1ba4fbe432cf4a1471db2e0c4
|
hariniavd/MethodProject
|
/test_nested_list.py
| 1,008 | 3.8125 | 4 |
""" Test cases for nested lists file.
"""
import unittest
import nested_lists
class TestNestedLists(unittest.TestCase):
""" Test cases for nested list function.
"""
def test_remove_nested_loop_dict(self):
""" Test case for nested lists passing a dictionary.
"""
expected = {}
result = nested_lists.remove_nested_loop(expected)
self.assertFalse(result)
def test_remove_nested_loop_list(self):
""" Test case for nested lists passing a simple list.
"""
expected = [1, 2, 3, 4]
result = nested_lists.remove_nested_loop(expected)
self.assertEqual(result, expected)
def test_remove_nested_loop_nested_list(self):
""" Test case for nested lists passing a nested list.
"""
expected = [1, 2, [3, 4], 5]
result = nested_lists.remove_nested_loop(expected)
expected = [1, 2, 3, 4, 5]
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
|
79db37e0b129c45892fb24b79f626477b3777b87
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_GUI/radio_button2.py
| 474 | 3.71875 | 4 |
from tkinter import *
d = {'thai':'th','japanese':'jp','korean':'kr','chinese':'cn'}
def on_select(e):
print(e.widget['text'], e.widget['value'])
root = Tk()
root.option_add('*Font','consolas 20')
tv_code = StringVar()
tv_code.set('thai')
n_col = 3
i=0
for k,v in d.items():
r = Radiobutton(root,text=k, value=v ,variable=tv_code,indicatoron=False, width=11)
r.bind("<Button-1>",on_select)
r.grid(row= i // n_col,column=i % n_col)
i+=1
root.mainloop()
|
11917d14801009c9fdcf3146dfeaa925a3eee19c
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Lab_programming/Matrix Addition.py
| 343 | 3.59375 | 4 |
row, col = input().split()
numberSum, matrix = [], []
for _ in range(int(row)):
matrix.append([int(j) for j in input().split()])
for _ in range(int(row)):
numberSum.append([int(j) for j in input().split()])
for i in range(len(matrix)):
for j in range(int(col)):
print(matrix[i][j] + numberSum[i][j], end=" ")
print()
|
92464b02d80f9faca7a3bbca6136bb7445cc1d56
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_Beginners/Sorting/list.py
| 331 | 3.828125 | 4 |
num = [10,2,3.4,56,1,1,11]
num2 = [10,2,3.4,56,1,1,11]
num.sort()
print(num)
num2.sort(reverse=True)
print(num2)
list1 = ['aa','b','eeee','ccccc','ddd']
list1.sort(key=len)
print(list1)
list2 = [[2,9],[1,10],[3,7]]
list2.sort()
print(list2)
def SortBySec(element):
return element[1]
list2.sort(key=SortBySec)
print(list2)
|
6c0777a8bd9129fcdf46041efa362c4abfc96652
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_Assignment/EP34.Assignment10.py
| 803 | 3.59375 | 4 |
# number = []
# while True:
# x = int(input("Enter number: "))
# if x < 0:
# break
# number.append(x)
# number.sort()
# number.reverse()
# print(number)
# print(min(number))
# print(max(number))
# print(sum(number))
fish_kg = []
number = []
while True:
x = int(input())
if x == 0:
max_min = input().lower()
if max_min == "max":
fish_kg.sort()
fish_kg.reverse()
for i in fish_kg:
a = str(i)
number.append(a)
if max_min == "min":
fish_kg.sort()
for i in fish_kg:
a = str(i)
number.append(a)
break
fish_kg.append(x)
result = " ".join(number)
print(result)
# number = ["1","2","3","4"]
# a = []
# for i in number:
# b = int(i)
# a.append(b)
# # txt = " ".join(number)
# print(a)
|
8ba9f444797916c33a00ce7d7864b1fa60ae6f24
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_basic/Ex24_UserInput.py
| 271 | 4.1875 | 4 |
#* User Input
"""
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.
"""
#* Python 3.6
username = input("Enter username:")
print("Username is: " + username)
#* Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username)
|
f83dc10a41d95cd7af2c032927dd40f88f084967
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/NumPy/numpy6_Split.py
| 236 | 3.78125 | 4 |
import numpy as np
#? การแยกอาร์เอย์ออกแบบส่วน ๆ array_split()
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
newarr = np.hsplit(arr, 3)
print(newarr)
|
c62f52ea5e6260fbe15943d27c07d902671e9d01
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_DataStructure/Recursion/SumListNumber2.py
| 257 | 3.8125 | 4 |
def list_sum(data_list):
total = 0
for element in data_list:
if type(element) == type([]):
total = total + list_sum(element)
else:
total = total + element
return total
print(list_sum([2,4,[6,8],[10,12]]))
|
929a317434e72aa599c84969e3bbdcc0f755653c
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python A.prasert/pass_fn_fn_arg.py
| 817 | 4.03125 | 4 |
import random
def add(a,b):
return a + b
def f(func,a,b):
return func(a,b)
def fx(func):
for _ in range(10):
a = random.randrange(1,13)
b = random.randrange(1,13)
print(f"{a} op {b} = {func(a,b)}")
def mental_math():
funcs = {
'+':lambda a,b: a+b,
'-':lambda a,b: a-b,
'*':lambda a,b: a*b
}
for _ in range(10):
a = random.randrange(1,13)
b = random.randrange(1,13)
op = random.choice(list(funcs.keys()))
print(f"{a:2} {op} {b:2} = ")
# print(f"{a} {op} {b} = {funcs[op](a,b)}")
if __name__ == "__main__":
# print(add(5,2))
# print(f(add,5,2))
# print(f(lambda a,b: a+b,5,2))
# fop = lambda a,b: a+b
# print(f(fop,5,2))
# fx(add)
# fx(lambda a,b: a - b)
mental_math()
|
6abf3d5d18caaab027fced167a444774be8412b6
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_Beginners/Control_Sturcures/for.py
| 176 | 4.03125 | 4 |
for var in "python":
print(var)
for letter in [10,20,30,40,50]:
if letter >= 25:
print(letter,'greater than 25')
else:
print(letter,'lass than 25')
|
1aa01887c22938e7c9de4f2672fb54e2f2596ac1
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python A.prasert/basic_zip.py
| 704 | 3.53125 | 4 |
def demo1():
weight = [70,60,48]
height = [170,175,161]
bmi = []
for i in range(len(weight)):
bmi.append(weight[i] / (height[i]/100) ** 2)
return bmi
def demo2():
weight = [70,60,48]
height = [170,175,161]
bmi = []
for w,h in zip(weight,height):
bmi.append(w / (h /100) ** 2)
return bmi
def demo3():
weight = [70,60,48]
height = [170,175,161]
return [w / (h /100) ** 2 for w,h in zip(weight,height)]
def demo4():
weight = [70,60,48]
height = [170,175,161]
name = ['Leo', 'Ben','Peter']
return [(n,w / (h /100) ** 2) for w,h,n in zip(weight,height,name)]
print(demo1())
print(demo2())
print(demo3())
print(demo4())
|
1c177c418dc1036b00da6a98ce409b7c233176ba
|
Bongkot-Kladklaen/Programming_tutorial_code
|
/Python/Python_basic/Ex5_Strings.py
| 5,224 | 4.03125 | 4 |
"""
Escape Character:
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
"""
#* String Literals
print("Hello")
print('Hello')
#* Assign String to a Variable
a = "Hello"
print(a)
#* Multiline Strings
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
#* Strings are Arrays
a = "Hello, World!"
print(a[1])
#* Slicing
b = "Hello, World!"
print(b[2:5])
print(b[-5:-2])
#* String Length
a = "Hello, World!"
print(len(a))
#* String Methods
#strip() remove whitespace left and right
a = " Hello, World! "
print(a.strip())
#lower() make all string to small
a = "Hello, World!"
print(a.lower())
#upper() make all string to big
a = "Hello, World!"
print(a.upper())
#replace("old_World","new_World")
a = "Hello, World!"
print(a.replace("H", "J"))
#split("sep") make string to list
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
#* Check String
# in -> check present in the word
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
#not in -> check present is not the word
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
#* String Concatenation
a = "Hello"
b = "World"
c = a + b
print(c)
a = "Hello"
b = "World"
c = a + " " + b
print(c)
#* String Format
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
#* String Methods
# capitalize() Converts the first character to upper case
# casefold() Converts string into lower case
# center() Returns a centered string
# count() Returns the number of times a specified value occurs in a string
# encode() Returns an encoded version of the string
# endswith() Returns true if the string ends with the specified value
# expandtabs() Sets the tab size of the string
# find() Searches the string for a specified value and returns the position of where it was found
# format() Formats specified values in a string
# format_map() Formats specified values in a string
# index() Searches the string for a specified value and returns the position of where it was found
# isalnum() Returns True if all characters in the string are alphanumeric
# isalpha() Returns True if all characters in the string are in the alphabet
# isdecimal() Returns True if all characters in the string are decimals
# isdigit() Returns True if all characters in the string are digits
# isidentifier() Returns True if the string is an identifier
# islower() Returns True if all characters in the string are lower case
# isnumeric() Returns True if all characters in the string are numeric
# isprintable() Returns True if all characters in the string are printable
# isspace() Returns True if all characters in the string are whitespaces
# istitle() Returns True if the string follows the rules of a title
# isupper() Returns True if all characters in the string are upper case
# join() Joins the elements of an iterable to the end of the string
# ljust() Returns a left justified version of the string
# lower() Converts a string into lower case
# lstrip() Returns a left trim version of the string
# maketrans() Returns a translation table to be used in translations
# partition() Returns a tuple where the string is parted into three parts
# replace() Returns a string where a specified value is replaced with a specified value
# rfind() Searches the string for a specified value and returns the last position of where it was found
# rindex() Searches the string for a specified value and returns the last position of where it was found
# rjust() Returns a right justified version of the string
# rpartition() Returns a tuple where the string is parted into three parts
# rsplit() Splits the string at the specified separator, and returns a list
# rstrip() Returns a right trim version of the string
# split() Splits the string at the specified separator, and returns a list
# splitlines() Splits the string at line breaks and returns a list
# startswith() Returns true if the string starts with the specified value
# strip() Returns a trimmed version of the string
# swapcase() Swaps cases, lower case becomes upper case and vice versa
# title() Converts the first character of each word to upper case
# translate() Returns a translated string
# upper() Converts a string into upper case
# zfill() Fills the string with a specified number of 0 values at the beginning
|
4d2dbcff8ab46180b0154e1503b1485739c6dde7
|
HannesOS/Systems-Modeling-Spring-2015-Notebooks
|
/Thursday Feb 12 2015.py
| 1,106 | 3.984375 | 4 |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
%gui tk
from turtle import *
# <codecell>
reset()
#speed("fastest")
current_color="red"
other_color="black"
for i in range(160):
pencolor(current_color)
forward(150)
backward(150)
left(3)
# comment - swap the colors
if i%3==0:
current_color,other_color=other_color,current_color
# <codecell>
current_color,other_color=other_color,current_color
print "Current: ",current_color
print "Other: ",other_color
# <markdowncell>
# ## Simulation example
# <codecell>
from science import *
# <codecell>
x=2
t=0
constant=10
dt=0.01
# <codecell>
reset()
store(t,x)
for i in range(1000):
dx=constant*dt
x=x+dx
t=t+dt
store(t,x)
# <codecell>
t,x=recall()
# <codecell>
x
# <codecell>
plot(t,x)
# <markdowncell>
# ### second simulation
# <codecell>
x=2
t=0
constant=3
dt=0.01
# <codecell>
reset()
store(t,x)
for i in range(1000):
dx=constant*x*dt
x=x+dx
t=t+dt
store(t,x)
# <codecell>
t,x=recall()
# <codecell>
plot(t,x)
# <codecell>
|
e6b156740ad6ad521cd27ad86cc6d728529ad3a2
|
HannesOS/Systems-Modeling-Spring-2015-Notebooks
|
/Correct Answer to HW from Thursday Feb 19 2015 - sim with two variables.py
| 1,589 | 3.890625 | 4 |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# ## Question to Hand In - Excel Simulation
#
# 1. For the following system, write out the discrete simulation equations
# 2. Make an Excel simulation using these equations
# 3. Discuss the result
#
# \begin{eqnarray}
# x'&=&v\\
# v'&=&k - c\cdot v^2
# \end{eqnarray}
# where $k$ is a constant number, say $k=10$, $c$ is a constant number, say $c=0.1$, and $x$ and $v$ are variables to be simulated. Use plots of $x(t)$ and $v(t)$ to help.
# <codecell>
from science import *
# <markdowncell>
# Just to compare, here is the 1-variable sim from before...
# <markdowncell>
# ### Linear growth example
#
# $y' = {\rm constant}$
# <codecell>
y=2
t=0
constant=10
dt=0.01
# <codecell>
reset()
store(t,y)
for i in range(9000):
dy=constant*dt
y=y+dy
t=t+dt
if i%100 == 0 : # if the remainder with i/100 = 0 (i.e. i is divisible by 100)
store(t,y)
# <codecell>
t,y=recall()
# <codecell>
plot(t,y)
xlabel('time')
ylabel('y')
# <markdowncell>
# ## Answer to the HW question
# <codecell>
x=2
v=1
t=0
k=10
c=0.1
dt=0.0005 # I made the time step smaller, so I can see the beginning
# <codecell>
reset()
store(t,x,v)
for i in range(9000):
dx=v*dt
dv=(k-c*v**2)*dt
x=x+dx
v=v+dv
t=t+dt
if i%100 == 0 : # if the remainder with i/100 = 0 (i.e. i is divisible by 100)
store(t,x,v)
# <codecell>
t,x,v=recall()
# <codecell>
plot(t,x)
xlabel('time')
ylabel('x')
# <codecell>
plot(t,v)
xlabel('time')
ylabel('v')
# <codecell>
|
fb599eaa6e2a8bb4293223c38b3f98179734b92f
|
jkpubsrc/python-module-jk-console
|
/examples/simpletable.py
| 892 | 3.875 | 4 |
#!/usr/bin/env python3
#
# This example demonstrates the use of SimpleTable with alignments, text transformations and colors.
#
import os
import sys
from jk_console import *
t = SimpleTable()
with t.addRow("Key", "Value") as r:
r.color = Console.ForeGround.STD_LIGHTGREEN
#r.halign = SimpleTable.HALIGN_LEFT
r.case = SimpleTable.CASE_UPPER
r.hlineAfterRow = True
t.addRow("Country", "Germany")
t.addRow("State", "Berlin")
t.addRow("Area", "891.7 km2 ")
t.addRow("State", "Berlin")
t.addRow("Elevation", "34 m")
t.addRow("Population", "3,748,148")
t.addRow("Website", "www.berlin.de")[1].color = Console.ForeGround.STD_LIGHTCYAN
with t.column(0) as c:
c.color = Console.ForeGround.STD_WHITE
c.halign = SimpleTable.HALIGN_RIGHT
c.vlineAfterColumn = True
t.column(0).color = Console.ForeGround.STD_LIGHTBLUE
print()
print(t.raw())
print()
t.print(prefix = "\t")
print()
|
88da38a450a71d384bb3c777b4dd2c80a82ed7e7
|
jkpubsrc/python-module-jk-console
|
/src/jk_console/viewport/Rectangle.py
| 7,465 | 3.578125 | 4 |
from typing import Union
class Rectangle(object):
def __init__(self, *args):
if len(args) == 0:
self.__x1 = 0
self.__y1 = 0
self.__x2 = 0
self.__y2 = 0
elif len(args) == 1:
arg = args[0]
if isinstance(arg, (tuple, list)):
assert len(arg) == 4
assert isinstance(arg[0], int)
assert isinstance(arg[1], int)
assert isinstance(arg[2], int)
assert isinstance(arg[3], int)
self.__x1 = arg[0]
self.__y1 = arg[1]
self.__x2 = self.__x1 + arg[2]
self.__y2 = self.__y1 + arg[3]
elif isinstance(arg, Rectangle):
self.__x1 = arg.x1
self.__y1 = arg.y1
self.__x2 = arg.x2
self.__y2 = arg.y2
else:
raise Exception("arg 0 is " + str(type(arg)) + " ???")
elif len(args) == 4:
assert isinstance(args[0], int)
assert isinstance(args[1], int)
assert isinstance(args[2], int)
assert isinstance(args[3], int)
self.__x1 = args[0]
self.__y1 = args[1]
self.__x2 = self.__x1 + args[2]
self.__y2 = self.__y1 + args[3]
else:
raise Exception("args ???")
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
#
@property
def width(self) -> int:
return self.__w
#
@width.setter
def width(self, value:int):
assert isinstance(value, int)
self.__w = value
self.__x2 = self.__x1 + self.__w
#
@property
def height(self) -> int:
return self.__h
#
@height.setter
def height(self, value:int):
assert isinstance(value, int)
self.__h = value
self.__y2 = self.__y1 + self.__h
#
@property
def x(self) -> int:
return self.__x1
#
@x.setter
def x(self, value:int):
assert isinstance(value, int)
self.__x1 = value
self.__w = self.__x2 - self.__x1
#
@property
def y(self) -> int:
return self.__y1
#
@y.setter
def y(self, value:int):
assert isinstance(value, int)
self.__y1 = value
self.__h = self.__y2 - self.__y1
#
@property
def x1(self) -> int:
return self.__x1
#
@x1.setter
def x1(self, value:int):
assert isinstance(value, int)
self.__x1 = value
self.__w = self.__x2 - self.__x1
#
@property
def y1(self) -> int:
return self.__y1
#
@y1.setter
def y1(self, value:int):
assert isinstance(value, int)
self.__y1 = value
self.__h = self.__y2 - self.__y1
#
@property
def x2(self) -> int:
return self.__x2
#
@x2.setter
def x2(self, value:int):
assert isinstance(value, int)
self.__x2 = value
self.__w = self.__x2 - self.__x1
#
@property
def y2(self) -> int:
return self.__y2
#
@y2.setter
def y2(self, value:int):
assert isinstance(value, int)
self.__y2 = value
self.__h = self.__y2 - self.__y1
#
@property
def topLeft(self) -> tuple:
return (self.__x1, self.__y1)
#
@topLeft.setter
def topLeft(self, value:Union[tuple, list]):
assert isinstance(value, (tuple, list))
assert len(value) == 2
self.__x1 = value[0]
self.__y1 = value[1]
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
#
@property
def topRight(self) -> tuple:
return (self.__x2 - 1, self.__y1)
#
@topRight.setter
def topRight(self, value:Union[tuple, list]):
assert isinstance(value, (tuple, list))
assert len(value) == 2
self.__x2 = value[0] + 1
self.__y1 = value[1]
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
#
@property
def bottomRight(self) -> tuple:
return (self.__x2 - 1, self.__y2 - 1)
#
@bottomRight.setter
def bottomRight(self, value:Union[tuple, list]):
assert isinstance(value, (tuple, list))
assert len(value) == 2
self.__x2 = value[0] + 1
self.__y2 = value[1] + 1
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
#
@property
def bottomLeft(self) -> tuple:
return (self.__x1, self.__y2 - 1)
#
@bottomLeft.setter
def bottomLeft(self, value:Union[tuple, list]):
assert isinstance(value, (tuple, list))
assert len(value) == 2
self.__x1 = value[0]
self.__y2 = value[1] + 1
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
#
def isValid(self) -> bool:
return (self.__w > 0) and (self.__h > 0)
#
def area(self) -> int:
return self.__w * self.__h
#
#def clone(self) -> Rectangle:
def clone(self):
return Rectangle(self)
#
def enlarge(self, *args):
if len(args) == 1:
v = args[0]
if isinstance(v, Rectangle):
self.__x1 -= v.x1
self.__y1 -= v.y1
self.__x2 += v.x2
self.__y2 += v.y2
else:
self.__x1 -= v
self.__y1 -= v
self.__x2 += v
self.__y2 += v
elif len(args) == 2:
vh = args[0]
vv = args[1]
self.__x1 -= vh
self.__y1 -= vv
self.__x2 += vh
self.__y2 += vv
elif len(args) == 4:
self.__x1 -= args[0]
self.__y1 -= args[1]
self.__x2 += args[2]
self.__y2 += args[3]
else:
raise Exception("args ???")
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
return self
#
def shrink(self, *args):
if len(args) == 1:
v = args[0]
if isinstance(v, Rectangle):
self.__x1 += v.x1
self.__y1 += v.y1
self.__x2 -= v.x2
self.__y2 -= v.y2
else:
self.__x1 += v
self.__y1 += v
self.__x2 -= v
self.__y2 -= v
elif len(args) == 2:
vh = args[0]
vv = args[1]
self.__x1 += vh
self.__y1 += vv
self.__x2 -= vh
self.__y2 -= vv
elif len(args) == 4:
self.__x1 += args[0]
self.__y1 += args[1]
self.__x2 -= args[2]
self.__y2 -= args[3]
else:
raise Exception("args ???")
self.__w = self.__x2 - self.__x1
self.__h = self.__y2 - self.__y1
return self
#
#def intersect(self, other:Rectangle) -> Rectangle:
def intersect(self, other):
assert isinstance(other, Rectangle)
if (other.__x1 > self.__x2) \
or (other.__y1 > self.__y2) \
or (other.__x2 < self.__x1) \
or (other.__y2 < self.__y1):
# no intersection
return None
x1 = max(self.__x1, other.__x1)
y1 = max(self.__y1, other.__y1)
x2 = min(self.__x2, other.__x2)
y2 = min(self.__y2, other.__y2)
return Rectangle(x1, y2, x2 - x1, y2 - y1)
#
#def unite(self, other:Rectangle) -> Rectangle:
def unite(self, other):
assert isinstance(other, Rectangle)
x1 = min(self.__x1, other.__x1)
y1 = min(self.__y1, other.__y1)
x2 = max(self.__x2, other.__x2)
y2 = max(self.__y2, other.__y2)
return Rectangle(x1, y1, x2 - x1, y2 - y1)
#
@staticmethod
#def intersectMany(other) -> Rectangle:
def intersectMany(other):
assert isinstance(other, (tuple, list))
if len(other) == 0:
raise Exception("args ???")
if len(other) == 1:
assert isinstance(other, Rectangle)
return other
rect = other[0]
assert isinstance(rect, Rectangle)
x1 = rect.__x1
y1 = rect.__y1
x2 = rect.__x2
y2 = rect.__y2
for r in other[1:]:
assert isinstance(r, Rectangle)
if (r.__x1 > x2) \
or (r.__y1 > y2) \
or (r.__x2 < x1) \
or (r.__y2 < y1):
# no intersection
return None
x1 = max(x1, r.__x1)
y1 = max(y1, r.__y1)
x2 = min(x2, r.__x2)
y2 = min(y2, r.__y2)
return Rectangle(x1, y1, x2 - x1, y2 - y1)
#
@staticmethod
#def uniteMany(other) -> Rectangle:
def uniteMany(other):
assert isinstance(other, (tuple, list))
x1 = min([ r.__x1 for r in other ])
y1 = min([ r.__y1 for r in other ])
x2 = max([ r.__x2 for r in other ])
y2 = max([ r.__y2 for r in other ])
return Rectangle(x1, y2, x2 - x2, y2 - y1)
#
def shift(self, x:int, y:int):
assert isinstance(x, int)
assert isinstance(y, int)
self.__x1 += x
self.__x2 += x
self.__y1 += y
self.__y2 += y
#
#
|
532ccfeeeb90f0253f797033fe95b1fd3f1634c4
|
jkpubsrc/python-module-jk-console
|
/examples/colorizedoutput.py
| 282 | 3.5 | 4 |
#!/usr/bin/env python3
#
# This example demonstrates how to write colored text to STDOUT.
#
from jk_console import Console
print(Console.ForeGround.CYAN + "Hello World!" + Console.RESET)
print(Console.BackGround.rgb256(128, 0, 0) + "Hello World!" + Console.RESET)
|
b19a0fca96e565ed56ccb2a82cb892b79dacafbc
|
NasreddinHodja/cg_t1
|
/rasterization.py
| 5,838 | 3.90625 | 4 |
#!/usr/bin/env python3
""" Rasterization
Takes in a scene description with primitives, that can
have an xform associated with, and rasterizes it to an
image that is then shown using PIL Image.show().
Usage:
./rasterization.py [shape]
Args:
shape: json file containing grafics description
"""
import sys
import json
import numpy as np
from PIL import Image
def bounding_box(primitive):
""" Creates a bounding box for a given circle ou convex polygon
Args:
primitive (dict): primitive shape
Returns:
[[x1, y1], [x2, y2]] corresponding do the bounding box, where
(x1, y1) X-----+
| |
+-----X (x2, y2)
"""
if primitive["shape"] == "circle":
bbox = [[primitive["center"][0] - primitive["radius"],
primitive["center"][1] - primitive["radius"]],
[primitive["center"][0] + primitive["radius"],
primitive["center"][1] + primitive["radius"]]]
else:
x_coords, y_coords = zip(*primitive["vertices"])
bbox = [[min(x_coords), min(y_coords)],
[max(x_coords), max(y_coords)]]
primitive["bounding_box"] = bbox
return primitive
def winding_number(x, y, primitive):
""" Winding number function
Checks if (x, y) is inside primitive using the winding number algorithm.
Args:
x (float): horizontal point position
y (float): vertical point position
primitive (dict): primitive shape (polygon)
Returns:
True if (x,y) is inside the primitive, False case contrary
"""
wn = 0
edges = zip(primitive["vertices"][-1:] + primitive["vertices"][:-1],
primitive["vertices"])
for edge in edges:
# check if cuts y parallel line at (x, y) &&
if (edge[0][0] > x) != (edge[1][0] > x):
# check what side of the edge is (x, y)
# side > 0 => point is to de left of the edge
# side = 0 => point is on the edge
# side < 0 => point is to de right of the edge
side = ((y - edge[0][1]) * (edge[1][0] - edge[0][0]) -
(x - edge[0][0]) * (edge[1][1] - edge[0][1]))
# if to the left, increase wn
if side > 0: wn += 1
# if to the right, decrease wn
else: wn -= 1
if wn != 0: return True
return False
def inside(x, y, primitive):
"""
Check if point (x,y) is inside the primitive
Args:
x (float): horizontal point position
y (float): vertical point position
primitive (dict): primitive shape
Returns:
True if (x,y) is inside the primitive, False case contrary
"""
# You should implement your inside test here for all shapes
# for now, it only returns a false test
if primitive["shape"] == "circle":
dist_sqr = ((primitive["center"][0] - x) ** 2 +
(primitive["center"][1] - y) ** 2)
return dist_sqr <= primitive["radius"] ** 2
else:
return winding_number(x, y, primitive)
return False
class Screen:
""" Creates a virtual basic screen
Args:
gdata (dict): dictionary containing screen size and scene description
"""
def __init__(self, gdata):
self._width = gdata.get("width")
self._height = gdata.get("height")
self._scene = self.preprocess(gdata.get("scene"))
self.create_image()
def preprocess(self, scene):
"""
Applies affine transformation on primitives, if given, and adds bounding boxes
Args:
scene (dict): Scene containing the graphic primitives
Returns:
scene (dict): Scene containing the graphic primitives with additional info
"""
# Possible preprocessing with scene primitives, for now we don't change anything
# You may define bounding boxes, convert shapes, etc
preprop_scene = []
for primitive in scene:
preprop_scene.append(bounding_box(primitive))
return preprop_scene
def create_image(self):
""" Creates image with white background
Returns
image (numpy array): White image with R, G, B channels
"""
self._image = 255 * np.ones((self._height, self._width, 3), np.uint8)
def rasterize(self):
""" Rasterize the primitives along the Screen
"""
for primitive in self._scene:
bbox = primitive["bounding_box"]
# Loop through all pixels
# You MUST use bounding boxes in order to speed up this loop
for w in range(bbox[0][0], bbox[1][0]):
x = w + 0.5
for h in range(bbox[0][1], bbox[1][1]):
y = h + 0.5
# First, we check if the pixel center is inside the primitive
im_x, im_y = w, self._height - (h + 1)
if inside(x, y, primitive):
# apply affine xfrom if needed
if "xform" in primitive.keys():
result = np.matmul(primitive["xform"],
[[im_x], [im_y], [1]])
im_x, im_y = int(result[0][0]), int(result[1][0])
self._image[im_y, im_x] = primitive["color"]
# break
# break
# break
def show(self, exec_rasterize = False):
""" Show the virtual Screen
"""
if (exec_rasterize):
self.rasterize()
Image.fromarray(self._image).show()
def main():
with open(sys.argv[1]) as json_f:
graphic_data = json.load(json_f)
screen = Screen(graphic_data)
screen.show(True)
if __name__ == "__main__":
main()
|
92e0fbe7905515ac40954a813dd2a37ffde79520
|
raviitsoft/Python_Fundamental_DataScience
|
/0 Python Fundamental/25.b.map.py
| 661 | 3.765625 | 4 |
# map python
def y(a):
return len(a)
a = ['Andilala', 'Budiman', 'Caca']
x = map(y, a)
# print(x)
# print(list(x))
########################################
a = ['Cokelat', 'Melon', 'Nangka']
b = ['Apel', 'Jeruk', 'Nanas']
def combi(a, b):
return a+' '+b
x = map(combi, a, b)
# print(x)
# print(list(x))
########################################
x = [2, 4, 6, 8, 10]
def pangkat2(a):
return a ** 2
# y = map(pangkat2, x)
# print(list(y))
y = map(lambda x : x ** 2, x)
# print(list(y))
# out: [4, 16, 36, 64, 100]
######################################
x = pow(2, 2)
y = pow(3, 3)
print(x)
print(y)
z = list(map(pow, [2, 3], [2, 3]))
print(z)
|
cccab191e43db383bb37c1a9a05e60ce4df8777e
|
mayankDhiman/cp
|
/codechef/AUG19B/DSTAPLS.py
| 188 | 3.546875 | 4 |
import math
tt = int(input())
for _ in range(tt):
n, k = input().split(' ')
n = int(n)
k = int(k)
if (n % (k**2) == 0):
print("NO")
else:
print("YES")
|
a2245d6d3d4eef959623298322eb5a2bb3af0485
|
SeungjuU/test1
|
/task_9.py
| 105 | 3.921875 | 4 |
x=int(input('enter the x: '))
y=int(input('enter the y: '))
def mySum(x,y):
print (x+y)
mySum(x,y)
|
dc6515bb3acd810a8e1d86aa59033b660a368594
|
Yibangyu/oldKeyboard1
|
/1023.py
| 381 | 4.1875 | 4 |
#!/usr/bin/python
import re
preg = input()
string = input()
result_string = ''
preg = preg.upper() + preg.lower()
if '+' in preg:
preg = preg+'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if preg:
for char in string:
if char in preg:
continue
else:
result_string = result_string + char
print(result_string)
else:
print(string)
|
14fd87a29e472ebb0c074765b26425597dfcb2cc
|
mijapa/FuzzyLogic
|
/add.py
| 994 | 3.703125 | 4 |
from norm import minimum
f_number_1 = {(0.3, 1), (1, 2)}
f_number_2 = {(1, 1), (0.5, 2)}
def addition(number_1, number_2, norm):
a_set = set() # creating empty set
for x in number_1:
for y in number_2:
fuzzy_sum = (norm(x, y)[0], x[1] + y[1])
print("x: {}, y: {}, fuzzy sum: {}".format(x, y, fuzzy_sum))
a_set.add(fuzzy_sum)
print("a_set before removing repetitions : {}".format(a_set))
visited = set()
b_set = set()
for a, b in a_set:
if not b in visited:
visited.add(b)
# print("visited: {}".format(visited))
b_set.add((a, b))
print("b_set before changing elements to upper bound: {}".format(b_set))
for x in a_set:
for y in b_set:
if x[1] == y[1]:
if x[0] > y[0]: # upper bound
b_set.remove(y)
b_set.add(x)
print("wynik: {}".format(b_set))
addition(f_number_1, f_number_2, minimum)
|
349cc587f4263f0eb99888dd43dc841b4c6c11e3
|
captainpainway/advent-of-code-2019
|
/day1.py
| 648 | 3.5625 | 4 |
import math
from functools import reduce
input = open('day1input.txt').read().splitlines()
def calcFuel(amt):
return math.floor(int(amt) / 3) - 2
def addFuel(f1, f2):
return f1 + f2;
def fuelRequired(modules):
return reduce(addFuel, map(calcFuel, modules))
def additionalFuelNeeded(fuel):
total = 0
current = calcFuel(int(fuel))
while(current > 0):
total += current
current = calcFuel(current)
return total
def totalFuelRequired(modules):
return reduce(addFuel, map(additionalFuelNeeded, modules))
print("Part 1: " + str(fuelRequired(input)))
print("Part 2: " + str(totalFuelRequired(input)))
|
8076fc2f60d0526ac5a1feed7941882ebdd72704
|
luizfranca/project-euler
|
/python/p09.py
| 302 | 4.09375 | 4 |
# Special Pythagorean triplet
import math
def pythagorean_Triplet(n):
number = 0
for a in range(1, n):
for b in range(1, n):
c = math.sqrt(a ** 2 + b ** 2)
if c % 1 == 0:
number = a + b + int(c)
c = int(c)
if number == n:
return a * b * c
print pythagorean_Triplet(1000)
|
d978a0a27c0987acdd1dca405e71d7195cf70907
|
alanbriolat/SFWG
|
/src/service.py
| 1,864 | 3.515625 | 4 |
#!/usr/bin/python
class Service:
ports = None
protocols = None
description = None
def __init__(self, params, desc):
# Split up parameters - these are the result of split('|') on a config
# line usually
port, proto = params
self.description = desc
# Check the validity of the port definition
if not port:
raise "You must define some ports to open!"
else:
self.ports = port
"""
try:
start, finish = port.split(':')
except ValueError:
start = finish = port
if 0 < int(start) < 65536 and 0 < int(finish) < 65536:
if int(finish) < int(start):
raise "End port higher than start port"
else:
self.ports = start, finish
else:
raise "Port number out of range"
"""
# Check which protocols are being allowed
if not proto:
self.protocols = "tcp", "udp"
else:
protocols = []
for p in proto.split(','):
p = p.strip().lower()
if p in ("tcp", "udp"):
protocols.append(p)
if len(protocols) == 0:
raise "No valid protocols were defined - use 'tcp', 'udp' or 'tcp,udp', or \
leave the field blank (will use both tcp and udp by default)"
else:
self.protocols = set(protocols)
def getrule(self):
output = []
if self.description:
output.append("# " + self.description)
ports = self.ports
for p in self.protocols:
output.append("iptables -A INPUT -p %s --dport %s -j ACCEPT" % (p, ports))
output.append('')
return output
|
21fe03d6144a70deccb408b6c4d1a2e5e065d255
|
aces/Loris-MRI
|
/python/lib/database_lib/session_db.py
| 3,784 | 3.578125 | 4 |
"""This class performs session table related database queries and common checks"""
__license__ = "GPLv3"
class SessionDB:
"""
This class performs database queries for session table.
:Example:
from lib.database_lib.session_db import SessionDB
from lib.database import Database
# database connection
db = Database(config.mysql, verbose)
db.connect()
session_obj = SessionDB(db, verbose)
...
"""
def __init__(self, db, verbose):
"""
Constructor method for the SessionDB class.
:param db : Database class object
:type db : object
:param verbose: whether to be verbose
:type verbose: bool
"""
self.db = db
self.verbose = verbose
def create_session_dict(self, cand_id, visit_label):
"""
Queries the session table for a particular candidate ID and visit label and returns a dictionary
with the session information.
:param cand_id: CandID
:type cand_id: int
:param visit_label: Visit label of the session
:type visit_label: str
:return: dictionary of the information present in the session table for that candidate/visit
:rtype: dict
"""
query = "SELECT * FROM session" \
" JOIN psc USING (CenterID)" \
" WHERE CandID=%s AND LOWER(Visit_label)=LOWER(%s) AND Active='Y'"
results = self.db.pselect(query=query, args=(cand_id, visit_label))
return results[0] if results else None
def get_session_center_info(self, pscid, visit_label):
"""
Get site information for a given visit.
:param pscid: candidate site ID (PSCID)
:type pscid: str
:param visit_label: visit label
:type visit_label: str
:return: dictionary of site information for the visit/candidate queried
:rtype: dict
"""
query = "SELECT * FROM session" \
" JOIN psc USING (CenterID)" \
" JOIN candidate USING (CandID)" \
" WHERE PSCID=%s AND Visit_label=%s"
results = self.db.pselect(query=query, args=(pscid, visit_label))
return results[0] if results else None
def determine_next_session_site_id_and_visit_number(self, cand_id):
"""
Determines the next session site and visit number based on the last session inserted for a given candidate.
:param cand_id: candidate ID
:type cand_id: int
:return: a dictionary with 'newVisitNo' and 'CenterID' keys/values
:rtype: dict
"""
query = "SELECT IFNULL(MAX(VisitNo), 0) + 1 AS newVisitNo, CenterID" \
" FROM session WHERE CandID = %s GROUP BY CandID, CenterID"
results = self.db.pselect(query=query, args=(cand_id,))
if results:
return results[0]
query = "SELECT 1 AS newVisitNo, RegistrationCenterID AS CenterID FROM candidate WHERE CandID = %s"
results = self.db.pselect(query=query, args=(cand_id,))
return results[0] if results else None
def insert_into_session(self, fields, values):
"""
Insert a new row in the session table using fields list as column names and values as values.
:param fields: column names of the fields to use for insertion
:type fields: list
:param values: values for the fields to insert
:type values: list
:return: ID of the new session registered
:rtype: int
"""
session_id = self.db.insert(
table_name="session",
column_names=fields,
values=values,
get_last_id=True
)
return session_id
|
9e1133291434351af948b3f10621b3548bc4b7ed
|
aces/Loris-MRI
|
/python/lib/database_lib/physiologicalannotationfile.py
| 2,229 | 3.515625 | 4 |
"""This class performs database queries for the physiological_annotation_file table"""
__license__ = "GPLv3"
class PhysiologicalAnnotationFile:
def __init__(self, db, verbose):
"""
Constructor method for the PhysiologicalAnnotationFile class.
:param db : Database class object
:type db : object
:param verbose : whether to be verbose
:type verbose : bool
"""
self.db = db
self.table = 'physiological_annotation_file'
self.verbose = verbose
def insert(self, physiological_file_id, annotation_file_type, annotation_file):
"""
Inserts a new entry in the physiological_annotation_file table.
:param physiological_file_id : physiological file's ID
:type physiological_file_id : int
:param annotation_file_type : type of the annotation file
:type annotation_file_type : str
:param annotation_file : path of the annotation file
:type annotation_file : str
:return : id of the row inserted
:rtype : int
"""
return self.db.insert(
table_name = self.table,
column_names = ('PhysiologicalFileID', 'FileType', 'FilePath'),
values = (physiological_file_id, annotation_file_type, annotation_file),
get_last_id = True
)
def grep_annotation_paths_from_physiological_file_id(self, physiological_file_id):
"""
Gets the FilePath given a physiological_file_id
:param physiological_file_id : Physiological file's ID
:type physiological_file_id : int
:return : list of FilePath if any or None
:rtype : list
"""
annotation_paths = self.db.pselect(
query = "SELECT DISTINCT FilePath "
"FROM physiological_annotation_file "
"WHERE PhysiologicalFileID = %s",
args=(physiological_file_id,)
)
annotation_paths = [annotation_path['FilePath'] for annotation_path in annotation_paths]
|
f1a2ceeea899520d3a3a5b3f11c5599ff1ee4903
|
apmcdaniels/CAAP-CS
|
/Lab2/Lab2/game/game.py
| 1,873 | 3.828125 | 4 |
# imports multiple clases from the python library and some of our
# own modules.
from sys import exit
from random import randint
from map import Map
from leaderboard import Leaderboard
from scores import Score
from game_engine import Engine
# global variables to keep track of score, player, and leaderboard
moves = 0
name = ''
leaderboard = Leaderboard()
# what happens when the game is over
# takes in a boolean parameter
# should update leaderboard, global variables, and print leaderboard
def game_over(won):
global name
global moves
score = Score(name, moves)
if won:
leaderboard.update(score)
print ("\nGame Over.")
name = ''
moves = 0
leaderboard.print_board()
# initializes/updates global variables and introduces the game.
# starts the Map and the engine.
# ends the game if needed.
def play_game():
while True:
global name
global moves
print("Welcome to The Program. This Program is running from an AI chip that was inserted\ninto your arm by the Hostile Political Party as a means of maintaining control.")
print(" ")
print("Because you committed a small infraction, this Program was initiated\nas a way to eliminate you. In the Program, you'll be transported through a series of scenarios.")
print(" ")
print ("In each of the scenarios, you will be faced with a series of tasks which you will have to complete.\nYour goal is to complete all the tasks so that you can terminate the Program and reclaim your livelihood!\nTo quit enter :q at any time. You will have 5 lives.\nHope you will make it!")
print("*****************************************************************")
name = input("\nLet's play. Enter your name. > ")
if (name == ':q'):
exit(1)
a_map = Map('treehouse_jungle')
a_game = Engine(a_map)
moves = a_game.play()
game_over(a_game.won())
play_game()
|
2ae0b6dc06c2185db777ac1f2713d01556a409f0
|
apmcdaniels/CAAP-CS
|
/hw1/Part_i/unitconversion.py
| 149 | 3.875 | 4 |
def main():
centimeters = eval(input("How many centimeters?"))
inches = centimeters/2.54
print("you have", inches, "inches.")
main()
|
8884da37c1e7b0076c6acd2a0daa077762d7aadd
|
kerzol81/Bash-and-Python-scripts
|
/multipleSiteSearch
| 314 | 3.5 | 4 |
#!/usr/bin/env python3
import webbrowser
sites = [ 'site1', 'site2', 'site3', 'etc.' ]
print('Multiple google search on sites:')
for site in sites:
print(site)
keyword = input('\nKeyword: ')
for site in sites:
webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' % keyword + ' ' + site)
|
0b4f540f089378f5adf6e5a5ad81283a0f2af7b2
|
suphaWiz/Sanntid
|
/Exercise1.py
| 442 | 3.609375 | 4 |
from threading import Thread
global i
i = 0
def someThreadFunction1():
global i
for s in range(0,1000000):
i = i+1
def someThreadFunction2():
global i
for s in range(0,1000000):
i = i-1
def main():
someThread1 = Thread(target = someThreadFunction1, args = (),)
someThread2 = Thread(target = someThreadFunction2, args = (),)
someThread1.start()
someThread2.start()
someThread1.join()
someThread2.join()
print(i)
main()
|
466eafb6a18fbb60b2403a55ca0938d9f5121bab
|
riaz34/simple_port_scanner_using_sock
|
/simple.py
| 684 | 3.734375 | 4 |
#!//usr/bin/python
import socket
target=input("enter the ipaddress: ")
port_rg=input("enter the port range: ")
low=int(port_rg.split('-')[0])
high=int(port_rg.split('-')[1])
print('########################################################################')
print('target ip:',target,'scanning start from:',low,' scanning end at: ',high)
print('########################################################################')
print('\n')
for port in range(low, high+1):
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
status=s.connect_ex((target,port))
if (status==0):
print('port:',port,'*open*')
else:
print('port:',port,'closed :)')
s.close()
|
c5df19647964583e9476722ba1128219e56acf78
|
vanessadyce/Movie-Trailer-Website
|
/media.py
| 450 | 3.890625 | 4 |
class Movie():
"""This class defines a movie.
Attributes:
movie_title (str): The title of the movie
poster_url (str): The url to the movie poster
youtube_link (str): The link to the movie trailer
"""
# Movie constructor
def __init__(self, movie_title, poster_url, youtube_link):
self.title = movie_title
self.poster_image_url = poster_url
self.trailer_youtube_url = youtube_link
|
abddade25f89b83a28dd56a92f742a6ef0e3e04f
|
zacharyzhu2023/CS61C
|
/lectures/Lec31-IO Devices.py
| 6,193 | 4.03125 | 4 |
Lecture 31: I/O Devices
I/O Devices
- I/O interface provides mechanism for program on CPU to interact w/ outside world
- Examples of I/O devices: keyboards, network, mouse, display
- Functionality: connect many devices--control, respond, & transfer data b/w devices
- User programs should be able to build on their functionality
- Tasks of processor for IO: input (read bytes), output (write bytes)
- Can either use: special I/O instructions/hardware OR memory mapped I/O
- Special instructions/hardware inefficient b/c constantly have to change as hardware changes
- Memory mapped I/O: allocate address space for IO, which contain IO device registers
- Addresses 0x7FFFFFFF and below are reserved for memory mapped IO
- Each IO device has a copy of its control reg & data reg in region of memory-mapped IO
- 1GHz IO throughput: 4 GiB/s (for load/store word operations)
- I/O data rates: 10 B/s (keyboard), 3 MiB/s for bluetooth, 64 GiB/s (HBM2 DRAM)
I/O Polling
- Device registers have 2 functions: control reg (gives go-ahead for R/W operations) & data reg (contains data)
- Polling: Processor reads from control reg in loop: if control reg readyBit = 1 --> data is available or ready
to accept data. Then, load data from input or write output to data reg. Last, reset control reg bit to 0
Memory map: Input control reg-0x7ffff000, Input data reg-0x7ffff004, Output control reg-0x7ffff008, Output data reg-0x7ffff00c
INPUT: read into a0 from IO Device
lui t0, 0x7ffff # IO Address: 7fffff000
wait:
lw t1, 0(t0) # Read the control
andi t1, t1, 0x1 # Check the ready bit of control
beq t1, x0, wait # Keep waiting if ready bit != 1
lw a0, 4(t0) # Once we have valid ready bit, load input data reg
OUTPUT: write to display from a1
lui t0, 0x7ffff # Same address as above
wait:
lw t1, 0(t0) # REad the control
andi t1, t1, 0x1 # Check ready bit of control
beq t1, x0, wait # Keep waiting if ready bit != 1
sw a1, 12(t0) # Store output data from a1
- Assume processor has specifications: 1 GHz clock rate, 400 clock cycles per polling operation
- % Processor for polling = Poll Rate * Clock cycles per poll/Clock Rate
- Example: mouse that conducts 30 polls/s --> % Processor for Polling = 30 * 400/(10^9) = 0.0012%
I/O Interrupts
- Idea: polling is wasteful of finite resources b/c constantly waiting for an event to occur
- Not a great idea when dealing with large quantities of input/output data
- Alternative: interrupt which "interrupts" the current program and transfers control to trap handler
when I/O is ready to be dealth with
- Throw an interrupt when delivering data or need have relevant information
- No IO activity? Regular program continues. Lots of IO? Interrupts are expensive b/c caches/VM are garbage,
requiring saving/restoring state often
- Devices w/ low data rate (ex: mouse, keyboard): use interrupts (overhead of interrupt is low)
- Devices w/ high data rate (ex: network, disk): start w/ interrupt then switch to direct memory access (DMA)
- Programmed I/O: used for ATA hard drive which has processor that initiates all load/store instructions for data movement
b/w device. CPU obtains data from device and delivers it to main mem & also performs computation on that data
- Disadvantages: CPU in charge of transfers (better spent doing smth else), device & CPU speeds misaligned,
high energy cost of using CPU when alternative methods exist
Direct Memory Access (DMA)
- DMA allows IO devices to read/write directly to main memory, utilizing DMA Engine (piece of hardware)
- DMA engine intended to move large chunks of data to/from data, working independently
- DMA engine registers contain: mem addr for data, num bytes, I/O device num, direction of transfer, unit of transfer, amount to transfer
- Steps for the DMA transfer:
Step 1: CPU intiaites transfer (writing addr, count, and control into DMA controller)
Step 2: DMA requests transfer to memory (goes through the disk controller, which contains a buffer)
Step 3: Data gets transferred to main memory from the disk controller (through its buffer)
Step 4: Disk controller send an acknowledgement back to the DMA controller
Step 5: Interrupt the CPU when all the above operations are completed
- CPU interrupted twice: once to start the transfer (meanwhile, CPU can do whatever else), and then at the end
to indicate that the transfer is complete
- Procedure DMA uses for dealing w/ incoming data: receive interrupt from device, CPU takes interrupt/start transfer (place data at right address),
device/DMA engine handles transfer, Device/DMA Engine interrupts CPU to show completion
- Procedure for outgoing data: CPU initiates transfer/confirms external device ready, CPU initiates transfer, Device/DMA engine
handles transfer, Device/DMA engine interrupts CPU to indicate completion
- DMA Engine can exist b/w L1$ and CPU: which allows for free coherency but trashes CPU working set for the data transferred
- Free coherency: processor memory/cache system is going to have coherency
- Can also exist b/w last level cache and main memory: does not mess w/ caches but need to manage coherency explicitly
Networking
- I/O devices can be shared b/w computers (ex: printers), communicate b/w computers (file transfer protocol-FTP), communicate
b/w ppl (ex: email), communicate b/w computer networks (ex: www, file sharing)
- Internet conceptualized in 1963 when JCR Licklider writes about connecting computers b/w universities
- 1969: 4 nodes deployed at colleges, 1973: TCP invented, part of internet protocol suite
- World Wide Web: system of interlinked hypertext documents on the internet
- 1989: Sir Tim Berners Lee develops Hypertext Transfer Protocol (HTTP) allowing for client & server for the internet
- Software protocol to send/receive:
1. SW SEND: copy data to OPS buffer, calculate checksum w/ timer, send data to network interface hardware to start
2. SW RECEIVE: OS copies data from network interface hardware to OS buffer, OS calculates checksum--if fine, send ACK, else delete msg
If fine, copy data into user address space & tell application it can continue
- Requires a network interface card (NIC) that can be wired or wireless
|
9b02c4bcb2ca1024a04cf0b354483d65e6a5d616
|
CoderQingli/MyLeetCode
|
/669. Trim a Binary Search Tree.py
| 456 | 3.53125 | 4 |
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
def trim(root):
if not root:
return None
if root.val > R:
return trim(root.left)
if root.val < L:
return trim(root.right)
else:
root.left = trim(root.left)
root.right = trim(root.right)
return root
return trim(root)
|
4fe4f4939210b2fe975124c51b4ce4808360e4d3
|
CoderQingli/MyLeetCode
|
/2. Add Two Numbers.py
| 604 | 3.578125 | 4 |
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
cur = res
flag = 0
while l1 or l2:
if l1 and l2:
flag, tmp = divmod(l1.val + l2.val + flag, 10)
elif l1:
flag, tmp = divmod(l1.val + flag, 10)
else:
flag, tmp = divmod(l2.val + flag, 10)
cur.next = ListNode(tmp)
cur = cur.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if flag == 1:
cur.next = ListNode(flag)
return res.next
|
9fb30377b4a0ec0c426923c8b6b3271bb8b6fb9b
|
CoderQingli/MyLeetCode
|
/415. Add Strings.py
| 466 | 3.65625 | 4 |
def addStrings(num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = ""
tmp = 0
while num1 or num2 or tmp != 0:
if num1:
tmp += (ord(num1[-1]) - ord("0"))
if num2:
tmp += (ord(num2[-1]) - ord("0"))
res += str(tmp % 10)
tmp = tmp // 10
num1 = num1[:len(num1) - 1]
num2 = num2[:len(num2) - 1]
return res[::-1]
r = addStrings("1","1")
print(r)
|
1c354c45edc44129c5cdc634a7a086c3826515a1
|
CoderQingli/MyLeetCode
|
/70. Climbing Stairs.py
| 175 | 3.671875 | 4 |
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
res = [1, 2]
while len(res) < n:
res.append(res[-1] + res[-2])
return res[n - 1]
|
24112db6f4e4624b1bffb3aa672b3a3bd0417227
|
CoderQingli/MyLeetCode
|
/860. Lemonade Change.py
| 610 | 3.59375 | 4 |
def lemonadeChange(bills):
"""
:type bills: List[int]
:rtype: bool
"""
res = {5: 0, 10: 0}
for b in bills:
if b == 5:
res[5] += 1
elif b == 10:
if res[5] == 0:
return False
else:
res[10] += 1
res[5] -= 1
else:
if res[5] == 0:
return False
if res[10] != 0:
res[5] -= 1
res[10] -= 1
else:
res[5] -= 3
if res[5] < 0:
return False
return True
|
e40709aef47d3b8c2477a9bf63e2a59e2dcceff7
|
CoderQingli/MyLeetCode
|
/283. Move Zeroes.py
| 306 | 3.5 | 4 |
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
t = 1
i = 0
while t <= n:
if nums[i] == 0:
nums.append(nums.pop(i))
else:
i += 1
t += 1
|
fe462e3d26b866c500619db330b4e7c027189f85
|
Grigorii60/geekbrains_DZ
|
/task_1.py
| 730 | 4.15625 | 4 |
name = input('Как твое имя? : ')
print(f'Привет {name}, а мое Григорий.')
age = int(input('А сколько тебе лет? : '))
my_age = 36
if age == my_age:
print('Мы ровестники!')
elif age > my_age:
print(f'{name} ты старше меня на {age - my_age} лет.')
else:
print(f'{name} ты младше меня на {my_age - age} лет.')
result = input('Надеюсь я понял задание и сделал все верно? : ')
if result == ["Да", "да", "Yes", "yes"]:
print(f'{name} отлично, тогда я перехожу к следующему!')
else:
print(f'{name} жаль, но я обещаю стараться!)))')
|
0b68b3a9ec8de57671257df11cce33dc7d11da13
|
gcvalderrama/python_foundations
|
/udemy/mine_sweeper_click.py
| 2,204 | 3.609375 | 4 |
import queue
def click_internal(field, num_rows, num_cols, given_i, given_j):
field[given_i][given_j] = -2
for i in range(given_i - 1, given_i + 2):
for j in range(given_j - 1, given_j + 2):
if 0 <= i < num_rows and 0 <= j < num_cols and field[i][j] == 0:
click_internal(field, num_rows, num_cols, i, j)
def click(field, num_rows, num_cols, given_i, given_j):
if field[given_i][given_j] != 0:
return field
click_internal(field, num_rows, num_cols, given_i, given_j)
return field
def click2(field, num_rows, num_cols, given_i, given_j):
to_check = queue.Queue()
if field[given_i][given_j] == 0:
field[given_i][given_j] = -2
to_check.put((given_i, given_j))
else:
return field
while not to_check.empty():
(current_i, current_j) = to_check.get()
for i in range(current_i - 1, current_i + 2):
for j in range(current_j - 1, current_j + 2):
if (0 <= i < num_rows and 0 <= j < num_cols
and field[i][j] == 0):
field[i][j] = -2
to_check.put((i, j))
return field
def print_board(board):
for i in board:
print(i)
if __name__ == "__main__":
print( 5 % 4)
field = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, -1, 1, 0]]
print_board(click(field, 3, 5, 0, 0))
field1 = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, -1, 1, 0]]
print("########")
print_board(click(field1, 3, 5, 2, 2))
# [[0, 0, 0, 0, 0],
# [0, 1, 1, 1, 0],
# [0, 1, -1, 1, 0]]
print("########")
print_board(click(field1, 3, 5, 1, 4))
# [[-2, -2, -2, -2, -2],
# [-2, 1, 1, 1, -2],
# [-2, 1, -1, 1, -2]]
field2 = [[-1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, -1]]
print("########")
print_board(click(field2, 4, 4, 0, 1))
# [[-1, 1, 0, 0],
# [1, 1, 0, 0],
# [0, 0, 1, 1],
# [0, 0, 1, -1]]
print("########")
print_board(click(field2, 4, 4, 1, 3))
# [[-1, 1, -2, -2],
# [1, 1, -2, -2],
# [-2, -2, 1, 1],
# [-2, -2, 1, -1]]
|
a110f4bcca38f5d3e437f1fc7aca21b20c62ab7b
|
gcvalderrama/python_foundations
|
/dynamicprogramming/dynamic_programming.py
| 744 | 3.984375 | 4 |
from collections import defaultdict
def fibonacci_recursive(n):
if n <= 0:
return 0
if n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
def dyna_fibonacci(n, state):
if n <= 0:
state[0] = 0
if n == 1:
state[n] = 1
if state[n] is None:
state[n] = dyna_fibonacci(n-1, state) + dyna_fibonacci(n-2, state)
return state[n]
def dyna_fibonacci_tabular(n):
results = [1, 1]
for i in range(2, n):
results.append(results[i-1] + results[i-2])
return results[-1]
if __name__ == "__main__":
print(fibonacci_recursive(6))
print(dyna_fibonacci(6, defaultdict(lambda: None)))
print(dyna_fibonacci_tabular(6))
|
9297f1a0d8710008990cf37b47690773f3102d75
|
gcvalderrama/python_foundations
|
/DailyCodingProblem/univaltrees.py
| 763 | 3.609375 | 4 |
# https://www.dailycodingproblem.com/blog/unival-trees/
import unittest
class Node:
def __init__(self):
self.left = None
self.right = None
self.value = None
def is_unival(root):
return unival_helper(root, root.value)
def unival_helper(root, value):
if root is None:
return True
if root.value == value:
return unival_helper(root.left, value) and unival_helper(root.right, value)
return False
def count_unival_subtrees(root):
if root is None:
return 0
left = count_unival_subtrees(root.left)
right = count_unival_subtrees(root.right)
return 1 + left + right if is_unival(root) else left + right
class Test(unittest.TestCase):
def test_case(self):
pass
|
8881aa774131d27aef05870593658afd182d21e8
|
gcvalderrama/python_foundations
|
/atest/CombinationSum.py
| 513 | 3.65625 | 4 |
import heapq
if __name__ == '__main__':
candidates =[2,3,6,7]
target = 7
res = []
resList = []
heapq.heappop()
def backtracking(start, rest):
if rest == 0:
temp = resList[:]
res.append(temp)
for i in range(start, len(candidates)):
if (candidates[i] <= rest):
resList.append(candidates[i])
backtracking(i, rest - candidates[i])
resList.pop()
backtracking(0, target)
print(res)
|
81cc75787fdd73aaa09436287c7c02cc6cec4012
|
gcvalderrama/python_foundations
|
/udemy/last_common_ancestor.py
| 1,395 | 3.75 | 4 |
import unittest
from collections import deque
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def path_to_x(node: Node, x):
if not node:
return None
if node.value == x:
stack = deque()
stack.append(x)
return stack
left_path = path_to_x(node.left, x)
if left_path:
left_path.append(node)
return left_path
right_path = path_to_x(node.right, x)
if right_path:
right_path.append(node)
return right_path
return None
def lca(root, j, k):
path_to_j = path_to_x(root, j)
path_to_k = path_to_x(root, k)
if not path_to_j or not path_to_k:
return None
lca_result = None
while path_to_j and path_to_k:
j_pop = path_to_j.pop()
k_pop = path_to_k.pop()
if j_pop == k_pop:
lca_result = j_pop
else:
break
return lca_result
class Test(unittest.TestCase):
def test_case_a(self):
root = Node(5)
root.right = Node(4)
root.right.right = Node(2)
root.right.left = Node(9)
root.left = Node(1)
root.left.left = Node(3)
root.left.right = Node(8)
root.left.left.left = Node(6)
root.left.left.right = Node(7)
result = lca(root, 8, 7)
self.assertTrue(1, result)
|
30e43fa2101a7b39c98b50fffbd513139615296e
|
gcvalderrama/python_foundations
|
/udemy/nth_element.py
| 1,663 | 3.890625 | 4 |
class Node:
def __init__(self, value, child=None):
self.value = value
self.child = child
def __str__(self):
return str(self.value)
def nth_from_last(head, n):
left = head
right = head
for i in range(n):
if right is None:
return None
right = right.child
while right:
right = right.child
left = left.child
return left
def linked_list_to_string(head):
current = head
str_list = []
while current:
str_list.append(str(current.value))
current = current.child
str_list.append('(None)')
return ' -> '.join(str_list)
if __name__ == "__main__":
current = Node(1)
for i in range(2, 8):
current = Node(i, current)
head = current
print(linked_list_to_string(head))
# 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> (None)
# 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> (None)
current2 = Node(4)
for i in range(3, 0, -1):
current2 = Node(i, current2)
head2 = current2
# head2 = 1 -> 2 -> 3 -> 4 -> (None)
print("#####")
print(nth_from_last(head, 1))
# nth_from_last(head, 1) should return 1.
print("#####")
print(nth_from_last(head, 5))
# nth_from_last(head, 5) should return 5.
print("#####")
print(nth_from_last(head2, 2))
# nth_from_last(head2, 2) should return 3.
print("#####")
print(nth_from_last(head2, 4))
# nth_from_last(head2, 4) should return 1.
print("#####")
print(nth_from_last(head2, 5))
# nth_from_last(head2, 5) should return None.
print("#####")
print(nth_from_last(None, 1))
# nth_from_last(None, 1) should return None.
|
bfc1370319731fb0bd10bf2aa4749210d97801be
|
gcvalderrama/python_foundations
|
/left_rotate_matrix.py
| 3,317 | 4.28125 | 4 |
# Python program to rotate a matrix
def rotate_recursive(matrix):
if not len(matrix):
return matrix
rows = len(matrix)
if rows < 2:
return matrix
if len(matrix[0]) < 2:
return matrix
rotate_recursive(matrix)
rows = len(sample)
columns = len(sample[0])
#sample_without_rows = (sample[:-1])[1:]
mm = [0] * (rows - 2)
for i in range(1, rows-1, 1):
mm[i-1] = [0] * (columns-2)
for j in range(1, columns -1, 1):
mm[i-1][j-1] = sample[i][j]
return matrix
def rotate_matrix_left(mat):
if not len(mat):
return
"""
top : starting row index
bottom : ending row index
left : starting column index
right : ending column index
"""
top = 0
bottom = len(mat) - 1
left = 0
right = len(mat[0]) - 1
while left < right and top < bottom:
pass
def rotateMatrix(mat):
if not len(mat):
return
"""
top : starting row index
bottom : ending row index
left : starting column index
right : ending column index
"""
top = 0
bottom = len(mat) - 1
left = 0
right = len(mat[0]) - 1
while left < right and top < bottom:
# Store the first element of next row,
# this element will replace first element of
# current row
prev = mat[top + 1][left]
# Move elements of top row one step right
for i in range(left, right + 1):
curr = mat[top][i]
mat[top][i] = prev
prev = curr
top += 1
# Move elements of rightmost column one step downwards
for i in range(top, bottom + 1):
curr = mat[i][right]
mat[i][right] = prev
prev = curr
right -= 1
# Move elements of bottom row one step left
for i in range(right, left - 1, -1):
curr = mat[bottom][i]
mat[bottom][i] = prev
prev = curr
bottom -= 1
# Move elements of leftmost column one step upwards
for i in range(bottom, top - 1, -1):
curr = mat[i][left]
mat[i][left] = prev
prev = curr
left += 1
return mat
def rotate_matrix(data, rows, columns):
matrix = [0] * rows
for i in range(rows):
matrix[i] = [0] * columns
temp = data.split(" ")
it = 0
for i in range(rows):
for j in range(columns):
matrix[i][j] = temp[it]
it = it + 1
print(matrix)
return rotateMatrix(matrix)
# Utility Function
def printMatrix(mat):
for row in mat:
print(row)
if __name__ == "__main__":
sample = [[1,2,3,4],[4,5,6,4],[4, 5, 6, 4],[7,8,9,1]]
tt = (sample[:-1])[1:]
tt[0][0] = 10
print("===")
printMatrix(tt)
print("===")
printMatrix(sample)
print("===")
rows = len(sample)
columns = len(sample[0])
#sample_without_rows = (sample[:-1])[1:]
mm = [0] * (rows - 2)
for i in range(1, rows-1, 1):
mm[i-1] = [0] * (columns-2)
for j in range(1, columns -1, 1):
mm[i-1][j-1] = sample[i][j]
print(mm)
# 1234
# 4564
# 7894
# 1234
# 4565
# 7895
#print(len(m))
|
8d025a060a5eeb1ffe544c51e6fac20acad11e17
|
gcvalderrama/python_foundations
|
/book/NewYearChaos.py
| 1,760 | 3.671875 | 4 |
import unittest
from collections import defaultdict, deque
import sys
def minimumBribes(q):
moves = 0
for pos, val in enumerate(q):
d = (val - 1) - pos
if d > 2:
return "Too chaotic"
start = max(0, val - 2)
end = pos + 1
for j in range(start, end):
if q[j] > val:
moves += 1
return moves
def minimumBribesa(final):
n = len(final)
queue = [i for i in range(1, n + 1)]
state = defaultdict(int)
n = len(final)
for index in range(n):
state[final[index]] = index
movements = 0
ite = deque(queue[:])
while ite:
target = ite.popleft()
pos = state[target]
index = queue.index(target)
dist = abs(pos - index)
if dist > 2:
return "Too chaotic"
while queue[pos] != target:
movements += 1
temp = queue[index + 1]
queue[index + 1] = target
queue[index] = temp
index = index + 1
return movements
class Test(unittest.TestCase):
def test_case(self):
peaple = 5
target = [2, 1, 5, 3, 4]
result = minimumBribes(target)
self.assertEqual(3, result)
def test_case_caotic(self):
peaple = 5
target = [2, 5, 1, 3, 4]
result = minimumBribes(target)
self.assertEqual("Too chaotic", result)
def test_case_caotic_b(self):
target = [5, 1, 2, 3, 7, 8, 6, 4]
result = minimumBribes(target)
self.assertEqual("Too chaotic", result)
def test_case_caotic(self):
#arget = [1, 2, 3, 4, 5, 6, 7, 8]
target = [1, 2, 5, 3, 7, 8, 6, 4]
result = minimumBribes(target)
self.assertEqual(7, result)
|
445b7001f0d91f771d18a23cad1a80f7c1075e8a
|
gcvalderrama/python_foundations
|
/book/substringanagram.py
| 528 | 3.953125 | 4 |
# We have two words. We need to determine if the second word contains
# a substring with an anagram of the first word
import unittest
def anagram_substring(target, base):
if not base or not target:
return False
state = dict()
for c in base:
state[c] = 1
for c in target:
if c not in state:
return False
return True
class Test(unittest.TestCase):
def test_case(self):
result = anagram_substring("board", "keyboard")
self.assertTrue(result)
|
db9cbff3f932f0e76a7595e2508e2413cd7d5d7c
|
gcvalderrama/python_foundations
|
/atest/BestTimetoBuyandSellStock.py
| 545 | 3.5 | 4 |
if __name__ == '__main__':
nums = [7, 1, 5, 3, 6, 4]
max_profit = 0
for i in range(len(nums) - 1):
for j in range(1, len(nums)):
if nums[i] < nums[j]:
profit = nums[j] - nums[i]
if max_profit < profit:
max_profit = profit
print(max_profit)
max_profit = 0
min_price = float('inf')
for price in nums:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
print(max_profit)
|
6ff2b981135a212c37555433fd617b8d9ca429f6
|
gcvalderrama/python_foundations
|
/cracking/arraysStrings.py
| 1,039 | 4.09375 | 4 |
import unittest
def is_unique(target):
temp = ""
for c in target:
if c in temp:
return False
else:
temp += c
return True
def check_permutation(str_a, str_b):
longest = None
shortest = None
if len(str_a) >= len(str_b):
longest = str_a
shortest = str_b
else:
longest = str_b
shortest = str_a
shortest_map = dict()
for item in shortest:
shortest_map[item] = 1
for item in longest:
if item not in shortest_map:
return False
return True
class Test(unittest.TestCase):
def test_unique_characters_true(self):
target = "abcdfe"
result = is_unique(target)
self.assertTrue(result)
def test_unique_characters_false(self):
target = "abcdfeef"
result = is_unique(target)
self.assertFalse(result)
def test_permutations(self):
result = check_permutation("abcde", "abcdeabcdeabcdeabcdeabcde")
self.assertTrue(result)
|
529bf7d2d2c40413f3cae61b307652d0760e779e
|
gcvalderrama/python_foundations
|
/DailyCodingProblem/MoveZeros.py
| 1,348 | 4.03125 | 4 |
# Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order
# of the non-zero elements.#
# Example:
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# You must do this in-place without making a copy of the array.
# Minimize the total number of operations.
import unittest
# [1,2,3,0]
def move(target, index, anchor):
pivot = index
while pivot < anchor - 1:
temp = target[pivot]
target[pivot] = target[pivot + 1]
target[pivot + 1] = temp
pivot += 1
def move_zeros(target):
if not target or len(target) == 1:
return target
if len(list(filter(lambda x: x == 0, target))) == 0:
return target
anchor = len(target)
while anchor >= 0:
for index in range(0, anchor):
if target[index] == 0:
move(target, index, anchor)
anchor -= 1
break
else:
break
return target
class Test(unittest.TestCase):
def test_empty(self):
result = move_zeros([])
self.assertEqual([], result)
def test_case(self):
result = move_zeros([0, 1, 0, 3, 12])
self.assertEqual([1, 3, 12, 0, 0], result)
def test_case_a(self):
result = move_zeros([0, 0, 0, 0, 12])
self.assertEqual([12, 0, 0, 0, 0], result)
|
7daab64b964cc36b579c1352f227421c4faabe1f
|
gcvalderrama/python_foundations
|
/udemy/setnumberssum16.py
| 737 | 3.78125 | 4 |
import unittest
def count_sets(arr, target):
state = dict()
return recursive(arr, target, len(arr)-1, state)
def recursive(arr, total, i, state):
key = '{}-{}'.format(total, i)
if key in state:
return state[key]
if total == 0:
result = 1
elif total < 0:
result = 0
elif i < 0:
result = 0
elif total < arr[i]:
result = recursive(arr, total, i-1, state)
else:
result = recursive(arr, total - arr[i], i-1, state) + recursive(arr, total, i-1, state)
state[key] = result
return result
class Test(unittest.TestCase):
def test_case(self):
arr = [2, 4, 6, 10]
result = count_sets(arr, 16)
self.assertEqual(2, result)
|
d982dbcd9d34ecfd77824b309e688f9e077093d5
|
gcvalderrama/python_foundations
|
/DailyCodingProblem/phi_montecarlo.py
| 1,292 | 4.28125 | 4 |
import unittest
# The area of a circle is defined as πr ^ 2.
# Estimate π to 3 decimal places using a Monte Carlo method.
# Hint: The basic equation of a circle is x2 + y2 = r2.
# we will use a basic case with r = 1 , means area = π ^ 2 and x2 + y2 <=1
# pi = The ratio of a circle's circumference to its diameter
# https://www.youtube.com/watch?v=PLURfYr-rdU
import random
def get_rand_number(min_value, max_value):
"""
This function gets a random number from a uniform distribution between
the two input values [min_value, max_value] inclusively
Args:
- min_value (float)
- max_value (float)
Return:
- Random number between this range (float)
"""
range = max_value - min_value
choice = random.uniform(0, 1)
return min_value + range * choice
def estimate():
square_points = 0
circle_points = 0
for i in range(1000000):
x = get_rand_number(0, 1)
y = get_rand_number(0, 1)
dist = x ** 2 + y ** 2
if dist <= 1:
circle_points += 1
square_points += 1
pi = 4 * (circle_points / square_points)
return pi
class Test(unittest.TestCase):
def test_monte_carlo(self):
print(estimate())
if __name__ == "__main__":
unittest.main()
|
bea44d1998cb0d4d88e61b513364cca9f525f8bb
|
wing-py/matplotlib
|
/lorenz.py
| 733 | 3.5 | 4 |
import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(0,15,150)
y1=np.linspace(0,10,100)
y2=np.linspace(10,0,50)
y=np.append(y1,y2)
f=(2*x+y)/(3**0.5)
h=(2*y+x)/(3**0.5)
#plt.subplot(30,30,1)
#plt.plot(x,y)
#plt.subplot(30,30,2)
plt.plot(f,h)
plt.show()
'''
图形横坐标为一维空间,纵坐标为时间,反斜率则为速度
图形中左方曲线象征着光的传播,右方为相对于原点的一个移动的探测者
图1表示原点探测者,图2表示运动探测者以自身为参考系的世界观
引入洛伦兹变换,同时实现参考系转换和光速不变原理
表示洛伦兹变换为相对绝对时空观更真实的时空观
洛伦兹变换得证
'''
|
edcc3362e3e1932cae7d4bec660bc7b71e19aae5
|
GFSCompSci/cs2
|
/9-sorting/euclid.py
| 254 | 3.8125 | 4 |
val1 = input("Enter first number: ")
val2 = input("Enter second number: ")
if (val2 > val1): val1, val2 = val2, val1
print "a = %i b = %i" %(val1, val2)
print "Divide and conquer!"
a = val1
b = val2
while (b !=0): a, b = b, a%b
print "GCD is %i" %a
|
74ddb102f698ad2cc6ada0db7b51d991091bf4de
|
GFSCompSci/cs2
|
/4-oop/employee/employee3.py
| 1,295 | 3.9375 | 4 |
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
manCount = 0
clerkCount = 0
def __init__(self, name, salary, title):
self.name = name
self.salary = salary
self.title = title
Employee.empCount += 1
if self.title == "manager":
Employee.manCount += 1
if self.title == "clerk":
Employee.clerkCount +=1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary, ", Title: ", self.title
emp = []
while 1:
comm = raw_input("Enter 1 to add employee, 2 to list employees: ")
if comm == "1":
name = raw_input("Enter Name: ")
salary = input("Enter salary: ")
title = raw_input("Enter title: clerk or manager: ")
emp.append(Employee(name,salary,title))
elif comm == "2":
try:
for i in range(0,len(emp)):
emp[i].displayEmployee()
print "Total Employee %d, Total Manager %d, Total Clerk %d" % (Employee.empCount, Employee.manCount, Employee.clerkCount)
except IndexError:
print "No current employees"
else:
print "Invalid input"
|
062a7ceaec7acbef86dd1f36154627f5cfa9f10d
|
aldenkyle/DAT8_Homework
|
/Working/14_Yelp_hw_KSA.py
| 6,345 | 3.5625 | 4 |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (6, 4)
plt.rcParams['font.size'] = 9
# 1. Read yelp.csv into a DataFrame.
#Read yelp.csv into a DataFrame.
yelp = pd.read_csv('yelp.csv', header=0)
yelp.head()
yelp.columns
yelp.dtypes
#2. Create a new DataFrame that only contains the 5-star and 1-star reviews.
yelp5_1 = yelp[(yelp.stars == 1) | (yelp.stars == 5)]
#3. Split the new DataFrame into training and testing sets, using the review text
#as the only feature and the star rating as the response.
# define X and y
X = yelp5_1.text
y = yelp5_1.stars
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
print(X_train.shape)
print(X_test.shape)
#4. Use CountVectorizer to create document-term matrices from X_train and X_test.
#Hint: If you run into a decoding error, instantiate the vectorizer with
#the argument decode_error='ignore'.
from sklearn.feature_extraction.text import CountVectorizer
# instantiate the vectorizer
vect = CountVectorizer()
# learn training data vocabulary, then create document-term matrix
vect.fit(X_train)
X_train_dtm = vect.transform(X_train)
X_train_dtm
# transform testing data (using fitted vocabulary) into a document-term matrix
X_test_dtm = vect.transform(X_test)
X_test_dtm
#5. Use Naive Bayes to predict the star rating for reviews in the testing set,
#and calculate the accuracy.
# train a Naive Bayes model using X_train_dtm
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB()
nb.fit(X_train_dtm, y_train)
# make class predictions for X_test_dtm
y_pred_class = nb.predict(X_test_dtm)
# calculate accuracy of class predictions
from sklearn import metrics
metrics.accuracy_score(y_test, y_pred_class)
### Accuracy was 91.8%
#6. Calculate the AUC.
#Hint 1: Make sure to pass the predicted probabilities to roc_auc_score,
# not the predicted classes.
#Hint 2: roc_auc_score will get confused if y_test contains fives
#and ones, so you will need to create a new object that contains
#ones and zeros instead.
# predict (poorly calibrated) probabilities
y_pred_prob = nb.predict_proba(X_test_dtm)[:, 1]
y_pred_prob
##create binary test
y_test_binary = (y_test -1)/4
y_test_binary
metrics.roc_auc_score(y_test_binary, y_pred_prob)
### AUC was .94
#7. Plot the ROC curve.
# plot ROC curve
fpr, tpr, thresholds = metrics.roc_curve(y_test_binary, y_pred_prob)
plt.plot(fpr, tpr)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate (1 - Specificity)')
plt.ylabel('True Positive Rate (Sensitivity)')
#8. Print the confusion matrix, and calculate the sensitivity and specificity.
#Comment on the results.
metrics.confusion_matrix(y_test, y_pred_class)
'''array([[126, 58],
[ 25, 813]] '''
sensitivity = 813/838
specificity = 126 / (126+58)
specificity
### KSA Comment: Sensitivity = .97 , specificity = .68 , our model did well at prediciting 5s
### but not as well at predicting 1s (though this is confusing, )
#9. Browse through the review text for some of the false positives and false negatives.
#Based on your knowledge of how Naive Bayes works, do you have any theories about why
#the model is incorrectly classifying these reviews?
# print message text for the false negatives
X_test[y_test > y_pred_class]
# print message test for the false positives
X_test[y_test < y_pred_class]
### seems to have a lot of ! pts, though they're surprising, really not sure
#10. Let's pretend that you want to balance sensitivity and specificity.
#You can achieve this by changing the threshold for predicting a 5-star review.
# What threshold approximately balances sensitivity and specificity?
# histogram of predicted probabilities grouped by actual response value
df = pd.DataFrame({'probability':y_pred_prob, 'actual':y_test})
df.hist(column='probability', by='actual', sharex=True, sharey=True)
fpr, tpr, thresholds = metrics.roc_curve(y_test_binary, y_pred_prob)
plt.plot(fpr, tpr)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate (1 - Specificity)')
plt.ylabel('True Positive Rate (Sensitivity)')
### KSA Comment: a threshold of .9 or higher might have helped, I think I understand
### what this means, but I have no clue how to do it.
#11. Let's see how well Naive Bayes performs when all reviews are included,
#rather than just 1-star and 5-star reviews:
#Define X and y using the original DataFrame from step
#1. (y should contain 5 different classes.)
#Split the data into training and testing sets.
#Calculate the testing accuracy of a Naive Bayes model.
#Compare the testing accuracy with the null accuracy.
#Print the confusion matrix.
#Comment on the results.
X = yelp.text
y = yelp.stars
#Split the data into training and testing sets.
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
print(X_train.shape)
print(X_test.shape)
from sklearn.feature_extraction.text import CountVectorizer
# instantiate the vectorizer
vect = CountVectorizer()
# learn training data vocabulary, then create document-term matrix
vect.fit(X_train)
X_train_dtm = vect.transform(X_train)
X_train_dtm
# transform testing data (using fitted vocabulary) into a document-term matrix
X_test_dtm = vect.transform(X_test)
X_test_dtm
# train a Naive Bayes model using X_train_dtm
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB()
nb.fit(X_train_dtm, y_train)
# make class predictions for X_test_dtm
y_pred_class = nb.predict(X_test_dtm)
# calculate accuracy of class predictions
from sklearn import metrics
metrics.accuracy_score(y_test, y_pred_class)
### KSA Comment: Testing accuracy is .47', this is better than the null (which I think is
### .2 because we would randomly guess 1 in 5 correcly), but not amazing.
metrics.confusion_matrix(y_test, y_pred_class)
'''array([[ 55, 14, 24, 65, 27],
[ 28, 16, 41, 122, 27],
[ 5, 7, 35, 281, 37],
[ 7, 0, 16, 629, 232],
[ 6, 4, 6, 373, 443]]'''
### KSA Comment -- it looks like though we weren't perfect, we often classified
### star rankings one number off
|
a449dc6d6cacc3a96c795f73972c14bf16408086
|
jros14/personal-work
|
/Game of Life/GameOfLife.py
| 4,744 | 3.703125 | 4 |
import numpy
import random
import pygame
class Grid:
def __init__(self):
self.grid = []
self.next_grid = []
self.display = Display()
self.create_random_grid()
self.display.main_display_loop(self)
def create_random_grid(self, grid_dimension=None):
if grid_dimension is None:
length = 40 # default grid size
else:
length = grid_dimension
for row in range(length):
self.grid.append(random.choices(["o", "_"], k=length, weights=[20, 80]))
self.display_grid()
def display_grid(self):
for row_index in range(len(self.grid)):
for cell_index in range(len(self.grid[row_index])):
if self.grid[row_index][cell_index] == "o":
self.display.draw_white_rectangle([row_index * 10, cell_index * 10, 10, 10])
if self.grid[row_index][cell_index] == "_":
self.display.draw_black_rectangle([row_index * 10, cell_index * 10, 10, 10])
def neighboring_cells(self, cell_location):
# returns the number of o's and _'s surrounding cell_location
x_value = cell_location[0]
y_value = cell_location[1]
num_o_neighbors = 0
num_blank_neighbors = 0
# starts at top left corner and goes around counter-clockwise
neighbors = [[x_value - 1, y_value - 1], [x_value - 1, y_value], [x_value - 1, y_value + 1],
[x_value, y_value + 1],
[x_value + 1, y_value + 1], [x_value + 1, y_value], [x_value + 1, y_value - 1],
[x_value, y_value - 1]]
# goes through each position and removes out-of-bounds cells, leaving only the surrounding cells that matter
for cell in reversed(neighbors):
if cell[0] < 0 or cell[1] < 0 or cell[0] >= len(self.grid) or cell[1] >= len(self.grid):
neighbors.remove(cell)
# go through each of the cells remaining (the ones that matter) and add up the number of o and _ neighbors
for neighbor in neighbors:
if self.grid[neighbor[0]][neighbor[1]] == "o":
num_o_neighbors += 1
else:
num_blank_neighbors += 1
return num_o_neighbors, num_blank_neighbors
def build_next_grid(self):
self.next_grid = []
for row in self.grid:
self.next_grid.append(row)
# for loops iterate through the whole grid (assumes a square grid) and determine how to change each position,
# and store this as the self.next_grid
for row in range(len(self.grid)):
for column in range(len(self.grid)):
num_o_neighbors, num_blank_neighbors = self.neighboring_cells([row, column])
if num_o_neighbors < 2: # off if fewer than 2 neighbors
self.next_grid[row][column] = "_"
# below: if it's on and has 2 or 3 neighbors, stay on
elif (num_o_neighbors == 2 or num_o_neighbors == 3) and self.grid[row][column] == "o":
self.next_grid[row][column] = "o"
elif self.grid[row][column] == "o" and num_o_neighbors > 3: # If on and >3 neighbors, turn off
self.next_grid[row][column] = "_"
elif self.grid[row][column] == "_" and num_o_neighbors == 3: # If off and has 3 neighbors, turn on
self.next_grid[row][column] = "o"
self.save_new_grid_as_current_grid()
def save_new_grid_as_current_grid(self):
self.grid = []
for row in self.next_grid:
self.grid.append(row)
self.display_grid()
class Display:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode([400, 400])
pygame.display.set_caption("Julian's Game of Life")
self.done = False
self.clock = pygame.time.Clock()
self.white = (255, 255, 255)
self.black = (0, 0, 0)
self.screen.fill(self.black)
# self.main_display_loop()
def main_display_loop(self, grid):
while not self.done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.done = True
grid.build_next_grid()
# pygame.draw.rect(screen, green, [300, 200, 20, 20])
pygame.display.update()
# 20 frames per second:
self.clock.tick(20)
pygame.quit()
def draw_white_rectangle(self, location_size):
pygame.draw.rect(self.screen, self.white, location_size)
def draw_black_rectangle(self, location_size):
pygame.draw.rect(self.screen, self.black, location_size)
g = Grid()
|
d53a5033fd448c4c98e1817b0c6795103e77beaf
|
biyam/This_is_Coding_Test
|
/정렬/part2/위에서아래로.py
| 439 | 3.828125 | 4 |
n = int(input())
array = []
for i in range(n):
num = int(input())
array.append(num)
def quick_sort(array):
if len(array) <= 1:
return array
pivot = array[0]
tail = array[1:]
# pivot의 왼쪽과 오른쪽
left = [x for x in tail if x < pivot]
right = [x for x in tail if x > pivot]
return left + [pivot] + right
res = quick_sort(array)
for i in res:
print(i, end = ' ')
|
2815ab701aae131cf81a11a77c1b69e49776cf56
|
ermolalex/tdd_money
|
/currency.py
| 924 | 3.953125 | 4 |
# -*- coding: utf-8 -*-
class Money():
def __init__(self, amount=0, currency="RUR"):
self._amount = amount
self._currency = currency
def __eq__(self, money):
return self._amount == money._amount and self._currency == money._currency
def __ne__(self, money):
return self._amount != money._amount or self._currency != money._currency
def __add__(self, money):
return Money(self._amount + money._amount, self._currency)
@staticmethod
def dollar(amount):
return Money(amount, "USD")
@staticmethod
def eur(amount):
return Money(amount, "EUR")
def currency(self):
return self._currency
def __str__(self):
return '{} {}'.format(self._currency, self._amount)
def mult(self, multiplier):
return Money(self._amount * multiplier, self._currency)
|
864e69f180897532924395a94a8bc09c27bba161
|
dsc-sookmyung/2021-MAFIA-algorithm-study
|
/02-Stack_Queue/고성연/프린터.py
| 592 | 3.640625 | 4 |
from collections import deque
def solution(priorities, location):
answer = 0
index_queue = deque(range(len(priorities)))
priorities_queue = deque(priorities)
while True:
max_priorities = max(priorities_queue)
priorities_head = priorities_queue.popleft()
index_head = index_queue.popleft()
if priorities_head == max_priorities:
answer += 1
if index_head == location:
break
else:
priorities_queue.append(priorities_head)
index_queue.append(index_head)
return answer
|
d2c4315cdc60837c1212eb380c4ca80058699191
|
dsc-sookmyung/2021-MAFIA-algorithm-study
|
/04-Sort/권은지/K번째수.py
| 296 | 3.578125 | 4 |
def solution(array, commands):
answer = []
for i in range(len(commands)):
start = commands[i][0]
end = commands[i][1]
cut = array[start-1:end]
cut.sort()
place = commands[i][2]
num = cut[place-1]
answer.append(num)
return answer
|
d8bc18bc0cbba334d9f38a6883f6309ed4a09425
|
dsc-sookmyung/2021-MAFIA-algorithm-study
|
/06-DFS_BFS/유지연/타겟 넘버.py
| 1,510 | 3.59375 | 4 |
# 데이터가 그래프 형태로 이루어져 있고, 그래프 끝에 노드까지 가서 그 값을 더하거나 뺀 값 얻어야함 -> DFS
# Solution1 : DFS - 반복
def iterative_solution(numbers, target):
result_list = [0]
for i in range(len(numbers)):
temp_list = []
for j in range(len(result_list)):
temp_list.append(result_list[j] - numbers[i])
temp_list.append(result_list[j] + numbers[i])
result_list = temp_list
print(result_list)
return result_list.count(target)
# Solution2 : DFS - 재귀
def solution(numbers, target):
cnt = 0
def operator(numbers, target, idx=0):
if idx < len(numbers):
numbers[idx] *= 1
operator(numbers, target, idx+1)
numbers[idx] *= -1
operator(numbers, target, idx+1)
elif sum(numbers) == target:
nonlocal cnt
cnt += 1
operator(numbers, target)
return cnt
# 공간 복잡도 개선
def solution(numbers, target):
cnt = 0
len_numbers = len(numbers)
def operator(idx=0):
if idx < len_numbers:
numbers[idx] *= 1
operator(idx+1)
numbers[idx] *= -1
operator(idx+1)
elif sum(numbers) == target:
nonlocal cnt
cnt += 1
operator()
return cnt
# 참고한 블로그1 : https://sexy-developer.tistory.com/40
# 참고한 블로그2 :https://itholic.github.io/kata-target-number/
|
e0ea907ac144d00560feb2520d48be1402e5a598
|
douzujun/LeetCode
|
/py56_1003_numOfBurgers.py
| 1,062 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
class Solution:
def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int):
low, high = 0, tomatoSlices // 4
# 巨无霸汉堡:4 片番茄和 1 片奶酪
# 小皇堡:2 片番茄和 1 片奶酪
print(low, high)
while low <= high:
mid = (low + high) // 2 # 巨无霸数量
tomatos, cheeses = tomatoSlices - mid*4, cheeseSlices - mid
# 符合 小皇煲 的 数据比
if tomatos == cheeses*2:
return [mid, cheeses]
elif tomatos > cheeses*2:
low = mid + 1
else:
high = mid - 1
return []
s = Solution()
#print(s.numOfBurgers(tomatoSlices = 48, cheeseSlices = 16))
print(s.numOfBurgers(tomatoSlices = 16, cheeseSlices = 7))
#print(s.numOfBurgers(tomatoSlices = 17, cheeseSlices = 4))
#print(s.numOfBurgers(tomatoSlices = 0, cheeseSlices = 0))
|
d6a2c672d165b23065a4b69fe334e9e7c03aa44d
|
douzujun/LeetCode
|
/py03_1078_findOcurrences.py
| 649 | 3.703125 | 4 |
# -*- coding: utf-8 -*-
class Solution:
def findOcurrences(self, text: str, first: str, second: str): #-> List[str]:
words = text.split(' ')
res = []
wlen = len(words)
for i in range(0, wlen - 2):
if words[i] == first and words[i + 1] == second:
res.append(words[i + 2])
return res
s = Solution()
print(s.findOcurrences(text = "alice is a good girl she is a good student", first = "a", second = "good"))
print(s.findOcurrences(text = "we will we will rock you", first = "we", second = "will"))
|
a4c125d1d4d713de23543bcee55e06f457a8c6b6
|
douzujun/LeetCode
|
/py5_longestPalindrome.py
| 655 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 26 18:03:04 2020
@author: douzi
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
result = ""
for i in range(length):
sum1 = ""
sum2 = ""
for str1 in s[i:]:
sum1 = sum1 + str1
sum2 = str1 + sum2
if sum1 == sum2 and len(sum1) > len(result):
result = sum1
else:
continue
return result
s = Solution()
print(s.longestPalindrome('babad'))
print(s.longestPalindrome('cbbd'))
|
95b07563e8c1d081abbed9706a1e648d44c9b549
|
douzujun/LeetCode
|
/py18_922_sortArrayByParity.py
| 533 | 3.609375 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 01:34:53 2020
@author: douzi
"""
class Solution:
def sortArrayByParityII(self, A):
Alen = len(A)
res = [0] * Alen
even, odd = 0, 1
for e in A:
if e % 2 == 0:
res[even] = e
even = even + 2
else:
res[odd] = e
odd = odd + 2
print(res)
return res
s = Solution()
print(s.sortArrayByParityII([4,2,5,7]))
|
e0b5213c06c03a2be402116a01d1771a70ed7b73
|
douzujun/LeetCode
|
/py08_575_distributeCandies.py
| 569 | 3.65625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 19:47:00 2020
@author: douzi
"""
class Solution:
def distributeCandies(self, candies) -> int:
clen = len(candies)
ave = clen // 2
cset = set()
for e in candies:
cset.add(e)
if len(cset) == ave:
break
# print(cset)
return len(cset)
s = Solution()
print(s.distributeCandies(candies = [1,1,2,2,3,3]))
print(s.distributeCandies(candies = [1,1,2,3]))
|
23150de0cc769f44723ece360aa4582474ee70f6
|
douzujun/LeetCode
|
/py78_20_isValid.py
| 997 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
class Solution:
def isValid(self, s: str) -> bool:
ans = []
for e in s:
if e in ['(', '[', '{']:
ans.append(e)
elif e == ')':
if ans:
t = ans.pop()
if t != '(':
return False
else:
return False
elif e == ']':
if ans:
t = ans.pop()
if t != '[':
return False
else:
return False
elif e == '}':
if ans:
t = ans.pop()
if t != '{':
return False
else:
return False
if ans:
return False
else:
return True
s = Solution()
print(s.isValid("()[]{}"))
print(s.isValid(']'))
|
3f554bfd6d303677bf51bd44a09b32ac329b2a74
|
douzujun/LeetCode
|
/142.环形链表-ii.py
| 773 | 3.578125 | 4 |
#
# @lc app=leetcode.cn id=142 lang=python3
#
# [142] 环形链表 II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return None
fast, slow = head, head
while True:
if not (fast and fast.next):
return None
slow, fast = slow.next, fast.next.next
if slow == fast:
break
fast = head
while fast != slow:
slow, fast = slow.next, fast.next
return fast
# @lc code=end
|
99d73368dd42d92f4115eab4424bdf8fb19267e5
|
douzujun/LeetCode
|
/py75_367_isPerfect.py
| 334 | 3.609375 | 4 |
# -*- coding: utf-8 -*-
class Solution:
def isPerfectSquare(self, num: int) -> bool:
for i in range(1, num+1):
if i**2 == num:
return True
elif i**2 > num:
return False
s = Solution()
print(s.isPerfectSquare(16))
print(s.isPerfectSquare(1))
|
1d2942e3b8b6adf93071e31050039c310c4b9bfd
|
douzujun/LeetCode
|
/py72_1184_distanceBetweenBusStops.py
| 891 | 3.859375 | 4 |
# -*- coding: utf-8 -*-
class Solution:
def distanceBetweenBusStops(self, distance, start: int, destination: int) -> int:
forward = 0
backward = 0
dlen = len(distance)
for i in range(0, dlen):
forward += distance[(start + i) % dlen]
if (start + i + 1) % dlen == destination:
break
for i in range(0, dlen):
backward += distance[(start + dlen - i - 1) % dlen]
if (start + dlen - i - 1) % dlen == destination:
break
# print(forward, backward)
return forward if forward < backward else backward
s = Solution()
print(s.distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 1))
print(s.distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 3))
|
574ae2836da910748210d3f2babd54565619545a
|
scroberts/Library
|
/MyUtil.py
| 1,883 | 3.53125 | 4 |
#!/usr/bin/env python3
# external modules
import re
# my modules
def strip_xml(mystring):
return(re.sub('<[^>]*>', '', mystring))
def get_all_none_indiv(question):
# Expects one of the following:
# 'A' = 'All'
# 'N' = 'None'
# 'I' = 'Individual Y/N'
# Returns 'All', 'None' or 'Individual'
ans = ''
while (ans.upper() != ('A' or 'N' or 'I')):
print(question,end="")
ans = input()
if ans.upper() == 'A':
return 'All'
elif ans.upper() == 'N':
return 'None'
elif ans.upper() == 'I':
return 'Individual'
def get_yn(question):
ans = ''
while (ans.upper() != 'Y') and (ans.upper() != 'N'):
print(question,end="")
ans = input()
if ans.upper() == 'Y':
return True
return False
def remove_dict_from_list(thelist, key, value):
# removes dictionaries containing the supplied key/value from a list of dictionaries
# note that lists are passed by reference so the input list is changed
thelist[:] = [d for d in thelist if d.get(key) != value]
def mod_dict_in_list(thelist, checkkey, checkvalue, changekey, changevalue):
# modifies entries in a list of dictionaries based on check criteria
outlist = []
for d in thelist:
if checkkey in d.keys():
if d[checkkey] == checkvalue:
d[changekey] = changevalue
outlist.append(d)
return(outlist)
def test_mod():
mylist = [{'name':'scott'}, {'name':'roberts'}]
outlist = mod_dict_in_list(mylist, 'name', 'scott', 'flag', False)
print(outlist)
def test_strip():
mystring = '<p>Desc of test collection.</p><p> </p>'
print(strip_xml(mystring))
if __name__ == '__main__':
print("Running module test code for",__file__)
test_mod()
test_strip()
|
24cf6864b5eb14d762735a27d79f96227438392f
|
ramalldf/data_science
|
/deep_learning/datacamp_cnn/image_classifier.py
| 1,545 | 4.28125 | 4 |
# Image classifier with Keras
from keras.models import Sequential
from keras.layers import Dense
# Shape of our training data is (50, 28, 28, 1)
# which is 50 images (at 28x28) with only one channel/color, black/white
print(train_data.shape)
model = Sequential()
# First layer is connected to all pixels in original image
model.add(Dense(10, activation='relu',
input_shape=(784,)))
# 28x28 = 784, so one input from every pixel
# More info on the Dense layer args: https://keras.io/api/layers/core_layers/dense/
# First arg is units which corresponds to dimensions of output
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
# Unlike hidden layers, output layer has 3 for output (for 3 classes well classify)
# and a softmax layer which is used for classifiers
model.add(Dense(3, activation='softmax'))
# Model needs to be compiled before it is fit. loss tells it to optimize for classifier
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Prepare data (needs to be tabular so 50 rows and 784 cols)
train_data = train_data.reshape((50, 784))
# Fit model
# To avoid overfiting we set aside 0.2 of images for validation set
# We'll send data through NN 3 times (epochs) and test on that validation set
model.fit(train_data, train_labels,
validation_split=0.2,
epochs=3)
# Evaluate on test set that's not evaluation set using the evaluation function
test_data = test_data.reshape((10, 784))
model.evaluate(test_data, test_labels)
|
9aeeabeb134a76adde0d1a417de6b43a3321b55f
|
cshintov/Learning-C
|
/c_projects/python_vm/testcases/recursive/reclcm_hcf.py
| 332 | 3.671875 | 4 |
def hcf(a, b):
if a < b:
return hcf(a, b - a)
elif a > b:
return hcf(a - b, b)
else:
return a
def lcm(a, b):
return a * b / hcf(a, b)
print 16
print 40
print hcf(16, 40)
print lcm(16, 40)
print 16
print 24
print hcf(16, 24)
print lcm(16, 24)
print 5
print 3
print hcf(5, 3)
print lcm(5, 3)
|
f26d127894dbe54916f773def305f2431e459db3
|
kingcunha23/python-learning
|
/n_impares.py
| 193 | 3.890625 | 4 |
# -*- coding: utf-8 -*-
n = int(input('Digite um número inteiro: '))
i = 0
y = (n // 10 ** i ) % 10
j = 0
while y != 0:
y = (n // 10 ** i ) % 10
i = i + 1
j = j + y
print(j)
|
943abd4fe4bbfe18d2fe476be17cccf4545a2581
|
kingcunha23/python-learning
|
/fizz.py
| 150 | 4.15625 | 4 |
# -*- coding: utf-8 -*-
x = int(input('Digite um inteiro: '))
if x % 3 == 0 and x % 5 == 0 :
print('FizzBuzz')
else:
print(x)
|
6f1fdf99f378119e89bae468fce57382da125f4b
|
hmjyn/fishmen
|
/fishman.py
| 955 | 3.6875 | 4 |
from random import randint
class fishman:
def __init__(self):
self.name="fishman"
self.live=100
self.livestatus=1
self.fishnb=0
self.fishchick=0
self.fishislandnb=0
def fishhamter(self):
#rrrdd=1
if randint(1,5) == 3:
self.fishnb+=1
#print rrrdd
print self.fishnb
def fishtochick(self):
self.fishnb-=1
self.fishchick+=1
def foodtolive(self):
self.fishnb-=1
self.live+=50
def printall(self):
print self.name
print self.live
print self.livestatus
print self.fishnb
print self.fishchick
print self.fishislandnb
if __
# print "name="+self.name
# print "live="+self.live
# print "livestatus="+self.livestatus
# print "fishnb="+self.fishnb
# print "fishchick="+self.fishchick
# print "fishislandnb="+self.fishislandnb
|
a4e0edd928e4f212d58cfc29277cf69417702622
|
DiegoPacheco2/gitpython
|
/ex003video10.py
| 152 | 3.953125 | 4 |
val1=int(input('Digite um valor: '))
val2=int(input('Digite outro valor: '))
print('A soma entre {} e {} é igual a {}!'.format(val1, val2, val1+val2))
|
89aa4c5a42c98986270f76c8c5b983e7ccdf207c
|
DiegoPacheco2/gitpython
|
/ex010video18.py
| 176 | 3.703125 | 4 |
dinheiro=float(input('Quanto dinheiro você tem na carteira? R$'))
print('Com R${} você pode comprar US${:.2f} e €${:.2f}'.format(dinheiro,dinheiro / 3.76,dinheiro / 4.27))
|
60b60160f8677cd49552fedcf862238f9128f326
|
Prash74/ProjectNY
|
/LeetCode/1.Arrays/Python/reshapematrix.py
| 1,391 | 4.65625 | 5 |
"""
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of the wanted
reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original
matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output
the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4
matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the
original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.
"""
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if r*c != len(nums)*len(nums[0]):
return nums
nums = [i for item in nums for i in item]
val = []
for i in range(0, len(nums), c):
val.append(nums[i:i+c])
return val
nums = [[1, 2], [3, 4]]
r = 1
c = 4
print matrixReshape(nums, r, c)
|
b08bda08ed82d71f6421e3f56407be10107b87d6
|
SarthakJShetty/Donkey
|
/donkey/mixers.py
| 2,473 | 3.5 | 4 |
'''
mixers.py
Classes to wrap motor controllers into a functional drive unit.
'''
import time
import sys
from donkey import actuators
class BaseMixer():
def update_angle(self, angle):
pass
def update_throttle(self, throttle):
pass
def update(self, throttle=0, angle=0):
'''Convenience function to update
angle and throttle at the same time'''
self.update_angle(angle)
self.update_throttle(throttle)
class AckermannSteeringMixer(BaseMixer):
'''
Mixer for vehicles steered by changing the angle of the front wheels.
This is used for RC cars
'''
def __init__(self,
steering_actuator=None,
throttle_actuator=None):
self.steering_actuator = steering_actuator
self.throttle_actuator = throttle_actuator
def update(self, throttle, angle):
self.steering_actuator.update(angle)
self.throttle_actuator.update(throttle)
class DifferentialDriveMixer:
"""
Mixer for vehicles driving differential drive vehicle.
Currently designed for cars with 2 wheels.
"""
def __init__(self, left_motor, right_motor):
self.left_motor = left_motor
self.right_motor = right_motor
self.angle=0
self.throttle=0
def update(self, throttle, angle):
self.throttle = throttle
self.angle = angle
if throttle == 0 and angle == 0:
self.stop()
else:
l_speed = ((self.left_motor.speed + throttle)/3 - angle/5)
r_speed = ((self.right_motor.speed + throttle)/3 + angle/5)
l_speed = min(max(l_speed, -1), 1)
r_speed = min(max(r_speed, -1), 1)
self.left_motor.turn(l_speed)
self.right_motor.turn(r_speed)
def test(self, seconds=1):
telemetry = [(0, -.5), (0, -.5), (0, 0), (0, .5), (0, .5), (0, 0), ]
for t in telemetry:
self.update(*t)
print('throttle: %s angle: %s' % (self.throttle, self.angle))
print('l_speed: %s r_speed: %s' % (self.left_motor.speed,
self.right_motor.speed))
time.sleep(seconds)
print('test complete')
def stop(self):
self.left_motor.turn(0)
self.right_motor.turn(0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.