blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
468fb97d863167d40518e9925cf265fead882663 | vimallohani/LearningPython | /three_while_loop.py | 142 | 3.921875 | 4 | # loop hello world 10 times
print("Hello World \n"*10) #without loop
#with loop
i=1
while i<11:
print(f"Hello World!! {i}")
i+=1 |
d2105f5c99426e3a8f27890ac419681cd1cf1ec0 | walkccc/LeetCode | /solutions/1860. Incremental Memory Leak/1860.py | 259 | 3.5 | 4 | class Solution:
def memLeak(self, memory1: int, memory2: int) -> List[int]:
i = 1
while memory1 >= i or memory2 >= i:
if memory1 >= memory2:
memory1 -= i
else:
memory2 -= i
i += 1
return [i, memory1, memory2]
|
2873878005dc800845272ee2727bc9b64ede6370 | jansche/EMEARegionsRandomizer | /randEMEA.py | 397 | 4.03125 | 4 | import random
# create the initial array
regionsEMEA = ["Central Eastern Europe", "France", "Germany", "Middle East / Africa", "United Kingdom", "Western Europe"]
# randomly pick region after region
num = len(regionsEMEA)
for x in range(num):
numRegions = len(regionsEMEA)
pos = random.randint(0,numRegions-1)
selected = regionsEMEA[pos]
print(selected)
regionsEMEA.pop(pos)
|
9093c2367d6c77d80d68b6cd92966a298f311b82 | pedroceciliocn/programa-o-1 | /lists/exe_8_matriz.py | 1,249 | 4.21875 | 4 | """
Fazer um programa Python para:
– Ler por linhas uma matriz M x N, onde M <= 4 e N <= 8
são lidos antes da leitura da matriz.
– Depois, percorrendo a matriz por colunas, armazenar
em um vetor os elementos desta matriz que sejam
múltiplos de 6.
– Finalmente, imprimir de maneira organizada a matriz e
depois o vetor.
"""
M = int(input("Dê o número M de linhas da matriz: "))
while M > 4 or M < 1:
M = int(input("Dê o número M de linhas da matriz (M <= 4): "))
N = int(input("Dê o número N de colunas da matriz: "))
while N > 8 or N < 1:
M = int(input("Dê o número N de colunas da matriz (N <= 8): "))
matriz = []
for i in range(M):
matriz.append([0]*N)
for j in range(N):
matriz[i][j] = int(input(f"Dê o elemento {i+1} {j+1} da matriz: "))
vetor = []
for j in range(N):
for i in range(M):
if matriz[i][j] % 6 == 0:
vetor.append(matriz[i][j])
for i in range(M):
print(matriz[i])
# imprimindo elemento por elemento
for i in range(M):
for j in range(N):
print(f"{matriz[i][j]:>5}", end = '') # pulando e alinhando
print()
if len(vetor) == 0:
print("Não há múltiplos de 6 na matriz")
else:
print(f"Múltiplos de 6 na matriz: {vetor}") |
38d0d1589a1e094b18d552598938df86137bb8e9 | FronkCow/ProjectEuler | /p7.py | 620 | 3.515625 | 4 | # What is the 10 001st prime number?
import sys
import math
# maybe too big lol
# max_num = sys.maxsize
# print(max_num)
arb_limit = 200000000
list_all = [True] * arb_limit
list_prime = []
print("part 2")
upper_limit = int(math.sqrt(len(list_all)))
print(upper_limit)
for x in xrange(2, upper_limit):
if list_all[x] == True:
# logic here is wrong, doesn't catch all primes
# list_prime.append(x)
for y in xrange(x + x, len(list_all), x):
list_all[y] = False
for x in xrange(2, arb_limit):
if list_all[x] == True:
list_prime.append(x)
print(list_prime[10000])
|
f2fa15dfa0f0d3d4f8202f169278d6e038a8c997 | PritiKale/Python | /numpy.py | 292 | 3.546875 | 4 | import numpy as np
a=np.array([[1,2,3,4],[9,0,2,3],[1,2,3,19]])
print("The Original Array:\n")
print(a)
b=a.copy()
print("\n Printing the deep copy b")
print(b)
b.shape=4,3;
print("\n Change made to the copy b do not reflect a")
print("\n Original array\n",a)
print("\n copy \n ",b)
|
2f567d11218701b09e33906d8393ee475d58e391 | rui-r-duan/courses | /ai/learn_python/testclosure.py | 381 | 3.75 | 4 | def foo():
def recalc(y):
a = 7 # creates local a, shadowing the outer a
bar(y+20) # but the a in bar is still the outer a (original)
def bar(x):
print a+b+x
a = 6
print a
b = 1
bar(10)
recalc(10)
print a
# we cannot define another 'a' variable inside a inner block, no inner block in python
foo()
|
f2f208594cad6c1992a4ecba5bb425f5640f5ac9 | leewalkergb/Python_Practice | /Chapter 2/ATBS_2-3.py | 641 | 4.15625 | 4 | # This file practices the use of imports
# This program allows the user to play a guess the number game with the random module
# if you want to import and not have to type random.* then from random import * is the syntax
#import random
from random import *
guess = 0
num = (randint(1, 5))
while guess != num:
print("Guess the number between 1 and 5")
guess = int(input())
if guess == num:
break
print("Well done the number was", num)
import sys
while True:
print("Type exit to exit")
response = input()
if response == "exit":
sys.exit()
print("You typed " + response + " that's not correct")
|
c185612f1e0ae1d04a7654a5e79252b412a3affb | albonicc/python_exercises | /collatz.py | 663 | 4.53125 | 5 | #The Collatz sequence
#This function does one operation or another based in if the number is even or odd
def collatz(number):
if even(number):
return number // 2
else: #Odd number
return 3 * number + 1
#This function verifies if the number is even or odd
def even(number):
if number % 2 == 0:
return True
else:
return False
#collatz() is exectuted and expects an input from the user,
#it will stop when the return value of collatz() is 1
num = 0
while collatz(num) != 1:
try:
num =int(input())
collatz(num)
print(collatz(num))
except:
print("An integer must be entered!")
|
afb4e34474ea6b08ceeed941bc572c4fa3d1cad0 | Tlonglan/Python | /HomeWork/1.turtle模块/交叉十字架.py | 414 | 3.515625 | 4 | import turtle
import time
def drawcross10(x,y,l,s,n): # n为条形数量,l为条形长度,s为条形宽度
turtle.pu()
turtle.setpos(x,y)
turtle.pd()
turtle.speed(4)
for i in range(1,n+1):
turtle.fd(l)
turtle.rt(90)
turtle.fd(s)
turtle.rt(90)
turtle.fd(l)
turtle.lt(360/n)
time.sleep(3)
turtle.ht()
drawcross10(10,20,90,30,8) |
bcb55c3e7cd5a25093693c97385e004f174055a6 | lcqbit11/algorithms | /easy/two-sum-iv-input-bst.py | 1,222 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.treeNode import TreeNode
def two_sum_iv_input_bst(root, k):
"""
给定一个二叉搜索树和一个目标值,如果在树中存在两个元素加和等于目标值则返回true,
否则返回false
:param root: TreeNode(int)
:return: bool
"""
nums = []
s = []
while s or root: # 中序遍历
while root:
s.append(root)
root = root.left
if s:
root = s.pop()
nums.append(root.val)
root = root.right
l = len(nums)
low, high = 0, l - 1
while low < high:
if nums[low] + nums[high] > k:
high -= 1
elif nums[low] + nums[high] < k:
low += 1
else:
return True
return False
if __name__ == "__main__":
"""
5
/ \
3 6
/ \ \
2 4 7
Target = 9
"""
root = TreeNode(5)
root.left = layer2_left = TreeNode(3)
root.right = layer2_right = TreeNode(6)
layer2_left.left = TreeNode(2)
layer2_left.right = TreeNode(4)
layer2_right.right = TreeNode(7)
target = 9
print(two_sum_iv_input_bst(root, k=target))
|
21725f43ba6f22ebae10bd22fdf335ec1d317772 | Kalwing/job-ready-project | /Tier2-Python_Basics/3-Introduction_Computational_Thinking/unit3/noreplacementSim.py | 768 | 4.03125 | 4 | import random
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were drawn.
'''
RED, GREEN = 1, 0
nbSameColor = 0
for n in range(numTrials):
bucket = [RED, RED, RED, GREEN, GREEN, GREEN]
out = 0
for i in range(3):
drawn = random.choice(bucket)
bucket.remove(drawn)
out += drawn
if out in (3*RED, 3*GREEN):
nbSameColor += 1
return nbSameColor/numTrials
for i in range(1,5001,1000):
print(noReplacementSimulation(i))
|
47dfd3c2458a71dc98e5a60b3566420f0fa9dcdb | hc270/BME547Class | /calculator.py | 737 | 4.125 | 4 | # calculator.py
def add (x, y) :
z = x + y
print("{} + {} = {}".format(x,y,z))
return z
def subtract (x,y) :
z = x - y
print("{} - {} = {}".format(x,y,z))
return z
def multiply (x,y) :
z = x * y
print("{} * {} = {}".format(x,y,z))
return z
def divide (x,y) :
z = x / y
print("{} / {} = {}".format(x,y,z))
return z
x = input("Enter a first number: ")
y = input("Enter a second number: ")
z = input("Enter a operation: ")
a = float(x)
b = float(y)
print("Two numbers are {} and {}. Operation is {}".format(x,y,z))
if z == "add":
add(a, b)
elif z == "subtract":
subtract(a,b)
elif z == "multiply":
multiply(a,b)
elif z == "divide":
divide(a,b)
else:
print("The {} operation is not recognized.".format(z))
print("DONE") |
3db471a75dbe48d1a97b83625b50fef4637052e7 | bhupendrak9917/GUI | /PyGUI-master/clock.py | 321 | 3.71875 | 4 | from tkinter import *
from time import strftime
root = Tk()
root.title("Digital Clock")
def time():
string = strftime("%H:%M:%S:%p")
label.config(text=string)
label.after(1000,time)
label = Label(root, font=("d%-digital",40),background="black",foreground="blue")
label.pack(anchor="center")
time()
mainloop() |
50fb6053a08b59ebd8761c11ca1a9c27dcf48f64 | toyanne/100-Python-exercises | /8.2.py | 245 | 4.0625 | 4 |
n=int(input("Enter a number:"))
def primeNumber(n):
for i in range(2,n):
if n%i==0:
return False
return True
if primeNumber(n) :
print("This is a prime number.")
else :
print("This isn't a prime number.")
|
e1d717e836bcac32ce79bd52600d89df3a351bd2 | Juoh-K/python_lecture | /for_string.py | 214 | 4.03125 | 4 | print(len("Hello World"))
#대문자를 제외한 문자 출력
# for i in "Hello World":
# if i!="H" and i!="W":
# print(i)
for i in "hello World":
if i=="H" or i=="W":
break
print(i) |
43fffde292fdc1777a3d500fe8d05d5d9ea87475 | kunalaphadnis99-zz/python-experiments | /generators/generators.py | 451 | 3.90625 | 4 | # generators are -> range which yield in memory like Enumerable in C# keep on yielding next
def generator_function(count):
for i in range(count):
yield i
for i in generator_function(100):
print(i, end=' ')
print('')
generator = generator_function(100)
print(generator)
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
|
879022569a2c91e78dc5739ac73b451f831e7d0b | vishwa742/Calculator | /src/Calculator.py | 863 | 3.75 | 4 | import math
def addition(a,b):
return a+b
def subtraction(a,b):
return b-a
def multiplication(a,b):
return a*b
def division(a,b):
return float(a)/float(b)
def squared(a):
return a*a
def squareroot(a):
return math.sqrt(a)
class Calc:
rest=0
def __init__(self):
pass
def add(self, a, b):
self.result = addition(a,b)
return self.result
def subtract(self, a, b):
self.result = subtraction(a,b)
return self.result
def multiply(self, a, b):
self.result = multiplication(a,b)
return self.result
def divide(self, a, b):
self.result = division(a,b)
return self.result
def square(self,a):
self.result = squared(a)
return self.result
def root(self,a):
self.result = squareroot(a)
return self.result |
4296fd91a7057f68ba8331d43c0abb57869ec000 | alansong95/leetcode | /637_average_of_levels_in_binary_tree.py | 2,105 | 3.828125 | 4 | import collections
# bfs
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
queue = collections.deque([(root, 0)])
res = []
while queue:
node, level = queue.popleft()
if node:
if len(res) == level:
res.append([])
res[level].append(node.val)
queue.append((node.left, level+1))
queue.append((node.right, level+1))
for i in range(len(res)):
res[i] = float(sum(res[i])) / len(res[i])
return res
# dfs recursion
class Solution2(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
lvlcnt = collections.defaultdict(int)
lvlsum = collections.defaultdict(int)
def dfs(node, level):
if not node:
return
lvlcnt[level] += 1
lvlsum[level] += node.val
dfs(node.left, level+1)
dfs(node.right, level+1)
dfs(root, 0)
return [float(lvlsum[i]) / lvlcnt[i] for i in range(len(lvlcnt))]
# dfs with stack
class Solution3(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
lvlcnt = collections.defaultdict(int)
lvlsum = collections.defaultdict(int)
stack = [(root, 0)]
while stack:
node, level = stack.pop()
if node:
lvlcnt[level] += 1
lvlsum[level] += node.val
stack.append((node.left, level+1))
stack.append((node.right, level+1))
return [float(lvlsum[i]) / lvlcnt[i] for i in range(len(lvlcnt))] |
24f8c5f6b848ba541a0f03a6241859851b481ca3 | gabriellaec/desoft-analise-exercicios | /backup/user_386/ch92_2019_10_02_18_01_55_591754.py | 276 | 4.125 | 4 | dict = {}
dict['felipe']="lacombe"
dict['ohara']="shiba"
def simplifica_dict(dict):
dictLista = []
for key, value in dict.items():
dictLista = [key,value]
dictLista.append(dictLista)
print (dictLista)
for i in dictLista:
print (i) |
a3fef2fd75433779ba553f59c5e5da42190feb05 | Xiaomifeng98/Python_File | /计时器/MyTimer_plus.py | 2,441 | 3.890625 | 4 | import time as t
class MyTimer():
def __init__(self):
self.unit = [' year(s)', ' month' , ' day', ' hour', ' minute', ' second.']
self.borrow = [0, 12, 31, 24, 60, 60]
self.prompt = 'Timing not started'
self.lasted = []
self.start_num = 0
self.stop_num = 0
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self, other):
prompt = 'Total running time is: '
result = []
for index in range(6):
result.append(self.lasted[index] + other.lasted[index])
if result[index]:
prompt += (str(result[index]) + self.unit[index])
return prompt
#_________________________________________________________Start the timer
def start(self):
self.start_num = t.localtime()
self.prompt = 'Tips: please call stop() to stop timing.'
print('Start the timer.')
#_________________________________________________________Stop the timer
def stop(self):
if not self.start_num:
print('Tips: please call start() to start timing.')
else:
self.stop_num = t.localtime()
self._calc()
print('Stop the timer.')
# _________________________________Internal method: calculate running time
def _calc(self):
self.lasted = []
self.prompt = 'Total running time is: '
for index in range(6):
temp = self.stop_num[index] - self.start_num[index]
#If the low is not enough, borrow from the high
if temp < 0:
#Test the high position can be borrowed, if not, borrow from the higher position.
i = 1
while self.lasted[index - i] < 1:
self.lasted[index - i] += self.borrow[index - i] - 1
self.lasted[index - i - 1] -= 1
i += 1
self.lasted.append(self.borrow[index] + temp)
self.lasted[index - 1] -= 1
else:
self.lasted.append(temp)
#Since the high position will be borrowed at any time, the print should be replaced at the end.
for index in range(6):
if self.lasted[index]:
self.prompt += (str(self.lasted[index]) + self.unit[index])
#Initialize variables for the next round.
self.start_num = 0
self.stop_num = 0 |
7d5cf6a3731e11d6a91d7c6c63d156c3b81a1b44 | mc0505/ct4b_basic | /ss7/minihack1-1/test3.py | 151 | 3.984375 | 4 | while True:
num = (input("Place a number: "))
if num.isdigit():
print(int(num)**2)
break
else:
print("Try Again!") |
506d384711b9fff02c47297bdf81a46f38545cb0 | Chan0619/FIS03 | /Python_pratice/objectdemo/game_round.py | 786 | 3.8125 | 4 | """
* 一个回合制游戏,每个角色都有hp和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
* 定义一个fight方法:
* my_hp = hp - enemy_power
* enemy_final_hp = enemy_hp - my_power
* 两个hp进行对比,血量剩余多的人获胜
"""
def game():
my_hp = 1000
my_power = 200
enemy_hp = 1200
enemy_power = 199
while True:
my_hp = my_hp - enemy_power
enemy_hp = enemy_hp - my_power
# 三目表达式
# print('我赢了') if my_final_hp > enemy_final_hp else print('我输了')
print(my_hp, enemy_hp)
if my_hp <= 0:
print('我输了')
break
if enemy_hp <= 0:
print('我赢了')
break
game()
|
8b7e43a4f68cca08438fed796ea6fb7f3b316fa2 | heysushil/numpy-array-coding | /3.datatype.py | 2,420 | 3.640625 | 4 | # मेरे Youtube चैनल को सबस्क्राइब करना ना भूलो ताकि आपको कोड का पूरा फ़्लो समझमे आए - https://www.youtube.com/channel/UCphs2JfmIClR62wbyf76HDg
# कोई भी सवाल है उसको मेरे यूट्यूब चैनल के कमेन्ट या डिस्कशन सेक्शन मे पूछ सकते हो - https://www.youtube.com/channel/UCphs2JfmIClR62wbyf76HDg/discussion
# Numpy Data Types
'''
Datatypes in Numpy
i - interger
u - unsigned inter
f - float
c - complex
b - bollean
m - timedetla
M - datetime
O - object
S - sting
U - unicode string
V - fixed chunk of memory for other type (void)
'''
import numpy as np
arr = np.array([1,2,3,4,5,6,'hello'])
print('\nChec datatype by python type(): ',type(arr))
print('Check datatype by numpy mehtod: ', arr.dtype)
stringArrayValues = np.array(['ram','shyam','radha'])
print('check sting datatype: ',stringArrayValues.dtype)
# define datatype at defing value of array
# dtype also have power to difne length of variable
valueWithDtype = np.array([1,2,3,4], dtype='S3')
print('Vlaus: ',valueWithDtype)
print('decode values: ',valueWithDtype[0].decode('utf-8'))
print('Dataype of value: ',valueWithDtype.dtype)
# to conver sting into interger
stringtoInter = np.array([1,2,3,4,6,7,8], dtype='i')
print('Chek int value: ',stringtoInter.dtype)
# copy array
newInterValues = stringtoInter.copy()
viewValues = stringtoInter.view()
stringtoInter[0] = 11
print('newInterValues: ',newInterValues)
# view use to get the array values
print('viewValues: ',viewValues)
'''
copy vs view methos
1. copy use to store the values in new varaible but remeber in this case then new varibale will not able to retive changes of main variable.
2. view : in this case it's like image of main varable and in case any changes made in main varaible then the changes alos reflexc in view varaible
'''
# matix: 2*3 row and cloumn
# how to find shap of array
# this is a 1*5 matix [[[[[]]]]]
matixarray = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]], ndmin=5)
print('Find the shap of matixarray: ',matixarray.shape)
newarr = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
# print('shap: ',newarr.reshape())
'''
Matix of 3*3
[00 01 02]
[10 11 12]
[20 21 22]
Pyramix examples:
*
***
*****
''' |
1fc4c981d25ffb99ee8a714e108e6ee25082281e | boolks/python_lecture | /20200716_python/class.py | 1,293 | 3.703125 | 4 | # SoccerPlayer 클래스 선언
class SoccerPlayer(object):
# 생성자 선언 - 객체가 생성될 때 자동으로 호출되는 함수
def __init__(self, name, position, back_number):
self.name = name
self.position = position
self.back_number = back_number
# 일반함수 (instance method), back_number 값을 입력받아 변경하는 함수
# 함수의 첫 번째 파라미터에 self 가 있어야 클래스에 속한 함수가 된다.
# 첫 번째 파라미터의 이름은 self 가 아니어도 된다.
def change_back_number(self, new_number):
print(f'선수의 등번호를 변경합니다. From {self.back_number} to {new_number}')
self.back_number = new_number
# toString() 메서드와 동일한 역할
# 객체의 주소가 아니라 객체가 가진 특정 인스턴스 값을 출력
def __str__(self):
return f'My Name is {self.name}, I Play in {self.position} in center, My Back Number is {self.back_number}'
def main():
# 객체 생성
dooly = SoccerPlayer('둘리', 'MF', '10')
print(dooly)
print('현재 선수의 등번호는 {}번'.format(dooly.back_number))
dooly.change_back_number(5)
print('현재 선수의 등번호는 {}번'.format(dooly.back_number))
|
779ce06b1ef47df2589ddba002e30782fea02144 | KRVPerera/AdvancedAlgorithms | /Python/BST/BST.py | 1,267 | 4.125 | 4 | #!/usr/bin/python3
"""
This is a simple implementation of BST
binary search tree
"""
import os, sys
lib_path = os.path.abspath(os.path.join('..', 'basic'))
sys.path.append(lib_path)
from TreeNode import Node
class BST(object):
# property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
def __init__(self):
self.root = None
self._size = 0
@property
def size(self):
return self._size
@size.setter
def size(self, value):
self._size = value
def __len__(self):
return self._size
def __iter__(self):
return self.root.__iter__()
def insert(self, val):
if self.root:
self._insert(val, self.root)
else:
self.root = Node(value=val)
self.size += 1
def _insert(self, value, currentNode):
if value <= currentNode.value:
if currentNode.hasLeftChild():
self._insert(value, currentNode.left)
else:
currentNode.left = Node(value, parent=currentNode)
else:
if currentNode.hasRightChild():
self._insert(value, currentNode.right)
else:
currentNode.right = Node(value, parent=currentNode)
|
d5e1eb9bed25f65d5d295f4b4324b5ca021c5e68 | aracthon/SPECT | /src/nn.py | 3,643 | 3.859375 | 4 | # Implementing a one-layer Neural Network
#---------------------------------------
#
# We will illustrate how to create a one hidden layer NN
#
# We will use the iris data for this exercise
#
# We will build a one-hidden layer neural network
# to predict the fourth attribute, Petal Width from
# the other three (Sepal length, Sepal width, Petal length).
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from sklearn.metrics import classification_report
ops.reset_default_graph()
def extract_data(filename):
out = np.loadtxt(filename, delimiter=',');
# Arrays to hold the labels and feature vectors.
labels = out[:,0]
labels = labels.reshape(labels.size,1)
fvecs = out[:,1:]
# Return a pair of the feature matrix and the one-hot label matrix.
return fvecs,labels
def formulate_data(filename):
# Extract data
data, labels = extract_data(filename)
# Get the shape
size, num_features = data.shape
return (data, labels, size, num_features)
train_data_filename = '../data/SPECT.train.txt'
test_data_filename = '../data/SPECT.test.txt'
train_data, train_labels, train_size, num_features = formulate_data(train_data_filename)
test_data, test_labels, test_size, num_features = formulate_data(test_data_filename)
# Create graph session
sess = tf.Session()
# Declare batch size
batch_size = 50
# Initialize placeholders
xData = tf.placeholder(shape=[None, 22], dtype=tf.float32)
yLabels = tf.placeholder(shape=[None, 1], dtype=tf.float32)
# Number of hidden nodes
hidden_layer1_nodes = 20
hidden_layer2_nodes = 10
# Hidden layer1
W1 = tf.Variable(tf.random_normal(shape=[22,hidden_layer1_nodes]))
b1 = tf.Variable(tf.random_normal(shape=[hidden_layer1_nodes]))
# Hidden layer2
W2 = tf.Variable(tf.random_normal(shape=[hidden_layer1_nodes,hidden_layer2_nodes]))
b2 = tf.Variable(tf.random_normal(shape=[hidden_layer2_nodes]))
# Output layer
W3 = tf.Variable(tf.random_normal(shape=[hidden_layer2_nodes,1]))
b3 = tf.Variable(tf.random_normal(shape=[1]))
# Build model
hidden_layer1_output = tf.nn.relu(tf.add(tf.matmul(xData, W1), b1))
hidden_layer2_output = tf.nn.relu(tf.add(tf.matmul(hidden_layer1_output, W2), b2))
final_output = tf.nn.relu(tf.add(tf.matmul(hidden_layer2_output, W3), b3))
# Calculate Minimum Square Error
loss = tf.reduce_mean(tf.square(yLabels - final_output))
# Declare optimizer
learning_rate = 0.001
training_epochs = 1000
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)
# Training loop
loss_vec = []
test_loss = []
for epoch in xrange(training_epochs):
# Randomize
rand_index = np.random.choice(len(train_data), size=batch_size)
rand_x = train_data[rand_index]
rand_y = train_labels[rand_index]
# Training
sess.run(optimizer, feed_dict={xData: rand_x, yLabels: rand_y})
temp_loss = sess.run(loss, feed_dict={xData: rand_x, yLabels: rand_y})
loss_vec.append(np.sqrt(temp_loss))
# Testing
test_temp_loss = sess.run(loss, feed_dict={xData: test_data, yLabels: test_labels})
test_loss.append(np.sqrt(test_temp_loss))
predicted = sess.run(final_output, feed_dict={xData: test_data})
predicted[predicted!=0] = 1
# print predicted.T
print classification_report(test_labels, predicted)
# Plot loss (MSE) over time
plt.plot(loss_vec, 'k-', label='Train Loss')
plt.plot(test_loss, 'r--', label='Test Loss')
plt.title('Loss (MSE) per Generation')
plt.legend(loc='upper right')
plt.xlabel('Generation')
plt.ylabel('Loss')
plt.show() |
04a1eddc9513f1ca8767af0cd9f2060be203a1b9 | Liviere97/CursoPythonEjercicios | /strings.py | 942 | 4.15625 | 4 | #CADENAS DE CARACTERES
#string = 'Hola mundo'
#string= input('Escribe un mensaje: ')
#primer_letra = string[0]
#longitud = len (string)
#ultimo_valor = string [len(string) - 1]
#print (ultimo_valor)
#Slices
mensaje = 'Aprendiendo a programar en python'
slc_1 = mensaje[12:]
slc_2 = mensaje[:21]
slc_3 = mensaje [6:17]
#print (slc_1)
#print (slc_2)
#print (slc_3)
#SPLIT
splited = mensaje.split (" ")
print (splited)
#LISTAS
lista = ['palabra' , 3 , 5.43 , True ,['soy','livi','manzano']]
#print (lista[4][1])
#lista_anidada = lista[4]
#lista_anidada[1]
print (lista)
#METODOS DE LAS LISTAS
#pop quita el ultimo elemento
lista.pop()
nueva_lista = lista.pop()
print (nueva_lista)
print(lista)
#append agregar un elemnto al final
lista.append(False)
print(lista)
# join toma una lista de strings y lo convierte a un string
lista_string = ['1','2','3','4']
separador = '-'
lista_joineada = separador.join(lista_string)
print (lista_joineada) |
b32e161c7600db40bd70709df1502b33075e010c | qq345386817/LeetCode | /LeetCode/2. AddTwoNumbers.py | 1,739 | 3.890625 | 4 | # -*- coding: utf-8 -*-
class ListNode:
'''
val: Node 保存的数据
next: 指向下一个节点
'''
def __init__(self, val, next=None):
self.val = val
self.next = next
def append(self, val):
if self.next == None:
newNode = ListNode(val)
self.next = newNode
else:
self.next.append(val)
def __repr__(self):
'''
定义 Node 的 print 输出
'''
result = str(self.val)
nextNode = self.next
while nextNode != None:
result = result + " -> " + str(nextNode.val)
nextNode = nextNode.next
return result
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
curr = dummy
carry = 0
p = l1
q = l2
while p != None or q != None:
x = 0
y = 0
if p != None:
x = p.val
p = p.next
if q != None:
y = q.val
q = q.next
sum = x + y + carry
carry = sum // 10 # 整除
newNode = ListNode(sum % 10)
curr.next = newNode
curr = newNode
if carry > 0 :
curr.next = ListNode(1)
return dummy.next
node1 = ListNode(2)
node1.append(4)
node1.append(3)
node2 = ListNode(5)
node2.append(6)
node2.append(4)
print(node1)
print(node2)
so = Solution()
print(so.addTwoNumbers(node1,node2))
node3 = ListNode(1)
node3.append(8)
print(so.addTwoNumbers(node3,ListNode(0)))
print(so.addTwoNumbers(ListNode(5),ListNode(5)))
|
12188abf8b5d7ef503f4a2f9504930edf2e898cb | gabriellaec/desoft-analise-exercicios | /backup/user_307/ch25_2019_03_12_22_47_23_987829.py | 549 | 3.921875 | 4 | #Escreva um programa que pergunta a distância que um passageiro deseja percorrer em km.
#Seu programa deve imprimir o preço da passagem,
#cobrando R$0.50 por km para viagens de até 200km e R$0.45 por quilômetro extra para viagens mais longas.
#(Adaptado do ex. 4.6 livro Nilo Ney).
#O resultado deve ser impresso com exatamente duas casas decimais.
dist=float(input('Qual distância desejada?'))
def desejo(dist):
if dist<=200:
y=dist*0.5
else:
y=100+(dist*0.45)
return y
print(("a distância desejada é {0:.2f}").format(desejo(dist))) |
2404efe8edc04fff52476b3c7b4ea74585375d40 | joke1196/FISType2 | /fuzzy_rule_type2.py | 4,116 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as pl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import linguistic_variable as lv
class Fuzzy_RuleT2:
"""
This class implements a fuzzy rule.
A single type of operation per rule is allowed. Yo can choose between:
AND - minimum
AND - product
AND - bounded product
OR - maximum
OR - probabilistic sum
OR - bounded sum
"""
__fuzzy_operations_names = {'AND_min':'AND', 'AND_prod':'AND', 'AND_boundprod':'AND', 'OR_max':'OR', 'OR_probsum':'OR', 'OR_boundsum':'OR'}
__fuzzy_operations = {'AND_min': np.min,
'AND_prod': np.prod,
'AND_boundprod': lambda x: np.max([0, np.sum(x) - 1]),
'OR_max': np.max,
'OR_probsum': lambda x: np.sum(x) - np.prod(x),
'OR_boundsum': lambda x: np.min([1, np.sum(x)])}
__fuzzy_implication = {'MIN': np.minimum,
'PROD': np.prod}
def __init__(self, operation, antecedent, consequent, implication):
"""
Three parameters are needed:
operation: the fuzzy operation to perform
antecedent: a list of tuples [(linguistic_variable, linguistic_value),...] defining the input fuzzy condition
consequent: a tuple (linguistic_variable, linguistic_value) defining the output fuzzy assignement
"""
assert operation in self.__fuzzy_operations.keys()
assert implication in self.__fuzzy_implication.keys()
self.operation = operation
self.antecedent = antecedent
self.consequent = consequent
self.implication = implication
self.antecedent_activation = 0.0
self.consequent_activationMin = np.zeros(len(consequent[0].input_values))
self.consequent_activationMax = np.zeros(len(consequent[0].input_values))
def compute_antecedent_activation(self, input_values):
"""
This function computes the activation of the antecedent of the rule.
The first step is the fuzzification of the input values. Then, the activation
is computed by applying the fuzzy operation to the values of the membership functions.
"""
temp = []
for pair in self.antecedent:
val = input_values.get(pair[0].name)
if val is not None:
membership_values = pair[0].fuzzify(val)
temp.append(membership_values[pair[1]])
if len(temp) == 0:
self.antecedent_activation = 0.0
else:
print temp
temp2 = []
for pair in temp:
if(pair[0] + pair[1] > 0.0):
temp2.append(pair)
if len(temp2) == 0:
temp2.append((0,0))
self.antecedent_activation = self.__fuzzy_operations[self.operation](temp2)
return self.antecedent_activation
def compute_consequent_activation(self):
"""
This function applies the causal implication operator in order to compute
the activation of the rule's consequent.
"""
self.consequent_activationMax, self.consequent_activationMin = self.consequent[0].get_linguistic_value(self.consequent[1])
print self.antecedent_activation
self.consequent_activationMin = self.__fuzzy_implication[self.implication](self.antecedent_activation, self.consequent_activationMin)
self.consequent_activationMax = self.__fuzzy_implication[self.implication](self.antecedent_activation, self.consequent_activationMax)
print self.consequent_activationMin
print self.consequent_activationMax
return (self.consequent_activationMax , self.consequent_activationMin)
def plot(self):
pl.plot(self.consequent[0].input_values, self.consequent_activationMin, label=self.consequent[1])
pl.plot(self.consequent[0].input_values, self.consequent_activationMax, label=self.consequent[1])
pl.ylim(0, 1.05)
pl.legend()
pl.title(self.consequent[0].name)
pl.grid()
|
cf581f6f22eec95faec32a5d073d7d71554e5c42 | D3MON1A/Python-lists-and-loops | /exercises/08.2-Divide_and_conquer/app.py | 412 | 3.859375 | 4 | list_of_numbers = [4, 80, 85, 59, 37,25, 5, 64, 66, 81,20, 64, 41, 22, 76,76, 55, 96, 2, 68]
#Your code here:
def merge_two_list(int):
odd=[]
even=[]
for int in list_of_numbers:
if int %2==0:
even.append (int)
else:
odd.append (int)
newlist=[]
newlist.append(odd)
newlist.append(even)
return newlist
print(merge_two_list(list_of_numbers))
|
df2b2e054ccf536fd5fe5563394ff06c4a4bf876 | Sorath93/Programming-Python-book | /9780596009250/PP3E-Examples-1.2/Examples/PP3E/extras/Assorted/minmax.py | 481 | 3.65625 | 4 | class MinMax:
def mm(self, *args):
res = args[0]
for x in args[1:]:
if self.docmp(x, res): # define me in subclass
res = x
return res
class Min(MinMax):
def docmp(self, x, y):
return x < y
class Max(MinMax):
def docmp(self, x, y):
return x > y
if __name__ == '__main__':
obj = Min()
print obj.mm('cc', 'aa', 'bb')
obj= Max()
print obj.mm(3, 2, 4, 1)
|
31102b1ddbf898ebc01e4495fa6b5604ed2a4bf2 | posenberg/LPTHW | /ex15.py | 1,217 | 4.46875 | 4 | from sys import argv
#script and filenames are argument variables. script refers to the python files and filename variable refers to the text file we will use
script, filename = argv
#the variable text uses the open() command to return the file object which are the texts within the document
#open function is built in module
text = open(filename)
#print output uses the formatter %r for the raw data.
#print uses text variable and uses .read() method/function to read the parameter "filename"
print "Here's our file: %r:" % filename
print text.read()
text = text.close()
#Takes input from the use about what's the file name and assigns it to file_again variable
#NOTE:When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file.
#if you omit these codes below, you just have the text printed once.
print "Type the filename again:"
file_again = raw_input("> ")
#Takes variable assigned from user and uses the function open() with file_again as the argument
txt_again = open(file_again)
#prints all the texts txt_again variable, but needs to be included with the .read() method
print txt_again.read()
txt_again = txt_again.close()
# "Ex 15 -Reading Files"
|
936512690a00cdcee0131db02dd91d9ecd5344d7 | agneshew/guess_game_colours | /game_random_colours.py | 820 | 4.03125 | 4 |
import random
print ("Welcome im my guess game. About what colour I'm thinking?, ")
colours = ["white", "yellow", "orange", "red", "pink", "blue", "green", "black"]
print (colours)
while True:
myColour = random.choice(colours)
userColour = input ("Give me a colour. ")
if myColour == userColour.lower():
print ("Congrats you guess")
contPlay = input ("Do you want play one more time? yes or no ")
if contPlay.lower() == "yes":
continue
else:
break
else:
print ("Sorry, a Was thinking about", myColour)
contPlay = input ("Do you want play one more time? yes or no ")
if contPlay.lower() == "yes":
continue
else:
break
print ("Thank you for playing")
|
7a2b03577b230d254973184c9fca6c800a268fa0 | reed-qu/leetcode-cn | /MergeSortedArray.py | 1,128 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/1 下午10:26
# @Title : 88. 合并两个有序数组
# @Link : https://leetcode-cn.com/problems/merge-sorted-array/
QUESTION = """
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
"""
THINKING = """
原地修改nums1即可,根据题设直写即可
"""
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> List[int]:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1[m:] = nums2
nums1.sort()
return nums1
if __name__ == '__main__':
s = Solution()
nums1 = [1, 2, 3, 0, 0, 0]
m = 3
nums2 = [2, 5, 6]
n = 3
print(s.merge(nums1, m, nums2, n))
|
106a9bc41ef756cf84916216eb9a4e9890844271 | huchangchun/learn-python3 | /leetcode/NP/4_bestProfit.py | 1,430 | 3.734375 | 4 | #encoding=utf-8
"""
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
"""
class Solution:
def bestProfit_recurve(self, prices: [int]) -> int:
if len(prices) < 2:
return 0
return max(prices[-1] - min(prices[:-1]),self.bestProfit_recurve(prices[:-1]))
def bestProfit_np(self, prices: [int]) -> int:
if len(prices) < 2:
return 0
result = [0]
minPrice = prices[0] #初始化一个最小值
for i in range(1, len(prices)):
minPrice = min(minPrice,prices[i - 1]) #从0开始记录和第i-1个比较后的最小值,然后第i个值减去最小值得到一个当前的最大值,和数组中的比较得到最大值
result.append(max(prices[i] - minPrice,result[i - 1]))
return result[-1]
if __name__ =="__main__":
Test = Solution()
lst = [7,1,5,3,6,4]
print(Test.bestProfit_recurve(lst))
print(Test.bestProfit_np(lst)) |
26cca7e9f0ad7b8e53d2914e431c8f7246a783ed | soumita0210/Image-stitching-using-RANSAC-algorithm | /task1.py | 4,221 | 3.765625 | 4 | """
RANSAC Algorithm Problem
(Due date: Oct. 23, 3 P.M., 2019)
The goal of this task is to fit a line to the given points using RANSAC algorithm, and output
the names of inlier points and outlier points for the line.
Do NOT modify the code provided to you.
Do NOT use ANY API provided by opencv (cv2) and numpy (np) in your code.
Do NOT import ANY library (function, module, etc.).
You can use the library random
Hint: It is recommended to record the two initial points each time, such that you will Not
start from this two points in next iteration.
"""
import random
def solution(input_points, t, d, k):
"""
:param input_points:
t: t is the perpendicular distance threshold from a point to a line
d: d is the number of nearby points required to assert a model fits well, you may not need this parameter
k: k is the number of iteration times
Note that, n for line should be 2
(more information can be found on the page 90 of slides "Image Features and Matching")
:return: inlier_points_name, outlier_points_name
inlier_points_name and outlier_points_name is two list, each element of them is str type.
For example: If 'a','b' is inlier_points and 'c' is outlier_point.
the output should be two lists of ['a', 'b'], ['c'].
Note that, these two lists should be non-empty.
"""
# TODO: implement this function.
#raise NotImplementedError
length=len(input_points)
pointlist=[]
inlier_points_name=[]
outlier_points_name=[]
min_d=10000
for i in range(k):
n1=random.randrange(0,length)
n2=random.randrange(0,length)
inl=[]
outl=[]
counter=0
dist=0
if (n1!=n2):
pl=[n1,n2]
pl_rev=[n2,n1]
if(pl not in pointlist and pl_rev not in pointlist):
pointlist.append(pl)
p1=input_points[n1]['value']
p2=input_points[n2]['value']
if(p1[0]==p2[0]):
xc=1
yc=0
intercept=-p1[0]
elif(p1[1]==p2[1]):
xc=0
yc=1
intercept=-p2[0]
else:
xc=(p2[1]-p1[1])/(p2[0]-p1[0])
yc=-1
intercept=p2[1]-xc*p2[0]
for j in range(length):
pi=input_points[j]['value']
pdist= (abs(xc*pi[0]+yc*pi[1]+intercept))/((xc**2+yc**2)**0.5)
if(pdist<t):
inl.append(input_points[j]['name'])
dist+=pdist
counter+=1
else:
outl.append(input_points[j]['name'])
if((counter-2)>=d):
dist/=(counter-2)
if(dist<min_d):
min_d=dist
inlier_points_name=inl
outlier_points_name=outl
return (inlier_points_name,outlier_points_name)
if __name__ == "__main__":
input_points = [{'name': 'a', 'value': (0.0, 1.0)}, {'name': 'b', 'value': (2.0, 1.0)},
{'name': 'c', 'value': (3.0, 1.0)}, {'name': 'd', 'value': (0.0, 3.0)},
{'name': 'e', 'value': (1.0, 2.0)}, {'name': 'f', 'value': (1.5, 1.5)},
{'name': 'g', 'value': (1.0, 1.0)}, {'name': 'h', 'value': (1.5, 2.0)}]
t = 0.5
d = 3
k = 100
inlier_points_name, outlier_points_name = solution(input_points, t, d, k) # TODO
assert len(inlier_points_name) + len(outlier_points_name) == 8
f = open('./results/task1_result.txt', 'w')
f.write('inlier points: ')
for inliers in inlier_points_name:
f.write(inliers + ',')
f.write('\n')
f.write('outlier points: ')
for outliers in outlier_points_name:
f.write(outliers + ',')
f.close()
|
57cfcf07a56d35349723ca7c54086fb7b6fe2658 | robertodias/deep_learning | /softmax/softmax.py | 342 | 3.796875 | 4 | import numpy as np
import math
# This function takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
L_prob = []
L_sum = 0
for i in range(len(L)):
L_sum += math.exp(L[i])
for i in range(len(L)):
L_prob.append(math.exp(L[i])/L_sum)
return L_prob
|
9a83bd945fe48c75dd38dc9024ae3a300571be2a | kasp470f/LearningProgramming | /Python/Black Jack/game/hand.py | 408 | 3.703125 | 4 | import re
def handCount(hand):
count = 0
for x in hand:
if "T" in x or "J" in x or "Q" in x or "K" in x:
count += 10
elif "A" in x and count+11 > 21:
count += 1
elif "A" in x:
count += 11
else:
count += int(re.sub('[♠♣♥♦]', '', x))
return count
def printHand(hand):
return "[" + "] [".join(hand) + "]" |
fee981c515ff61712637f73d842ea29c3bc4947c | sereglo/Escuela | /Ejericio Nº 1.py | 1,644 | 3.921875 | 4 | """Diseñar un algoritmo que calcule y muestre el salario mensual de un empleado a partir de sus
horas trabajadas y del valor hora establecido. La cantidad de horas trabajadas que superen
las 160 se pagan aun valor de un 50% adicional. En cambio, las que superen las 200 se abonan
al doble de su valor hora original. Al salario mensual calculado se le debe descontar un 5%
en concepto de aportes y contribuciones siempre que su sueldo bruto no supere los $5000"""
HorasTrabajadasMayor160=0
HorasTrabajadasMayor200=0
HorasAdicionales=0
HorasExtras=0
HorasNormales=0
SueldoBruto=0
SueldoNeto=0
Descuento=0
HorasTrabajadas=float(input("Ingrese las horas trabajadas: "))
PagoHoras=float(input("Ingrese el valor de las horas: "))
if HorasTrabajadas >= 160 and HorasTrabajadas < 200:
HorasTrabajadasMayor160 = (HorasTrabajadas -160)
HorasAdicionales = HorasTrabajadas / 2
HorasExtras = HorasTrabajadasMayor160 * HorasAdicionales
HorasNormales = 160 * HorasTrabajadas
SueldoBruto = HorasNormales + HorasExtras
print(SueldoBruto)
if HorasTrabajadas > 200:
HorasTrabajadasMayor200 = (HorasTrabajadas -160)
HorasAdicionales = HorasTrabajadas * 2
HorasExtras = HorasTrabajadasMayor200 * HorasAdicionales
HorasNormales = 160 * HorasTrabajadas
SueldoBruto = HorasNormales + HorasExtras
print(SueldoBruto)
if HorasTrabajadas < 160:
SueldoBruto = HorasTrabajadas * PagoHoras
if SueldoBruto > 5000:
Descuento = (5 * SueldoBruto) / 100
SueldoNeto = SueldoBruto - Descuento
else:
SueldoNeto = SueldoBruto - Descuento
print(SueldoNeto)
|
0e2fdf005ef3b0e84ca1c81860791587d33c6565 | PlumpMath/designpatterns-428 | /Builder/meal_builder.py | 741 | 3.53125 | 4 | #!/usr/bin/env python
from meal import Meal
from veg_burger import VegBurger
from chicken_burger import ChickenBurger
from pepsi import Pepsi
from coke import Coke
class MealBuilder(object):
"""Meal builder class implementing the builder design pattern"""
def prepare_veg_meal(self):
"""Make vegetarian meal builder method
Returns:
vegetarian meal
"""
vmeal = Meal()
vmeal.add_item(VegBurger())
vmeal.add_item(Pepsi())
print "vegetarian meal created"
return vmeal
def prepare_non_veg_meal(self):
"""Make non-vegetarian meal builder
Returns:
non-vegetarian meal
"""
nvmeal = Meal()
nvmeal.add_item(ChickenBurger())
nvmeal.add_item(Coke())
print "non-vegetarian meal created"
return nvmeal
|
6ca38d71be119328a5280bae0cb8b0802c8f3440 | duanluyun/SolutionsOfLeetCode | /101. Symmetric Tree.py | 1,208 | 3.703125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root==None:
return True
res1=[]
res1=self.LeftMiddleRight(root,res1)
res2=[]
res2=self.RightMiddleLeft(root,res2)
return res1==res2
def LeftMiddleRight(self,root,res):
if root==None:
return
if root.left==None and root.right==None:
res.append(root.val)
return res
if root.left:
self.LeftMiddleRight(root.left,res)
res.append(root.val)
if root.right:
self.LeftMiddleRight(root.right,res)
return res
def RightMiddleLeft(self,root,res):
if root==None:
return
if root.left==None and root.right==None:
res.append(root.val)
return res
if root.right:
self.RightMiddleLeft(root.right,res)
res.append(root.val)
if root.left:
self.RightMiddleLeft(root.left,res)
return res
|
27d3160bffb2127e4937c592285a30925204f26e | erjan/coding_exercises | /lintcode/uncommon_word_from_two_sentences.py | 1,050 | 3.796875 | 4 | '''
We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
'''
from typing import (
List,
)
from collections import Counter
class Solution:
"""
@param a: Sentence A
@param b: Sentence B
@return: Uncommon Words from Two Sentences
"""
def uncommon_from_sentences(self, a: str, b: str) -> List[str]:
# Write your code here.
res = []
alist = a.split(' ')
blist = b.split(' ')
dic = {}
for i in alist:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
for i in blist:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
for key in dic.keys():
if dic[key] == 1:
res.append(key)
return res
|
23d6efee0e353a5b94b9613eeef61138fdc56d24 | thinkerston/curso-em-video-python3 | /mundo-01/exercicio-004.py | 183 | 3.640625 | 4 | ''' Crie um programa que leia algo pelo teclado e mostre o seu tipo primitivo e todas as informações possiveis sobre ela'''
reader = input('Digite algo: ')
print(type(reader))
|
1cab54dbca77789531351e03942f125e88d10d75 | aCoffeeYin/pyreco | /repoData/profjsb-python-bootcamp/allPythonContent.py | 94,398 | 3.609375 | 4 | __FILENAME__ = b1sol
## solutions to the breakout #1 (Day 1)
sent = ""
while True:
newword = raw_input("Please enter a word in the sentence (enter . ! or ? to end.): ")
if newword == "." or newword == "?" or newword == "!":
if len(sent) > 0:
# get rid of the nasty space we added in
sent = sent[:-1]
sent += newword
break
sent += newword + " "
print "...currently: " + sent
print "--->" + sent
### created by Josh Bloom at UC Berkeley, 2010,2012,2013 (ucbpythonclass+bootcamp@gmail.com)
########NEW FILE########
__FILENAME__ = breakout1
## solutions to the breakout #1 (Day 1)
sent = ""
while True:
newword = raw_input("Please enter a word in the sentence (enter . ! or ? to end.): ")
if newword == "." or newword == "?" or newword == "!":
if len(sent) > 0:
# get rid of the nasty space we added in
sent = sent[:-1]
sent += newword
break
sent += newword + " "
print "...currently: " + sent
print "--->" + sent
### created by Josh Bloom at UC Berkeley, 2010,2012 (ucbpythonclass+bootcamp@gmail.com)
########NEW FILE########
__FILENAME__ = breakout2
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# <p class="title">Breakout 2 Solutions</p>
#
# ### First, copy over the airport and flight information from [airline.py](https://raw.github.com/profjsb/python-bootcamp/master/DataFiles_and_Notebooks/02_AdvancedDataStructures/airline.py). ###
airports = {"DCA": "Washington, D.C.", "IAD": "Dulles", "LHR": "London-Heathrow", \
"SVO": "Moscow", "CDA": "Chicago-Midway", "SBA": "Santa Barbara", "LAX": "Los Angeles",\
"JFK": "New York City", "MIA": "Miami", "AUM": "Austin, Minnesota"}
# airline, number, heading to, gate, time (decimal hours)
flights = [("Southwest",145,"DCA",1,6.00),("United",31,"IAD",1,7.1),("United",302,"LHR",5,6.5),\
("Aeroflot",34,"SVO",5,9.00),("Southwest",146,"CDA",1,9.60), ("United",46,"LAX",5,6.5),\
("Southwest",23,"SBA",6,12.5),("United",2,"LAX",10,12.5),("Southwest",59,"LAX",11,14.5),\
("American", 1,"JFK",12,11.3),("USAirways", 8,"MIA",20,13.1),("United",2032,"MIA",21,15.1),\
("SpamAir",1,"AUM",42,14.4)]
# Sort the list of flights.
flights.sort()
# Print out the header. the \t character prints a tab.
print "Flight \tDestination\t\tGate\tTime"
print "-"*53 #53 instances of the "-" character
# Loop through each of the flight tuples in the sorted list
# Recall that each tuple contains the elements: (airline, number, destination lookup code, gate, time)
for flight in flights:
# Use the dest lookup code (3rd element of the flight tuple) to get the full destination string from the airports dict
dest = airports[flight[2]]
dest += " "*(20 - len(dest)) # add the appropriate amount of whitespace after the Destination string
# Print the nicely formatted string. Don't forget to convert int and float types to strings using str()
print flight[0] + " " + str(flight[1]) + "\t" + dest + "\t" + str(flight[3]) + "\t" + str(flight[4])
# Sorting by Departure Time
# ### Sorting the information by time requires a bit more coding. ###
# First, we create a new list, time_ordered_flights, which initially just contains the first element of the list flights.
# Create a new list, time_ordered, which initially just contains the first element of the list flights
time_ordered_flights = [flights[0]]
print time_ordered_flights
# We then loop through the remaining flights and insert it into the proper
# position in time_ordered_flights by comparing the time element in each flight
# tuple (at the fifth index position).
# We determine where the current flight belongs by manually comparing the times
# of the flights already added to time_ordered_flights. (This is really
# trivial with lambda functions, which you'll learn later.)
# Iterate through each of the remaining elements in flights to see where it
# should go in the sorted list
for flight in flights[1:]:
# Does it belong in the beginning?
# is current flight's time less than the time in the first list element?
if flight[4] < time_ordered_flights[0][4]:
# insert the flight tuple at position 0 in the list
time_ordered_flights.insert(0,flight)
continue
## ... or the end?
# is current flight's time greater than the time in the last list element?
if flight[4] > time_ordered_flights[-1][4]:
# append the flight tuple to the end of the list
time_ordered_flights.append(flight)
continue
## Or is it in the middle?
# Loop through each element and see if the current flight is between two adjacent ones
## note that range(N) returns a list [0, 1, ... , N-1]
for i in range(len(time_ordered_flights) - 1):
if flight[4] >= time_ordered_flights[i][4] and flight[4] <= time_ordered_flights[i+1][4]:
time_ordered_flights.insert(i+1,flight) # insert the flight tuple at position i+1 in the list
break
print "Flight \tDestination\t\tGate\tTime"
print "-"*53
for flight in time_ordered_flights:
dest = airports[flight[2]]
dest += " "*(20 - len(dest))
print flight[0] + " " + str(flight[1]) + "\t" + dest + "\t" + str(flight[3]) + "\t" + str(flight[4])
# ### One line sorting solution. ###
# We can use the operator.itemgetter() function as the key in sort and sort by the time (4th) element.
import operator
flights.sort(key=operator.itemgetter(4))
print "Flight \tDestination\t\tGate\tTime"
print "-"*53
for flight in flights:
dest = airports[flight[2]]
dest += " "*(20 - len(dest))
print flight[0] + " " + str(flight[1]) + "\t" + dest + "\t" + str(flight[3]) + "\t" + str(flight[4])
# Alternate printing solution
print "%.20s %.20s %.6s %.5s" % ("Flight"+20*' ', "Destination"+20*' ', "Gate"+20*' ', "Time"+20*' ')
print "-"*53
for flight in flights:
print "%.20s %.20s %.6s %.5s" % (flight[0] + ' ' + str(flight[1])+20*' ', airports[flight[2]]+20*' ', str(flight[3])+20*' ', str(flight[4])+20*' ')
########NEW FILE########
__FILENAME__ = talktools
"""Tools to style a talk."""
from IPython.display import HTML, display, YouTubeVideo
def prefix(url):
prefix = '' if url.startswith('http') else 'http://'
return prefix + url
def simple_link(url, name=None):
name = url if name is None else name
url = prefix(url)
return '<a href="%s" target="_blank">%s</a>' % (url, name)
def html_link(url, name=None):
return HTML(simple_link(url, name))
# Utility functions
def website(url, name=None, width=800, height=450):
html = []
if name:
html.extend(['<div class="nb_link">',
simple_link(url, name),
'</div>'] )
html.append('<iframe src="%s" width="%s" height="%s">' %
(prefix(url), width, height))
return HTML('\n'.join(html))
def nbviewer(url, name=None, width=800, height=450):
return website('nbviewer.ipython.org/url/' + url, name, width, height)
# Load and publish CSS
style = HTML(open('style.css').read())
display(style)
########NEW FILE########
__FILENAME__ = age
#!/usr/bin/env python
"""
PYTHON BOOT CAMP BREAKOUT3 SOLUTION;
created by Josh Bloom at UC Berkeley, 2010
(ucbpythonclass+bootcamp@gmail.com)
modified by Katy Huff at UC Berkeley, 2013
"""
# First, we want to import datetime, which is a python module for dates
# and times and such.
import datetime
# Next, we want to use datetime.datetime() to create a variable representing
# when John Cleese was born.
# Note that utcnow() gives the universal time, while .now() gives the
# local time. We're ignoring timezone stuff here.
born = datetime.datetime(1939, 10, 27)
# Then use datetime.datetime.now() to create a variable representing now.
now = datetime.datetime.now()
# Next, subtract the two, forming a new variable, which will be a
# datetime.timedelta() object.
cleese_age = now - born
# Finally, print that variable.
print cleese_age
# Grab just the days :
print "days John Cleese has been alive : ", cleese_age.days
# There is no hours data member, so let's multiply to find the hours :
print "hours John Cleese has been alive : ", cleese_age.days * 24
# What will be the date in 1000 days from now?
td = datetime.timedelta(days=1000)
# Print it.
print "in 1000 days it will be ", now + td # this is a datetime object
########NEW FILE########
__FILENAME__ = age1
#!/usr/bin/env python
"""
PYTHON BOOT CAMP BREAKOUT3 SOLUTION;
created by Josh Bloom at UC Berkeley, 2010
(ucbpythonclass+bootcamp@gmail.com)
modified by Katy Huff at UC Berkeley, 2013
"""
import datetime
import sys
def days_from_now(ndays):
"""Returns the date ndays from now"""
now = datetime.datetime.now()
new = now + datetime.timedelta(int(ndays))
return "in " + str(ndays) + " days the date will be : " + str(new)
def days_since(year, month, day):
"""Returns a string reporting the number of days since some time"""
now = datetime.datetime.now()
then = datetime.datetime(year, month, day)
diff = now - then
return "days since then . . . " + str(diff.days)
if __name__ == "__main__":
"""
Executed only if run from the command line.
call with
ageI.py <year> <month> <day>
to list the days since that date
or
ageI.py <days>
to list the dat in some number of days
"""
if len(sys.argv) == 2 :
result = days_from_now(int(sys.argv[1]))
elif len(sys.argv) == 4 :
year = int(sys.argv[1])
month = int(sys.argv[2])
day = int(sys.argv[3])
result = days_since(year, month, day)
else :
result = "Error : don't know what to do with "+repr(sys.argv[1:])
print result
########NEW FILE########
__FILENAME__ = Breakout6Solution
"""
PYTHON BOOT CAMP ADVANCED STRINGS BREAKOUT SOLUTION;
created by Adam Morgan at UC Berkeley, 2010 (ucbpythonclass+bootcamp@gmail.com)
"""
#import regular expressions
import re
import sys
def reverse_extension(filename):
'''Given a filename, find and reverse the extension at the end'''
# First split the filename string by periods. The last item in the
# resultant list (index -1) is assumed to be the extension.
extension = filename.split('.')[-1]
# Now let's strip off this old extension from the original filename
base_name = filename.rstrip(extension)
# And reverse the extension:
r_extension = extension[::-1]
# Now append the reversed extension to the base
return base_name + r_extension
def count_occurances(filename, substring):
''' Count all occurances of the substring in the file'''
my_file = open(filename,'r')
string_file = my_file.read()
count = string_file.count(substring)
my_file.close()
return count
def find_and_halve_numbers(line):
''' Find all occurances of numbers in a line, and divide them by 2
Note! We're using regular expressions here to find the groups of numbers.
This is complex and you aren't expected to know how to do this. The
rest of the function is straightforward, however.
Another possible solution would be to split each line word by word
with split() and test whether each "word" is a number
'''
split_line = re.split("(\d+)",line)
new_line = ''
for item in split_line:
if item.isdigit():
# If the string contains only digits, convert to integer, divide by 2
item = str(int(item)/2)
new_line += item
return new_line
def do_operations(filename):
"""Given a file, perform the following operations:
1) Reverse the extension of the filename
2) Delete every other line
3) change occurance of words:
love -> hate
not -> is
is -> not
4) sets every number to half its original value
5) count the number of words "astrology" and "physics"
"""
# Open file for reading
orig_file = open(filename,'r')
# Get new filename for writing
new_filename = reverse_extension(filename)
new_file = open(new_filename,'w')
index = 0
# Loop over every line in the file
for line in orig_file.readlines():
index += 1
# if we're on an odd numbered line, perform operations and write
# (this effectively deletes every other line)
if index%2 == 1:
# make the desired replacements
newline = line.replace(' love ',' hate ')
# make temp_is string so we don't overwrite all new instances of 'is'
newline = newline.replace(' not ',' temp_is ')
newline = newline.replace(' is ',' not ')
newline = newline.replace(' temp_is ',' is ')
# Divide all numbers by 2
newline = find_and_halve_numbers(newline)
# Write new line
new_file.write(newline)
print 'There are %i occurances of astrology and %i occurances of physics' % \
(count_occurances(filename,'astrology'),count_occurances(filename,'physics'))
orig_file.close()
new_file.close()
print 'Wrote %s' % (new_filename)
if __name__ == "__main__":
if len(sys.argv) == 2:
do_operations(sys.argv[1])
else:
print "dont know what to do with", repr(sys.argv[1:])
########NEW FILE########
__FILENAME__ = Breakout7Solution
import numpy as np
from random import randint
def generate_function(X,Y, voc, max_try=1000000, max_chars=10):
''' find the analytic form that describes Y on X '''
tries = []
for n in xrange(max_try):
## make some random function using the vocabulary
thefunc = "".join([voc[randint(0,len(voc)-1)] for x in range(randint(1,max_chars))])
## construct the python statement, declaring the lambda function and evaluating it on X
mylam = "y = lambda x: " + thefunc + "\n"
mylam += "rez = y(X)"
try:
## this may be volitile so be warned!
## Couch everything in error statements, and
## simply throw away functions that aren't reasonable
exec(mylam)
except:
continue
try:
tries.append( ( (abs(rez - Y).sum()) ,thefunc))
if (abs(rez - Y)).sum() < 0.0001:
## we got something really close
break
except:
pass
del rez
del y
### numpy arrays handle NaN and INF gracefully, so we put
### answer into an array before sorting
a = np.array(tries,dtype=[('rez','f'),("func",'|S10')])
a.sort()
if a[0]["rez"] < 0.001:
print "took us ntries = {0}, but we eventually found that '{1}' is functionally equivalent to f(X)".format(n,a[0]["func"])
else:
print "after ntries = {0}, we found that '{1}' is close to f(x) (metric = {2})".format(n,a[0]["func"],a[0]["rez"])
return a[0]
voc = ["x","x"," ","+","-","*","/","1","2","3"]
x_array = np.arange(-3,3,0.4)
real_function = x_array**2 + x_array
generate_function(x_array, real_function, voc, 100)
########NEW FILE########
__FILENAME__ = OOP_I_solutions
###
# Procedural approach
import math
def perimeter(polygon):
"""Given a list of vector vertices (in proper order),
returns the perimeter for the associated polygon."""
sum = 0
for i in range(len(polygon)):
vertex1 = polygon[i]
vertex2 = polygon[(i+1) % len(polygon)]
distance = math.sqrt(pow(vertex2[0]-vertex1[0],2) + \
pow(vertex2[1]-vertex1[1],2))
sum += distance
return sum
perimeter([[0,0],[1,0],[1,1],[0,1]]) # Returns 4.0
perimeter([[0,-2],[1,1],[3,3],[5,1],[4,0],[4,-3]])
# Returns 17.356451097651515
###
# Object-oriented approach
class Polygon:
"""A new class named Polygon."""
def __init__(self, vertices=[]):
self.vertices = vertices
print "(Creating an instance of the class Polygon)"
def perimeter(self):
sum = 0
for i in range(len(self.vertices)):
vertex1 = self.vertices[i]
vertex2 = self.vertices[(i+1) % len(self.vertices)]
distance = math.sqrt(pow(vertex2[0]-vertex1[0],2)+\
pow(vertex2[1]-vertex1[1],2))
sum += distance
return sum
a = Polygon([[0,-2],[1,1],[3,3],[5,1],[4,0],[4,-3]])
a.perimeter()
# Returns 17.356451097651515
########NEW FILE########
__FILENAME__ = hw2sol
"""
This is a solution to the Homework #2 of the Python Bootcamp
The basic idea is to create a simulation of the games Chutes and Ladders,
to gain some insight into how the game works and, more importantly,
to exercise new-found skills in object oriented programming within Python.
The setup for the homework is given here:
http://tinyurl.com/homework2-bootcamp
Usage:
python hw2sol.py
UC Berkeley
J. Bloom 2013
"""
import random
import numpy as np
## here's a layout of the board
## I just made this by hand looking at the picture of the board:
## http://i.imgur.com/Sshgk4X.jpg
## the key is the starting point, the value is the ending point
board = {1: 38, 4: 14, 9: 31, 16: 6, 21: 42, 28: 84, 36: 44, 48: 26, 49: 11,
51: 67, 56: 53, 62: 19, 64: 60, 71: 91, 80: 100, 87: 24, 93: 73, 95: 75, 98: 78}
class Pawn(object):
""" representation of a player in the game."""
def __init__(self,run_at_start=False):
## start off at the beginning
self.loc = 0
self.path = []
self.n_throws = 0
self.n_chutes = 0
self.n_ladders = 0
self.reached_end = False
if run_at_start:
self.play_till_end()
def play_till_end(self):
""" keep throwing new random dice rolls until the player gets to 100 """
while not self.reached_end:
## throw a spin
throw = random.randint(1,6)
self.n_throws += 1
# if we're near the end then we have to get exactly 100
if throw + self.loc > 100:
## oops. Can't move.
self.path.append(self.loc)
continue
self.loc += throw
# keep track of the path is took to get there
self.path.append(self.loc)
if board.has_key(self.loc):
## new location due to chute or ladder
if self.loc > board[self.loc]:
self.n_chutes += 1
else:
self.n_ladders += 1
self.loc = board[self.loc]
self.path.append(self.loc)
if self.loc == 100:
self.reached_end = True
def __str__(self):
""" make a nice pretty representation of the player attributes """
s = """n_throws = %i ; n_ladders = %i ; n_chutes = %i
path = %s""" % (self.n_throws,self.n_ladders, self.n_chutes, str(self.path))
return s
class Game(object):
""" simulate a game between a certain number of players """
def __init__(self,n_players=2):
self.n_players = n_players
self.run()
def run(self):
""" actually run the Game, by making a new list of Pawns
we play ALL Pawns to the end...this has the advantage of
allowing us to run multiple simulations of Pawn movements
and keep track of 1st, 2nd, 3rd, ... place winners.
"""
self.pawns = [Pawn(run_at_start=True) for i in range(self.n_players)]
self.settle_winner()
def settle_winner(self):
""" go through the Game and figure out who won"""
throws = [x.n_throws for x in self.pawns]
self.min_throws, self.max_throws = min(throws), max(throws)
## if it's the same number, then make sure the Pawn that went first wins
self.winning_order = [x for x,y in sorted(enumerate(throws), key = lambda x: (x[1],x[0]))]
self.throws = throws
## what's the first throw value and how long did it take to get to 100?
self.first_throw_length = [(x.path[0],x.n_throws) for x in self.pawns ]
class Simulate(object):
""" Play multiple games and spit out some of the answers to the homework questions,
basically high-level statistics
"""
def __init__(self,num_games = 1000, num_players = 4):
self.num_games = num_games
self.num_players = num_players
def run(self):
self.shortest_path = []
self.longest_path = []
#self.winner_times = dict( [(i,0) for i range(num_players)] )
self.all_lengths = []
self.first_throws = dict( [(i+1,[]) for i in range(6)])
self.first_turn_wins = []
# NB: I'm running these games in serial. Would be nice to make use of my
# multicore environment to do this instead. Or even a cluster. Soon....
# TODO: Parallelize me!
for i in range(self.num_games):
g = Game(n_players=self.num_players)
# save the shortest and longest paths
if self.shortest_path == [] or (g.min_throws < len(self.shortest_path)):
self.shortest_path = g.pawns[g.winning_order[0]].path
if self.longest_path == [] or (g.max_throws > len(self.longest_path)):
self.longest_path = g.pawns[g.winning_order[-1]].path
## save all the lengths
self.all_lengths.extend(g.throws)
# save the first moves
for ft in g.first_throw_length:
#print ft
self.first_throws[ft[0]].append(ft[1])
# save the winning orders:
self.first_turn_wins.append(int(g.winning_order[0] == 0))
def __str__(self):
avg_throws = np.array(self.all_lengths).mean()
s = "1. What is the average number of turns a player must take before she gets to 100?\n"
s += "%.2f\n\n" % avg_throws
s+= "2. What is the minimal number of turns in the simulation before getting to 100?\n"
s+= str(len(self.shortest_path) ) + "\n"
s+= "What was the sequence of values in the spin in each turn?\n"
s+= str(self.shortest_path) +"\n"
s+= "What was the longest number of turns?\n"
s+= str(len(self.longest_path)) + "\n\n"
s+= "3. What is the ordering of initial spins that gives, on average, the quickest path to 100?\n"
tmp= [(np.array(self.first_throws[t]).mean(), t) for t in self.first_throws.keys()]
tmp.sort()
s+= str(tmp) + " \n"
s+= "What about the median?\n"
tmp= [(np.median(np.array(self.first_throws[t])), t) for t in self.first_throws.keys()]
tmp.sort()
s+= str(tmp) + " \n\n"
s+= "4. What is the probability that someone who goes first will win in a 2 and 4 person game?\n"
s+= str(float(np.array(self.first_turn_wins).sum())/len(self.first_turn_wins)) + "\n"
s+= " random expectation is %f\n" % (1.0/self.num_players)
return s
def test_Pawn():
p = Pawn()
p.play_till_end()
print p
def test_Game():
g = Game(4)
g.settle_winner()
if __name__ == "__main__":
print "HW#2 solutions"
print "UC Berkeley Python Bootcamp 2013"
nsim = 10000
for n_players in [2,4]:
print "*"*60
print "Running a 10000 game simulation with {0} players".format(n_players)
s = Simulate(num_games =nsim, num_players=n_players)
s.run()
print s
########NEW FILE########
__FILENAME__ = hello
print "Hello World!"
########NEW FILE########
__FILENAME__ = temp1
### PYTHON BOOT CAMP EXAMPLE;
### created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
### all rights reserved 2012 (c)
### https://github.com/profjsb/python-bootcamp
# set some initial variables. Set the initial temperature low
faren = -1000
# we dont want this going on forever, let's make sure we cannot have too many attempts
max_attempts = 6
attempt = 0
while faren < 100:
# let's get the user to tell us what temperature it is
newfaren = float(raw_input("Enter the temperature (in Fahrenheit): "))
if newfaren > faren:
print "It's getting hotter"
elif newfaren < faren:
print "It's getting cooler"
else:
# nothing has changed, just continue in the loop
continue
faren = newfaren # now set the current temp to the new temp just entered
attempt += 1 # bump up the attempt number
if attempt >= max_attempts:
# we have to bail out
break
if attempt >= max_attempts:
# we bailed out because of too many attempts
print "Too many attempts at raising the temperature."
else:
# we got here because it's hot
print "it's hot here, man."
########NEW FILE########
__FILENAME__ = temp2
### PYTHON BOOT CAMP EXAMPLE;
### created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
### all rights reserved 2012 (c)
### https://github.com/profjsb/python-bootcamp
# set some initial variables. Set the initial temperature low
faren = -1000
# we dont want this going on forever, let's make sure we cannot have too many attempts
max_attempts = 6
attempt = 0
while faren < 100 and (attempt < max_attempts):
# let's get the user to tell us what temperature it is
newfaren = float(raw_input("Enter the temperature (in Fahrenheit): "))
if newfaren > faren:
print "It's getting hotter"
elif newfaren < faren:
print "It's getting cooler"
else:
# nothing has changed, just continue in the loop
continue
faren = newfaren
attempt += 1 # bump up the attempt number
if attempt >= max_attempts:
# we bailed out because of too many attempts
print "Too many attempts at raising the temperature."
else:
# we got here because it's hot
print "it's hot here, man."
########NEW FILE########
__FILENAME__ = airline
airports = {"DCA": "Washington, D.C.", "IAD": "Dulles", "LHR": "London-Heathrow", \
"SVO": "Moscow", "CDA": "Chicago-Midway", "SBA": "Santa Barbara", "LAX": "Los Angeles",\
"JFK": "New York City", "MIA": "Miami", "AUM": "Austin, Minnesota"}
# airline, number, heading to, gate, time (decimal hours)
flights = [("Southwest",145,"DCA",1,6.00),("United",31,"IAD",1,7.1),("United",302,"LHR",5,6.5),\
("Aeroflot",34,"SVO",5,9.00),("Southwest",146,"CDA",1,9.60), ("United",46,"LAX",5,6.5),\
("Southwest",23,"SBA",6,12.5),("United",2,"LAX",10,12.5),("Southwest",59,"LAX",11,14.5),\
("American", 1,"JFK",12,11.3),("USAirways", 8,"MIA",20,13.1),("United",2032,"MIA",21,15.1),\
("SpamAir",1,"AUM",42,14.4)]
########NEW FILE########
__FILENAME__ = getinfo
"""
this is a demo of some methods used in the os and sys.
usage:
import getinfo
getinfo.getinfo()
getinfo.getinfo("/tmp/")
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
"""
import os
import sys
def getinfo(path="."):
"""
Purpose: make simple use of os and sys modules
Input: path (default = "."), the directory you want to list
"""
print "You are using Python version ",
print sys.version
print "-" * 40
print "Files in the directory " + str(os.path.abspath(path)) + ":"
for f in os.listdir(path): print f
########NEW FILE########
__FILENAME__ = modfun
#!/usr/bin/env python
"""
Some functions written to demonstrate a bunch of concepts like modules, import
and command-line programming
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
"""
import os
import sys
def getinfo(path=".",show_version=True):
"""
Purpose: make simple us of os and sys modules
Input: path (default = "."), the directory you want to list
"""
if show_version:
print "-" * 40
print "You are using Python version ",
print sys.version
print "-" * 40
print "Files in the directory " + str(os.path.abspath(path)) + ":"
for f in os.listdir(path): print " " + f
print "*" * 40
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
"""
Purpose: does a simple operation on two numbers.
Input: We expect x,y are numbers
multiplier is also a number (a float is preferred) and is optional.
It defaults to 1.0. You can also specify a small greeting as a string.
Output: return x + y times the multiplier
"""
if greetings is not None:
print greetings
return (x + y)*multiplier
if __name__ == "__main__":
"""
Executed only if run from the command line.
call with
modfun.py <dirname> <dirname> ...
If no dirname is given then list the files in the current path
"""
if len(sys.argv) == 1:
getinfo(".",show_version=True)
else:
for i,dir in enumerate(sys.argv[1:]):
if os.path.isdir(dir):
# if we have a directory then operate on it
# only show the version info if it's the first directory
getinfo(dir,show_version=(i==0))
else:
print "Directory: " + str(dir) + " does not exist."
print "*" * 40
########NEW FILE########
__FILENAME__ = numfun1
"""
small demo of modules
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
"""
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
"""
Purpose: does a simple operation on two numbers.
Input: We expect x,y are numbers
multiplier is also a number (a float is preferred) and is optional.
It defaults to 1.0. You can also specify a small greeting as a string.
Output: return x + y times the multiplier
"""
if greetings is not None:
print greetings
return (x + y)*multiplier
########NEW FILE########
__FILENAME__ = numfun2
"""
small demo of modules
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
"""
print "numfun2 in the house"
x = 2
s = "spamm"
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
"""
Purpose: does a simple operation on two numbers.
Input: We expect x,y are numbers
multiplier is also a number (a float is preferred) and is optional.
It defaults to 1.0. You can also specify a small greeting as a string.
Output: return x + y times the multiplier
"""
if greetings is not None:
print greetings
return (x + y)*multiplier
########NEW FILE########
__FILENAME__ = numop1
"""
Some functions written to demonstrate a bunch of concepts like modules, import
and command-line programming
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
"""
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
"""
Purpose: does a simple operation on two numbers.
Input: We expect x,y are numbers
multiplier is also a number (a float is preferred) and is optional.
It defaults to 1.0. You can also specify a small greeting as a string.
Output: return x + y times the multiplier
"""
if greetings is not None:
print greetings
return (x + y)*multiplier
########NEW FILE########
__FILENAME__ = checkemail
"""
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2010,2012 (ucbpythonclass+bootcamp@gmail.com)
"""
import string
## let's only allow .com, .edu, and .org email domains
allowed_domains = ["com","edu","org"]
## let's nix all the possible bad characters
disallowed = string.punctuation.replace(".","")
while True:
res = raw_input("Enter your full email address: ")
res = res.strip() # get rid of extra spaces from a key-happy user
if res.count("@") != 1:
print "missing @ sign or too many @ signs"
continue
username,domain = res.split("@")
## let's look at the domain
if domain.find(".") == -1:
print "invalid domain name"
continue
if domain.split(".")[-1] not in allowed_domains:
## does this end as it should?
print "invalid top-level domain...must be in " + ",".join(allowed_domains)
continue
goodtogo = True
for s in domain:
if s in disallowed:
print "invalid character " + s
## cannot use continue here because then we only continue the for loop, not the while loop
goodtogo = False
## if we're here then we're good on domain. Make sure that
for s in username:
if s in disallowed:
print "invalid character " + s
goodtogo = False
if goodtogo:
print "valid email. Thank you."
break
########NEW FILE########
__FILENAME__ = tabbify_my_csv
"""
small copy program that turns a csv file into a tabbed file
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2010,2012 (ucbpythonclass+bootcamp@gmail.com)
"""
import os
def tabbify(infilename,outfilename,ignore_comments=True,comment_chars="#;/"):
"""
INPUT: infilename
OUTPUT: creates a file called outfilename
"""
if not os.path.exists(infilename):
return # do nothing if the file isn't there
f = open(infilename,"r")
o = open(outfilename,"w")
inlines = f.readlines() ; f.close()
outlines = []
for l in inlines:
if ignore_comments and (l[0] in comment_chars):
outlines.append(l)
else:
outlines.append(l.replace(",","\t"))
o.writelines(outlines) ; o.close()
########NEW FILE########
__FILENAME__ = OOP_I
# Code for Object-Oriented Programming with Python - Lesson 1
# SBC - 01/12/12
###
# Slide 9 - Bear: Our first Python class
class Bear:
print "The bear class is now defined"
a = Bear
a
# Equates a to the class Bear. Not very useful
a = Bear()
# Creates a new *instance* of the class Bear
###
# Slide 10 - Attributes: Access, Creation, Deletion
a.name
# name attributed has not been defined yet
a.name = "Oski"
a.color = "Brown"
# new attributes are accessed with the "." operator
del(a.name)
# attributes can be deleted as well
a.name
# Throws AttributeError Exception
###
# Slide 11 - Methods: Access, Creation, and (not) Deletion
class Bear:
print "The bear class is now defined."
def say_hello(self):
print "Hello, world! I am a bear."
a = Bear()
# create a new instance of the bear class
a.say_hello
# This provides access to the method itself
a.say_hello()
# This actually executes the method
###
# Slide 12 - The __init__ method
class Bear:
def __init__(self, name):
self.name = name
def say_hello(self):
print "Hello, world! I am a bear."
print "My name is %s." % self.name
a = Bear()
# Now you need to specify one argument to create the Bear class
a = Bear("Yogi")
a.name
a.say_hello()
# Prints desired text
###
# Slide 13 - Scope: self and "class" variables
class Bear:
population = 0
def __init__(self, name):
self.name = name
Bear.population += 1
def say_hello(self):
print "Hello, world! I am a bear."
print "My name is %s." % self.name
print "I am number %i." % Bear.population
a = Bear("Yogi")
# Create a new instance of the Bear class. Needs 1 argument
a.say_hello()
# Prints name and 1st bear
b = Bear("Winnie")
b.say_hello()
# Prints name and 2nd bear
c = Bear("Fozzie")
Bear.say_hello(c)
# Need "self" argument when calling directly from class
###
# Slide 15 - A Zookeeper's Travails I
class Bear:
def __init__(self, name, weight):
self.name = name
self.weight = weight
a = Bear("Yogi", 80)
b = Bear("Winnie", 100)
c = Bear("Fozzie", 115)
# Create three new Bear instances
my_bears = [a, b, c]
# Combine them into a list
total_weight = 0
for z in my_bears:
total_weight += z.weight
# Loop over the list and add to the total weight
total_weight < 300
# The zookeeper only needs to make one trip.
###
# Slide 17 - A Zookeeper's Travails II
class Bear:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self, amount):
self.weight += amount
def hibernate(self):
self.weight /= 1.20
a = Bear("Yogi", 80)
b = Bear("Winnie", 100)
c = Bear("Fozzie", 115)
my_bears=[a, b, c]
a.weight
a.eat(20)
a.weight
# After eating, Yogi gains 20 kg
b.eat(10)
# Winnie eats
c.hibernate()
# Fozzie hibernates`
total_weight = 0
for z in my_bears:
total_weight += z.weight
total_weight < 300
# Now the keeper needs two trips.
###
# Slide 19 - A Zookeeper's Travails III
class Bear:
def __init__(self, name, fav_food, friends=[]):
self.name = name
self.fav_food = fav_food
self.friends = friends
def same_food(self):
for friend in self.friends:
if (friend.fav_food == self.fav_food):
print "%s and %s both like %s" % \
(self.name, friend.name, self.fav_food)
a = Bear("Yogi", "Picnic baskets")
b = Bear("Winnie", "Honey")
c = Bear("Fozzie", "Frog legs")
###
# Slide 20 - A Zookeeper's Travails III
c.friends # empty list
c.fav_food # 'Frog legs'
c.same_food() # Returns None since no friends
c.friends = [a, b] # Now Fozzie has two friends
c.same_food() # But still no overlap in food tastes
c.fav_food = "Honey" # Fozzie now likes honey
c.same_food() # And shares same food with Winnie
########NEW FILE########
__FILENAME__ = bear
import datetime
class Bear:
logfile_name = "bear.log"
bear_num = 0
def __init__(self,name):
self.name = name
print " made a bear called %s" % (name)
self.logf = open(Bear.logfile_name,"a")
Bear.bear_num += 1
self.my_num = Bear.bear_num
self.logf.write("[%s] created bear #%i named %s\n" % \
(datetime.datetime.now(),Bear.bear_num,self.name))
self.logf.flush()
def growl(self,nbeep=5):
print "\a"*nbeep
def __del__(self):
print "Bang! %s is no longer." % self.name
self.logf.write("[%s] deleted bear #%i named %s\n" % \
(datetime.datetime.now(),self.my_num,self.name))
self.logf.flush()
# decrement the number of bears in the population
Bear.bear_num -= 1
# dont really need to close because Python will do the garbage collection
# for us. but it cannot hurt to be graceful here.
self.logf.close()
def __str__(self):
return " name = %s bear number = %i (population %i)" % \
(self.name, self.my_num,Bear.bear_num)
"""
print Bear.__doc__
print Bear.__name__
print Bear.__module__
print Bear.__bases__
print Bear.__dict__
"""
########NEW FILE########
__FILENAME__ = bear1
class Bear:
"""
class to show off addition (and multiplication)
"""
bear_num = 0
def __init__(self,name):
self.name = name
print " made a bear called %s" % (name)
Bear.bear_num += 1
self.my_num = Bear.bear_num
def __add__(self,other):
## spawn a little tike
cub = Bear("progeny_of_%s_and_%s" % (self.name,other.name))
cub.parents = (self,other)
return cub
def __mul__(self,other):
## multiply (as in "go forth and multiply") is really the same as adding
self.__add__(other)
########NEW FILE########
__FILENAME__ = bear2
import datetime
class Bear:
logfile_name = "bear.log"
bear_num = 0
def __init__(self,name):
self.name = name
print " made a bear called %s" % (name)
self.logf = open(Bear.logfile_name,"a")
Bear.bear_num += 1
self.created = datetime.datetime.now()
self.my_num = Bear.bear_num
self.logf.write("[%s] created bear #%i named %s\n" % \
(datetime.datetime.now(),Bear.bear_num,self.name))
self.logf.flush()
def growl(self,nbeep=5):
print "\a"*nbeep
def __del__(self):
print "Bang! %s is no longer." % self.name
self.logf.write("[%s] deleted bear #%i named %s\n" % \
(datetime.datetime.now(),self.my_num,self.name))
self.logf.flush()
# decrement the number of bears in the population
Bear.bear_num -= 1
# dont really need to close because Python will do the garbage collection
# for us. but it cannot hurt to be graceful here.
self.logf.close()
def __str__(self):
age = datetime.datetime.now() - self.created
return " name = %s bear (age %s) number = %i (population %i)" % \
(self.name, age, self.my_num,Bear.bear_num)
"""
print Bear.__doc__
print Bear.__name__
print Bear.__module__
print Bear.__bases__
print Bear.__dict__
"""
########NEW FILE########
__FILENAME__ = catcherr
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error(%i): %s" % (errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
########NEW FILE########
__FILENAME__ = downgradenb
"""Simple utility script for semi-gracefully downgrading v3 notebooks to v2"""
import io
import os
import sys
from IPython.nbformat import current
def heading_to_md(cell):
"""turn heading cell into corresponding markdown"""
cell.cell_type = "markdown"
level = cell.pop('level', 1)
cell.source = '#'*level + ' ' + cell.source
def raw_to_md(cell):
"""let raw passthrough as markdown"""
cell.cell_type = "markdown"
def downgrade(nb):
"""downgrade a v3 notebook to v2"""
if nb.nbformat != 3:
return nb
nb.nbformat = 2
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'heading':
heading_to_md(cell)
elif cell.cell_type == 'raw':
raw_to_md(cell)
return nb
def downgrade_ipynb(fname):
base, ext = os.path.splitext(fname)
newname = base+'.v2'+ext
print "downgrading %s -> %s" % (fname, newname)
with io.open(fname, 'r', encoding='utf8') as f:
nb = current.read(f, 'json')
nb = downgrade(nb)
with open(newname, 'w') as f:
current.write(nb, f, 'json')
if __name__ == '__main__':
map(downgrade_ipynb, sys.argv[1:])
########NEW FILE########
__FILENAME__ = subclass
class Plant:
num_known = 0
def __init__(self,common_name,latin_name=None):
self.latin_name = latin_name
self.common_name = common_name
Plant.num_known += 1
def __str__(self):
return "I am a plant (%s)!" % self.common_name
class Flower(Plant):
has_pedals = True
def __init__(self,common_name,npedals=5,pedal_color="red",latin_name=None):
## call the __init__ of the
Plant.__init__(self,common_name,latin_name=latin_name)
self.npedals=5
self.pedal_color = pedal_color
def __str__(self):
return "I am a flower (%s)!" % self.common_name
class A:
def __init__(self):
print "A"
class B(A):
def __init__(self):
A.__init__(self)
print "B"
########NEW FILE########
__FILENAME__ = animals_0
"""
Test Driven Development using animals and Nose testing.
"""
def test_moves():
assert Animal('owl').move() == 'fly'
assert Animal('cat').move() == 'walk'
assert Animal('fish').move() == 'swim'
def test_speaks():
assert Animal('owl').speak() == 'hoot'
assert Animal('cat').speak() == 'meow'
assert Animal('fish').speak() == ''
########NEW FILE########
__FILENAME__ = animals_1
"""
Test Driven Development using animals and Nose testing.
"""
class Animal:
""" This is an animal.
"""
animal_defs = {'owl':{'move':'fly',
'speak':'hoot'},
'cat':{'move':'walk',
'speak':'meow'},
'fish':{'move':'swim',
'speak':''}}
def __init__(self, name):
self.name = name
def move(self):
return self.animal_defs[self.name]['move']
def speak(self):
return self.animal_defs[self.name]['speak']
def test_moves():
assert Animal('owl').move() == 'fly'
assert Animal('cat').move() == 'walk'
assert Animal('fish').move() == 'swim'
def test_speaks():
assert Animal('owl').speak() == 'hoot'
assert Animal('cat').speak() == 'meow'
assert Animal('fish').speak() == ''
########NEW FILE########
__FILENAME__ = animals_2
"""
Test Driven Development using animals and Nose testing.
"""
from random import random
class Animal:
""" This is an animal
"""
animal_defs = {'owl':{'move':'fly',
'speak':'hoot'},
'cat':{'move':'walk',
'speak':'meow'},
'fish':{'move':'swim',
'speak':''}}
def __init__(self, name):
self.name = name
def move(self):
return self.animal_defs[self.name]['move']
def speak(self):
return self.animal_defs[self.name]['speak']
def test_moves():
assert Animal('owl').move() == 'fly'
assert Animal('cat').move() == 'walk'
assert Animal('fish').move() == 'swim'
def test_speaks():
assert Animal('owl').speak() == 'hoot'
assert Animal('cat').speak() == 'meow'
assert Animal('fish').speak() == ''
def test_dothings_list():
""" Test that the animal does the same number of things as the number of hour-times given.
"""
times = []
for i in xrange(5):
times.append(random() * 24.)
for a in ['owl', 'cat', 'fish']:
assert len(Animal(a).dothings(times)) ==\
len(times)
def test_dothings_with_beyond_times():
for a in ['owl', 'cat', 'fish']:
assert Animal(a).dothings([-1]) == ['']
assert Animal(a).dothings([25]) == ['']
def test_nocturnal_sleep():
""" Test that an owl is awake at night.
"""
night_hours = [0.1, 3.3, 23.9]
noct_behaves = Animal('owl').dothings(night_hours)
for behave in noct_behaves:
assert behave != 'sleep'
########NEW FILE########
__FILENAME__ = animals_3
"""
Test Driven Development using animals and Nose testing.
"""
from random import random
class Animal:
""" This is an animal
"""
animal_defs = {'owl':{'move':'fly',
'speak':'hoot'},
'cat':{'move':'walk',
'speak':'meow'},
'fish':{'move':'swim',
'speak':''}}
def __init__(self, name):
self.name = name
def move(self):
return self.animal_defs[self.name]['move']
def speak(self):
return self.animal_defs[self.name]['speak']
def dothings(self, times):
""" A method which takes a list
of times (hours between 0 and 24) and
returns a list of what the animal is
(randomly) doing.
- Beyond hours 0 to 24: the animal does: ""
"""
out_behaves = []
for t in times:
if (t < 0) or (t > 24):
out_behaves.append('')
elif ((self.name == 'owl') and
(t > 6.0) and (t < 20.00)):
out_behaves.append('sleep')
else:
out_behaves.append( \
self.animal_defs[self.name]['move'])
return out_behaves
def test_moves():
assert Animal('owl').move() == 'fly'
assert Animal('cat').move() == 'walk'
assert Animal('fish').move() == 'swim'
def test_speaks():
assert Animal('owl').speak() == 'hoot'
assert Animal('cat').speak() == 'meow'
assert Animal('fish').speak() == ''
def test_dothings_list():
""" Test that the animal does the same number of things as the number of hour-times given.
"""
times = []
for i in xrange(5):
times.append(random() * 24.)
for a in ['owl', 'cat', 'fish']:
assert len(Animal(a).dothings(times)) ==\
len(times)
def test_dothings_with_beyond_times():
for a in ['owl', 'cat', 'fish']:
assert Animal(a).dothings([-1]) == ['']
assert Animal(a).dothings([25]) == ['']
def test_nocturnal_sleep():
""" Test that an owl is awake at night.
"""
night_hours = [0.1, 3.3, 23.9]
noct_behaves = Animal('owl').dothings(night_hours)
for behave in noct_behaves:
assert behave != 'sleep'
if __name__ == '__main__':
### The above line is Python syntax which defines a
### section that is only used when animals_?.py is either:
# - executed from the shell as an executable script
# - executed from the shell using: python animals_?.py
# - executed using another program, eg: python pdb.py animals_?.py
#
# This section is not used when nose_example1 is imported as a module.
c = Animal('cat')
o = Animal('owl')
f = Animal('fish')
times = []
for i in xrange(10):
times.append(random() * 24.)
times.sort()
c_do = c.dothings(times)
o_do = o.dothings(times)
f_do = f.dothings(times)
for i in xrange(len(times)):
print "time=%3.3f cat=%s owl=%s fish=%s" % ( \
times[i], c_do[i], o_do[i], f_do[i])
########NEW FILE########
__FILENAME__ = doctests_example
def multiply(a, b):
"""
'multiply' multiplies two numbers and returns the result.
>>> multiply(0.5, 1.5)
0.75
>>> multiply(-1, 1)
-1
"""
return a*b + 1
########NEW FILE########
__FILENAME__ = nose_example1
""" Nose Example 1
"""
class Transmogrifier:
""" An important class
"""
def transmogrify(self, person):
""" Transmogrify someone
"""
transmog = {'calvin':'tiger',
'hobbes':'chicken'}
new_person = transmog[person]
return new_person
def test_transmogrify():
TM = Transmogrifier()
for p in ['Calvin', 'Hobbes']:
assert TM.transmogrify(p) != None
def main():
TM = Transmogrifier()
for p in ['calvin', 'Hobbes']:
print p, '-> ZAP! ->', TM.transmogrify(p)
if __name__ == '__main__':
### The above line is Python syntax which defines a
### section that is only used when nose_example1.py is either:
# - executed from the shell as an executable script
# - executed from the shell using: python nose_example1.py
# - executed using another program, eg: python pdb.py nose_example1.py
#
# This section is not used when nose_example1 is imported as a module.
main()
########NEW FILE########
__FILENAME__ = loggin1
import logging
LOG_FILENAME = 'loggin1.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.WARNING)
def make_logs():
logging.debug('This is a debug message')
logging.warning('This is a warning message')
logging.error('This is an error message')
########NEW FILE########
__FILENAME__ = loggin2
import logging
logger = logging.getLogger("some_identifier")
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.stream = open("loggin2.log", 'w')
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
def make_logs():
logger.info("This is an info message")
logger.debug("This is a debug message")
logger.warning("This is a warning message")
logger.error("This is an error message")
########NEW FILE########
__FILENAME__ = my_assertions
def do_string_stuff(val):
assert type(val) == type("")
print ">" + val + "< length:", len(val)
def do_string_stuff_better(val):
val_type = type(val)
assert val_type == type(""), "Given a %s" % (str(val_type))
print ">" + val + "< length:", len(val)
########NEW FILE########
__FILENAME__ = test_simple
"A simple set of tests"
def testTrue():
"Thruth-iness test"
assert True == 1
def testFalse():
"Fact-brication test"
assert False == 0
########NEW FILE########
__FILENAME__ = tryexcept0
def divide_it(x, y):
try:
out = x / y
except:
print ' Divide by zero!'
out = None
return out
########NEW FILE########
__FILENAME__ = tryexcept1
import traceback
def example1():
try:
raise SyntaxError, "example"
except:
traceback.print_exc()
print "...still running..."
def example2():
""" Here we have access to the (filename, line number, function name, text)
of each element in the Traceback stack.
"""
try:
raise SyntaxError
except:
stack_list = traceback.extract_stack()
for (filename, linenum, functionname, text) in stack_list:
print "%s:%d %s()" % (filename, linenum, functionname)
print "...still running..."
########NEW FILE########
__FILENAME__ = appetite
#! /usr/bin/env python
# this file was originall written by Brad Cenko for 2012 UCB Python Bootcamp
# modified and extended by Paul Ivanov for the 2013 UCB Python Bootcamp
import sqlite3, os, smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import NothingToSeeHere # Email password stored in this (private) file
from NothingToSeeHere import username as email_addr
# Global variables
piDB = "piDB.sql"
# Need to change this to a path you can write to
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger(__name__)
###########################################################################
def create_friends_table(filename=piDB):
"""Creates sqlite database to store basic information on my buddies"""
conn = sqlite3.connect(filename)
c = conn.cursor()
c.execute('''CREATE TABLE CYCLISTS (f_name text, l_name text,
email text, status text)''')
ins_tpl= 'INSERT INTO CYCLISTS VALUES ("%s", "%s", "%s", "%s")'
l = []
l += [ins_tpl % ( "Paul", "Ivanov", email_addr, 'committed')]
l += [ins_tpl % ( "Dan", "Coates", email_addr, 'committed')]
l += [ins_tpl % ( "James", "Gao", email_addr, 'casual')]
l += [ins_tpl % ( "Sara", "Emery", email_addr, 'committed')]
l += [ins_tpl % ( "Jonathan", "Giffard", email_addr, 'weekender')]
l += [ins_tpl % ( "Janet", "Young", email_addr, 'weekender')]
for s in l:
print s
c.execute(s)
conn.commit()
c.close()
return
############################################################################
def retrieve_random_cyclist(filename=piDB, kind="committed"):
"""Returns the name and email address of a random cyclist"""
conn = sqlite3.connect(filename)
c = conn.cursor()
c.execute("SELECT f_name, l_name, email FROM CYCLISTS WHERE status" + \
" = '%s' ORDER BY RANDOM() LIMIT 1" % kind)
row = c.fetchall()
conn.commit()
c.close()
if len(row)== 0:
raise ValueError("There are no people who are '%s'" % kind )
return [row[0][0], row[0][1], row[0][2]]
###########################################################################
###############################################################################
def email_cyclist(address, f_name, l_name, myemail=NothingToSeeHere.username):
"""Generate and send an email to address with a request to observe
the given supernova."""
# Create the message
msg = MIMEMultipart()
msg["From"] = myemail
msg["To"] = address
msg["Subject"] = "Let's go for a ride, %s" % f_name
# Write the body, making sure all variables are defined.
msgstr = r"""Hey %s,
Wanna go for a bike ride later on today?
best,
pi
--
_
/ \
A* \^ -
,./ _.`\\ / \
/ ,--.S \/ \
/ `"~,_ \ \
__o ?
_ \<,_ /:\
--(_)/-(_)----.../ | \
--------------.......J
Paul Ivanov
http://pirsquared.org
""" % f_name
msg.attach(MIMEText(msgstr))
# Configure the outgoing mail server
log.info("sending out email")
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.starttls()
mailServer.login(myemail, NothingToSeeHere.password)
# Send the message
mailServer.sendmail(myemail, address, msg.as_string())
mailServer.close()
return
###############################################################################
def go_cycling(filename=piDB, myemail=NothingToSeeHere.username):
"""Script to go cycling with one of my cycling buddies.
Grabs
and emails that student to request follow-up observations."""
# See if the department database exists. If not, create it.
if not os.path.exists(filename):
create_friends_table(filename=filename)
# Select a random graduate student to do our bidding
[f_name, l_name, address] = retrieve_random_cyclist(filename=filename)
# Email the student
email_cyclist(address, f_name, l_name, myemail=myemail)
print "I emailed %s %s at %s about going cycling." % (f_name, l_name,
address)
###############################################################################
########NEW FILE########
__FILENAME__ = get_tweets
# This example is taken verbatim from Chapter 1 of
# Mining the Social Web by Matthew A. Russell (O'Reilly Publishers)
import json
from twitter_init import twitter_api
def search_tweets(q='#pyboot'):
"""Get twitter status based on a search string `q`"""
count = 100
# See https://dev.twitter.com/docs/api/1.1/get/search/tweets
search_results = twitter_api.search.tweets(q=q, count=count)
statuses = search_results['statuses']
# Iterate through 5 more batches of results by following the cursor
for _ in range(5):
print "Length of statuses", len(statuses)
try:
next_results = search_results['search_metadata']['next_results']
except KeyError, e: # No more results when next_results doesn't exist
break
# Create a dictionary from next_results, which has the following form:
# ?max_id=313519052523986943&q=NCAA&include_entities=1
kwargs = dict([ kv.split('=') for kv in next_results[1:].split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
return statuses
# Show one sample search result by slicing the list...
#print json.dumps(statuses[0], indent=1)
########NEW FILE########
__FILENAME__ = hello1
from flask import Flask
app = Flask(__name__)
run_on_public_interface = True
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
if run_on_public_interface:
app.run(host='0.0.0.0')
else:
app.run()
########NEW FILE########
__FILENAME__ = hello2
from flask import Flask
app = Flask(__name__)
run_on_public_interface = True
@app.route("/")
def hello():
return "Hello World!"
# read more about using variables here:
# http://flask.pocoo.org/docs/quickstart/#variable-rules
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/tweet/<int:tweet_id>')
def show_tweet(tweet_id):
# show the tweet with the given id, the id is an integer
return 'tweet_id %d' % tweet_id
if __name__ == "__main__":
if run_on_public_interface:
app.run(host='0.0.0.0')
else:
app.run()
########NEW FILE########
__FILENAME__ = hello3
from flask import Flask, url_for
app = Flask(__name__)
run_on_public_interface = True
@app.route("/")
def hello():
return "Hello World!"
# read more about using variables here:
# http://flask.pocoo.org/docs/quickstart/#variable-rules
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/tweet/<int:tweet_id>')
def show_tweet(tweet_id):
# show the tweet with the given id, the id is an integer
username = 'ivanov'
user_url = url_for('show_user_profile', username=username)
link = '<a href="{url}">{text}</a>'
s = link.format(url=user_url, text=username)
return s + 'tweet_id %d' % tweet_id
if __name__ == "__main__":
if run_on_public_interface:
app.run(debug=True,host='0.0.0.0')
else:
app.run()
########NEW FILE########
__FILENAME__ = hello4
# We're going to try to add some style to our website
# but if we continue to deal with just strings, it's going to get messy
from flask import Flask, url_for
app = Flask(__name__)
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger(__name__)
import os
import sys
import IPython.html as ipynb
if not os.path.exists('static') :
if sys.platform == 'win32':
import shutil
shutil.copytree(ipynb.DEFAULT_STATIC_FILES_PATH, 'static')
else:
# the next line won't work on windows
os.symlink(ipynb.DEFAULT_STATIC_FILES_PATH, 'static')
header = """
<head>
<link rel="stylesheet" href="/static/components/jquery-ui/themes/smoothness/jquery-ui.min.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/style/style.min.css" type="text/css"/>
</head>
"""
run_on_public_interface = True
@app.route("/")
def hello():
return "Hello World!"
# read more about using variables here:
# http://flask.pocoo.org/docs/quickstart/#variable-rules
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/tweet/<int:tweet_id>')
def show_tweet(tweet_id):
# show the tweet with the given id, the id is an integer
username = 'ivanov'
user_url = url_for('show_user_profile', username=username)
link = '<div class="prompt"><a href="{url}">{text}</a></div>'
s = ''
s += "<div class='container' id='notebook-container'>"
s += "<div class='cell border-box-sizing selected' >"
s += link.format(url=user_url, text=username)
s += "<div class='input_area' style='padding:20px'> <p>let's see how this looks</p></div>"
s += "</div>"
s += "</div>"
s += "</div>"
return header + s + 'tweet_id %d' % tweet_id
if __name__ == "__main__":
if run_on_public_interface:
app.run(debug=True,host='0.0.0.0')
else:
app.run()
########NEW FILE########
__FILENAME__ = hello5
# We're going to try to add some style to our website
# but if we continue to deal with just strings, it's going to get messy
from flask import Flask, url_for, render_template
app = Flask(__name__)
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger(__name__)
import os
import sys
import IPython.html as ipynb
if not os.path.exists('static') :
if sys.platform == 'win32':
import shutil
shutil.copytree(ipynb.DEFAULT_STATIC_FILES_PATH, 'static')
else:
# the next line won't work on windows
os.symlink(ipynb.DEFAULT_STATIC_FILES_PATH, 'static')
run_on_public_interface = True
@app.route("/")
def hello():
return "Hello World!"
# read more about using variables here:
# http://flask.pocoo.org/docs/quickstart/#variable-rules
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
# Let's just hardcode some tweets for now
tweets = ["Something awesome happened at #pyboot",
"The first rule of #pyboot is you must tell everyone about #pyboot",
"The second rule of #pyboot is: you must endure memes and pop culture references"
]
return render_template('user_dummy.html', username=username, tweets=tweets)
@app.route('/tweet/<int:tweet_id>')
def show_tweet(tweet_id):
# show the tweet with the given id, the id is an integer
username = 'ivanov'
user_url = url_for('show_user_profile', username=username)
# We've hidden away the string logic in the file templates/tweet.html
tweet_text = 'this is some test test #' + str(tweet_id)
return render_template('tweet.html', user_url=user_url, username=username,
tweet=tweet_text)
if __name__ == "__main__":
if run_on_public_interface:
app.run(debug=True,host='0.0.0.0')
else:
app.run()
########NEW FILE########
__FILENAME__ = hello6
# We're going to try to add some style to our website
# but if we continue to deal with just strings, it's going to get messy
from flask import Flask, url_for, render_template
app = Flask(__name__)
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger(__name__)
import os
import sys
import get_tweets
import IPython.html as ipynb
if not os.path.exists('static') :
if sys.platform == 'win32':
import shutil
shutil.copytree(ipynb.DEFAULT_STATIC_FILES_PATH, 'static')
else:
# the next line won't work on windows
os.symlink(ipynb.DEFAULT_STATIC_FILES_PATH, 'static')
run_on_public_interface = True
@app.route("/")
def hello():
return "Hello World!"
# read more about using variables here:
# http://flask.pocoo.org/docs/quickstart/#variable-rules
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
# Let's just hardcode some tweets for now
tweets = ["Something awesome happened at #pyboot",
"The first rule of #pyboot is you must tell everyone about #pyboot",
"The second rule of #pyboot is: you must endure memes and pop culture references"
]
return render_template('user_dummy.html', username=username, tweets=tweets)
@app.route('/tweet/<int:tweet_id>')
def show_tweet(tweet_id):
# show the tweet with the given id, the id is an integer
username = 'ivanov'
user_url = url_for('show_user_profile', username=username)
# We've hidden away the string logic in the file templates/tweet.html
tweet_text = 'this is some test test #' + str(tweet_id)
return render_template('tweet.html', user_url=user_url, username=username,
tweet=tweet_text)
@app.route('/hashtag/<hashtag>')
def show_hashtag(hashtag):
tweets = get_tweets.search_tweets('#'+hashtag)
return render_template('tweets.html', username=hashtag, tweets=tweets)
if __name__ == "__main__":
if run_on_public_interface:
app.run(debug=True,host='0.0.0.0')
else:
app.run()
########NEW FILE########
__FILENAME__ = NothingToSeeHere
# UC Berkeley users. To use the bmail (Google) smtp server, you will need to
# create a Google Key: see this website for details
# https://kb.berkeley.edu/campus-shared-services/page.php?id=27226
username = ''
password = ''
########NEW FILE########
__FILENAME__ = simple_scraper
import urllib2
import numpy.testing as npt
url_instance= urllib2.urlopen('https://twitter.com/search?q=%23pyboot&mode=realtime')
content = url_instance.read()
url_instance.close()
def scrape_usernames_quick_and_dirty(content):
"extract @ usernames from content of a twitter search page"
# you can do this more elegantly with regular expressions (import re), but
# we don't have time to go over them, and as Jamie Zawinski once said:
#
# Some people, when confronted with a problem, think: "I know, I'll use
# regular expressions." Now they have two problems.
#
# Also, we should note that there are better ways of parsing out html
# pages in Python. Have a look at
at_marker = '<s>@</s><b>'
end_marker = '</b>'
start = 0
usernames = []
while True:
# find the first index of an @ marker
hit = content.find(at_marker, start)
if hit == -1:
# we hit the end and nothing was found, break out of the while
# loop, and return what we have
break;
hit += len(at_marker)
end = content.find(end_marker, hit)
if hit != end:
# twitter has some @ signs with no usernames on that page
username = content[hit:end]
usernames.append(username)
start = end
return usernames
def scrape_usernames_beautiful(content):
try:
import BeautifulSoup
except ImportError:
raise("Sorry, you'll need to install BeautifulSoup to use this" )
soup = BeautifulSoup.BeautifulSoup(content)
all_bs = [x.findParent().findNextSibling('b') for x in soup.findAll('s', text='@')]
usernames = []
for b in all_bs:
if len(b.contents) > 0:
# twitter has some @ signs with no usernames on that page
usernames.append(b.contents[0])
return usernames
def test_scrapers():
"Verify that our two ways of getting usernames yields the same results"
url_instance= urllib2.urlopen('https://twitter.com/search?q=%23pyboot&mode=realtime')
content = url_instance.read()
url_instance.close()
names_quick = scrape_usernames_quick_and_dirty(content)
names_beautiful = scrape_usernames_beautiful(content)
npt.assert_array_equal(names_quick, names_beautiful)
########NEW FILE########
__FILENAME__ = twitter_init
# This example is taken verbatim from Chapter 1 of
# Mining the Social Web by Matthew A. Russell (O'Reilly Publishers)
import twitter
# XXX: Go to http://dev.twitter.com/apps/new to create an app and get values
# for these credentials that you'll need to provide in place of these
# empty string values that are defined as placeholders.
# See https://dev.twitter.com/docs/auth/oauth for more information
# on Twitter's OAuth implementation
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
# Nothing to see by displaying twitter_api except that it's now a
# defined variable
print twitter_api
########NEW FILE########
__FILENAME__ = hw_2_solutions
#!/usr/bin/env python
"""
A small monte carlo code to simulate the growth of coins in a cookie jar over a 1 year period
The following are assumed:
1) you make X purchases each day with petty cash, starting out with only bills in your pocket (i.e., no change).
2) Each purchase has a random chance of costing some dollar amount plus YY cents (where YY goes from 0-99).
You always get change in the smallest number of coins possible. For instance,
if you have a purchase of $2.34, then you assume you acquire 66 cents in change
(2 quarters, 1 dime, 1 nickel, 1 penny).
3) If you have enough change to cover the YY cents of the current transaction, you use it.
Otherwise, you accumulate more change. For example, if you have $1.02 in loose change,
and you have a purchase of $10.34, then you use 34 cents (or as close to it as possible) in coins
leaving you with 68 cents.
4) At the end of each day you dump all your coins collected for the day in a Money Jar.
PYTHON BOOT CAMP HOMEWORK2 SOLUTION;
created by Josh Bloom at UC Berkeley, 2010 (ucbpythonclass+bootcamp@gmail.com)
TO RUN:
from command line:
>> python hw_2_solutions.py
from within python, from the folder in which this file resides:
>> from hw_2_solutions import CookieJar, answer_homework_questions
>> answer_homework_questions()
"""
import random, math
import numpy
__version__ = "0.1"
__author__ = "J. Bloom (jbloom@astro.berkeley.edu)"
# define a global dictionary for values of the coins
val = {"nickels": 0.05, "quarters": 0.25, "dimes": 0.10, "pennies": 0.01}
class CookieJar:
"""
the basic workhorse
"""
## set the contents upon create to nothing
deplete_quarters_frequency=7 # remove quarters every 1 week
num_quarters_to_deplete=8 # how many quarters to remove
def __init__(self,transactions_per_day=8,number_of_days_until_fill=365,deplete_quarters=False,\
print_summary_every_week=False,print_summary_of_every_transaction=False):
self.contents = {"quarters": 0, "dimes": 0, "nickels": 0, "pennies": 0}
self.final_value = self._content_value(self.contents)
self.final_contents = self.contents
self.num_transactions_performed = 0
self.day = 0
self.days_to_reach_500_pennies = -1
self.print_summary_of_every_transaction = print_summary_of_every_transaction
self.print_summary_every_week = print_summary_every_week
self.transactions_per_day = transactions_per_day
self.number_of_days_until_fill=number_of_days_until_fill
self.deplete_quarters = deplete_quarters
def fill_er_up(self):
"""
the main engine, it runs all the transactions and accumulates some final results for this cookie jar
"""
while self.day < self.number_of_days_until_fill:
if self.print_summary_every_week:
print "Day %i" % (self.day + 1)
self.perform_a_days_worth_of_transactions()
self.day += 1
if self.contents["pennies"] > 500 and self.days_to_reach_500_pennies == -1:
self.days_to_reach_500_pennies = self.day
if self.day % self.deplete_quarters_frequency == 0 and self.deplete_quarters:
self.contents["quarters"] = max(0,self.contents["quarters"] - self.num_quarters_to_deplete)
#print "all done after %i transactions" % self.num_transactions_performed
self.final_value = self._content_value(self.contents)
self.final_contents = self.contents
self.final_order = self._order(self.contents)
def __str__(self):
"""
print a summary of yourself
"""
a = "Value %.2f after %i transactions performed." % (self.final_value,self.num_transactions_performed)
a += " days to reach 500 pennies: %i" % self.days_to_reach_500_pennies
return a
def _order(self,purse):
"""
determine the ordering of number of coins in the purse.
here the purse is assumed to be a dict like
{"nickels": 0, "quarters": 12, "dimes": 3, "pennies": 32}
returns
{1: "pennies", 2: "quarters", 3: "dimes", 4: "nickels"}
"""
tmp = [(v,k) for k,v in purse.iteritems()]
tmp.sort(reverse=True)
return dict([(i+1,tmp[i][1]) for i in range(len(tmp))])
def _content_value(self,purse):
"""
determine the value of coins in the purse.
here the purse is assumed to be a dict like
{"nickels": 0, "quarters": 12, "dimes": 3, "pennies": 32}
"""
rez = 0.0
for k in purse.keys():
rez += val[k]*purse[k]
return rez
def best_change(self,cost,contents,verbose=False):
"""
for given transaction cost determines the best combination of coins that
gives as close to the exact change amount needed as possible given the contents of a purse
returns a tuple where the first element is False if the contents of the purse cannot
cover the change cost, True if it can
the second element is a dict showing how much of each coin type is required to make the transaction
as close to $x.00 as possible
This is just a big ugly 4x nested for loop, trying out all combinations
"""
cost_in_cents = cost % 1.0
if cost_in_cents > self._content_value(contents):
# there's no way we have enough...our purse value is less than the cost in cents
return (False,{})
exact = False
best_diff = 1.00
best = {}
for q in range(contents["quarters"] + 1):
for d in range(contents["dimes"] + 1):
for n in range(contents["nickels"] + 1):
for p in range(contents["pennies"] + 1):
v = round(q*0.25 + d*0.10 + n*0.05 + p*0.01,2)
if verbose:
print "val",p,n,d,q,v,cost_in_cents,best_diff
if abs(v - cost_in_cents) < 0.005:
## this is within the tolerance of a floating point difference
best_diff = 0.0
best = {"nickels": n, "dimes": d, "pennies": p, "quarters": q}
exact = True
break
elif (v - cost_in_cents) > 0.0 and (v - cost_in_cents) < best_diff:
best_diff = (v - cost_in_cents)
best = {"nickels": n, "dimes": d, "pennies": p, "quarters": q}
exact = False
if exact:
break
if exact:
break
if exact:
break
return (True,best)
def perform_a_days_worth_of_transactions(self):
"""
loop over all the transactions in the day keeping track of the number of coins of each type
in the purse.
The random cost of a transaction is set to be:
cost = round(random.random()*50,2)
"""
#initialize how much booty we have in our pockets
pocket_contents = {"nickels": 0, "quarters": 0, "dimes": 0, "pennies": 0}
n_exact = 0
for i in xrange(self.transactions_per_day):
cost = round(random.random()*50,2) # assume a transaction cost of $0 - $50
# round to the nearest cent
if self.print_summary_of_every_transaction:
print "Day %i, transaction %i" % (self.day + 1,i + 1)
print " pocket_contents = %s" % repr(pocket_contents)
print " cost = $%.2f" % cost
## do I have exact change?
got_enough = self.best_change(cost,pocket_contents)
if got_enough[0]:
## we have enough change and it might just enough to get us where we need to be
## That is the cost + this change ends in .00. So, subtract the value to the cost
cost -= sum([got_enough[1][x]*val[x] for x in val.keys()])
## now remove all that from our purse
for k,v in got_enough[1].iteritems():
pocket_contents[k] -= v
# print "...new cost", cost
if cost % 1.0 == 0.0:
n_exact += 1
change = self.calc_change(cost)
for k,v in change.iteritems():
if v != 0:
pocket_contents[k] += v
self.num_transactions_performed += 1
if self.print_summary_of_every_transaction:
print " end the end of the day: pocket_contents = %s" % repr(pocket_contents)
print " we had %i exact change times out of %i transactions" % (n_exact,self.transactions_per_day)
## dump what we have into the cookie jar at the end of the day
for k in self.contents.keys():
self.contents[k] += pocket_contents[k]
def calc_change(self,transaction_amount):
"""
for a given transaction amount, determines how many coins of each type to return
"""
change = 1.0 - (transaction_amount % 1.0) # make this a number from 0.0 - 0.99
change_in_cents = int(round(change*100.0) % 100) ## make from 0 - 99 as type int
#print "change",change,"change_in_cents",change_in_cents
oring_change_in_cents = change_in_cents
n_quarters = change_in_cents / 25 ## since this is int / int we'll get back an int
change_in_cents -= n_quarters*25
n_dimes = change_in_cents / 10
change_in_cents -= n_dimes*10
n_nickels = change_in_cents / 5
change_in_cents -= n_nickels*5
n_pennies = change_in_cents
if self.print_summary_of_every_transaction:
print " Transaction is $%.2f (coin change was %i cents)" % (transaction_amount ,oring_change_in_cents)
print " %s: quarters: %i dimes: %i nickels: %i pennies: %i" % ("returned", \
n_quarters ,n_dimes,n_nickels,n_pennies)
print "*" * 40
return {"nickels": n_nickels, "quarters": n_quarters, "dimes": n_dimes, "pennies": n_pennies}
def answer_homework_questions():
"""performs the monte carlo, making many instances of CookieJars under different assumptions."""
## a: What is the average total amount of change accumulated each year (assume X=5)?
# What is the 1-sigma scatter about this quantity?
## let's simulate 50 cookie jars of 1 year each
njars = 50
jars = []
for j in xrange(njars):
jars.append(CookieJar(transactions_per_day=5,number_of_days_until_fill=365,deplete_quarters=False))
jars[-1].fill_er_up()
fin = numpy.array([x.final_value for x in jars])
mn = fin.mean()
st = numpy.std(fin)
print "question a"
print "-"*50
print "mean value accumulated per year:",mn,"\nstandard deviation from {} trials:".format(njars), st
print "-"*50
# mean = $181.71
# st = $5.99
## b. What coin (quarter, dime, nickel, penny) are you most likely to accumulate
## over time? Second most likely? Does it depend on X?
first = {"nickels": 0, "quarters": 0, "dimes": 0, "pennies":0}
second = {"nickels": 0, "quarters": 0, "dimes": 0, "pennies":0}
for j in jars:
first[j.final_order[1]] += 1
second[j.final_order[2]] += 1
print "\nquestion b"
print "-"*50
print "transactions per day:",5
print "times each coin was the most common:\n",first
print "times each coin was the second most common:\n",second
# pennies always first, quarters usually second (sometimes dimes)
## now let's try # transaction changes
for tr in [2,10,20]:
jars = []
for j in xrange(50):
jars.append(CookieJar(transactions_per_day=tr,number_of_days_until_fill=365,deplete_quarters=False))
jars[-1].fill_er_up()
first = {"nickels": 0, "quarters": 0, "dimes": 0, "pennies":0}
second = {"nickels": 0, "quarters": 0, "dimes": 0, "pennies":0}
for j in jars:
first[j.final_order[1]] += 1
second[j.final_order[2]] += 1
print "\ntransactions per day:",tr
print "times each coin was the most common:\n",first
print "times each coin was the second most common:\n",second
## answer: no. it doesn't
## c. Let's say you need 8 quarters per week to do laundry. How many quarters do you have at the end of the year?
## (if you do not have enough quarters at the end of each week, use only what you have).
jars = []
for j in xrange(50):
jars.append(CookieJar(transactions_per_day=5,number_of_days_until_fill=365,deplete_quarters=True))
jars[-1].fill_er_up()
nq = 0
for j in jars:
nq += j.final_contents["quarters"]
print "-"*50
print "\nquestion c"
print "-"*50
print "average # of quarters left after a year:",nq/len(jars)
# answer = 28
print "-"*50
if __name__ == "__main__":
answer_homework_questions()
########NEW FILE########
__FILENAME__ = mknbindex
#!/usr/bin/env python
"""Simple script to auto-generate the index of notebooks in a given directory.
"""
import glob
import urllib
notebooks = sorted(glob.glob('*.ipynb'))
tpl = ( '* [{0}](http://nbviewer.ipython.org/url/raw.github.com/profjsb/python-bootcamp/master/Lectures/04_IPythonNotebookIntroduction/{1})' )
idx = [
"""Introduction to IPython
=======================
These notebooks introduce the basics of IPython, as part of the [Berkeley Python
Bootcamp](http://pythonbootcamp.info).
"""]
idx.extend(tpl.format(nb.replace('.ipynb',''), urllib.quote(nb))
for nb in notebooks)
with open('README.md', 'w') as f:
f.write('\n'.join(idx))
f.write('\n')
########NEW FILE########
__FILENAME__ = talktools
"""Tools to style a talk."""
from IPython.display import HTML, display, YouTubeVideo
def prefix(url):
prefix = '' if url.startswith('http') else 'http://'
return prefix + url
def simple_link(url, name=None):
name = url if name is None else name
url = prefix(url)
return '<a href="%s" target="_blank">%s</a>' % (url, name)
def html_link(url, name=None):
return HTML(simple_link(url, name))
# Utility functions
def website(url, name=None, width=800, height=450):
html = []
if name:
html.extend(['<div class="nb_link">',
simple_link(url, name),
'</div>'] )
html.append('<iframe src="%s" width="%s" height="%s">' %
(prefix(url), width, height))
return HTML('\n'.join(html))
def nbviewer(url, name=None, width=800, height=450):
return website('nbviewer.ipython.org/url/' + url, name, width, height)
# Load and publish CSS
style = HTML(open('style.css').read())
display(style)
########NEW FILE########
__FILENAME__ = oop1_plots
import matplotlib.pyplot as plt
import numpy as np
data_vars = [ [0.2,0.7,'x'],
[0.3,0.6,'y'],
[0.22,0.5,'newx'],
[0.21, 0.4,'coolest_y'],
[0.19,0.24,'perimeter1' ] ]
code_vars = [ [0.2,0.7,'read_sensor()'],
[0.20,0.5,'calculate_perimeter()'],
[0.24,0.24,'generate_figure_for_nature_paper()' ] ]
def denude_plot():
plt.xticks([])
plt.yticks([])
plt.xlim(0,1)
plt.ylim(0,1)
plt.xticks([])
plt.yticks([])
plt.xlim(0,1)
plt.ylim(0,1)
def show_background1():
plt.figure(figsize=(11.5,8))
#plt.gcf().clf()
rect_data = plt.Rectangle((0.1,0.1), 0.3, 0.7, facecolor="#e0e0f0")
plt.gca().add_patch( rect_data )
rect_code = plt.Rectangle((0.6,0.1), 0.3, 0.7, facecolor="#e0e0f0")
plt.gca().add_patch( rect_code )
plt.text(0.25, 0.85, 'Data (i.e., numbers)', style='italic', size=16, horizontalalignment='center' )
plt.text(0.75, 0.85, 'Code', style='italic', size=16, horizontalalignment='center' )
for n,avar in enumerate(data_vars):
plt.text( avar[0], avar[1], avar[2], size=10, rotation=np.random.rand()*10.0-5.0, ha="center", va="center", bbox = dict(boxstyle="round", ec=(0.8, 0.1, 1.0), fc=(0.8, 0.4, 1.0),))
for n,avar in enumerate(code_vars):
plt.text( avar[0]+0.5, avar[1], avar[2], size=10, rotation=np.random.rand()*10.0-5.0, ha="center", va="center", bbox = dict(boxstyle="round", ec=(1.0, 0.1, 0.8), fc=(1.0, 0.4, 0.8),))
denude_plot()
def code_to_data():
ax=plt.gca()
ax.arrow( data_vars[0][0]+0.5, data_vars[0][1], -0.4, 0.0, head_width=0.01, head_length=0.01,fc='k',ec='k' )
ax.arrow( data_vars[0][0]+0.5, data_vars[0][1], -0.35,-0.1, head_width=0.01, head_length=0.01,fc='k',ec='k' )
def data_to_code():
ax=plt.gca()
ax.arrow( data_vars[0][0]+0.0, data_vars[0][1], 0.38, -0.18, head_width=0.01, head_length=0.01,fc='k',ec='k' )
ax.arrow( data_vars[1][0]+0.0, data_vars[1][1], 0.25, -0.08, head_width=0.01, head_length=0.01,fc='k',ec='k' )
ax.arrow( code_vars[1][0]+0.5, code_vars[1][1], -0.4, -0.26, head_width=0.01, head_length=0.01,fc='k',ec='k' )
plt.show()
def Procedural_programming():
show_background1()
plt.show()
def Function1():
show_background1()
code_to_data()
def Function2():
show_background1()
data_to_code()
def Objects():
plt.figure(figsize=(11.5,8))
rect_obj = plt.Rectangle((0.1,0.1), 0.4, 0.7, facecolor="#101080")
plt.gca().add_patch( rect_obj )
rect_data = plt.Rectangle((0.7,0.15), 0.2, 0.2, facecolor="#e0e0f0")
plt.gca().add_patch( rect_data )
rect_code = plt.Rectangle((0.7,0.55), 0.2, 0.2, facecolor="#e0e0f0")
plt.gca().add_patch( rect_code )
plt.text(0.3, 0.85, 'Objects', size=16, style='italic', horizontalalignment='center' )
plt.text(0.8, 0.8, '...(Data)...', size=12, style='italic', horizontalalignment='center' )
plt.text(0.8, 0.4, '...(Code)...', size=12, style='italic',horizontalalignment='center' )
for n,avar in enumerate([code_vars[0],code_vars[2]]):
msg= 'Polygon Sensor %d\n---------------\n<\$$RAWDATA$\$>\n----------\n- acquire_data()\n- calculate_perimeter()\n- make_Nobel_fig()'%n
plt.text( avar[0], avar[1], msg, size=10, rotation=np.random.rand()*10.0-5.0, ha="left", va="center", bbox = dict(boxstyle="round", ec=(1.0, 1.0, 0.1), fc=(1.0, 1.0, 0.1),))
#plt.text( avar[0], avar[1], 'Polygon Sensor %d\n---------------\n- acquire_data()\n- calculate_perimeter()'%n, size=10, rotation=np.random.rand()*10.0-5.0, ha="left", va="center", bbox = dict(boxstyle="round", ec=(1.0, 0.1, 0.8), fc=(1.0, 0.4, 0.8),))
denude_plot()
########NEW FILE########
__FILENAME__ = talktools
"""Tools to style a talk."""
from IPython.display import HTML, display, YouTubeVideo
def prefix(url):
prefix = '' if url.startswith('http') else 'http://'
return prefix + url
def simple_link(url, name=None):
name = url if name is None else name
url = prefix(url)
return '<a href="%s" target="_blank">%s</a>' % (url, name)
def html_link(url, name=None):
return HTML(simple_link(url, name))
# Utility functions
def website(url, name=None, width=800, height=450):
html = []
if name:
html.extend(['<div class="nb_link">',
simple_link(url, name),
'</div>'] )
html.append('<iframe src="%s" width="%s" height="%s">' %
(prefix(url), width, height))
return HTML('\n'.join(html))
def nbviewer(url, name=None, width=800, height=450):
return website('nbviewer.ipython.org/url/' + url, name, width, height)
# Load and publish CSS
style = HTML(open('style.css').read())
display(style)
########NEW FILE########
__FILENAME__ = mycircle
class MyCircle(object):
def _repr_html_(self):
return "○ (<b>html</b>)"
def _repr_svg_(self):
return """<svg width="100px" height="100px">
<circle cx="50" cy="50" r="20" stroke="black" stroke-width="1" fill="blue"/>
</svg>"""
def _repr_latex_(self):
return r"$\bigcirc \LaTeX$"
def _repr_javascript_(self):
return "alert('I am a circle!');"
########NEW FILE########
__FILENAME__ = mycircle2
# We first verify that indeed, `display_latex` doesn't do anything for this class:
print "Calling display_latex:"
display_latex(c2)
# Now we grab the latex formatter
latex_f = ip.display_formatter.formatters['text/latex']
# And register for our `AnotherCircle` class, the desired $\LaTeX$ format function. In this case we can use a simple lambda:
latex_f.for_type(AnotherCircle, lambda x: r"$\bigcirc \LaTeX$" )
# Calling `display_latex` once more now gives a different result:
print "Calling display_latex again:"
display_latex(c2)
########NEW FILE########
__FILENAME__ = talktools
"""Tools to style a talk."""
from IPython.display import HTML, display, YouTubeVideo
def prefix(url):
prefix = '' if url.startswith('http') else 'http://'
return prefix + url
def simple_link(url, name=None):
name = url if name is None else name
url = prefix(url)
return '<a href="%s" target="_blank">%s</a>' % (url, name)
def html_link(url, name=None):
return HTML(simple_link(url, name))
# Utility functions
def website(url, name=None, width=800, height=450):
html = []
if name:
html.extend(['<div class="nb_link">',
simple_link(url, name),
'</div>'] )
html.append('<iframe src="%s" width="%s" height="%s">' %
(prefix(url), width, height))
return HTML('\n'.join(html))
def nbviewer(url, name=None, width=800, height=450):
return website('nbviewer.ipython.org/url/' + url, name, width, height)
# Load and publish CSS
style = HTML(open('style.css').read())
display(style)
########NEW FILE########
|
8a404edee1d0ba3525c388371d7a571c3af7b5ad | SerikDanaaa/Python_ | /TSIS7/lecture samples/3.py | 697 | 3.5625 | 4 | import pygame
pygame.init()
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
PINK = (150,0,150)
ORANGE = (150,100,0)
size = (500,500)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
text_rotate = 1
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#TEXT ROTATE
screen.fill((255,255,255))
font = pygame.font.SysFont('Calibri', 25, True, False)
text = font.render("Programming Technologies", True,(0,0,0))
text = pygame.transform.rotate(text, text_rotate)
screen.blit(text, (100,100))
text_rotate += 1
clock.tick(60)
pygame.display.flip()
pygame.quit() |
9c3b1d7787eea0fd5e71ea0835bd124e308deb88 | mottJohn/returnAirportDistance | /returnAirportDistance.py | 985 | 3.609375 | 4 | import pandas as pd
from requests_html import HTMLSession
session = HTMLSession()
#read excel
df_input = pd.read_excel("input.xlsx")
def getDistance(from_destination, to_destination):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'} #to avoid bad response
html = "https://www.world-airport-codes.com/distance/?a1={}&a2={}&code=IATA".format(from_destination, to_destination) #parse the link with from and to
r = session.get(html, verify = False, headers = headers) #request turn ssl false and headers = headers
xpath = '/html/body/div[1]/div[4]/div/div/div/div/div[1]/main/article/div/div[1]/p/strong/text()' #path to the html tag containing distance
return r.html.xpath(xpath)[0]
df_input["Distance"] = df_input.apply(lambda row: getDistance(row['from_destination'], row['to_destination']), axis=1)
print(df_input)
df_input.to_excel("output.xlsx", index = False) |
77e56f0e54cde4a899e12039fb44a54428918ccf | backman-git/leetcode | /sol13.py | 583 | 3.6875 | 4 |
13. Roman to Integer
key point:
roman numerals:
1.look from left.
if numerical symbol is less than right symbol substract it!
後記:
終於去解決了! 20170417 消防役時期
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
romanTlb={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
ans=0
for idx,c in enumerate(s):
if idx+1 <len(s) and romanTlb[c] < romanTlb[s[idx+1]]:
ans+= -1*romanTlb[c]
else:
ans+=romanTlb[c]
return ans
sol = Solution()
print sol.romanToInt("DCXXI")
|
fd1c723ab890364724bcd1f1cf57468bcc6cab0e | LMFrank/Algorithm | /offer/python/08_跳台阶.py | 322 | 3.640625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def jumpFloor(self, number):
# write code here
if number <= 0:
return 0
if number == 1:
return 1
res = [0, 1, 2]
for i in range(3, number + 1):
res.append(res[i-1] + res[i-2])
return res[number] |
7e60001e41676b487cfb73c4a156a015a7ba8332 | tianrking/justforfun | /python3/b.py | 727 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import math
import random
ss=0
#print(ss)
time=int(input())
def distance(a,b):
temp=abs(a-b)
return temp*temp
def rd(x1,x2,y1,y2):
rd=math.sqrt(distance(x1,x2)+distance(y1,y2))
#print("x1(%f,%f)" %(x1,y1))
if rd>math.sqrt(12):
print ("x1(%f,%f) x2(%f,%f) ∨"%(x1,y1,x2,y2))
return 0
else:
print ("x1(%f,%f) x2(%f,%f)"%(x1,y1,x2,y2))
return 1
for n in range (1,time,1):
ax=random.uniform(-2,2)
bx=random.uniform(-2,2)
ay=float(math.sqrt(4-ax*ax))
by=float(math.sqrt(4-bx*bx))
if random.randint(1,2)==2:
ay=-ay
if random.randint(1,2)==1:
by=-by
ss+=float(rd(ax,bx,ay,by))
print("P=",ss/time)
|
8b9373634fbd99afe524da4cc79c1aa239441fc5 | Madstergaard/Masterpiece | /utils/accounts.py | 11,041 | 3.796875 | 4 | import sqlite3, hashlib
#-----------------------------ACCOUNTS TABLE-----------------------------
# if username given matches a username in the database, return true
# else, return false
def userExists(user):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT * FROM accounts;"
sel = c.execute(cmd)
for record in sel:
if user == record[0]:
db.close()
return True
db.close()
return False
# adds user to the database
def register(user, hashedPass):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT userID FROM accounts ORDER BY userID DESC;"
sel = c.execute(cmd)
userID = 1
iList = ""
for record in sel:
userID = userID + record[0]
break
entry = "INSERT INTO accounts VALUES ('%s','%s','%d');"%(user, hashedPass, userID)
c.execute(entry)
db.commit()
db.close()
# if username and hashed password given match a username and its corresponding hashed password in the database, return true
# else, return false
def verify(user, hashedPass):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT * FROM accounts;"
sel = c.execute(cmd)
for record in sel:
if user == record[0] and hashedPass == record[1]:
db.close()
return True
db.close()
return False
# returns the unique userID associated with a user account
def getUID(user):
db = sqlite3.connect("data/database.db")
c = db.cursor()
id = ""
cmd = "SELECT * FROM accounts;"
sel = c.execute(cmd)
for record in sel:
if user == record[0]:
id = record[2]
db.close()
return id
# returns a hashed version of the password
def hashPass(password):
return hashlib.sha224(password).hexdigest()
# returns a user's hashed password
def getPass(userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT hashedPass FROM accounts WHERE userID = %d;"%(userID)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
# changes a user's hashed password
def changePass(newHashedPass, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE accounts SET hashedPass = '%s' WHERE userID = %d;"%(newHashedPass, int(userID))
sel = c.execute(cmd)
db.commit()
db.close()
#-------------------------------DOCS TABLE-------------------------------
# adds a document and its settings into the docs table
# userID for original author, authors for all contributors
def addDoc(title, content, userID, status, comments, description, coverURL, authors):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "INSERT INTO docs VALUES ('%s','%s','%d','%s','%s','%s','%s','%s');"%(title, content, userID, status, comments, description, coverURL, authors)
c.execute(cmd)
db.commit()
db.close()
# returns a list of titles for a specific user
def getTitles(userID):
titles = []
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT title FROM docs WHERE userID = %d;"%(int(userID))
sel = c.execute(cmd)
for record in sel:
titles.append(record[0])
db.close()
return titles
#print getTitles(1)
# changes a document's title
def changeTitle(title, userID, newTitle):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET title = '%s' WHERE userID = %d AND title = '%s';"%(newTitle, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#changeTitle("h",1,"yay")
def titleExists(title, userID):
titles = getTitles(userID)
for t in titles:
if t == title:
return True
return False
#print titleExists("coffee",1)
# returns the status of a particular document
def getStatus(title, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT status FROM docs WHERE userID = %d AND title = '%s';"%(int(userID), title)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
#print getStatus("coffee",1)
# changes a document's status from private to public or public to private
def changeStatus(title, userID, newStatus):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET status = '%s' WHERE userID = %d AND title = '%s';"%(newStatus, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#changeStatus("coffee",1,"public")
# returns the list of comments from a particular document
def getComments(title, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT comments FROM docs WHERE userID = %d AND title = '%s';"%(int(userID), title)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
#print getComments("coffee",1)
# if given comment exists, return true
# else, return false
def commentExists(title, userID, comment):
comments = getComments(title, userID)
comments = comments[:len(comments)-3].split(";;;")
for cmt in comments:
if cmt == comment:
return True
return False
# adds a comment to a particular document
def addComment(title, userID, comment):
if not commentExists(title, userID, comment):
db = sqlite3.connect("data/database.db")
c = db.cursor()
tmp = getComments(title, userID) + comment + ";;;"
cmd = "UPDATE docs SET comments = '%s' WHERE userID = %d AND title = '%s';"%(tmp, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#addComment("coffee",1,"i agree")
# removes a comment from a particular document
def rmComment(title, userID, comment):
if commentExists(title, userID, comment):
comments = getComments(title, userID)
comments = comments[:len(comments)-3].split(";;;")
newComments = ""
for cmt in comments:
if cmt != comment:
newComments += cmt + ";;;"
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET comments = '%s' WHERE userID = %d AND title = '%s';"%(newComments, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#rmComment("coffee",1,"i agree")
# returns doc content
def getContent(title, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT content FROM docs WHERE userID = %d AND title = '%s';"%(int(userID), title)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
#print getContent("coffee",1)
# if we end up storing the content
# if not, function is unnecessary because link does not change
def updateContent(title, userID, newContent):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET content = '%s' WHERE userID = %d AND title = '%s';"%(newContent, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#updateContent("coffee",1,"coffeedoclink")
# returns a document's description
def getDescription(title, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT description FROM docs WHERE userID = %d AND title = '%s';"%(int(userID), title)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
#print getDescription("coffee", 1)
# changes a document's description
def changeDescription(title, userID, newDescription):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET description = '%s' WHERE userID = %d AND title = '%s';"%(newDescription, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#changeDescription("coffee",1,"very delicious drink")
# returns a document's book cover url
def getCoverURL(title, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT coverURL FROM docs WHERE userID = %d AND title = '%s';"%(int(userID), title)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
#print getCoverURL("h", 1)
# changes a document's book cover url
def changeCoverURL(title, userID, newCoverURL):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET coverURL = '%s' WHERE userID = %d AND title = '%s';"%(newCoverURL, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#changeCoverURL("h",1,"cool")
# returns the list of authors from a particular document
def getAuthors(title, userID):
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT authors FROM docs WHERE userID = %d AND title = '%s';"%(int(userID), title)
sel = c.execute(cmd).fetchone()
db.close()
return sel[0]
#print getAuthors("coffee", 1)
# if given author exists, return true
# else, return false
def authorExists(title, userID, author):
authors = getAuthors(title, userID)
authors = authors[:len(authors)-3].split(";;;")
for a in authors:
if a == author:
return True
return False
# adds an author to a particular document
def addAuthor(title, userID, author):
if not authorExists(title, userID, author):
db = sqlite3.connect("data/database.db")
c = db.cursor()
tmp = getAuthors(title, userID) + author + ";;;"
cmd = "UPDATE docs SET authors = '%s' WHERE userID = %d AND title = '%s';"%(tmp, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#addAuthor("h", 1, "asdf")
# removes an author from a particular document
def rmAuthor(title, userID, author):
if authorExists(title, userID, author):
authors = getAuthors(title, userID)
authors = authors[:len(authors)-3].split(";;;")
newAuthors = ""
for a in authors:
if a != author:
newAuthors += a + ";;;"
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "UPDATE docs SET authors = '%s' WHERE userID = %d AND title = '%s';"%(newAuthors, int(userID), title)
sel = c.execute(cmd)
db.commit()
db.close()
#rmAuthor("h",1,"asdf")
# returns all of the documents that the user created
def getUserDocs(userID):
docs = []
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT title, description, coverURL, authors, userID FROM docs WHERE userID = %d;"%(int(userID))
sel = c.execute(cmd)
for record in sel:
docs.append(record)
db.close()
return docs
#print getUserDocs(1)
# returns the title, description, URL to book cover image, author names for all public documents
def getLibraryInfo():
info = []
db = sqlite3.connect("data/database.db")
c = db.cursor()
cmd = "SELECT title, description, coverURL, authors, userID FROM docs WHERE status = '%s';"%("public")
sel = c.execute(cmd)
for record in sel:
info.append(record)
db.close()
return info
#print getLibraryInfo()
|
9faa603be6552b7fff56e32172269f0aeb2fadfe | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sublist/379e83e34eaf43e7ac622d77c95d08d5.py | 321 | 3.90625 | 4 |
SUBLIST, SUPERLIST, EQUAL, UNEQUAL = (1, 2, 3, 4)
def check_lists(list1, list2):
if list1 == list2:
return EQUAL
set1, set2 = set(list1), set(list2)
if set1 <= set2:
return SUBLIST
elif set2 <= set1:
return SUPERLIST
else:
return UNEQUAL
|
e53c5201b58a737d3d73ba65fc22ce13c48173ea | jovesterchai/AppDev | /PycharmProjects/Practical5 Ref/Q2.py | 130 | 4.09375 | 4 | count=0
sum=0
while count==0:
num=int(input("Enter a number: "))
if num==0:
count+=1
sum+=num
print(sum)
|
58695286f39eb58f8c90b562c9e0d3727f1c43c1 | mmoriche/lib | /pyfiles/mylist.py | 464 | 4.34375 | 4 | def sublists(mylist,mylistdone):
"""
Function to substract mylistdone from mylist
The output is a list of the items of mylist that
are not in mylistdone
"""
# warning check
for item in mylistdone:
if not item in mylist:
print
print ' WARNING: item '+item+' not in mylist'
print
#
mynewlist = []
for item in mylist:
if not item in mylistdone:
mynewlist.append(item)
return mynewlist
|
27890d9bd7b344c04f242cef23020c3472d24a58 | mpailab/cancer-detector | /selector.py | 10,085 | 3.703125 | 4 | """
Feature selection functions
Every feature selection function inputs expression dataframe and number n,
and returns list of features:
def selector(df, n, **kwargs):
some code
TODO: for supervised feature selection one should also pass
subset of datasets for feature selection
"""
# External imports
import numpy as np
import scipy
import xgboost
import shap
from scipy.stats import spearmanr
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_classification
# Internal imports
import dataset
def pvalue(df, n, **kwargs):
'''
Select n features with respect to p-values of the T-test for relapse
and non-relapse samples.
'''
datasets = kwargs.get("datasets", None)
_df = df if datasets is None else df.loc[df["Dataset"].isin(datasets)]
genes = _df.drop(columns=["Class", "Dataset", "Dataset type"]).columns.to_numpy()
X = _df.loc[df["Class"] == 1].drop(columns=["Class", "Dataset", "Dataset type"]).to_numpy()
Y = _df.loc[df["Class"] == 0].drop(columns=["Class", "Dataset", "Dataset type"]).to_numpy()
if X.shape[0] < Y.shape[0]:
index = np.random.choice(Y.shape[0], X.shape[0], replace=False)
Y = Y[index]
if X.shape[0] > Y.shape[0]:
index = np.random.choice(X.shape[0], Y.shape[0], replace=False)
X = X[index]
t_test_results = scipy.stats.ttest_ind(X, Y, axis=0)
ind = np.argsort(t_test_results.pvalue)
return genes[ind[:n]]
def nt_pvalue (df, n, **kwargs):
'''
Select n features with respect to normal-tumor pvalues
'''
df_normal = dataset.normal()
df_tumor = dataset.tumor()
if df_normal is None or df_tumor is None:
return []
genes = [ g for g in df if g in df_normal.index and
any(df_normal[p][g] != df_tumor[p][g] for p in df_normal) ]
df_normal = df_normal.filter(items=genes, axis=0)
df_tumor = df_tumor.filter(items=genes, axis=0)
t_test_results = scipy.stats.ttest_rel(df_normal, df_tumor, axis=1)
ind = np.argsort(t_test_results.pvalue)
return genes[ind[:n]]
def geffect (df, n, **kwargs):
'''
Select n features with respect to gene effect
Parameters:
cell_lines : list or numpy array, default dataset.breast_cell_lines
The cell lines to filter on gene effect table
'''
if dataset.geffect is None:
return []
cell_lines = kwargs.get("cell_lines", dataset.breast_cell_lines)
gene_effect = dataset.geffect.loc[cell_lines].mean(axis=0).sort_values()
return gene_effect[:n].index.to_numpy()
def pubmed (df, n, **kwargs):
'''
Select n features with respect to the number of pubmed references
'''
if dataset.pubmed is None:
return []
genes = df.columns.to_numpy()
pubmed_df = dataset.pubmed.filter(items=genes, axis=0).sort_values(by='refs_num', ascending=False)
return pubmed_df[:n].index.to_numpy()
def top_from_file (df, n, **kwargs):
'''
Select n top features from a file
Lines format in the file: <feature><sep><any info>
By default <sep> is any whitespace
'''
filepath = kwargs["file"]
sep = kwargs.get("sep", None)
with open(filepath) as f:
lines = f.readlines()
return list(filter(lambda x: x in df.columns, map(lambda x: x.split(sep)[0], lines)))[:n]
def nt_diff (df, n, **kwargs):
'''
Select n features with respect to difference between normal and tumor expressions
diff: int or function (n, t -> float), where n, t are np.arrays of equal length
'''
diff = kwargs.get("diff", 0)
g_mean = lambda ar: ar.prod() ** (1. / ar.size)
a_mean = lambda ar: ar.sum() / ar.size
default = {
0: lambda n, t: g_mean(np.absolute(t - n) / n),
1: lambda n, t: g_mean(np.absolute(t - n) / t),
2: lambda n, t: abs(a_mean(t - n)),
3: lambda n, t: a_mean(np.absolute(t - n)),
4: lambda n, t: g_mean(t / n),
5: lambda n, t: g_mean(n / t),
6: lambda n, t: max(np.absolute(t - n))
}
if diff in default.keys():
diff = default[diff]
df_normal = dataset.normal()
df_tumor = dataset.tumor()
if df_normal is None or df_tumor is None:
return []
genes = [ g for g in df if g in df_normal.index and
any(df_normal[p][g] != df_tumor[p][g] for p in df_normal) ]
df_normal = df_normal.filter(items=genes, axis=0)
df_tumor = df_tumor.filter(items=genes, axis=0)
dist = {g : diff(df_normal.loc[g], df_tumor.loc[g]) for g in genes}
genes = list(filter(lambda g: str(dist[g]) not in ['nan', 'inf', '-inf'] , genes))
genes.sort(key = lambda g: dist[g], reverse=True)
#[print("{} : {}".format(g, dist[g])) for g in genes]
return genes[:n]
def max_correlation(df, n, **kwargs):
'''
Input expression dataframe and number n, return list
of n selected features
Uses Spearman correlation to select the most important genes
TODO: for supervised feature selection one should also pass
subset of datasets for feature selection
'''
datasets = kwargs["datasets"]
df_subset = df.loc[df["Dataset"].isin(datasets)]
X = df_subset.drop(columns=["Class", "Dataset", "Dataset type"]).to_numpy()
Y = df_subset["Class"].to_numpy()
n_genes = X.shape[1]
corr_coeff = np.zeros(n_genes)
for i in range(n_genes):
corr, _ = spearmanr(X[:,i], Y)
corr_coeff[i] = corr
features = df_subset.drop(columns=["Class", "Dataset", "Dataset type"]).columns
return [feature for feature, corr_coeff in sorted(zip(features, corr_coeff), key=lambda x: x[1], reverse=True)][0:n]
def min_p_value(df, n, **kwargs):
'''
Input expression dataframe and number n, return list
of n selected features
Uses Spearman p-value to select most important genes
TODO: for supervised feature selection one should also pass
subset of datasets for feature selection
'''
datasets = kwargs["datasets"]
df_subset = df.loc[df["Dataset"].isin(datasets)]
X = df_subset.drop(columns=["Class", "Dataset", "Dataset type"]).to_numpy()
Y = df_subset["Class"].to_numpy()
n_genes = X.shape[1]
p_values = np.zeros(n_genes)
for i in range(n_genes):
_, pval = spearmanr(X[:,i], Y)
p_values[i] = pval
features = df_subset.drop(columns=["Class", "Dataset", "Dataset type"]).columns
return [feature for feature, p_values in sorted(zip(features, p_values), key=lambda x: x[1], reverse=False)][0:n]
def boosting_shapley(df, n, **kwargs):
'''
Input expression dataframe and number n, return list
of n selected features
TODO: for supervised feature selection one should also pass
subset of datasets for feature selection
'''
datasets = kwargs["datasets"]
eta = kwargs.get("eta", 0.001)
num_rounds = kwargs.get("num_rounds", 3000)
early_stopping_rounds = kwargs.get("early_stopping_rounds", 40)
subsample = kwargs.get("subsample", 0.8)
df_subset = df.loc[df["Dataset"].isin(datasets)]
X = df_subset.drop(columns=["Class", "Dataset", "Dataset type"]).to_numpy()
y = df_subset["Class"].to_numpy()
xgboost_input = xgboost.DMatrix(X, label=y)
params = {
"objective": "binary:logistic",
"eval_metric": "logloss",
"eta": eta,
"subsample": subsample,
"base_score": np.mean(y)
}
model = xgboost.train(
params,
xgboost_input,
num_rounds,
evals = [(xgboost_input, "test")],
early_stopping_rounds=early_stopping_rounds,
verbose_eval=False
)
shap_values = shap.TreeExplainer(model).shap_values(X)
feature_importances = np.mean(np.abs(shap_values), axis=0)
features = df_subset.drop(columns=["Class", "Dataset", "Dataset type"]).columns
return [feature for feature, importance in sorted(zip(features, feature_importances), key=lambda x: x[1], reverse=True)][0:n]
def linearSVC(df, n, **kwargs):
'''
Select n features with respect to coefficients of LinearSVC.
'''
datasets = kwargs.get("datasets", None)
_df = df if datasets is None else df.loc[df["Dataset"].isin(datasets)]
genes = _df.drop(columns=["Class", "Dataset", "Dataset type"]).columns.to_numpy()
X = _df.drop(columns=["Class", "Dataset", "Dataset type"]).to_numpy()
y = _df["Class"].to_numpy()
c_best = 1.0
delta = float("inf")
for c in np.logspace(-4, 4, 9):
clf = make_pipeline( StandardScaler(),
LinearSVC( penalty='l1', C=c, dual=False))
clf.fit(X, y)
coef = clf.named_steps['linearsvc'].coef_
coef = np.resize(coef,(coef.shape[1],))
m = len(np.nonzero(coef)[0])
if n <= m and delta > m - n:
delta = m - n
c_best = c
clf = make_pipeline( StandardScaler(),
LinearSVC( penalty='l1', C=c_best, dual=False))
clf.fit(X, y)
coef = clf.named_steps['linearsvc'].coef_
coef = np.resize(coef,(coef.shape[1],))
ind = np.nonzero(coef)[0]
np.random.shuffle(ind)
return genes[ind[:n]]
##########################################################################################
HASH = {
'nt_pvalue' : nt_pvalue,
'geffect' : geffect,
'pubmed' : pubmed,
'top_from_file' : top_from_file,
'nt_diff' : nt_diff,
'max_correlation' : max_correlation,
'min_p_value' : min_p_value
}
def get (name):
'''
Get selector by name
Returns:
a selector function if name is its name;
None, otherwise.
'''
return HASH[name] if name in HASH else None
def funcs ():
'''
Get all avaliable selectors
Returns:
list of functions
'''
return list(HASH.values())
def names ():
'''
Get names of all avaliable selectors
Returns:
list of strings
'''
return list(HASH.keys())
|
2f82d7265f9aee810600d24ca4c1198a2dd87bfe | Akshay-Chandelkar/PythonTraining2019 | /Ex41_FuncDemo.py | 252 | 3.734375 | 4 |
# Posiyional arguments
def add(a,b):
return a + b
res = add(10,20)
print("Result = %d"%res)
# Default arguments
def add(a,b=10):
return a + b
res = add(100,200)
print("Result = %d"%res)
res = add(100)
print("Result = %d"%res) |
09e53e0ff7e83a9bc0d40d85cfc058a100f9a490 | luoyi94/Python | /07-面向对象/单例2.py | 1,014 | 3.578125 | 4 | # class Singleton:
# __instance = None
# __has_init = False
#
# def __new__(cls):
# if cls.__instance is None:
# print("创建对象")
# cls.__instance = super().__new__(cls)
# return cls.__instance
# def __init__(self):
# if not self.__hash__():
# print("初始化")
# self.type = "猫"
# self.__has_init = True
#
#
# # 创建了两个对象 却只开辟了同一个内存地址
# s1 = Singleton()
# s1.type = "动漫人物"
# print(s1)
#
# s2 = Singleton()
# s1.type = "哈哈"
# print(s2)
#
#
#
# print(s1.type)
class Shoping:
__instance = None
__has_init = False
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self):
if Shoping.__has_init is False:
self.total_price = 0
Shoping.__has_init = True
cart1 = Shoping()
cart1.total_price = 200
|
7106044722dae51afe02ee0f3d88dc18f664fb57 | ArrogantNobody/leetcode | /algorithms/link_list/82_Remove Duplicates from Sorted List II.py | 1,711 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
tmp = dict()
nodeL = []
while head:
if head.val in tmp:
tmp[head.val] += 1
else:
tmp[head.val] = 1
head = head.next
for i in tmp.keys():
if tmp[i] == 1:
nodeL.append(i)
if not nodeL:
return
else:
nodeL.sort()
newhead = ListNode(nodeL[0])
p = newhead
for i in nodeL[1:]:
p.next = ListNode(i)
p = p.next
return newhead
#====================================================================
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: # 0个或者1个元素不用去重
return head
newhead = ListNode(-1) # 设置dummyhead
newhead.next = head
if head.val != head.next.val: # 如果前两个节点不同,说明第一个节点一定有效
head.next = self.deleteDuplicates(head.next)
else: # 如果前两个节点相同,就一直往后找,直到找到链表结束或者找到跟头节点值不同的节点p
p = head
while p and p.val == head.val:
p = p.next
newhead.next = self.deleteDuplicates(p)
return newhead.next |
d4ad61ffc7dc764159212d50c62254e73ac25029 | santiago-silva/Paradigmas | /Clase1.py | 742 | 4 | 4 | def ejercicio1():
oracion = "Hello World"
print(oracion)
# Imprimir los numeros de 0 a 100 que sean divisibles por 3
def ejercicio3():
for number in range (0, 101):
if number % 3 == 0:
print(number)
def ejercicio5():
userValueList = []
for number in range(10):
userValue = int(input("Ingrese un numero: "))
userValueList.append(userValue)
userValueList.sort()
print(userValueList)
def ejercicio6(number1, number2):
if number1 > number2:
return 1
elif number1 == number2:
return 0
else:
return -1
def main():
#ejercicio1()
#ejercicio3()
#ejercicio5()
userInput1 = int(input("ingrese el numero 1: "))
userInput2 = int(input("ingrese el numero 2: "))
print(ejercicio6(number1, number2))
main() |
28357d0218f8279cc0730f4b7a3fbe873b26c235 | statistics-exercises/t-tests-1 | /main.py | 782 | 3.65625 | 4 | import numpy as np
import scipy.stats
def testStatistic( data, mu0 ) :
# This fucntion should calcualte and return the test statistic T that is
# described in the panel on the right. In order to do so you will need to
# compute the standard deviation.
def pvalue( data, mu0 ) :
# You need to write code to determine the pvalue here. This code will need to
# include a call to test statistic
data = np.loadtxt("mydata.dat")
print("Null hypothesis: the data points in mydata.dat are all samples from a")
print("distribution with an expectation of 5")
print("Alternative hypothesis: the data points in mydata.dat are")
print("from a distribution with an expectation that is greater than 5")
print("The p-value for this hypothsis test is", pvalue( data, 5 ) )
|
bd373af25e3ed2a054ed2fedbd019a7815b55d1b | AuroraBoreas/CSharp_Review_2021 | /_02_C#_pro_c#/src_code/p5_program_with_,NET_assemblies/c17_processes_AppDomains_ObjectContexts/registration.py | 733 | 3.8125 | 4 | """
this module demonstrates how to utilise decorator in Python
@ZL, 20210210
"""
registration = set()
def register(active=True):
def dec(func):
def inner(*args, **kwargs):
if active:
registration.add(func)
else:
registration.remove(func)
return func(*args, **kwargs)
return inner
return dec
@register(active=True)
def hello(name: str) -> str:
return f"hello {name}"
@register()
def add(*args, **kwargs):
for i in args:
print(i, end=" ")
print()
for k, v in kwargs.items():
print(k, v)
if __name__ == '__main__':
greet: str = hello("XY")
add(1,2,3, a=2.7, b=3.1)
print(len(registration))
|
cf9229f1a37bad48241d3c9e3810d31dcbb0f2a3 | Uponn/AdventureGame | /BedroomOne.py | 1,621 | 3.609375 | 4 | import time
from Room import Room
from Player import Player
from Parser import parser_furniture
john = Player()
class BedroomOne(Room):
furniture = ("bed", "closet", "mirror", "mattress")
def __init__(self):
self.__name = "Master Bedroom"
john.set_room(self.get_name())
def room_info(self):
print(
"You've entered the Master Bedroom by the looks of it the mother and the father of the family lived in it."
"Here you can see a {}, {}, a half broken {} and a {} laying on the floor.".format(*self.furniture))
self.action()
def get_name(self):
return self.__name
def action(self):
from SecondFloor import SecondFloor, clear_screen
second_floor = SecondFloor()
choice = input("What now:\n>>> ")
user_choice = parser_furniture(choice, self.furniture)
if user_choice == "bed":
print("You are at the bed but there seems to be nothing useful here.")
time.sleep(1)
self.action()
elif user_choice == "closet":
print("There are some old clothes here, nothing that could be of use.")
time.sleep(1)
self.action()
elif user_choice == "mirror":
print("You look at the broken mirror, you noticed that there is someone behind you, you startle turn around"
"just to see that there is nothing there.")
time.sleep(1)
self.action()
elif user_choice == "mattress":
print("By the looks of it it is the mattress from the bed, just moved to the ground. Strange, seems like someone has been sleeping here")
time.sleep(1)
self.action()
elif choice == "leave":
clear_screen()
print("You return back to the Second Floor")
second_floor.introduction()
|
43cee44470b55bc78ffd154d713e29d59ca9bffe | cesarschool/cesar-school-fp-2018-2-lista2-Fmendes21 | /questoes/questao_4.py | 2,599 | 4.125 | 4 | ## QUESTÃO 4 ##
#
# Escreva um programa que leia uma data do usuário e calcule seu sucessor imediato.
# Por exemplo, se o usuário inserir valores que representem 2013-11-18, seu programa
# deve exibir uma mensagem indicando que o dia imediatamente após 2013-11-18 é
# 2013-11-19. Se o usuário inserir valores que representem 2013-11-30, o programa deve
# indicar que o dia seguinte é 2013-12-01. Se o usuário inserir valores que representem
# 2013-12-31 então o programa deve indicar que o dia seguinte é 2014-01-01. A data
# será inserida em formato numérico com três instruções de entrada separadas;
# uma para o ano, uma para o mês e uma para o dia. Certifique-se de que o seu programa
# funciona corretamente para anos bissextos.
##
##
# A sua resposta da questão deve ser desenvolvida dentro da função main()!!!
# Deve-se substituir o comado print existente pelo código da solução.
# Para a correta execução do programa, a estrutura atual deve ser mantida,
# substituindo apenas o comando print(questão...) existente.
##
def main():
ano = int(input("Digite o ano: "))
mes = int(input("Digite o mês: "))
dia = int(input("Digite o dia: "))
print('A data digita foi {}-{}-{}'.format(ano, mes, dia))
if (ano % 400 == 0) or (ano % 4 == 0 and ano % 100 != 0):
ano_bi = 1
else:
ano_bi = 0
if ano_bi == 1:
if(mes == 1) or (mes == 3) or (mes == 5) or (mes == 7) or (mes == 8) or (mes == 10) or (mes == 12):
if dia == 31:
dia = 1
if mes == 12:
mes = 1
ano += 1
else:
mes += 1
else:
dia += 1
print('A data seguinte será: {}-{}-{}'.format(ano, mes, dia))
else:
if (dia == 29) and (mes == 2):
dia = 1
mes += 1
print('A data seguinte será: {}-{}-{}'.format(ano, mes, dia))
else:
if (dia == 30):
dia = 1
mes += 1
else:
dia += 1
print('A data seguinte será: {}-{}-{}'.format(ano, mes, dia))
else:
if(dia == 31):
dia = 1
if(mes == 12):
mes = 1
ano += 1
else:
mes += 1
else:
if(dia == 28) and (mes == 12):
dia = 1
mes += 1
else:
if(dia == 30):
dia = 1
mes += 1
else:
dia += 1
print('A data seguinte será: {}-{}-{}'.format(ano, mes, dia))
if __name__ == '__main__':
main()
|
75b44fa3b6d3cd32da35ce3277a7f35386c02093 | craleigh318/CS-156 | /Homework 3/sudoku_csp_generator.py | 5,236 | 3.640625 | 4 | __author__ = 'Anthony Ferrero'
import string
NUM_SUDOKU_ROWS = 9
NUM_SUDOKU_COLUMNS = NUM_SUDOKU_ROWS
NUM_BOX_ROWS = 3
EQUAL_STRING = 'eq'
NOT_EQUAL_STRING = 'ne'
LESS_THAN_STRING = 'lt'
GREATER_THAN_STRING = 'gt'
MIN_SUDOKU_CELL_VALUE = 1
MAX_SUDOKU_CELL_VALUE = 9
_last_sudoku_row_letter = 'I'
_last_letter_ind = string.ascii_uppercase.index(_last_sudoku_row_letter)
SUDOKU_ROW_LETTERS = string.ascii_uppercase[:_last_letter_ind + 1]
def cell(cell_letter, cell_number):
return cell_letter + str(cell_number)
def constraint(left_cell, constraint_str, right_cell_or_num):
return left_cell + ' ' + constraint_str + ' ' + str(right_cell_or_num)
def equal_constraint(left_cell, num):
return constraint(left_cell, EQUAL_STRING, num)
def greater_than_constraint(left_cell, right_cell_or_num):
return constraint(left_cell, GREATER_THAN_STRING, right_cell_or_num)
def less_than_constraint(left_cell, right_cell_or_num):
return constraint(left_cell, LESS_THAN_STRING, right_cell_or_num)
def diff_constraint(left_cell, right_cell_or_num):
return constraint(left_cell, NOT_EQUAL_STRING, right_cell_or_num)
def alldiff_list(sudoku_cells):
alldiff = []
for static_index in xrange(len(sudoku_cells)):
cell = sudoku_cells[static_index]
cell_diff = []
for changing_index in xrange(static_index + 1, len(sudoku_cells)):
other_cell = sudoku_cells[changing_index]
cell_diff.append(diff_constraint(cell, other_cell))
alldiff.extend(cell_diff)
return alldiff
def cell_list(letters, numbers):
l = []
for letter in letters:
for number in numbers:
l.append(cell(letter, number))
return l
def row_list(row_num):
letter = string.ascii_uppercase[row_num - 1]
return cell_list([letter], xrange(1, NUM_SUDOKU_COLUMNS + 1))
def column_list(column_num):
return cell_list(SUDOKU_ROW_LETTERS, [column_num])
def box_list(box_num):
box_row_num = ((box_num - 1) // NUM_BOX_ROWS) + 1
box_letters = SUDOKU_ROW_LETTERS[(box_row_num - 1) * 3: box_row_num * 3]
box_column_num = (box_num - ((box_row_num - 1) * NUM_BOX_ROWS))
box_numbers = xrange(((box_column_num - 1) * 3) + 1, (box_column_num * 3) + 1)
l = []
for letter in box_letters:
for number in box_numbers:
l.append(cell(letter, number))
return l
def list_2d_to_1d(list_2d):
return [elem for sublist in list_2d for elem in sublist]
def flat_list(list_maker_function, iterable):
list_2d = [list_maker_function(elem) for elem in iterable]
return list_2d_to_1d(list_2d)
def domain_constraints(flat_row_list):
constraints = [less_than_constraint(cell, MAX_SUDOKU_CELL_VALUE + 1) for cell in flat_row_list]
constraints.extend([greater_than_constraint(cell, MIN_SUDOKU_CELL_VALUE - 1) for cell in flat_row_list])
return constraints
def general_constraints():
rows = [row_list(row_num) for row_num in xrange(1, NUM_SUDOKU_COLUMNS + 1)]
columns = [column_list(col_num) for col_num in xrange(1, NUM_SUDOKU_ROWS + 1)]
boxes = [box_list(box_num) for box_num in xrange(1, NUM_BOX_ROWS ** 2 + 1)]
alldiff_lambda = lambda cells: alldiff_list(cells)
rows_alldiff = flat_list(alldiff_lambda, rows)
columns_alldiff = flat_list(alldiff_lambda, columns)
boxes_alldiff = flat_list(alldiff_lambda, boxes)
sudoku_diffs = []
sudoku_diffs.extend(rows_alldiff)
sudoku_diffs.extend(columns_alldiff)
sudoku_diffs.extend(boxes_alldiff)
flat_row_list = list_2d_to_1d(rows)
result = []
result.extend(domain_constraints(flat_row_list))
result.extend(sudoku_diffs)
return result
# These are taken from the book, page 269, figure 4.
def given_cell_assignments():
return [
equal_constraint('A3', 3),
equal_constraint('A5', 2),
equal_constraint('A7', 6),
equal_constraint('B1', 9),
equal_constraint('B4', 3),
equal_constraint('B6', 5),
equal_constraint('B9', 1),
equal_constraint('C3', 1),
equal_constraint('C4', 8),
equal_constraint('C6', 6),
equal_constraint('C7', 4),
equal_constraint('D3', 8),
equal_constraint('D4', 1),
equal_constraint('D6', 2),
equal_constraint('D7', 9),
equal_constraint('E1', 7),
equal_constraint('E9', 8),
equal_constraint('F3', 6),
equal_constraint('F4', 7),
equal_constraint('F6', 8),
equal_constraint('F7', 2),
equal_constraint('G3', 2),
equal_constraint('G4', 6),
equal_constraint('G6', 9),
equal_constraint('G7', 5),
equal_constraint('H1', 8),
equal_constraint('H4', 2),
equal_constraint('H6', 3),
equal_constraint('H9', 9),
equal_constraint('I3', 5),
equal_constraint('I5', 1),
equal_constraint('I7', 3)
]
def generate_sudoku_csp():
constraints = general_constraints()
constraints.extend(given_cell_assignments())
return '\n'.join(constraints)
if __name__ == '__main__':
sudoku_csp_string = generate_sudoku_csp()
with open('Test Sudoku.txt', 'w+') as sudoku_csp_file:
sudoku_csp_file.write(sudoku_csp_string)
|
c9d883235c78763b90af4ff60a0894ca0cd23c17 | i13flyboy/Assigment2 | /main.py | 7,014 | 3.875 | 4 | """
Name:Kyle Kunz
Date:10/10/2020
Brief Project Description:this is a program that allows you to add places you want ot travel to
and mark off places that you have visited.
GitHub URL: https://github.com/i13flyboy/Assigment2
"""
# Create your main program in this file, using the TravelTrackerApp class
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.properties import StringProperty
from kivy.properties import ListProperty
from place_collection import PlaceCollection
from place import Place
__author__ = 'Kyle Kunz'
sort_dictionary ={'Priority': 'priority', 'Visited': 'is_visited', 'Country': 'country'}
VISITED_COLOUR = (1, 0.5, 1, 1)
NOT_VISITED_COLOUR = (0, 1, 1, 0.7)
BLANK_STRING = ""
class TravelTrackerApp(App):
"""
main program
"""
current_place = StringProperty()
list_codes = ListProperty
program_status_bar = StringProperty()
visited_status_message = StringProperty()
def __init__(self, **kwargs):
"""
makes the main app
"""
super().__init__(**kwargs)
self.place_collections = PlaceCollection()
self.place = Place
self.place_collections.load_places("places.csv")
self.list_codes = sort_dictionary
def build(self):
"""
Build the Kivy GUI.
"""
self.title = "Travel Tracker APP"
self.root = Builder.load_file('app.kv')
self.list_codes = sorted(sort_dictionary.keys())
self.root.ids.select_day.text = self.list_codes[2]
self.dynamic_places()
return self.root
def change_status(self, list_code):
self.root.ids.output_label = sort_dictionary[list_code]
self.place_collections.sort(sort_dictionary[list_code])
def dynamic_places(self):
index = 1
for place in self.place_collections.places:
temp_button = Button(text=str(place), id=str(index))
temp_button.place = place
temp_button.bind(on_release=self.press_entry)
self.root.ids.box_list.add_widget(temp_button)
index = index + 1
return
def press_entry(self, instance):
"""
updates the entry
"""
instance.place.is_visited = True
self.root.ids.status_visited.text = "You visited " + instance.place.country
self.root.ids.box_list.clear_widgets()
self.dynamic_places()
def on_stop(self):
self.place_collections.save_places("places.csv")
print("Bye")
def create_widget(self):
"""
makes all the place buttons
"""
self.update_visited_status_bar()
for index, place in enumerate(self.place_collections.places):
visited_status = BLANK_STRING
if place.is_visited:
colour = VISITED_COLOUR
visited_status = "visited"
else:
colour = NOT_VISITED_COLOUR
temp_button = Button(
text=str("{} {} {} ({})".format(place.city, place.country, place.priority, visited_status)),
id=str(index), background_color=colour)
temp_button.bind(on_release=self.handle__button_press)
self.root.ids.box_list.add_widget(temp_button)
def handle__button_press(self, instance):
"""
handle pressing buttons
"""
index_number = int(instance.id)
if self.place_collections.places[index_number].is_visited:
self.place_collections.places[index_number].place_is_visited()
place_is_not_visited = self.place_collections.places[index_number]
self.update_program_status_bar("You need to visit {}".format(place_is_not_visited))
else:
self.place_collections.places[index_number].place_is_visited()
place_is_visited = self.place_collections.places[index_number]
self.update_program_status_bar("You visited {}".format(place_is_visited))
self.root.ids.box_list.clear_widgets()
self.sort_places(self.root.ids.select_day.text)
def add_new_place(self):
"""
adds new place to the place collection
"""
# Get the text from the text inputs
new_place = self.root.ids.new_place.text
new_country = self.root.ids.new_country.text
new_priority = self.root.ids.new_priority.text
if new_place == BLANK_STRING or new_country == BLANK_STRING or new_priority == BLANK_STRING:
self.update_program_status_bar("All fields must be completed")
else:
try:
new_priority = int(new_priority)
if new_priority < 0:
self.update_program_status_bar("Please enter a number >= 0")
self.update_program_status_bar("Please enter a number <= 0")
else:
self.root.ids.new_place.text = BLANK_STRING
self.root.ids.new_country.text = BLANK_STRING
self.root.ids.new_priority.text = BLANK_STRING
self.place_collections.add_place(
Place(new_place, new_country, new_priority))
self.sort_places(self.root.ids.select_day.text)
self.update_program_status_bar(
"{} {} from {} Added".format(new_place, new_country, new_priority))
except ValueError:
self.update_program_status_bar("Please enter a valid number")
except TypeError:
self.update_program_status_bar("Please enter a valid number")
def update_visited_status_bar(self):
"""
updates on how many places have been visited
"""
self.visited_status_message = "To visited: {}. visited: {}".format(self.place_collections.get_number_not_visited
(),
self.place_collections.get_number_visited())
def update_program_status_bar(self, instance):
"""
updates when ever a function passes through
"""
self.program_status_bar = "{}".format(instance)
def sort_places(self, text):
"""
sort the current places
"""
text = text.lower() # Call lower because it needs to be a capital in the spinner but lower case for sort
if text == "visited":
text = "is_visited"
self.place_collections.sort(text)
self.root.ids.box_list.clear_widgets()
self.create_widget()
def handle_clear(self):
"""
Clear the new place inputs and the status bar
"""
self.root.ids.new_place.text = BLANK_STRING
self.root.ids.new_country.text = BLANK_STRING
self.root.ids.new_priority.text = BLANK_STRING
self.update_program_status_bar(BLANK_STRING)
"""
Run main
"""
if __name__ == '__main__':
TravelTrackerApp().run()
|
2b76dec494f207ac258e73ba9ed9a009554fc9e1 | hiteshd/python-goa | /examples/conditionals/conditionals_1.py | 278 | 4.0625 | 4 |
a = 11
if a > 10 and a < 12:
print "a is greater than 10 but lesser than 12"
elif a < 10 and a > 8:
print "a is lesser than 10 and greater than 8"
elif a > 5 and a < 8:
print "a is greater than 5 and less than 8"
else:
print "i could not find the right range"
|
01c51aeafab790fab658c7031e3412fb97b1435a | JohnSmith9527/snow-flake | /assignment_finished.py | 344 | 3.671875 | 4 | import turtle,random
x=0
y=0
turtle.colormode(255)
for i in range(12):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
r=random.randint(200,255)
g=random.randint(150,200)
b=random.randint(20,100)
turtle.pencolor(r,g,b)
for j in range(2):
turtle.forward(100)
turtle.dot(50)
turtle.left(30) |
35d5f2f21309d41ba68f2185fdcad424eeae0ace | mp/Test-averages | /test_average.py | 564 | 4.03125 | 4 | # GLOBAL CONST for high score
HIGH_SCORE = 95
def main():
# Get 3 scores
test1 = int(input("Enter the score for test 1: "))
test2 = int(input("Enter the score for test 2: "))
test3 = int(input("Enter the score for test 3: "))
# Calculate the average test score
average = (test1 + test2 + test3) / 3
# Print the average
print('The average score is', average)
# If the average is a high score congratulate them
if average >= HIGH_SCORE:
print('Congratulations')
print('That\'s a great average!')
main() |
90f202c2e2f24141aae90d81c495d0f6a67af806 | Acapellia/Algorithm | /Python/Code2011/201118_UnionCycle.py | 729 | 3.890625 | 4 | def findParent(parent,x):
if parent[x] != x:
parent[x] = findParent(parent, parent[x])
return parent[x]
def unionParent(parent,a,b):
a = findParent(parent,a)
b = findParent(parent,b)
if a<b:
parent[b] = a
else:
parent[a] = b
v,e = map(int, input().split())
parent = [0] * (v+1)
for i in range(1,v+1):
parent[i] = i
cycle = False
for i in range(e):
x,y = map(int, input().split())
if findParent(parent,x) == findParent(parent,y):
cycle = True
break
else:
unionParent(parent,x,y)
if cycle == True:
print("사이클이 발생했습니다.")
else:
print("사이클이 발생하지 않았습니다.") |
5184cbb11fe0d93ebece3d2d1198504e1c5aa7c7 | amitp-ai/CS231n_Stanford_Computer_Vision | /assignment1/cs231n/classifiers/softmax.py | 4,024 | 3.75 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_examples = X.shape[0]
num_features = X.shape[1]
num_classes = W.shape[1]
scores = np.dot(X,W)
loss = 0.0
for i in range(num_examples):
scores[i] = scores[i]-np.max(scores[i]) #for numerical stability. See http://cs231n.github.io/linear-classify/#softmax
correct_class_scores = scores[i,y[i]]
SM = np.exp(correct_class_scores)/np.sum(np.exp(scores[i]))
loss += -np.log(SM)
temp1 = np.exp(scores[i])/np.sum(np.exp(scores[i]))
temp1[y[i]] = SM-1
temp1 = np.reshape(temp1,(1,num_classes))
temp2 = np.reshape(X[i],(num_features,1))
dW += np.dot(temp2,temp1)
loss /= num_examples
loss += 0.5*reg*np.sum(W*W)
dW /= num_examples
dW += reg*W
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_examples = X.shape[0]
num_classes = W.shape[1]
scores = np.dot(X,W)
scores_max = np.max(scores,axis=1)
scores_max = np.reshape(scores_max,(num_examples,1))
scores = scores - scores_max #for numerical stability. See http://cs231n.github.io/linear-classify/#softmax
exp_sum = np.sum(np.exp(scores),axis=1)
exp_sum = np.reshape(exp_sum,(num_examples,1))
correct_class_scores = scores[np.arange(num_examples),y]
correct_class_scores = np.reshape(correct_class_scores,(num_examples,1))
SM = np.exp(correct_class_scores)/exp_sum
temp1 = np.exp(scores)/exp_sum
temp1[np.arange(num_examples),y] = np.reshape(SM-1,(num_examples,))
dW = np.dot(X.T,temp1)
dW /= num_examples
dW += reg*W
loss = -np.log(SM)
loss = np.mean(loss)
loss += 0.5*reg*np.sum(W*W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
08010614cd612b40af028deab90f5352739018f2 | MohammadB88/Sci_Prog_Exc | /Prime_check.py | 945 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 22 13:15:00 2019
@author: mb1988
"""
import math
number = int(input('Please enter a positive integer number more than "1": '))
sign_prime = 'true'
i=1
while 2*i+1 <= int(math.sqrt(number)) :
if number%2 == 0 or number%(2*i+1) == 0 :
#print(number, 2*i+1, number%(2*i+1))
sign_prime = 'false'
break
i += 1
print('\nYou entered this number: "{}" '.format(number))
if number <= 1 :
print('\nI asked for a number greater than "1"!!! \nI am sorry but I have to stop the script!!!')
else:
if number == 2 or number == 3:
print('\nYou hit the jackpot!!! \n"{}" is a prime number!'.format(number))
elif sign_prime == 'false' :
print('\nIt seems "{}" is not a prime number! \nMaybe next time you will get more lucky!'.format(number))
else :
print('\nYou hit the jackpot!!! \n"{}" is a prime number!'.format(number))
|
f48af0064e5b726f4fe3cb2e5ced312bbea0e3b0 | bimri/programming_python | /chapter_9/alarm.py | 1,132 | 3.625 | 4 | "Using the after Method"
# flash and beep every second using after() callback loop
'''
Of all the event tools in the preceding list, the after method may be the most interesting.
It allows scripts to schedule a callback handler to be run at some time in the future.
But after doesn’t pause the caller: callbacks are scheduled to occur in the background.
'''
from tkinter import *
class Alarm(Frame):
def __init__(self, msecs=1000): # default = 1 second
Frame.__init__(self)
self.msecs = msecs
self.pack()
stopper = Button(self, text='Stop the beeps!!', command=self.quit)
stopper.pack()
stopper.config(bg='navy', fg='white', bd=8)
self.stopper = stopper
self.repeater()
def repeater(self): # on every N millisecs
self.bell() # beep now
self.stopper.flash() # flash button now
self.after(self.msecs, self.repeater) # reschedule handler
if __name__ == '__main__': Alarm(msecs=1000).mainloop()
|
1dd6fc02604ecff72b7195aa2e46ee07cab49aca | dscjntuc/Data-Structures-and-Algorithms | /Python/FizzBuzz.py | 390 | 4.125 | 4 | def fizzbuzz(n):
for i in range(1,n):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizzbuzz(23)
'''
Time Complexity: O(n)
Sample Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
''' |
ae4ace2c08a6819d0a1fe5fbb8c67d536e45a965 | magentay/CTCI | /Q1.6.py | 841 | 3.65625 | 4 | # Given an image represented by an NxN matrix,
# where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
def rotation(matrix):
if not matrix:
return matrix
n = len(matrix[0])
for layer in range(n/2):
first = layer
last = n - 1 -layer
for i in range(first, last):
offset = i - first
#save top
top = matrix[first][i]
# left ->top
matrix[first][i] = matrix[last -offset][first]
# bottom -> left
matrix[last-offset][first] = matrix[last][last -offset]
# right -> bottom
matrix[last][last-offset] = matrix[i][last]
# top -> right
matrix[i][last] = top
return matrix
|
14b0232491f13139005419016c3e8bb7683607dd | zeynepdenizcankut/technicalAssignment | /maxPathSum-Q3/maxPathSum-Q3/maxPathSum_Q3.py | 1,445 | 3.8125 | 4 |
tri = [[int(s) for s in l.split()] for l in open('data.txt').readlines()]
def maxPathSum(tri):
sum = 0
r = -1 # Initial value of the reference value index
for row in range(len(tri)): #iterate through the rows of the pyramid from top to bottom
max = -1 # Initial value of max, reset at each row
if r == -1: #Top of the pyramid
max = tri[row][0] #Value of the top of the pyramid
r = 0
else:
for i in range(r,r+2): #Diagonally check the two bottom numbers
if tri[row][i] > 1:
for j in range(2,int(tri[row][i])):
if (tri[row][i] % j == 0) and tri[row][i] > max: #check if it's a prime number and if it's higher than the local maximum
max = tri[row][i] #set the number value as local maximum
r = i # set its index to be the reference index for the next row
else: # if the integer number is 0 or 1:
if tri[row][i] > max: #check if it's higher than the local maximum value
max = tri[row][i]
r = i
if max == -1: # if the two numbers are prime
max = -10
if max == -10: #check if both numbers are prime
break
else:
#print (max)
sum += max
return sum
max_test = maxPathSum(tri)
print(max_test) |
abb3966051b72e14ab4affc1c8d980b0330d78be | Boogst/python-basic-course | /src/list.py | 1,295 | 4.25 | 4 | lista = [1, 'hello', 1.34, True, [1, 2, 3]]
numberList = list([1, 2, 3, 4]) # Creando lista, utilizando el constructor.
colores = ['green', 'red', 'blue']
print(dir(lista))
print(lista)
print(numberList)
print(lista[2])
# list.count(value)
print(colores.count('green'))
# Crear una lista con un rango.
l = list(range(1, 10))
print(l)
# Para saber si un elemento esta en una lista, podemos utilizar el operador "in"
print('hello' in lista)
print('bye' in lista)
# Para agregar un nuevo elemento a la lista.
lista.append('bye')
print(lista)
# Para agregar varios elementos a la misma lista.
# Esto no hace una lista dentro de otra.
lista.extend(['green', 'car'])
print(lista)
# Insertar un elemento, con una posicion establecida.
lista.insert(2, 'world')
print(lista)
# list.pop(index) Quitar el ultimo elemento de la lista y me retorna el valor eliminado.
item = lista.pop()
print(lista)
print(item)
# list.remove(value) Para quitar un item en especifico.
lista.remove('green')
print(lista)
# Para ordenar elementos, alfabéticamente
colores.sort()
print(colores)
# Para ordenar de forma inversa
colores.sort(reverse=True)
print(colores)
# lista.index(value) Para ver el indice de un elemento:
print(colores.index('blue'))
# Para limpiar toda la lista.
lista.clear()
print(lista) |
b417f54970846b61b3748a730f3732c33f135539 | leanhill/learning-git-task | /lista_zakupow.py | 459 | 3.609375 | 4 | lista_zakupów={
"piekarnia":["chleb", "pączek","bułki"],
"warzywniak":["marchew", "seler","rukola"]
}
for i, a in lista_zakupów.items():
for b in range (len(a)):
a[b] = a[b].capitalize()
i = i.capitalize()
print("Idę do %s"%i,"i kupuję tu następujące rzeczy:%s"%a)
sum = sum([len(a) for i, a in lista_zakupów.items()])
print("W sumie kupuję %s"%sum, "produktów")
input("Oceń program w skali 1-10")
# Zakończono projekt |
6157b99df95cf9be28b13d514c6cb620fd1a62c9 | RobRoger97/test_tomorrowdevs | /cap4/ex98_Is_a_Number_Prime.py | 535 | 4.28125 | 4 | def isPrime(n):
if n <= 1:
return False
# Check each number from 2 up to but not including n to see if it divides evenly into n
for i in range(2, n):
if n % i == 0:
return False
return True
# Determine if a number entered by the user is prime
def main():
value = int(input("Enter an integer: "))
if isPrime(value):
print(value, "is prime.")
else:
print(value, "is not prime.")
# Call the main function if the file has not been imported
if __name__ == "__main__":
main() |
b244842514001da5d922b5853c538c94ff5980ff | Sona1414/luminarpython | /collections/tuples/set.py | 371 | 4.0625 | 4 | st={1,2,3,4,5}
print(st)
#element has to ne added
#use add function
st.add(6)
print(st)
#how to add multiple values
st.update([7,8])
print(st)
#how to remove values from set
st.remove(7)
print(st)
#how to remove using another method
st.discard(6)
print(st)
#difference btw discard and remove
st.pop()
print(st)
st.pop()
print(st)
st1={True,False,0,1}
st1.pop()
print(st1) |
aacf03ad8f3465c73fb0de4ab0567648a7f7fea5 | skapil/practice-programming | /kickstart/dp/educative/longest_increasing_subsequence.py | 1,091 | 4.3125 | 4 | """
Given a number sequence, find the length of its Longest Increasing Subsequence
(LIS). In an increasing subsequence, all the elements are in increasing order
(from lowest to highest).
Example 1:
Input: {4,2,3,6,10,1,12}
Output: 5
Explanation: The LIS is {2,3,6,10,12}.
Example 1:
Input: {-4,10,3,7,15}
Output: 4
Explanation: The LIS is {-4,3,7,15}.
"""
from types import SimpleNamespace
def longest_increasing_subsequence_rec(input: list):
def helper(cur: int, prev: int):
if cur == len(input):
return 0
start_match = 0
if prev < 0 or input[cur] > input[prev]:
print("Inside the block => ", cur, prev)
start_match = 1 + helper(cur + 1, cur)
print("Outside the block => ", cur, prev)
end_match: int = helper(cur + 1, prev)
print("Final Result", start_match, end_match)
return max(start_match, end_match)
print(helper(0, -1))
print(longest_increasing_subsequence_rec([4, 2, 3, 6, 10, 1, 12]))
print(longest_increasing_subsequence_rec([-4, 10, 3, 7, 15]))
|
ac131153938a935afac18b2f8048903ad6c4b29d | fdmxfarhan/ikiu_python | /test-24 integer.py | 75 | 3.921875 | 4 | a = float(input('Enter a number: '))
if a == int(a):
print("integer")
|
5e0fc51c886c4c3611b7e4578710d99255cdb72e | robvdbogert/adventofcode2016 | /day6.py | 879 | 3.65625 | 4 | class MessageRecovery:
def get_message(self, data, use_most_common_letter=True):
letter_counts = [{} for x in range(0, len(data[0]))]
for line in data:
for index, char in enumerate(line):
if char not in letter_counts[index]:
letter_counts[index][char] = 0
letter_counts[index][char] += 1
result = ''.join([sorted(x, key=lambda k: x[k], reverse=use_most_common_letter)[0] for x in letter_counts])
return result
if __name__ == '__main__':
with open('./input/day6') as f:
data = f.read().split()
recovery = MessageRecovery()
message = recovery.get_message(data)
print('Message using most common letter in each column: ' + message)
message = recovery.get_message(data, False)
print('Message using least common letter in each column: ' + message) |
820635ac4dbd65477e65341e279da9b476685320 | murayama333/sample_code | /src/work/05_misc/41.py | 139 | 3.9375 | 4 | names1 = ["Andy", "Betty", "Carol"]
names2 = ["Alice", "Bob", "Charlie"]
for name1, name2 in zip(names1, names2):
print(name1, name2)
|
ee41ee5bf4f58f31ffd05854128674e5fd22785f | Rub444/-practicas-programacion-orientada-a-objetos- | /program17.py | 516 | 3.75 | 4 | datos = [10, 20, 30, 40, 50]
print(datos[0])
print(datos[2])
print(datos[4])
datos = []
for n in range(1, 11):
dato = int(input("Dime el dato "+ str(n) +": "))
datos.append(dato)
print("Los datos pares son:")
for d in datos:
if d % 2 == 0:
print(d)
nombres = ["enero", "febrero", "marzo", "abril", "mayo", "junio",
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
mes = int(input("Dime el número de mes (1 a 12): "))
print("Se llama:", nombres[mes-1]) |
af0e498adf031cb5182be4f5a165d6a9f578e465 | lengwe/C90_Compiler | /tmp/formative/hard4-got.py | 249 | 3.5 | 4 |
x=9
y=8
def main():
global x
global y
if 0:
if 0:
if 0:
if 0:
else:
if 0:
else:
return 1
return 8
if __name__ == "__main__":
import sys
ret=main()
sys.exit(ret)
|
f62783db5a1a058cb0a66e4303241475fb6ca651 | lychristy/Algorithm | /Array/4. K Sum/2 Difference In Sorted Array.py | 837 | 3.859375 | 4 | #2 Difference In Sorted Array
#Given a sorted array A, find a pair (i, j) such that A[j] - A[i] is identical to a target number(i != j).
#If there does not exist such pair, return a zero length array.
#Assumptions:
#The given array is not null and has length of at least 2.
#If more than one pair of index exits, return the one with ascending order.
class Solution(object):
def twoDiff(self, array, target):
"""
input: int[] array, int target
return: int[]
"""
# write your solution here
if abs(array[len(array) - 1] - array[0]) < abs(target):
return []
res = []
for i in range(len(array) - 1):
for j in range(i + 1, len(array)):
if array[j] - array[i] == target:
return [i, j]
elif array[j] - array[i] == -target:
res = [j, i]
return res |
d64b380a89dd1db865ec5c32ff2b27ed4738ffb2 | Sahil4UI/PythonJan3-4AfternoonRegular2021 | /operators.py | 1,565 | 3.515625 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #Operators
>>> #arithmetical operators -> +,-,/,**,**,%,*
>>> #conditional/relational Operators
>>> #>,<,>=,<=,==(equality operator),!= (not equals)
>>> 1==1
True
>>> 5>=2
True
>>> 1!=1
False
>>> # =(Asignment operator) , ==
>>> #Assignment Operators
>>> x = 5
>>> x
5
>>> x += 1#x=x+1
>>> x
6
>>> x-=2
>>> x
4
>>> x/=2
>>> x
2.0
>>> x**=2
>>> x
4.0
>>> x %=2
>>> x
0.0
>>> #logical operators
>>> #and, or , not
>>> #and - returns true if all conditions are True
>>> 5==5 and 5>=100
False
>>> #or
>>> #or- for true, atleast one condition must be true
>>> 5==5 or 5>=1000
True
>>> #not-> compliment -> Truew->false, FAlse-True
>>> not 5==5
False
>>> #bitwise operators
>>> 23 & 13
5
>>> 23 | 13
31
>>> 13<<2
52
>>> 13<<1
26
>>> 13<<3
104
>>> ~12
-13
>>> ~-12
11
>>> #membership operator
>>> vowels = 'aeiouAEIOU'
>>> 'x' in vowels
False
>>> 'A' in vowels
True
>>> 'A' not in vowels
False
>>> #identity operator
>>> x = 1
>>> y = 1
>>> x == y
True
>>> x is y
True
>>> id(x)
1502559103280
>>> id(y)
1502559103280
>>> x= [1,2,3,4]
>>> y = [1,2,3,4]
>>> x is y
False
>>> x == y
True
>>> id(x)
1502601419712
>>> id(y)
1502601419904
>>> x
[1, 2, 3, 4]
>>> y=x
>>> id(x)
1502601419712
>>> id(y)
1502601419712
>>> x.remove(1)
>>> x
[2, 3, 4]
>>> y
[2, 3, 4]
>>> x = 5
>>> y=x
>>> x
5
>>> y
5
>>> x=5
>>> y
5
>>> x=2
>>> x
2
>>> y
5
>>> x = 456
>>> x=1
>>> y=1
>>> x is y
True
>>> x is not y
False
>>>
|
f129682b4299c18ce0fc1ca5a9f3a2945504aec2 | ruchir-hj/FunAlgoProblems | /leetcode20_valid_parentheses.py | 783 | 3.5 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
openers_to_closers_mapping = {
'{' : '}',
'[' : ']',
'(' : ')'
}
openers = frozenset(openers_to_closers_mapping.keys())
closers = frozenset(openers_to_closers_mapping.values())
openers_stack = []
for char in s:
if char in openers:
openers_stack.append(char)
elif char in closers:
#edge case : if stack is empty
if not openers_stack:
return False
else:
last_unclosed_opener = openers_stack.pop()
if not openers_to_closers_mapping[last_unclosed_opener] == char:
return False
return openers_stack == []
|
22210303ace91dc17cca5e2286e497f6ce90277c | Chadyka/python-projects | /8_classes/queue-with-stacks.py | 1,002 | 4 | 4 | #!/usr/bin/env python3
# coding: utf-8
class Queue:
def __init__(self):
self.s1 = []
self.s2 = []
def __str__(self):
return str(self.s1)
def append(self, x):
while len(self.s1) != 0:
self.s2.append(self.s1[-1])
self.s1.pop()
self.s1.append(x)
while len(self.s2) != 0:
self.s1.append(self.s2[-1])
self.s2.pop()
def popleft(self):
return self.s1.pop() if len(self.s1) != 0 else None
def is_empty(self):
return True if len(self.s1) == 0 else False
def size(self):
return len(self.s1)
def main():
q = Queue()
print(q.is_empty())
q.append(1)
q.append(2)
q.append(3)
q.append(4)
print(q)
print(q.is_empty())
q.popleft()
print(q)
print(q.size())
q.popleft()
q.popleft()
print(q.size())
q.popleft()
print(q)
print(q.size())
print(q.is_empty())
if __name__ == '__main__':
main()
|
c96dded56a0c6ba8b0653afe264818ae28bc0379 | elitan/euler | /093/main.py | 2,344 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
By using each of the digits from the set, {1, 2, 3, 4}, exactly once, and making use of the four arithmetic operations (+, −, *, /) and brackets/parentheses, it is possible to form different positive integer targets.
For example,
8 = (4 * (1 + 3)) / 2
14 = 4 * (3 + 1 / 2)
19 = 4 * (2 + 3) − 1
36 = 3 * 4 * (2 + 1)
Note that concatenations of the digits, like 12 + 34, are not allowed.
Using the set, {1, 2, 3, 4}, it is possible to obtain thirty-one different target numbers of which 36 is the maximum, and each of the numbers 1 to 28 can be obtained before encountering the first non-expressible number.
Find the set of four distinct digits, a < b < c < d, for which the longest set of consecutive positive integers, 1 to n, can be obtained, giving your answer as a string: abcd.
"""
import sys
import itertools
import time
sys.path.append("../")
import functions as f
def perm_parenthesis(s):
ret_array = []
ret_array.append(("%s" % s))
ret_tmp = "(((%s)%s)%s)" % (s[0:7], s[7:11], s[11:])
ret_array.append(ret_tmp)
ret_tmp = "(%s)%s(%s)" % (s[0:7], s[7:8], s[8:])
ret_array.append(ret_tmp)
ret_tmp = "(%s)%s" % (s[0:11], s[11:])
ret_array.append(ret_tmp)
return ret_array
perm_numbers = list(itertools.combinations([str(float(i)) for i in range(1, 10)], 4))
sum_set = set()
highest = 0
highest_numbers = 0;
highest_sum_set = 0;
for n in perm_numbers:
#n = [4.0, 5.0, 6.0, 8.0]
sum_set = set()
for number in itertools.permutations(n):
comb_with_replacement_operators = itertools.combinations_with_replacement("*/+-", 3)
for op in comb_with_replacement_operators:
perm_operators = set(itertools.permutations(list(op)))
for operator in perm_operators:
# create string of numbers and operators
s = ""
s += "%s%s" % (number[0], operator[0])
s += "%s%s" % (number[1], operator[1])
s += "%s%s" % (number[2], operator[2])
s += "%s" % (number[3])
for perm in perm_parenthesis(s):
try:
res_tmp = eval(perm)
if res_tmp == int(res_tmp):
sum_set.add(abs(int(round(eval(perm)))))
except:
pass
i = 1
while i in sum_set:
i += 1
if i-1 > highest:
highest = i-1
highest_numbers = [int(float(i)) for i in list(n)]
highest_sum_set = sum_set
print(highest)
print(highest_numbers)
print(highest_sum_set) |
6a4be0db3be8b54f5f65b2bbf56b63149c442461 | kpodlaski/NeuralNetworks2018 | /tablice_i_listy.py | 503 | 3.765625 | 4 | lista = []
lista2 = ['a', "b", 'c']
lista.append(2)
lista.append(3)
lista.insert(1,"bb")
for x in lista:
print (x)
print (lista2)
print (lista[2])
a= lista.pop()
print (lista)
a ="Ala ma Kota"
print(a[4])
print(a[4::])
print(a[4::6])
print(a[4:-2:])
def tuple_test(x):
a,b = x, x*x
return a,b
w = tuple_test(3)
print (w)
print (w[0])
v = (2,4)
print (w+v)
x = float ('inf')
print(x*3)
print(3//x)
c = complex(2,7)
print(c)
c= c.conjugate()
print(c**2);
print(str(c.real) + " "+ str(c.imag))
|
907160443fd9ce6260515942ef11e1382ce71ecf | phucduongBKDN/100exercies | /100 exercise/no150.py | 314 | 3.671875 | 4 | #Valid Parentheses
input = "()[]{}"
def solution(s):
pars = [None]
parmap = {')': '(', '}': '{', ']': '['}
for c in s:
if c in parmap:
if parmap[c] != pars.pop():
return False
else:
pars.append(c)
return len(pars) == 1
print(solution(input)) |
7e36596bc6eb48b56e6ae7fe7dda767c1ecfa27c | AndreaEdwards/AndreaEdwards.github.io | /other/code_review/code_review_052815.py | 4,869 | 3.84375 | 4 | #Parsing a fastq file using BioPython
"""
What does it mean to parse a file?
Parsing (syntactic analysis) is the process of analysing a string of symbols
that conform to a particular set of rules.
This means that in order to parse a file, you have to know ahead of time What
the format of that file is.
Things to ask yourself:
1. What is the format of the file you are trying to extract information from?
2. What information are you trying to extract from the file?
A fastq file normally uses four lines per sequence:
1. Always begins with the '@' character and is followed by a sequence identifies
2. Always the raw sequence
3. Always begins with a + character and is optionally followed by the same sequence identifier.
4. Always encodes the quality values for the sequence in line 2 and must contain the same number
of symbols as the letters in the raw sequence.
Let's look at a .fastq file.
Always check that the file is in the correct format before you begin to write or apply
a parser.
Here is an example function. The question I was asking is: how many reads above 30nt are in this file?
"""
def parse_fastq(file_name):
fastq_dict = {}
file = open(file_name)
file_content = file.readlines()
i = 0
while i < len(file_content):
if i % 4 == 0:
fastq_dict[file_content[i].strip('\n')] = file_content[i+1].strip('\n')
i += 1
else:
i += 1
return fastq_dict
fastq_dict = parse_fastq("/Users/Andrea/Desktop/code_review/Sample_R1.fastq")
print fastq_dict
def filter_by_length(fastq_dict, filter_length):
filtered_dict = {}
for key in fastq_dict:
if len(fastq_dict[key]) >= filter_length:
filtered_dict[key] = fastq_dict[key]
return filtered_dict
filtered_dict = filter_by_length(fastq_dict, 30)
print filtered_dict
percent = (float(len(filtered_dict))/len(fastq_dict)) * 100
print percent
"""
How to find out if BioPython contains a utility you are interested in?
Consult the documents!! Look at website for example.
Here is an example of using the parse method of the SeqIO object to print out
all the sequences in the fastq file.
"""
from Bio import SeqIO
handle = open("/Users/Andrea/Desktop/code_review/Sample_R1.fastq")
for record in SeqIO.parse(handle, "fastq"):
print record.seq
handle.close()
"""
Bio.SeqIO is the sequence input/output interface for BioPython. For implementations,
see the tutorials (there are many).
Bio.SeqIO provides a simple uniform interface to input and output assorted
sequence file formats (including MSAs), but will only deal with sequences as
SeqRecord formats.
What is Bio.SeqIO?
What is a SeqRecord object?
In BioPython, sequences are usually held as Seq objects, which hold the sequence
and an associated alphabet. The Seq object essentially combines a Python string with
an (optional) biological alphabet.
"""
from Bio.Seq import Seq
my_seq = Seq("AGTACACTGGT")
print my_seq
#Seq('AGTACACTGGT', Alphabet())
print my_seq.alphabet
#Alphabet()
"""
In the above example, we haven't specified an alphabet so we end up with a default
generic alphabet. Biopython doesn't know if this is a nucleotide sequence or a
protein rich in alanines, glycines, cysteines and threonines. If you know, you
should (can) supply this information.
"""
#from Bio.Seq import Seq
from Bio.Alphabet import generic_dna, generic_protein
my_seq = Seq("AGTACACTGGT")
print my_seq
#Seq('AGTACACTGGT', Alphabet())
my_dna = Seq("AGTACACTGGT", generic_dna)
print my_dna
#Seq('AGTACACTGGT', DNAAlphabet())
my_protein = Seq("AGTACACTGGT", generic_protein)
print my_protein
#Seq('AGTACACTGGT', ProteinAlphabet())
"""
Supplying this information is important because it allows for error handling.
For example, it doesn't make any sense to concatentate a protein and nucleotide
sequence, so BioPython will throw an error if you try to do this.
"""
my_protein + my_dna
#Traceback (most recent call last):
#...
#TypeError: Incompatable alphabets ProteinAlphabet() and DNAAlphabet()
"""
Similarly, an error will be thrown if you try to do something like translate
a protein sequence.
"""
"""
The Seq object has a number of methods which act just like those of a Python
string (For example, the find and count methods).
"""
#rom Bio.Seq import Seq
#from Bio.Alphabet import generic_dna
my_dna = Seq("AGTACACTGGT", generic_dna)
print my_dna
#Seq('AGTACACTGGT', DNAAlphabet())
my_dna.find("ACT")
#5
my_dna.find("TAG")
#-1
my_dna.count("GG")
#note that count is non-overlapping
"AAAAAAA".count("AA")
"""
BioPython has several built-in functions for biological applications:
complement, reverse complement, translation, back translation
"""
#from Bio.Seq import Seq
#from Bio.Alphabet import generic_dna
#my_dna = Seq("AGTACACTGGT", generic_dna)
print my_dna
my_dna.complement()
#Seq('TCATGTGACCA', DNAAlphabet())
my_dna.reverse_complement()
#Seq('ACCAGTGTACT', DNAAlphabet())
my_dna.transcribe()
|
624a678cc9b46e4f3254702e460ac84ecd868f39 | MikeDev0X/PythonPracticeEcercises | /ciclos/while promedio.py | 359 | 3.625 | 4 | #Miguel Jiménez
def tecla():
i=0
contador=0
suma=0
while i>=0:
i=int(input('tecla: \n'))
if i<0:
break
else:
suma=0
suma=suma+i
contador+=suma
if contador!=0:
print('El promedio es: ',(suma)/(contador))
tecla()
|
aec2f6127c90189b6f4a681a36fb2d90d828edd1 | mc-suchecki/WMH | /test/graph.py | 1,159 | 3.703125 | 4 | # Python module for generating random complete graphs.
# Author: Maciej 'mc' Suchecki
import random
import string
import itertools
# generates random complete graph with desired amount of verticles
# and saves the edges to selected filename
# verticles count is max 26, because of conversion to letters
def saveRandomGraphToFile(filename, verticlesCount):
graphFile = open(filename, "w")
verticles = list(string.ascii_uppercase)
verticles = verticles[:verticlesCount]
# iterate over every possible pair containing two different verticles - which
# means every edge in undirected complete graph - and write it to the file
for edge in itertools.combinations(verticles, 2):
weight = str(random.randint(1, 100))
graphFile.write(edge[0] + " " + edge[1] + " " + weight + "\n")
graphFile.close()
# generates multiple random graphs and saves them to files
def saveRandomGraphsToFiles(graphsCount, verticlesCount):
filenamesList = []
for number in range(0, graphsCount):
filename = './graph' + str(number) + '.txt'
saveRandomGraphToFile(filename, verticlesCount)
filenamesList.append(filename)
return filenamesList
|
ac9ecb22ffa16b5a9a0c3292b5b6fd0858e928f7 | kelr/practice-stuff | /maths/factorial.py | 216 | 4.0625 | 4 | def factorial(n):
if n < 0:
print("Input must be a non negative integer please")
return
if n <= 1:
return 1
curr = 1
for i in range(n, 1, -1):
curr *= i
return curr |
ca6eff32e27fbfa1af0f0b5cffa13758f0d1e2af | boyac/pyUndefined | /Project_undefined/py_Novice_Pro/Project_01/Project_01_proto/rules_proto.py | 1,691 | 3.875 | 4 | # Heading is a block that consisis of only one line, which has a length of at most 70 characters. If the block ends with a colon, it is not a heading
# The title is the first block in the document, provided that it is a heading
# A list item is a block that begins with a hyphen(-).
# A list begins between a block that is not a list item and a following list item and ends between a list item and a following block that is not a list item
class Rule:
def action(self, block, handler):
handler.start(self.type)
handler.feed(block)
handler.end(self.type)
return True # to stop rule processing
class HeadingRule(Rule):
type = 'title'
first = True
def condition(self, block):
if not self.first:
return False
self.first = False
return HeadingRule.condition(self, block)
class TitleRule(HeadingRule):
type = 'title'
first = True
def condition(self, block):
if not self.first:
return False
self.first = False
return HeadingRule.condition(self, block)
class ListItemRule(Rule):
type = 'listitem'
def condition(self, block):
return block[0] == '-'
def action(self, block, handler):
handler.start(self.type)
handler.feed(block[1:].strip())
handler.end(self.type)
return True
class ListRule(ListItemRule):
type = 'list'
inside = False
def condition(self, block):
return True
def action(self, block, handler):
if not self.inside and ListItemRule.condition(self, block):
handler.start(self.type)
self.inside = True
elif self.inside and not ListItemRule.condition(self, block):
handler.end(self.type)
self.inside = False
return False
class ParagraphRule(Rule):
type = 'paragraph'
def condition(self, block):
return True
|
ef9d2f0f5286bef04bcf3048ea78ce2269dc6e03 | nandansn/pythonlab | /learnings/Loops/simpleforloop.py | 778 | 4.625 | 5 | # For loops iterate over a given sequence
names = ["nanda", "nilesh", "ashtoush"]
for name in names:
print(name)
for numbers in (1,2,3):
print(numbers)
# For loops can iterate over a sequence of numbers using the "range" and "xrange" functions.
# The difference between range and xrange is that the range function returns a new list with numbers of that specified range,
# whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange).
# Note that the range function is zero based.
for number in range(10,20):
print(number)
#range and xrange takes 3 param, start,stop and step.
#start initial value, stop final value and step is increment and decrement.
for number in range(1,20,2):
print(number)
|
96b97ac77708c6aa2bca37390447623a478c155a | sts-sadr/cvhub | /all/chapter_03/Number_07.py | 1,455 | 3.859375 | 4 | """
Bitwise Operations
AND, OR, NOT, XOR
For grayscale binary images the pixel value 0 means off and value greater than 0 means on.
AND:
The bitwise AND operation of two image arrays calculates element-wise conjunction.
Bitwise AND can also be performed with an array and a scalar.
OR:
The bitwise OR operation calculates element-wise disjunction of two arrays or an array and a scalar.
NOT:
Bitwise NOT inverts the bit values of its operand.
XOR:
A bitwise XOR of the two operands “a” and “b” results in 1 if either but not both “a” or “b”
is 1; otherwise, the result is 0.
"""
import cv2
import numpy as np
# Creating a circle
circle = cv2.circle(np.zeros((500, 500, 3), dtype="uint8"), (250, 250), 90, (255, 255, 255), -1)
cv2.imshow("A white circle", circle)
# Creating a square
square = cv2.rectangle(np.zeros((500, 500, 3), dtype="uint8"), (250, 250), (100, 100),
(255, 255, 255), -1)
cv2.imshow("A white square", square)
# Bitwise AND
bitwise_and = cv2.bitwise_and(circle, square)
cv2.imshow("Bitwise AND", bitwise_and)
# Bitwise OR
bitwise_or = cv2.bitwise_or(circle, square)
cv2.imshow("Bitwise OR", bitwise_or)
# Bitwise NOT
bitwise_not = cv2.bitwise_not(circle)
cv2.imshow("Bitwise NOT", bitwise_not)
# Bitwise XOR
bitwise_xor = cv2.bitwise_xor(circle, square)
cv2.imshow("Bitwise XOR", bitwise_xor)
cv2.waitKey(0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.