blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
1bd1eee00210e861a7f4cc329e6298d978cf8ce4
|
lvrbanec/100DaysOfCode_Python
|
/Project08. Beginner, Blind bid decision/main.py
| 1,094 | 4.15625 | 4 |
# 03.02.21, Frollo
# level: Beginner
# project: Create a blind bid program
from replit import clear
from art import logo
print(logo)
# add a new bidder function
bidder_info = [] # could be also saved as {name1: amount1, name2: amount2}
def add_bidder_info(val_name, val_bid):
new_bidder = {"name": val_name, "bid": val_bid}
bidder_info.append(new_bidder)
# find the highest bidder function
def find_highest_bidder(list_of_dictionary):
max_bid = 0
for dictionary in list_of_dictionary:
bid = dictionary["bid"]
if bid > max_bid:
max_bid = bid
max_name = dictionary["name"]
print(f'Highest bid is {max_bid}$ bidded by {max_name}.')
# save info about the bidders
will_continue = True
while will_continue:
input_name = input("What is your name?\n")
input_bid = float(input("What's your bid?\n$"))
input_continue = input("Are there any other bidders? Type 'yes' or 'no'.\n")
add_bidder_info(val_name = input_name, val_bid = input_bid)
clear()
if input_continue == "no":
will_continue = False
print(bidder_info)
find_highest_bidder(bidder_info)
|
07453d6cd3191a976c28147f7a4095e4c0bff300
|
AFishyOcean/py_unit_two
|
/age.py
| 161 | 3.84375 | 4 |
age =int(input('How old are you?'))
old_age = (100 - age)
year_of_age = (2021 + old_age)
print('You will be 100 years old in', old_age, 'years in', year_of_age)
|
93798cd63ba8a244e6ef6039368b4ab053fd5816
|
alexnhan/CrackingTheCodingInterview
|
/Chapter1/rotateMatrix.py
| 429 | 4.03125 | 4 |
#!/usr/bin/python
# Question 1.7
# ith row becomes N-1-ith column
def rotateMatrix(mat,N):
# create an empty matrix to hold rotated matrix
newMat=[]
for i in range(N):
newMat.append(range(N)) # size newMat the same as mat
for i in range(N):
for j in range(N):
newMat[j][N-1-i]=mat[i][j]
return newMat
if __name__=="__main__":
mat=[[1,2,3,4],[4,5,6,7],[7,8,9,10],[10,11,12,13]]
N=4
print mat,rotateMatrix(mat,N)
|
71d2f68bb1c4866381b5bd1350e10ddff84b1200
|
Shirados9/MaschineLearningSS20
|
/src/explore/dictonaries/explore_dicts.py
| 203 | 3.515625 | 4 |
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year" : 1964
}
print(type(thisdict.values()))
print(thisdict.values())
values = thisdict.values()
for x in thisdict.values():
print(x)
|
b5567628bd4f086980f68d366562471c6831ccfa
|
demar01/python
|
/Chapter_PyBites/180_Group_names_by_country/names.py
| 903 | 3.578125 | 4 |
from collections import defaultdict
data = """last_name,first_name,country_code
Watsham,Husain,ID
Harrold,Alphonso,BR
Apdell,Margo,CN
Tomblings,Deerdre,RU
Wasielewski,Sula,ID
Jeffry,Rudolph,TD
Brenston,Luke,SE
Parrett,Ines,CN
Braunle,Kermit,PL
Halbard,Davie,CN"""
def group_names_by_country(data: str = data) -> defaultdict:
countries = defaultdict(list)
for line in data.splitlines():
name, surname, country = line.split(",")
countries[country].append(f"{surname} {name}")
return countries
#group_names_by_country(data)
# dep = [('Sales', 'John Doe'),
# ('Sales', 'Martin Smith'),
# ('Accounting', 'Jane Doe'),
# ('Marketing', 'Elizabeth Smith'),
# ('Marketing', 'Adam Doe')]
# from collections import defaultdict
# dep_dd = defaultdict(list)
# for department, employee in dep:
# dep_dd[department].append(employee)
# set(dir(defaultdict)) - set(dir(dict))
|
f4fa3ecc341adce4c0e2c88f49537319eac38f6a
|
lreimer/fast-fibonacci
|
/src/test/polyglot/fibonacci.py
| 487 | 4.03125 | 4 |
print('Fibonacci in Python on GraalVM!')
n = 42
def fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def fibonacci_iter(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
a = 1
b = 1
for i in range(2, n):
c = a + b
a = b
b = c
return b
print("{0}'s fibonacci value is {1}".format(n, fibonacci(n)))
|
624e6f5faeda1783ad359b70a85b31cf0aea2cd1
|
pintuiitbhi/Codechef
|
/JulyLongChallenge2018/NSA.py
| 2,640 | 3.75 | 4 |
T = int(input())
def partition(arr,low,high):
i = ( low-1 ) # index of smaller element
pivot = arr[high] # pivot
for j in range(low , high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr,low,high):
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr,low,high)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
import numpy as np
# Python Program to find
# prefix sum of 2d array
#R = 4
#C = 5
# calculating new array
def prefixSum2D(a,R,C) :
#global C, R
psa = [[0 for x in range(C)]
for y in range(R)]
psa[0][0] = a[0][0]
# Filling first row
# and first column
for i in range(1, C) :
psa[0][i] = (psa[0][i - 1] +
a[0][i])
for i in range(0, R) :
psa[i][0] = (psa[i - 1][0] +
a[i][0])
# updating the values in
# the cells as per the
# general formula
for i in range(1, R) :
for j in range(1, C) :
# values in the cells of
# new array are updated
psa[i][j] = (psa[i - 1][j] +
psa[i][j - 1] -
psa[i - 1][j - 1] +
a[i][j])
# # displaying the values
# # of the new array
# for i in range(0, R) :
# for j in range(0, C) :
# print (psa[i][j],
# end = " ")
# print ()
return psa
for test_case in range(T):
S = input()
#l=[ord(c) for c in S]
N=len(S)
#quickSort(l,0,N-1)
matrix=np.zeros([26,N],dtype=int)
for i in range(N):
matrix[ord(S[i])-97][i]=1
prefix_sum=prefixSum2D(matrix,26,N)
for k in range(N):
for i in range(1, R) :
for j in range(1, C) :
# values in the cells of
# new array are updated
psa[i][j] = (psa[i - 1][j] +
psa[i][j - 1] -
psa[i - 1][j - 1] +
a[i][j])
print(matrix)
print(prefix_sum)
|
771329aa614d4765f709dea7a00095edaca4ed3f
|
appupratik/ADV_Python
|
/02-Assignment.py
| 2,718 | 3.59375 | 4 |
#Question 1
#The SHIELD is a secretive organization entrusted with the task of guarding the world against any disaster. Their arch nemesis is the organization called HYDRA. Unfortunately some members from HYDRA had infiltrated into the SHIELD camp. SHIELD needed to find out all these infiltrators to ensure that it was not compromised. Nick Fury, the executive director and the prime SHIELD member figured out that every one in SHIELD could send a SOS signal to every other SHIELD member he knew well. The HYDRA members could send bogus SOS messages to others to confuse others, but they could never receive a SOS message from a SHIELD member. Every SHIELD member would receive a SOS message ateast one other SHIELD member, who in turn would have received from another SHIELD member and so on till NickFury. SHIELD had a sophisticated mechanism to capture who sent a SOS signal to whom. Given this information, Nick needed someone to write a program that could look into this data and figure out all HYDRA members.
#Sample Input
'''
Nick Fury : Tony Stark, Maria Hill, Norman Osborn
Hulk : Tony Stark, HawkEye, Rogers
Rogers : Thor,
Tony Stark: Pepper Potts, Nick Fury
Agent 13 : Agent-X, Nick Fury, Hitler
Thor: HawkEye, BlackWidow
BlackWidow:Hawkeye
Maria Hill : Hulk, Rogers, Nick Fury
Agent-X : Agent 13, Rogers
Norman Osborn: Tony Stark, Thor
'''
#Sample Output
#Agent 13, Agent-X, Hitler
dict1 = { 'Nick Fury': ['Tony Stark', 'Maria Hill', 'Norman Osborn'],
'Hulk' : ['Tony Stark', 'HawkEye', 'Rogers'],
'Rogers' : ['Thor'],
'Tony Stark': ['Pepper Potts', 'Nick Fury'],
'Agent 13' : ['Agent-X', 'Nick Fury', 'Hitler'],
'Thor': ['HawkEye', 'BlackWidow'],
'BlackWidow':['Hawkeye'],
'Maria Hill' : ['Hulk', 'Rogers', 'Nick Fury'],
'Agent-X' : ['Agent 13', 'Rogers'],
'Norman Osborn': ['Tony Stark', 'Thor']
}
list1 = []
list2 = []
list1.append(('Nick Fury',1))
for el in dict1['Nick Fury']:
list1.append((el,0))
for k,v in enumerate(list1):
if list1[k][1] == 0:
temp = list(list1[k])
temp[1] = 1
list1[k] = tuple(temp)
if list1[k][0] in dict1.keys():
for el in dict1[list1[k][0]]:
addVal = 0
for item in list1:
if item[0] == el:
addVal = 1
break
if addVal == 0:
list1.append((el,0))
for key in dict1.keys():
for val in dict1[key]:
list2.append(val)
list2 = list(set(list2))
final_list, addVal = zip(*list1)
final_list = list(final_list)
for person in final_list:
list2.remove(person)
list2.sort()
print ('\nMembers of HYDRA are:')
a = 1
for i in list2:
print("\t",a,i)
a +=1
|
9364772e75a94ec85ce7cec7869dd9029b82086c
|
TheThornBirds/pythonworker
|
/bases/tuple.py
| 695 | 4.34375 | 4 |
classmates = ('刘刘', '晨晨', 'charles') #tuple和list类似,但是tuple一旦初始化就不能修改
print(classmates)
t = () #定义一个空的tuple
t = (1,) #定义只有一个元素的tuple必须加一个逗号,消除歧义
print(t)
t = ('a', 'b', ['A', 'B']) #"可变"的tuple,这里变得不是tuple的元素,而是list的元素。
t[2][0] = 'x'
t[2][1] = 'y'
print(t)
#练习:用索引取出下面list的指定元素:
# -*- coding: utf-8 -*-
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# 打印Apple:
print(L[0][0])
# 打印Python:
print(L[1][1])
# 打印Lisa:
print(L[2][2])
print(L[-1][-1])
|
1e68153a0856330398eb698c211b4ca5ea4d3b4f
|
akashvshroff/Puzzles_Challenges
|
/k_goodness_string.py
| 1,059 | 3.5625 | 4 |
def min_ops(n, k, s):
"""
Charles defines the goodness score of a string as the number of indices
i such that Si≠SN−i+1 where 1≤i≤N/2 (1-indexed). For example, the string
CABABC has a goodness score of 2 since S2≠S5 and S3≠S4.
Charles gave Ada a string S of length N, consisting of uppercase letters
and asked her to convert it into a string with a goodness score of K. In one
operation, Ada can change any character in the string to any uppercase letter.
Could you help Ada find the minimum number of operations required to transform
the given string into a string with goodness score equal to K?
"""
score = 0
limit = n//2
for i in range(n):
if i < limit and s[i] != s[n-i-1]:
score += 1
if score == k:
return 0
else:
return abs(k - score)
if __name__ == '__main__':
test = int(input())
for t in range(test):
n, k = map(int, input().split())
s = input()
ans = min_ops(n, k, s)
print(f'Case #{t+1}: {ans}')
|
6bd01ced108b9ea56ff11bcfd4bbcef37cab1dad
|
renanreyc/linguagem_python
|
/algoritmos/AeC/questao08.py
| 336 | 4.15625 | 4 |
#Python
num = int(input("Informe um número inteiro: "))
while num < 0:
num = int(input("Número inválido. Digite um número maior ou igual a 0: "))
#Função
def fatorial(num):
fatorial = 1
for i in range(num, 0, -1):
fatorial *= i
return fatorial
print(f"\nO valor do fatorial de {num} é:",fatorial(num))
|
3dd33013cb8c044e85b0a031a49cf34382cfc419
|
pondycrane/algorithms
|
/om_api/deck_of_cards/deck_of_cards.py
| 2,899 | 3.828125 | 4 |
import abc
import collections
import random
import unittest
class Card:
def __init__(self, number, color, suit, folded=False):
self.number = number
self.color = color
self.suit = suit
self.folded = folded
def fold(self):
self.fold = not self.fold
def __str__(self):
return f'{self.__class__.__name__}, num: {self.number}, suit: {self.suit}, color: {self.color}'
class FaceCard(Card): pass
class NumberCard(Card): pass
class GhostCard(Card):
def __init__(self, number=-1, color='Black', suit='Ghost', folded=False):
self.number = -1
self.color = 'Black'
self.suit = 'Ghost'
self.folded = folded
class DeckOfCards(abc.ABC):
def __init__(self, size):
self.size = size
self.cards = []
def shuffle(self):
random.shuffle(self.cards)
def draw(self):
return self.cards.pop()
@abc.abstractmethod
def new_deck(self, factory):
"""
Create a new deck of cards. Supply a factory to create new deck.
"""
class HouseDeck(DeckOfCards):
def __init__(self, size=54):
super().__init__(size=54)
def new_deck(self, factory):
self.cards = []
for suit in ['diamond', 'heart', 'spade', 'club']:
for i in range(1, 14):
self.cards.append(factory.add_card(i, suit))
self.cards.extend([GhostCard() for i in range(2)])
self.shuffle()
class BlackJackDeck(DeckOfCards):
def __init__(self, size=5):
super().__init__(size=5)
def new_deck(self, house: HouseDeck):
self.cards = [house.draw() for i in range(self.size)]
class CardFactory(abc.ABC):
def __init__(self):
self.COLOR_CONFIG = collections.defaultdict(lambda x: 'BLACK')
self.COLOR_CONFIG['diamond'] = 'RED'
self.COLOR_CONFIG['heart'] = 'RED'
self.COLOR_CONFIG['spade'] = 'BLACK'
self.COLOR_CONFIG['club'] = 'BLACK'
@abc.abstractmethod
def add_card(self, number, suit):
"""
Add a new card based on the info provided.
"""
class HouseCardFactory(CardFactory):
def add_card(self, number, suit):
if number in [11, 12, 13]:
card = Card(number, self.COLOR_CONFIG[suit], suit)
elif 1 <= number <= 10:
card = NumberCard(number, self.COLOR_CONFIG[suit], suit)
elif number == -1:
card = GhostCard()
else:
raise ValueError(f'Card number {number} not supported')
return card
class Test(unittest.TestCase):
def test_house_deck(self):
doc = HouseDeck()
doc.new_deck(HouseCardFactory())
assert len(doc.cards) == 54
def test_blackjack_deck(self):
doc = HouseDeck()
doc.new_deck(HouseCardFactory())
bj = BlackJackDeck()
bj.new_deck(doc)
assert len(bj.cards) == 5
|
b75a0ddb353a3f00bab4fb9f512e5c887b95c3fe
|
Henri-J-Norden/solve-system
|
/solve_system.py
| 3,784 | 3.53125 | 4 |
from fractions import Fraction
def _div(l, divider, new=False):
if new:
ln = []
for i in range(len(l)):
if new:
ln.append(Fraction(l[i], divider))
else:
l[i] = Fraction(l[i], divider)
if new:
return ln
def _sub(l, lSub):
for i in range(len(l)):
l[i] -= lSub[i]
# performs the transformation in place
def gauss(l, col=0, log=False):
print("Column " + str(col+1))
for r in range(len(l)):
print("Row " + str(r+1))
if len(l) <= col or l[col][col] == 0 or l[r][col] == 0:
continue
if r == col:
_div(l[r], l[r][col])
print(getMatrix(l))
continue
subtract = _div(l[col], Fraction(l[col][col], l[r][col]), True)
_sub(l[r], subtract)
print(getMatrix(l))
if len(l[0]) > col+2:
gauss(l, col+1)
def isComplete(l):
for r in range(len(l)):
for c in range(len(l)):
if r == c:
if l[r][c] != 1:
return False
continue
if l[r][c] != 0:
return False
return True
def getInput():
size = [int(input("Matrix rows: "))]
cols = input("Matrix columns (leave empty for " + str(size[0]+1) + "): ")
if len(cols) == 0:
size.append(size[0] + 1)
else:
size.append(int(cols))
l = [[] for i in range(size[0])]
if size[0] < 2 or size[1] <= size[0]:
print("<rows> must be larger than 2 and <cols> must be larger <rows> + 1!")
return l
for i in range(size[0]):
while True:
l[i] = []
try:
vals = input("Row " + str(i+1) + ": ")
j = 0
for val in vals.split(" "):
if "/" in val:
val = list(map(int, val.split("/")))
l[i].append(Fraction(*val))
else:
l[i].append(Fraction(float(val)))
j += 1
if len(l[i]) != size[1]:
print("Input does not match column count! (use spaces as separators between numbers)")
continue
break
except Exception as e:
if isinstance(e, KeyboardInterrupt):
print("Input cancelled!\n")
raise KeyboardInterrupt()
print("Input parsing failed!")
return l
def _getStrings(l, getMax=False):
lp = [[] for i in range(len(l))]
maxLen = 0
for r in range(len(l)):
for v in l[r]:
lp[r].append((str(v.numerator) if v.denominator == 1 else str(v.numerator) + "/" + str(v.denominator)))
maxLen = max(maxLen, len(lp[r][-1]))
return lp if not getMax else (lp, maxLen)
def getMatrix(l):
lp, maxLen = _getStrings(l, True)
ls = []
formatStr = "{: >" + str(maxLen) + "} "
print(len(lp))
print(len(lp[0]))
s = formatStr * (len(lp[0]) - 1) + "| " + formatStr
for r in range(len(l)):
ls.append(s.format(*lp[r]))
return "\n".join(ls)
l = [[]]
while True:
# calculate
while len(l[0]) == 0:
try:
l = getInput()
except:
print("Input parsing failed!")
gauss(l)
if not isComplete(l):
l1 = l.copy()
gauss(l)
while l1 != l:
l1 = l.copy()
gauss(l)
# print values
print()
if isComplete(l):
lp = _getStrings(l)
for i in range(len(l)):
print("Value col " + str(i+1) + ": " + " ".join(lp[i][len(lp):]))
else:
print("Complete transmutation failed!")
print(getMatrix(l))
l = [[]]
print("\n")
|
ae962928e6300ebf3fec6cb8626a18407e5e7a9a
|
kstulgys/coding-challenges
|
/leetcode/125/index.py
| 315 | 3.78125 | 4 |
import re
def isPalindrome(s):
s = re.sub(r'[\W_]', "", s).lower()
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
test = 'A man, a plan, a canal: Panama'
print(isPalindrome(test))
|
71409e651ae833aebbaa68b87be04a1ecc06c9a0
|
joseph-mutu/JianZhiOfferCodePics
|
/数组中重复的数字.py
| 1,031 | 3.90625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-09-14 09:22:11
# @Author : mutudeh ([email protected])
# @Link : ${link}
# @Version : $Id$
import os
class Solution:
# 利用额外的散列表寻找重复出现的数字
# def duplicate(self,numbers,duplication):
# if not numbers:
# return False
# dupli_dic = {}
# for num in numbers:
# if dupli_dic.get(num):
# dupli_dic[num] += 1
# duplication[0] = num
# print(duplication[0])
# return True
# else:
# dupli_dic[num] = 1
# return False
# 不使用散列表
def duplicate(self,numbers,duplication):
cur_pos = 0
while cur_pos < len(numbers):
if numbers[cur_pos] == cur_pos:
cur_pos +=1
else:
if numbers[cur_pos] == numbers[numbers[cur_pos]]:
print("cur_pos",cur_pos)
duplication[0] = numbers[cur_pos]
return True
else:
tem = numbers[cur_pos]
numbers[cur_pos] = numbers[numbers[cur_pos]]
numbers[tem] = tem
return False
s = Solution()
print(s.duplicate([0,1,2,3,4,5],[-1]))
|
005895eb599215870ff2432641ebaa7d5280941a
|
bigearsenal/test
|
/04_data_structures/task_4_2.py
| 356 | 3.53125 | 4 |
""" Задание 4.2
Преобразовать строку MAC из формата XXXX:XXXX:XXXX в формат
XXXX.XXXX.XXXX
Ограничение: Все задания надо выполнять используя только пройденные темы.
MAC = 'AAAA:BBBB:CCCC'"""
MAC = 'AAAA:BBBB:CCCC'
print(MAC.replace(':', '.'))
|
b646db5680c422573657a009925c0820f8354c2f
|
Toofifty/project-euler
|
/python/006.py
| 606 | 3.734375 | 4 |
"""
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
import timer
@timer.many(1000)
def main():
return sum(i for i in range(100 + 1)) ** 2 - sum([i*i for i in range(100 + 1)])
main()
# 25164150
# 0.0110ms
|
3896b2da8c8a8abc22fa82d977d982b1b8df81c1
|
luzlyherrera/Ejercicios-de-repaso
|
/Ejercicio92.py
| 3,919 | 3.84375 | 4 |
#Funcion que llena el arreglo con números aleatorios
#Funcion que crea una copia original del arreglo
#Funcion que muestra en pantalla en arreglo
#Funcion de ordena por burbuja
#Funcion de ordenar por seleccion
#Funcion de ordenar por insercion
#Funcion de ordenar por quirk-sort
#Funcion que muestra un menú de opciones
import random
def arreglo(n):
lista = []
for i in range(n):
lista.append(random.randint(0,100))
return lista
def copiar(original):
copia = []
for i in range(len(original)):
copia.append(original[i])
return copia
def mostrar(lista):
print("-------------")
for i in range(len(lista)):
print(lista[i])
print("-------------")
def metodoBurbuja(lista):
for i in range(1,len(lista)):
for j in range(0,len(lista)-i):
if(lista[j+1] < lista[j]):
aux=lista[j]
lista[j]=lista[j+1]
lista[j+1]=aux
mostrar(lista)
print("----------------\n")
def metodoSeleccion(lista):
for i in range(len(lista)-1,0,-1):
posicionDelMayor=0
for j in range(1,i+1):
if lista[j]>lista[posicionDelMayor]:
posicionDelMayor = j
temp = lista[i]
lista[i] = lista[posicionDelMayor]
lista[posicionDelMayor] = temp
mostrar(lista)
print("----------------\n")
def metodoInsercion(lista):
for i in range(len(lista)):
for j in range(i,0,-1):
if(lista[j-1] > lista[j]):
aux=lista[j]
lista[j]=lista[j-1]
lista[j-1]=aux
mostrar(lista)
print("----------------\n")
def metodoQuickSort(lista,izq,der):
i=izq
j=der
x=lista[(izq + der)//2]
while( i <= j ):
while lista[i]<x and j<=der:
i=i+1
while x<lista[j] and j>izq:
j=j-1
if i<=j:
aux = lista[i]; lista[i] = lista[j]; lista[j] = aux;
i=i+1; j=j-1;
if izq < j:
metodoQuickSort(lista, izq, j)
if i < der:
metodoQuickSort(lista, i, der )
mostrar(lista)
print("----------------\n")
def menu():
l=[]
print("Seleccione una opcion:")
print("1. Ordenar el arrelo por el método de burbuja")
print("2. Ordenar el arrelo por el método de seleccion")
print("3. Ordenar el arrelo por el método de insercion")
print("4. Ordenar el arrelo por el método de quick sort")
print("5. Salir")
n=int(input("Ingrese un numero: "))
if n==1:
num=int(input("Ingresa cuantos numeros quiere que tenga el arreglo\n"))
l=arreglo(num)
print("El arreglo creado es: ")
mostrar(l)
print("El arreglo ordenado es:")
metodoBurbuja(l)
menu()
elif n==2:
num=int(input("Ingresa cuantos numeros quiere que tenga el arreglo\n"))
l=arreglo(num)
print("El arreglo creado es: ")
mostrar(l)
print("El arreglo ordenado es:")
metodoSeleccion(l)
menu()
elif n==3:
num=int(input("Ingresa cuantos numeros quiere que tenga el arreglo\n"))
l=arreglo(num)
print("El arreglo creado es: ")
mostrar(l)
print("El arreglo ordenado es:")
metodoInsercion(l)
menu()
elif n==4:
num=int(input("Ingresa cuantos numeros quiere que tenga el arreglo\n"))
l=arreglo(num)
print("El arreglo creado es: ")
mostrar(l)
print("El arreglo ordenado es:")
metodoQuickSort(l)
menu()
else:
print("Bye")
menu()
"""
l=arreglo(5)
print(l)
print(copiar(l))
mostrar(l)
metodoQuickSort(l,0,len(l)-1)
"""
|
c4264cce2eb267cec68c407d485aaba71b49e1c8
|
smileyoung1993/pystudy
|
/mymod.py
| 430 | 3.609375 | 4 |
# mymod.ex
# 내가 정의한 모듈
pi =3.14
def add(a,b):
return a + b
def subtract(a,b):
return a - b
def multiply(a,b):
return a * b
def divide(a,b):
return a / b
def main():
print("mymod testcode")
print("add", add(10,20))
print("subtract", subtract(20,10))
if __name__ == "__main__":
main()# 파이썬에서 바로 시작했을때 __main__출력
# import 했을때는 mymod가 출력
|
04a08f5e12b72e5f4309a3f3490d9f1845ea456a
|
henrylin2008/Coding_Problems
|
/LeetCode/Easy/28_strStr.py
| 1,144 | 4.0625 | 4 |
# 28. Implement strStr()
# Link: https://leetcode.com/problems/implement-strstr/
#
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
#
# Example 1:
#
# Input: haystack = "hello", needle = "ll"
# Output: 2
# Example 2:
#
# Input: haystack = "aaaaa", needle = "bba"
# Output: -1
# Clarification:
#
# What should we return when needle is an empty string? This is a great question to ask during an interview.
#
# For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr()
# and Java's indexOf().
def strStr(haystack, needle):
for i in range(len(haystack) - len(needle) + 1): # go through every item in range b/t difference of 2 strings
# range = difference b/t len(haysatack) and len(needle)
if haystack[i: i + len(needle)] == needle: # search if there's a match of string of needle in haystack
# ex 1 (above): i + len(needle) = 2 + 2 = 4
# haystack[i: i + len(needle)] = ll
return i # return the index of first matched letter (of needle)
return -1 # if no match found
|
745f93b4d4320a2163222bb8837fb7d2ede15118
|
shourya192007/A-dance-of-python
|
/pandas_tutorial/1.Basics.py
| 818 | 4.25 | 4 |
import pandas as pd
# creating a data frame
titanic_data = pd.DataFrame(
{
"name":["Preyansh","Prerit","Doreamon"],
"age":[11,11,24],
"type":["Human","Human","Robo Cat"],
"century":["21st","21st","22nd"],
"specialPower":["coding","coding","gadgets"]
}
)
# print(titanic_data.describe())
# selecting a series
print(titanic_data["age"].max())
# creating a series
titanic_series = pd.Series(["Preyansh","Prerit","Nobita"], name="Boyz")
print(titanic_series)
# REMEMBER
# Import the package, aka import pandas as pd
# A table of data is stored as a pandas DataFrame
# Each column in a DataFrame is a Series
# You can do things by applying a method to a DataFrame or Series
# https://pandas.pydata.org/docs/getting_started/intro_tutorials/01_table_oriented.html
|
8877d866fe371f416f24cf323c96184371f746b3
|
dwildmark/aoc_2018
|
/06/code.py
| 2,589 | 3.828125 | 4 |
from collections import defaultdict
import sys
def parse_input_to_list():
output = []
with open("input.txt", "r") as file:
for i, line in enumerate(file):
x, y = line.split(", ")
output.append(dict(x = int(x), y = int(y)))
return output
def manhattan_dist(point_a, point_b):
return abs(point_a["x"] - point_b["x"]) + abs(point_a["y"] - point_b["y"])
def find_closest_point(point_list, coordinate):
min = sys.maxsize
min_point = dict()
min_index = sys.maxsize
min_occurence = 1
for i, point in enumerate(point_list):
distance = manhattan_dist(point, coordinate)
if distance < min:
min = distance
min_index = i
min_point = point
min_occurence = 1
elif distance == min:
min_occurence += 1
if min_occurence > 1:
#print coordinate, "is equally close to", min_point
return -1
#print coordinate, "is closest to", min_point
return min_index
def point_is_neighbor_with_infinity(point, xmax, ymax):
if point["x"] >= xmax or point["x"] <= 0 or point["y"] >= ymax or point["y"] <= 0:
return True
return False
def part_one():
points = parse_input_to_list()
xmax = max(points, key=lambda x:x["x"])["x"] + 1
ymax = max(points, key=lambda x:x["y"])["y"] + 1
grid = [[-1 for y in range(ymax)] for x in range(xmax)]
points_score = defaultdict(int)
for x, row in enumerate(grid):
for y, col in enumerate(row):
index = find_closest_point(points, dict(x = x, y = y))
if index == -1:
continue
elif points_score[index] != -1:
if point_is_neighbor_with_infinity(dict(x = x, y = y), xmax, ymax):
points_score[index] = -1
else:
points_score[index] += 1
print "Part 1 solution:"
print max(points_score.items(), key=lambda x:x[1])
def calc_total_dist(points_list, coordinate):
total_distance = 0
for point in points_list:
total_distance += manhattan_dist(point, coordinate)
return total_distance
def part_two():
coords = parse_input_to_list()
xmax = max(coords, key=lambda x:x["x"])["x"] + 1
ymax = max(coords, key=lambda x:x["y"])["y"] + 1
area = 0
for x in range(xmax):
for y in range(ymax):
distance = calc_total_dist(coords, dict(x = x, y = y))
if distance <= 10000:
area += 1
print "Part 2 solution:"
print area
part_one()
part_two()
|
2ceaf8371f5effa82ecd5e89c8f1ff0c5743da23
|
Minkov/python-advanced-2020-01
|
/comprehensions/2_vowels.py
| 132 | 4.15625 | 4 |
vowels = {'a', 'o', 'u', 'e', 'i'}
text = input()
result = [ch for ch in text if ch.lower() not in vowels]
print(''.join(result))
|
7cc0ee3f5f318961ace74c111edc90d4227a5023
|
babichevko/proga_babichev_2021
|
/звёзды.py
| 220 | 3.578125 | 4 |
import turtle as t
t.speed(5)
def z(n):
b=(n-2)*180/n
a=180-b/3
for i in range(n):
t.forward(100)
t.left(a)
z(5)
t.penup()
t.backward(150)
t.pendown()
z(11)
|
cce5d4db3ca6cd1079de84673613f86ba7faafc7
|
segmond/pythonThingz
|
/err_day_countdown/countdown.py
| 1,538 | 3.765625 | 4 |
#!/usr/bin/python
import Tkinter as tk
import time
from datetime import datetime, timedelta
'''
Count down to bed time, then count down to wake up time
'''
class Countdown:
def __init__(self):
# create root/main window
self.root = tk.Tk()
self.time_str = tk.StringVar()
label_font = ('helvetica', 20)
tk.Label(self.root, textvariable=self.time_str, font=label_font, bg='white',
fg='blue', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
def get_next_countdown(self):
now = datetime.now()
sleep_time = datetime(now.year,now.month,now.day,23,00,0) # sleep at 11:00pm
if now >= sleep_time:
# up at 5:00am
wakeup_time = datetime(now.year,now.month,now.day, 5, 0) + timedelta(days=1)
time_left = wakeup_time - now
self.event = 'Wake up in'
else:
time_left = sleep_time - now
self.event = 'Sleep in'
return time_left.seconds
def count_down(self, seconds_left):
(mins, sec) = divmod(seconds_left, 60)
(hr, mins) = divmod(mins, 60)
sf = self.event + " {:02d}:{:02d}:{:02d}".format(*(hr, mins, sec))
self.time_str.set(sf)
time.sleep(1)
def draw(self):
while True:
seconds_left = self.get_next_countdown()
self.count_down(seconds_left)
self.root.update()
def run(self):
self.draw()
self.root.mainloop()
c = Countdown()
c.run()
|
ff2a343b4c550f6a78eb5ff343d39a847ff70f8a
|
mcauleyc/CA4015_Assignment_1
|
/Book/_build/jupyter_execute/clustering.py
| 17,666 | 3.90625 | 4 |
#!/usr/bin/env python
# coding: utf-8
# # Cluster Analysis
#
# Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group are more similar to each other than to those in other groups.
# In[1]:
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
sns.set_palette('gnuplot2', n_colors=10)
from sklearn.cluster import KMeans
from collections import Counter
from sklearn.metrics import silhouette_score
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
# In[2]:
all_95 = pd.read_csv("./data/all_95.csv", header = [0,1], index_col=0)
all_100 = pd.read_csv("./data/all_100.csv", header = [0,1], index_col=0)
all_150 = pd.read_csv("./data/all_150.csv", header = [0,1], index_col=0)
df = pd.read_csv("./data/agg_all.csv", index_col=0)
df
# ## 1. The Optimal Number of Clusters
#
# There are two methods to find the optimal number of clusters for a dataset, the Elbow Method and the Silhouette Method.
# ### 1.1 The Elbow Method
#
# This is the most common method for determining the optimal number of clusters. To do this you must calculate the Within-Cluster-Sum of Squared Errors (WSS) for different values of *k*, and choose the *k* for which WSS first starts to diminish. In a plot of WSS-versus-k, this is visible as an elbow.
# In[3]:
def elbow_score(x):
distortions = []
K = range(1,11)
for k in K:
kmeanModel = KMeans(n_clusters=k)
kmeanModel.fit(x)
distortions.append(kmeanModel.inertia_)
plt.plot(K, distortions, 'bx-')
plt.xlabel('k')
plt.ylabel('Distortion')
plt.title('The Elbow Method showing the optimal k')
plt.show()
# ### 1.2 The Silhouette Method
#
#
# This is a method to find the optimal number of clusters *k*. The silhouette value measures how similar a point is to its own cluster (cohesion) compared to other clusters (separation). A high value is desirable. This is the formula:
#
# $$
# s(i) = \frac{b(i) - a(i)}{max(a(i), b(i))}
# $$
#
# >**_NOTE:_** *s(i)* is defined to be equal to zero if *i* is the only point in the cluster. This is to prevent the number of clusters from increasing significantly with many single-point clusters.
#
# *a(i)* is the measure of the similarity of the point *i* to its own cluster.
#
# $$
# a(i) = \frac{1}{\lvert C_{i}\rvert - 1} \sum_{j{\in}C_{i}, i{\neq}j} d(i,j)
# $$
#
# Similarly, *b(i)* is the measure of dissimilarity of *i* from points in other clusters.
#
# $$
# b(i) = \min_{i{\neq}j} \frac{1}{\lvert C_{j}\rvert} \sum_{j{\in}C_{j}} d(i,j)
# $$
#
# Where *d(i,j)* is the euclidean distance between the two points.
#
# In[4]:
def sil_value(x):
sil = []
kmax = 10
# dissimilarity would not be defined for a single cluster, thus, minimum number of clusters should be 2
for k in range(3, kmax+1):
kmeans = KMeans(n_clusters = k).fit(x)
labels = kmeans.labels_
sil.append(silhouette_score(x, labels, metric = 'euclidean'))
return sil
# https://medium.com/analytics-vidhya/how-to-determine-the-optimal-k-for-k-means-708505d204eb
# ## 2. Clustering the Data
#
# I chose to perform clustering on the total amount won or lost compared to the amount the participants chose the deck 'C'. I thought this would be interesting because C was a "good" deck but had frequent losses. The losses also depended on the payload of the study. I wanted to see if the clusters had any relationship to the payload.
#
# I also wanted to cluster the data comparing the total amount won or lost to the amount of times the participants chose a "good" deck. This would be interesting to see if there was anything in particular that defined each of these clusters.
# ### 2.1 Performing Clustering on Deck C
#
# I began by making a dataframe with just 'Total' and 'C' columns.
# In[5]:
c = df.iloc[:,[1,4]]
c
# I then used the elbow method and the silhouette method to find the optimal number of clusters.
# In[6]:
elbow_score(c)
# In[7]:
c_sil = sil_value(c)
plt.plot([3,4,5,6,7,8,9,10], c_sil)
plt.title('Optimal k for c')
plt.xlabel('silhouette score')
plt.ylabel('k')
plt.show()
# It was not completely clear from the elbow method whick value I should use for *k*. It looked to be between 3 and 7. In the silhouette method the peak was at 10 but there was also a slightly lower peak at 7. For this reason I chose 7 as my *k* and made 7 clusters.
# I used `sklearn.cluster.KMeans` to create the clusters and fit them to the data.
# In[8]:
c_kmeans = KMeans(7)
c_kmeans.fit(c)
# I then find the identified clusters in c.
# In[9]:
c_identified_clusters = c_kmeans.fit_predict(c)
c_identified_clusters
# This is a graph of the data with the different clusters shown in different colours.
# In[10]:
c_data_with_clusters = df.copy()
c_data_with_clusters['Clusters'] = c_identified_clusters
sns.lmplot(data=c_data_with_clusters, x='Total', y='C', hue='Clusters',
fit_reg=False, legend=True)
# Then, for a comparison, I plotted the data using colour to differentiate payload.
# In[11]:
sns.lmplot(data=c_data_with_clusters, x='Total', y='C', hue='Payload',
fit_reg=False, legend=True, palette='rainbow')
# As you can see the datapoints in cluster 6 all chose c less and had the highest loss in the study. All of these data points were in payload 3. This makes sense because these people obviously chose C less because they were getting frequent losses from it and those losses were growing as they went. Most of the people who chose C the most were in payload 2 which is where the losses in C were constant.
# ### 2.2 Performing Clustering on "Good" Decks
#
# Now I would like to cluster the data based on the "good" card decks to see if there is any insight to be gleamed from it.
# In[12]:
good = df.iloc[:,[1,7]]
elbow_score(good)
good_sil = sil_value(good)
good_k = good_sil.index(max(good_sil)) + 2
plt.plot([3,4,5,6,7,8,9,10], good_sil)
plt.title('Optimal k for good')
plt.xlabel('silhouette score')
plt.ylabel('k')
plt.show()
# There is no clear *k* from the elbow plot, and the peak at 10 is a fair bit higher than any other peak in the silhouette plot. Therefore, I chose to make 10 clusters this time.
# In[13]:
good_kmeans = KMeans(10)
good_kmeans.fit(good)
good_identified_clusters = good_kmeans.fit_predict(good)
good_data_with_clusters = df.copy()
good_data_with_clusters['Clusters'] = good_identified_clusters
sns.lmplot(data=good_data_with_clusters, x='Total', y='Good', hue='Clusters',
fit_reg=False, legend=True)
sns.lmplot(data=good_data_with_clusters, x='Total', y='Good', hue='Payload',
fit_reg=False, legend=True, palette='rainbow')
sns.lmplot(data=good_data_with_clusters, x='Total', y='Good', hue='StudyNo',
fit_reg=False, legend=True)
# As you can see from the two graphs, there is obviously a strong correlation between picking "good" decks and winning more money. There does not seem to be any correlation between payload and "good" decks though. Maia et al. frequently asked the participants about their knowledge of the decks at regular intervals during the task. This is study number 4 and is shown in yellow on the graph. Nothing major stands out about this study except there were less people who chose the "bad" decks. It is hard to see because the datapoints for study 4 are all in the centre of the graph but there are a lot less of their datapoints under 0.4 than the other studies.
# ### 2.3 Further Analysis of "Good" Decks
#
# I would now like to look more closely at clusters 7 and 9 because they are the most extreme on each side. It is said that after about 50 choices most people begin to see the patterns ang go for the "good" decks more consistently. I want to see if the people in cluster 9 seemed to figure out the pattern and the people in cluster 7 did not.
# I began by getting the number of the good cluster (9) and the bad cluster (7). This is just in case the cluster numbers change at some point.
# In[14]:
good_cluster = good_data_with_clusters[good_data_with_clusters['Total'] == max(good_data_with_clusters['Total'])]['Clusters'].iloc(0)[0]
bad_cluster = good_data_with_clusters[good_data_with_clusters['Total'] == min(good_data_with_clusters['Total'])]['Clusters'].iloc(0)[0]
# I then found the subjects of the cluster so that I could find out whether they belonged to 95, 100, or 150. I then looked at the choices they made after the first 50 rounds and did some analysis on that.
# In[15]:
good_subj_1 = list(good_data_with_clusters[good_data_with_clusters['Clusters'] == bad_cluster]['Subj'])
good_subj_1
good_lst = []
for i in good_subj_1:
n, idx = i.split('_', 1)
if n == '100':
good_lst.append(list(all_100[all_100.index == idx].values[0])[101::2])
elif n == '150':
good_lst.append(list(all_150[all_150.index == idx].values[0])[101::2])
elif n == '95':
good_lst.append(list(all_95[all_95.index == idx].values[0])[101::2])
good_d = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0}
good_l, no_bad = [], []
for i in good_lst:
c = Counter(i)
good_d['a'] += c[1]
good_d['b'] += c[2]
good_d['c'] += c[3]
good_d['d'] += c[4]
if c[1] + c[2] != 0:
good_l.append((c[3] + c[4]) / (c[1] + c[2]))
else:
no_bad.append(c)
print(good_d)
print(len([x for x in good_l if x < .5]))
print(len(good_l))
print(no_bad)
print(np.mean(good_l))
# This cluster chose 'B' the most and 6 out of 8 people were twice as likely to choose "bad" decks over "good" decks. This shows that the people in this cluster probably did not see the pattern and got distracted by the infrequent losses in Deck B.
#
# The mean of the ratios between good and bad is 0.369, which shows that the participants in the cluster were far less likely to choose good decks. If the mean was 1 it would mean that the participants chose fairly evenly between the "good" and "bad" decks.
# In[16]:
good_subj_2 = list(good_data_with_clusters[good_data_with_clusters['Clusters'] == good_cluster]['Subj'])
good_subj_2
good_lst = []
for i in good_subj_2:
n, idx = i.split('_', 1)
if n == '100':
good_lst.append(list(all_100[all_100.index == idx].values[0])[101::2])
elif n == '150':
good_lst.append(list(all_150[all_150.index == idx].values[0])[101::2])
elif n == '95':
good_lst.append(list(all_95[all_95.index == idx].values[0])[101::2])
good_d = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0}
good_l, no_bad = [], []
for i in good_lst:
c = Counter(i)
good_d['a'] += c[1]
good_d['b'] += c[2]
good_d['c'] += c[3]
good_d['d'] += c[4]
if c[1] + c[2] != 0:
good_l.append((c[3] + c[4]) / (c[1] + c[2]))
else:
no_bad.append(c)
print(good_d)
print(len([x for x in good_l if x < 1]))
print(len(good_l))
print(no_bad)
print(np.mean(good_l))
# In this cluster 'C' was chosen the most despite its frequent losses. None of the participants chose the "bad" decks more frequently than the "good" decks, with some people never choosing the bad decks at all. The mean was 15.049 which is very high. This means that the "bad" were barely chosen in comparison to the "good" decks.
#
# For these reasons I think it is safe to assume that a lot of these participants figured out that the decks C and D contained more rewards than penalties.
# ## 3. Preserving the Privacy of Each Lab
#
# Next, I wanted to find a way to obtain similar clustering results while preserving the privacy of each lab.
# ### 3.1 Using PCA
#
# Principal Component Analysis, or PCA, is a way to reduce the dimensionality of a dataset. It also is able to provide some degree of privacy to the data.
# First I dropped the columns that were not numeric and useful.
# In[17]:
x = df.drop(columns = ['Subj','Study', 'StudyNo', 'Payload'])
# I then performed PCA for two components and added them to a dataframe with the study number and payload.
# In[18]:
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
principalDf = pd.DataFrame(data = principalComponents
, columns = ['principal component 1', 'principal component 2'])
pca_df = pd.concat([principalDf, df[['StudyNo', 'Payload']]], axis = 1)
# https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
pca_df
# I then got the elbow and silhouette scores and chose 7 as my optimal *k*.
# In[19]:
elbow_score(principalDf)
pca_sil = sil_value(principalDf)
pca_k = pca_sil.index(max(pca_sil)) + 2
plt.plot([3,4,5,6,7,8,9,10], pca_sil)
plt.title('Optimal k for pca')
plt.xlabel('silhouette score')
plt.ylabel('k')
plt.show()
# I then clustered the data and made graphs showing the clusters, the payload, and the study.
# In[20]:
pca_kmeans = KMeans(7)
pca_kmeans.fit(pca_df)
pca_identified_clusters = pca_kmeans.fit_predict(pca_df)
pca_data_with_clusters = pca_df.copy()
pca_data_with_clusters['Clusters'] = pca_identified_clusters
sns.lmplot(data=pca_data_with_clusters, x='principal component 1', y='principal component 2', hue='Clusters',
fit_reg=False, legend=True)
sns.lmplot(data=pca_data_with_clusters, x='principal component 1', y='principal component 2', hue='Payload',
fit_reg=False, legend=True, palette='rainbow')
sns.lmplot(data=pca_df, x='principal component 1', y='principal component 2', hue='StudyNo',
fit_reg=False, legend=True)
# These graphs do not look like the graphs I made before. There is more data in the top left quadrant of the graph. There does not seem to be much correlation between the clusters and the payoff but cluster 4 seems to be made up of majority payload 3 studies. There is no clear connection between these clusters and the studies.
# ### 3.2 Using Centroids
#
# To do this I decided to perform clustering on each lab's results separately and then cluster their centroids to see if it gave similar results to clustering the data from all of the labs together. For this example I will use the same analysis as before, the 'Total' and the "good" decks.
# I looped through the studies and got the silhouette score for each study. I then performed k-means clustering on the data from each study. I added the centroid of each cluste to a dataframe called 'centroids'.
# In[21]:
centroids = pd.DataFrame(columns = ['Total', 'Good', 'StudyNo'])
for study in range(1,11):
study_df = df[df['StudyNo'] == study]
study_good = study_df.iloc[:,[1,7]]
study_good_sil = sil_value(study_good)
study_good_k = study_good_sil.index(max(study_good_sil)) + 2
# plt.plot([3,4,5,6,7,8,9,10], study_good_sil)
# plt.title('Optimal k for {}'.format(study_df['Study'].iloc(0)[0]))
# plt.xlabel('silhouette score')
# plt.ylabel('k')
# plt.show()
study_good_kmeans = KMeans(study_good_k)
study_good_kmeans.fit(study_good)
study_good_identified_clusters = study_good_kmeans.fit_predict(study_good)
centers = np.array(study_good_kmeans.cluster_centers_)
for i in centers:
centroids = centroids.append({'Total': i[0], 'Good': 1-i[1], 'StudyNo': study}, ignore_index=True)
print(centroids)
# Here is a graph of all the centroids. As you can see, it is similar to the graph for all datapoints when plotting 'Total' and 'Good'. It also still captures that some studies had more variation in their 'Total' or in the amount a "good" deck was chosen. For example, the 6th study had people choosing "good" decks all the time and some people never choosing them. In contrast, the people in study 4 mostly chose a "good" deck somewhere between 40% and 80% of the time.
# In[22]:
sns.lmplot(data=centroids, x='Total', y='Good', hue='StudyNo',
fit_reg=False, legend=True, palette='gnuplot2')
# This is where I got the optimal *k* for the centroids data and performed clustering on it.
# In[23]:
centroid_good = centroids.iloc[:,[0,1]]
elbow_score(centroid_good)
centroid_good_sil = sil_value(centroid_good)
centroid_good_k = centroid_good_sil.index(max(centroid_good_sil)) + 2
plt.plot([3,4,5,6,7,8,9,10], centroid_good_sil)
plt.title('Optimal k for centroid_good')
plt.xlabel('silhouette score')
plt.ylabel('k')
plt.show()
centroid_good_kmeans = KMeans(10)
centroid_good_kmeans.fit(centroid_good)
centroid_good_identified_clusters = centroid_good_kmeans.fit_predict(centroid_good)
centroid_good_data_with_clusters = centroids.copy()
centroid_good_data_with_clusters['Clusters'] = centroid_good_identified_clusters
sns.lmplot(data=centroid_good_data_with_clusters, x='Total', y='Good', hue='Clusters',
fit_reg=False, legend=True)
# The clusters show the same as the original clusters that the smaller clusters are on the edge because there are less datapoints there and the ones in the middle are bigger.
# Overall, I would say that this method of preserving privacy is fine if you just want to understand the overall picture of the data and see roughly what way the data would look if it was clustered. However if you want to perform deeper analysis on the data it would not be very useful.
# ## Conclusion
#
# There are some interesting insights to be learned from this data when it has been clustered. There are relationships between the amount won or lost and the decks chosen, and the payload for the amount deck C was rewarding or penalising may have impacted the way that participants made their decisions. It is also harder to gain insight into the data as a whole when the privacy of each study is preserved.
|
a24522be5f97badb956590dccdec0731a0a69024
|
kapppa-joe/leetcode-practice
|
/daily/20201025-stone-game-IV.py
| 959 | 3.5 | 4 |
from functools import lru_cache
from math import sqrt
class Solution:
def winnerSquareGame(self, n: int) -> bool:
square_nums = [i * i for i in range(int(sqrt(n)), 0, -1)]
@lru_cache(None)
def can_win(i: int) -> bool:
if i in square_nums:
return True
else:
for j in square_nums:
if j < i and not can_win(i - j):
return True
return False
return can_win(n)
def winnerSquareGameb(self, n: int) -> bool:
if sqrt(n) % 1 == 0:
return True
dp = {}
square_nums = [i * i for i in range(1, int(sqrt(n)) + 1)]
dp[0] = False
for i in range(1, n + 1):
if i in square_nums:
dp[i] = True
else:
dp[i] = any(not dp[i-j] for j in square_nums if j < i)
return dp[n]
fn = Solution().winnerSquareGame
|
77bebfd73388d0fc3e432a2784e5ef99c5e6aa4a
|
jsgiant/SDE-sheet-python
|
/1_find_the_duplicate.py
| 695 | 3.71875 | 4 |
# Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
def findTheDuplicate(nums):
nums_len = len(nums)
if nums_len > 1:
# Find the intersection point of the two runners.
slow = nums[0]
fast = nums[nums[0]]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
# Find the "entrance" to the cycle.
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
return -1
# Input: nums = [1,3,4,2,2]
# Output: 2
|
0e5ef84ad4b36150a414456450533759c4ba6de5
|
jinglepp/python_cookbook
|
/07函数/07.07匿名函数捕获变量值.py
| 1,506 | 4.03125 | 4 |
# coding:utf-8
# 问题
# 你用lambda定义了一个匿名函数,并想在定义时捕获到某些变量的值。
# 解决方案
# 先看下下面代码的效果:
x = 10
a = lambda y: x + y
x = 20
b = lambda y: x + y
print(a(10)) # 30
print(b(10)) # 30
# 这其中的奥妙在于lambda表达式中的x是一个自由变量, 在运行时绑定值,而不是定义时就绑定,
# 这跟函数的默认值参数定义是不同的。因此,在调用这个lambda表达式的时候,x的值是执行时的值。例如:
x = 15
print(a(10)) # 25
x = 3
print(a(10)) # 13
# 如果你想让某个匿名函数在定义时就捕获到值,可以将那个参数值定义成默认参数即可,就像下面这样:
x = 10
a = lambda y, x=x: x + y
x = 20
b = lambda y, x=x: x + y
print(a(10)) # 20
print(b(10)) # 30
# 讨论
# 在这里列出来的问题是新手很容易犯的错误,有些新手可能会不恰当的使用lambda表达式。
# 比如,通过在一个循环或列表推导中创建一个lambda表达式列表,并期望函数能在定义时就记住每次的迭代值。例如:
funcs = [lambda x: x + n for n in range(5)]
for f in funcs:
print(f(0))
# 4,4,4,4,4
# 但是实际效果是运行是n的值为迭代的最后一个值。现在我们用另一种方式修改一下:
funcs = [lambda x, n=n: x + n for n in range(5)]
for f in funcs:
print(f(0))
# 0,1,2,3,4
# 通过使用函数默认值参数形式,lambda函数在定义时就能绑定到值。
|
3738d1ca4910d62feebe0e7f3cebfc94404c49cd
|
bljessica/machine-learning-practices
|
/studying-practices/gradient-descent.py
| 1,692 | 3.71875 | 4 |
import matplotlib.pyplot as plt
import random
#训练集
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
w = 1.0 #初始权重猜测
def forward(x):
return x * w
#梯度下降代价函数
def cost(xs, ys):
cost = 0
for x, y in zip(x_data, y_data):
cost += (forward(x) - y) ** 2
return cost / len(xs)
#随机梯度下降(SGD)代价函数
def stochastic_cost(x, y):
return (forward(x) - y) ** 2
def gradient(xs, ys):
grad = 0
for x, y in zip(xs, ys):
grad += 2 * (forward(x) - y) * x
return grad / len(xs)
#随机梯度下降梯度
def stochastic_gradient(x, y):
return 2 * (forward(x) - y) * x
print('Predict(before training)', 4, forward(4))
epoch_list = []
loss_list = []
#进行100轮训练(梯度下降算法)
# for epoch in range(100): #epoch 阶段(轮)
# cost_val = cost(x_data, y_data)
# grad_val = gradient(x_data, y_data)
# w -= 0.01 * grad_val
# print('Epoch: ', epoch, 'w=', w, 'loss=', cost_val)
# epoch_list.append(epoch)
# loss_list.append(cost_val)
#进行100轮训练(随机梯度下降算法)
for epoch in range(100):
randIndex = random.randint(0, len(x_data) - 1) #随机取一个数据
x = x_data[randIndex]
y = y_data[randIndex]
grad = stochastic_gradient(x, y)
w -= 0.01 * grad
print('\tgrad:', x, y, grad)
loss = stochastic_cost(x, y)
epoch_list.append(epoch)
loss_list.append(loss)
print('Epoch: ', epoch, 'w=', w, 'loss=', loss)
print('Predict(after training)', 4, forward(4))
plt.plot(epoch_list, loss_list)
plt.xlabel('epoch')
plt.ylabel('Loss')
plt.show()
|
9655650d39dfc18d50e83de8adc24f75dcf34c76
|
wahello/physics
|
/backend/data/random_student.py
| 1,500 | 3.65625 | 4 |
from openpyxl import Workbook
import random
import string
# 姓名 学校 年级 学号 专业 电话号码 电子邮箱 账号状态
major = ['物理','化学','英语','计算机','经管','人文','环境','土木','机械','设计']
mail = ['163','162']
status = [True,False]
def random_phone():
head = ['139','188','185','136','155','135','158','151','152','153']
s = '0123456789'
return random.choice(head)+"".join(random.choice(s) for i in range(8))
def main():
wb = Workbook()
ws = wb.create_sheet("学生信息")
for i in range(1,200):
name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
school_id = random.randint(1,6)
grade = random.randint(2017,2020)
code = '{:0>7}'.format(str(i))
major_id = random.randint(0,len(major)-1)
phone = random_phone()
mail_name = phone+"@"+random.choice(mail)+".com"
statuss = random.choice(status)
print(name,school_id,grade,code,major[major_id],phone,mail_name,statuss)
ws.cell(row=i,column=1).value = name
ws.cell(row=i,column=2).value = school_id
ws.cell(row=i,column=3).value = grade
ws.cell(row=i,column=4).value = code
ws.cell(row=i,column=5).value = major[major_id]
ws.cell(row=i,column=6).value = phone
ws.cell(row=i,column=7).value = mail_name
ws.cell(row=i,column=8).value = statuss
wb.save("random.xlsx")
if __name__ == '__main__':
main()
|
eeb9669ee0c15a5d7d4412b77e8011a4af4c0316
|
lionheartStark/sword_towards_offer
|
/leetcode/py36/最短无序连续子数组N581.py
| 714 | 3.625 | 4 |
from typing import List
from typing import List
class Solution:
def my_findUnsortedSubarray(self, nums: List[int]) -> int:
stack = []
n = len(nums)
shixu = []
minx = float('INF')
maxy = 0
for i in range(n):
if stack == [] or nums[i] >= stack[-1][0]:
stack.append((nums[i], i))
else:
j = 0
while stack[j][0] <= nums[i]:
j += 1
minx = min(minx, stack[j][1])
maxy = i
if minx != float('INF'):
return -minx + maxy + 1
else:
return 0
a = Solution().findUnsortedSubarray([1, 3, 5, 2, 4])
print(a)
|
8ab66ebc8be0b313943cb9f2889c8400ec053581
|
saldanaj/CS325-Algorithms
|
/HW1/JoaquinSaldana_Question4FinalSubmission/mergesort.py
| 2,565 | 3.953125 | 4 |
#!/usr/bin/python
# Student: Joaquin Saldana
# Assignment: Homework 1 / Merge Sort program
import string
import io
# Citation: the code for the merge_sort and the sort functions was borrowed from the
# following site https://pythonandr.com/2015/07/05/the-merge-sort-python-code/
def merge(array1, array2):
mergedArray = []
while len(array1) != 0 and len(array2) != 0:
if array1[0] < array2[0]:
mergedArray.append(array1[0])
array1.remove(array1[0])
else:
mergedArray.append(array2[0])
array2.remove(array2[0])
if len(array1) == 0:
mergedArray += array2
else:
mergedArray += array1
return mergedArray
#=====================================================================
# Citation: the code for the merge_sort and the sort functions was borrowed from the
# following site https://pythonandr.com/2015/07/05/the-merge-sort-python-code/
def merge_sort(arrayOfInts):
if len(arrayOfInts) == 0 or len(arrayOfInts) == 1:
return arrayOfInts
else:
middle = len(arrayOfInts)/2
a1 = merge_sort(arrayOfInts[:middle])
a2 = merge_sort(arrayOfInts[middle:])
return merge(a1,a2)
#=====================================================================
def main():
# list/array variable that will hold what we read from the file and later sort
intArray = []
file = open('merge.out', 'w')
with open('data.txt') as datafile:
for line in datafile:
#read the line from the file and insert/append the values in to a list/array where we will start
# the insertsort algorithm and output to a file
data = line.split()
# append to the list the numbers read from the file
for i in data:
intArray.append(int(i))
# store the size of the array into the variable
arraySize = intArray[0]
# print the variable for testing
# print arraySize
# remove the variable from the array/list
del intArray[0]
#insertion sort algorithm
newArray = merge_sort(intArray)
# print the list for the sake of checking it's working
print newArray
for number in newArray:
file.write(str(number))
file.write(" ")
file.write("\n")
# empty the contents of the array so we can start over, and continue starting over until
# we have reached the end of file
del intArray[:]
del newArray[:]
file.close()
print "Finished writing to merge.out. Please open the file to see the results. Thanks."
main()
|
f2efc4243b1b305b43cbd1fb583a8e5a0e684249
|
Oscar883/AprendiendoPython
|
/Conversiones.py
| 646 | 4.09375 | 4 |
#Declaramos variable str, con cadena de numeros.
numero = "1234"
#Se MUESTRA el tipo de variable ,
# type = da un dato type, no un str(<class 'str'>).
print(type(numero))
#Convertimos la cadena a int.
numero=int(numero)
#Se MUESTRA como el tipo ha cambiado,
#aunque se usa la misma variable (<class 'int'>).
print(type(numero))
#Se declara un str con meta sustitucion
#(posiciones donde iran valores usando format).
salida="El numero utilizado es {}"
#Se MUESTRA el resultado. La meta sustitucion hara que donde
#donde esta {} se coloque el valor de la variable numero, (El numero utilizado es 1234).
print(salida.format(numero))
|
ca433b1c89660a13dfd6b81777e9e0297728a6f4
|
Esirn/Learning_Coding
|
/SUM(1!~20!).py
| 146 | 3.609375 | 4 |
a=1
b=0
print("SUM(1!~20!)\n=0",end='')
for i in range(1,21):
a *= i;
b += a;
print("+{0}".format(a),end='')
print("\n={0}".format(b))
|
16bee523d94e83d6181822e0522a44083740dc02
|
webclinic017/Financial_Machine_Learning
|
/old_stuff/fixed_window_labeling.py
| 8,670 | 3.6875 | 4 |
"""
Name :fixed_window_labeling.py in Project: Financial_ML
Author : Simon Leiner
Date : 19.05.2021
Description: sheet contains the functions for computing the triple barrier method
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import matplotlib.dates as mdates
# some printing options
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Checked: Functions work
def get_vertical_barriers(ps,numdays):
"""
This function calculates the horizontal barriers numdays ahead.
:param ps: pd.Series: Prices
:param numdays: integer: number of days to add for vertical barrier
:return: pd.Series: Timestamps of vertical barriers
"""
# get the index as numbers and add numdays
vertical_barriers = ps.index.searchsorted(ps.index + pd.Timedelta(days = numdays))
# remove the last entries: by shifting we exceeded the number of rows
vertical_barriers = vertical_barriers[vertical_barriers < ps.shape[0]]
# subset the price Series index and get the index too
vertical_barriers = pd.Series(ps.index[vertical_barriers], index = ps.index[:vertical_barriers.shape[0]])
return vertical_barriers
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Checked: Functions work
def get_labels(barriers,ps):
"""
This function calcualtes the path returns and thus the Labels for each triple barrier event.
:param barriers: pd.DataFrame: with all the needed information
:param ps: pd.Series: Prices
:return: pd.DataFrame: Labels with the starting date of the triple barrier as index
"""
# drop na rows if there isn't a horizontal barrier
barriers.dropna(subset = ["vert_barrier"], inplace = True)
# create a df with the events as index
df_label = pd.DataFrame(index = barriers.index)
# calculate the path returns : differnece between price at starting date and date the price hit a barrier:
df_label["ret"] = ps.loc[barriers["vert_barrier"].values].values / ps.loc[barriers.index] - 1
# add colum bin: indicate the sign of a number element-wise. returns 1 ,0, -1 for the sign
df_label["Label"] = np.sign(df_label["ret"])
# note if the return is exactly 0, np.sign return 0, as we want a binary problem, we have to convert these rare events to another class
for index, value in enumerate(df_label["Label"]):
if value == 0:
# declare 0 returns as negative returns
df_label["Label"][index] = -1
# only for writing the new gained information in the container
barriers["ret"] = df_label["ret"]
barriers["Label"] = df_label["Label"]
return df_label
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Checked: Functions work
def get_triple_barrier_labeld_data(ps,h,num_days,plotting = True):
"""
This function combines all the above functions and executes them in the correct order
:param ps: pd.Series: Prices
:param h: float: filter size
:param numdays: integer: number of days to add for vertical barrier
:param plotting: boolean: wether to plot or not
:return: pd.DataFrame: Labels with the starting date of the triple barrier as index
"""
# most recent datapoint
most_recent_date = ps.index[-1].strftime('%Y-%m-%d')
# get the vertical barriers
vertical_barriers = get_vertical_barriers(ps, num_days)
# most recent horizontal barrier
most_recent_horizontal = pd.to_datetime(str(vertical_barriers.values[-1]))
# create a container to save the values
barriers = pd.concat({"price": ps, "vert_barrier": vertical_barriers}, axis=1)
# get the labeld Data
df_label = get_labels(barriers,ps)
# get the class distribution
distribution = df_label["Label"].value_counts(normalize=True)
# flag warning
if (distribution[1] > 0.75) or (distribution[1] < 0.15):
print(f"Be careful, the class distribution is very unbalanced with positive: {round(distribution[1],2)*100} % and negative returns: {round(distribution[2],2)*100} %")
print("-" * 10)
print(f"The last triple barrier for {num_days} days back has formed on the {df_label.index[-1].strftime('%Y-%m-%d')} - {most_recent_horizontal.strftime('%Y-%m-%d')} and there is data up to the {most_recent_date}.")
print("-" * 10)
# show the df with all the given information
print(f"Overview of the triple barrier labling approach:")
print(barriers.tail(2))
print("-" * 10)
if plotting == True:
# plotting
plot_one_triple_barrier(barriers, ps, num_days)
# change the index to not the first, nut the horizontal barrier
df_label.set_index(vertical_barriers,inplace = True)
# show the returning DF
# print(f"Overview of the Labeld Data:")
# print(df_label.tail(3))
# print("-" * 10)
return df_label
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Checked: Functions work
def plot_one_triple_barrier(barriers,ps,numdays,last_barriers = 5):
"""
This function plots some triple barrier events.
:param barriers: pd.DataFrame: with all the needed information
:param ps: pd.Series: Prices
:param numdays: integer: number of days to add for vertical barrier
:param last_barriers: integer: number on how many barriers to plot
:return: None
"""
# barriers old index
starting_dates_tpb = barriers.index
# change the index to not the first, but the horizontal barrier
barriers.set_index("vert_barrier", inplace=True)
# get the most recent date
now = datetime.now()
# last_barriers times the timepan of the horizontal barriers
last_x_months = now - timedelta(days=31 + numdays)
# plot the last formed triple barrier and just the most recent month
plotting_price_recent_x_months = ps[(ps.index >= last_x_months) & (ps.index <= barriers.index[-1])]
# print(plotting_price_recent_x_months)
# plot the last Labled Datapoints (returns)
plotting_labels_returns_recent_x_months = barriers[barriers.index >= last_x_months]["ret"] * 100
# print(plotting_labels_returns_recent_x_months)
# plotting
plt.subplot(2, 3, 1)
# plot the Labels of the last recent month
plt.plot(plotting_labels_returns_recent_x_months,color="goldenrod")
# stylistical stuff
plt.ylabel("Returns in %:")
plt.axhline(y=0, color="black")
plt.title(f"Returns forming the Labels from {last_x_months.strftime('%Y-%m-%d')} up to {plotting_labels_returns_recent_x_months.index[-1].strftime('%Y-%m-%d')}:")
date_format = mdates.DateFormatter('%m-%d')
plt.gca().xaxis.set_major_formatter(date_format)
# plotting
plt.subplot(2, 3, 4)
# plot the adjusted Close of the last recent month
plt.plot(plotting_price_recent_x_months, label="Adj Close", color="goldenrod")
# possible colors to select
all_colors = ["black","blue","teal","navy","grey","darkred","dimgray","royalblue","teal","cyan","maroon","indigo"]
# define a colorrange:
colors = []
# create a colorlist
for j in range(1,(last_barriers + 2)):
# choose one color
color = all_colors[j]
# append the color
colors.append(color)
# loop over the last recent points
for i in range(1,len(colors)):
# ith last starting date
start = starting_dates_tpb[-i]
# print(start)
# ith last vertical barrier
end = barriers.index[-i]
# print(end)
price = plotting_price_recent_x_months[-i]
# plot
plt.plot([start, end], [price, price], color=f"{colors[i]}", linestyle="--")
plt.plot([start, start], [price -0.1,price +0.1], color=f"{colors[i]}", linestyle="-")
plt.plot([end, end], [price -0.1,price +0.1], color=f"{colors[i]}", linestyle="-")
# stylistical stuff
plt.ylabel("Price in € or $:")
plt.title(f"Adjusted Close and the last {last_barriers} TPBs from {last_x_months.strftime('%Y-%m-%d')} up to {plotting_price_recent_x_months.index[-1].strftime('%Y-%m-%d')}:")
date_format = mdates.DateFormatter('%m-%d')
plt.gca().xaxis.set_major_formatter(date_format)
return None
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
ca7a0210475b5004ed5a2b1b06516d480592bba3
|
marwin-ko/dsp
|
/python/q8_parsing.py
| 751 | 4.21875 | 4 |
# The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import numpy as np
data = np.genfromtxt('football.csv',delimiter=',',dtype='S15,int,int,int,int,int,int,int')
temp = []
for i,x in enumerate(data):
info = (x[0],x[5]-x[6])
temp.append(info)
temp = sorted(temp,key=lambda x:x[1])
print 'The team with the smallest point differential is',temp[0][0]
|
ceb9d87770312344b359564481355bd9b4c9d4aa
|
statsmodels/statsmodels
|
/statsmodels/stats/contingency_tables.py
| 44,247 | 3.546875 | 4 |
"""
Methods for analyzing two-way contingency tables (i.e. frequency
tables for observations that are cross-classified with respect to two
categorical variables).
The main classes are:
* Table : implements methods that can be applied to any two-way
contingency table.
* SquareTable : implements methods that can be applied to a square
two-way contingency table.
* Table2x2 : implements methods that can be applied to a 2x2
contingency table.
* StratifiedTable : implements methods that can be applied to a
collection of 2x2 contingency tables.
Also contains functions for conducting McNemar's test and Cochran's q
test.
Note that the inference procedures may depend on how the data were
sampled. In general the observed units are independent and
identically distributed.
"""
import warnings
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels import iolib
from statsmodels.tools import sm_exceptions
from statsmodels.tools.decorators import cache_readonly
def _make_df_square(table):
"""
Reindex a pandas DataFrame so that it becomes square, meaning that
the row and column indices contain the same values, in the same
order. The row and column index are extended to achieve this.
"""
if not isinstance(table, pd.DataFrame):
return table
# If the table is not square, make it square
if not table.index.equals(table.columns):
ix = list(set(table.index) | set(table.columns))
ix.sort()
table = table.reindex(index=ix, columns=ix, fill_value=0)
# Ensures that the rows and columns are in the same order.
table = table.reindex(table.columns)
return table
class _Bunch:
def __repr__(self):
return "<bunch containing results, print to see contents>"
def __str__(self):
ky = [k for k, _ in self.__dict__.items()]
ky.sort()
m = max([len(k) for k in ky])
tab = []
f = "{:" + str(m) + "} {}"
for k in ky:
tab.append(f.format(k, self.__dict__[k]))
return "\n".join(tab)
class Table:
"""
A two-way contingency table.
Parameters
----------
table : array_like
A contingency table.
shift_zeros : bool
If True and any cell count is zero, add 0.5 to all values
in the table.
Attributes
----------
table_orig : array_like
The original table is cached as `table_orig`.
See Also
--------
statsmodels.graphics.mosaicplot.mosaic
scipy.stats.chi2_contingency
Notes
-----
The inference procedures used here are all based on a sampling
model in which the units are independent and identically
distributed, with each unit being classified with respect to two
categorical variables.
References
----------
Definitions of residuals:
https://onlinecourses.science.psu.edu/stat504/node/86
"""
def __init__(self, table, shift_zeros=True):
self.table_orig = table
self.table = np.asarray(table, dtype=np.float64)
if shift_zeros and (self.table.min() == 0):
self.table[self.table == 0] = 0.5
def __str__(self):
s = ("A %dx%d contingency table with counts:\n" %
tuple(self.table.shape))
s += np.array_str(self.table)
return s
@classmethod
def from_data(cls, data, shift_zeros=True):
"""
Construct a Table object from data.
Parameters
----------
data : array_like
The raw data, from which a contingency table is constructed
using the first two columns.
shift_zeros : bool
If True and any cell count is zero, add 0.5 to all values
in the table.
Returns
-------
A Table instance.
"""
if isinstance(data, pd.DataFrame):
table = pd.crosstab(data.iloc[:, 0], data.iloc[:, 1])
else:
table = pd.crosstab(data[:, 0], data[:, 1])
return cls(table, shift_zeros)
def test_nominal_association(self):
"""
Assess independence for nominal factors.
Assessment of independence between rows and columns using
chi^2 testing. The rows and columns are treated as nominal
(unordered) categorical variables.
Returns
-------
A bunch containing the following attributes:
statistic : float
The chi^2 test statistic.
df : int
The degrees of freedom of the reference distribution
pvalue : float
The p-value for the test.
"""
statistic = np.asarray(self.chi2_contribs).sum()
df = np.prod(np.asarray(self.table.shape) - 1)
pvalue = 1 - stats.chi2.cdf(statistic, df)
b = _Bunch()
b.statistic = statistic
b.df = df
b.pvalue = pvalue
return b
def test_ordinal_association(self, row_scores=None, col_scores=None):
"""
Assess independence between two ordinal variables.
This is the 'linear by linear' association test, which uses
weights or scores to target the test to have more power
against ordered alternatives.
Parameters
----------
row_scores : array_like
An array of numeric row scores
col_scores : array_like
An array of numeric column scores
Returns
-------
A bunch with the following attributes:
statistic : float
The test statistic.
null_mean : float
The expected value of the test statistic under the null
hypothesis.
null_sd : float
The standard deviation of the test statistic under the
null hypothesis.
zscore : float
The Z-score for the test statistic.
pvalue : float
The p-value for the test.
Notes
-----
The scores define the trend to which the test is most sensitive.
Using the default row and column scores gives the
Cochran-Armitage trend test.
"""
if row_scores is None:
row_scores = np.arange(self.table.shape[0])
if col_scores is None:
col_scores = np.arange(self.table.shape[1])
if len(row_scores) != self.table.shape[0]:
msg = ("The length of `row_scores` must match the first " +
"dimension of `table`.")
raise ValueError(msg)
if len(col_scores) != self.table.shape[1]:
msg = ("The length of `col_scores` must match the second " +
"dimension of `table`.")
raise ValueError(msg)
# The test statistic
statistic = np.dot(row_scores, np.dot(self.table, col_scores))
# Some needed quantities
n_obs = self.table.sum()
rtot = self.table.sum(1)
um = np.dot(row_scores, rtot)
u2m = np.dot(row_scores**2, rtot)
ctot = self.table.sum(0)
vn = np.dot(col_scores, ctot)
v2n = np.dot(col_scores**2, ctot)
# The null mean and variance of the test statistic
e_stat = um * vn / n_obs
v_stat = (u2m - um**2 / n_obs) * (v2n - vn**2 / n_obs) / (n_obs - 1)
sd_stat = np.sqrt(v_stat)
zscore = (statistic - e_stat) / sd_stat
pvalue = 2 * stats.norm.cdf(-np.abs(zscore))
b = _Bunch()
b.statistic = statistic
b.null_mean = e_stat
b.null_sd = sd_stat
b.zscore = zscore
b.pvalue = pvalue
return b
@cache_readonly
def marginal_probabilities(self):
"""
Estimate marginal probability distributions for the rows and columns.
Returns
-------
row : ndarray
Marginal row probabilities
col : ndarray
Marginal column probabilities
"""
n = self.table.sum()
row = self.table.sum(1) / n
col = self.table.sum(0) / n
if isinstance(self.table_orig, pd.DataFrame):
row = pd.Series(row, self.table_orig.index)
col = pd.Series(col, self.table_orig.columns)
return row, col
@cache_readonly
def independence_probabilities(self):
"""
Returns fitted joint probabilities under independence.
The returned table is outer(row, column), where row and
column are the estimated marginal distributions
of the rows and columns.
"""
row, col = self.marginal_probabilities
itab = np.outer(row, col)
if isinstance(self.table_orig, pd.DataFrame):
itab = pd.DataFrame(itab, self.table_orig.index,
self.table_orig.columns)
return itab
@cache_readonly
def fittedvalues(self):
"""
Returns fitted cell counts under independence.
The returned cell counts are estimates under a model
where the rows and columns of the table are independent.
"""
probs = self.independence_probabilities
fit = self.table.sum() * probs
return fit
@cache_readonly
def resid_pearson(self):
"""
Returns Pearson residuals.
The Pearson residuals are calculated under a model where
the rows and columns of the table are independent.
"""
fit = self.fittedvalues
resids = (self.table - fit) / np.sqrt(fit)
return resids
@cache_readonly
def standardized_resids(self):
"""
Returns standardized residuals under independence.
"""
row, col = self.marginal_probabilities
sresids = self.resid_pearson / np.sqrt(np.outer(1 - row, 1 - col))
return sresids
@cache_readonly
def chi2_contribs(self):
"""
Returns the contributions to the chi^2 statistic for independence.
The returned table contains the contribution of each cell to the chi^2
test statistic for the null hypothesis that the rows and columns
are independent.
"""
return self.resid_pearson**2
@cache_readonly
def local_log_oddsratios(self):
"""
Returns local log odds ratios.
The local log odds ratios are the log odds ratios
calculated for contiguous 2x2 sub-tables.
"""
ta = self.table.copy()
a = ta[0:-1, 0:-1]
b = ta[0:-1, 1:]
c = ta[1:, 0:-1]
d = ta[1:, 1:]
tab = np.log(a) + np.log(d) - np.log(b) - np.log(c)
rslt = np.empty(self.table.shape, np.float64)
rslt *= np.nan
rslt[0:-1, 0:-1] = tab
if isinstance(self.table_orig, pd.DataFrame):
rslt = pd.DataFrame(rslt, index=self.table_orig.index,
columns=self.table_orig.columns)
return rslt
@cache_readonly
def local_oddsratios(self):
"""
Returns local odds ratios.
See documentation for local_log_oddsratios.
"""
return np.exp(self.local_log_oddsratios)
@cache_readonly
def cumulative_log_oddsratios(self):
"""
Returns cumulative log odds ratios.
The cumulative log odds ratios for a contingency table
with ordered rows and columns are calculated by collapsing
all cells to the left/right and above/below a given point,
to obtain a 2x2 table from which a log odds ratio can be
calculated.
"""
ta = self.table.cumsum(0).cumsum(1)
a = ta[0:-1, 0:-1]
b = ta[0:-1, -1:] - a
c = ta[-1:, 0:-1] - a
d = ta[-1, -1] - (a + b + c)
tab = np.log(a) + np.log(d) - np.log(b) - np.log(c)
rslt = np.empty(self.table.shape, np.float64)
rslt *= np.nan
rslt[0:-1, 0:-1] = tab
if isinstance(self.table_orig, pd.DataFrame):
rslt = pd.DataFrame(rslt, index=self.table_orig.index,
columns=self.table_orig.columns)
return rslt
@cache_readonly
def cumulative_oddsratios(self):
"""
Returns the cumulative odds ratios for a contingency table.
See documentation for cumulative_log_oddsratio.
"""
return np.exp(self.cumulative_log_oddsratios)
class SquareTable(Table):
"""
Methods for analyzing a square contingency table.
Parameters
----------
table : array_like
A square contingency table, or DataFrame that is converted
to a square form.
shift_zeros : bool
If True and any cell count is zero, add 0.5 to all values
in the table.
Notes
-----
These methods should only be used when the rows and columns of the
table have the same categories. If `table` is provided as a
Pandas DataFrame, the row and column indices will be extended to
create a square table, inserting zeros where a row or column is
missing. Otherwise the table should be provided in a square form,
with the (implicit) row and column categories appearing in the
same order.
"""
def __init__(self, table, shift_zeros=True):
table = _make_df_square(table) # Non-pandas passes through
k1, k2 = table.shape
if k1 != k2:
raise ValueError('table must be square')
super(SquareTable, self).__init__(table, shift_zeros)
def symmetry(self, method="bowker"):
"""
Test for symmetry of a joint distribution.
This procedure tests the null hypothesis that the joint
distribution is symmetric around the main diagonal, that is
.. math::
p_{i, j} = p_{j, i} for all i, j
Returns
-------
Bunch
A bunch with attributes
* statistic : float
chisquare test statistic
* p-value : float
p-value of the test statistic based on chisquare distribution
* df : int
degrees of freedom of the chisquare distribution
Notes
-----
The implementation is based on the SAS documentation. R includes
it in `mcnemar.test` if the table is not 2 by 2. However a more
direct generalization of the McNemar test to larger tables is
provided by the homogeneity test (TableSymmetry.homogeneity).
The p-value is based on the chi-square distribution which requires
that the sample size is not very small to be a good approximation
of the true distribution. For 2x2 contingency tables the exact
distribution can be obtained with `mcnemar`
See Also
--------
mcnemar
homogeneity
"""
if method.lower() != "bowker":
raise ValueError("method for symmetry testing must be 'bowker'")
k = self.table.shape[0]
upp_idx = np.triu_indices(k, 1)
tril = self.table.T[upp_idx] # lower triangle in column order
triu = self.table[upp_idx] # upper triangle in row order
statistic = ((tril - triu)**2 / (tril + triu + 1e-20)).sum()
df = k * (k-1) / 2.
pvalue = stats.chi2.sf(statistic, df)
b = _Bunch()
b.statistic = statistic
b.pvalue = pvalue
b.df = df
return b
def homogeneity(self, method="stuart_maxwell"):
"""
Compare row and column marginal distributions.
Parameters
----------
method : str
Either 'stuart_maxwell' or 'bhapkar', leading to two different
estimates of the covariance matrix for the estimated
difference between the row margins and the column margins.
Returns
-------
Bunch
A bunch with attributes:
* statistic : float
The chi^2 test statistic
* pvalue : float
The p-value of the test statistic
* df : int
The degrees of freedom of the reference distribution
Notes
-----
For a 2x2 table this is equivalent to McNemar's test. More
generally the procedure tests the null hypothesis that the
marginal distribution of the row factor is equal to the
marginal distribution of the column factor. For this to be
meaningful, the two factors must have the same sample space
(i.e. the same categories).
"""
if self.table.shape[0] < 1:
raise ValueError('table is empty')
elif self.table.shape[0] == 1:
b = _Bunch()
b.statistic = 0
b.pvalue = 1
b.df = 0
return b
method = method.lower()
if method not in ["bhapkar", "stuart_maxwell"]:
raise ValueError("method '%s' for homogeneity not known" % method)
n_obs = self.table.sum()
pr = self.table.astype(np.float64) / n_obs
# Compute margins, eliminate last row/column so there is no
# degeneracy
row = pr.sum(1)[0:-1]
col = pr.sum(0)[0:-1]
pr = pr[0:-1, 0:-1]
# The estimated difference between row and column margins.
d = col - row
# The degrees of freedom of the chi^2 reference distribution.
df = pr.shape[0]
if method == "bhapkar":
vmat = -(pr + pr.T) - np.outer(d, d)
dv = col + row - 2*np.diag(pr) - d**2
np.fill_diagonal(vmat, dv)
elif method == "stuart_maxwell":
vmat = -(pr + pr.T)
dv = row + col - 2*np.diag(pr)
np.fill_diagonal(vmat, dv)
try:
statistic = n_obs * np.dot(d, np.linalg.solve(vmat, d))
except np.linalg.LinAlgError:
warnings.warn("Unable to invert covariance matrix",
sm_exceptions.SingularMatrixWarning)
b = _Bunch()
b.statistic = np.nan
b.pvalue = np.nan
b.df = df
return b
pvalue = 1 - stats.chi2.cdf(statistic, df)
b = _Bunch()
b.statistic = statistic
b.pvalue = pvalue
b.df = df
return b
def summary(self, alpha=0.05, float_format="%.3f"):
"""
Produce a summary of the analysis.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the interval.
float_format : str
Used to format numeric values in the table.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
fmt = float_format
headers = ["Statistic", "P-value", "DF"]
stubs = ["Symmetry", "Homogeneity"]
sy = self.symmetry()
hm = self.homogeneity()
data = [[fmt % sy.statistic, fmt % sy.pvalue, '%d' % sy.df],
[fmt % hm.statistic, fmt % hm.pvalue, '%d' % hm.df]]
tab = iolib.SimpleTable(data, headers, stubs, data_aligns="r",
table_dec_above='')
return tab
class Table2x2(SquareTable):
"""
Analyses that can be performed on a 2x2 contingency table.
Parameters
----------
table : array_like
A 2x2 contingency table
shift_zeros : bool
If true, 0.5 is added to all cells of the table if any cell is
equal to zero.
Notes
-----
The inference procedures used here are all based on a sampling
model in which the units are independent and identically
distributed, with each unit being classified with respect to two
categorical variables.
Note that for the risk ratio, the analysis is not symmetric with
respect to the rows and columns of the contingency table. The two
rows define population subgroups, column 0 is the number of
'events', and column 1 is the number of 'non-events'.
"""
def __init__(self, table, shift_zeros=True):
if type(table) is list:
table = np.asarray(table)
if (table.ndim != 2) or (table.shape[0] != 2) or (table.shape[1] != 2):
raise ValueError("Table2x2 takes a 2x2 table as input.")
super(Table2x2, self).__init__(table, shift_zeros)
@classmethod
def from_data(cls, data, shift_zeros=True):
"""
Construct a Table object from data.
Parameters
----------
data : array_like
The raw data, the first column defines the rows and the
second column defines the columns.
shift_zeros : bool
If True, and if there are any zeros in the contingency
table, add 0.5 to all four cells of the table.
"""
if isinstance(data, pd.DataFrame):
table = pd.crosstab(data.iloc[:, 0], data.iloc[:, 1])
else:
table = pd.crosstab(data[:, 0], data[:, 1])
return cls(table, shift_zeros)
@cache_readonly
def log_oddsratio(self):
"""
Returns the log odds ratio for a 2x2 table.
"""
f = self.table.flatten()
return np.dot(np.log(f), np.r_[1, -1, -1, 1])
@cache_readonly
def oddsratio(self):
"""
Returns the odds ratio for a 2x2 table.
"""
return (self.table[0, 0] * self.table[1, 1] /
(self.table[0, 1] * self.table[1, 0]))
@cache_readonly
def log_oddsratio_se(self):
"""
Returns the standard error for the log odds ratio.
"""
return np.sqrt(np.sum(1 / self.table))
def oddsratio_pvalue(self, null=1):
"""
P-value for a hypothesis test about the odds ratio.
Parameters
----------
null : float
The null value of the odds ratio.
"""
return self.log_oddsratio_pvalue(np.log(null))
def log_oddsratio_pvalue(self, null=0):
"""
P-value for a hypothesis test about the log odds ratio.
Parameters
----------
null : float
The null value of the log odds ratio.
"""
zscore = (self.log_oddsratio - null) / self.log_oddsratio_se
pvalue = 2 * stats.norm.cdf(-np.abs(zscore))
return pvalue
def log_oddsratio_confint(self, alpha=0.05, method="normal"):
"""
A confidence level for the log odds ratio.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
confidence interval.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
f = -stats.norm.ppf(alpha / 2)
lor = self.log_oddsratio
se = self.log_oddsratio_se
lcb = lor - f * se
ucb = lor + f * se
return lcb, ucb
def oddsratio_confint(self, alpha=0.05, method="normal"):
"""
A confidence interval for the odds ratio.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
confidence interval.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
lcb, ucb = self.log_oddsratio_confint(alpha, method=method)
return np.exp(lcb), np.exp(ucb)
@cache_readonly
def riskratio(self):
"""
Returns the risk ratio for a 2x2 table.
The risk ratio is calculated with respect to the rows.
"""
p = self.table[:, 0] / self.table.sum(1)
return p[0] / p[1]
@cache_readonly
def log_riskratio(self):
"""
Returns the log of the risk ratio.
"""
return np.log(self.riskratio)
@cache_readonly
def log_riskratio_se(self):
"""
Returns the standard error of the log of the risk ratio.
"""
n = self.table.sum(1)
p = self.table[:, 0] / n
va = np.sum((1 - p) / (n*p))
return np.sqrt(va)
def riskratio_pvalue(self, null=1):
"""
p-value for a hypothesis test about the risk ratio.
Parameters
----------
null : float
The null value of the risk ratio.
"""
return self.log_riskratio_pvalue(np.log(null))
def log_riskratio_pvalue(self, null=0):
"""
p-value for a hypothesis test about the log risk ratio.
Parameters
----------
null : float
The null value of the log risk ratio.
"""
zscore = (self.log_riskratio - null) / self.log_riskratio_se
pvalue = 2 * stats.norm.cdf(-np.abs(zscore))
return pvalue
def log_riskratio_confint(self, alpha=0.05, method="normal"):
"""
A confidence interval for the log risk ratio.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
confidence interval.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
f = -stats.norm.ppf(alpha / 2)
lrr = self.log_riskratio
se = self.log_riskratio_se
lcb = lrr - f * se
ucb = lrr + f * se
return lcb, ucb
def riskratio_confint(self, alpha=0.05, method="normal"):
"""
A confidence interval for the risk ratio.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
confidence interval.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
lcb, ucb = self.log_riskratio_confint(alpha, method=method)
return np.exp(lcb), np.exp(ucb)
def summary(self, alpha=0.05, float_format="%.3f", method="normal"):
"""
Summarizes results for a 2x2 table analysis.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the confidence
intervals.
float_format : str
Used to format the numeric values in the table.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
def fmt(x):
if isinstance(x, str):
return x
return float_format % x
headers = ["Estimate", "SE", "LCB", "UCB", "p-value"]
stubs = ["Odds ratio", "Log odds ratio", "Risk ratio",
"Log risk ratio"]
lcb1, ucb1 = self.oddsratio_confint(alpha, method)
lcb2, ucb2 = self.log_oddsratio_confint(alpha, method)
lcb3, ucb3 = self.riskratio_confint(alpha, method)
lcb4, ucb4 = self.log_riskratio_confint(alpha, method)
data = [[fmt(x) for x in [self.oddsratio, "", lcb1, ucb1,
self.oddsratio_pvalue()]],
[fmt(x) for x in [self.log_oddsratio, self.log_oddsratio_se,
lcb2, ucb2, self.oddsratio_pvalue()]],
[fmt(x) for x in [self.riskratio, "", lcb3, ucb3,
self.riskratio_pvalue()]],
[fmt(x) for x in [self.log_riskratio, self.log_riskratio_se,
lcb4, ucb4, self.riskratio_pvalue()]]]
tab = iolib.SimpleTable(data, headers, stubs, data_aligns="r",
table_dec_above='')
return tab
class StratifiedTable:
"""
Analyses for a collection of 2x2 contingency tables.
Such a collection may arise by stratifying a single 2x2 table with
respect to another factor. This class implements the
'Cochran-Mantel-Haenszel' and 'Breslow-Day' procedures for
analyzing collections of 2x2 contingency tables.
Parameters
----------
tables : list or ndarray
Either a list containing several 2x2 contingency tables, or
a 2x2xk ndarray in which each slice along the third axis is a
2x2 contingency table.
Notes
-----
This results are based on a sampling model in which the units are
independent both within and between strata.
"""
def __init__(self, tables, shift_zeros=False):
if isinstance(tables, np.ndarray):
sp = tables.shape
if (len(sp) != 3) or (sp[0] != 2) or (sp[1] != 2):
raise ValueError("If an ndarray, argument must be 2x2xn")
table = tables * 1. # use atleast float dtype
else:
if any([np.asarray(x).shape != (2, 2) for x in tables]):
m = "If `tables` is a list, all of its elements should be 2x2"
raise ValueError(m)
# Create a data cube
table = np.dstack(tables).astype(np.float64)
if shift_zeros:
zx = (table == 0).sum(0).sum(0)
ix = np.flatnonzero(zx > 0)
if len(ix) > 0:
table = table.copy()
table[:, :, ix] += 0.5
self.table = table
self._cache = {}
# Quantities to precompute. Table entries are [[a, b], [c,
# d]], 'ad' is 'a * d', 'apb' is 'a + b', 'dma' is 'd - a',
# etc.
self._apb = table[0, 0, :] + table[0, 1, :]
self._apc = table[0, 0, :] + table[1, 0, :]
self._bpd = table[0, 1, :] + table[1, 1, :]
self._cpd = table[1, 0, :] + table[1, 1, :]
self._ad = table[0, 0, :] * table[1, 1, :]
self._bc = table[0, 1, :] * table[1, 0, :]
self._apd = table[0, 0, :] + table[1, 1, :]
self._dma = table[1, 1, :] - table[0, 0, :]
self._n = table.sum(0).sum(0)
@classmethod
def from_data(cls, var1, var2, strata, data):
"""
Construct a StratifiedTable object from data.
Parameters
----------
var1 : int or string
The column index or name of `data` specifying the variable
defining the rows of the contingency table. The variable
must have only two distinct values.
var2 : int or string
The column index or name of `data` specifying the variable
defining the columns of the contingency table. The variable
must have only two distinct values.
strata : int or string
The column index or name of `data` specifying the variable
defining the strata.
data : array_like
The raw data. A cross-table for analysis is constructed
from the first two columns.
Returns
-------
StratifiedTable
"""
if not isinstance(data, pd.DataFrame):
data1 = pd.DataFrame(index=np.arange(data.shape[0]),
columns=[var1, var2, strata])
data1[data1.columns[var1]] = data[:, var1]
data1[data1.columns[var2]] = data[:, var2]
data1[data1.columns[strata]] = data[:, strata]
else:
data1 = data[[var1, var2, strata]]
gb = data1.groupby(strata).groups
tables = []
for g in gb:
ii = gb[g]
tab = pd.crosstab(data1.loc[ii, var1], data1.loc[ii, var2])
if (tab.shape != np.r_[2, 2]).any():
msg = "Invalid table dimensions"
raise ValueError(msg)
tables.append(np.asarray(tab))
return cls(tables)
def test_null_odds(self, correction=False):
"""
Test that all tables have odds ratio equal to 1.
This is the 'Mantel-Haenszel' test.
Parameters
----------
correction : bool
If True, use the continuity correction when calculating the
test statistic.
Returns
-------
Bunch
A bunch containing the chi^2 test statistic and p-value.
"""
statistic = np.sum(self.table[0, 0, :] -
self._apb * self._apc / self._n)
statistic = np.abs(statistic)
if correction:
statistic -= 0.5
statistic = statistic**2
denom = self._apb * self._apc * self._bpd * self._cpd
denom /= (self._n**2 * (self._n - 1))
denom = np.sum(denom)
statistic /= denom
# df is always 1
pvalue = 1 - stats.chi2.cdf(statistic, 1)
b = _Bunch()
b.statistic = statistic
b.pvalue = pvalue
return b
@cache_readonly
def oddsratio_pooled(self):
"""
The pooled odds ratio.
The value is an estimate of a common odds ratio across all of the
stratified tables.
"""
odds_ratio = np.sum(self._ad / self._n) / np.sum(self._bc / self._n)
return odds_ratio
@cache_readonly
def logodds_pooled(self):
"""
Returns the logarithm of the pooled odds ratio.
See oddsratio_pooled for more information.
"""
return np.log(self.oddsratio_pooled)
@cache_readonly
def riskratio_pooled(self):
"""
Estimate of the pooled risk ratio.
"""
acd = self.table[0, 0, :] * self._cpd
cab = self.table[1, 0, :] * self._apb
rr = np.sum(acd / self._n) / np.sum(cab / self._n)
return rr
@cache_readonly
def logodds_pooled_se(self):
"""
Estimated standard error of the pooled log odds ratio
References
----------
J. Robins, N. Breslow, S. Greenland. "Estimators of the
Mantel-Haenszel Variance Consistent in Both Sparse Data and
Large-Strata Limiting Models." Biometrics 42, no. 2 (1986): 311-23.
"""
adns = np.sum(self._ad / self._n)
bcns = np.sum(self._bc / self._n)
lor_va = np.sum(self._apd * self._ad / self._n**2) / adns**2
mid = self._apd * self._bc / self._n**2
mid += (1 - self._apd / self._n) * self._ad / self._n
mid = np.sum(mid)
mid /= (adns * bcns)
lor_va += mid
lor_va += np.sum((1 - self._apd / self._n) *
self._bc / self._n) / bcns**2
lor_va /= 2
lor_se = np.sqrt(lor_va)
return lor_se
def logodds_pooled_confint(self, alpha=0.05, method="normal"):
"""
A confidence interval for the pooled log odds ratio.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
interval.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
Returns
-------
lcb : float
The lower confidence limit.
ucb : float
The upper confidence limit.
"""
lor = np.log(self.oddsratio_pooled)
lor_se = self.logodds_pooled_se
f = -stats.norm.ppf(alpha / 2)
lcb = lor - f * lor_se
ucb = lor + f * lor_se
return lcb, ucb
def oddsratio_pooled_confint(self, alpha=0.05, method="normal"):
"""
A confidence interval for the pooled odds ratio.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
interval.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
Returns
-------
lcb : float
The lower confidence limit.
ucb : float
The upper confidence limit.
"""
lcb, ucb = self.logodds_pooled_confint(alpha, method=method)
lcb = np.exp(lcb)
ucb = np.exp(ucb)
return lcb, ucb
def test_equal_odds(self, adjust=False):
"""
Test that all odds ratios are identical.
This is the 'Breslow-Day' testing procedure.
Parameters
----------
adjust : bool
Use the 'Tarone' adjustment to achieve the chi^2
asymptotic distribution.
Returns
-------
A bunch containing the following attributes:
statistic : float
The chi^2 test statistic.
p-value : float
The p-value for the test.
"""
table = self.table
r = self.oddsratio_pooled
a = 1 - r
b = r * (self._apb + self._apc) + self._dma
c = -r * self._apb * self._apc
# Expected value of first cell
dr = np.sqrt(b**2 - 4*a*c)
e11 = (-b + dr) / (2*a)
# Variance of the first cell
v11 = (1 / e11 + 1 / (self._apc - e11) + 1 / (self._apb - e11) +
1 / (self._dma + e11))
v11 = 1 / v11
statistic = np.sum((table[0, 0, :] - e11)**2 / v11)
if adjust:
adj = table[0, 0, :].sum() - e11.sum()
adj = adj**2
adj /= np.sum(v11)
statistic -= adj
pvalue = 1 - stats.chi2.cdf(statistic, table.shape[2] - 1)
b = _Bunch()
b.statistic = statistic
b.pvalue = pvalue
return b
def summary(self, alpha=0.05, float_format="%.3f", method="normal"):
"""
A summary of all the main results.
Parameters
----------
alpha : float
`1 - alpha` is the nominal coverage probability of the
confidence intervals.
float_format : str
Used for formatting numeric values in the summary.
method : str
The method for producing the confidence interval. Currently
must be 'normal' which uses the normal approximation.
"""
def fmt(x):
if isinstance(x, str):
return x
return float_format % x
co_lcb, co_ucb = self.oddsratio_pooled_confint(
alpha=alpha, method=method)
clo_lcb, clo_ucb = self.logodds_pooled_confint(
alpha=alpha, method=method)
headers = ["Estimate", "LCB", "UCB"]
stubs = ["Pooled odds", "Pooled log odds", "Pooled risk ratio", ""]
data = [[fmt(x) for x in [self.oddsratio_pooled, co_lcb, co_ucb]],
[fmt(x) for x in [self.logodds_pooled, clo_lcb, clo_ucb]],
[fmt(x) for x in [self.riskratio_pooled, "", ""]],
['', '', '']]
tab1 = iolib.SimpleTable(data, headers, stubs, data_aligns="r",
table_dec_above='')
headers = ["Statistic", "P-value", ""]
stubs = ["Test of OR=1", "Test constant OR"]
rslt1 = self.test_null_odds()
rslt2 = self.test_equal_odds()
data = [[fmt(x) for x in [rslt1.statistic, rslt1.pvalue, ""]],
[fmt(x) for x in [rslt2.statistic, rslt2.pvalue, ""]]]
tab2 = iolib.SimpleTable(data, headers, stubs, data_aligns="r")
tab1.extend(tab2)
headers = ["", "", ""]
stubs = ["Number of tables", "Min n", "Max n", "Avg n", "Total n"]
ss = self.table.sum(0).sum(0)
data = [["%d" % self.table.shape[2], '', ''],
["%d" % min(ss), '', ''],
["%d" % max(ss), '', ''],
["%.0f" % np.mean(ss), '', ''],
["%d" % sum(ss), '', '', '']]
tab3 = iolib.SimpleTable(data, headers, stubs, data_aligns="r")
tab1.extend(tab3)
return tab1
def mcnemar(table, exact=True, correction=True):
"""
McNemar test of homogeneity.
Parameters
----------
table : array_like
A square contingency table.
exact : bool
If exact is true, then the binomial distribution will be used.
If exact is false, then the chisquare distribution will be
used, which is the approximation to the distribution of the
test statistic for large sample sizes.
correction : bool
If true, then a continuity correction is used for the chisquare
distribution (if exact is false.)
Returns
-------
A bunch with attributes:
statistic : float or int, array
The test statistic is the chisquare statistic if exact is
false. If the exact binomial distribution is used, then this
contains the min(n1, n2), where n1, n2 are cases that are zero
in one sample but one in the other sample.
pvalue : float or array
p-value of the null hypothesis of equal marginal distributions.
Notes
-----
This is a special case of Cochran's Q test, and of the homogeneity
test. The results when the chisquare distribution is used are
identical, except for continuity correction.
"""
table = _make_df_square(table)
table = np.asarray(table, dtype=np.float64)
n1, n2 = table[0, 1], table[1, 0]
if exact:
statistic = np.minimum(n1, n2)
# binom is symmetric with p=0.5
# SciPy 1.7+ requires int arguments
int_sum = int(n1 + n2)
if int_sum != (n1 + n2):
raise ValueError(
"exact can only be used with tables containing integers."
)
pvalue = stats.binom.cdf(statistic, int_sum, 0.5) * 2
pvalue = np.minimum(pvalue, 1) # limit to 1 if n1==n2
else:
corr = int(correction) # convert bool to 0 or 1
statistic = (np.abs(n1 - n2) - corr)**2 / (1. * (n1 + n2))
df = 1
pvalue = stats.chi2.sf(statistic, df)
b = _Bunch()
b.statistic = statistic
b.pvalue = pvalue
return b
def cochrans_q(x, return_object=True):
"""
Cochran's Q test for identical binomial proportions.
Parameters
----------
x : array_like, 2d (N, k)
data with N cases and k variables
return_object : bool
Return values as bunch instead of as individual values.
Returns
-------
Returns a bunch containing the following attributes, or the
individual values according to the value of `return_object`.
statistic : float
test statistic
pvalue : float
pvalue from the chisquare distribution
Notes
-----
Cochran's Q is a k-sample extension of the McNemar test. If there
are only two groups, then Cochran's Q test and the McNemar test
are equivalent.
The procedure tests that the probability of success is the same
for every group. The alternative hypothesis is that at least two
groups have a different probability of success.
In Wikipedia terminology, rows are blocks and columns are
treatments. The number of rows N, should be large for the
chisquare distribution to be a good approximation.
The Null hypothesis of the test is that all treatments have the
same effect.
References
----------
https://en.wikipedia.org/wiki/Cochran_test
SAS Manual for NPAR TESTS
"""
x = np.asarray(x, dtype=np.float64)
gruni = np.unique(x)
N, k = x.shape
count_row_success = (x == gruni[-1]).sum(1, float)
count_col_success = (x == gruni[-1]).sum(0, float)
count_row_ss = count_row_success.sum()
count_col_ss = count_col_success.sum()
assert count_row_ss == count_col_ss # just a calculation check
# From the SAS manual
q_stat = ((k-1) * (k * np.sum(count_col_success**2) - count_col_ss**2)
/ (k * count_row_ss - np.sum(count_row_success**2)))
# Note: the denominator looks just like k times the variance of
# the columns
# Wikipedia uses a different, but equivalent expression
# q_stat = (k-1) * (k * np.sum(count_row_success**2) - count_row_ss**2)
# / (k * count_col_ss - np.sum(count_col_success**2))
df = k - 1
pvalue = stats.chi2.sf(q_stat, df)
if return_object:
b = _Bunch()
b.statistic = q_stat
b.df = df
b.pvalue = pvalue
return b
return q_stat, pvalue, df
|
32719f446dd7a95bbe88ac400788876377462b36
|
merimus/coding-bootcamp
|
/euler/merimus/35/35.py
| 1,471 | 3.90625 | 4 |
import math
class GenPrime(object):
def __init__(self):
self.primes = [2, 3, 5, 7]
def Primes(self):
for p in self.primes:
yield p
while True:
yield self.GenPrime()
def IsPrime(self, n):
cuttoff = math.sqrt(n)
for p in self.primes:
if p > cuttoff:
return True
if n % p == 0:
return False
def GenPrime(self, n):
c = n + 1
while not self.IsPrime(c):
c += 1
self.primes.append(c)
return c
class Primes(object):
def __init__(self):
self.primes = set([2, 3, 5, 7])
self.lastprime = 7
self.gp = GenPrime()
def IsPrime(self, p):
while self.lastprime < p:
self.lastprime = self.gp.GenPrime(self.lastprime)
self.primes.add(self.lastprime)
return p in self.primes
def digits(n):
tmp = n
result = []
while tmp > 0:
result.append(tmp % 10)
tmp /= 10
result.reverse()
return result
def number(d):
tmp = map(lambda x:str(x), d)
return int(''.join(tmp))
def test(p, n):
d = digits(n)
for i in range(len(d)):
if not p.IsPrime(number(d)):
return False
tmp = d[0]
d = d[1:]
d.append(tmp)
return True
num = 0
p = Primes()
for i in range(2, 1000000):
if test(p, i):
print i
num += 1
print "ANSWER:", num
|
569a527462bbfbdd06b23a2a18f309fd728ba545
|
tamily-duoy/pyfile
|
/2017-5/DS/eightde/select_sortde.py
| 345 | 3.828125 | 4 |
#!/usr/bin/python
# -*- coding:utf-8 -*-
def select_sort(a):
# 选择排序
for i in range(0, len(a)):
pos = i
for j in range(i + 1, len(a)):
if a[pos] > a[j]:
pos = j
a[pos], a[i] = a[i], a[pos]
return a
if __name__=='__main__':
a=[4,3,1,7]
c=select_sort(a)
print(c)
|
8a7fba97f2e5895d65f3181d82455883cbe5eeee
|
zuxinlin/leetcode
|
/leetcode/204.CountPrimes.py
| 741 | 3.828125 | 4 |
#! /usr/bin/env python
# coding: utf-8
'''
题目: 统计素数 https://leetcode-cn.com/problems/count-primes/
主题: hash table & math
解题思路:
1. 利用数组缓存是否素数
'''
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
no_prime = [False] * n
count = 0
for i in range(2, n):
if not no_prime[i]:
count += 1
for j in range(i, n/i+1):
if i * j < n:
no_prime[i*j] = True
else:
break
return count
if __name__ == '__main__':
solution = Solution()
print ord('0') - ord('P')
|
925cc5e42f6e746f24bc7e5d6488186e53754097
|
gavjan/py_data_struct
|
/trie.py
| 1,677 | 3.640625 | 4 |
class TrieNode:
def __init__(self, char):
self.char = char
self.is_end = False
self.children = {}
"""
Trie that returns the first 3 suggestions for a given query
"""
class Trie(object):
output = []
def __init__(self):
self.root = TrieNode("")
def insert(self, word):
node = self.root
for char in word:
if char in node.children:
node = node.children[char]
else:
new_node = TrieNode(char)
node.children[char] = new_node
node = new_node
node.is_end = True
def dfs(self, node, prefix):
if len(self.output) >= 3:
return
if node.is_end:
self.output.append(prefix + node.char)
for child in node.children.values():
self.dfs(child, prefix + node.char)
def query(self, query):
self.output = []
node = self.root
for char in query:
if char in node.children:
node = node.children[char]
else:
return []
self.dfs(node, query[:-1])
return self.output
class Suggester:
prods = []
trie = Trie()
def __init__(self):
f = open("words.txt", "r")
for word in f.read().split("\n"):
self.trie.insert(word)
f.close()
def suggest(self, test_case):
return self.trie.query(test_case)
def test(self):
for test_case in ["Sta", "Rec", "Pick"]:
ans = self.suggest(test_case)
print(f"For '{test_case}' suggestions are: {ans}")
suggester = Suggester()
suggester.test()
|
824853a3c83f0d2c46cf43fbe34b86372f85b772
|
Sgrives/Python-Class
|
/using_numpy.py
| 9,806 | 4.53125 | 5 |
# Crash Course in Python
# Author: Breanna McBean
# Select functions from the NumPy package
# May 28, 2019
##############################################
# Using the NumPy Package (especially NumPy Arrays)
# importing a package (adding "as np" allows us to shorten what we type in the future)
import numpy as np
# Why use numpy arrays?
# - less memory used
# - faster run-time
# observations
height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
print("height:", height)
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
print("weight:", weight)
# creating numpy arrays
# Use "np" to tell Python what package to check for the function
np_height = np.array(height)
print("np_height:", np_height)
np_weight = np.array(weight)
print("np_weight:", np_weight)
# Print the data type of the variable
print("np_height type:", type(np_height))
# Print the type of elements held in the array
print("np_height element type:", np_height.dtype)
# Create a multi-dimensional np array
np_data = np.array([height, weight])
print("np_data:")
print(np_data)
# Note: NumPy arrays must have the same data type for each entry.
# You can print the dimensions of the data
print("dimensions of np_data:", np_data.shape)
# You can print the number of elements in the array
print("number of elements in np_data:", np_data.size)
# There are also many ways to create an array
# You can read in data from a file using "np.genfromtxt("file.type", skip_header=1, delimiter="x")"
populations = np.genfromtxt("city.csv", skip_header=1, delimiter=",")
# Since NumPy arrays must have the same data type for each element, if there is a title on the column,
# use the argument "skip_header=1" to skip the first line.
# There is also an argument "unpack" that you can set to "True" if you want to save each column to a separate
# variable. You would set x,y,...=np.genfromtxt(..., unpack=True).
# Note: If there are string values in numerical data, they will be changed to nan when converted into a
# NumPy array. Since there are non-numerical entries "city.csv", we need to address this.
populations[np.isnan(populations)] = 0
# The "isnan(np.array)" function will return a boolean array where ones indicate that the entry in that position in
# np.array is not a number. In line 61, we use this to set the non-numerical values to 0. Depending on what your
# application is, you could also set the value to be the average of the other data points in that column, or
# whatever makes the most sense.
print(populations)
# You can create an array and specify the data type of the elements
a = np.array([[1, 2, 4], [5, 8, 7]], dtype='int')
print("creating an np array with lists:", a.dtype)
# Instead of lists, you can also use tuples to create an np array
# Creating a 3X4 array with all zeros
b = np.zeros((3, 4))
print("initializing np array full of zeros:")
print(b)
# You can create the identity matrix
eye = np.identity(3)
print("identity matrix:")
print(eye)
# You can also choose a number to initialize all of the elements to (if you don't want 0)
c = np.full((3, 3), 6, dtype='complex')
print("initializing np array with a specific value:")
print(c)
# You can also randomize inputs from the distribution of your choice
d = 5 * np.random.random_sample((3, 2))
print("initializing np array from a random sample in [0,5):")
print(d)
# Check out https://docs.scipy.org/doc/numpy/reference/routines.random.html for more information
# on how to sample from different distributions
# Create a sequence of integers from 0 to 30 with steps of 5
e = np.arange(0, 30, 5)
print("creates a np array using arange:", e)
# Like range, this is not inclusive on the second endpoint
# Create a sequence of 10 values in range 0 to 5
f = np.linspace(0, 5, 10)
print("creates np array using linspace:")
print(f)
# This is like the linspace command from MATLAB
# You can reshape arrays. Here, we will reshape 3X4 array to 2X2X3 array
arr = np.array([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])
# Reshape the array to 3 dimensions
new_arr = arr.reshape(2, 2, 3)
print("original array:")
print(arr)
print("reshaped array:")
print(new_arr)
# You can also flatten numpy arrays
# Flatten array
arr = np.array([[1, 2, 3], [4, 5, 6]])
fl_arr = arr.flatten()
print("original array:")
print(arr)
print("flattened array:")
print(fl_arr)
# You can also look at only certain portions of arrays
# Arrange elements from 0 to 19
g = np.arange(20)
print("np array with elements 0-19:", g)
# Here, we are "slicing" the array. The format is arr[start:stop:step]
h = g[8:17:1]
print("creates np array of the 8th-17th element of g:", h)
# Choosing one of the indices as negative starts counting from the end of the array rather than the start
i = g[-8:17:1]
print("creates np array of 8th element from the end of g to the 17th element of g:", i)
# Like in MATLAB, the : operator when indexing means all elements.
j = g[10:]
print("creates np array of 10th-last elements of g:", j)
# You can also look at portions of an array which meet a given condition.
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("original array:")
print(arr)
cond = arr > 0
# Here, "cond" is a boolean array.
print("boolean array of which elements in the original array meet the condition:")
print(cond)
temp = arr[cond]
print("flat array of elements that met the condition:")
print(temp)
# You can also perform many operations on arrays
k = np.array([1, 2, 5, 3])
print("original array:", k)
# You can add 1 to every element
print("original array +1:", k+1)
# You can subtract 3 from each element
print("original array -3:", k-3)
# You can multiply each element by 10
print("original array times 10:", k*10)
# You can square each element
print("square each element of the original array:", k**2)
# It is nice that we can do these operations for NumPy arrays, because we cannot do this for lists.
# Note: The +=, -=, *=, /= operators work for NumPy arrays.
# You can take the transpose of numpy array
m = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print("original array:")
print(m)
print("transpose array:")
print(m.T)
# NumPy arrays also support unary operators
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
print("original array:")
print(arr)
# You can get the maximum element of array
print("max element:", arr.max())
# You can find the maximum element in a row
print("np array of max elements by row:", arr.max(axis=1))
# Choosing axis=0 gives the maximum of each columns
# You can get the minimum element in each column
print("np array of min elements by column", arr.min(axis=0))
# Choosing axis=1 gives minimum of each row
# You can get the sum of array elements
print("sum of each element in the array:", arr.sum())
# You can get the cumulative sum along each row
print("np array of cumulative sum of elements going across each row:")
print(arr.cumsum(axis=1))
# Choosing axis=0 gives teh cumulative sum along each column
# NumPy arrays also support binary operations
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
print("array 1:")
print(a)
print("array 2:")
print(b)
# You can add arrays
print("array 1 + array 2:")
print(a + b)
# You can perform element-wise multiplication
print("element wise multiplication of arrays 1 and 2:")
print(a * b)
# You can perform matrix multiplication
print("matrix multiplication of array 1 * array 2:")
print(a.dot(b))
# NumPy also contains many common mathematical functions that can be performed on arrays
# You can perform trig operations
c = np.array([0, np.pi / 2, np.pi])
print("original array:", c)
print("sin of each element:", np.sin(c))
# You can exponentiate array values
d = np.array([0, 1, 2, 3])
print("original array:", d)
print("exponentiate each element:", np.exp(d))
# You can take the square root of array values
print("square root each element:", np.sqrt(d))
# You can also sort arrays. We will sort the following array:
e = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
print("original array:")
print(e)
# Sort the array (returns a flat array of sorted values if axis=None)
print("flattened sorted array:", np.sort(e, axis=None))
# If you set "axis=0" or "axis=1", you will get an array sorted along either the columns or rows, respectively.
# Note: Adding an extra argument, "kind= 'sort_algo'", you can choose the sorting algorithm.
# If you're familiar with sorting algorithms and have a large array this may be beneficial to you.
# Default sorting algorithm is quicksort. The other two options are merge sort and heap sort.
# You can also sort an array by certain values
# Fist, set alias names for dtypes
dtypes = [('name', object), ('grad_year', int), ('cgpa', float)]
# np array requires strings to have a fixed length, so use 'object' for the data type and it can store a
# string of any length
# Values to be put in array
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype=dtypes)
print("original array:")
print(arr)
# You can sort the array by name
print("array sorted by name:")
print(np.sort(arr, order='name'))
# You can also sort the array by grad year first then by the cumulative gpa
print("array sorted by grad year then GPA:")
print(np.sort(arr, order=['grad_year', 'cgpa']))
# You can access elements of a numpy array using square brackets
print(arr[0])
|
c2024f2269216f8e794d010ea11b9d3d2a04fc24
|
LeslieHor/woof-tile
|
/lib/src/helpers.py
| 861 | 4.03125 | 4 |
def join_and_sanitize(list_):
"""Join a list of items into a single string"""
if isinstance(list_, str):
return list_
new_list = []
for item in list_:
if isinstance(item, str):
new_list.append(item)
elif isinstance(item, int):
new_list.append(str(item))
elif isinstance(item, float):
new_list.append(str(item))
else:
raise Exception('Invalid type when attempting to join and sanitize')
return ' '.join(new_list)
def cut_off_rest(arg):
"""
Cuts of the comment of the args
"""
return arg.split(' : ')[0]
def combine_lists(list_1, list_2):
if (list_1, list_2) == (None, None):
return []
elif list_1 is None:
return list_2
elif list_2 is None:
return list_1
else:
return list_1 + list_2
|
ec70e4d94a405465763d739bdbf1728e90559075
|
mtucker91/Intro_to_Python
|
/past_assignments/Prog Assignment 5 - 2_ Print Even numbers + indexes/even_numbers.py
| 1,037 | 4.0625 | 4 |
# This part is to ask the user to input the list items.
# It works, don't change or delete.
# The way it works is not the scope of this question, we will cover it later
#commented this out for testing
#list_string = input('Enter list items (all int):\n')
list_string = "7 5 6 5 4 9"
my_list = [int(elem) for elem in list_string.split()]
#my_list = [7, 5, 6, 5, 4, 9]
print('The list entered is:')
print(my_list)
# FIXME: complete the program after this line
print('The even numbers in the list with their indexes:')
#
for index, x in enumerate(my_list):
if(x % 2) == 0:
#print('my_list[%s]: %d' % (index, elem))
print('my_list[' + str(index) + ']: ' + str(x))
#print('my_list[' + index + ']: ' + x)
#placeholder
k = 1
for j in my_list:
#adding to said placeholder
k += 1
print('the amount of indexes = ' + str(k))
i = 0
while(i < k): #compare i (iteration) to my placeholder k
x = my_list[i]
if(x % 2) == 0:
print('my_list[' + str(i) + ']: ' + str(x))
i += 1
|
a8eee36c673c6081ad3c57b84ea9e371bb068c50
|
zuobing1995/tiantianguoyuan
|
/第一阶段/day04/exercise/square.py
| 553 | 3.921875 | 4 |
# 练习:
# 输入一个整数代表正方形的宽度,用变量n绑定,
# 打印指定宽度的正方形
# 如:
# 请输入: 5
# 打印如下:
# 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
# 如:
# 请输入: 3
# 打印如下:
# 1 2 3
# 1 2 3
# 1 2 3
n = int(input("请输入: "))
line = 1 # 代表当前行
while line <= n:
# print('打印第%d行' % line)
i = 1
while i <= n:
print(i, end=' ')
i += 1
print() # 一行打印完,换行
line += 1
|
45181810d2d51ed8df8b5a6dc7f61c9d30888b6d
|
Dragos-n/Composite_design
|
/01_Python/Submenu.py
| 562 | 3.609375 | 4 |
class Submenu:
"""
Class for leaf/submenu
"""
def __init__(self, name):
""""
'Constructor' (init) method for a new leaf/submenu object
Input parameter: the name of new class object
"""
self.name = name
def __del__(self):
""""
Destructor method for a new object - inherited also in Menu
"""
del self.name
def print_method(self):
""""
Method that prints out the leaf/submenu objects
"""
print("\t", end="")
print(self.name)
|
7768feee6a59b972a085a5fba4bb50053dbcc4d7
|
mohammedaasem/PythonBasicPrograms
|
/26_operator_identity.py
| 166 | 4.09375 | 4 |
# is & is not
a=10
if a is 10:
print("Equal")
else:
print("Not Equal")
b=5
if b is not a:
print("Both are different")
else:
print("Both are Equal")
|
d64bbe00e52430cce530be00a42fd62ae17aeed2
|
Ricky-Hu5918/Python-Lab
|
/sortedSquares.py
| 1,191 | 3.6875 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#Leetcode.num = 977
"""
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number,
also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
"""
'''以下两种方式均借助了排序方法,耗时在250ms左右'''
''' #1
def sortedSquares(A):
for i in range(len(A)):
A[i] *= A[i]
A.sort()
return A
'''
''' #2
def sortedSquares(A):
return sorted([i**2 for i in A])
'''
''' #3: 用了冒泡排序,但timeout了
def sortedSquares(A):
for i in range(len(A)):
A[i] *= A[i]
for i in range(len(A)):
for j in range(i+1, len(A)):
if (A[i]>A[j]):
A[i], A[j] = A[j], A[i]
return A
'''
'''用了所谓的双指针,首尾比较,将最大的放在最前面,最后再排序'''
def sortedSquares(A):
i, j = 0, len(A)-1
res = []
while (i <= j):
if (A[i]*A[i]>A[j]*A[j]):
res.append(A[i]*A[i])
i += 1
else:
res.append(A[j]*A[j])
j -= 1
return res[::-1]
l1 = [-5,-2,1,3,6]
print(sortedSquares(l1))
|
8ebaac53f31fa9bee0a8c5ab169bedf614255483
|
andyworkingholiday/Operating_System
|
/Lab02/Safety_Algorithm.py
| 4,838 | 3.59375 | 4 |
import sys
def print_safe_sequence(allocations, needs, availables, sequence):
global process_count, instance_count
if(len(sequence) == process_count):
print("시작", end=" => ")
for process_num in sequence:
print("process{}".format(process_num), end=" => ")
print("종료")
else:
for i in range(process_count):
if i not in sequence:
is_safe = True
for j in range(instance_count):
if availables[j] < needs[i][j]:
is_safe = False
break
if is_safe:
new_availables = availables[:]
new_sequence = sequence[:]
for j in range(instance_count):
new_availables[j] = availables[j] + allocations[i][j]
new_sequence.append(i)
print_safe_sequence(allocations, needs, new_availables, new_sequence)
print("[입력]")
print("\n====== Process 갯수 입력 ====== ")
process_count = int(input("process 갯수를 입력해주세요(2~10) : "))
if process_count < 2 or process_count > 10:
print("[Error] process 갯수를 잘못 입력하셨습니다. 프로그램을 종료합니다.")
sys.exit()
print("\n====== Resource 갯수 입력 ======")
resource_count = int(input("resource 갯수를 입력해주세요(2~5) : "))
if resource_count < 2 or resource_count > 5:
print("[Error] resource 갯수를 잘못 입력하셨습니다. 프로그램을 종료합니다.")
sys.exit()
print("====== Instance 입력 ====== ")
instances = []
instance_count = 0
while(instance_count<resource_count):
instance = int(input("{}번째 자원의 instance 갯수를 입력해주세요(0~99) : ".format(instance_count + 1)))
if instance == 0:
break
if instance < 0 or instance > 99:
print("[Error] instance 갯수를 잘못 입력하셨습니다. 프로그램을 종료합니다.")
sys.exit()
instances.append(instance)
instance_count += 1
if instance_count < 2:
print("[Error] 자원 종류는 2개 이상만 가능합니다. 프로그램을 종료합니다.")
sys.exit()
print("\n====== Allocation 입력 ====== ")
allocations = []
availables = instances[:]
for i in range(process_count):
allocation = input("process{}의 자원을 할당해주세요(띄어쓰기로 구분 ex) 0 1 2 ...) : ".format(i)).split(" ")
if len(allocation) != instance_count:
print("[Error] 자원 종류와 입력된 자원의 갯수가 같지 않습니다. 프로그램을 종료합니다.")
sys.exit()
for j in range(instance_count):
allocation[j] = int(allocation[j])
availables[j] = availables[j] - allocation[j]
if allocation[j] < 0 or allocation[j] > instances[j] or availables[j] < 0:
print("[Error] 자원 입력이 잘못되었습니다. 프로그램을 종료합니다.")
sys.exit()
allocations.append(allocation)
print("\n====== Max 입력 ====== ")
maxes = []
needs = []
for i in range(process_count):
max_row = input("process{}의 자원의 최대치를 입력해주세요(띄어쓰기로 구분 ex) 0 1 2 ...) : ".format(i)).split(" ")
need = []
if len(max_row) != instance_count:
print("[Error] 자원 종류와 입력된 자원의 개수가 같지 않습니다. 프로그램을 종료합니다.")
sys.exit()
for j in range(instance_count):
max_row[j] = int(max_row[j])
if max_row[j] < 0 or max_row[j] > instances[j] or max_row[j] < allocations[i][j]:
print("[Error] 자원 입력이 잘못되었습니다. 프로그램을 종료합니다.")
sys.exit()
need.append(max_row[j] - allocations[i][j])
maxes.append(max_row)
needs.append(need)
print("\n[출력]")
print("====== Instance ====== ")
print("Instances : ", end="")
for i in range(instance_count):
print(instances[i], end=" ")
print("")
print("Available : ", end="")
for i in range(instance_count):
print(availables[i], end=" ")
print("")
print("\n====== Allocation ====== ")
for i in range(process_count):
print("process{} : ".format(i), end="")
for j in range(instance_count):
print(allocations[i][j], end=" ")
print("")
print("\n====== Max ====== ")
for i in range(process_count):
print("process{} : ".format(i), end="")
for j in range(instance_count):
print(maxes[i][j], end=" ")
print("")
print("\n====== Need ======")
for i in range(process_count):
print("process{} : ".format(i), end="")
for j in range(instance_count):
print(needs[i][j], end=" ")
print("")
print("\n====== 가능한 Safety sequence 종류 ======")
print_safe_sequence(allocations, needs, availables, [])
|
cb5163b3b2e95e5dd417ab5cc51b4031e4665e7a
|
BreakZhu/nltk_start
|
/start05/class5_7.py
| 1,067 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
import nltk
# 如何确定一个词的分类
"""
形态学线索
ness 是一个后缀,与形容词结合产生一个名词,如 happy→happiness,ill→illness。因此,如果我们遇到的一个
以-ness 结尾的词,很可能是一个名词。同样的,-ment 是与一些动词结合产生一个名词的后缀,如 govern→government
和 establish→establishment一个动词的现在分词以-ing 结尾,表示正在进行的还没有结束的行动(如:falling,eating)
的意思。-ing 后缀也出现在从动词派生的名词中,如:the falling of the leaves(这被称为动名词)。
句法线索
另一个信息来源是一个词可能出现的典型的上下文语境。例如:假设我们已经确定了名词类。那么我们可以说,
英语形容词的句法标准是它可以立即出现在一个名词前,或紧跟在词 be 或 very 后。根据这些测试,near 应该被归类为形容词:
(2) a. the near window
b. The end is (very) near
"""
|
623f6218b656df8ef6480ea17321355fc2a53e16
|
TomGardoni/ExamPython
|
/Eval v3.py
| 744 | 3.5 | 4 |
from colorama import init
init()
from colorama import Fore, Back, Style
print("Bienvenue dans motus sans ami")
essais=4
chances=4
l=6*[0]
for i in range(len(l)):
l[i]=6*[0]
l[0][0]=1
print(l)
list = ["castor","cinema","cypres","citron","camion","webcam","ajoute","aligne","bronze","brutal"]
motadeviner = list [random.randmint (0,5)]
choice(list) = motadeviner = list(motadeviner.lower())
while plusdechances or mottrouve:
if len(essaimotlist) != len(motadeviner):
print("Vous devez entrer un mot de" , len(motadeviner), "lettres! Réessayez!")
if plusdechances:
print("Vous avez perdu, le mot etait: ",motadeviner )
if mottrouve:
print("Bravo vous avez trouvé le mot avec", essais-chances , "essais !")
input()
|
2296eaff433b8cf81cc7207108640b12ddc39ce3
|
NishiMaliya/Analyzer
|
/analyzer.py
| 1,035 | 3.5 | 4 |
import argparse
import requests
from lxml import html
def parse(link: str) -> str:
"""Function for extracting path to element"""
page = requests.get(link)
root = html.fromstring(page.text)
tree = root.getroottree()
element_path = root.xpath("//div[@id='page-wrapper']//a[contains(@class,'btn-success') "
"or contains(@class, 'test-link-ok')]")
for element in element_path:
return tree.getpath(element)
def write_to_file(file_name: str, path: str) -> None:
"""Function for writing exctracted path to the file"""
with open(f'{file_name}.txt', "w") as file:
file.write(str(path))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Parser")
parser.add_argument("-l", "--link", help="Input link")
parser.add_argument("-o", "--output", help="Output file")
args = parser.parse_args()
input_link = args.link
output_file = args.output
result = parse(str(input_link))
write_to_file(output_file, result)
|
d5eb5285fe5cc8b8fbb666fd9fe536dd8f45ad53
|
gschen/sctu-ds-2020
|
/1906101052-曾倩/day0310.py/test01.py
| 853 | 3.953125 | 4 |
class Student(object):
def __init__(self,name,age,score):
self.name=name
self.age=age
self.score=score
def personInfo(self):
print(("name:%s,age:%s,score:%s")%(self.name, self.age,self.score))
yi=Student("张三",20,'语文:92,数学:90,英语:90')
yi.personInfo()
class Student():
def __init__(self,name,age,chinese,math,english):
self.name=name
self.age=age
self.chinese=chinese
self.math=math
self.english=english
def get_name(self):
print(self.name)
def get_age(self):
print(self.age)
def get_course(self):
list1=[]
list1.append(self.chinese)
list1.append(self.math)
list1.append(self.english)
print(max(list1))
a=Student("bob",20,'67,56,34')
a.get_name()
a.get_age()
a.get_course()
|
bdc4696c30161f6f07776d66f87a649fdd4a02f7
|
C-SON-TC1028-001-2113/listas-tarea5-A01252527
|
/assignments/17MenoresANumero/src/exercise.py
| 263 | 3.671875 | 4 |
def main():
a = int(input(''))
aa = int(input(''))
aaa = a*aa
lista=[]
i=1
while i<=aaa:
i=i+1
aaaa = int(input(''))
if aaaa<10:
lista.append(aaaa)
print(lista)
if __name__=='__main__':
main()
|
5d107f5830efc12296b21b86f84b3616dbcd2512
|
mwhit74/interpreter
|
/rbi/inte3.py
| 4,141 | 3.984375 | 4 |
#Token types
#
#EOF (end-of-file) token is used to indicate that
#there is no more input left for lexical analysis
INTEGER, PLUS, MINUS, MULTI, DIV, EOF = ('INTEGER', 'PLUS', 'MINUS', 'MULTI',
'DIV', 'EOF')
class Token(object):
def __init__(self, type, value):
#token type: INTEGER, PLUS, MINUS, or EOF
self. type = type
#token value: non-negative integer value, '+', '-', '*', '/', or None
self.value = value
def __str__(self):
"""String representation of class.
Examples:
Token(INTEGER, 3)
Token(PLUS, '+')
"""
return 'Token({type}, {value})'.format(type=self.type,
value=repr(self.value))
def __repr__(self):
return self.__str__()
class Interpreter(object):
def __init__(self, text):
#client string input, e.g. 3+5
self.text = text
#self.pos is an index into self.text
self.pos = 0
self.current_token = None
self.current_char = self.text[self.pos]
def error(self):
raise Exception('Error parsing input')
def advance(self):
"""Advance the 'pos' pointer and set the 'current_char'"""
self.pos += 1
if self.pos > len(self.text) - 1:
self.current_char = None #EOF
else:
self.current_char = self.text[self.pos]
def skip_whitespace(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
result = ''
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()
return int(result)
def get_next_token(self):
"""Lexical analyzer (also known as scanner or tokenizer)
This method is reponsible for breaking a sentence apart into
tokens. On token at a time.
"""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
return Token(INTEGER, self.integer())
if self.current_char == '+':
self.advance()
return Token(PLUS, '+')
if self.current_char == '-':
self.advance()
return Token(MINUS, '-')
if self.current_char == '*':
self.advance()
return Token(MULTI, '*')
if self.current_char == '/':
self.advance()
return Token(DIV, '/')
self.error()
return Token(EOF,None)
def check_type(self, token_type):
#compare the current token type with token_type
#and if they match get the next token
#essentially type checking for the language
if self.current_token.type == token_type:
self.current_token = self.get_next_token()
else:
self.error()
def term(self):
token = self.current_token
self.check_type(INTEGER)
return token.value
def expr(self):
"""expr -> INTEGER PLUS INTEGER
expr -> INTEGER MINUS INTEGER"""
#set current token to first token taken from the input
self.current_token = self.get_next_token()
result = self.term()
while self.current_token.type in (PLUS, MINUS):
token = self.current_token
if token.type == PLUS:
self.check_type(PLUS)
result = result + self.term()
elif token.type == MINUS:
self.check_type(MINUS)
result = result - self.term()
return result
def main():
while True:
try:
text = raw_input('calc> ')
except EOFError:
break
if not text:
continue
interpreter = Interpreter(text)
result = interpreter.expr()
print(result)
if __name__ == "__main__":
main()
|
9cfd285e5d2ce31a169e523d1baff1c21db64581
|
maihan040/Python_Random_Scripts
|
/courseList.py
| 1,288 | 4.25 | 4 |
#!/usr/bin/python3
#
#module name: courseList.py
#
#purpose: determine the order of courses that need to be taken based on their prerequisites of them.
# The courses, along with their prerequisites will be passed a as a dictionary
#
#date created: 10/03/2019
#
#version: 1.0
#
#################################################################
# function definition #
#################################################################
def prerequisites(course):
#validation check
if courses == None:
print("No courses were passed")
#local variables
course_list = []
#iterate through the dicionary until there are no more classes left
#based on the prerequisites
for i in range(0, len(courses)):
print()
for k,v in courses.items():
if v == course_list:
course_list.append(k)
#print the order to take the courses
print("Courses should be taken in the following order: " + str(course_list))
#################################################################
# Main #
#################################################################
#local variable
courses = {
'csc400' : ['csc100', 'csc200', 'csc300'],
'csc300' : ['csc100', 'csc200'],
'csc200' : ['csc100'],
'csc100' : []
}
#call function to print the list in order
prerequisites(courses)
|
6f6e6df2f1784aedbacd777244d0e72fc02ec096
|
LuisGabrielZamora/python_first_steps
|
/02_functions/01_my_first_function.py
| 1,766 | 4.34375 | 4 |
# PRACTICE TITLE: Function Definition
# DESCRIPTION: Code structure that enable to execute an specific process
# NOTATION: def my_first_function():
# NOTES:
# 1. All the code that corresponds to the function has to be with tabulation
# 2. To execute the function we have to call it with the same "def" tabulation
# Definition to my function
def my_first_function():
print('Hello from my First Function')
# Function which receives arguments
def arguments_function(name, year):
print('')
print(f'My name is: {name} and this year is: {year}')
# Returns result
def add_arguments(a, b):
return a + b
# Default arguments with the data type to return
def default_minus_arguments(a=100, b=100) -> int:
return a - b
# Python consider a dynamic parameters that receives like a tuple
# IMPORTANT NOTE: For dynamic arguments in a function have to use with *
def name_list(*names):
for name in names:
print(name)
def add_all_arguments(*args: int) -> int:
total = 0
for arg in args:
total = total + arg
return total
def multiply_all_arguments(*args: int) -> int:
total = 1
for arg in args:
total = total * arg
return total
# Call the function
my_first_function()
# Call the function with parameters
arguments_function('Gabriel Zamora', 2030)
# Add function
print('')
print(add_arguments(10, 96))
# Minus function
print('')
print(default_minus_arguments(120))
print(default_minus_arguments())
# Function with dynamic parameters
print('')
name_list('Juan', 'Karla', 'Maria', 'Ernesto', 'Javier')
# Function with dynamic add parameters
print('')
print(f'Sum total is: {add_all_arguments(10, 15, 20, 15, 202, 4, 5)}')
print(f'Multiply total is: {multiply_all_arguments(10, 15, 20, 15, 202, 4, 5)}')
|
0f795408aaf68709488def037ec03aa4836df30d
|
urvib3/ccc-exercises
|
/herding.py
| 1,563 | 3.515625 | 4 |
def onespace(x,y,z):
if(x+2 == y):
return True
elif(x+2 == z):
return True
elif(y+2 == x):
return True
elif(y+2 == z):
return True
elif(z+2 == x):
return True
elif(z+2 == y):
return True
def maxmoves(nums):
nums.sort()
firstgap = nums[1] - nums[0]
secondgap = nums[2] - nums[1]
return max(firstgap, secondgap)-1
def main():
try:
filein = open("herding.in", "r")
file = open("herding.out", "w")
print("files opened")
# initialize nums with positions of cows
nums = filein.readline().split(' ')
nums = [int(i) for i in nums]
print("nums: ", nums)
# if all positions are consecutive, output min = 0, max = 0
print("case 1: ", nums[0]+1 == nums[1] and nums[1]+1 == nums[2])
print("case 2: ", nums[0]-1 == nums[1] and nums[1]-1 == nums[2])
if((nums[0]+1 == nums[1] and nums[1]+1 == nums[2]) or (nums[0]-1 == nums[1] and nums[1]-1 == nums[2])):
file.write("0\n0")
return
print("first if loop good")
# elif 2 positions only have one space
set = onespace(nums[0], nums[1], nums[2])
if(set):
file.write("1\n")
# if the other gap is also 1 space, max = 1
print("second if loop good")
else:
file.write("2\n")
file.write(str(maxmoves(nums)))
file.close()
except:
print("exception")
if __name__=="__main__":
main()
|
65492a228dd46eed5bafc725dae2bdb07fb2baaf
|
nuno-21902803/pw-python
|
/pw-python-03/exercicio_3/main.py
| 667 | 3.6875 | 4 |
import os
def pede_pasta():
while True:
try:
nome = input("Introduza o caminho para pasta: ")
if os.path.isdir(nome):
return os.path.realpath(nome)
except IOError:
print("Pasta não existente")
def calcula_tamanho_pasta(pasta):
if os.path.isfile(pasta):
return os.path.getsize(pasta)
sizes = [calcula_tamanho_pasta(os.path.join(pasta, file)) for file in os.listdir(pasta)]
return sum(sizes)
def main():
nome = pede_pasta()
size = calcula_tamanho_pasta(nome)
print(f"Tamanho da pasta: {9.537*0.00000010 * size}MB")
if __name__ == "__main__":
main()
|
e32e0355e5083c19e78c6648192bb82e8d3ab6fe
|
bainco/bainco.github.io
|
/course-files/tutorials/tutorial05/warmup/b_while_termination_condition.py
| 511 | 4.03125 | 4 |
import time
'''
A few things to note here:
1. A counter is initialized before the while loop begins.
2. The counter is updated each time the code block within the while
loop executes.
3. If counter is less than 5, the block executes, otherwise, the
while loop terminates.
4. The condition is always checked before each iteration.
'''
counter = 0
while counter < 5:
print('Hello! How are you doing today?')
time.sleep(0.5)
counter += 1
print('Program terminated')
|
e62f2c08aa364a46e29d6bbf702281c4fe70122c
|
perfect-song/LeetCode
|
/剑指66/二维数组查找.py
| 391 | 3.609375 | 4 |
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
m, n = len(array), 0
m -= 1
while (m >= 0 and n < len(array[0])):
if array[m][n] == target:
return True
elif array[m][n] > target:
m -= 1
else:
n += 1
return False
|
de2696aff3a6fd645c769228e2aee6db27aa8de2
|
L200180034/praktikum-ASD
|
/MODUL 5/No 1.py
| 1,033 | 3.5 | 4 |
class Mahasiswa(object):
def __init__(self,nama,nim,kota,us):
self.nama = nama
self.nim = nim
self.kotaTinggal = kota
self.uangSaku = us
class MhsTIF (Mahasiswa):
def katakanPy(self):
print('Python is cool.')
listan = [MhsTIF ('Vara',34,'Surakarta', 255000),
MhsTIF('Aisyah',42,'Wonosobo', 255000),
MhsTIF('Goe',15,'Yogyakarta', 155000),
MhsTIF('Septia',26,'Semarang', 175000),
MhsTIF('Waku',18,'Lembang', 200000),
MhsTIF('Fiita',31,'Magelang', 980000),
MhsTIF('Septin',10,'Tegal', 265000),
MhsTIF('Iqbal',45,'Kutoarjo', 185000),
MhsTIF('Justin',11,'Bekasi', 245000),
MhsTIF('Febrian',21,'Depok', 235000),
MhsTIF('Rio',18,'Bogor', 195000)]
#1
def urutkannim(l):
n = len(l)
for i in range (n -1) :
for k in range (n-i-1) :
if l[k].nim > l[k+1].nim :
swap(l,k,k+1)
def checknim (l):
for i in l :
print (i.nim)
def swap (a, p, q) :
tmp = a[p]
a[p] = a[q]
a[q] = tmp
|
d570bcea6b0fd5ad4447c90973c2776e5a9eddfe
|
IriW/rock_paper_scissors_v2
|
/main.py
| 980 | 3.96875 | 4 |
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
imgs = [rock, paper, scissors]
comp_choice = random.randint(0, 2)
usr_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
if usr_choice < 0 or usr_choice >=3:
print("You provided wrong value. Bye")
elif usr_choice >= 0 or usr_choice <=2:
print(f"You chose: {imgs[usr_choice]}\nComputer chose: {imgs[comp_choice]}")
choices_matrix = [["It's a draw.", "You lose!", "You win!"],["You win", "It's a draw.", "You lost"],["You lost", "You win", "It's a draw"]]
print(choices_matrix[usr_choice][comp_choice])
else:
print("How did you even get here?")
|
baacbb690b743547203ce29e62012c8db4801a14
|
Keegan-Ross/it-python
|
/Rock, Paper, Scissors.py
| 1,471 | 4.09375 | 4 |
import random
from banner import banner
banner("ROCK, PAPER, SCISSORS", "Keegan Ross")
print("We are going to play a game of Rock, Paper, Scissors. The first to win two times out of 3 rounds is the winner.")
cpu_score = 0
player_score = 0
while player_score < 2 and cpu_score < 2:
print(f"SCORE: Player: {player_score} Computer: {cpu_score}")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
players_choice = int(input("What is your choice? "))
cpu_choice = random.randint(1,3)
if players_choice == 1:
if cpu_choice == 1:
print("Tie")
if cpu_choice == 2:
print("Lose")
cpu_score += 1
if cpu_choice == 3:
print("Win")
player_score += 1
if players_choice == 2:
if cpu_choice == 1:
print("Win")
if cpu_choice == 2:
print("Tie")
cpu_score += 1
if cpu_choice == 3:
print("Lose")
player_score += 1
if players_choice == 3:
if cpu_choice == 1:
print("Lose")
if cpu_choice == 2:
print("Win")
cpu_score += 1
if cpu_choice == 3:
print("Tie")
player_score += 1
if player_score == 2:
print("Congratulations you have defeated the computer! Your robotic overlords tremble in fear!")
if cpu_score ==2:
print("Sorry for your loss, but the computer reigns superior!")
|
9d02a0916fd49a09cbf01475d04730514eda231d
|
sadieh0ugh/12-balls-problem
|
/balls.py
| 2,043 | 3.640625 | 4 |
import random
balls =[1,1,1,1,1,1,1,1,1,1,1]
place = random.randint(0,11)
num02 = (random.randint(0,1))*2
balls.insert((place),(num02))
print(balls)
ball_label=[["ball 1","normal"],["ball 2","normal"],["ball 3","normal"],["ball 4","normal"],["ball 5","normal"],["ball 6","normal"],
["ball 7","normal"],["ball 8","normal"],["ball 9","normal"],["ball 10","normal"],["ball 11","normal"],["ball 12","normal"]]
#passed through fucntion compare1 as n
def compare1(n):
add1 = balls[0]+balls[1]+balls[2]+balls[3]
add2 = balls[4]+balls[5]+balls[6]+balls[7]
if add1 == add2:
for i in range(8,12):
n[i][1] = "different" # more efficient
compare2(ball_label)
elif add
def compare2(n):
if balls[8]+balls[9]+balls[10] > balls[0]+balls[1]+balls[2]:
n[8][1], n[9][1], n[10][1] = "heavier","heavier","heavier"
n[11][1] = "normal"
if balls[8] > balls[9]:
n[9][1], n[10][1] = "normal","normal"
if balls[8] < balls[9]:
n[8][1], n[10][1] = "normal","normal"
elif balls[8] == balls[9]:
n[8][1], n[9][1] = "normal","normal"
elif balls[8]+balls[9]+balls[10] < balls[0]+balls[1]+balls[2]:
n[8][1], n[9][1], n[10][1] = "lighter","lighter","lighter"
n[11][1] = "normal"
if balls[8] > balls[9]:
n[8][1], n[10][1] = "normal","normal"
if balls[8] < balls[9]:
n[9][1], n[10][1] = "normal","normal"
elif balls[8] == balls[9]:
n[8][1], n[9][1] = "normal","normal"
elif balls[8]+balls[9]+balls[10] == balls[0]+balls[1]+balls[2]:
n[8][1], n[9][1], n[10][1] = "normal","normal","normal"
if balls[0] > balls[11]:
n[11][1] = "lighter"
elif balls[0] < balls[11]:
n[11][1] = "heavier"
compare1(ball_label)
for i in ball_label:
if i[1] == "heavier" or i[1] == "lighter":
print(i[0],"is",i[1])
|
dc7ac81da2551298e74f1a073ec101c7963eb28a
|
super-penguin/Data_Projects
|
/Test_Perceptual_Phenomenon/stroop.py
| 5,308 | 3.53125 | 4 |
# -*- coding: utf-8 -*-
"""
P1: Test a Perceptual Phenomenon
Stroop data analysis and visualization in python
04/20/16
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
##########################################################################
## 1. Read stroop dataset into a dataframe:data.
data = pd.read_csv ('stroopdata.csv', sep =',', header = 0)
##########################################################################
## 2. Descriptive statistics and statistical test
## 2.1 Save the descriptive statistics into a dataframe: D_data.
D_data = data.describe()
D_data.to_csv('Descriptive_stat.csv', sep=',')
t, p = stats.ttest_rel(data['Congruent'],data['Incongruent'])
print('t-statistic = %6.3f\np-value = %6.4f' % (t,p),sep=',')
if p <0.05:
print('The null hypothesis is rejected;')
print('Conclusion: the average time used to name the colors of incongruent words is significant longer than the congruent words.')
else:
print('The null hypothesis is not rejected;')
print('Conclusion: the average time used to name the colors of incongruent words is the same as the congruent words.')
##########################################################################
## 3. Visualization of the dataset.
# These are the "Tableau 10" colors as RGB. (Modified yellow)
tableau10 = [(114,158,206), (255,158,74), (103,191,92), (237,102,93),
(173,139,201), (168,120,110), (237,151,202), (162,162,162),
(255,221,113), (109,204,218)]
for i in range(len(tableau10)):
r, g, b = tableau10[i]
tableau10[i] = (r / 255., g / 255., b / 255.)
##########################################################################
## 3.1. Boxplot
##########################################################################
## combine dataset into a list
data_to_plot = [data['Congruent'],data['Incongruent']]
## plot
fig1 = plt.figure(1, figsize=(12, 9))
ax1 = fig1.add_subplot(111)
bp = ax1.boxplot(data_to_plot)
plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
plt.setp(bp['boxes'], color=tableau10[7])
# Modify the color of box plot
bp = ax1.boxplot(data_to_plot, patch_artist=True)
bp['boxes'][0].set(facecolor =tableau10[0])
bp['boxes'][1].set(facecolor =tableau10[3])
for whisker in bp['whiskers']:
whisker.set(color=tableau10[7], linewidth=2)
for cap in bp['caps']:
cap.set(color=tableau10[7], linewidth=2)
for median in bp['medians']:
median.set(color=tableau10[8], linewidth=2)
## add labels
ax1.set_xticklabels(['Congruent', 'Incongruent'],fontsize=16)
ax1.get_xaxis().tick_bottom()
ax1.get_yaxis().tick_left()
ax1.spines["top"].set_visible(False)
ax1.spines["right"].set_visible(False)
ax1.set_ylabel('Time(ms)',fontsize=16)
ax1.set_title('Comparison of Congruent & Incongruent',fontsize=22)
fig1.savefig('boxplot.png', bbox_inches='tight')
##########################################################################
## 3.2. Histogram
##########################################################################
fig2= plt.figure(2,figsize=(12, 9))
bins = np.linspace(0, 40, 21)
## histogram for Congruent
ax21 = fig2.add_subplot(2,1,1)
ax21.spines["top"].set_visible(False)
ax21.spines["right"].set_visible(False)
ax21.get_xaxis().tick_bottom()
ax21.get_yaxis().tick_left()
ax21.hist(data['Congruent'],bins,color=tableau10[0],alpha=0.5)
ax21.set_ylabel('Count',fontsize=14)
ax21.set_xlabel('Time (ms) to name the colors',fontsize=14)
ax21.legend(fontsize=16)
## histogram for Incongruent
ax22 = fig2.add_subplot(2,1,2)
ax22.spines["top"].set_visible(False)
ax22.spines["right"].set_visible(False)
ax22.get_xaxis().tick_bottom()
ax22.get_yaxis().tick_left()
ax22.hist(data['Incongruent'],bins,color=tableau10[3],alpha=0.5)
ax22.set_ylabel('Count',fontsize=14)
ax22.set_xlabel('Time (ms) to name the colors',fontsize=14)
ax22.legend(fontsize=16)
# Save the figure
fig2.savefig('histogram.png', bbox_inches='tight')
##########################################################################
## 3.3. Bar figure
##########################################################################
mu_Congruent, sig_Congruent = np.mean(data['Congruent']), np.std(data['Congruent'])
mu_Incongruent, sig_Incongruent = np.mean(data['Incongruent']), np.std(data['Incongruent'])
width = 0.2
fig3 = plt.figure(3,figsize=(12, 9))
ax3 = fig3.add_subplot(111)
bar1 = ax3.bar(0.2, mu_Congruent, width, color =tableau10[0],alpha=0.5)
err_bar1 = ax3.errorbar(0.3, mu_Congruent,yerr= sig_Congruent,capsize =20, markeredgewidth =2, elinewidth =2, ecolor=tableau10[7])
bar2 = ax3.bar(0.6, mu_Incongruent, width, color =tableau10[3], alpha=0.5)
err_bar2 = ax3.errorbar(0.7,mu_Incongruent, yerr=sig_Incongruent,capsize =20,markeredgewidth =2, elinewidth =2, ecolor=tableau10[7] )
ax3.set_ylabel('Time(ms)',fontsize=16)
ax3.set_xlabel('Conditions',fontsize=16)
ax3.set_title('Comparison of Congruent & Incongruent',fontsize=22)
ax3.set_xlim([0,1])
ax3.spines["top"].set_visible(False)
ax3.spines["right"].set_visible(False)
plt.setp(ax3.get_xticklabels(), visible=False)
ax3.get_xaxis().tick_bottom()
ax3.get_yaxis().tick_left()
ax3.legend((bar1[0], bar2[0]), ('Congruent', 'Incongruent'),bbox_to_anchor=(1, 0.9), loc=2, borderaxespad=0.,fontsize=16)
fig3.savefig('bar_graph.png', bbox_inches='tight')
|
13e77f023c93620347735b3d00537b911f7cf1e5
|
kns94/algorithms_practice
|
/powerofthree.py
| 613 | 3.625 | 4 |
import sys
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
if n == 1:
return True
if n < 0:
return False
if (math.log10(n)/math.log10(3)).is_integer():
return True
return False
#largest = pow(3,20)
#if largest % n == 0:
# return True
#return False
if __name__ == "__main__":
print Solution().isPowerOfThree(int(sys.argv[1]))
|
b57bab273d091434ed43a76c04a3a8c3fcbedb62
|
boknowswiki/mytraning
|
/lintcode/python/0085_insert_node_in_a_binary_search_tree.py
| 1,722 | 4.40625 | 4 |
#!/usr/bin/python -t
# iteration way
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if root == None:
return node
cur = root
while cur != node:
if cur.val < node.val:
if cur.right == None:
cur.right = node
cur = cur.right
else:
if cur.left == None:
cur.left = node
cur = cur.left
return root
# dfs, traversal way
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if root == None:
return node
if node.val < root.val:
if root.left:
self.insertNode(root.left, node)
else:
root.left = node
else:
if root.right:
self.insertNode(root.right, node)
else:
root.right = node
return root
|
0496105f3d578bf727c4e1ebc01d6f94fadd73e8
|
jmvazquezl/programacion
|
/Prácticas Phyton/P5/P5E11 - PROGRAMA QUE PIDA UN NÚMERO E IMPRIMA SUS DIVISORES.py
| 249 | 3.828125 | 4 |
# JOSE MANUEL - P5E11 - PROGRAMA QUE PIDA UN NÚMERO E IMPRIMA SUS DIVISORES
num = int(input('Dame un número: '))
print('Los divisores de', num, 'son', end=': ')
for i in range(num):
i = i + 1
if (num % i == 0):
print(i, '', end='')
|
533b524df2134a52a702cfa92c58a8825505ca74
|
dubian98/Cursos-Python
|
/100 ejercicios/ejercicio10.py
| 195 | 3.65625 | 4 |
def sum_pos_divisor(num):
sum=0
for i in range(1,num):
if num%i == 0:
sum+=i
if sum==num:
n=True
else:
n=False
return n
sum_pos_sivisor(28)
|
b67c2c6499f38c88511594c1c7aae8d813ea84b8
|
ansoncoding/CTCI
|
/Python/01_Strings_Arrays/IsPermutation.py
| 1,427 | 4 | 4 |
#1.2 is one string a permutation of another string?
def is_permutation(str1, str2):
if len(str1) != len(str2):
return False
counts = {}
for i in range(0, len(str1)):
if str1[i] not in counts:
counts[str1[i]] = 1
#print(counts)
else:
counts[str1[i]] = counts[str1[i]] + 1
#print(counts)
for i in range(0, len(str1)):
if ((str2[i] not in counts) or (counts[str2[i]] <= 0)):
#print(counts)
return False
else:
counts[str2[i]] = counts[str2[i]] - 1
#print(counts)
return True
# use sorting to save space
def is_permutation_2(str1, str2):
if len(str1) != len(str2):
return False
str1_sorted = sorted(str1)
str2_sorted = sorted(str2)
for i in range(0, len(str1)):
if (str1_sorted[i] != str2_sorted[i]):
return False
return True
# instead of dictionary use list
# this will save some space
# assume ascii charset of 128
def is_permutation_3(str1, str2):
if len(str1) != len(str2):
return False
counts = [0]*128
for i in range(0, len(str1)):
index = ord(str1[i])
#print(index)
counts[index] += 1
for i in range(0, len(str2)):
index = ord(str2[i])
#print(index)
counts[index] -= 1
if counts[index] < 0:
return False
return True
|
789ae00a7540e9d1894b966d11a0f1e0e4065f41
|
rAndrewNichol/random
|
/Python/hackerrank/stats2.py
| 639 | 3.515625 | 4 |
# Weighted Mean
N = int(input())
values = input().split()
weights = input().split()
weighted_values = []
for i in range(N):
values[i] = int(values[i])
weights[i] = int(weights[i])
weighted_values.append(values[i]*weights[i])
weighted_mean = round(sum(weighted_values)/sum(weights),1)
print(weighted_mean)
# Input shortcut(works in executable and not in console)
# X = list(map(int, input().split()))
# short method:
n = int(input())
nums = [int(x) for x in input().split()]
weight = [int(x) for x in input().split()]
print (round(float(sum([nums[i]*weight[i] for i in range(n)]))/sum(weight), 1))
|
cfd7b1f6ec51e586c0e58bcd37c2361b8ab95379
|
FarzamHejaziK/DyLoc
|
/KNNCNN/Indoor/MakeADPgrid.py
| 5,281 | 3.578125 | 4 |
import numpy as np
# Define x and y grid size. Must match xnum and ynum in "Train.py"
xnum = 18
ynum = 55
# Function calculates class of each ADP based on the loc data
# Inputs: raw validation data (ADP, location), and size of (x,y) grid
# t - handles name of location dataset. Can be removed if name of location column is known
# Outputs: (ADP, class) pairs and new location based on classes (similar to get_data in tarin.py)
def get_valid_data(data,xnum,ynum,t):
# Calculate total number of classes
num_classes = xnum*ynum
adp = data['ADP']
print('adp shape ',adp.shape)
# Get ADP and (x,y) location from dataset
M = np.reshape(adp,(-1,32,32))
if t ==0 :
loc = data['Location']
elif t ==1:
loc = data['Loc']
x = loc[:,0]
y = loc[:,1]
# Create placeholders for class (grid) and new (X,Y) coordiantes which are at the center of each grid.
# Example: If the user is in the mth segment in x-direaction and nth segment in y-direction, the new coordinates are (m,n) and the sample belongs to class c = m*n.
cnew = np.zeros((len(loc),num_classes))
c = np.zeros(len(loc))
xnew = np.zeros(len(x))
ynew = np.zeros(len(y))
# Calculate step size based on the grid
xmax = max(x)
xmin = min(x)
xstep = (xmax-xmin)/xnum
ymax = max(y)
ymin = min(y)
ystep = (ymax-ymin)/ynum
# Convert x coordinate to grid segment in x
for i in range(len(x)):
for j in range(1,xnum+1):
low = xmin + (j-1)*xstep
high = xmin + j * xstep
if(x[i]>=low and x[i]<high):
xnew[i] = j
if(x[i] == xmax):
xnew[i] = xnum
if (xnew[i] == 0):
print(x[i])
print(xmax)
print(xmin)
sys.exit()
# Convert y coordinate to grid segment in y
for i in range(len(y)):
for j in range(1,ynum+1):
low = ymin + (j-1)*ystep
high = ymin + (j*ystep)
if(y[i]>=low and y[i]<high):
ynew[i] = j
if(y[i] == ymax):
ynew[i] = ynum
if (ynew[i] == 0):
print(y[i])
print(ymax)
print(ymin)
sys.exit()
# Assign classes to dataset based on grid starting with grid (1,1) assigned to class c=1
# and grid (m,n) assigned to class c = m*n.
for i in range(len(loc)):
c[i] = (xnew[i]-1)+xnum*(ynew[i]-1)
c = np.reshape(c,(len(c),1))
# M - ADP
# c - class
# new location (x,y) based on grid
return loc,c, M
# For any grid, collect and group all ADP samples from the training set that belong to that grid
# This means that by calling this function for for each grid there will be a collection of ADPs that belong to that grid.
# This collection will later be used for KNN alogirthm to search within.
# Input:
# subclass - that class for which you want to collect all the ADPs. If you want all the ADPs in the training data beloning to class m, then subclass = m.
# M - All ADPs in the training data
# c - total number of class
# (x,y)- loc from training data for all ADPs
# Outputs:
# Mnew - All ADPs beloning to the selected subclass m
# c1 - class m
# (xlocnew,ylocnew) - new (x,y) location coordinates based on the grid
def get_sub(subclass,M,c,x,y):
xnum = 18
ynum = 55
n = 0
for i in range(len(c)):
if (c[i]==subclass):
n+=1
M = np.reshape(M,[-1,64,64])
Mnew = np.zeros([n,64,64])
xlocnew = np.zeros(n)
ylocnew = np.zeros(n)
j=0
# Search for all (ADP, loc) beloning to the subclass
for i in range((len(c))):
if (c[i]==subclass):
Mnew[j,:,:]=M[i,:,:]
xlocnew[j] = x[i]
ylocnew[j] = y[i]
j+=1
c1 = np.zeros(n)
xnew = np.zeros(n)
ynew = np.zeros(n)
xmax = max(xlocnew)
xmin = min(xlocnew)
xstep = (xmax-xmin)/xnum
ymax = max(ylocnew)
ymin = min(ylocnew)
ystep = (ymax-ymin)/ynum
# Compute new x and y location based on the grid
for i in range(n):
for j in range(1,xnum+1):
low = xmin + (j-1)*xstep
high = xmin + j * xstep
if(xlocnew[i]>=low and x[i]<high):
xnew[i] = j
if(xlocnew[i] == xmax):
xnew[i] =xnum
for i in range(n):
for j in range(1,ynum+1):
low = ymin + (j-1)*ystep
high = ymin + (j*ystep)
if(ylocnew[i]>=low and ylocnew[i]<high):
ynew[i] = j
if(y[i] == ymax):
ynew[i] = ynum
#Compute class based on grid
for i in range(len(c1)):
c1[i] = (xnew[i]-1)+xnum*(ynew[i]-1)
c1 = np.reshape(c1,(n,1))
# Mnew -ADP
# c1- class
#xlocnew and ylocnew are x and y coordinates
return Mnew, c1,xlocnew,ylocnew
# Loads Train Dataset
data_path1 ='Data/TrainDCNNI1.npz'
data1 = np.load(data_path1)
# Takes the dataset and grid size as input and outputs ADP, class, and location (x,y)
loc_t, c_t, ADP_t= get_valid_data(data1,xnum,ynum,1)
num_classes = xnum*ynum
x_loc = loc_t[:,0]
y_loc = loc_t[:,1]
for sub in range(num_classes):
# For every class on the grid it creates a dataset of (ADP, class, location)
train_ADP, train_c, xtrain, ytrain = get_sub(sub,ADP_t,c_t,x_loc,y_loc)
np.save('ADP/ADP'+str(sub),train_ADP)
np.save('ADP/class'+str(sub),train_c)
np.save('ADP/xtrain'+str(sub),xtrain)
np.save('ADP/ytrain'+str(sub),ytrain)
|
692073825a339d2aa4b412bd4a18c61a873919b6
|
dannyhollman/holbertonschool-higher_level_programming
|
/0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py
| 3,157 | 3.5 | 4 |
#!/usr/bin/python3
"""unittest for Rectangle"""
import unittest
import pep8
from models.rectangle import Rectangle
class TestRectangle(unittest.TestCase):
"""class to test Rectangle"""
def test_pep8(self):
"""tests PEP8 format"""
pep8style = pep8.StyleGuide(quiet=True)
result = pep8style.check_files(['models/rectangle.py'])
self.assertEqual(result.total_errors, 0, "Found code style errors (and warnings).")
def test_rec(self):
"""test rectangle class"""
test = Rectangle(10, 2)
self.assertEqual(test.width, 10)
self.assertEqual(test.height, 2)
def test_rec_id(self):
"""test rectangle id"""
test = Rectangle(10, 2, 1, 1, 10)
self.assertEqual(test.id, 10)
def test_rec_area(self):
"""test rectangle area"""
test = Rectangle(10, 2)
self.assertEqual(test.area(), 20)
def test_rec_set_width(self):
"""test setting width"""
test = Rectangle(10, 2)
test.width = 5
self.assertEqual(test.width, 5)
def test_rec_set_height(self):
"""test setting height"""
test = Rectangle(10, 2)
test.height = 5
self.assertEqual(test.height, 5)
def test_rec_set_x(self):
"""test setting x"""
test = Rectangle(10, 2)
test.x = 5
self.assertEqual(test.x, 5)
def test_rec_set_y(self):
"""test setting y"""
test = Rectangle(10, 2)
test.y = 5
self.assertEqual(test.y, 5)
def test_rec_width_type(self):
"""test width with wrong type"""
test = Rectangle(10, 2)
with self.assertRaises(TypeError):
test.width = "10"
def test_rec_height_type(self):
"""test height with wrong type"""
test = Rectangle(10, 2)
with self.assertRaises(TypeError):
test.width = "2"
def test_rec_x_type(self):
"""test x with wrong type"""
test = Rectangle(10, 2)
with self.assertRaises(TypeError):
test.x = "10"
def test_rec_y_type(self):
"""test y with wrong type"""
test = Rectangle(10, 2)
with self.assertRaises(TypeError):
test.y = "10"
def test_rec_width_value(self):
"""test width with wrong value"""
test = Rectangle(10, 2)
with self.assertRaises(ValueError):
test.width = 0
def test_rec_height_value(self):
"""test height with wrong value"""
test = Rectangle(10, 2)
with self.assertRaises(ValueError):
test.height = 0
def test_rec_x_value(self):
"""test x with wrong value"""
test = Rectangle(10, 2)
with self.assertRaises(ValueError):
test.x = -1
def test_rec_y_value(self):
"""test y with wrong value"""
test = Rectangle(10, 2)
with self.assertRaises(ValueError):
test.y = -1
def test_rec_to_dic(self):
"""test to_dictionary function"""
test = Rectangle(10, 2, 1, 1, 1)
self.assertEqual(test.to_dictionary(), {'width': 10, 'height': 2, 'x': 1, 'y': 1, 'id': 1})
|
507ca68d0a97543a429dc3d53116a52d79d7ad24
|
sindhu819/Array-2
|
/Problem-31.py
| 731 | 4.09375 | 4 |
# Finding minimum and maximum element in an array
# time complexity =O(N)
#space complexity =O(1)
# Approach : we compare two elements in an array then find the max and min element between and simultaneously update the max and min values.
def min_max(nums):
min_num=nums[0]
max_num=nums[0]
n=len(nums)
for i in range(0,n,2):
if i==n-1:
max_num=max(max_num,nums[i])
min_num=min(min_num,nums[i])
else:
if nums[i]>nums[i+1]:
max_num=max(max_num,nums[i])
min_num=min(min_num,nums[i+1])
else:
max_num=max(max_num,nums[i+1])
min_num=min(min_num,nums[i])
return ( [min_num,max_num])
|
728d75b7e5c2e70da464a8c8d5645a5fd77dd319
|
ndjenkins85/Code
|
/Frisbee Golf/Hole.py
| 1,140 | 3.5 | 4 |
from Utilities import show_pic
from Wind import *
class Hole:
def __init__(self):
self.zones = []
self.starting_position = (0.0, 0.0)
self.goal_position = (0.0, 0.0)
self.goal_zone = []
self.name = ""
self.number = 0
self.par = 0
self.wind = Wind()
def is_in_goal(self, the_frisbee_coordinate):
for zone in self.goal_zone:
if zone.has_coord(the_frisbee_coordinate):
return True
return False
def get_current_zone(self, the_frisbee_coordinate):
for zone in self.zones:
if zone.has_coord(the_frisbee_coordinate):
return zone
return None
# gives tour of the hole, says wind, player says something
def tour(self):
print("Next hole is hole number " + str(self.number) + ", " + self.name + ". It is par " + str(self.par) + ".")
raw_input("Press enter to see a tour of the hole: ")
for zone in self.zones:
show_pic(zone.picture)
# time.sleep(0.6)
show_pic(self.zones[0].picture)
print(self.wind.to_string())
|
aae67bc984f347a23394cba0dd74c8dd272c57c0
|
yukijuki/Statistics
|
/test.py
| 95 | 3.609375 | 4 |
arr = [2,4,6,7,8]
sum = 0
i = 0
while(i < 5):
sum = sum + arr[i]
i = i+1
print(sum)
|
0c793c93c551048e0fbd38abbed63122d8958c8a
|
Jribbit/GenCyber-2016
|
/hex64.py
| 1,269 | 3.953125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 21 09:08:22 2016
Cryptopals Set 1 Challenge 1
This program converts a hexadecimal string into base64.
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 19 12:54:08 2016
@author: student
"""
def hex64(string):
""" Converts hex string to binary string """
num = str(bin(int(string, 16)))
num = num.replace("b", "")
# print(num)
""" Makes string evenly divisible by 6 """
while not((len(num) - 2) % 6 == 0):
num = num + "0"
for x in range(0, len(num) - 2, 6):
""" Each new character in string will be made up of 3 bits """
index = num[x:x+6]
# print(index, end = " ")
""" Converts binary strings to decimal number"""
index = int(index, 2)
# print(index, end = " ")
""" Decides what character the integer will be """
if index <= 25:
index = chr(index + 65)
elif index <= 52:
index = chr(index + 71)
elif index <= 61:
index = str(index - 52)
elif index == 62:
index = "+"
else:
index = "/"
print(index, end = "")
#hex64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d")
|
a5e9f3cb25c2bcc948f24db3ae277676d2170d40
|
RaduMatees/Python
|
/Algorithms/ghicire.py
| 414 | 3.796875 | 4 |
"""Ghicirea unui numar generat aleator intre 1 si 1000"""
from random import randint
numar = randint(1,1000)
ghici = int(input("Introduceti un numar intreg "))
contor = 1
while ghici != numar:
if ghici > numar: print("Numarul tau este mai mare ")
else: print("Numarul tau este mai mic ")
ghici = int(input("Introduceti alt numar "))
contor += 1
print ("Ati ghicit numarul din ",contor, "incercari")
|
f7e17cda5e487615c7ab9c88a5e2796feb8f0d5d
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/python/sum-of-multiples/4b069fd846384561ad59a168d2253577.py
| 219 | 3.734375 | 4 |
def sum_of_multiples(value, bases = None):
if bases is None:
bases = [3, 5]
while 0 in bases:
bases.remove(0)
return sum(set([i * b for b in bases for i in range(1, round(value / b) + 1) if i * b < value]))
|
41a869c8e930a3cf526a9760ca2197619b948f01
|
Monisha1892/Practice_Problems
|
/car game.py
| 2,381 | 4.34375 | 4 |
print("""Welcome to the car game.
Type commands to start and stop the car.
List of commands will be available when you type help.
Enjoy the game.""")
command = input(">")
while command != 'quit':
if command == 'help':
print("""start - to start the car
stop - to stop the car
quit - to exit""")
command = input(">")
elif command == 'start':
print("car started.....ready to go")
command = input(">")
elif command == 'stop':
print("car stopped")
command = input(">")
else:
print("i dont understand that.....")
command = input(">")
else:
print("game ended. thanks for playing")
# print("""Welcome to the car game.
# Type commands to start and stop the car.
# List of commands will be available when you type help.
# Enjoy the game.""")
#
# def game_function(command):
# while command != 'quit':
# if command == 'help':
# print("""start - to start the car
# stop - to stop the car
# quit - to exit""")
# command = input(">")
# game_function(command)
# elif command == 'start':
# print("car started.....ready to go")
# command = input(">")
# game_function(command)
# elif command == 'stop':
# print("car stopped")
# command = input(">")
# game_function(command)
# else:
# print("game ended. thanks for playing")
#
# command = input(">")
# game_function(command)
# print("""Welcome to the car game.
# Type commands to start and stop the car.
# List of commands will be available when you type help.
# Enjoy the game.""")
#
# def game_function(command):
# while command != 'quit':
# if command == 'help':
# print("""start - to start the car
# stop - to stop the car
# quit - to exit""")
# command = input(">")
# elif command == 'start':
# print("car started.....ready to go")
# command = input(">")
# elif command == 'stop':
# print("car stopped")
# command = input(">")
# else:
# print("i dont understand that....")
# command = input(">")
# else:
# print("game ended. thanks for playing")
#
# command = input(">")
# game_function(command)
|
8a883ac2bafa871568cba967278310730742b04e
|
OliverMD/TPOP
|
/theory/hw1.py
| 898 | 3.5625 | 4 |
def gcd(a,b):
#gdc(int,int) -> int
#Recursive implementation of GCD
if a > b:
c = a
a = b
b = c
def internal(a,b):
if a % b == 0:
return b
return internal(b,a%b)
return internal(a,b)
def altGcd(a,b):
#altGcd(int,int) -> int
#A more literal interpretation of
#the algorithm in the work sheet.
while True:
r = a % b
if r == 0:
return b
a = b
b = r
def divide(a,b):
#divide(int,int) -> (quotient int, remainder int)
#Divides a by b and returns quotient and remainder.
#performed 200,000 divisions of 60034 by 234 in 2.947s
#compared with 0.014s for the normal python divide.
#Tested using cProfile from command line.
q = 0
while a - b >= 0:
a = a - b
q += 1
return q, a
for i in range(0,200000):
60034/234
|
3fcdc9d71501c9d51166795ac3227d4ce3dd737e
|
jeremiedecock/snippets
|
/python/opencv/opencv_2/drawing_functions/drawing_functions.py
| 2,737 | 3.96875 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
"""
OpenCV - Drawing functions: draw lines, circles, rectangles, ellipses and text
Required: opencv library (Debian: aptitude install python-opencv)
See: https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html
"""
from __future__ import print_function
import cv2 as cv
import numpy as np
def main():
# Common arguments:
# - points : (0,0) is at the top left
# - color : use a tuple for BGR, eg: (255,0,0) for blue. For grayscale, just pass the scalar value.
# - thickness : thickness of the line. If -1 is passed for closed figures like circles, it will fill the shape.
# - lineType : type of line, whether 8-connected, anti-aliased line etc. By default, it is 8-connected. cv2.LINE_AA gives anti-aliased line which looks great for curves.
# CREATE A BLACK IMAGE
img_np = np.zeros((512, 512, 3), np.uint8)
# DRAW A LINE
point_1 = (0, 0)
point_2 = (256, 256)
color = (0, 0, 255)
thickness = 3
cv.line(img_np, point_1, point_2, color, thickness)
# DRAW A RECTANGLE
point_1 = (300, 100)
point_2 = (400, 400)
color = (255, 0, 0)
thickness = -1
cv.rectangle(img_np, point_1, point_2, color, thickness)
# DRAW A CIRCLE
center_point = (100, 300)
radius = 64
color = (0, 255, 0)
thickness = 2
cv.circle(img_np, center_point, radius, color, thickness)
line_type = cv.CV_AA # Anti-Aliased
cv.circle(img_np, center_point, radius + 20, color, thickness, line_type)
# DRAW A ELLIPSE
center_point = (200, 400)
axes_length = (100, 50)
angle = 45 # the angle of rotation of ellipse in anti-clockwise direction
start_angle = 0
end_angle = 180
color = (255, 255, 0)
thickness = 3
line_type = cv.CV_AA # Anti-Aliased
cv.ellipse(img_np, center_point, axes_length, angle, start_angle, end_angle, color, thickness, line_type)
# DRAW A POLYGON
pts = np.array([[32,87], [124,81], [75,43], [60,11]], np.int32)
pts = pts.reshape((-1,1,2))
is_closed = True
color = (255, 0, 255)
thickness = 3
line_type = cv.CV_AA # Anti-Aliased
cv.polylines(img_np, [pts], is_closed, color, thickness, line_type)
# ADD TEXT
text = "Hello!"
start_point = (150, 500)
font = cv.FONT_HERSHEY_SIMPLEX
font_scale = 4
color = (255, 0, 255)
thickness = 3
line_type = cv.CV_AA # Anti-Aliased
cv.putText(img_np, text, start_point, font, font_scale, color, thickness, line_type)
# SAVE THE IMAGE
cv.imwrite("drawing_functions.png", img_np)
if __name__ == '__main__':
main()
|
71b18e371270cdc1b998b86dad6146f71f942194
|
randiaz95/nysom
|
/utils.py
| 911 | 3.6875 | 4 |
import os
def create_directory(root, folder):
if folder is str:
path = os.path.join(root, folder)
if not os.path.exists(path):
os.mkdir(path)
return path
elif folder is list:
path = os.path.join(root, *folder)
if not os.path.exists(path):
os.mkdir(path)
return path
else:
return "Error while creating directory; folder argument is not string or list of strings."
class Conceptor:
def __init__(self, name):
self.name = name
self.columns = []
def addColumn(name, type, primary_key=False):
self.columns.append({"name": name,
"type": type,
"primary_key": primary_key})
def createController():
pass
def createModel():
pass
def createComponent():
pass
|
359e01605ec43e181ec70e4389a79192696a4b19
|
Researching-Algorithms-For-Us/4.Implementation
|
/source/python/시각.py
| 535 | 3.890625 | 4 |
#source code
'''
21:08~21:17
정수 N입력 00:00:00 ~ N:59:59초
3이하나라도 포함되는 모든 경우의수를 작성하시오
'''
def set_input():
clock = int(input())
#roads.append(0)
return clock
def main():
clock = set_input()
count = 0
for hour in range(clock+1):
for minute in range(60):
for second in range(60):
time = f'{hour}:{minute}:{second}'
if '3' in time:
count += 1
if __name__ == '__main__':
main()
|
108c4caded59a4d9b5be66f627dd9f07cdb4cdeb
|
sikendershahid91/SoftwareDesign
|
/assign3/src/fibonacci_iterative.py
| 259 | 3.875 | 4 |
from functools import reduce
def fibonacci_iterative(number):
if number < 0:
raise ValueError("Negative number!")
return reduce(
lambda previous, index: [previous[1], sum(previous)],
range(number + 1), [1, 0]) [1]
|
c54de7736befcbf4569c8a1758b452a1ba3001de
|
croot95/BMGT404_FInal
|
/analyze_cuisines.py
| 1,927 | 3.96875 | 4 |
#!/usr/bin/python
import pandas as pd
#create dataframe column names
col_names = ['Cuisine' , 'Avg Sentiment','Avg Rating','Restaraunts','Ratings']
#choose the file with the data
file_path = "/Users/christopherroot 1/Desktop/cuisines.csv"
df = pd.read_csv(file_path, header = None, names = col_names)
#find mean and sdev for each metric
analyze_these = ['Avg Sentiment','Avg Rating','Restaraunts','Ratings']
for i in analyze_these:
avg = df[i].mean()
sdev = df[i].std()
print i, " Avg: ", avg, " Sdev: ", sdev
avg_rating = df["Ratings"].mean()
sdev_rating = df["Ratings"].std()
avg_sent = df["Avg Sentiment"].mean()
sdev_sent = df["Avg Sentiment"].std()
top_rating = []
top_sent = []
#find cuisines with above avg rating
print "Here are all the cuisines with above average rating"
for index, row in df.iterrows():
if row["Ratings"] >= avg_rating:
top_rating.append(row["Cuisine"])
print row["Cuisine"]
#find cuisines in top 33%
print "Here are all the cuisines with ratings greater than 1 sdev + mean:"
top_33 = avg_rating + sdev_rating
for index, row in df.iterrows():
if row["Ratings"] >= top_33:
print row["Cuisine"]
#find cuisines with above avg sentiment
print "Here are all the cuisines with above average sentiment"
for index, row in df.iterrows():
if row["Avg Sentiment"] >= avg_sent:
top_sent.append(row["Cuisine"])
print row["Cuisine"]
#find cuisines in top 33%
print "Here are all the cuisines with sentiments greater than 1 sdev + mean:"
top_33_sent = avg_sent + sdev_sent
for index, row in df.iterrows():
if row["Avg Sentiment"] >= top_33_sent:
print row["Cuisine"]
#print a list of cuisines that are in top 50% of both avg rating and avg sent
in_both = []
for rest in top_sent:
if rest not in in_both:
in_both.append(rest)
list_len = len(in_both)
print "Here is a list of " , list_len , " restaurants that are in both the top 50% of rating and sentiment: "
print in_both
|
d0b45a622ed42d3074ae0e469e165bf603d01721
|
brityboy/python-workshop
|
/day2/src/substring.py
| 1,078 | 4.125 | 4 |
from collections import defaultdict
def substring_old(words, substrings):
'''
INPUT: list, list
OUTPUT: list
Given two lists of strings, return the list of strings from the second list
that are a substring of a string in the first list.
The strings in the substrings list are all 3 characters long.
'''
result = []
for word in words:
for substring in substrings:
if word.find(substring) != -1:
result.append(substring)
return result
def substring_new(words, substrings):
'''
INPUT: list, list
OUTPUT: list
Given two lists of strings, return the list of strings from the second list
that are a substring of a string in the first list.
The strings in the substrings list are all 3 characters long.
'''
# in the old method, i was going through the substring list 5 times
dict = defaultdict(str)
for word in words:
for substring in substrings:
if word.find(substring) != -1:
dict[word]=substring
return dict.values()
|
7739a1d442d28c210c44b22fb841f25ab9d31efc
|
dehvCurtis/NSA_Py3_COMP3321
|
/Lesson_02/lesson02_sec4_ex2.py
| 164 | 3.65625 | 4 |
def all_the_snacks(snack, spacer):
print((snack + spacer) * num)
num = 42
spacer = '! '
my_snack = input('Pick a snack > ')
all_the_snacks(my_snack, spacer)
|
5c19ce06f65e92b4c5642e75fbe2581b29e99423
|
geeks121/TriangularArbitrage-1
|
/Events.py
| 488 | 3.5625 | 4 |
from abc import ABCMeta, abstractmethod
from threading import Timer, Thread
import time
import queue
class HelloEvent(Thread):
def __init__(self, string_arg):
self.string_arg = string_arg
Thread.__init__(self)
def run(self):
print('hello world!')
time.sleep(3)
print(self.string_arg)
class AnotherEvent(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
print('THIS IS A DIFFERENT KIND OF EVENT!')
|
2ab80870c38bee607444dfafe88ff926fe192ede
|
tejapenugonda/pythonIcp2
|
/Source/FIRST.py
| 257 | 3.875 | 4 |
n = int(input("How many numbers do you have? "))
s = 0
obs = list(map(int, input().split()))
if len(obs) != n:
print("Did not enter "+str(n)+" values")
else:
for i in range(0,len(obs)):
s = s+obs[i]
avg = s / float(n)
print (avg)
|
b73de30be801bfc88bad65a118ebf93ba4cd1e11
|
MrAaaah/fractals_basics
|
/sierpinski_triangle.py
| 1,549 | 3.5 | 4 |
# -*- coding: utf-8 -*-
# noinspection PyPackageRequirements
from PIL import Image, ImageDraw
from datetime import datetime
# each vertices is represented by a tupple (x, y)
# define some params
WIDTH = HEIGHT = 800
ITERATIONS = 7
# vertices of the sierpinski triangle
A = (400, 68)
B = (10, 760)
C = (790, 760)
BACKGROUND_COLOR = '#020104'
TRIANGLE_COLOR = '#A4B1F2'
# return the coordinates of the middle of the segment [ab]
def middle_of_segment(a, b):
return (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
# draw a triangle abc
def draw_triangle(a, b, c, color):
canvas.polygon([a, b, c], fill=color)
# Main function who calculate the sierpinski triangle
# a, b and c are the vertices of the triangle
# n is the number of remaining iterations
def generate_triangle(a, b, c, n):
if n > 1:
# calculate the middle of each segments
p1 = middle_of_segment(a, b)
p2 = middle_of_segment(a, c)
p3 = middle_of_segment(b, c)
# repeat the process for each subtriangle
generate_triangle(a, p1, p2, n - 1)
generate_triangle(b, p1, p3, n - 1)
generate_triangle(c, p2, p3, n - 1)
else:
draw_triangle(a, b, c, TRIANGLE_COLOR)
if __name__ == "__main__":
# init the canvas
img = Image.new("RGB", (WIDTH, HEIGHT), BACKGROUND_COLOR)
canvas = ImageDraw.Draw(img)
generate_triangle(A, B, C, ITERATIONS)
# save the fractal
now = datetime.now()
filename = now.strftime("%Y-%m-%d-%H:%M:%S") + '_sierpinski_triangle.png'
img.save(filename, "PNG")
|
c447c31b37e3085dc5d9a0c6243aa37a0706ffc0
|
siyam04/python_problems_solutions
|
/Siyam Solved/Problem Set -1/Solutions - 1/8.py
| 132 | 3.78125 | 4 |
print("Enter 1st String:")
a = str(input())
print("Enter 2nd String:")
b = str(input())
print("the two strings are", a, 'and', b)
|
33033fee63afe069bddc05b9f0f09a082fb3722a
|
ClaraKim2002/cs110-connect-four
|
/connect_four.py
| 3,045 | 3.78125 | 4 |
import pygame
import sys
import ai
class Board():
def __init__(self):
self.spots = [None]*7
for col in xrange(0, 7):
self.spots[col] = [None]*6
def get_spot_status(self, col, row):
return self.spots[col][row]
def add_piece(self, col, player):
"""
Add a piece to the correct row in the column. If there are no spaces
left in the column return False. If the piece is added return True
"""
pass
def get_game_result(self):
"""
If there is currently a winner, return "R" or "B" depending on who
won the game. Otherwise return None
"""
pass
def draw_board(b):
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 255, 0), (50, 50, 700, 600), 0)
for row in xrange(0, 6):
for col in xrange(0, 7):
x = (col * 100) + 100
y = 700 - ((row * 100) + 100)
if b.get_spot_status(col, row) == "R":
pygame.draw.circle(screen, (255, 0, 0), (x, y), 50)
elif b.get_spot_status(col, row) == "B":
pygame.draw.circle(screen, (0, 0, 0), (x, y), 50)
else:
pygame.draw.circle(screen, (255, 255, 255), (x, y), 50)
if __name__ == '__main__':
screen = pygame.display.set_mode((800, 700))
board = Board()
move = "R"
while True:
change_move = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if move == "R":
valid = False
if event.key == pygame.K_1:
valid = board.add_piece(0, "R")
elif event.key == pygame.K_2:
valid = board.add_piece(1, "R")
elif event.key == pygame.K_3:
valid = board.add_piece(2, "R")
elif event.key == pygame.K_4:
valid = board.add_piece(3, "R")
elif event.key == pygame.K_5:
valid = board.add_piece(4, "R")
elif event.key == pygame.K_6:
valid = board.add_piece(5, "R")
elif event.key == pygame.K_7:
valid = board.add_piece(6, "R")
if valid:
change_move = True
if move == "B":
valid = False
ai_col = ai.choose_move(board, "B")
valid = board.add_piece(ai_col, "B")
if valid:
change_move = True
if change_move:
if move == "B":
move = "R"
elif move == "R":
move = "B"
if board.get_game_result() == "R":
exit("Red Wins!")
elif board.get_game_result() == "B":
exit("Black Wins!")
draw_board(board)
pygame.display.flip()
|
f83e3c398374ff243c036ea0b0cef5e5104cbc67
|
supriyashahane/TIC-TAC-TOE-game
|
/tic-tac-toe.py
| 21,826 | 3.671875 | 4 |
import os
import random
#os.system("clear")
class Board():
def __init__(self):
self.blocks = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def display(self):
print("\t\t\t\t ===============")
print ("\t\t\t\t || %s | %s | %s ||" %(self.blocks[0], self.blocks[1], self.blocks[2]))
print("\t\t\t\t ===============")
print ("\t\t\t\t || %s | %s | %s ||" %(self.blocks[3], self.blocks[4], self.blocks[5]))
print("\t\t\t\t ===============")
print ("\t\t\t\t || %s | %s | %s ||" %(self.blocks[6], self.blocks[7], self.blocks[8]))
print("\t\t\t\t ===============")
def update_blocks(self, x_player, player):
try:
if self.blocks[x_player] == " ":
self.blocks[x_player] = player
elif player == "X":
x_player = int(raw_input("\nblock is not empty Please chosse 0-8 > ") )
self.update_blocks(x_player, player)
else:
self.ai_move(x_player)
except IndexError:
x_player = int(raw_input("\nblock is not empty Please chosse 0-8 > ") )
self.update_blocks(x_player, player)
def winner_player(self, player):
if self.blocks[0] == player and self.blocks[1] == player and self.blocks[2] == player:
return True
if self.blocks[3] == player and self.blocks[4] == player and self.blocks[5] == player:
return True
if self.blocks[6] == player and self.blocks[7] == player and self.blocks[8] == player:
return True
if self.blocks[0] == player and self.blocks[3] == player and self.blocks[6] == player:
return True
if self.blocks[1] == player and self.blocks[4] == player and self.blocks[7] == player:
return True
if self.blocks[2] == player and self.blocks[5] == player and self.blocks[8] == player:
return True
if self.blocks[0] == player and self.blocks[4] == player and self.blocks[8] == player:
return True
if self.blocks[2] == player and self.blocks[4] == player and self.blocks[6] == player:
return True
return False
def tie_found(self):
used_blocks = 0
for block in self.blocks:
if block != " ":
used_blocks += 1
if used_blocks == 9:
return True
else:
return False
def reset(self):
self.blocks = []
self.blocks = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
### Inheritance Concept
class player_show(Board):
def __init__(self, name, class_a):
self.name = name
self.blocks = class_a.blocks
#Board.__init__(self)
####Polymorphism
def update_blocks(self, x_player, player):
if self.blocks[x_player] == " ":
self.blocks[x_player] = player
elif player != "":
x_player = int(raw_input("\nblock is not empty Please chosse 0-8 > ") )
self.update_blocks(x_player, player)
def player_move(self,player):
print("player {} is".format( self.name))
refresh_screen()
x_player = raw_input("\n{} Please chosse 0-8 > ".format(self.name))
if x_player in ["0","1","2","3","4","5","6","7","8"]:
self.update_blocks(int(x_player), player)
refresh_screen()
elif x_player not in ["0","1","2","3","4","5","6","7","8"]:
print("Incorrecr")
self.player_move(player)
#### Inheritance Concept AI_Build
class ai_build(Board):
def __init__(self, name, class_a):
self.name = name
self.blocks = class_a.blocks
def ai_move(self, player):
#cnt = cnt + 1
#if player == "X":
# enemy = "O"
#if player == "O":
# enemy = "X"
#choose center
if self.blocks[4] == " ":
self.update_blocks(4, player)
else:
for i in range(0,8):
#print(cnt)
i = random.randint(0, 8)
if self.blocks[i] == " ":
self.update_blocks(i, player)
#self.ai_move_sucess(player)
break
#AI win player
def ai_move_sucess(self, player):
enemy = "X"
if self.blocks[0] == player and self.blocks[3] == player and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[3] == player and self.blocks[6] == player and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[0] == player and self.blocks[6] == player and self.blocks[3] == " ":
board.update_blocks(3, "O")
#return 3
elif self.blocks[1] == player and self.blocks[4] == player and self.blocks[7] == " ":
board.update_blocks(7, "O")
#return 7
elif self.blocks[4] == player and self.blocks[7] == player and self.blocks[1] == " ":
board.update_blocks(1, "O")
#return 1
elif self.blocks[7] == player and self.blocks[1] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[2] == player and self.blocks[5] == player and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[5] == player and self.blocks[8] == player and self.blocks[2] == " ":
board.update_blocks(2, "O")#
#return 2
elif self.blocks[8] == player and self.blocks[2] == player and self.blocks[5] == " ":
board.update_blocks(5, "O")
#return 5
elif self.blocks[0] == player and self.blocks[1] == player and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[1] == player and self.blocks[2] == player and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[2] == player and self.blocks[0] == player and self.blocks[1] == " ":
board.update_blocks(1, "O")
#return 1
elif self.blocks[3] == player and self.blocks[4] == player and self.blocks[5] == " ":
board.update_blocks(5, "O")
#return 5
elif self.blocks[4] == player and self.blocks[5] == player and self.blocks[3] == " ":
board.update_blocks(3, "O")
#return 3
elif self.blocks[5] == player and self.blocks[3] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[6] == player and self.blocks[7] == player and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[7] == player and self.blocks[8] == player and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[8] == player and self.blocks[6] == player and self.blocks[7] == " ":
board.update_blocks(7, "O")
#return 7
elif self.blocks[0] == player and self.blocks[4] == player and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[4] == player and self.blocks[8] == player and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[8] == player and self.blocks[0] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[2] == player and self.blocks[4] == player and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[4] == player and self.blocks[6] == player and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[6] == player and self.blocks[2] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
elif self.blocks[0] == enemy and self.blocks[3] == enemy and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[3] == enemy and self.blocks[6] == enemy and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[0] == enemy and self.blocks[6] == enemy and self.blocks[3] == " ":
board.update_blocks(3, "O")
#return 3
elif self.blocks[1] == enemy and self.blocks[4] == enemy and self.blocks[7] == " ":
board.update_blocks(7, "O")
#return 7
elif self.blocks[4] == enemy and self.blocks[7] == enemy and self.blocks[1] == " ":
board.update_blocks(1, "O")
#return 1
elif self.blocks[7] == enemy and self.blocks[1] == enemy and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[2] == enemy and self.blocks[5] == enemy and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[5] == enemy and self.blocks[8] == enemy and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[8] == enemy and self.blocks[2] == enemy and self.blocks[5] == " ":
board.update_blocks(5, "O")
#return 5
elif self.blocks[0] == enemy and self.blocks[1] == enemy and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[1] == enemy and self.blocks[2] == enemy and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[2] == enemy and self.blocks[0] == enemy and self.blocks[1] == " ":
board.update_blocks(1, "O")
#return 1
elif self.blocks[3] == enemy and self.blocks[4] == enemy and self.blocks[5] == " ":
board.update_blocks(5, "O")
#return 5
elif self.blocks[4] == enemy and self.blocks[5] == enemy and self.blocks[3] == " ":
board.update_blocks(3, "O")
#return 3
elif self.blocks[5] == enemy and self.blocks[3] == enemy and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[6] == enemy and self.blocks[7] == enemy and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[7] == enemy and self.blocks[8] == enemy and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[8] == enemy and self.blocks[6] == enemy and self.blocks[7] == " ":
board.update_blocks(7, "O")
#return 7
elif self.blocks[0] == enemy and self.blocks[4] == enemy and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[4] == enemy and self.blocks[8] == enemy and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[8] == enemy and self.blocks[0] == enemy and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[2] == enemy and self.blocks[4] == enemy and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[4] == enemy and self.blocks[6] == enemy and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[6] == enemy and self.blocks[2] == enemy and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
else :
self.ai_move("O")
#choose random
def ai_move_sucess1(self, player):
if self.blocks[0] == player and self.blocks[3] == player and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[3] == player and self.blocks[6] == player and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[0] == player and self.blocks[6] == player and self.blocks[3] == " ":
board.update_blocks(3, "O")
#return 3
elif self.blocks[1] == player and self.blocks[4] == player and self.blocks[7] == " ":
board.update_blocks(7, "O")
#return 7
elif self.blocks[4] == player and self.blocks[7] == player and self.blocks[1] == " ":
board.update_blocks(1, "O")
#return 1
elif self.blocks[7] == player and self.blocks[1] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[2] == player and self.blocks[5] == player and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[5] == player and self.blocks[8] == player and self.blocks[2] == " ":
board.update_blocks(2, "O")#
#return 2
elif self.blocks[8] == player and self.blocks[2] == player and self.blocks[5] == " ":
board.update_blocks(5, "O")
#return 5
elif self.blocks[0] == player and self.blocks[1] == player and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[1] == player and self.blocks[2] == player and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[2] == player and self.blocks[0] == player and self.blocks[1] == " ":
board.update_blocks(1, "O")
#return 1
elif self.blocks[3] == player and self.blocks[4] == player and self.blocks[5] == " ":
board.update_blocks(5, "O")
#return 5
elif self.blocks[4] == player and self.blocks[5] == player and self.blocks[3] == " ":
board.update_blocks(3, "O")
#return 3
elif self.blocks[5] == player and self.blocks[3] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[6] == player and self.blocks[7] == player and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[7] == player and self.blocks[8] == player and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[8] == player and self.blocks[6] == player and self.blocks[7] == " ":
board.update_blocks(7, "O")
#return 7
elif self.blocks[0] == player and self.blocks[4] == player and self.blocks[8] == " ":
board.update_blocks(8, "O")
#return 8
elif self.blocks[4] == player and self.blocks[8] == player and self.blocks[0] == " ":
board.update_blocks(0, "O")
#return 0
elif self.blocks[8] == player and self.blocks[0] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
#return 4
elif self.blocks[2] == player and self.blocks[4] == player and self.blocks[6] == " ":
board.update_blocks(6, "O")
#return 6
elif self.blocks[4] == player and self.blocks[6] == player and self.blocks[2] == " ":
board.update_blocks(2, "O")
#return 2
elif self.blocks[6] == player and self.blocks[2] == player and self.blocks[4] == " ":
board.update_blocks(4, "O")
else :
self.ai_move("O")
#choose random
board = Board()
def print_header():
print("\t\t\t WELCOME TO TIC_TAC_TOE\n")
def refresh_screen():
os.system("clear")
print_header()
board.display()
def main(play_again1,choose_leval):
cnt = 0
refresh_screen()
board.reset()
while True:
refresh_screen()
if play_again1 == "Y":
player1 = player_show("John",board)
player1.player_move("X")
if board.winner_player("X"):
print("\nJohn wins!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
board.reset()
cnt = 0
continue
else:
break
if board.tie_found():
print("\nTie Game!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
board.reset()
cnt = 0
continue
else:
break
cnt = cnt + 1
player2 = ai_build("Computer",board)
if choose_leval == "E":
player2.ai_move("O")
refresh_screen()
elif choose_leval == "H":
if cnt > 1:
player2.ai_move_sucess("O")
#board.update_blocks(x, "O")
refresh_screen()
#board.winner_player("O")
else:
player2.ai_move("O")
refresh_screen()
else:
if cnt > 1:
player2.ai_move_sucess1("O")
#board.update_blocks(x, "O")
refresh_screen()
#board.winner_player("O")
else:
player2.ai_move("O")
refresh_screen()
if board.winner_player("O"):
print("\nComputer wins!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
cnt = 0
board.reset()
continue
else:
break
if board.tie_found():
print("\nTie Game!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
cnt = 0
board.reset()
continue
else:
break
elif play_again1 == "N":
player1 = player_show("John",board)
player1.player_move("X")
if board.winner_player("X"):
print("\nJohn wins!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
board.reset()
cnt = 0
continue
else:
break
if board.tie_found():
print("\nTie Game!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
board.reset()
cnt = 0
continue
else:
break
player2 = player_show("Joe",board)
player2.player_move("O")
# winner
if board.winner_player("O"):
print("\nJoe wins!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
cnt = 0
board.reset()
continue
else:
break
# tie
if board.tie_found():
print("\nTie Game!!\n")
play_again = raw_input("would you like to play again? (Y/N) >").upper()
if play_again == "Y":
cnt = 0
board.reset()
continue
else:
break
elif play_again1 is not ["Y" or "N"]:
main(play_again1,choose_leval)
if __name__ == "__main__":
try:
while True:
os.system("clear")
play_again2 = raw_input("would you like to play TIC TAC TOE? (Y/N) >").upper()
if play_again2 == "Y":
print("If you don't have a friend to play beside computer will play with you")
play_again1 = raw_input("would you like to play with computer (Y/N) >").upper()
choose_leval = "H"
while(True):
if play_again1 == "Y":
choose_leval = raw_input("Choose leval (E/M/H) >").upper()
while(True):
if choose_leval in ["H","E","M"]:
print("All d best")
break
elif choose_leval is not ["H","E","M"] :
choose_leval = raw_input("Choose leval (E/M/H) >").upper()
main(play_again1,choose_leval)
break
if play_again1 == "N":
main(play_again1,choose_leval)
break
if play_again1 is not ["Y" or "N"]:
play_again1 = raw_input("would you like to play with computer (Y/N) >").upper()
elif play_again2 == "N":
break
elif play_again2 is not ["Y" or "N"]:
os.system("clear")
play_again1 = raw_input("would you like to play TIC TAC TOE? (Y/N) >").upper()
except KeyboardInterrupt:
# do nothing here
print("\n")
pass
|
ae19f46702080a4b284b9c4ee7fa6875d3aa8278
|
askiefer/practice-code-challenges
|
/sentence_reversal.py
| 408 | 4.125 | 4 |
def sentence_reversal(strg):
# remove the whitespace before and after the string
strg = strg.strip()
# split the string on each space
lst = strg.split(' ')
new_lst = []
for word in lst:
if word == '':
continue
new_lst.insert(0, word)
return ' '.join(new_lst)
if __name__ == '__main__':
print(sentence_reversal(' Hello John how are you '))
print(sentence_reversal(' space before'))
|
793ac06bd2f228e546ef40ff13bad8b6c7099c11
|
keshav304/DSC-SIST-CP-QUESTIONS
|
/DAY-5/ClosestNumbers.py
| 523 | 3.578125 | 4 |
# Closest Numbers: https://www.hackerrank.com/challenges/closest-numbers
# Complete the closestNumbers function below.
def closestNumbers(arr):
arr.sort()
result = min([arr[i]-arr[i-1] for i in range(1,len(arr))])
print(arr)
print(result)
summ=[]
for i in range(1,len(arr)):
if (arr[i]-arr[i-1])==result:
summ.append(str(arr[i-1]))
summ.append(str(arr[i]))
return summ
n = int(input())
arr = list(map(int, input().rstrip().split()))
print(closestNumbers(arr))
|
67a7b667f16e9f55d85a07adf4337ba8fa5f40bc
|
MYMSSENDOG/leetcodes
|
/111. Minimum Depth of Binary Tree.py
| 670 | 3.71875 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from tree_node_lib import *
class Solution:
def minDepth(self, root: TreeNode) -> int:
def helper(root):
if not root:
return 0
l = helper(root.left)
r = helper(root.right)
if not l and not r:
return 1
elif r and l:
return min(l,r) + 1
else:
return max(l,r) + 1
return helper(root)
sol = Solution()
p = makeTree([-10,-3,0,5,9])
print(sol.minDepth(p))
|
1f40c8a2f302fd2158bf4714e649089544e810b0
|
tinsleyzzz/Field_Control_Score
|
/Field Control Cutton.py
| 3,046 | 3.6875 | 4 |
from tkinter import Tk, W, E
from tkinter.ttk import Frame, Button, Label, Style
from tkinter.ttk import Entry
#from tkinter import *
#from tkinter import ttk
#class Frame:
#frame = Frame(self, relief=RAISED, borderwidth=1)
#frame.pack(fill=BOTH, expand=1)
class Calculator(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Calculator")
Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10')
self.columnconfigure(0, pad=3)
self.columnconfigure(1, pad=3)
self.columnconfigure(2, pad=3)
self.columnconfigure(3, pad=3)
self.columnconfigure(4, pad=3)
self.columnconfigure(5, pad=3)
self.rowconfigure(0, pad=3)
entry1 = Entry(self)
#entry.grid(row=0, columnspan=4, sticky=W+E)
entry1.insert(0, "0")
entry2 = Entry(self)
entry2.insert(0, "0")
Team_1_Score = 0
Team_2_Score = 0
def Addition_1():
nonlocal Team_1_Score
Team_1_Score += 1
entry1.delete(0, 3)
entry1.insert(0, Team_1_Score)
F = open("Team1.txt", "w")
F.write(str(Team_1_Score))
F.close()
def Substraction_1():
nonlocal Team_1_Score
Team_1_Score -= 1
entry1.delete(0, 3)
entry1.insert(0, Team_1_Score)
F = open("Team1.txt", "w")
F.write(str(Team_1_Score))
F.close()
def Addition_2():
nonlocal Team_2_Score
Team_2_Score += 1
entry2.delete(0, 3)
entry2.insert(0, Team_2_Score)
F = open("Team2.txt", "w")
F.write(str(Team_2_Score))
F.close()
def Substraction_2():
nonlocal Team_2_Score
Team_2_Score -= 1
entry2.delete(0, 3)
entry2.insert(0, Team_2_Score)
F = open("Team2.txt", "w")
F.write(str(Team_2_Score))
F.close()
def display_1():
return Team_1_Score
def display_2():
return Team_2_Score
One_Pls = Button(self, text="+", command = Addition_1)
One_Pls.grid(row=0, column=0)
One_Mns = Button(self, text="-", command = Substraction_1)
One_Mns.grid(row=0, column=1)
#One_Display = Button(self, text="=", command = display_1)
entry1.grid(row=0, column=2)
Two_Pls = Button(self, text="+", command = Addition_2)
Two_Pls.grid(row=0, column=3)
Two_Mns = Button(self, text="-", command = Substraction_2)
Two_Mns.grid(row=0, column=4)
#Two_Display = Button(self, text="=", command = display_2)
entry2.grid(row=0, column=5)
self.pack()
def main():
root = Tk()
app = Calculator(root)
root.mainloop()
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.