text
stringlengths 37
1.41M
|
---|
"""Group Anagrams
Write a method to sort an array of strings so that all the anagrams are next to
each other.
Hints:
#177
How do you check if two words are anagrams of each other? Think about what the definition
of "anagram" is. Explain it in your own words.
#182
Two words are anagrams if they contain the same characters but in different orders.
How can you put characters in order?
#263
Can you leverage a standard sorting algorithm?
#342
Do you even need to truly "sort"? Or is just reorganizing the list sufficient?
"""
'''Method 1
1. Transform each string to a tuple (sorted string, original string). For instance, “cat” will be mapped to (“act”, “cat”).
2. Sort all the tuples by the sorted string, thus, anagrams are grouped together.
3. Output original strings if they share the same sorted string.
Time Complexity : O(nlogn)
'''
def group_anagrams(input):
tuple_array = [(sorted(word), word) for word in input]
tuple_array.sort(key=lambda x: x[0])
return [pair[1] for pair in tuple_array]
'''Method 2
1. Transform each string to a tuple (sorted string, original string). For instance, “cat” will be mapped to (“act”, “cat”).
2. Save the tuples to hash map.
3. Output original strings if they share the same sorted string.
Time Complexity : O(n)
'''
from collections import defaultdict
def group_anagrams_with_hashmap(input):
hashmap = defaultdict(list)
for word in input:
sorted_word = ''.join(sorted(word))
hashmap[sorted_word].append(word)
return [value for value in hashmap.values()]
import unittest
class Test(unittest.TestCase):
def setUp(self):
self.input = ['cat', 'door', 'act', 'dog', 'odor']
def test_group_anagram_with_sorting(self):
self.assertListEqual(group_anagrams(self.input), ['cat', 'act', 'dog', 'door', 'odor'])
def test_group_anagram_with_hashmap(self):
self.assertListEqual(group_anagrams_with_hashmap(self.input), [['cat', 'act'], ['door', 'odor'], ['dog']])
if __name__ == "__main__":
unittest.main()
|
def merge_sort(alist):
print("Splitting ",alist)
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
merge_sort(lefthalf)
merge_sort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i = i + 1
else:
alist[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
alist[k] = righthalf[j]
j = j + 1
k = k + 1
print("Merging ",alist)
import unittest
class Test(unittest.TestCase):
def test_merge_sort(self):
alist = [54,26,93,17,77,31,44,55,20]
merge_sort(alist)
self.assertListEqual(alist, [17, 20, 26, 31, 44, 54, 55, 77, 93])
if __name__ == "__main__":
unittest.main()
|
"""Permutations without Dups
Write a method to compute all permutations of a string of unique characters.
Hints:
#150
Approach 1: Suppose you had all permutations of abc. How can you use that to get all
permutations of abcd?
#185
Approach 1 :The permutations of abc represent all ways of ordering abc. Now, we want
to create all orderings of abcd. Take a specific ordering of abed, such as bdca. This
bdca string represents an ordering of abc, too: Remove the d and you get bca. Given
the string bca, can you create all the "related" orderings that include d, too?
#200
Approach 1: Given a string such as bca, you can create all permutations of abcd that
have {a, b, c} in the order bca by inserting d into each possible location: dbca,
bdca, bcda, bcad. Given all permutations of abc, can you then create all permutations
of abcd?
#267
Approach 1: You can create all permutations of abcd by computing all permutations of
abc and then inserting d into each possible location within those.
#278
Approach 2: If you had all permutations of two-character substrings, could you generate
all permutations of three-character substrings?
#309
Approach 2: To generate a permutation of abcd, you need to pick an initial character. It
can be a, b, c, or d. You can then permute the remaining characters. How can you use
this approach to generate all permutations of the full string?
#335
Approach 2: To generate all permutations of abcd, pick each character (a, b, c, or d)
as a starting character. Permute the remaining characters and prepend the starting
character. How do you permute the remaining characters? With a recursive process that
follows the same logic.
#356
Approach 2: You can implement this approach by having the recursive function pass
back the list of the strings, and then you prepend the starting character to it. Or, you can
push down a prefix to the recursive calls.
"""
'''Method 1
It is the way to find permutation by order of characters
string[0], prev_list, next_list = c, [''], [c]
string[0], prev_list, next_list = b, [c], [bc]
string[0], prev_list, next_list = b, [c], [cb]
string[0], prev_list, next_list = a, [bc, cb], [abc]
string[0], prev_list, next_list = a, [bc, cb], [abc, bac]
string[0], prev_list, next_list = a, [bc, cb], [abc, bac, bca]
string[0], prev_list, next_list = a, [bc, cb], [abc, bac, bca, acb]
'''
def find_permutation(string):
if len(string) == 0:
return ['']
prev_list = find_permutation(string[1:len(string)])
next_list = []
for i in range(len(prev_list)):
for j in range(len(string)):
new_str = prev_list[i][0:j] + string[0] + prev_list[i][j:len(string)-1]
if new_str not in next_list:
next_list.append(new_str)
return next_list
'''Method 2
This is the way to swap two values.
"abc" , index start, i = 2, 2
"acb" , index start, i = 1, 2
"abc" , index start, i = 1, 2
"bac" , index start, i = 0, 1
"bca" , index start, i = 1, 2
'''
def find_permutations_by_swapping(string):
result = []
__find_permutations_by_swapping(string, 0, result)
return result
def __find_permutations_by_swapping(string, start, result):
if start >= len(string):
result.append(string)
else:
for i in range(start, len(string)):
string = swap(string, start, i)
__find_permutations_by_swapping(string, start+1, result)
string = swap(string, start, i)
def swap(string, i, j):
temp = string[i]
string = string[:i] + string[j] + string[i+1:]
string = string[:j] + temp + string[j+1:]
return string
'''Method 3
With seperating to prefix and suffix, it makes permutation.
("", "abc")
("a", "bc")
("ab", "c")
("ac", "b")
("abc", "")
("acb", "")
'''
def find_permutations_by_recursion(string):
result = []
__find_permutations_by_recursion("", string, result)
return result
def __find_permutations_by_recursion(prefix, suffix, result):
if not len(suffix):
result.append(prefix)
else:
for i in range(len(suffix)):
__find_permutations_by_recursion(
prefix+suffix[i], suffix[:i]+suffix[i+1:], result)
import unittest
class Test(unittest.TestCase):
def test_swap_permutation(self):
self.assertListEqual(find_permutations_by_swapping("abc"),
['abc', 'acb', 'bac', 'bca', 'cba', 'cab'])
def test_recursive_permutation(self):
self.assertListEqual(find_permutations_by_recursion("abc"),
['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
def test_permutation(self):
self.assertListEqual(find_permutation("abc"),
['abc', 'bac', 'bca', 'acb', 'cab', 'cba'])
if __name__ == "__main__":
unittest.main()
|
"""Delete Middle Node
Implement an algorithm to delete a node in the middle
(i.e., any node but the first and last node, not necessarily the exact middle)
of a singly linked list, given only access to that node.
EXAMPLE
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but the new linked list looks like a -> b -> d -> e -> f
"""
from SingleLinkedList import SingleLinkedList
import unittest
def delete_middle_node(linkedlist):
first_runner = linkedlist.head
second_runner = first_runner.next
previous_node = None
while second_runner is not None:
if second_runner.next is None:
previous_node.next = first_runner.next
second_runner = second_runner.next
elif second_runner.next.next is None:
first_runner.next = first_runner.next.next
second_runner = second_runner.next.next
else:
second_runner = second_runner.next.next
previous_node = first_runner
first_runner = first_runner.next
class Test(unittest.TestCase):
def test_delete_middle_node(self):
sll = SingleLinkedList()
sll.append(10)
sll.append(9)
sll.append(9)
sll.append(5)
sll.append(1)
delete_middle_node(sll)
self.assertEqual(sll.values(), "10 -> 9 -> 5 -> 1 -> None")
delete_middle_node(sll)
self.assertEqual(sll.values(), "10 -> 5 -> 1 -> None")
if __name__ == "__main__":
unittest.main() |
import unittest
'''Method 1
Time complexity : O(2^n)
'''
def fibonacci(n):
if n == 0 or n == 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
'''Method 2
Time complexity : O(n)
'''
def fibonacci_top_down(n):
return __fibonacci_top_down(n, {})
def __fibonacci_top_down(n, memo):
if n == 0 or n == 1:
return n
if n not in memo:
memo[n] = __fibonacci_top_down(n-1, memo) + __fibonacci_top_down(n-2, memo)
return memo[n]
'''Method 3
Time complexity : O(n)
'''
def fibonacci_bottom_up(n):
if n == 0 or n == 1:
return n
a = 0
b = 1
for _ in range(2, n):
c = a + b
a = b
b = c
return a + b
class Test(unittest.TestCase):
def test_fibonacci(self):
self.assertEqual(fibonacci(5), 5)
self.assertEqual(fibonacci_top_down(6), 8)
self.assertEqual(fibonacci_bottom_up(7), 13)
if __name__ == "__main__":
unittest.main() |
# Below is a link to a 10-day weather forecast at weather.com
# Use urllib and BeautifulSoup to scrape data from the weather table.
# Print a brief synopsis of the weather for the next 10 days.
# Include the day, date, high temp, low temp, and chance of rain.
# You can customize the text as you like, but it should be readable
# for the user. You will need to target specific classes or other
# attributes to pull some parts of the data.
# (e.g. Wednesday, March 22: the high temp will be 48 with a low of 35, and a 20% chance of rain). (25pts)
import urllib.request
from bs4 import BeautifulSoup
url = "https://weather.com/weather/tenday/l/USIL0225:1:US"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read(), "html.parser")
print(soup.prettify())
headers = [x.text.strip() for x in soup.findAll("th")]
data_list = [[y.text.strip() for y in x.findAll("td")] for x in soup.find("table",{"class" : "twc-table"}).findAll("tr")]
data_list = data_list[1:]
for i in range(len(data_list)):
del(data_list[i][0])
if i != 0:
if data_list[i][0][:3] == "Wed":
day_of_week = "Wednesday"
elif data_list[i][0][:3] == "Thu":
day_of_week = "Thursday"
elif data_list[i][0][:3] == "Tue":
day_of_week = "Tuesday"
elif data_list[i][0][:3] == "Sat":
day_of_week = "Saturday"
else:
day_of_week = data_list[i][0][:3] + "day"
length_of_day = 3
else:
day_of_week = data_list[i][0][:5]
length_of_day = 5
print(day_of_week + ", " + data_list[i][0][length_of_day:] + ": the high will be " + data_list[i][2][:3] + "the low will be " + data_list[i][2][3:] + ", there " + data_list[i][5] + " chance of rain.")
|
# def addN(n):
# def add(x):
# return x+n
# return add
class addN(object):
def __init__(self, n):
self.n = n
# 括号运算符
def __call__(self, x):
return x+self.n
add3 = addN(3)
add4 = addN(4)
print(add3(42), add4(42))
|
# 25. Reverse Nodes in k-Group
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 分开成小块,每一块执行反转,画图解释for循环里面的
# 两个指针pre,cur一直往后移动
# 1->2->3->4->5 k = 3举这个例子,先变成2->1->3->4->5,再变成3->2->1->4->5
def reverseKGroup(self, head, k):
h = ListNode(-1)
h.next = head
cur = pre = h
n = -1
# 统计链表长度n
while cur != None:
n += 1
cur = cur.next
while n >= k:
cur = pre.next
for _ in range(k - 1):
lat = cur.next
cur.next = lat.next
lat.next = pre.next
pre.next = lat
pre = cur
n -= k
return h.next
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
s = Solution()
print(s.reverseKGroup(node1, 3)) |
# 92. Reverse Linked List II
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# Input: 1->2->3->4->5->NULL, m = 2, n = 4
# Output: 1->4->3->2->5->NULL
# pre,cur一直往后移动
# t1 t2 pre cur lat
# 1 <- 2 <- 3 <- 4 5 -> null
# t1.next = pre, t2.next = cur
# 首先把pre和cur移动到指定位置,然后反转链表
# t1和t2记录pre和cur反转前的位置
def reverseBetween(self, head, m, n):
if head == None or head.next == None or m >= n or m < 0 or n < 0:
return head
pre = None
cur = head
i = 1
while i < m and cur != None:
pre = cur
cur = cur.next
i += 1
t1 = pre
t2 = cur
while i <= n and cur != None:
lat = cur.next
cur.next = pre
pre = cur
cur = lat
i += 1
if m == 1:
t2.next = cur
return pre
t1.next = pre
t2.next = cur
return head
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
s = Solution()
print(s.reverseBetween(node1, 2, 4)) |
# 82. Remove Duplicates from Sorted List II
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 两个指针来存储位置, 两个指针,一个一直找到next不重复的然后另一个直接next到这个下面。
def deleteDuplicates(self, head):
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur = dummy.next
while cur:
while cur.next and cur.next.val == pre.next.val:
cur = cur.next
if pre.next == cur:
pre = pre.next
else:
pre.next = cur.next
cur = cur.next
return dummy.next
node1 = ListNode(1)
node2 = ListNode(1)
node3 = ListNode(1)
node4 = ListNode(2)
node5 = ListNode(3)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
s = Solution()
print(s.deleteDuplicates(node1)) |
# 503. Next Greater Element II
# 输入: [1,2,1]
# 输出: [2,-1,2]
class Solution:
def nextGreaterElements(self, nums):
# 对于循环数组的问题一个常见的处理手段就是通过余数,
# 然后将数组的长度扩大两倍即可
stack, nums_len = list(), len(nums)
res = [-1] * nums_len
for i in range(nums_len * 2):
while stack and nums[stack[-1]] < nums[i % nums_len]:
res[stack.pop()] = nums[i % nums_len]
stack.append(i % nums_len)
return res
s = Solution()
print(s.nextGreaterElements([1,2,1])) |
# 9. Palindrome Number
class Solution:
# int 转 string解决
# def isPalindrome1(self, x):
# strx = str(x)
# return strx == strx[::-1]
# 将数字倒过来比较
def isPalindrome(self, x):
temp = x
ans = 0
while temp > 0:
ans = ans * 10 + temp % 10
temp //= 10
return ans == x
s = Solution()
print(s.isPalindrome(121)) |
# 344. Reverse String
class Solution:
def reverseString(self, s):
l = 0
r = len(s) - 1
s = list(s)
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return ''.join(s)
s = Solution()
print(s.reverseString(["h","e","l","l","o"])) |
# 300. Longest Increasing Subsequence
class Solution:
# [1, 1, 1, 1, 1]然后每次迭代增加
# [1, 2, 2, 1, 2]
# [1, 2, 3, 1, 3]
# [1, 2, 3, 1, 4]
# [1, 2, 3, 1, 4] max(2, 4)
def lengthOfLIS(self, nums):
if not nums:
return 0
result = [1]*len(nums)
for i in range(len(nums)):
for j in range(i, len(nums)):
if nums[j] > nums[i]:
result[j] = max(result[i]+1, result[j])
return max(result)
nums = [1, 2, 3, 0, 4]
s = Solution()
print(s.lengthOfLIS(nums)) |
# 234. Palindrome Linked List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 快慢指针找到中点,栈弹出判断
def isPalindrome(self, head):
if head == None or head.next == None:
return True
fast, slow = head, head
reverse_node = []
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
cur = slow.next
slow.next = None
while cur:
reverse_node.append(cur.val)
cur = cur.next
while head and len(reverse_node) > 0:
if head.val != reverse_node.pop():
return False
head = head.next
return True
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(1)
node1.next = node2
node2.next = node3
s = Solution()
print(s.isPalindrome(node1)) |
# 46. Permutations
class Solution:
# 递归遍历谁把谁拿出来然后剩下的继续递归
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
def permute(self, nums):
if len(nums) <= 1:
return [nums]
ans = []
for i, num in enumerate(nums):
extra = nums[:i] + nums[i+1:]
for j in self.permute(extra):
ans.append([num]+j)
return ans
nums = [1, 2, 3]
s = Solution()
print(s.permute(nums)) |
# 128. Longest Consecutive Sequence
class Solution:
# 先找到最小的数,然后递增到不存在
def longestConsecutive(self, nums):
nums = set(nums)
best = 0
for x in nums:
if x - 1 not in nums:
y = x + 1
while y in nums:
y += 1
best = max(best, y - x)
return best
nums = [100, 4, 200, 1, 3, 2]
s = Solution()
print(s.longestConsecutive(nums)) |
# 69. Sqrt(x)
class Solution:
def mySqrt(self, x):
if x < 0:
return -1
elif x == 0:
return 0
l, r = 1, x
while l+1 < r:
mid = (l+r)//2
if mid**2 == x:
return mid
elif mid**2 > x:
r = mid
else:
l = mid
return l
s = Solution()
print(s.mySqrt(8)) |
# las funciones en python con ciudadanas de primera clase
# first class citizens
# definimos la funcion
def sumar(a, b):
return a + b
# asignar funcion a variable
mi_funcion = sumar
# verificar el tipo de la variable
print(type(mi_funcion))
resultado = mi_funcion(3, 5)
print(resultado)
# funcion como argumento
def operacion(a, b, sumar_arg):
print(f'Resultado de sumar: {sumar(a, b)}')
operacion(4, 5, sumar)
# retornar funcion
def retornar_function():
return sumar
mi_funcion_retornada = retornar_function()
print(f'Resultado de funcionr etornada: {mi_funcion_retornada(5,7)}')
|
variable = ''
if bool(variable):
print('Verdadera')
else:
print('falsa')
'''
Ocho formas de generar un bool False en python
1. Comilla simple o doble ''/""
2. Lista vacia []
3. Tupla vacia ()
4. Diccionario vacio {}
5. Entero con 0
6. Flotante 0.0
7. bool False
8. Objeto None
''' |
class MiClase:
# variable estatica
variable_clase = 'Valor variable clase'
def __init__(self, variable_instancia):
self.variable_instancia = variable_instancia
# metodos estaticos
@staticmethod
def metodo_estatico():
print(MiClase.variable_clase)
# emtodos de clase cls es la clase
@classmethod
def metodo_clase(cls):
print(cls.variable_clase)
print(MiClase.variable_clase)
miClase = MiClase('valor variable instancia')
print(miClase.variable_instancia)
print(miClase.variable_clase)
miClase2 = MiClase('otro valor de variable de instancia')
print(miClase2.variable_instancia)
print(miClase2.variable_instancia)
#variables al vuelo
MiClase.variable_clase2 = 'Valor variable clase 2'
print(MiClase.variable_clase2)
print('***')
# llamar metodo estatico
MiClase.metodo_estatico()
#llamar metodo de clase
MiClase.metodo_clase()
miObjecto1 = MiClase('Variable instancia')
# un objeto si puede acceder al contexto estatico
miObjecto1.metodo_clase()
miObjecto1.metodo_estatico()` |
# operador de suma esta sobrecargado
a = 2
b = 3
print(a + b)
a = 'hola '
b = 'mundo '
print(a + b)
a = [1, 2, 3]
b = [6, 7, 8]
print(a + b)
# sobreescribir el metodo heredado de la clase object
|
# listas
nombres = ['Juan', 'Karla', 'Ricardo', 'Maria']
# imprimir la lista
print(nombres)
print(nombres[0])
print(nombres[1])
# acceder a elementos de manera inversa
print(nombres[-1])
print(nombres[-2])
# rangos de 0 a 2 sin incluir 2
print(nombres[0:2])
# ir del inicio de la lista al indice sin incluirlo
# desde el inicio hasta el 3
print(nombres[:3])
# desde el indice indicado hasta el final
print(nombres[1:])
# cambiar el valor de la lista
nombres[3] = 'Ivon'
print(nombres)
for nombre in nombres:
print(nombre)
else:
print('No hay mas nombres en la lista')
# preguntar tamanio de una lista
print(len(nombres))
nombres.append('Lorenzo')
print(nombres)
nombres.insert(1, 'Octavio')
print(nombres)
nombres.remove('Octavio')
print(nombres)
nombres.pop()
print(nombres)
# eliminar el elemento 0
del nombres[0]
print(nombres)
nombres.clear()
print(nombres)
# borrar lista por completo
del nombres
# print(nombres) # error ya no se puede acceder despues de borrarlo
rango = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in rango:
if num % 3 == 0:
print(num)
# tuplas no se pueden modificar si solo se tiene un valor hay que poner una coma al final
frutas = ('Naranja', 'Platano', 'Guayaba')
print(frutas)
print(len(frutas))
print(frutas[2])
print(frutas[-1])
print(frutas[0:1])
for fruta in frutas:
print(fruta, end=' ')
# error no se puede modificar
# frutas[0] = '';
frutasLista = list(frutas)
frutasLista[0] = 'Pera'
frutas = tuple(frutasLista)
print('')
print(frutas)
del frutas
#print(frutas)
print('*********************')
tupla = (13,1,8,3,2,5,8)
lista = []
for t in tupla:
if t < 5:
lista.append(t)
print(lista)
print('*********************')
# coleccion tipo set no guarda orden
planetas = {'Marte', 'Jupiter', 'Venus'}
print(planetas)
print(len(planetas))
# revisar si existe un elemento
print('Marte' in planetas)
print('Martes' in planetas)
# agregar
planetas.add('Tierra')
print(planetas)
# no soporte elementos duplicados
planetas.add('Tierra')
print(planetas)
# eliminar pero arroja error si no lo encuentra
planetas.remove('Tierra')
print(planetas)
# planetas.remove('Tierras')
print(planetas)
planetas.discard('Jupiter')
print(planetas)
# no arroja error al eliminar
planetas.discard('Jupiters')
print(planetas)
planetas.clear()
print(planetas)
del planetas
print('*****************************')
# diccionarios
diccionario = {
'IDE': 'Integrated development environment',
'OOP': 'Object oriented programming',
'DBMS': 'Database management system'
}
print(diccionario)
print(len(diccionario))
# acceder a elemento
print(diccionario['IDE'])
# recuperar elemento
print(diccionario.get('OOP'))
# modificar
diccionario['IDE'] = 'INTEGRATED DEVELOPMENT ENVIRONMENT'
print(diccionario)
# recorrer diccionario
for termino, valor in diccionario.items():
print(termino, valor)
for termino in diccionario.keys():
print(termino)
for valor in diccionario.values():
print(valor)
# existencia de elemento
print('IDE' in diccionario)
print('IDe' in diccionario)
#agregar
diccionario['PK'] = 'Primary key'
print(diccionario)
# remover
diccionario.pop('DBMS')
print(diccionario)
diccionario.clear()
print(diccionario)
del diccionario
#print(diccionario)
|
import itertools, time
def imright(h1, h2):
# House h1 is immediately right of h2 if h1-h2 == 1."
return h1-h2 == 1
def nextto(h1, h2):
# Two houses are next to each other if they differ by 1."
return abs(h1-h2) == 1
def zebra_puzzle_fast():
# Return a tuple (WATER, ZEBRA) indicating their house numbers
houses = first, _, middle, _, _ = [1, 2, 3, 4, 5]
orderings = list(itertools.permutations(houses)) #1
return next((WATER, ZEBRA)
for (red, green, ivory, yellow, blue) in cnt(orderings)
if imright(green, ivory) #6
for (Englishman, Spaniard, Ukranian, Japanese, Norwegian) in cnt(orderings)
if Englishman == red #2
if Norwegian == first #10
if nextto(Norwegian, blue) #15
for (coffee, tea, milk, oj, WATER) in cnt(orderings)
if coffee == green #4
if Ukranian == tea #5
if milk == middle #9
for (OldGold, Kools, Chesterfields, LuckyStrike, Parliaments) in cnt(orderings)
if Kools == yellow #8
if LuckyStrike == oj #13
if Japanese == Parliaments #14
for (dog, snails, fox, horse, ZEBRA) in cnt(orderings)
if Spaniard == dog #3
if OldGold == snails #7
if nextto(Chesterfields, fox) #11
if nextto(Kools, horse) #12
)
def t():
t0 = time.clock()
zebra_puzzle_fast()
t1 = time.clock()
return t1-t0
def timedcall(fn, *args):
# Call function with args; return the time in seconds and result
t0 = time.clock()
result = fn(*args)
t1 = time.clock()
return t1-t0, result
def timedcalls(n, fn, *args):
# Call fn(*args) repeatedly: n times if n is an int, or up to
# n seconds if n is a float; return the min, avg, and max time
if isinstance(n, int):
times = [timedcall(fn, *args)[0] for _ in range(n)]
else:
times = []
while sum(times) < n:
times.append(timedcall(fn, *args)[0])
return min(times), average(times), max(times)
def average(numbers):
# Retuen the average (arithmetic mean) of a sequence of numbers
return sum(numbers) / float(len(numbers))
def instrument_fn(fn, *args):
cnt.starts, cnt.items = 0, 0
result = fn(*args)
print "%s got %s with %5d iters over %7d items" % (
fn.__name__, result, cnt.starts, cnt.items)
def cnt(sequence):
""" Generate items in sequence; keeping counts as we go. c.starts is the
number of sequences; c.items is number of items generated"""
cnt.starts += 1
for item in sequence:
cnt.items += 1
yield item
def timedcalls_Beta(n, fn, *args):
# Call function n times with args; return the min, avg, and max time
times = [timedcall(fn, *args)[0] for _ in range(n)]
return min(times), average(times), max(times)
if __name__ == "__main__":
instrument_fn(zebra_puzzle_fast) |
print("Hallo! Mit diesem Konverter kannst du Kilometer in Meilen umwandeln.")
while True:
print("Bitte gib eine Zahl in Kilometer an, welche du umgewandelt haben willst. Bitte nur Zahlen eingeben!")
km = input("Kilometer: ")
km = float(km.replace(",", "."))
miles = km * 0.621371
print(f"{km} Kilometer entsprechen {miles} Meilen")
choice = input("Willst du noch etwas umgerechnet haben? (y/n): ")
if choice.lower() != "y":
break
print("Vielen Dank für die Verwendung dieses Konverters!")
|
dic01 = {'name':'John', 'phone':'0933980284', 'height':'170cm', 'age':'15', 'course': ['Math', 'History']}
dic01['gender'] = 'Female'
print(dic01.get('ddd', 'Not Found'))
age = dic01.pop('age')
print(age)
print (dic01.items())
for key, value in dic01.items():
print (key, value) |
'''
# self 像是 this一樣傳入物件本身,
# 類似於 Person.getAge(person) 這樣
class Person:
def getName(self):
print ("Avi")
def getAge(self):
print ("16")
person = Person()
person.getName()
person.getAge()
'''
'''
# Initialization function : Takes parameters you want to pass in when creating the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print ("You just created a guy named " + self.name)
def getName(self):
print ("Your name is " + self.name)
def getAge(self):
print ("Your age is " + self.age)
p1 = Person("Bob", "22")
p1.getName()
p1.getAge()
print (p1.name)
print (p1.age)
'''
# Inheritance
class Parent():
def __init__(self):
print ("This is parent class!")
def parentFunc(self):
print ("This is parent function!")
class Child(Parent):
def __init__(self):
print ("This is child class!")
def childFunc(self):
print ("This is child function!")
p = Parent()
p.parentFunc()
c = Child()
c.childFunc()
c.parentFunc() |
'''
The net class defines the overall topology of a neural networks, be it
directed or undirected. This is a very flexible setup which should give
the user a high degree of manipulative ability over the various aspects
of neural net training.
'''
import numpy as np
import cPickle
import gzip
import theano
import theano.tensor as T
from layer import Layer
from initialisation import Initialisation
from train import Train
class NN(object):
''' NN class
We can define a general network topology. At the moment masks are not
supported and all hidden nodes MUST bind ONE input to ONE output
'''
def __init__(
self,
topology=(784, 500, 784),
nonlinearities=('sigmoid','sigmoid'),
initialisation='glorot',
pparams=None,
input_bias=False,
input=None
):
'''
:type topology: tuple of ints
:param topology: tuple defining NN topology
:type nonlinearities: tuple of strings
:param nonlinearities: tuple defining the nonlinearities of the network
:type initialisation: string
:param initialisation: the type of initalisation precedure for the NN parameters
:type pparams: list of named tuples
:param pparams: contains pretrained parameters from a previous network
:type input_bias: boolean
:param input_bias: flag to denote whether there is an input bias in the first layer
'''
# We are going to store the layers of the NN in a net object, where
# net[0] is the input layer etc. This has callable symbolic parameters
# e.g. net[x].W, net[x].b
self.net = []
# Make sure that the specfied nonlinearities correspond to layers,
# otherwise throw an error and exit
assert len(nonlinearities) == len(topology) - 1
# It may be the case that we wish to load a premade model, in which
# case it is important to check that the parameters match up with
# the stated topology and we also need to bypass parameter initialisation.
# Note that a pretrained model may only be fully pretrained. Partial
# pretraining is yet to be supported
if pparams is None:
W=None,
b=None,
b_in=None,
mask=None
else:
if hasattr(pparams[0], 'b_in'):
assert input_bias == True, "Need to set 'input_bias=True'"
assert pparams[0].b_in.shape[0] == pparams[0].W.shape[1], \
"b_in or W wrong shape"
print('Input biases consistent')
for i in np.arange(0,len(pparams)-1):
assert pparams[i].W.shape[1] == pparams[i+1].W.shape[0], \
"W connectivity mismatch between layer %i and layer %i" % (i, i+1)
assert pparams[i].b.shape[0] == pparams[i].W.shape[0], \
"b/W connectivity mismatch in layer %i" % i
assert self.supported_nonlinearity(pparams[i].nonlinearity), \
"Unsupported nonlinearity"
print('Layer %i parameters are consistent' % (i))
'''
Now we simply loop through the elements of 'topology' and create a
network layer with appropriate bound nonlinearities and initialised
weights/biases.
'''
if pparams is None:
# Build layers
for i in np.arange(1,len(topology)):
if (input_bias == True) and (i == 1):
# Instantiate layer with inputs biases
lyr = Layer(topology[i-1],topology[i], b_in = topology[i-1])
else:
#Instantiate hidden/output layers
lyr = Layer(topology[i-1],topology[i])
self.net.append(lyr)
# Initialise weights of each constructed layer
init_lyr = Initialisation()
for lyr in self.net:
init_lyr.init_weights(lyr, command='Glorot', nonlinearity='sigmoid')
print(lyr, 'built')
del init_lyr
else:
# Build layers
for i in np.arange(1,len(topology)):
if (input_bias == True) and (i == 1):
# Instantiate layer with inputs biases
lyr = Layer(W=pparams[0].W, b=pparams[0].b, b_in=pparams[0].b_in)
else:
#Instantiate hidden/output layers
lyr = Layer(W=pparams[i-1].W, b=pparams[i-1].b)
self.net.append(lyr)
print(lyr, "built")
# It will turn out advantageous later to easily access these variables
self.num_layers = len(topology) - 1
self.topology = topology
self.nonlinearities = nonlinearities
self.intialisation = initialisation
self.pparams = pparams
self.input_bias = input_bias
# Run this command to load defaults.
self.pretrain_params()
# if no input is given, generate a variable representing the input
if input is None:
# we use a matrix because we expect a minibatch of several
# examples, each example being a row
self.x = T.dmatrix(name='input')
else:
self.x = input
def load_data(self, dataset):
'''Load the dataset, which must be in pickled form. Will want to add a
database retrieval function later
Disclaimer: Copied straight from Montreal deep learning tutorials
:type dataset: string
:param dataset: path to dataset directory
'''
print('Loading data')
f = gzip.open(dataset, 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
def shared_dataset(data_xy, borrow=True):
data_x, data_y = data_xy
shared_x = theano.shared(np.asarray(data_x,
dtype=theano.config.floatX),
borrow=borrow)
shared_y = theano.shared(np.asarray(data_y,
dtype=theano.config.floatX),
borrow=borrow)
return shared_x, T.cast(shared_y, 'int32')
self.test_set_x, self.test_set_y = shared_dataset(test_set)
self.valid_set_x, self.valid_set_y = shared_dataset(valid_set)
self.train_set_x, self.train_set_y = shared_dataset(train_set)
def pretrain_params(
self,
method='AE',
loss='SE',
regulariser=('L2'),
optimiser='SDG',
momentum='0.1',
scheduler='ED'
):
'''
Load pretraining parameters into every layer in the network.
For now we force the pretrainer to apply the same scheme to every layer
but in future we expect the training scheme to be per layer, hence the
training commands are stored layer-wise.
'''
for lyr in self.net:
lyr.method = method
lyr.loss = loss
lyr.regulariser = regulariser
lyr.optimiser = optimiser
lyr.momentum = momentum
lyr.scheduler = scheduler
# Note that for the autoencoder setup we need to specify a few extra parameters
# These are whether the AE in symmetric in the representation layer and thus,
# the kinds of weight-tying we would like to use. Furthermore, which half of the
# parameters we may wish to discard.
#
# AE = symmetric + weight tying
# AE_ns = non_symmetric (no weight tying)
if method == 'AE':
# Check for topology symmetry and various constraints which are:
# 1 - even number of layers
assert self.num_layers%2 == 0, \
"Autoencoders require an even number of layers"
for i in xrange(self.num_layers):
# print i
assert self.topology[i] == self.topology[self.num_layers - i], \
'AE-autoencoders need to symmetric in the representations layer'
def pretrain(self):
'''
Greedy layer-wise pretrain the network
'''
train = Train()
for layer_number in xrange(len(self.net)):
train.train_layer_build(self, layer_number)
train.train_layer(self, layer_number)
def supported_nonlinearity(self,nonlinearity):
return nonlinearity == 'sigmoid'
|
import wikipedia
import wikipediaapi
import requests
# Setting up requests, sessions, and urls for Media Wiki API
S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"
# Setting up wikipedia API library
wiki_wiki = wikipediaapi.Wikipedia('en')
# Getting the list of queries to search wikipedia
queries = ["Deep learning", "Machine Learning", "NLP", "Computer Vision", "Mathematics", "Optimization",
"Statistics", "Linear Algebra", "Calculus", "Linguistics", "Computation", "Probability", "Database", "Biology",
"Physics", "Chemistry", "Economics", "Political Sciences", "Drama", "Poetry", "Arts"]
# Creating an empty string named data to store all the extracted data in the future.
data = []
# Using a for loop to search through the queries one by one
for query in queries:
# Using wikipedia API to get first 20 search results and storing them in a list called titles
titles = wikipedia.search(query, results = 20)
for title in titles:
# Extracting TITLE
page = wiki_wiki.page(title)
# Extracting URL
url = page.fullurl
# Extracting CATEGORIES
categories = [category for category in page.categories]
# Extracting TEXT CONTENT
text = page.text
# Calculating WORD COUNT
word_count = len(text.split())
# Creating a URL to get data from media wiki api
PARAMS = {"action": "query", "titles": title, "prop": "contributors|extlinks|links|images", "format": "json", "ellimit": 500, "pllimit": 500, "pclimit": 500, "imlimit": 500}
R = S.get(url=URL, params=PARAMS)
DATA = R.json()
pageid = list(DATA["query"]["pages"].keys())[0]
# CONTRIBUTORS
contributors = DATA["query"]["pages"][pageid]["contributors"]
# EXTERNAL LINKS
try:
link_data = DATA["query"]["pages"][pageid]["extlinks"]
extlinks = []
for link in link_data:
extlinks.append(link["*"])
except:
extlinks = []
# INTERNAL LINKS
internal_link_data = DATA["query"]["pages"][pageid]["links"]
intlinks = []
for link in internal_link_data:
intlinks.append(link["title"])
# IMAGES
try:
image_data = DATA["query"]["pages"][pageid]["images"]
images = []
for image in image_data:
new_title = image['title'].replace(" ", "_")
image_url = "https://en.wikipedia.org/wiki/" + new_title
images.append(image_url)
except:
images = []
print(title)
# Adding data to the the "data" list
data.append({"Title": title, "Categories": categories, "Contributors": contributors, "External Links": extlinks, "Internal Links": intlinks, "Images": images, "Word Count": word_count, "URL": url, "Text Content": text})
# Printing out final data
print(data) |
import json
WIDTH = 9
FULLSUDOKU = {1, 2, 3, 4, 5, 6, 7, 8, 9}
FILE = 'sudoku1.json'
FILL = "x"
matrix = [[FILL]*WIDTH for i in range(9)]
borders = [2,5,8]
counter = 0
class Sudoku:
def __init__(self):
self.matrix = [[FILL]*WIDTH for i in range(WIDTH)]
with open(FILE) as data_file:
json_object = json.load(data_file)
for key in json_object:
value = json_object[key]
for v in value:
self.setNumber(int(key), int(v), int(value[v]))
def printCanvas(self):
for i in range(WIDTH):
print ""
for j in range(WIDTH):
print self.matrix[i][j],
def setNumber(self, x, y, number):
self.matrix[x][y] = number
def isNumber(self , x , y):
try:
value = self.matrix[x][y]
if value == FILL:
return False
else:
return True
except Exception as e:
return False
def listHorizontalLine(self, x):
nums = []
for i in range(WIDTH):
value = self.matrix[x][i]
if (value != FILL):
nums.append(value)
return nums
def listVerticalLine(self, y):
nums = []
for i in range(WIDTH):
value = self.matrix[i][y]
if (value != FILL):
nums.append(value)
return nums
def findSquare(self, x, y):
nums =[]
for b in borders:
for bo in borders:
if x <= b and y <= bo:
nums = [b, bo]
return nums
return False
def listSquare(self, coordinate):
z = coordinate[0]+1
a = coordinate[1]+1
x = coordinate[0]-2
y = coordinate[1]-2
nums = []
for i in range( x, z):
for j in range(y, a):
value = self.matrix[i][j]
if (value != FILL):
nums.append(value)
return nums
def search(self, x, y):
horizontal = set(self.listHorizontalLine(x))
vertical = set(self.listVerticalLine(y))
square = set(self.listSquare(self.findSquare(x,y)))
result = (horizontal | vertical | square)
numbers = FULLSUDOKU - result
if len(numbers) == 1:
number = numbers.pop()
return number
return False
def startSolve(self):
for i in range(WIDTH):
for j in range(WIDTH):
if not self.isNumber(i, j):
k = self.search(i , j)
if not k:
print ""
else:
self.setNumber(i , j , k)
|
import random
class GenericTyle:
def __init__(self, type, value):
self.type = type
self.value = value
self.clicked = False
def getType(self):
return self.type
def setType(self, type):
self.type = type
return True
def getValue(self):
return self.value
def setValue(self, value):
self.value = value
return True
def getClicked(self):
return self.clicked
def setClicked(self, clicked):
self.clicked = clicked
return True
def toggleClicked(self):
self.clicked = not self.clicked
return True
class Bomb(GenericTyle):
def __init__(self):
self.Clicked = False
self.type = "bomb"
self.value = "b"
class Number(GenericTyle):
def __init__(self, value):
self.value = value
self.type = "number"
self.clicked = False
def incrementValue(self):
self.value+=1
return self.value
# main code starts here
def getBoard():
board = []
length = 24 # user values here
height = 30 # user values here
bombNumber = 200 # user values here
for i in range(height):
board.append([])
for j in range(length):
board[i].append(Number(0))
usedVals = []
stuff = []
for i in range(bombNumber):
x = random.randint(0, length) - 1
y = random.randint(0, height) - 1
temp = [y, x]
while usedVals.__contains__(temp) or temp[0] < 0 or temp[1] < 0:
x = random.randint(0, length) - 1
y = random.randint(0, height) - 1
temp = [y, x]
usedVals.append(temp)
#print(temp[1])
board[y][x] = Bomb()
yp1 = y+1 >= 0 and y+1 < height
ym1 = y-1 >= 0 and y-1 < height
xp1 = x+1 >= 0 and x+1 < length
xm1 = x-1 >= 0 and x-1 < length
#print([y,x])
#print(xp1)
if xp1 and board[y][x+1].type != "bomb":
board[y][x+1].incrementValue()
if xm1 and board[y][x-1].type != "bomb":
board[y][x-1].incrementValue()
if yp1:
if board[y+1][x].type != "bomb":
board[y+1][x].incrementValue()
if xp1 and board[y+1][x+1].type != "bomb":
board[y+1][x+1].incrementValue()
if xm1 and board[y+1][x-1].type != "bomb":
board[y+1][x-1].incrementValue()
if ym1:
if board[y-1][x].type != "bomb":
board[y-1][x].incrementValue()
if xp1 and board[y-1][x+1].type != "bomb":
board[y-1][x+1].incrementValue()
if xm1 and board[y-1][x-1].type != "bomb":
board[y-1][x-1].incrementValue()
return board
def printBoard(board):
bString = ""
for y in range(len(board)):
for x in range(len(board[y])):
bString += str(board[y][x].getValue())
bString += " "
bString += "\n"
print(bString)
|
import math
from display import *
def magnitude(vector):
magnitude = math.sqrt(math.pow(vector[0], 2) + math.pow(vector[1], 2) + math.pow(vector[2], 2))
#vector functions
#normalize vetor, should modify the parameter
def normalize(vector):
for i in vector:
vector[i] = vector[i] / magnitude
#Return the dot product of a . b
def dot_product(a, b):
return sum([a[0] * b[0], a[1] * b[1], a[2] * b[2]])
#Calculate the surface normal for the triangle whose first
#point is located at index i in polygons
def calculate_normal(polygons, i):
first = polygons[i]
second = polygons[i + 1]
third = polygons[i + 2]
vector1 = []
vector2 = []
for i in range(3):
vector1.append(second[i] - first[i])
vector2.append(third[i] - first[i])
def cross_product(a, b):
""" Given: a and b are vectors\n
Returns: vector made from cross product of a and b
"""
return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
return cross_product(vector1, vector2)
|
from typing import List
from src.morse_alphabet import morse_code, PAUSE
def translate_marks(input_text: str):
"""method translates the input string into the morse alphabet
Args:
input (str): string, that will be translated to morse alphabet
Returns:
[list]: list of morse code sequence
"""
input_text = input_text.lower()
translated_marks: List[str] = []
for letter in input_text:
if letter in morse_code:
translated_marks += morse_code[letter]
translated_marks.append(PAUSE)
return translated_marks
|
# Step 1 - Scraping
# Complete your initial scraping using Jupyter Notebook, BeautifulSoup, Pandas, and Requests/Splinter.
# Create a Jupyter Notebook file called mission_to_mars.ipynb and use this to complete all of your scraping and analysis tasks. The following outlines what you need to scrape.
# NASA Mars News
# Scrape the NASA Mars News Site and collect the latest News Title and Paragragh Text. Assign the text to variables that you can reference later.
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
import requests
import tweepy
import time
# load tweeter api keys
from config import consumer_key, consumer_secret, access_token, access_token_secret
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
executable_path = {'executable_path': 'chromedriver.exe'}
return Browser('chrome', **executable_path, headless=False)
def scrape():
browser = init_browser()
# ----create a dictionary to hold all the data (steps covered from mission_to_mars.py)
mars_data = {}
#mars nasa web news page
url = "https://mars.nasa.gov/news/"
browser.visit(url)
# scrape page into soup
html = browser.html
soup = BeautifulSoup(html, "html.parser")
# find the title and paragraph
news_title = soup.find("div", class_="content_title").text
news_p = soup.find("div",class_="article_teaser_body").text
news_date = soup.find("div", class_="list_date").text
#----add to dict ----
mars_data["news_date"] = news_date
mars_data["news_title"] = news_title
mars_data["news_p"] = news_p
# JPL Mars Space Images - Featured Image
# Visit the url for JPL's Featured Space Image here.
# Use splinter to navigate the site and find the image url for the current Featured Mars Image and assign the url string to a variable called featured_image_url.
# Make sure to find the image url to the full size .jpg image.
# Make sure to save a complete url string for this image.
#JPL Mars Space Images - featured image
url_img = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"
browser.visit(url_img)
#scrape browser to find the image
html = browser.html
soup = BeautifulSoup(html, 'html.parser')
image = soup.find('article', class_="carousel_item").get('style')
#thanks kat
image = image.split("('", 1)[1].split("')")[0]
featured_image_url = "https://jpl.nasa.gov" + image
full_image_url = featured_image_url
#----add to dict----
mars_data["full_image_url"] = full_image_url
# Mars Weather
# Visit the Mars Weather twitter account here and scrape the latest Mars weather tweet from the page.
# Save the tweet text for the weather report as a variable called mars_weather.
# Twitter credentials and APi authentification
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())
# find the target user
target_user = "MarsWxReport"
mars_tweet = api.user_timeline(target_user , count = 1)
latest_mars_weather=mars_tweet[0]['text']
#----add to dict----
mars_data["latest_mars_weather"] = latest_mars_weather
# Mars Facts
# Visit the Mars Facts webpage here and use Pandas to scrape the table containing facts about the planet including Diameter, Mass, etc.
# Use Pandas to convert the data to a HTML table string.
url_facts= "https://space-facts.com/mars/"
browser.visit(url_facts)
table = pd.read_html(url_facts)
table[0]
# add headers to the columns to replace 0 and 1
df_mars_table = table [0]
df_mars_table.columns = ["Mars Variables", "Data"]
# reset index to Variables
df_mars_table.set_index(["Mars Variables"])
mars_table_html = df_mars_table.to_html()
mars_table_html = mars_table_html.replace("\n", "")
#----add to dict----
mars_data["df_mars_table"] = mars_table_html
# Mars Hemispheres
# Visit the USGS Astrogeology site here to obtain high resolution images for each of Mar's hemispheres.
# You will need to click each of the links to the hemispheres in order to find the image url to the full resolution image.
# Save both the image url string for the full resolution hemipshere image, and the Hemisphere title containing the hemisphere name. Use a Python dictionary to store the data using the keys img_url and title.
# Append the dictionary with the image url string and the hemisphere title to a list. This list will contain one dictionary for each hemisphere.
# Mars hemispheres
url_hemisphere = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
browser.visit(url_hemisphere)
html = browser.html
soup = BeautifulSoup(html, 'html.parser')
# create hemisphere list
mars_hemispheres = []
# grab the different hemispheres
# looping through the pages
# use find by tag http://splinter.readthedocs.io/en/latest/finding.html
for i in range (4):
time.sleep(2)
hemisphere_images = browser.find_by_tag ("h3")
hemisphere_images [i].click()
html = browser.html
soup = BeautifulSoup(html, 'html.parser')
img_product = soup.find("img", class_="wide-image")["src"]
img_title = soup.find("h2",class_="title").text
img_url = 'https://astrogeology.usgs.gov'+ img_product
# Append the dictionary with the image url string and the hemisphere title to a list.
hemisphere_image_dict={"title":img_title,"img_url":img_url}
mars_hemispheres.append(hemisphere_image_dict)
browser.back()
#----add to dict----
mars_data["mars_hemispheres"] = mars_hemispheres
# return the dictionnary of each steps
return mars_data
# from pprint import pprint
# pprint (mars_data) |
class Animal:
animal_type = 'mamma'
counter = 0
def __init__(self, name):
self.name = name
Animal.counter += 1
animal_one = Animal('rat')
animal_two = Animal('cat')
print(animal_one.animal_type)
print(animal_two.animal_type)
print(animal_one.counter)
# to check how many times an object is being instantiated/called in a program
# print(Animal.counter)
# DIFFERENT METHODS IN PYTHON
# Instance Method
# Class Method
# Static Method
|
# register
# - first name, last name, password and email
# - generate userAccount
# login
# - account number and password
# bank operations
# Initializing the system
import random
import database
import validation
from getpass import getpass
# dictionary
def init():
print('Welcome to Zuri Bank')
have_account = int(input('Do you have an account with us? 1 (Yes) 2(No) \n'))
if have_account == 1:
login()
elif have_account == 2:
register()
else:
print('You Have selected an invalid option')
init()
def login():
print("******* Login *******")
account_number_from_user = (input("What is Your Account Number? \n"))
is_valid_account_number = validation.account_number_validation(account_number_from_user)
if is_valid_account_number:
# modifyiing password to appear encrypted
# password = input('Input Your Password \n')
password = getpass('What is Your Password \n')
user = database.authenticated_user(account_number_from_user, password)
if user:
bank_operation(user)
# for account_number, user_details in database.items():
# if account_number == int(account_number_from_user):
# if user_details[3] == password:
print('Invalid Account or Password')
login()
else:
print("Account Number Invalid; ensure you have only integers!")
init()
def register():
print("******Register*****")
email = input('What is Your email Address? \n')
first_name = input('What is Your First Name \n')
last_name = input('What is Your Last Name \n')
# password = input("Create A Password For Yourself \n")
password = getpass('Create A Password For Yourself \n')
account_number = generating_account_number()
is_user_created = database.create(account_number, first_name, last_name, email, password)
if is_user_created:
print('Your Account Has Been Created')
print("== ==== ===== ==== ==")
print('Your Account Number is: %d' % account_number)
print("Make sure you keep it safe")
print("== ==== ===== ==== ==")
login()
else:
print("Something went wrong, please try again")
register()
def bank_operation(user):
print("Welcome %s %s" % (user[0], user[1]))
selected_option = int(input("What would you like to do? (1) Deposit (2) Withdrawal (3) Logout (4) Exit \n"))
if selected_option == 1:
deposit_operation()
elif selected_option == 2:
withdrawal_operation()
elif selected_option == 3:
login()
elif selected_option == 4:
exit()
else:
print("Invalid Option Selected")
bank_operation(user)
def withdrawal_operation():
print('Withdrawal')
def deposit_operation():
print('Deposit Operation')
def generating_account_number():
return random.randrange(1111111111, 9999999999) # to give a random number within 10 digits
def logout():
login()
# ACTUAL BANKING SYSTEM ####
init()
|
"""
Problem Statement
James found a love letter his friend Harry has written for his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes.
To do this, he follows two rules:
He can reduce the value of a letter, e.g. he can change d to c, but he cannot change c to d.
In order to form a palindrome, if he has to repeatedly reduce the value of a letter, he can do it until the letter becomes a. Once a letter has been changed to a, it can no longer be changed.
Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome.
Input Format
The first line contains an integer T, i.e., the number of test cases.
The next T lines will contain a string each. The strings do not contain any spaces.
Constraints
1≤T≤10
1≤ length of string ≤104
All characters are lower case English letters.
Output Format
A single line containing the number of minimum operations corresponding to each test case.
Sample Input
4
abc
abcba
abcd
cba
Sample Output
2
0
4
2
Explanation
For the first test case, abc -> abb -> aba.
For the second test case, abcba is already a palindromic string.
For the third test case, abcd -> abcc -> abcb -> abca = abca -> abba.
For the fourth test case, cba -> bba -> aba
"""
count = 0
def checkpalindrome(string, index, ascii_char):
#abcd
print "index: ", index, " asciichar: ", chr(ascii_char)
global count
original_string = string
reversed_string = string[::-1]
if reversed_string == string:
return
else:
if(original_string[index] == chr(ascii_char) and index > len(original_string)/2):
checkpalindrome(original_string, index-1, ascii_char+1)
else:
print "else part"
original_string[index] = chr(ord(original_string[index]) - 1)
print original_string[index]
count = count + 1
checkpalindrome(original_string, index, ascii_char)
if __name__ == '__main__':
n = input()
string_array = []
for i in range(n):
input_string = raw_input()
string_array.append(input_string)
for string in string_array:
print string
checkpalindrome(list(string), len(string)-1, 97)
print count
count = 0
|
"""
Problem Statement
You are given two strings, A and B. Find if there is a substring that appears in both A and B.
Input Format
Several test cases will be given to you in a single file. The first line of the input will contain a single integer T, the number of test cases
Then there will be T descriptions of the test cases. Each description contains two lines. The first line contains the string A and the second line contains the string B.
Output Format
For each test case, display YES (in a newline), if there is a common substring. Otherwise, display NO.
Constraints
All the strings contain only lowercase Latin letters.
1<=T<=10
1<=|A|,|B|<=105
Sample Input
2
hello
world
hi
world
Sample Output
YES
NO
Explanation
For the 1st test case, the letter o is common between both strings, hence the answer YES. (Furthermore, the letter l is also common, but you only need to find one common substring.)
For the 2nd test case, hi and world do not have a common substring, hence the answer NO.
"""
def common_start(sa, sb):
""" returns the longest common substring from the beginning of sa and sb """
def _iter():
for a, b in zip(sa, sb):
if a == b:
yield a
else:
return
return ''.join(_iter())
def find_sub_string(string):
temp_array = []
for i in range(0, len(string)):
for j in range(i, len(string)):
temp_array.append(string[i:j+1])
return set(temp_array)
def check_for_substrings(string1, string2):
for character in string1:
if character in string2:
return True
return False
if __name__ == '__main__':
n = input()
n = int(n)*2
string_array = []
for i in range(n):
input_string = input()
string_array.append(input_string)
for i in range(0, n, 2):
val = check_for_substrings(string_array[i], string_array[i+1])
if val == True:
print "YES"
else:
print "NO"
"""
t = input()
assert t<=10 and t>=1
for _ in range(t):
s = list(raw_input())
assert len(s) >=1 and len(s)<= 10000
su = 0
for i in range(0,len(s)/2):
su+= abs(ord(s[i]) - ord(s[-1-i]))
print su
"""
|
'''
=====================
`logger` module
=====================
A simplified interface to the standard library's logging module.
Summary
-------
Two handlers are attached to the root logger, one logs to a file and the other
logs to the console. Log levels of the two handlers can be set independently
by calling `setloglevel()` and '`setecholevel()`. Logging can be enabled with
`enable()` and disabled with `disable()`.
The file logger is in fact optional, and is only enabled if `start()`
is called with either a `logdir` parameter or a `logfile` parameter.
In the case where you only want logging to the console (stdout), then it
It is not necessary to call *start()* explicitly, it will be called behind the
scenes once any of the logging statements are invoked.
All logging statements:
-----------------------
* debug
* info
* warning
* error
* critical
* exception
* divider
Usage
-----
Basic usage:
.. sourcecode:: python
>>> debug("A debug statement.")
DEBUG A debug statement.
>>> info("Some info.")
INFO Some info.
>>> warning("A warning")
WARNING A warning
>>> error("A bad thing.")
ERROR A bad thing.
Raise the logging level for the console logger:
.. sourcecode:: python
>>> setecholevel(logging.ERROR)
>>> info("Some info.")
>>> warning("A warning")
>>> error("A bad thing.")
ERROR A bad thing.
And lower it again:
.. sourcecode:: python
>>> setecholevel(logging.INFO)
>>> info("Some info.")
INFO Some info.
>>> warning("A warning")
WARNING A warning
>>> end()
INFO End logging.
Logging messages may also be sent to a file
.. sourcecode:: python
>>> import tempfile
>>> fp, tmp = tempfile.mkstemp()
>>> log = start(logfile=tmp) #doctest:+ELLIPSIS
>>> tmp == log
True
>>> info("Some info.")
INFO Some info.
>>> warning("A warning")
WARNING A warning
Temporarily disable all logging.
.. sourcecode:: python
>>> disable()
>>> debug('Debugging')
>>> info("Some info.")
>>> warning("A warning")
>>> error("A bad thing.")
>>> critical("Even worser.")
And re-enable.
.. sourcecode:: python
>>> enable()
>>> info("Some info.")
INFO Some info.
>>> debug('Debugging')
>>> setecholevel(logging.DEBUG)
>>> debug('Debugging')
DEBUG Debugging
>>> end()
INFO End logging.
Here we verify that the log file exists and is non-empty:
(`end` should close all open file-handles, but it doesn't
here, so have to do it with `os.close()` - related to tempfile.mkstemp perhaps).
.. sourcecode:: python
>>> os.close(fp)
>>> os.path.exists(log)
True
>>> os.stat(log).st_size > 0
True
and tidy up:
.. sourcecode:: python
>>> os.remove(log)
'''
__docformat__ = "restructuredtext en"
__author__ = "Gerard Flanagan <[email protected]>"
import os
import logging
from datetime import datetime
import functools
__all__ = [
'step','disable_step',
'start', 'end','debug', 'info', 'warning', 'critical',
'error', 'exception', 'event', 'divider', 'mklogname',
'setloglevel', 'setecholevel', 'enable', 'disable'
]
__doc_all__ = __all__
LOGNAME_FORMAT = "%Y%m%d-%H%M%S.log"
#LOG_FORMAT = '%(asctime)s %(levelname)-8s %(message)s'
LOG_FORMAT = '%(asctime)s [%(user)s@%(clientip)s] %(levelname)-8s %(message)s'
DATE_FORMAT = '%Y-%m-%d %H:%M'
LOG_LEVEL = logging.DEBUG
ECHO_FORMAT = '%(levelname)-8s %(message)s'
ECHO_LEVEL = logging.DEBUG
def getuser():
try:
import win32api
usr = win32api.GetUserName()
except ImportError:
import getpass
usr = getpass.getuser()
return usr or 'unknown'
def getclientip():
import socket
try:
return socket.gethostbyaddr(socket.gethostname())[2][0]
except:
return 'unknown'
KWARGS = {}
def mklogname(prefix=''):
'''
Generate a timestamped log file name. Eg. 20071210_140934.log
'''
return prefix + datetime.now().strftime(LOGNAME_FORMAT)
def start(logfile=None, logdir=None, logfileprefix='', level=ECHO_LEVEL):
'''
Start logging
:param logfile: The name of a file to log to.
:param logdir: If `logfile` is not specified create one here.
:param logfileprefix: Prefix to add to log file names.
:param level: The logging level, by default DEBUG
:return: The absolute path of the logfile
'''
import sys
global KWARGS
KWARGS['user'] = getuser()
KWARGS['clientip'] = getclientip()
root = logging.getLogger()
root.setLevel(level)
if len(root.handlers) == 0:
console = logging.StreamHandler(sys.stdout)
console.setLevel(ECHO_LEVEL)
formatter = logging.Formatter(ECHO_FORMAT, DATE_FORMAT)
console.setFormatter(formatter)
root.addHandler(console)
if logdir or logfile:
logfile = os.path.abspath(logfile or \
os.path.join(logdir, mklogname(logfileprefix)))
logdir = os.path.dirname(logfile)
if not os.path.exists(logdir):
try:
os.makedirs(logdir)
except:
raise Exception("Error creating log directory: %s" % logdir)
hdlr = logging.FileHandler(logfile, 'a')
hdlr.setLevel(LOG_LEVEL)
formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
hdlr.setFormatter(formatter)
root.addHandler(hdlr)
return logfile
def end():
'''
End logging, closing all file handles.
:return: None
'''
info('End logging.')
logging.shutdown()
def setloglevel(level):
'''
Set the logging level for the file logger.
'''
if len(logging.root.handlers) > 1:
global LOG_LEVEL
LOG_LEVEL = level
logging.root.handlers[1].setLevel(level)
def setecholevel(level):
'''
Set the logging level for the console logger.
'''
if len(logging.root.handlers) > 0:
global ECHO_LEVEL
ECHO_LEVEL = level
logging.root.handlers[0].setLevel(level)
def disable():
'''
Disable logging on all handlers.
'''
logging.root.manager.disable = logging.CRITICAL + 10
def enable():
'''
Renable logging if it has been disabled.
'''
logging.root.manager.disable = min(ECHO_LEVEL, LOG_LEVEL) - 10
def _start(func):
def wrapper(msg, *args):
if len(logging.root.handlers) == 0:
start()
func(msg, *args)
functools.update_wrapper(wrapper, func)
return wrapper
STEP = 0
def step(func):
'''
A function decorator. This will log a step number such as 0005, then
call the decorated function, then ouput an 'end step' marker, eg. Done.
'''
def wrapper(*args, **kwargs):
global STEP
STEP += 1
id = "%04d " % STEP
divider()
info("%s%s" % (id, func.__name__))
divider()
ret = func(*args, **kwargs)
info("Done.(%s)" % id.strip())
return ret
functools.update_wrapper(wrapper, func)
return wrapper
@_start
def debug(msg, *args):
'''
Logs a message with level 10 (DEBUG) to the root logger.
:param msg: Message to be written
:return: None
'''
logging.debug(msg, extra=KWARGS)
@_start
def info(msg, *args):
'''
Logs a message with level 20 (INFO) to the root logger.
:param msg: Message to be written
:return: None
'''
logging.info(msg, extra=KWARGS)
@_start
def warning(msg, *args):
'''
Logs a message with level 30 (WARNING) to the root logger.
:param msg: Message to be written
:return: None
'''
logging.warning(msg, extra=KWARGS)
@_start
def error(msg, *args):
'''
Logs a message with level 40 (ERROR) to the root logger.
:param msg: Message to be written
:return: None
'''
logging.error(msg, extra=KWARGS)
@_start
def critical(msg, *args):
'''
Logs a message with level 50 (CRITICAL) to the root logger.
:param msg: Message to be written
:return: None
'''
logging.critical(msg, extra=KWARGS)
@_start
def exception(msg, *args):
'''
Logs a message with level 40 (ERROR) to the root logger, and
adds exception information to the log. This function should
only be called from within an exception handler.
:param msg: Message to be written
:return: None
'''
logging.exception(msg, *args)
def divider(char=':'):
'''
Create a dividing line in the log output.
:param char: The character of which the dividing line will be composed, by default a ':'.
'''
info(char*70)
@_start
def event(lvl, msg, *args):
'''
Logs a message with the specified level to the root logger.
'''
logging.log(lvl, msg, extra=KWARGS)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
#!/usr/bin/python
print "Summing 1 to 1000";
#Learning: Newline is printed at the end of each print statement
sum = 0;
for i in range (1, 1000, 1):
#Learning: Range excludes the last number, here it excludes 1000
print i
sum = sum + i
# New Block
print "Sum is ", sum
|
Can you find the needle in the haystack?
Write a function findNeedle() that takes an array full of junk but containing one "needle"
After your function finds the needle it should return a message (as a string) that says:
"found the needle at position " plus the index it found the needle
So
should return
def find_needle(haystack):
a = haystack.index("needle")
return "found the needle at position %i" % a
|
def check_palindromo(frase):
"""
Función que recibe una frase, es decir un conjunto de palabras separadas
por espacio y devuelve True si es un palíndromo y False en caso contrario.
Recibe por parámetro la frase que debe ser de tipo string, de lo contrario
devuelve TypeError.
La función devuelve un string.
nota = una frase vacía o una sola letra es un palíndromo, por lo menos
para mi consideración.
nota2 = no importan la capitalización, los acentos sí.
"""
# Validaciones
if not isinstance(frase, str):
return TypeError
# Todo ok
frase = frase.replace(" ", "").upper()
if frase == frase[::-1]:
return True
else:
return False
return frase_final
|
def contar_vocales(palabra):
"""
Función que recibe una palabra y decide si tiene mas letras "e" o mas
letras "a".
Recibe como parámetro un solo dato de tipo string, en caso contrario
devuelve TypeError.
La función devuelve una letra, que hace referencia a la mayor cantidad de
vocales que hay, es decir devuelve "a" si hay mas a's y "e" si hay mas e's
En caso de que haya iguales e's que a's, devuelve None.
"""
# Validaciones
if not isinstance(palabra, str):
return TypeError
# Todo ok
cantidad_a = 0
cantidad_e = 0
# Recorro la palabra.
for letra in palabra:
if letra == "a":
cantidad_a += 1
elif letra == "e":
cantidad_e += 1
# Me fijo cual es el numero más grande.
if cantidad_a == cantidad_e:
return None
else:
if cantidad_a > cantidad_e:
return "a"
else:
return "e"
if __name__ == "__main__":
palabra_pedida = input("Porfavor, ingrese una palabra: ")
result = contar_vocales(palabra_pedida)
if result is None:
print("Hay la misma cantidad de a's que de e's.")
elif result == "a":
print("Hay más a's que e's.")
elif result == "e":
print("Hay más e's que a's.")
|
#!/usr/bin/env python
# coding: utf-8
# # House Price Predictor
# ## Data ananysis using jupytor
# Here we are taking data from uci repository for housing price
#
#
# link : http://archive.ics.uci.edu/ml/machine-learning-databases/housing/
#
# housing.data
#
#
# housing.names
#
# copy these files in the working repository
# # making this data file to work for the project
#
# convert the housing.data to .csv file using microsoft excel (should be properly delimitted for each column)
#
# * copy all the housing.data data to ms excel file
# * select a col and then go to data tab and click on text-to-columns option and set the cols (14 cols)
# * create a blank row for setting heading for each col
# * you can write headings mannually also or can extract it from the housing.names by copying and pasting attribute(attribute information) part in excel and convert it using text-to-cols some how (heading of each col should be same as the heading given in the housing.names
#
# * then finally save the file as .csv file in the same folder
#
#
# here i saved it as data.csv which 13 features and 1 label (14 cols).
#
# Now our raw data is ready to work with ml
#
# ### Note: if data is given to you in .csv format then you don't need to format it you can use it directly for ml project
#
# #### Note: before moving to the project you should know about each and every attributes in the data. how that attribute affect the problem negatively or positively. then you will be able to provide a solution for the given problem
#
#
# versions of library used here
# * python - 3.8.2
# * pip- 20.0.2
# * numpy-1.18.2
# * pandas-1.0.3
# * scikit-learn 0.22.2.post1
# * matplotlib-3.2.1
# * sklearn 0.0
# * jupyter - 1.0.0
# * scipy-1.4.1
#
# before going ahead please install required libraries using pip
#
# Note :if you have different versions or higher versions then please check for functions which are not working in libraries and then update them by searching from google for new versions of library
# # data analysis using pandas
# pandas : pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language
#
# In[1]:
import pandas as pd
# In[2]:
housing = pd.read_csv("data.csv") # housing is a dataframe here openning using pandas
# In[3]:
housing.head() # shows top 5 rows of the data set with heading
# In[4]:
housing.info() # informatoin about the data its attributes,datatypes,and much more
# here the no . of data is very short that is 506 because we are setting a demo for the analysis.
#
# the process gonna be same for ml project with data set like in millions in real world.
#
# taking small data set according to the machine we are having
# In[5]:
housing['CHAS'].value_counts()
# In[6]:
housing.describe() #std : standard deviation 25% -25 percentile of data (50,75),min,max of cols
# In[7]:
# for plotting histogram
get_ipython().run_line_magic('matplotlib', 'inline')
# inline to see the plots in here using matplotlib
import matplotlib.pyplot as plt
# housing.hist(bins=50, figsize=(20,15)) # to show histograms
# ## Now we will split the data for testing and training
# ### Train - Test Splitting
#
# by defining a function for splitting
# it is only for learning purpose
# In[8]:
import numpy as np
def split_train_test(data, test_ratio):
#randomly shuffling the data using numpy
np.random.seed(42) # for fixing the random suffling so that it will be fixed shuffling everytime
shuffled = np.random.permutation(len(data))
#print(shuffled)
#now split
#generally test ratio is 80%-20%
test_set_size = int(len(data) * test_ratio) #506 * 0.2 or 20%
test_indices = shuffled[:test_set_size]
train_indices = shuffled[test_set_size:]
return data.iloc[train_indices], data.iloc[test_indices]
# In[9]:
# train_set, test_set = split_train_test(housing, 0.2)
# In[10]:
# print(f"Rows in train set: {len(train_set)}\nRows in test set: {len(test_set)}\n")
# ## Train - test splitting using sklearn
# we don't need to define a function it is already in sklearn package
# In[11]:
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(housing, test_size = 0.2, random_state=42)
print(f"Rows in train set: {len(train_set)}\nRows in test set: {len(test_set)}\n")
# there is problem here : there may be condition that in training data set we don't cover all kind of population(type of data) present in dataset e.g. in CHAS there are online 35 values which has 1 and 471 has 0 so there may be condition that all 1's will go to test_set and our model will be trained with only 0 value of CHAS which can lead to error in the model because this feature may be very important to know . so while training we will have to cover all kind population given in the data. so we will use stratified sampling to sample the training and testing data.
#
#
# stratified sampling
#
# ### Stratified sampling
# HERE WE WILL BE DOING FOR COL 'CHAS' (WHAT EVER COL IS IMPORTANT USE THAT HERE) SPECIFIED BY THE COMPANY
# In[12]:
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing['CHAS']):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
#splitting the data by the CHAS values in both the datasets
# n-splits : no. of re-shuffling
# In[13]:
# strat_test_set
# strat_test_set.describe()
strat_test_set.info()
strat_test_set['CHAS'].value_counts()
# In[14]:
strat_train_set['CHAS'].value_counts()
# In[15]:
print(95/7)
print(376/28) #you will see here no. of 0's and 1's are equally distributted in both the datasets
# In[16]:
# from here housing will be the training data set
#setting copy of training data set to housing after shuffling
housing = strat_train_set.copy() # now housing will contain training data only
# ## looking for correlation
#
# we are talking about pearson correlation
#
# correlation = how strongly a variable depends on the output
# * 1- strong positive correlation
# * 0- no correlation
# * -1- weak correlation / strong negative correlation
#
# correlation lie between -1 and 1
# In[17]:
#creating correlation matrix
corr_matrix = housing.corr()
corr_matrix['MEDV'].sort_values(ascending=False)
# In[18]:
#plotting correlations for some attributes
from pandas.plotting import scatter_matrix
attributes = ["MEDV","RM","ZN","LSTAT"]
scatter_matrix(housing[attributes], figsize = (15,8))
# In[19]:
housing.plot(kind="scatter", x="RM", y="MEDV",alpha=0.8) # RM vs MEDV +ve correlation
# ## Trying out attribute combinations
#
# In[20]:
housing['TAXRM']= housing['TAX']/housing['RM'] #creating a new attribute by combining TAX and RM and try to see the impact
#TAX per number of rooms in the house
# In[21]:
housing.head() #now you will 15 cols in data
# NOte : it will not affect the original data.csv file it is only for the housing dataframe in this program
# In[22]:
#creating correlation matrix
corr_matrix = housing.corr()
corr_matrix['MEDV'].sort_values(ascending=False)
# In[23]:
housing.plot(kind="scatter", x="TAXRM", y="MEDV",alpha=0.8) #plotting TAXRM with MEDV
# you will see here a -ve correlation
# ## setting train data set featues and labels
# In[24]:
# MEDV is the label col
# we are not adding here the new extra col "TAXRM" to train the model
# it was just for not standard data
# here we are working on a standard data set from uci repository
housing = strat_train_set.drop("MEDV", axis=1) #features 1-13 col
housing_labels = strat_train_set["MEDV"].copy() #labels last col
# ## Missing Attributes
# Means if some of the data is missing from a col/attribute
#
# to take care of missing attributes,you have three options:
# 1. Get rid of the missing data points
# 2. Get rid of the whole attribute
# 3. Set the vlaue to some value(0, mean, median)
# In[25]:
#let assume that some that is missing in attribute RM
a= housing.dropna(subset=["RM"]) #option1
a.shape
# Note that the original housing dataframe will remain unchanged
# In[26]:
housing.drop("RM", axis=1).shape #option2
#Note that there is no RM column and also note that the original housing dataframe will ramain unchanged
# In[27]:
median = housing["RM"].median() #compute median for option3
# In[28]:
housing["RM"].fillna(median) #option3
#note that the original housing dataframe will remain unchanged
# In[29]:
housing.shape
# In[30]:
housing.describe() #before we started imputer
# RM has 3 missing values in the dataset
# ## Now we will be doing this using sklearn
# In[31]:
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy = "median")
imputer.fit(housing)
# In[32]:
imputer.statistics_.shape
# In[33]:
imputer.statistics_ #median of each cols
# ### Now we will fit value in any missing values in any column in the data
# In[34]:
X = imputer.transform(housing)
# In[35]:
housing_tr = pd.DataFrame(X, columns=housing.columns) # create new dataframe with housing for training data set
# In[36]:
housing_tr.describe() #after applying imputer in housing and storing it to housing_tr
#now no missing values are there
# #### upto this step we were analysing the data , understanding its patthern, and understanding the data , Now we prepare the model
# ## Scikit-learn Design
# Primarily, there are three types of objects
# 1. Estimators - It estimates some parameter based on a dataset. Eg. imputer. It has fit() method and transform() method. Fit method - Fits the dataset and calculates internal parameters
#
# 2. Transformers - transform method takes input and returns output based on the learnings from fit() . It also has a convenience function called fit_transform() which fits and then transforms.
#
# 3. Predictors - LinearRegression model is an example of predictor. fit() and predict() are two common functions. It also gives score() function which will evaluate the predictions.
# ## Feature Scaling
# making all feature values to a similar kind of scaling
# Primarily, two types of feature scaling methods:
# 1. Min-max scaling (Normalization)
# * (value-min)/(max-min)
# * Sklearn provides a class called MinMaxScaler for this
# 2. Standardization
# * (value - mean)/std
# * Sklearn provides a class called standard scaler for this
#
# std - >standard deviation
#
# we will use standardization here
# # Creating a Pipeline
# pipeline : so that we can make changes to our model easily later, doing series of steps in the problem, so that we can automate the task
#
# using sklearn: it provide piplining also
# In[37]:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
my_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
# .... add as many as you want in your pipeline
('std_scaler', StandardScaler()),
])
# In[38]:
housing_num_tr= my_pipeline.fit_transform(housing)
# In[39]:
housing_num_tr #it is an numpy array
# In[40]:
housing_num_tr.shape # for train dataset
# # Selecting a desired model for this House Price Prediction problem
# ## You can change here different models for results don't need to change anywhere
# In[41]:
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
#using Linear
# model = LinearRegression()
#usng tree regressor
# model = DecisionTreeRegressor()
#using random forest
model = RandomForestRegressor()
model.fit(housing_num_tr, housing_labels) #giving features and lables of training data to fit the model
# ## now model has been fitted
# In[42]:
#check for some data from training dataset
some_data = housing.iloc[:5]
# In[43]:
some_labels = housing_labels.iloc[:5]
# In[44]:
prepared_data = my_pipeline.transform(some_data)
# In[45]:
model.predict(prepared_data) #predicted output numpy array
# In[46]:
list(some_labels) #original output
# ## Evaluating the model
# using Root mean square error
# In[47]:
from sklearn.metrics import mean_squared_error
housing_predictions = model.predict(housing_num_tr)
mse = mean_squared_error(housing_labels, housing_predictions) #parameter actual labels, predicted labels
rmse = np.sqrt(mse)
# In[48]:
rmse
# it shows overfitting for tree regressor
# ## Using better evaluation technique - cross validation
# making 10 groups of training data 1 2 3 4 5 6 7 8 9 10
#
# then take 1 group for testing and 9 group for training and find error
#
# do this for all the ten groups and then find the combined error
# In[49]:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, housing_num_tr, housing_labels, scoring="neg_mean_squared_error", cv=10)
#cv = 10 means go for 10 folds
rmse_scores = np.sqrt(-scores)
# In[50]:
rmse_scores #numpy array
# using this evaluation for tree regression it looks like this is better than linear regression
# In[51]:
def print_scores(scores):
print("Scores: ",scores)
print("Mean: ",scores.mean())
print("Standard deviation" , scores.std())
# In[52]:
print_scores(rmse_scores)
# #### make python file for this model to run on visual studio
# #### now create a sklearn joblib for this
# # Saving the model
# In[53]:
from joblib import dump, load
dump(model, 'HPP.joblib')
# # Testing the model on test data
# In[54]:
X_test = strat_test_set.drop("MEDV", axis=1)
Y_test = strat_test_set["MEDV"].copy()
X_test_prepared = my_pipeline.transform(X_test)
final_predictions = model.predict(X_test_prepared)
final_mse = mean_squared_error(Y_test, final_predictions)
final_rmse = np.sqrt(final_mse)
# In[55]:
final_rmse
# In[56]:
print(final_predictions, list(Y_test))
# In[57]:
prepared_data[0]
# In[58]:
some_labels
# # Using the model to take output
# In[59]:
from joblib import dump, load
import numpy as np
model = load('HPP.joblib')
features = np.array([[-0.43942006, 3.12628155, -1.12165014, -0.27288841, -1.42262747,
-0.841041, -1.312238772, 2.61111401, -1.0016859 , -0.5778192 ,
-0.97491834, 0.456164221, -0.86091034]])
model.predict(features)
# In[ ]:
|
#! python3
# EnglishTools.py - some helpful english tools
def Usage():
print("""
Usage:
#1
Thesaurus(word: "the word you want to search")
==> open thesaurus.com to find the thesaurus for the word
#2
Dictionary(word: "the word you want to search")
==> open dictionary.com to find the definition of the word
""")
import requests, bs4
from selenium import webdriver
def Thesaurus(word: str):
"""open thesaurus.com to find the thesaurus for the word"""
if type(word) != str:
raise TypeError("input has to be a string")
word = word.lower()
res = requests.get(r"http://www.thesaurus.com/browse/{}".format(word))
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")
word_list = soup.select("li > a[data-linkid='nn1ov4']")[:5]
for i in range(len(word_list)):
word_list[i] = word_list[i].getText()
return word_list
def Dictionary(word: str):
"""open dictionary.com to find the definition of the word"""
if type(word) != str:
raise TypeError("input has to be a string")
word = word.lower()
browser = webdriver.Firefox()
browser.get(r"http://www.dictionary.com/browse/{}".format(word))
if __name__ == "__main__":
Usage()
print(Thesaurus("cat"))
Dictionary("colic")
|
class Solution:
def thirdMax(self, nums: List[int]) -> int:
nums = set(nums)
return sorted(nums, reverse=True)[2] if len(nums) > 2 else max(nums)
|
from math import sqrt
class Vec():
@staticmethod
def distance(v1, v2):
delta = v1 - v2
return sqrt(delta.x ** 2.0 + delta.y ** 2.0)
@staticmethod
def zero():
return Vec(0.0, 0.0)
def __init__(self, x, y):
self.x = x
self.y = y
def magnitude(self):
return sqrt(self.x**2 + self.y**2)
def dot(self, v):
return self.x * v.x + self.y * v.y
def normalized(self):
return self / self.length
def __eq__(a, b):
return a.x == b.x and a.y == b.y
def __add__(a, b):
return Vec(a.x + b.x, a.y + b.y)
def __iadd__(a, b):
a.x += b.x
a.y += b.y
return a
def __sub__(a, b):
return Vec(a.x - b.x, a.y - b.y)
def __isub__(a, b):
a.x -= b.x
a.y -= b.y
return a
def __mul__(a, b):
if isinstance(a, (float, int, complex)):
return Vec(a.x * b, a.y * b)
return Vec(a.x * b.x, a.y * b.y)
def __imul__(a, b):
if isinstance(b, (float, int, complex)):
a.x *= b
a.y *= b
else:
a.x *= b.x
a.y *= b.y
return a
def __div__(a, b):
if isinstance(b, (float, int, complex)):
return Vec(a.x/b, a.y/b)
return Vec(a.x/b.x, a.y/b.y)
def __idiv__(a, b):
if isinstance(b, (float, int, complex)):
a.x /= b
a.y /= b
else:
a.x /= b.x
a.y /= b.y
return a
def __truediv__(a, b):
return a.__div__(b)
def __str__(self):
return 'Vec: [%s, %s]' % (self.x, self.y)
def __repr__(self):
return self.__str__()
|
from Room import Room
from Guest import Guest
from Booking import Booking
from inputHandler import handleInput
from utilityFunctions import *
guestObjList = [];
roomObjList = [];
bookingObjList = [];
def addGuest():
while(True):
guestName = handleInput("Please enter guest name:", "string", [1,1], None)
newGuestId = len(guestObjList) + 1
guestObjList.append(Guest(guestName,newGuestId))
print("Guest {} has been created with guest ID: {}".format(guestName,newGuestId))
multiChoice = handleInput("Would you like to [A]dd a new guest or [R]eturn to the previous menu? ", "string", [1,1],["A","R"])
if(multiChoice == 'R'): return
def addRoom():
while(True):
while(True):
enteredRoomNumber = handleInput("Please enter room number:", "integer", None, None)
roomNumberRepeated = listMatchedProperty(roomObjList,"roomNum", enteredRoomNumber) #checks for duplicate property arguments(object, getterFunction, newPropertyValue)
if(len(roomNumberRepeated) > 0):
print("Room already exists.", end =" ")
else: break
roomCapacity = handleInput("Please enter room capacity:", "integer", None, None)
roomObjList.append(Room(enteredRoomNumber,roomCapacity))
multiChoice = handleInput("Would you like to [A]dd a new room or [R]eturn to the previous menu? ", "string", [1,1],["A","R"])
if(multiChoice == 'R'): return
def addBooking():
while(True):
enteredGuestId = validateGuestId(guestObjList) # validate if entered guestId exists or not
while(True): #this loop continues if user enters existing room number which does not exceed guest number
enteredRoomNumber = handleInput("Please enter room number:", "integer", None, None)
roomNumExists = listMatchedProperty(roomObjList,"roomNum", enteredRoomNumber)
if(roomNumExists):
selectedRoomObj = roomObjList[roomNumExists[0]]
roomCapacity = getattr(selectedRoomObj,"roomCapacity")
enteredGuestNumber = handleInput("Please enter number of guests: ", "integer", [1,None], None)
if(roomCapacity < enteredGuestNumber):
print("Guest count exceeds room capacity of: {}".format(roomCapacity))
else: break
else:
print("Room does not exist.")
checkInMonth = handleInput("Please enter check-in month: ", "integer", [1,12], None)
checkInDay = handleInput("Please enter check-in day: ", "integer", [1,31], None)
checkOutMonth = handleInput("Please enter check-out month: ", "integer", [checkInMonth,12], None) #input is invalid for checkout month before checkin month
coutDayLowerLimit = checkInDay if(checkInMonth == checkOutMonth) else 1 #getting limit for checkout day, for same month checkout day cant be before check in day
checkOutDay = handleInput("Please enter check-out day: ", "integer", [coutDayLowerLimit,31], None) #input is invalid for checkout day before checkin day
checkinDOY = dateToDayNumber(checkInMonth,checkInDay) #checkin day of year
checkoutDOY = dateToDayNumber(checkOutMonth,checkOutDay) #checkout day of year
isBookingAvailable = bookingAvailable(checkinDOY,checkoutDOY,enteredRoomNumber,bookingObjList)
if(isBookingAvailable):
guestName = getattr(guestObjList[enteredGuestId-1],"name")
bookingObjList.append(Booking(guestName,enteredRoomNumber,enteredGuestId,enteredGuestNumber,checkinDOY,checkoutDOY))
print("*** Booking successful! ***")
else:
while(True): #this loop continues if user enter exixting room number and does not exceed
enteredRoomNumber = handleInput("Room is not available during that period. Please enter new room number:", "integer", None, None)
roomNumExists = listMatchedProperty(roomObjList,"roomNum", enteredRoomNumber)
isBookingAvailable = bookingAvailable(checkinDOY,checkoutDOY,enteredRoomNumber,bookingObjList)
if(isBookingAvailable):
guestName = getattr(guestObjList[enteredGuestId-1],"name")
bookingObjList.append(Booking(guestName,enteredRoomNumber,enteredGuestId,enteredGuestNumber,checkinDOY,checkoutDOY))
print("*** Booking successful! ***")
break
multiChoice = handleInput("Would you like to [A]dd a new booking or [R]eturn to the previous menu? ", "string", [1,1],["A","R"])
if(multiChoice == 'R'): return
def viewBookings():
multiChoice = handleInput("Would you like to view [G]uest bookings, [R]oom booking, or e[X]it? ", "string", [1,1],["G","R","X"])
if(multiChoice == "G"):
enteredGuestId = validateGuestId(guestObjList)
matchingBookingList = listMatchedProperty(bookingObjList,"guestId", enteredGuestId)
showBooking(matchingBookingList,bookingObjList,"guestId") # shows booking according to guest Id
if(multiChoice == "R"):
while(True): #this loop continues if user enter existing room number
enteredRoomNumber = handleInput("Please enter room number:", "integer", None, None)
roomExists = listMatchedProperty(roomObjList,"roomNum", enteredRoomNumber)
if(roomExists):
break
else:
print("Room does not exist.")
matchingBookingList = listMatchedProperty(bookingObjList,"roomNum", enteredRoomNumber)
showBooking(matchingBookingList,bookingObjList,"roomNum") # shows booking according to guest Id
if(multiChoice == "X"): return |
import copy
file_input = 'input.txt'
with open(file_input, encoding='utf-8') as file:
contents = file.read()
inputs = contents.split('\n')
for i in range(len(inputs)):
inputs[i] = inputs[i].replace(' ', '')
def calculate_end_parenthesis(expression):
level = 0
for i in range(len(expression)):
if(expression[i]=='('):
level += 1
if(expression[i]==')'):
level -= 1
if(expression[i]==')' and level==0):
return i
def calculate_expression(expression):
answer = []
cur_ans = 0
i = 0
while i < len(expression):
if(expression[i]=='*'):
answer.append(cur_ans)
cur_ans=0
if(expression[i]=='('):
end_position = calculate_end_parenthesis(expression[i:])
cur_ans += calculate_expression(expression[i+1:end_position+i+1])
i+=end_position
if(expression[i].isnumeric()):
cur_ans += int(expression[i])
i+= 1
answer.append(cur_ans)
result = 1
for i in range(len(answer)):
result*=answer[i]
return result
def day_1():
result = 0
for i in range(len(inputs)):
result += calculate_expression(inputs[i])
print(result)
day_1() |
# Disciplina: Bioinformática
# Professor: Luiz Cláudio Demes
# Aluno: Hilderlan
######### Programa que faz a transcrição de DNA para RNAm ##########
arq = open('input.txt', 'r')
dna = arq.read()
arq.close()
rna = ''
print('Molécula de DNA a ser transcrita: {}'.format(dna))
for i in dna:
if (i == 'A'):
rna += 'U'
elif (i == 'T'):
rna += 'A'
elif (i == 'G'):
rna += 'C'
elif (i == 'C'):
rna += 'G'
else:
rna += ''
print('̣O resultado da transcrição está no arquivo output.txt!')
arq = open ('output.txt', 'w')
arq.write(rna)
arq.close() |
# -*-coding=utf-8-*-
__author__ = 'Rocky'
import sqlite3
def create_table():
conn = sqlite3.connect('shenzhen_house.db')
try:
create_tb_cmd='''
CREATE TABLE IF NOT EXISTS HOUSE
('日期' TEXT,
'一手房套数' TEXT,
'一手房面积' TEXT,
'二手房套数' TEXT,
'二手房面积' TEXT);
'''
#主要就是上面的语句
conn.execute(create_tb_cmd)
except:
print("Create table failed")
return False
conn.execute(create_tb_cmd)
conn.commit()
conn.close()
def insert(date,one_hand,one_area,second_hand,second_area):
conn = sqlite3.connect('shenzhen_house.db')
print("open database passed")
cmd="INSERT INTO HOUSE ('日期','一手房套数','一手房面积','二手房套数','二手房面积') VALUES('%s','%s','%s','%s','%s');" %(date,one_hand,one_area,second_hand,second_area)
#works 要么加\"
#paul_su="INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES(5,'%s',32,'CALIFORNIA',2000.00);" %temp2
#works 要么加 ’‘
#allen="INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES(2,'ALLEN',72,'CALIFORNIA',20500.00);"
#teddy="INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES(3,'TEDDY',732,'CALIFORNIA',52000.00);"
#mark="INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES(4,'MARK',327,'CALIFORNIA',3000.00);"
#sun="INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES(?,?,?,?,?);"
#conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES(?,?,32,'CALIFORNIA',2000.00)",temp)
conn.execute(cmd)
conn.commit()
conn.close() |
print("Enter the number")
num=input()
i=int(int(num)/int(num))
while i<int(num)+int(i/i):
if i%((i/i)+(i/i)+(i/i))==i-i:
if i%((i/i)+(i/i)+(i/i)+(i/i)+(i/i))==i-i:print("Fizz\nBuzz")
else:print("Fizz")
else:
if i%((i/i)+(i/i)+(i/i)+(i/i)+(i/i))==i-i:print("Buzz")
else:print(i)
i=i+(i-(i-int(i/i)))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 10:29:24 2018
@author: yatheen!
"""
"""Step 1: Import the neccessary Packages """
import cv2 #OpenCv to handle and process the images
import numpy as np #Images are stores as numpy arrays
import matplotlib.pyplot as plt # to plot the image we have to use matplotlib
#----------------------------------------------------------------------------------------------#
""" To display the result in a seperate Screen, use the following code (Optional) """
from IPython import get_ipython # the plot is shown as a seperate screen
get_ipython().run_line_magic('matplotlib', 'qt') # use Ipython package to make the run_line_magic function
print("All packages Imported succesfully!") #jus a check
#----------------------------------------------------------------------------------------------#
"""Step 3: Read the image input """
image = cv2.imread(r"E:\Image processing\Edge detection\vp.jpg",0) # get the image as input
"""
The second argument in the image determines how the input is readed
0 ---> the image is read as grayscale image
1 ---> the image is read as color image """
#image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) if color image is read as input , change it to grayscale
#----------------------------------------------------------------------------------------------#
"""Step 4 : Detect the egdes using Canny Shape Descriptor """
edges = cv2.Canny(image , 300,200) #Canny shape descriptor is used to identify the edges.
#----------------------------------------------------------------------------------------------#
"""Step 5: Plot the result """
plt.subplot(121) #121 is the index of the plot of the original image
plt.imshow(image,cmap = 'gray')
plt.title('Original Image')
plt.xticks([])
plt.yticks([])
plt.subplot(122)
plt.imshow(edges ,cmap = 'gray')
plt.title('Image with edges detected')
plt.xticks([]) #Get or set the x-limits of the current tick locations and labels.
plt.yticks([]) #Get or set the y-limits of the current tick locations and labels.
plt.show() # Display the plot
#----------------------------------------------------------------------------------------------# |
import turtle
turtle.bgcolor("black")
turtle.width(2)
turtle.color("red","yellow")
def trifun(size):
for i in range(3):
turtle.fd(size)
turtle.left(120)
size = size-5
for i in range(5):
trifun(150)
trifun(135)
trifun(120)
turtle.done() |
'''
@author: Mateus Araujo
'''
nomes_proprios = ["carlos", "antonio", "paulo", "pedro", "maria", "chico", "chica"]
s1 = "Antonio comprou dois livros sobre a vida de chico"
s2 = "paulo joga muito bem, mas pedro joga melhor"
s3 = "antonio não sabe brincar, é um brutamonte..."
def capitalize_names(s, lista):
alter_e = str()
for item in lista:
if item in s and alter_e == "":
alter_e = s.replace(item, item.capitalize()) + "\n"
elif alter_e:
alter_e = alter_e.replace(item, item.capitalize())
return alter_e
entrada = str(input("Entrada: \nR- "))
alter_e = capitalize_names(entrada, nomes_proprios)
print("Saída: ", alter_e)
'''
as1 = capitalize_names(s1, nomes_proprios)
as2 = capitalize_names(s2, nomes_proprios)
as3 = capitalize_names(s3, nomes_proprios)
print(s1)
print(as1)
print(s2)
print(as2)
print(s3)
print(as3)
''' |
r1=int(input())
r2=1
for j in range(1,r1+1):
r2=r2*j
print(r2)
|
#Return the items from the beginning to "green": ["black", "yellow", "pink", "green", "purple", "white", "grey"]
thislist =["black", "yellow", "pink", "green", "purple", "white", "grey"]
print(thislist[:4])
|
import tkinter as TK
from tkinter import ttk
import crud as crud
class interface:
def __init__(self, janela):
print("--------------------- CONSTRUCTOR ---------------------")
self.objeto_bd = crud.AppBD()
#----------- COMPONENTES ----------- #
self.label_codigo = TK.Label(janela, text= "codigo do Produto")
self.label_nome = TK.Label(janela, text= "nome do Produto")
self.label_preco = TK.Label(janela, text= "preco do Produto")
self.texto_codigo = TK.Entry(bd=3)
self.texto_nome = TK.Entry()
self.texto_preco = TK.Entry()
# AS FUNCOES MEU JOVEM DOS COMANDOS DOS BTNS ESTAO LA EM BAIXO NA LINHA 114
self.btn_cadastrar = TK.Button(janela, text="CADASTRAR", command= self.fn_cadastrar_produto)
self.btn_atualizar = TK.Button(janela, text="ATUALZIAR", command= self.fn_atualizar_produto)
self.btn_excluir = TK.Button(janela, text="EXCLUIR", command= self.fn_exluir_produto)
self.btn_limpar = TK.Button(janela, text="LIMPAR", command= self.fn_limpar_tela)
# O construtor ainda possui mais duas partes. Uma delas é responsável por instanciar e configurar o componente “TreeView”
self.dados_column = ("Código", "Nome", "Preço")
self.tree_produtos = ttk.Treeview(janela, columns= self.dados_column, selectmode= "browse")
self.scrollbar = ttk.Scrollbar(janela, orient="vertical", command= self.tree_produtos.yview)
self.scrollbar.pack(side="right", fill= 'x' )
self.tree_produtos.configure(yscrollcommand = self.scrollbar.set)
self.tree_produtos.heading("Código", text="Códido")
self.tree_produtos.heading("Nome", text="Nome")
self.tree_produtos.heading("Preço", text="Preço")
self.tree_produtos.column("Código", minwidth= 0, width= 100)
self.tree_produtos.column("Nome", minwidth= 0, width= 100)
self.tree_produtos.column("Preço", minwidth= 0, width= 100)
self.tree_produtos.pack(padx=10, pady=10)
self.tree_produtos.bind("<<TreeviewSelect>>", self.apresentar_registros_selecionados)
# O posicionamento dos elementos na janela
# ------------- CODIGO ------------- #
self.label_codigo.place( x= 100, y= 50)
self.texto_codigo.place( x= 250, y= 50)
# -------------- NOME -------------- #
self.label_nome.place( x= 100, y= 100)
self.texto_nome.place( x= 250, y= 100)
# -------------- PRECO ------------- #
self.label_preco.place( x= 100, y= 150)
self.texto_preco.place( x= 250, y= 150)
# ------------- BUTTON ------------- #
self.btn_cadastrar.place( x= 100, y= 200)
self.btn_atualizar.place( x= 200, y= 200)
self.btn_excluir.place( x= 300, y= 200)
self.btn_limpar.place( x= 400, y= 200)
# ------------ TREEVIEW ------------ #
self.tree_produtos.place( x= 100, y= 300)
self.scrollbar.place( x= 805, y= 300, height= 225)
self.carregar_dados_iniciais()
# Esta function exibe os dados selecionados na grade (componente “TreeView”) nas caixas de texto, de modo que o usuário possa fazer alterações, ou exclusões sobre eles
def apresentar_registros_selecionados(self, evento):
self.fn_limpar_tela()
for selection in self.tree_produtos.selection():
item = self.tree_produtos.item(selection)
codigo, nome, preco = item["values"][0:3]
self.texto_codigo.insert( 0, codigo)
self.texto_nome.insert( 0, nome)
self.texto_preco.insert( 0, preco)
# Esta function carrega os dados que já estão armazenados na tabela para serem exibidos na grade de dados (componente “TreeView”)
def carregar_dados_iniciais(self):
try:
self.id = 0
self.iid = 0
registros = self.objeto_bd.selecionarProduto()
print("-------------------------- DADOS DISPONIVEIS NO BD ------------------------------")
for item in registros:
codigo = item[0]
nome = item[1]
preco = item[2]
# INSERIR NA TABELA TREEVIEW
self.tree_produtos.insert('', 'end', iid= self.iid, values= ( codigo, nome, preco ))
self.iid = self.iid + 1
self.id = self.id + 1
print("------------> DADOS DA BASE <------------- ")
except:
print('------------> AINDA NAO EXISTE DADOS PARA SEREM CARREGADOS <-----------')
# Esta function lê os dados que estão nas caixas de texto e os retorna para quem faz a chamada.
def fler_campos(self):
try:
print("*************** DADOS DISPONIVEIS ******************")
codigo = int(self.texto_codigo.get()) # pegar o texto que esta no campo e converter para inteiro safe!
nome = self.texto_nome.get()
preco = float(self.texto_preco.get())# pegar o texto que esta no campo e converter para float "famoso ctrl + v da linha 102 kk" safe!
print("-----------------> LEITURA DOS DADOS COM SUCESSO <-------------------")
print('codigo --> '+ codigo,'\nnome ---> '+ nome,'\npreco --> '+ preco)
except:
print('NAO FOI POSSIBLE LER OS DADOS!')
return codigo, nome, preco
# Esta function tem como objetivo fazer a inserção dos dados na tabela “PRODUTOS”
def fn_cadastrar_produto(self):
try:
print("*************** DADOS DISPONIVEIS ******************")
# DESESTRUTURANDO kkkk O FLEX CAMPOS FUNCAO DE CIMA
codigo, nome, preco = self.fler_campos()
# LEMBRANDO QUE ESSE È O CRUD DO ARQUIVO CRUD.PY
self.objeto_bd.inserirDados(codigo, nome, preco) # INSERT INTO public."PRODUTO" os campinhos basicos VALUES (codigo, nome, preco)
# INSERINDO TBM NO NOSSO QUERIDA TABELINHA TREEVIEW
self.tree_produtos.insert('', 'end', iid= self.iid, values= ( codigo, nome, preco ))
self.iid = self.iid + 1
self.id = self.id + 1
self.fn_limpar_tela()
print("------> PRODUTO CADASTRADO COM SUCESSO!!")
except:
print("NAO FOI POSSIVEL FAZER O CADASTRO")
# ESSA FUNCTION SE JA TA LIGADO QUE VAI FAZER !!!!! brinks É atualizar os dados que o usuário selecionou na grade de dados
def fn_atualizar_produto(self):
try:
print("*************** DADOS DISPONIVEIS ******************")
codigo, nome, preco = self.fler_campos()
#FILE CRUD.JS
self.objeto_bd.atualizarDados(codigo, nome, preco)
#CARREGAR DADOS NA TELA
self.tree_produtos.delete(*self.tree_produtos.get_children())
self.carregar_dados_iniciais()
self.fn_limpar_tela()
print("------> PRODUTO ATUALIZADO COM SUCESSO!!")
except:
print("NAO FOI POSSIVEL FAZER ATUALIZAÇÂO")
#Essa function Excluir os dados que o usuário selecionou na grade de dados, aque menos gosto :)
def fn_exluir_produto(self):
try:
print("*************** DADOS DISPONIVEIS ******************")
codigo = self.fler_campos()
#FILE CRUD.JS
self.objeto_bd.deletarDados(codigo)
#CARREGAR DADOS NA TELA
self.tree_produtos.delete(*self.tree_produtos.get_children())
self.carregar_dados_iniciais()
self.fn_limpar_tela()
print("------> PRODUTO DELETADO COM SUCESSO!!")
except:
print(f"NAO FOI POSSIVEL DELETAR O PRODUTO COM O Nº{codigo}")
#Esta function limpa o conteúdo das caixas de texto
def fn_limpar_tela(self):
try:
print("*************** DADOS DOS CAMPOS ************")
self.texto_codigo.delete(0, TK.END)
self.texto_nome.delete(0, TK.END)
self.texto_preco.delete(0, TK.END)
print("*************** CAMPOS LIMPOS ***************")
except:
print("NAO FOI POSSIVEL LIMPAR OS CAMPOS") |
from inheritance_intro import Decimal
class Leg:
def __init__(self):
self.length = 0
def set_leg_length(self, length):
self.length = length
def __repr__(self):
return "A leg {} inches long".format(Decimal(self.length, 2))
class Back:
pass
class Chair:
def __init__(self, num_legs):
self.legs = [Leg() for leg in range(num_legs)]
self.back = Back()
def __repr__(self):
return "I am a Chair with {} legs and one Back".format(len(self.legs))
c = Chair(4)
c.legs[0].set_leg_length(12)
print(c.legs[0])
|
def rev_string(input):
str = ""
for i in input:
str = i + str
return str
s=input("Please type someting here to reverse : ")
rmv_space=s.replace(" ", "")
lower_string=rmv_space.lower()
rev_string_display=rev_string(lower_string)
print(rev_string_display)
import sys
sys.exit(0)
|
x = 5
y = 2
z = (f"P({x},{y})")
if x>0 and y>0:
print(f'Punkt {z} znajduje się w pierwszej ćwiartce układu współrzędnych')
elif x<0 and y>0:
print(f'Punkt {z} znajduje się w drugiej ćwiartce układu współrzędnych')
elif x<0 and y<0:
print(f'Punkt {z} znajduje się w trzeciej ćwiartce układu współrzędnych')
else:
print(f'Punkt {z} znajduje się w czwartej ćwiartce układu współrzędnych') |
print('Książka e-book')
print(15 * '=')
class Ksiazka_elektroniczna():
def __init__(self, tytul, autor, liczba_stron):
self.stan_k = False
self.tytul = tytul
self.autor = autor
self.liczba_stron = liczba_stron
self.nr_bieżącej_strony = 1
def otwarta(self):
self.stan_k = True
def zamknieta(self):
self.stan_k = False
def set_strona(self, new_nr_strony):
self.nr_bieżącej_strony = new_nr_strony
#def set_strona(self, strona):
#self.nr_bieżącej_strony += strona
if self.nr_bieżącej_strony > 350:
self.nr_bieżącej_strony = 350
if self.nr_bieżącej_strony <= 0:
self.nr_bieżącej_strony = 1
def status(self):
print(self.tytul)
print(self.autor)
print(f'{self.liczba_stron} stron')
print(15 * '=')
if self.stan_k:
print(f'Książka jest otwarta na stronie {self.nr_bieżącej_strony}')
else:
print('Książka jest zamknięta')
ksiazka = Ksiazka_elektroniczna('Harry Potter', 'J.K.Rowling', 350)
ksiazka.otwarta()
ksiazka.set_strona(1)
ksiazka.status() |
x = int(input("Wprowadź liczbę: "))
y = int(input("Wprowadź liczbę: "))
if x < 0 or y < 0:
print("Jedna lub dwie z wprowadonych liczb są ujemne")
else:
print("Żadna z wprowadonych liczb nie jest ujemna") |
a = input('Podaj liczbe a: ')
b = input('Podaj liczbe b: ')
c = input('Podaj liczbe c: ')
import math
a = int(a)
b = int(b)
c = int(c)
d = b**2 - 4*a*c
D = math.sqrt(d)
x1 = (-b+D)/2*a
x2 = (-b-D)/2*a
print(a, 'x^2', '+', b, 'x', '+', c, '=', '0', end='')
print(f'D = {D}')
print(f'X1 = {x1}')
print(f'X2 = {x2}')
|
def binary_search(alist, item):
#二分查找,递归版本
n = len(alist)
if n > 0:
mid = n // 2
if item == alist[mid]:
return True
elif item < alist[mid]:
return binary_search(alist[:mid], item)
else:
return binary_search(alist[mid+1:], item)
return False
def binary_search_2(alist,item):
#二分法查找,非递归的方式
n = len(alist)
first = 0
last = n - 1
while first <= last:
mid = (first + last) // 2
if item == alist[mid]:
return True
elif item < alist[mid]:
last = mid - 1
elif item > alist[mid]:
first = mid + 1
return False
ll = [1,2,3,4,5,6,7]
print(binary_search(ll,3))
print(binary_search(ll,10))
print(binary_search_2(ll,4))
print(binary_search_2(ll,10))
|
class Deque(object):
#双端队列
def __init__(self):
self.__list = []#创建一个私有容器
# 如果出队的频率比入队的频率大得多,那就从列表的尾部弹出,头部进入队列
# 反之的话,就从头部弹出,尾部进入,与具体的应用相关
def add_front(self, item):
# 头部进队列
# self.__list.append(item)
self.__list.insert(0, item)
def add_rear(self, item):
# 尾部进队列
self.__list.append(item)
#self.__list.insert(0, item)
def remove_front(self):
# 出队列,头部出队列
return self.__list.pop(0)
# self.__list.pop()
def remove_rear(self):
return self.__list.pop()
def is_empty(self):
# 判断是否为空
return self.__list == []
def size(self):
# 返回队列的大小
return len(self.__list)
s = Deque()
s.add_front(1)
s.add_front(2)
s.add_rear(3)
s.add_rear(4)
print(s.size())
# print(s.peek())
print(s.remove_front())
print(s.remove_front())
print(s.remove_rear())
print(s.remove_rear()) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class calc:
def suma(self, x, y):
'''argumentos de entrada: dos listas, cada una con un polinomio
retorna: la suma de los dos polinomios
'''
may = x
men = y
sum = [0]*len(may)
if len(x) < len(y):
men = x
may = y
sum = [men[i] + may[i] for i in range(len(men))]
aux = [may[i] for i in range(len(men),len(may))]
sum = sum + aux
print("--------------------------------------------------------------")
print("El resultado de sumar ", str(x), "+", str(y), " es: ", str(sum))
print("--------------------------------------------------------------")
def resta(self, x, y):
'''argumentos de entrada: dos listas, cada una con un polinomio
retorna: la resta de los dos polinomios
'''
may = x
men = [y[i]*(-1) for i in range(len(y))]
sum = [0]*len(may)
if len(x) < len(y):
men = x
may = [y[i]*(-1) for i in range(len(y))]
sum = [men[i] + may[i] for i in range(len(men))]
aux = [may[i] for i in range(len(men),len(may))]
res = sum + aux
print("--------------------------------------------------------------")
print("El resultado de restar ", str(x), "-", str(y), " es: ", str(res))
print("--------------------------------------------------------------")
def multPolinomio(self, x, y):
'''argumentos de entrada: dos listas, cada una con un polinomio
retorna: la multiplicación de los dos polinomios
'''
p1 = len(x) - 1
p2 = len(y) - 1
p_mult = [0]*(p1 + p2 + 1)
for i in range(len(x)):
for j in range(len(y)):
p_mult[i+j] += x[i]*y[j]
print("------------------------------------------------------------------------------------")
print("El resultado de multiplicar los polinomios ", str(x), "*", str(y), " es: ", str(p_mult))
print("------------------------------------------------------------------------------------")
def multEscalar(self, x, y):
'''argumentos de entrada: dos listas, una con un polinomio y otra con el valor correpsondiente al escalar
retorna: la multiplicación de un polinomio y un escalar
'''
e_mult = [x[i]*(y[0]) for i in range(len(x))]
print("-----------------------------------------------------------------------------------------------")
print("El resultado de multiplicar el polinomio y el escalar ", str(x), "*", str(y), " es: ", str(e_mult))
print("------------------------------------------------------------------------------------------------")
def evalPolinomio(self, x, y):
'''argumentos de entrada: dos listas, una con un polinomio y otra con el valor correpsondiente al escalar
retorna: la evaluación de los dos polinomios
'''
eval, power = 0, 0
for coeff in x:
eval += (y[0]**power) * coeff
power += 1
print("--------------------------------------------------------------------------------")
print("El resultado de evaluar los polinomios ", str(x), "y", str(y), " es: ", str(eval))
print("--------------------------------------------------------------------------------") |
'''
@amoghari
Determin average salary of a driver in a given year, month and over all.
'''
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import month,year
conf = SparkConf().setAppName('Sample Program')
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
s3 = 's3://taxidata.com/'
year1 = s3+'2010/'
year2 = s3+'2011/'
year3 = s3+'2012/'
year4 = s3+'2013/'
inputData = sqlContext.read.parquet(year1,year2,year3,year4)
# Convert datetime format into year and month column. Create new df for analysis.
pickupDistSalary = inputData.select('driverId','totalAmount',\
year('pickupTime').alias('year'),\
month('pickupTime').alias('month')).cache()
# Sum every driver's salary over year and month.
yearMonthGroup = (pickupDistSalary.groupBy('year','month','driverId')
.sum('totalAmount'))
# Performans monthly salary analysis by averaging by the number of drivers.
averageMonthYearSalary = (yearMonthGroup.withColumnRenamed('sum(totalAmount)','Sum')
.groupBy('year','month').mean('Sum')).coalesce(1)
# Creates new dataframe to do salary analysis on yearly basis.
pickupDistSalaryYear = pickupDistSalary.select('driverId','year','totalAmount')
# Sum every driver's yearly salary.
yearGroup = (pickupDistSalaryYear.groupBy('year','driverId')
.sum('totalAmount'))
# Average the yearly salary of a driver by taking average of all driver's salary.
averageYearSalary = (yearGroup.withColumnRenamed('sum(totalAmount)','Sum')
.groupBy('year').mean('Sum')).coalesce(1)
# Rename the columns to save it into the CSV file.
averageMonthYearSalary = averageMonthYearSalary.withColumnRenamed('avg(Sum)','Salary')
averageYearSalary = averageYearSalary.withColumnRenamed('avg(Sum)','Salary')
(averageMonthYearSalary.write.mode('overwrite')
.format("com.databricks.spark.csv")
.save('MonthYearSalary'))
(averageYearSalary.write.mode('overwrite')
.format("com.databricks.spark.csv")
.save('YearlySalary')) |
# number = input("Pick a number?")
# for x in range(1,number + 1):
# print number
# number = number - 1
# print "boom!"
x = input("pick a number?")
while x > 0:
print x
x = x - 1
print "boom!"
|
test = int(input())
while test:
val = 0
test -= 1
TS = int(input())
while TS % 2 == 0:
# '//' is a floor division and is used to give the quotient as integer since sometimes......
# it cannot handle large float numbers
TS = TS//2
val = TS//2
print(val) |
x = eval(input('Enter the first no:'))
y = eval(input('Enter the second no:'))
z = x - y
print('The diff is',z)
|
import numpy
import math
from math import *
import os
import sys
os.chdir("C:\\Users\\justi_jtw\\OneDrive\\Documents\\GitHub\\Coding\\Python\\Python Tutorials\\FreeCodeCamp Tutorial\\python")
send = print
say = print
# input("Enter anything to continue ")
# class hello_world:
# print(f"Hello World")
# class drawing_a_shape:
# print(f""" /|\n / |\n / |\n/___|""")
# class variables_and_data_types:
# name = f"John"
# age = 70
# message = f"""There once was a man named {name},\nHe was {age} years old.\nHe really liked the name {name},\nbut didn't like being {age}."""
# print(message)
# class working_with_strings:
# phrase = f"Hello Python"
# print("Hello \nPython")
# print(phrase)
# print(phrase.lower())
# print(phrase.upper())
# """Len returns the number of of characters in a string"""
# print(len(phrase))
# print(phrase[0])
# """For index, caps matter, phrase.index(f"P") and phrase.index(f"p") will give different responces"""
# print(phrase.index(f"P"))
# phrase1 = phrase
# print(phrase1.replace("Python", "JavaScript"))
# class working_with_numbers:
# my_number = 7
# print(my_number)
# my_negative_number = -7
# """abs stands for absolute"""
# print(abs(my_negative_number))
# """pow stands for power"""
# print(pow(2, 3))
# """Max returns the largest number of any amount of numbers"""
# print(max(6, 8, 5))
# """Min returns the smallest number of any amount of numbers"""
# print(min(6, 8, 5))
# """Round rounds a number. NOTE: .5 will wound down"""
# print(round(2.6))
# """Floor will always round a number down"""
# print(floor(2.6))
# """Ceil will always round a number up"""
# print(ceil(6.2))
# """sqrt will give the square root of a number"""
# print(sqrt(36))
# class getting_input:
# """This is for input"""
# # input(f"Enter your name: ")
# """add a variable if you want to store the input"""
# user_name = input(f"Enter your name: ")
# print(f"Hello {user_name}")
# class building_a_basic_calculator:
# num1 = float(input("Enter a number: "))
# num2 = float(input("Enter another number: "))
# result = (num1) + (num2)
# print(result)
# """Alternatively you could do print(num1 + num2)"""
# # print(num1 + num2)
# class mad_libs_game:
# colour = input("Enter a colour: ")
# plural_noun = input("Enter a Plural Noun: ")
# celebrity = input("Enter a celebrity: ")
# print(f"Roses are {colour}")
# print(f"{plural_noun} are blue")
# print(f"I love {celebrity}")
# class lists:
# friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"]
# """ 0 1 2 3 4
# python starts counting at 0 not 1,
# if you use a negative it will start from the end of the list."""
# print(friends[-1])
# """If you add a number:number it will grab everything from in between those 2,
# however it will not include the first number but will include the second.
# example is bellow"""
# print(friends[1:3])
# """you can use list_name[number] = "new variable" to edit a list"""
# friends1 = friends
# friends1[1] = "Mike"
# print(friends1[1])
# class list_functions:
# lucky_numbers = ["7", "77", "5", "1", "2", "3"]
# friends = ["Kevin", "Karen", "Jim", "Jim", "Oscar", "Toby"]
# friends1 = friends
# lucky_numbers1 = lucky_numbers
# """Adds the list, basically joins the list"""
# friends1.extend(lucky_numbers1)
# print(friends1)
# """Adds a new object to the end of the list"""
# friends1.append("Creed")
# """Adds a bew item to the specified location"""
# friends1.insert(1, "Kelly")
# """Removes the specified object"""
# friends1.remove("Jim")
# """Clears the list"""
# friends1.pop()
# """Shows the position of an object"""
# print(friends.index("Kevin"))
# """Shows the number of times and object is in the list"""
# print(friends.count("Jim"))
# """Sorts all the items by alpabetical order"""
# friends1.sort()
# print(friends1)
# """Sorts all the items in ascending order order"""
# lucky_numbers1.sort()
# print(lucky_numbers1)
# """Joins a list together, default is -"""
# friends2 = ", ".join(friends1)
# print(friends2)
# friends1.clear()
# """Removes an object"""
# class tuples:
# """Tuples can't be changed or edited"""
# coordinates = (4, 5)
# coordinates1 = coordinates
# print(coordinates)
# """Some similar stuff too lists"""
# print(coordinates[0])
# print(coordinates1[1])
# """You can have a list of tuples"""
# coordinates2 = [(4, 5), (1, 2)]
# class functions:
# def say_hi(name, age):
# print(f"Hello {name}, you are {age}")
# print("Top")
# """How to run a function"""
# say_hi(name="John", age="20")
# print("Bottom")
# class return_statement:
# def cube(number):
# return number*number*number
# print(cube(3))
# """You could also do:"""
# def cube2(number):
# number = number*number*number
# return number
# number = cube2(4)
# print(number)
# class if_statements:
# is_male = True
# is_tall = True
# if is_male or is_tall:
# """checks if you are tall or a male"""
# print("You are either a male, tall or both!")
# else:
# """only runs if both is_male and is_tall is false"""
# print("Your nither a male nor tall")
# """You can also do:"""
# if is_male and is_tall:
# print(f"You are a tall male.")
# elif is_male and not(is_tall):
# print(f"You are a short male.")
# elif not(is_male) and is_tall:
# print(f"You are not a male but are tall.")
# else:
# print(f"You are not a male and not tall.")
# class if_statements_and_comparisons:
# def max_num(num1, num2, num3):
# # """Checks if num1 is greater than or equal to num 2 and 3"""
# if num1 >= num2 and num1 >= num3:
# return num1
# # """Checks if num2 is greater than or equal to num 1 and 3
# # but only if num1 is not greater than or equal to num 2 and 3"""
# elif num2 >= num1 and num2 >= num3:
# return num2
# # """Returns num3"""
# else:
# return num3
# print(max_num(3, 4, 5))
# """My version, includes a error handler"""
# def max_num_2(num1, num2, num3):
# try:
# # """Checks if num1 is greater than or equal to num 2 and 3"""
# if num1 >= num2 and num1 >= num3:
# return num1
# # """Checks if num2 is greater than or equal to num 1 and 3
# # but only if num1 is not greater than or equal to num 2 and 3"""
# elif num2 >= num1 and num2 >= num3:
# return num2
# # """Returns num3"""
# else:
# return num3
# except Exception():
# print("ERROR!")
# class building_a_better_calculator:
# """Input stuff"""
# num1 = float(input(f"Enter the first number: "))
# opperator = input("Enter a operator: ")
# num2 = float(input(f"Enter the second number: "))
# if opperator == "+":
# print(num1 + num2)
# elif opperator == "-":
# print(num1 - num2)
# elif opperator == "/":
# print(num1 / num2)
# elif opperator == "*":
# print(num1 * num2)
# else:
# print(f"Invalid operator.")
# class Dictionaries:
# month_conversions = {
# 'Jan' or 'jan': 'January',
# 'Feb' or 'feb': 'February',
# 'Mar' or 'mar': 'March',
# 'Apr' or 'apr': 'April',
# 'May' or 'may': 'May',
# 'Jun' or 'jun': 'June',
# 'Jul' or 'jul': 'July',
# 'Aug' or 'aug': 'August',
# 'Sep' or 'Sept' or 'sep' or 'sept': 'September',
# 'Oct' or 'oct': 'October',
# 'Nov' or 'nov': 'November',
# 'Dec' or 'dec': 'December'
# }
# print(month_conversions["Nov"])
# print(month_conversions.get("Dec"))
# print(month_conversions.get("Luv", "Not a valid key"))
# class while_loop:
# i = 1
# """while 1 is less then 10"""
# while i <= 10:
# """ i + 1"""
# i += 1
# print("Done with loop")
# class building_a_guessing_game:
# secret_word = "giraffe"
# guess = ""
# """While guess does not equal secret word"""
# while guess != secret_word:
# guess = input(f"Enter a guess: ")
# print("You win!!")
# """Second bit in the video"""
# secret_word = "giraffe"
# guess = ""
# guess_count = 0
# guess_limit = 3
# out_of_guesses = False
# """While guess does not equal secret word and you are not out of guesses"""
# while guess != secret_word and not(out_of_guesses):
# if guess_count < guess_limit:
# guess = input(f"Enter a guess: ")
# guess_count += 1
# else:
# out_of_guesses = True
# if out_of_guesses:
# print("Out of guesses, YOU LOSE!")
# else:
# print("You win!!")
# class for_loops:
# friends = ["Jim", "Karen", "Kevin"]
# """Letter is a variable"""
# for letter in "Giraffe Academy":
# """Will print the letters in giraffe academy from first to last"""
# print(letter)
# for index in range(10):
# print(index)
# for index in range(3, 10):
# """Prints numbers between 3 and 10"""
# print(index)
# for index in range(len(friends)):
# print(friends[index])
# for index in range(5):
# if index == 0:
# print(f"First Iteration")
# else:
# print(f"Not first")
# class Exponent_Function:
# def raise_to_power(base_num, pow_num):
# result = 1
# for index in range(pow_num):
# result = result * base_num
# return result
# print(raise_to_power(3, 2))
# class two_d_lists_and_nested_loops:
# """A list in a list"""
# number_grid = [
# [1, 2, 3],
# [4, 5, 6],
# [7, 8, 9],
# [0]
# ]
# """Prints the first number from the first list"""
# print(number_grid[0][0])
# for row in number_grid:
# print(row)
# for row in number_grid:
# for col in row:
# print(col)
# class Build_a_Translator:
# def translate(phrase):
# translation = ""
# for letter in phrase:
# if letter.lower() in "aeiou":
# if letter.isupper():
# translation = translation + "g"
# else:
# translation = translation + "g"
# else:
# translation = translation + letter
# return translation
# print(translate(input("Enter a phrase: ")))
# class Comments:
# # This program is cool
# # THis prints out a string
# """
# This is a multi line comment
# """
# '''
# THis also is a multi line comment
# '''
# print("Comments are fun")
# # print("Comments are fun")
# class Try_and_Except:
# """Basically trying to do:
# number = int(input(f"Enter a number: "))
# print(number)"""
# try:
# number = int(input(f"Enter a number: "))
# print(number)
# except:
# """I an error happenes"""
# print("Invalid input")
# try:
# answer = 10/0
# number = int(input(f"Enter a number: "))
# print(number)
# except ZeroDivisionError as err:
# print(err)
# except ValueError:
# print("Invalid input")
# """
# TIP:
# Don't use
# except:
# instead use
# use except Exception:
# I don't want to write too much but if you want to know more you can
# search it up.
# """
# class Reading_Files:
# """
# This will open up the text document called employees.txt
# if you can't see the .txt don't worry you just don't have the settings
# enabled to view the file type.
# """
# """r means read, w means write, a means append,
# r+ means read and write"""
# employee_file = open("employees.txt", "r")
# """Will print if it is readable"""
# print(employee_file.readable())
# """
# Will print the items in the file by line
# this will print the first line.
# """
# print(employee_file.readline())
# """This will print the second"""
# print(employee_file.readline())
# """This the third"""
# print(employee_file.readline())
# """
# This will put the items in a list by line,
# so the first line will be the first item in the list
# the second line the second, and so on
# """
# print(employee_file.readlines())
# for employee in employee_file.readlines():
# print(employee)
# employee_file.close()
# class Writing_to_Files:
# """the a is for appending"""
# employee_file = open("employees.txt", "a")
# employee_file.write("Toby - Human Resources")
# """Adding a new line for when we append something"""
# employee_file.write("\nKelly - Customer Service")
# employee_file.close()
# class Modules_and_pip:
# import useful_tools
# print(useful_tools.roll_dice(10))
# """Run pip install python-docx in the command prompt"""
# import docx
# """You can use functions just like the ones in
# useful_tools"""
# # docx.
# class Classes_and_Objects:
# from Student import Student
# student1 = Student("Jim", "Business", 3.1, False)
# student2 = Student("Pam", "Art", 2.5, True)
# class Building_a_Multiple_Choice_Quiz:
# from Question import Question
# question_prompts = [
# "What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n",
# "What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n",
# "What color are strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n"
# ]
# questions = [
# Question(question_prompts[0], "a"),
# Question(question_prompts[1], "c"),
# Question(question_prompts[2], "b")
# ]
# def run_test(questions):
# score = 0
# for question in questions:
# answer = input(question.prompt)
# if answer == question.answer:
# score += 1
# print(f"You got {score}/{len(questions)} Correct!")
# run_test(questions)
# class Object_Functions:
# from Student import Student
# student1 = Student("Oscar", "Accounting", 3.1)
# student2 = Student("Phyllis", "Business", 3.8)
# print(student2.on_honor_roll())
class Inheritance:
from Chef import Chef
myChef = Chef()
myChef.make_special_dish()
from ChineseChef import ChineseChef
myChineseChef = ChineseChef()
myChineseChef.make_special_dish()
myChineseChef.make_chicken()
class Python_Interpreter:
"""
You will need to watch the video for this bit:
https://youtu.be/rfscVS0vtbw?t=15643
"""
|
import random
import csv
from cryptography.fernet import Fernet
##PY3
#name = input("Name: ")
#password = input("password: ")
#def Create():
# email = input("e-mail: ")
# password = input("password: ")
# return(email, passowrd)
class Account():
def __init__(self, login, email = None, password = None): ######ADD BALANCE OVERDRAFT< TYPE
#self.balance = balance
#self.overdraft = False
#self.type = False
self.email = email
self.password = password
self.accountNumber = random.randint(100000,999999)
self.login = False
def openAccount(self):
self.email = input("Email: ")
self.password = input("Password: ")
def isLogin(self):
with open('accounts.csv', mode='r', newline = '') as accounts_file:
line = accounts_file.readlines()
line = [line.rstrip('\n') for line in open('accounts_file')]
print(line)
print("LOGIN TO YOUR ACCOUNT")
promptEmail = input("Email: ")
promptPassword = input("Password: ")
if promptEmail == self.email:
if promptPassword == self.password:
print("YOUIN")
self.login = True
else:
print("Wrong username or password")
self.isLogin()
else:
print("Wrong username or password")
self.isLogin()
#Removed all to do with balance, overdraft
'''
def isOverdraft(self, bool):
self.type = bool
'''
'''
def displayBalance(self):
if self.login == True:
print("Account balance: " +str(self.balance))
else:
self.isLogin()
def displayNewBalance(self):
print("New account balance: " +str(self.balance))
def deposit(self, amount):
if self.login == True:
#print(amount)
self.balance += amount
self.displayNewBalance()
if self.overdraft == True:
if self.balance >= 0:
self.overdraft = False
else:
self.isLogin()
def withdraw(self, amount):
print(amount)
#self.balance -= amount
#self.displayNewBalance()
if self.balance < amount:
print("Warning")
if self.type == True:
self.balance -= amount
self.displayNewBalance()
self.overdraft = True
else:
print("Not an overdraft account")
else:
self.balance -= amount
self.displayBalance()
def overdraftAction(self):
if self.type == True:
print("")
else:
print("No")
return
'''
#######ADD 0, False, False
#Create instance of class asap
account = Account(False, 'email', 'password')
#Write the name row of the csv file
with open('accounts.csv', mode='w', newline = '') as accounts_file:
writer = csv.writer(accounts_file)
writer.writerow(['Email', 'Password', 'Balance'])
#setup up encryption key
key = Fernet.generate_key()
f = Fernet(key)
#All the UI in the main
def main():
print("What do you want to do?"
"\n 1. To open account"
"\n 2. To Log into account"
"\n 3. To Delete Account")
userInput = int(input())
if userInput == 1:
account.openAccount()
password = account.password.encode()
encrypted = f.encrypt(password)
with open('accounts.csv', mode='a', newline = '') as accounts_file:
writer = csv.writer(accounts_file)#, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow([account.email, encrypted])
main()
if userInput == 2:
account.isLogin()
if userInput == 3:
Print("Dell")
#Create()
#account = Account(0, False, False, False, 'email', 'password')
#print(account.balance)
#account.openAccount()
#account.isLogin()
#normAccound = Account(200, False, False)
#normAccound.isOverdraft(True)
#account.displayBalance()
#normAccound.withdraw(400)
#normAccound.displayBalance()
#account.deposit(400)
#normAccound.displayBalance()
if __name__ == '__main__':
main()
|
from itertools import (
accumulate,
chain,
repeat,
tee,
)
from typing import List
class ListUtils(object):
"""
List Utils
"""
@classmethod
def flatten(cls, value: List) -> List:
"""
Flatten a list recursively
"""
if value is None:
return
res = []
for k in chain(value):
if isinstance(k, list):
res.extend(cls.flatten(k))
else:
res.append(k)
return res
@classmethod
def chunk(cls, value: List, size: int):
"""
Break a list apart into chunks
"""
xs = value
n = size
assert n > 0
L = len(xs)
s, r = divmod(L, n)
widths = chain(repeat(s + 1, r), repeat(s, n - r))
offsets = accumulate(chain((0, ), widths))
b, e = tee(offsets)
next(e)
return [xs[s] for s in map(slice, b, e)]
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
"""
# M = L[i(1+i)n] / [(1+i)n-1]
# M = monthly payment
# L = Loan amount
# i = interest rate (for an interest rate of 5%, i = 0.05)
# n = number of payments
M =L =I = N = loanduration = 0
L = input('How much loan you want?\n')
I = input('Interest rate on the loan?\n')
loanduration = input('In How much Time return back the loan?\n')
#Convert the strings into floating numbers so we can use them in the formula
loanduration = float(loanduration)
L = float(L)
I = float(I)
#Since payments are once per month, number of payments is number of years for the loan
N = loanduration*12
#calculate the monthly payment based on the formula
M = L * I * (1+ I) * N / ((1 + I) * N -1)
|
"""
Shutterflly challenge to Calculate Life time value of given customers to predict his future purchase power index
In this part of code we are generating Fake date to build our model to Calculate Life Time Value of Customer
Author: Rajesh Jaiswal
Dated: 10th June 2017
"""
import random
import string
from datetime import datetime
from faker import Faker
# We are using Faker Package to generate dummy data for all data structures.
# Faker packaged replaced old dummy data creation package Factory
# This function will create Fake timestamp for a given purchase entry in(YY:MM:DD Hh:MM:SS) format
def date_gen(date_one):
return date_one.strftime("%Y-%m-%d %H:%M:%S")
# This Function will generate random Cutomer ID for purchase entry
def customer_id_gen(n):
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in xrange(n))
# This Function will generate data as per the sample given in challenge n customers
def data_genaration(n_customers, n_events, filepath):
fake = Faker()
iteration_one = True
list_all_event = ['CUSTOMER', 'SITE_VISIT', 'IMAGE', 'ORDER']
with open(filepath, 'w') as f:
# this for loop will create one customer entry
for _ in xrange(n_customers):
cutomerid = customer_id_gen(12)
n_cutomer_date = fake.date_time_this_decade()
custmer_entry = { 'type': 'CUSTOMER', 'verb': 'NEW', 'key': cutomerid, 'last_name': fake.last_name(),
'event_time': date_gen(n_cutomer_date), 'adr_city': fake.city(), 'adr_state': fake.state()}
# Write customer entry into data set
if iteration_one:
f.write('[' + str(custmer_entry))
iteration_one = False
else:
f.write(',\n' + str(custmer_entry))
print "Customer entry #{}:\n{}".format(_, custmer_entry)
# Create events
for i in xrange(random.randint(0,n_events)):
event_timestamp = fake.date_time_this_decade()
type_of_event = list_all_event[random.randint(0, len(list_all_event)-1)]
# create site visit data for given event
if type_of_event == 'SITE_VISIT':
event = { 'type': type_of_event, 'verb': 'NEW', 'key': customer_id_gen(12),
'event_time': date_gen(event_timestamp), 'customer_id': cutomerid }
# create image fake data of a given event
elif type_of_event == 'IMAGE':
event = { 'type': type_of_event, 'verb': 'UPLOAD', 'key': customer_id_gen(12),
'event_time': date_gen(event_timestamp), 'customer_id': cutomerid }
# create order fake data of given event
elif type_of_event == 'ORDER':
order_id = customer_id_gen(8)
event = { 'type': type_of_event, 'verb': 'NEW', 'key': order_id,
'event_time': date_gen(event_timestamp), 'customer_id': cutomerid,
'total_amount': "{:.2f} USD".format(random.uniform(4, 500))}
f.write(',\n' + str(event))
print "\tEvent #{}:\n\t{}".format(i, event)
# Randomly updated_order orders 0-2 times
for updated_order in xrange(random.randint(0, 2)):
event = {'type':type_of_event, 'verb':'UPDATE', 'key':order_id, 'customer_id':cutomerid,
'event_time': date_gen(fake.date_time_between_dates(event_timestamp, datetime.now())),
'total_amount':"{:.2f} USD".format(random.uniform(4, 500))}
f.write(',\n' + str(event))
print "\t > Update #{}:\n\t {}".format(updated_order, event)
elif type_of_event == 'CUSTOMER':
event = { 'type': type_of_event, 'verb': 'UPDATE', 'key': cutomerid, 'adr_state': fake.state(),
'event_time': date_gen(fake.date_time_between_dates(n_cutomer_date, datetime.now()))}
print "\tEvent #{}:\n\t{}".format(i, event)
if type_of_event != 'ORDER':
f.write(',\n' + str(event))
f.write(']')
print "\n-------------Cutomer Purchase Entries--------------".format(n_customers, filepath)
# main function to load a program step by step
if __name__ == '__main__':
# this number will decide number of entries in input dataset
newCustomersCount = 1000
# Random parameter to pick entry
maxRandomEvent = 15
# To store generated fake data to use in main program
inputData = "../input/input.txt"
# data_genaration function to write data in input text file
data_genaration(newCustomersCount, maxRandomEvent, inputData) |
nome="raul"
anos=8
print(nome+str(anos))
nome="raul"
anos=8
print(nome+" "+str(anos)+"!")
nome1="raul varela"
print(nome1)
print(nome1.upper())
print(nome1.lower())
print(nome1.title())
print("raul\n varela")
print("raul\tvarela")
print("\\novo")
|
# Napisz program do sprawdzania czy liczba jest podzielna przez 3 lub 5 lub 7
num = float(input("Podaj liczbę: "))
if num % 3 == 0 or num % 5 == 0 or num % 7 == 0:
print("Ta liczba jest podzielna przez 3, 5 lub 7")
else:
print("Ta liczba nie jest podzielna ani przez 3, ani przez 5, ani przez 7") |
import Excercises.Moduly.games as games
from random import randint
def rand():
wybor = randint(1, 15)
wybor = str(wybor)
print(f"Wylosowano numer {wybor}")
programy[wybor]['call']()
def leave():
print("Do zobaczenia!")
exit()
def menu(programy):
print('MultiTOOL\nMenu:')
for key, program in programy.items():
print(f'{key} - {program["nazwa"]}')
return input('Który program uruchomić? ').upper()
programy = {
"1" : {'nazwa': "Przeliczanie temperatury C -> F", 'call' : games.cel_to_fahr},
"2" : {'nazwa': "Przeliczanie temperatury F -> C", 'call' : games.fahr_to_cel},
"3" : {'nazwa': "Obliczanie pola koła", 'call' : games.disk_area},
"4" : {'nazwa': "Podawanie pierwszej i ostatniej cyfry", 'call' : games.first_and_last},
"5" : {'nazwa': "Rysowanie prostokąta", 'call' : games.draw_rectangle},
"6" : {'nazwa': "Zamiana liczby binarnej na dziesiętną", 'call' : games.binary_to_decimal},
"7" : {'nazwa': "Sprawdzenie czy liczba jest parzysta", 'call' : games.is_even},
"8" : {'nazwa': "Sprawdzenie czy liczba jest podzielna przez 3, 5 lub 7", 'call' : games.is_divisible_or},
"9" : {'nazwa': "Sprawdzenie czy liczba jest podzielna przez 3, 5 i 7", 'call' : games.is_divisible_and},
"10" : {'nazwa': "Sprawdzenie czy rok jest przestępny", 'call' : games.leap_year},
"11" : {'nazwa': "Rysowanie tabeli", 'call' : games.table_game},
"12" : {'nazwa': "Rozmienianie kwoty na monety", 'call' : games.coins_game},
"13" : {'nazwa': "Rysowanie piramidy", 'call' : games.pyramid_draw},
"14" : {'nazwa': "Obliczanie wieku psa", 'call' : games.dog_game},
"R" : {'nazwa': "Zaskocz mnie!", 'call' : rand},
"X" : {'nazwa': "Wyjście z programu", 'call' : leave},
# "S" : {'nazwa': "Statystyka", 'call' : games.counter}
}
wybor = None
while wybor != 'X':
wybor = menu(programy)
try:
print('=' * 20)
programy[wybor]['call']()
print('=' * 20)
except KeyError:
print('Taki program nie isnieje') |
# Program przyjmuje kwotę w parametrze i wylicza jak rozmienić to na monety: 5, 2, 1, 0.5, 0.2, 0.1 wydając ich jak najmniej.
def coins_change():
money = (float(input("Podaj kwotę, którą chcesz rozmienić: "))) * 100
div_list = (500, 200, 100, 50, 20, 10, 5, 2, 1)
while money >= 1:
for i in div_list:
num = int(money / i)
print(f"{num} monet {i / 100} zł.")
money = money - num * i
while True:
try:
coins_change()
break
except ValueError:
print("Nieprawidłowe dane, zacznij jeszcze raz.")
|
import csv
class Item():
"""
"""
def __init__(self, id, name, price, amount, created_at, last_buy_at, pic):
self.id = id
self.name = name
self.price = price
self.amount = amount
self.created_at = created_at
self.last_buy_at = last_buy_at
self.pic = pic
def __str__(self):
template = """
Id: {0}
Name: {1}
Price: {2}
"""
return template.format(self.id, self.name, self.price)
class Book(Item):
"""
"""
vat = 0.05
def __init__(self, id, name, price, amount, created_at, last_buy_at, author, number_of_pages, pic, format = "Książka"):
super().__init__(id, name, price, amount, created_at, last_buy_at, pic)
self.author = author
self.number_of_pages = number_of_pages
self.net_price = price - price * Book.vat
self.format = format
def __str__(self):
details = super().__str__()
template = """
{0}
Author: {1}
Pages: {2}
"""
return template.format(details, self.author, self.number_of_pages)
def __getitem__(self, key):
# print("Inside `__getitem__` method!")
return getattr(self, key)
class Ebook(Book):
def __init__(self, id, name, price, amount, created_at, last_buy_at, author, number_of_pages, format, pic):
super().__init__(id, name, price, amount, created_at, last_buy_at, author, number_of_pages, pic)
self.format = format
self.net_price = price - price * Book.vat
def __str__(self):
details = super().__str__()
template = """
{0}
Format: {1}
"""
return template.format(details, self.format)
class Db():
def __init__(self, csv_file):
"""
read from file
create book/ebook objects
add to items as a dict of objects {id:item, id:item}
"""
self.database = []
with open(csv_file, "r+", encoding="utf-8", newline="") as file:
reader = csv.DictReader(file)
counter = 1
for row in reader:
if row["Typ"] == "Book":
object = Book(id=row["ID"], name=row["Nazwa"], price=20, amount=row["Ilość"],
created_at=row["Data dodania"], last_buy_at=row["Data ostatniego zakupu"],
author=row["Autor"], number_of_pages=row["Ilość stron"], pic=row['Link do miniaturki'])
self.database.append(object)
counter += 1
elif row["Typ"] == "Ebook":
object = Ebook(id=row["ID"], name=row["Nazwa"], price=20, amount=row["Ilość"],
created_at=row["Data dodania"], last_buy_at=row["Data ostatniego zakupu"],
author=row["Autor"], number_of_pages=row["Ilość stron"],
pic=row['Link do miniaturki'],
format=row["Format"])
self.database.append(object)
counter += 1
def addItem(self, object, file):
"""
Function to add item in DB
:param Book/Ebook object - object of book/ebook?
"""
counter = len(self.database) + 1
self.database.append(object)
with open (file, "a+", newline="") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(object)
return "Dodano do bazy"
def getItems(self):
"""
Function to get all items from db. Display a list of products
"""
for object in self.database:
print(object)
def removeItem(self, object):
"""
Function to get remove item from DB
:param int id - id of book?
"""
if object in self.database:
self.database.remove(object)
return "Usunięto z bazy."
else:
return "Nie znaleziono w bazie."
def updateItem(self, object):
"""
Function to updete item in DB
:param Book/Ebook object - object of book/ebook?
"""
pass
def __len__(self):
return len(self.database)
class Cart():
def __init__(self):
self.elements = []
self.elements_number = 0
self.net = 0
self.gross = 0
def dodaj(self, element):
self.elements.append(element)
self.elements_number += 1
# self.net += element.net_price
# self.gross += element.price()
def __len__(self):
return len(self.elements)
def __str__(self):
template = """
"""
def net_worth(self):
return self.net
def gross_worth(self):
return self.gross |
def is_num(num):
try:
num = float(num)
return True
except:
return False
print(is_num(5.6)) |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if not head:
return None
slow = head
fast = head
while slow.next and fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
node = slow
start = head
while start is not node:
start = start.next
node = node.next
return node
if (not slow.next) or (not fast.next) or (not fast.next.next):
return None |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
return self.dfs(root, sum, 0)
def dfs(self, root, sum, cursum):
if not root:
return False
if (not root.left) and (not root.right):
return cursum + root.val == sum
return self.dfs(root.left, sum, cursum + root.val) or self.dfs(root.right, sum, cursum + root.val)
|
import random
door =9
livesLeft=3
x=300
def intro ():
print("Welcome to the game Andrew, Gloria or housecats.")
print("U, the great Elizabeth Li is infront of 9 great doors.")
print("Behind one of the doors is Gloria Zhu.")
print("After marrying Gloria each time, you will lose a life.")
print("Behind another door is Andrew Chen")
print("After marrying Andrew each time, you will earn a life.")
print("There are housecats behind all other doors.")
print("YOu have three lives.")
print("If there is a person behind the door You will marry he/she")
print("Which door #1-9 will you chose?")
def gloria ():
print("Gloria is behind the door!")
print("CONGRADULATIONS!!!U just married Gloria!")
print("You have " + str(livesLeft) + " lives left")
def housecat():
print("There is a housecat behind the door!")
print("Nothing Happens!")
def andrew ():
print("Andrew is behind the door.")
print("CONGRADULATIONS!!!!!!U just married Andrew.")
print("You have " + str(livesLeft) + " livesleft")
def end_the_game():
print("Oh no!You are dead.")
print("Fin.")
def try_again():
print("Try Again.")
return int(input())
intro()
while livesLeft!=0:
g=random.randint(1,door)
a=random.randint(1,door)
while g==a:
a=random.randint(1,door)
x=int(input())
while x!=g and x!=a:
housecat()
x=try_again()
if x==g:
livesLeft=livesLeft-1
gloria()
if x==a:
livesLeft=livesLeft+1
andrew()
end_the_game()
|
import cryptography
from cryptography.fernet import Fernet
k = Fernet.generate_key()
f = open('key.txt' , 'wb' )
f.write(k)
f.close()
def enc():
datafile = open('data.txt', 'rb')
data = datafile.read()
u = Fernet(k)
x = u.encrypt(data)
cipher = open('encdata.txt' , 'wb')
cipher.write(x)
datafile.close()
cipher.close()
def dec():
cipherfile = open('encdata.txt', 'rb')
cipher = cipherfile.read()
u = Fernet(k)
x = u.decrypt(cipher)
data = open('decdata.txt' , 'wb')
data.write(x)
cipherfile.close()
data.close()
def insert():
print('Type Your Data in the data.txt File ')
print('Answar Y for Yes')
s= 0
while s<1:
x = input('- Done ? : ')
if x == "Y" or x == 'y':
enc()
s=2
i = 0
while i < 1:
print('Do You Want To :')
print(' 1. Encrypt File')
print(' 2. Decrypt File')
print(' 3. Close The Program')
choice = input('- ')
if choice == '1':
insert()
elif choice == '2':
dec()
print('Your data is at file decdata.txt')
elif choice == '1':
print('Thank You & come back soon ')
i = 2
|
# python3
# Description: edX UCSanDiegoX: ALGS201x PA#1
# Problem 2: Tree Height
# given: #of nodes and parents index
# compute tree height, using recursion
#
# For submission 10,
# computeHeight - starting from root and looking at kids at each level
# (instead of going through leaves)
#
# main datastruct numpy array - looking up kids by sending np.array of parents
# relying on np.in1d
#
# results
# Failed case #18/24: time limit exceeded (locally 14 seconds)
# Time used: 6.10/3.00, memory used: 37318656/536870912.
import sys, threading
import time #to track time
import numpy as np
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Tree:
def read(self):
# given:
self.n = int(sys.stdin.readline())
self.parent = np.array(sys.stdin.readline().split(),int)
# hardcoded examples
# ex1
#self.n = 5 # int(sys.stdin.readline())
#temp = '4 -1 4 1 1' # [-1, 0, 4, 0, 3] #
# ex2
#self.n = 10
#temp = '8 8 5 6 7 3 1 6 -1 5'
#self.parent = np.array(temp.split(), int)
#get root
self.root = np.where(self.parent==-1)[0]
# self.idx = np.arange(self.n)
# find leaves
#self.leaves = np.setdiff1d(self.idx, self.parent)
#self.parents = np.arange(self.leaves.size)
# my recursive function - start from root, look for kids until no kids
height = 0
done = 0
def compute_height(self, nodes):
while not self.done:
#print (nodes)
self.height += 1
# find kids
kids = np.nonzero(np.in1d(self.parent, nodes))[0]
#print('kids ', kids_)
# look for nodes that found kids
if kids.size > 0:
# this level still has nodes to process
self.compute_height(kids)
else:
self.done = 1
# # my recursive function1 - only look at leaves
# def compute_height1(self):
# maxHeight = 0
#
# for vertex in self.leaves:
# height = 0
# i = vertex
# while i != -1:
# height += 1
# i = self.parent[i]
# maxHeight = max(maxHeight, height);
# return maxHeight;
#
# #original recursive function
# def compute_height0(self):
# # Replace this code with a faster implementation
# maxHeight = 0
#
# for vertex in range(self.n):
# height = 0
# i = vertex
# while i != -1:
# height += 1
# i = self.parent[i]
# maxHeight = max(maxHeight, height);
# return maxHeight;
def main():
# track time
start_time = time.time()
myTree = Tree()
myTree.read()
# compute tree height
myTree.compute_height(myTree.root)
print(myTree.height)
# track time
elapsed_time = time.time() - start_time
print('done in ', elapsed_time)
threading.Thread(target=main).start()
# initialize to store levels, starting with leaves and finding parents
# list_levels = []
# def compute_levels(self):
# parents = self.parent[self.leaves]
# # look for nodes that found root
# done_idx = np.where(self.parents < 0)[0]
# # replace that node with value of root node so that code won't choke
# self.parents[done_idx] = self.root
# self.list_levels.append(parents)
#
# #check if all leaves found root
# if not done_idx.size == self.leaves.size:
# #ac stopped here
# print (self.list_levels) |
#Autor: Juan Sebastián Lozano Derbez
#Se calcula el cosato total de la compra de unos asientos
def calcboletosa(cantidada, cantidadb, cantidadc): #Se calcula el total de todos los asientos
total = 925*(cantidada) + 775*(cantidadb) + 360*(cantidadc)
return total
#Se reciben las entradas y se imprime el resultado
def main():
cantidada = int(input("Cuántos boletos A?: "))
cantidadb = int(input("Cuántos boletos B?: "))
cantidadc = int(input("Cuántos boletos C?: "))
total = calcboletosa(cantidada, cantidadb, cantidadc)
print("Total: ", total)
main() |
import os # This module use for create and delete the file in location
import pickle # This module use for getting the user data dump to another file and again getting the same data and secure purpose
import pathlib #This module use for create file path and take the file path
class Bank_system():
def CreateAccount(self):
try:
self.Acct_NO = int(input("Enter the Acct Number:"))
self.Holder_Name = input("Enter the customer Name:")
self.date_of_Birth = input("Enter the Birth Date(dd/mm/yyyy):")
self.Address = input("Enter the Address:")
self.Phone_Number = int(input("Enter the Phone Number:"))
self.type = input("Ente the type of account [C/S] : ")
self.Deposit_Amt = int(input("Enter the amount of doposit:"))
print("Account Created")
except ValueError:
print("Invalid value,Please check")
def Account(self):
try:
obj = Bank_system()
obj.CreateAccount()
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
oldlist = pickle.load(infile)
oldlist.append(obj)
infile.close()
os.remove('accounts.data')
else:
oldlist = [obj]
outfile = open('newaccounts.data', 'wb')
pickle.dump(oldlist, outfile)
outfile.close()
os.rename('newaccounts.data', 'accounts.data')
except FileNotFoundError:
print("File has no records")
def ViewAll(self):
try:
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
mylist = pickle.load(infile)
for item in mylist:
print(item.Acct_NO,'//', item.Holder_Name,'//', item.date_of_Birth,'//', item.Address,'//',item.Phone_Number,'//',item.type ,'//',item.Deposit_Amt)
infile.close()
else:
print("No records to display")
except FileNotFoundError:
print("File Doesn't exist ")
def search(self):
try:
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
mylist = pickle.load(infile)
infile.close()
found = False
NO = int(input("\tEnter The account No. : "))
for item in mylist:
if item.Acct_NO == NO:
print("Holder Name is :",item.Holder_Name)
print("Holder birth Dats is:",item.date_of_Birth)
print("Address detail:",item.Address)
print("Account type is :",item.type)
print("Phone Number is :",item.Phone_Number)
print("Your account Balance is = ", item.Deposit_Amt)
found = True
else:
print("No records to Search")
if not found:
print("No existing record with this number")
except FileNotFoundError:
print("No records to Search")
except ValueError or UnboundLocalError:
print("Invalid value entered, Please Check")
def BalanceDeposit(self):
try:
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
mylist = pickle.load(infile)
infile.close()
os.remove('accounts.data')
NO = int(input("\tEnter The account No. : "))
for item in mylist:
if item.Acct_NO == NO:
amount = int(input("Enter the amount to deposit : "))
item.Deposit_Amt += amount
print("Deposit Completed")
print("your current balance is>>>>",item.Deposit_Amt)
else:
print("No records to Search")
outfile = open('newaccounts.data', 'wb')
pickle.dump(mylist, outfile)
outfile.close()
os.rename('newaccounts.data', 'accounts.data')
except ValueError:
print("invalid value entered,Please check it")
except FileNotFoundError:
print("File Not Found")
def BalanceWithdraw(self):
try:
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
mylist = pickle.load(infile)
infile.close()
os.remove('accounts.data')
NO = int(input("\tEnter The account No. : "))
for item in mylist:
if item.Acct_NO == NO:
amount = int(input("Enter the amount to withdraw : "))
if amount <= item.Deposit_Amt:
item.Deposit_Amt -= amount
print("Withdraw completed")
print("Your current balance is >>>",item.Deposit_Amt)
else:
print("You cannot withdraw larger amount")
else:
print("No records to Search")
outfile = open('newaccounts.data', 'wb')
pickle.dump(mylist, outfile)
outfile.close()
os.rename('newaccounts.data', 'accounts.data')
except ValueError:
print("invalid value entered,Please check it")
except FileNotFoundError:
print("File Not Found")
def deleteAccount(self):
try:
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
oldlist = pickle.load(infile)
infile.close()
newlist = []
NO = int(input("\tEnter The account No. : "))
for item in oldlist:
if item.Acct_NO != NO:
newlist.append(item)
print("Account Removed")
os.remove('accounts.data')
outfile = open('newaccounts.data', 'wb')
pickle.dump(newlist, outfile)
outfile.close()
os.rename('newaccounts.data', 'accounts.data')
print("Account Deleted")
except FileNotFoundError:
print("File Not Found")
####-----update the user acctount-------#######
def modifyAccount(Self):
try:
file = pathlib.Path("accounts.data")
if file.exists():
infile = open('accounts.data', 'rb')
oldlist = pickle.load(infile)
infile.close()
os.remove('accounts.data')
NO = int(input("\tEnter The account No. : "))
for item in oldlist:
if item.Acct_NO == NO:
item.Holder_Name = item.Holder_Name
item.date_of_Birth = item.date_of_Birth
item.Address = input("Enter the Address Detail: ")
item.Phone_Number = int(input("Enter the Phone Number : "))
item.type = input("Ente the type of account [C/S] : ")
item.Deposit_Amt = item.Deposit_Amt
print("Your Account updated")
outfile = open('newaccounts.data', 'wb')
pickle.dump(oldlist, outfile)
outfile.close()
os.rename('newaccounts.data', 'accounts.data')
except ValueError:
print("invalid value entered,Please check it")
except FileNotFoundError:
print("File Not Found")
###--------this statement calling the whole class---------####
obj = Bank_system() # create the instance class
####___________This intro section of project-----------######
ch = ''
num = 0
#intro()
while ch != 8:
# system("cls");
print("\t\t\t\t\t\t\t\t\************WELCOME TO MY BANK**************\t\t\t\t\t\t\t\t\t")
print("HOW CAN I HELP YOU")
print("\tMAIN MENU")
print("\t1. NEW ACCOUNT")
print("\t2. BALANCE DEPPOSIT ")
print("\t3. BALANCE WITHDRAW ")
print("\t4. ACCOUNT SEARCH")
print("\t5. ALL ACCOUNT HOLDER LIST")
print("\t6. DELETE ACCOUNT")
print("\t7. MODIFY AN ACCOUNT")
print("\t8. Exit")
print("\tSelect Your Option (1-8) ")
ch = input("Enter your choice : ")
if ch == '1':
obj.Account()
elif ch == '2':
obj.BalanceDeposit()
elif ch == '3':
obj.BalanceWithdraw()
elif ch == '4':
obj.search()
elif ch == '5':
obj.ViewAll()
elif ch == '6':
obj.deleteAccount()
elif ch == '7':
obj.modifyAccount()
elif ch == '8':
print("\tThanks for using bank managemnt system")
break
else:
print("Invalid choice,Please check your value")
|
# a piece of text with leading spaces
def useless_function():
a = 123
ab =927
abc = 215
if abc <= 500:
abcd = ab + abc
abcd += a
if abcd == abc:
abcd = 0
|
array=[11,5,8,9,7]
def selectionsort(array):
n = len(array)
for i in range(n):
for j in range(0,n-i-1):
if array[j]>array[j+1]:
array[j], array[j+1]=array[j+1],array[j]
print(array)
return array
print(selectionsort(array))
|
import numpy as np
class NN:
"""
Arguments:
data: data
labels: labels
layers: List (of lists) of net layer sizes and activation functions, e.g.
[[8,"relu"],
[5,"relu"],
[3,"relu"],
[2, "sigmoid"]]
Currently supported functions: "relu", "tanh", "sigmoid"
Notes:
- Need to pass data or array-like of similar shape on initialization for creation of first layer
- Currently only works with sigmoid activation in the last layer due to
the cost function partial derivative
learning_rate: learning rate
Uses heuristic initialization similar to Xavier (initial weights multiplied by np.sqrt(2/layer_sizes[i-1]))
Uses cross-entropy cost
"""
def __init__(self,
layers,
data,
labels,
learning_rate):
self.layers = layers
self.data = data
self.labels = labels
self.learning_rate = learning_rate
self.params = self.init_params()
def sigmoid(self, Z):
#Also returns original to help with backprop
return 1/(1+np.exp(-Z)), Z
def d_sigmoid(self, dA, cache):
s, _ = self.sigmoid(cache)
dZ = dA * s * (1-s)
assert (dZ.shape == cache.shape)
return dZ
def relu(self, Z):
#Also returns original to help with backprop
return Z.clip(min=0), Z
def d_relu(self, dA, cache):
dZ = np.array(dA, copy=True)
dZ[cache <= 0] = 0
assert (dZ.shape == cache.shape)
return dZ
def tanh(self, Z):
#Also returns original to help with backprop
A, _ = (self.sigmoid(Z * 2) * 2) - 1
return A, Z
def d_tanh(self, dA, cache):
t, _ = self.tanh(cache)
dZ = dA * (1 - t**2)
assert (dZ.shape == cache.shape)
return dZ
def init_params(self):
layer_sizes = [item[0] for item in self.layers]
layer_sizes.insert(0, self.data.shape[0])
params = {}
for l in range(1,len(layer_sizes)):
params['W' + str(l)] = np.random.randn(layer_sizes[l], layer_sizes[l-1]) * np.sqrt(2/self.data.shape[1])
params['b' + str(l)] = np.zeros((layer_sizes[l], 1))
return params
def forward_linear_step(self, A, W, b):
Z = np.dot(W, A) + b
return Z, (A, W, b)
def forward_activation_step(self, A_prev, W, b, function):
Z, lin_cache = self.forward_linear_step(A_prev, W, b)
assert (function in ["relu", "sigmoid", "tanh"])
A, act_cache = getattr(self, function)(Z)
return A, (lin_cache, act_cache)
def model_forward(self, X):
caches = []
A = X
funcs = [item[1] for item in self.layers]
L = len(self.params) // 2
assert (len(funcs) == L)
for l in range(L):
A_prev = A
A, cache = self.forward_activation_step(A_prev, self.params['W' + str(l+1)], self.params['b' + str(l+1)], funcs[l])
caches.append(cache)
return A, caches
def cross_entropy_cost(self, AL, Y):
cost = -np.mean(Y*np.log(AL) + (1-Y)*np.log(1-AL))
cost = np.squeeze(cost)
assert (cost.shape == ())
return cost
def backward_linear_step(self, dZ, cache):
A_prev, W, b = cache
m = A_prev.shape[1]
dW = (1/m) * np.dot(dZ, A_prev.T)
db = (1/m) * np.sum(dZ, axis=1, keepdims=True)
dA_prev = np.dot(W.T, dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
def backward_activation_step(self, dA, cache, function):
lin_cache, act_cache = cache
assert (function in ["relu", "sigmoid", "tanh"])
function = str("d_" + function)
dZ = getattr(self, function)(dA, act_cache)
dA_prev, dW, db = self.backward_linear_step(dZ, lin_cache)
return dA_prev, dW, db
def model_backward(self, AL, Y, caches):
grads = {}
L = len(caches)
m = AL.shape[1]
Y = Y.reshape(AL.shape)
grads["dA" + str(L)] = -(np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
funcs = [item[1] for item in self.layers]
assert (len(funcs) == L)
for l in reversed(range(L)):
current_cache = caches[l]
dA_prev_temp, dW_temp, db_temp = self.backward_activation_step(grads["dA" + str(l+1)], current_cache, funcs[l])
grads["dA" + str(l)] = dA_prev_temp
grads["dW" + str(l + 1)] = dW_temp
grads["db" + str(l + 1)] = db_temp
return grads
def gradient_descent_update(self, grads):
L = len(self.params) // 2
for l in range(L):
self.params["W" + str(l+1)] = self.params["W" + str(l+1)] - grads["dW" + str(l+1)] * self.learning_rate
self.params["b" + str(l+1)] = self.params["b" + str(l+1)] - grads["db" + str(l+1)] * self.learning_rate
def train(self, iterations, verbose=False):
costs = []
for i in range(0, iterations):
AL, caches = self.model_forward(self.data)
cost = self.cross_entropy_cost(AL, self.labels)
grads = self.model_backward(AL, self.labels, caches)
self.gradient_descent_update(grads)
if i % 100 == 0:
if verbose:
print ("Cost after iteration %i: %f" % (i, cost), end='\r')
costs.append(cost)
return costs, grads
def minibatch_gen_from_pddf(data, target_label, batch_size, shuffle=True):
"""
Args:
data: data as pandas df
target_label: target label column name in df
batch_size: batch size
shuffle: whether to shuffle the data.
Yields:
Data in num_batches equal batches with the last one (possibly) shorter
"""
target = np.array(data.pop(target_label))
data = np.array(data)
if shuffle:
perm = np.random.permutation(len(target))
target, data = target[perm], data[perm]
num_batches = int(np.ceil(len(target) / batch_size))
for i in range(1,num_batches+1):
yield data[(i-1)*batch_size:i*batch_size, :], \
target[(i-1)*batch_size:i*batch_size] |
import math
def to_minute(time):
time = time.replace(" ", "")
hour = int(time[:-2].split(":")[0])
minute = int(time[:-2].split(":")[1])
if time[-2:] == 'am':
hour = hour + 12
print("time in hours: {} hour: {} minute: {}".format(time, hour, minute))
return hour*60+minute
def to_hour(time):
hour = math.floor(time/60)
minute = round(time%60)
print("time in minutes: {} hour: {} minute: {}".format(time, hour, minute))
if hour > 12:
time = str(hour - 12) + ':' + str(minute) + 'pm'
else:
time = str(hour) + ':' + str(minute) + 'am'
return time
def time_decrement(time, decrease_amt):
return time - decrease_amt
def calculate_weekly_goal(ideal_time, current_time):
#convert to minute format (output format: 8:00 am -> 480)
current_time = to_minute(current_time)
print("convered to minutes: {}".format(current_time))
#calcualte weekly goal
goal1 = time_decrement(current_time, 30)
goal2 = time_decrement(current_time, 45)
print("goals in minutes: {} {}".format(goal1, goal2))
#convert to hour format (output format: 480 -> 8:00 am)
goal1 = to_hour(goal1)
goal2 = to_hour(goal2)
print("goals in hours: {} {}".format(goal1, goal2))
#self._bedtime_list = [goal1, str(3), goal2, str(2)]
return goal1, goal2, str(3), str(2)
calculate_weekly_goal('10:00pm', '1:20am')
|
import statistics as stats
#ejercicios medidas de dispersion
'''
1.1 What is the range for the data set?
1.2 How does the standard deviation change when 6 is replaced with 12? Does it increase, or decrease, or it remains the same?
1.3 Is is possible to have a dataset with 0 standard deviation or variance?
If yes, can you think of any dataset with 6 data points that have 0 standard deviation?
1.4 We know that standard deviation is a measure of spread in the dataset. What is meant by deviation here?
What is the formula for calculating deviation? Can deviation be negative?
1.5 What is the deviation from the mean for each of the points in the list? Write a for loop and print each of the values.
1.6 How is standard deviation different than variance?
'''
#1.1
points = [-4, 17, 25, 19, 6, 11, 7]
range = max(points)- min(points)
print('El rango es '+ str(range))
#1.2
data = [2,4,7,1,6,8]
b=stats.stdev(data)
print(b)
data[-2] = 12
a = stats.stdev(data)
print(a)
#1.3
'''
Yes, it is posible.
'''
c = [2,2,2,2,2,2]
dc = stats.stdev(c)
print(dc)
#1.4
'''
the variation between values. The formula would be sum of (xi - mean(x))^2/N and a standard desviation cant be negative.
'''
#1.5 no he sido capaz de sacarlo
data = [23, 12, 34, 65, 34, 81]
for item in data:
print("Deviation for item: ", item, "is: ", item - stats.mean(data))
#1.6
'''
Even though both variance and standard deviation are measures of spread/dispersion, there is a difference in the units of the two things.
Unit of variance is squared of the unit of the original data while unit of standard deviation is same as the unit of the original data.
Therefore for practical purposes, sometimes people prefer to use standard deviation instead of variance.
Also since variance is square of standard deviation, if the value of standard deviation is large then the magnitude of variance becomes larger.
Sometimes it is prefereable to work with numbers of lesser magnitudes
'''
|
# Fizz Buzz & Make String Lowercase
zahl = int(input("Geben Sie bitte eine Zahl zw. 1 und 100 ein: "))
while zahl > 0:
if zahl % zahl == 0 and zahl % 3 == 0 and zahl % 5 == 0:
print("FizzBuzz")
elif zahl % 5 == 0:
print("Buzz")
elif zahl % 3 == 0:
print("Fizz")
else:
print(zahl)
zahl = zahl - 1
# Abfrage, ob nochmal gespielt werden möchte
if zahl <= 0:
abfrage = input("Wollen Sie nochmal? JA oder NEIN eingeben: ")
abfrage = abfrage.upper()
print(abfrage)
if abfrage == "JA":
zahl = int(input("Bitte neue Zahl eingeben: "))
elif abfrage != "JA" and abfrage != "NEIN":
print("Bitte Ja oder Nein eingeben")
elif abfrage == "NEIN":
print("Ihre Antwort ist " + abfrage + " Vielen Dank")
|
#!/usr/bin/python3
row_column = input("please input row and column: ")
dimension = [int(i) for i in row_column.split(',')]
dimension_row = dimension[0]
dimension_column = dimension[1]
Matrix = [[0 for x in range(dimension_column)] for y in range(dimension_row)]
for row in range(dimension_row):
for column in range(dimension_column):
Matrix[row][column] = row * column
print(Matrix)
|
#!/usr/bin/python3
"""input a number to calculate"""
n = input("please input a number to compute: ")
n = int(n)
d = dict()
for i in range(1, n+1):
d[i] = i*i
print(d)
|
#!/usr/bin/python3
str_input = str(input("please input letters and digits: "))
letters = 0
digits = 0
for i in str_input:
if i.isdigit():
digits += 1
elif i.isalpha():
letters += 1
else:
pass
print("LETTERS", letters)
print("DIGITS", digits)
|
#!/usr/bin/python3
values = input("please input a list of number: ")
numbers = [x for x in values.split(",") if int(x) % 2 != 0]
print(",".join(numbers))
|
#!/usr/bin/python3
number = int(input("please input a number: "))
new_list = input("please input a list of number: ")
new_list = new_list.split(",")
def get_number_list(): # get number list_number
list_number = []
for i in new_list:
numbers = int(i)
list_number.append(numbers)
return list_number
def check_number(numbers, number_list): # check if the number is in the list # noqa
for i in number_list:
if numbers == i:
return True
else:
return False
print(check_number(number, get_number_list()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.