blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
2909c7baca3f265c9ba5c4f2b1f9171d6cb51a4b | DanilooSilva/Cursos_de_Python | /Curso_Python_3_UDEMY/desafios/desafio_dia_semana.py | 273 | 3.515625 | 4 | def get_dia_semana(dia):
dias = {
(1, 7): 'fim-de-semanda',
tuple(range(2, 7)): 'semana'
}
dia_escolhido = (tipo for numero, tipo in dias.items() if dia in numero)
return next(dia_escolhido, '** dia inválido ***')
print(get_dia_semana(2)) |
f374c8b57722d4677cbf9cc7cde251df8896b33d | sreerajch657/internship | /practise questions/odd index remove.py | 287 | 4.28125 | 4 | #Python Program to Remove the Characters of Odd Index Values in a String
str_string=input("enter a string : ")
str_string2=""
length=int(len(str_string))
for i in range(length) :
if i % 2 == 0 :
str_string2=str_string2+str_string[i]
print(str_string2)
|
6896c8dc7af0a4dde9d561c5347454b039aa5b10 | FreekDS/Discord-Bot | /chess/chess_base.py | 1,338 | 3.84375 | 4 | import enum
from abc import abstractmethod
class Position:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return None if (x or y) not in range(0, 8) else Position(x, y)
def __str__(self):
return "({}, {})".format(self.x, self.y)
def __repr__(self):
return str(self)
class COLOR(enum.Enum):
WHITE = 0
BLACK = 1
class Piece:
def __init__(self, pos=Position(), color: COLOR = COLOR.WHITE, string_repr="0"):
self.color = color
self.string_repr = string_repr
self.pos = pos
self._made_first_move = False
def set_pos(self, new_pos, *args, **kwargs):
self.pos = new_pos
self._made_first_move = True
@abstractmethod
def possible_moves(self, *args, **kwargs) -> list:
return []
@abstractmethod
def attack_locations(self, *args, **kwargs) -> list:
return []
def __str__(self):
return self.string_repr
@abstractmethod
def display(self, *args, **kwargs):
pass
def has_moved(self):
return self._made_first_move
def __repr__(self):
return str(self)
if __name__ == '__main__':
p = Position(0, 0)
p2 = Position(7, 7)
print(p + p2)
|
acc1c4163d2fa38824203e725076c9f8d5068888 | komotunde/DATA602 | /Homework 2 (Cars Data Set).py | 3,264 | 4.09375 | 4 |
#1. fill in this class
# it will need to provide for what happens below in the
# main, so you will at least need a constructor that takes the values as (Brand, Price, Safety Rating),
# a function called showEvaluation, and an attribute carCount
class CarEvaluation:
"""A simple class that represents a car evaluation"""
#all your logic here
carCount = 0
def __init__(self, Brand, Price, SafetyRating):
self.Brand = Brand
self.Price = Price
self.SafetyRating = SafetyRating
CarEvaluation.carCount += 1
def showEvaluation(self):
"""Shows the attributes of the object"""
print "The", self.Brand, "has a ", self.Price, "price", "and it's safety is rated a", self.SafetyRating
def __repr__(self):
return self.Brand
#My output for teh order function was not correct until I added the above code. It displays characteristics of the item.
#2. fill in this function
# it takes a list of CarEvaluation objects for input and either "asc" or "des"
# if it gets "asc" return a list of car names order by ascending price
# otherwise by descending price
# you fill in the rest
def sortbyprice(List, Rank):
SortedList = []
for i in List:
if i.Price == "Low":
SortedList.append(i.Brand)
elif i.Price == "Med":
SortedList.append(i.Brand)
else:
SortedList.append(i.Brand)
if Rank == "asc":
return SortedList.reverse()
#3. fill in this function
# it takes a list for input of CarEvaluation objects and a value to search for
# it returns true if the value is in the safety attribute of an entry on the list,
# otherwise false
# you fill in the rest
def searchforsafety(List, Value):
"""Takes a list of CarEvaluation objects and value to search for. It returns true if the value is in the safety attribute of an entry on the list, otherwise, false."""
for car in List:
if car.SafetyRating == Value:
return True
else:
return False
# This is the main of the program. Expected outputs are in comments after the function calls.
if __name__ == "__main__":
eval1 = CarEvaluation("Ford", "High", 2)
eval2 = CarEvaluation("GMC", "Med", 4)
eval3 = CarEvaluation("Toyota", "Low", 3)
print "Car Count = %d" % CarEvaluation.carCount # Car Count = 3
eval1.showEvaluation() #The Ford has a High price and it's safety is rated a 2
eval2.showEvaluation() #The GMC has a Med price and it's safety is rated a 4
eval3.showEvaluation() #The Toyota has a Low price and it's safety is rated a 3
L = [eval1, eval2, eval3]
print sortbyprice(L, "asc"); #[Toyota, GMC, Ford]
print sortbyprice(L, "des"); #[Ford, GMC, Toyota]
print searchforsafety(L, 2); #true
print searchforsafety(L, 1); #false
#Note, I spent about 30 minutes trying to figure out why I kept getting a "this construct does not take any inputs" only to discover it was a typo. After correcting a few mistakes, I have ended here where when ran, by functions give an error of not defined when in fact, they are. |
c3ba85a5be209b6ce186b54b22a49a4cc6259010 | Confidential-Innovation/Algorithm | /Searching_Algorithm/Binary Searching.py | 1,451 | 3.859375 | 4 | # Binary Searching- 1
'''
def binary_search(L,i):
left, right = 0, len(L)-1
while left <= right:
mid = (left + right)//2 # integer divison
if L[mid] == i:
return mid
if L[mid] < i:
left = mid + 1
else:
right = mid -1
return -1
if __name__ == "__main__":
L = [1,2,3,4,5,6,7,8]
for i in range(1,11):
position = binary_search(L,i)
if position == -1:
if i in L:
print(i, "is in L, But function freturned -1")
else:
print(i, "not in list")
else:
if L[position] == i:
print(i, "found in correct position.")
else:
print("Binary search returned", position, "for", i,"which is incorrect")
print("Program terminated")
'''
#Binary Searching - 2
L = list(map(int,input().split()))
print("Main List: ",L)
N = int(input())
left, right = 0, len(L) - 1
print("Total Length: ",right)
while left <= right:
mid = (left + right)//2
if L[mid] == N:
print("Baniry Position: ",mid + 1)
break
elif L[mid] < N:
left = mid + 1
print("left position : ",left)
else:
right = mid - 1
print("right position: ",right)
else:
print("Sorry! %d Not found.: ",N)
|
6cb9c313594341112ecea9b3d69968361ce0ff10 | dls-controls/dls-pmac-lib | /dls_pmaclib/dls_pmaclib.py | 887 | 4.09375 | 4 | class HelloClass:
"""A class who's only purpose in life is to say hello"""
def __init__(self, name: str):
"""
Args:
name: The initial value of the name of the person who gets greeted
"""
#: The name of the person who gets greeted
self.name = name
def format_greeting(self) -> str:
"""Return a greeting for `name`"""
greeting = f"Hello {self.name}"
return greeting
def say_hello_lots(hello: HelloClass = None, times=5):
"""Print lots of greetings using the given `HelloClass`
Args:
hello: A `HelloClass` that `format_greeting` will be called on.
If not given, use a HelloClass with name="me"
times: The number of times to call it
"""
if hello is None:
hello = HelloClass("me")
for _ in range(times):
print(hello.format_greeting())
|
cd239ed588f11605897aca695473bc918093190f | zzhyzzh/Leetcode | /leetcode-algorithms/130. Surrounded Regions/solve.py | 1,644 | 3.828125 | 4 | class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if board == []:
return
def search(i, j):
if j not in range(len(board[0])) or i not in range(len(board)):
return
if board[i][j] == "O":
board[i][j] = "S"
if i == 0:
search(i + 1, j)
elif i == len(board):
search(i - 1, j)
elif j == 0:
search(i, j + 1)
elif j == len(board[0]):
search(i, j - 1)
else:
search(i, j + 1)
search(i, j - 1)
search(i + 1, j)
search(i - 1, j)
else:
return
for m in range(0, len(board[0])):
search(0, m)
search(len(board) - 1, m)
for m in range(1, len(board) - 1):
search(m, 0)
search(m, len(board[0]) - 1)
for n in range(0, len(board[0])):
for m in range(0, len(board)):
if board[m][n] == "S":
board[m][n] = "O"
elif board[m][n] == "O":
board[m][n] = "X"
solution = Solution()
result = solution.solve([["X","O","X","O","X","O"],
["O","X","O","X","O","X"],
["X","O","X","O","X","O"],
["O","X","O","X","O","X"]])
print(result)
print(type(result))
|
e0284f68c706a251380ee31163352c26e9ab8571 | MatheusTostes/simular-triangulos | /(TKINTER) Identificando tipos de triângulo.py | 6,929 | 4.1875 | 4 | # O objetivo aqui era criar uma interface grafica que pedisse 3 entradas, rodasse condições dizendo se esses 3 valores
# poderiam formar um triangulo, em caso afirmativo, devolver as classificações do triângulo e plotar uma representação
# do mesmo em escala reduzida.
# Resultado: https://i.imgur.com/5I6uX21.png
from tkinter import * # Importa tudo da biblioteca tkinter.
janela = Tk() # Instancia o tkinter com a variável janela.
janela.title("TIPO DE TRIÂNGULO") # Renomeia o titulo janela.
def bt_click(): # Define uma função para o botão.
v1 = V1.get() # Armazenamento dos valores de entrada.
v2 = V2.get()
v3 = V3.get()
values = [v1, v2, v3]
values.sort()
a = int(v1) # Conversão dos valores de entrada de string para inteiros.
b = int(v2)
c = int(v3)
normalizer = c / 3
c = 3
b = b / normalizer
a = a / normalizer
if (a <= 0 or b <= 0 or c <= 0): # Primeira condição de exisência de um triângulo.
#print("Valores invalidos.")
lb4["text"] = "Valores invalidos." # Renomeia o label vazio para retornar quebra da condição.
else:
if (a + b <= c or a + c <= b or b + c <= a): # Segunda condição de exisência de um triângulo.
#print("Valores nao podem formar um triangulo.")
lb5["text"] = "Valores nao podem formar um triangulo." # Renomeia o label vazio para retornar quebra da condição.
else:
if (a == b and a == c): # Condição de triângulo equilátero.
#print("Triangulo equilatero.") # Teste para exibir no console se a condição passou ou reprovou.
lb4["text"] = "Triangulo equilatero." # Renomeia o label 4 para avisar caso a condição passe.
# Abaixo o processo se repete com condições distintas para cada tipo de triângulo.
if (a == b and b !=c or a == c and a != b or c==b and c != a):
#print("Triangulo isosceles.")
lb5["text"] = "Triangulo isosceles."
if (a != b and b != c and a != c):
#print("Triangulo escaleno.")
lb6["text"] = "Triangulo escaleno."
if ((b ** 2 == (a ** 2 + c ** 2)) or (a ** 2 == (b ** 2 + c ** 2)) or (c ** 2 == (a ** 2 + b ** 2))):
#print("Triangulo retangulo.")
lb7["text"] = "Triangulo retangulo."
if (((b ** 2 < (a ** 2 + c ** 2))and a<=b and c<=a) or ((a ** 2 < (c ** 2 + b ** 2))and c <= a and b <= c) or ((c ** 2 < (b ** 2 + a ** 2))and b <= c and a <= b)):
#print("Triangulo acutangulo.")
lb8["text"] = "Triangulo acutangulo."
if (b ** 2 > (a ** 2 + c ** 2)) or (a ** 2 > (b ** 2 + c ** 2)) or (c ** 2 > (b ** 2 + a ** 2)):
#print("Triangulo obtusangulo.")
lb9["text"] = "Triangulo obtusangulo."
lbs = [lb4, lb5, lb6, lb7, lb8, lb9] # Todo label que não for renomeado sob as condições acima será enviado para o final da janela,
for lb in lbs: ## aos labels que irão fornecer informação (caso contrário, espaço seria desperdiçado com labels
if lb["text"] == "": ## vazias).
lb.grid(row=11)
A = (0, 0) # A, B e C definem as coordenadas iniciais do triângulo dentro da célula da grade.
B = (c, 0)
hc = (2 * (a**2*b**2 + b**2*c**2 + c**2*a**2) - (a**4 + b**4 + c**4))**0.5 / (2.*c)
dx = (b**2 - hc**2)**0.5
if abs((c - dx)**2 + hc**2 - a**2) > 0.01: dx = -dx
C = (dx, hc)
coords = [int((x + 1) * 10) for x in A+B+C] # Cria a variável coord para utilizar A, B, C e escalonar a figura.
canvas = Canvas(janela, width=200, height=50) # Restringe a área que a figura ocupará.
blue = canvas.create_polygon(*coords) # Cria a figura sobre a variável coords.
canvas.grid(row=1, column=3, rowspan=4) # Posiciona a figura em uma celula específica da grade e une as 3 colunas abaixo dela para seu uso.
lb0 = Label(janela, text="Insira os valores dos lados") # Texto inicial sobre as entradas.
lb1 = Label(janela, text="A : ") # Texto que antecede as entradas à esquerda.
lb2 = Label(janela, text="B : ")
lb3 = Label(janela, text="C : ")
lb4 = Label(janela, text="") # Labels que serão usados pela função para informar o tipo de triângulo.
lb5 = Label(janela, text="")
lb6 = Label(janela, text="")
lb7 = Label(janela, text="")
lb8 = Label(janela, text="")
lb9 = Label(janela, text="")
V1 = Entry(janela, width = 30) # Define as caixas de entrada e sua largura.
V2 = Entry(janela, width = 30)
V3 = Entry(janela, width = 30)
lb0.grid(row=0, column=2) # Posiciona na grade o lb0 (o mesmo para os demais labels abaixo).
lb1.grid(row=1, column=1)
lb2.grid(row=2, column=1)
lb3.grid(row=3, column=1)
lb4.grid(row=5, column=2)
lb5.grid(row=6, column=2)
lb6.grid(row=7, column=2)
lb7.grid(row=8, column=2)
lb8.grid(row=9, column=2)
lb9.grid(row=10, column=2)
V1.grid(row=1, column=2) # Posiciona na grade as caixas de entrada.
V2.grid(row=2, column=2)
V3.grid(row=3, column=2)
bt1 = Button(janela, text="Confirmar", command=bt_click) # Botão que chamará a função definida no inicio.
bt1.grid(row=4 ,column=2) # Posiciona o botão.
janela.geometry("300x200+500+200") # Define o tamanho da janela.
janela.mainloop() # Mantém a execução da janela.
|
64fc1baed6b18f12360b3ad341730637cc486ca5 | wwzz1/Wilson-s | /Scylla.py | 1,556 | 4 | 4 | from fractions import Fraction
from math import pi
#1
def mixed_number(a,b):
x=str(a//b)
y=str(a%b)
b=str(b)
z=x+" "+y+"/"+b
return z
print(mixed_number(5,2))
#2
def vowel_count_1(x):
num=0
for char in x:
if char in "aeiouAEIOU":
num+=1
return num
print(vowel_count_1("This is a sample"))
#3
def vowel_count_2(x):
numa=0
nume=0
numi=0
numo=0
numu=0
for char in x:
if char in "aA":
numa+=1
for char in x:
if char in "eE":
nume+=1
for char in x:
if char in "iI":
numi+=1
for char in x:
if char in "oO":
numo+=1
for char in x:
if char in "uU":
numu+=1
return numa,nume,numi,numo,numu
print(vowel_count_2("This is a sample"))
#4
def sphere_volume(x):
x=float(x)
y=4/3*(pi)*(x**3)
return y
print(sphere_volume(10))
def sphere_surface_area(x):
x=float(x)
y=4*pi*(x**2)
return y
print(sphere_surface_area(10))
#5
def sphere_metics(x):
x=float(x)
y=str(sphere_volume(x))
y="Sphere Volume "+y
z=str(sphere_surface_area(x))
z="Sphere Surface Area: "+z
return y, z
print(sphere_metics(10))
#6
def name_function(x):
if x=="Ted":
return "Ted", 50, 80
print(name_function("Ted"))
#7
def rgb_to_hex(r,b,g):
r=hex(r)
g=hex(g)
b=hex(b)
return r,g,b
print(rgb_to_hex(255,0,0))
def hex_to_rgb(r,b,g):
r=int(r, 16)
g=int(g, 16)
b=int(b, 16)
return r,g,b
print(hex_to_rgb("ff","00","00"))
|
4f09e5225ff0ecbfc6d24767be5cd5805f37155b | wandesky/codility | /lesson03TimeComplexity/TapeEquilibrium/solutionA.py | 788 | 3.625 | 4 | '''
Failed complexity test, the code below returt O(N*N) yet the question wants O(N)
'''
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
lengthy = len(A)
if (lengthy == 0 or lengthy == 1):
return 0
diffies =[]
for i in range(1, lengthy, 1):
lefty, righty = A[:i], A[-(lengthy-i):]
# print('lefty', lefty)
# print('righty', righty)
sumlefty, sumrighty = sum(lefty), sum(righty)
# print('sumlefty', sumlefty)
# print('sumrighty', sumrighty)
absdiffy = abs(sumlefty-sumrighty)
diffies.append(absdiffy)
# print('diffies ',diffies)
# print(min(diffies))
return(min(diffies)) |
6e9ea7f5ad4272c66654137d67a8509a97b9cc65 | Kimyechan/codingTestPractice | /programmers/queueAndStack/다리를 지나는 트럭.py | 1,032 | 3.546875 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
answer = 0
bridge_line = deque([0] * bridge_length)
current_truck = []
while True:
current_weight = 0
if bridge_line.popleft() != 0:
if current_truck:
current_truck.pop(0)
for weightV in current_truck:
current_weight += weightV
value = 10001
if truck_weights:
value = truck_weights[0]
if current_weight + value <= weight:
value_w = truck_weights.pop(0)
current_truck.append(value_w)
bridge_line.append(value_w)
else:
bridge_line.append(0)
answer += 1
if not truck_weights:
total = 0
for line in bridge_line:
total += line
if total == 0:
break
return answer
print(solution(2, 10, [7,4,5,6]))
print(solution(100, 100, [10]))
print(solution(100, 100, [10,10,10,10,10,10,10,10,10,10])) |
47a0b1fb4c75deae9e591d1ebe8a5c415b0e6e46 | Trigl/Recommender-System-Learning | /Chapter1.py | 972 | 3.640625 | 4 | # 推荐系统评分预测准确度指标:均方根误差(RMSE)和平均绝对误差(MAE)
# records[i]=[u,i,rui,pui],测试数据:records = [['haha',1,3.2,3],['hehe',2,2.5,2]]
from math import sqrt
def RMSE(records):
return sqrt(sum([(rui-pui)*(rui-pui) for u,i,rui,pui in records]))/float(len(records))
def MAE(records):
return sum([abs(rui-pui) for u,i,rui,pui in records])/float(len(records))
# TopN推荐的预测准确率通过准确率(precision)和召回率(recall)度量
def PrecisionRecall(test, N):
hit = 0
n_recall = 0
n_precision = 0
for user, items in test.items():
rank = Recommend(user, N)
hit += len(rank & items)
n_recall += len(items)
n_precision += N
return [hit / (1.0 * n_recall), hit / (1.0 * n_precision)]
# 可以定义覆盖率的指标,基尼系数
def GiniIndex(p):
j = 1
n = len(p)
G = 0
for item, weight in sorted(p.items(), key=itemgetter(1)):
G += (2*j - n -1) * weight
return G/float(n-1)
|
f378064cf7c91da51eacdbf933382d8a36053c31 | ParanoidAndroid19/Common-Patterns_Grokking-the-Coding-Interview | /6. In-place reversal of Linked List/3_Reverse k node sublist.py | 1,360 | 3.828125 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def reverseKSublist(head, k):
current = head
prev = None
while True:
i = 1
node_before_sublist = prev
last_node_sublist = current
temp = None
while current != None and i <= k:
temp = current.next
current.next = prev
prev = current
current = temp
i = i + 1
# conneting to first part
if node_before_sublist != None:
node_before_sublist.next = prev
else:
head = prev
# connect with next part
last_node_sublist.next = current
if current == None:
break
prev = last_node_sublist
return head
def printLL(head):
curr = head
st = ""
while curr != None:
st = st + str(curr.data) + "-->"
curr = curr.next
print(st + "||")
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
head.next.next.next.next.next.next = Node(7)
head.next.next.next.next.next.next.next = Node(8)
printLL(head)
printLL(reverseKGroup(head, 3)) |
46879a3bb3c2c47c3e7408816eda150becfdc725 | brunopesmac/Python | /Python/curso/ex45.py | 388 | 3.65625 | 4 | from random import randint
cpu = randint(1,3)
player = int (input("JO KEN PO\n1 pedra\n2 papel\n3 tesoura\n"))
if cpu == player:
print ("EMPATE!")
elif cpu == 1 and player == 2 or cpu == 2 and player == 3 or cpu == 3 and player == 1:
print ("VOCÊ VENCEU!")
elif player == 1 and cpu == 2 or player == 2 and cpu == 3 or player == 3 and cpu == 1:
print ("VOCÊ PERDEU!") |
f0957036ea33120d2001adb75ba33f877cb8439e | EnthusiasticTeslim/MIT6.00.1x | /other/gcdIter.py | 560 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 16 20:43:48 2019
@author: olayi
"""
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
if a < b:
init_d = a
else:
init_d = b
while a%init_d != 0 and b%init_d != 0:
if init_d > 0:
init_d -= 1
if init_d%2 == 0:
init_d = 2
elif init_d%3 == 0:
init_d = 2
return init_d
print(gcdIter(9,8))
|
7c70d9ed04ecae63c3f0dfa073045dd23da415ae | daniel-reich/ubiquitous-fiesta | /dqJYvDRTyXzQPGimc_19.py | 135 | 3.578125 | 4 |
def is_unfair_hurdle(hurdles):
if len(hurdles) > 3: return True
if len(hurdles[0].split('#')[1]) < 4: return True
return False
|
cbc1c82e42e5e5b61b1be878efddb00757818a52 | calebe-takehisa/repository_Python | /procedural_programming/ex013.py | 537 | 3.71875 | 4 | """
Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento.
SAÍDA:
Qual é o salário do Funcionário? R$4319.43
Um funcionário que ganhava R$4319.43, com 15% de aumento, passa a receber R$4967.34
"""
# Minha solução:
salario = input('Qual é o salário do Funcionário? R$')
reajuste = 15
novo_salario = (float(salario)*reajuste/100)+float(salario)
print(f'Um funcionário que ganhava R${salario}, com {reajuste}% de aumento, passa a receber R${novo_salario:.2f}')
|
266e2012071b9e3c272ef5504f395685488a8f05 | DiasVitoria/Python_para_Zumbis | /Lista de Exercícios I Python_para_Zumbis/Exercicio10.py | 333 | 3.75 | 4 | cigarrosDia = int(input("Informe a quantidade de cigarros fumados por dia: "))
anosFumando = int(input("Informe os anos fumando: "))
totalDia = (anosFumando * 365 * cigarrosDia * 10)/1440
print('O total de dias perdidos será de: %.2f' %totalDia, 'dias')
print ('2 elevado a 1 milhão tem %i digitos' %len(str(2**1000000)))
|
9832ce0a1de701b7c77bb270a91037f1d25c9484 | andresnunes/Projetos_Python | /Projetos_Python/Exercicios-Livro-PythonForEverybody/9Ex1.py | 569 | 4.0625 | 4 | '''
Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt
Write a program that reads the words in words.txt and stores them as
keys in a dictionary. It doesn’t matter what the values are. Then you
can use the in operator as a fast way to check whether a string is in the
dictionary.
'''
value = 0
di = dict()
hfile = open("words.txt")
for line in hfile:
words = line.split()
for word in words:
di[word] = value
value += 1
check = input("Enter a word to check: ")
if check in di:
print("True!!")
else:
print("False!!")
|
44cee04bddae4273e7adf178c93442c0605d5886 | knight-byte/Codeforces-Problemset-Solution | /Python/AntonAndPolyhedrons.py | 294 | 4.03125 | 4 | def main():
sides = {"tetrahedron": 4, "cube": 6, "octahedron": 8,
"dodecahedron": 12, "icosahedron": 20}
n = int(input())
ans = 0
for _ in range(n):
shape = input().lower()
ans += sides[shape]
print(ans)
if __name__ == '__main__':
main()
|
34dcc5df5e4d6498245d448b580f05f936d537c4 | BXGrzesiek/HardCoder | /pythonBasics/Exam/exam3.py | 2,049 | 4.0625 | 4 | from os import system, name
from time import sleep
# -----------VARIABLES-------------- #
x = 0
shopping_list = []
ballance = 100.0
shopping_cart = ''
product_costs = dict()
choice = 'y'
# -----------FUNCTIONS-------------- #
def removeDuplicates(shopping_cart):
for i in shopping_cart:
if i not in shopping_list:
shopping_list.append(i)
def addValues():
for i in shopping_list:
try:
x = float(input('Cost for product: ' + i + ' is: '))
if isinstance(x, (int, float)) and isPositive(x):
product_costs.update({i.upper(): float(x)})
else:
print('Products can not be negative, the product: ' + i
+ ' will not be included in the cost estimate.')
product_costs.update({i.upper(): 0})
except ValueError:
print('Wrong value - item: (' + i + ') expelled from Shopping List')
print(product_costs)
def isEnough():
bill = sum(list(product_costs.values()))
if bill > ballance:
print('You need more money (' + str(ballance-bill)
+ ') - It\'s not enough!')
elif bill == ballance:
print('You\'ve come to the estimation - that\'s exactly how much money you need')
else:
print('You have enough funds :)\nYour rest: ' + str(ballance-bill), end="\n")
def isPositive(x):
if x >= 0:
return True
else:
return False
# -----------BODY------------------- #
while choice =='y' or choice == 'Y':
print('SHOPPING LIST - - Your declared account balance is: ' + str(ballance))
shopping_cart = input('Provide shopping list as [apples,bananas,carrots,bread]: ')
shopping_cart = shopping_cart.replace(' ', '').split(',')
removeDuplicates(shopping_cart)
shopping_list = sorted(shopping_list)
addValues()
isEnough()
choice = input('Do you want to try again? [Y/n]: ')
if choice == 'y' or choice == 'Y':
print('Clearing the screen')
sleep(3)
print('\n'*30)
else:
break |
80c7e417f7afb9ba58e4470e7048e37f268e706e | aravindanath/TeslaEV | /Assignment/TaxCalculation.py | 238 | 3.6875 | 4 | x=int(input("Enter the gross Income:"))
y=int(input("Enter the percentage of State tax: "))
z=int(input("Enter the percentage of Central tax: "))
totaltax=y+z
a=(totaltax/100)*x
netincome=x-a
print("The Net income is:" + str(netincome))
|
389843f2c1dc0312c93a54f594639045c534bd98 | memelogit/python | /module2/listas - range.py | 212 | 3.78125 | 4 | # RANGE
# ------
# Creando rangos
rango = range(1, 3)
rango = range(3, 30)
rango = range(2, 10, 2)
# Tipo de dato range
print(type(rango))
print(rango)
# Imprimiendo la secuencia de un rango
print(list(rango)) |
be993cc8710c0c2a8fe30d476838d5aab78176c1 | ivanjankovic16/pajton-vjezbe | /Excercise 2a.py | 220 | 4.125 | 4 | print('Enter a number.')
number = input()
if int(number) % 4 == 0:
print('This number can be divided by 4.')
elif int(number) % 2 == 0:
print('This is an even number.')
else:
print('This is an odd number.')
|
5596002695f1af0443e4c19596516cc34c69a60e | zwarburg/exercism | /python/kindergarten-garden/kindergarten_garden.py | 692 | 3.859375 | 4 | class Garden(object):
def __init__(self, diagram, students=['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry']):
self.rows = map(lambda row: list(row), diagram.split())
self.students = students
def plants(self, student):
plants = {'G': 'Grass', 'C': 'Clover', 'R': 'Radishes', 'V': 'Violets'}
result = []
index = 2 * self.students.index(student)
print(index)
for row in self.rows:
print(row)
print(row[index], row[index+1])
result.append(plants[row[index]])
result.append(plants[row[index + 1]])
return result
|
66651b416b99aac1ddfa8c88591535d9d6c52964 | dmontag23/mars-rovers | /test/test_create_rovers.py | 5,902 | 3.625 | 4 | import unittest
from rovers.create_rovers import CreateRovers
from rovers.point import Point
from rovers.terrain import Terrain
class TestCreateRovers(unittest.TestCase):
'''
Tests the CreateRovers class.
'''
def test_create_command_from_user_input(self):
input_string = "MLRMMRL"
self.assertEqual(input_string, CreateRovers.create_command_from_user_input(input_string))
with self.assertRaises(Exception) as context:
input_string = "MLRMOMRL"
CreateRovers.create_command_from_user_input(input_string)
self.assertTrue("One of your inputs is not a valid movement" in str(context.exception))
def test_create_rover_from_user_input(self):
mock_terrain = Terrain(Point(10, 10))
input_string = "0 0 N"
rover = CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertIsNotNone(rover)
self.assertEqual(mock_terrain, rover.terrain)
self.assertEqual('N', rover.direction)
self.assertEqual(Point(0, 0), rover.position)
with self.assertRaises(Exception) as context:
input_string = "MLRMMRL"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("You did not input 3 values. Please follow my very polite input instructions next time."
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "-9 0 W"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("One of your first 2 numbers was not a non-negative integer "
"[non-negative means bigger than or equal to 0 ;-)]" in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "0 -2 W"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("One of your first 2 numbers was not a non-negative integer "
"[non-negative means bigger than or equal to 0 ;-)]" in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "0.4 6 W"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("One of your first two numbers was not an integer. "
"Please see the definition for an integer here: https://en.wikipedia.org/wiki/Integer"
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "0 dfgdf W"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("One of your first two numbers was not an integer. "
"Please see the definition for an integer here: https://en.wikipedia.org/wiki/Integer"
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "0 6 w"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("w is not a valid direction." in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "11 6 W"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("The initial position (11, 6) of the rover "
"is not on the plateau!" in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "9 11 W"
CreateRovers.create_rover_from_user_input(input_string, mock_terrain)
self.assertTrue("The initial position (9, 11) of the rover "
"is not on the plateau!" in str(context.exception))
def test_create_terrain_from_user_input(self):
input_string = "10 10"
terrain = CreateRovers.create_terrain_from_user_input(input_string)
self.assertIsNotNone(terrain)
self.assertEqual(Terrain(Point(10, 10)), terrain)
with self.assertRaises(Exception) as context:
input_string = "0"
CreateRovers.create_terrain_from_user_input(input_string)
self.assertTrue("You did not input 2 values. Please follow my very polite input instructions next time."
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "1 -2"
CreateRovers.create_terrain_from_user_input(input_string)
self.assertTrue("Part of your input was not a positive integer [positive means bigger than 0 ;-)]"
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "0 1"
CreateRovers.create_terrain_from_user_input(input_string)
self.assertTrue("Part of your input was not a positive integer [positive means bigger than 0 ;-)]"
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "6.344 1"
CreateRovers.create_terrain_from_user_input(input_string)
self.assertTrue("Part of your input was not an integer. "
"Please see the definition for an integer here: https://en.wikipedia.org/wiki/Integer"
in str(context.exception))
with self.assertRaises(Exception) as context:
input_string = "3 asdfd"
CreateRovers.create_terrain_from_user_input(input_string)
self.assertTrue("Part of your input was not an integer. "
"Please see the definition for an integer here: https://en.wikipedia.org/wiki/Integer"
in str(context.exception))
if __name__ == '__main__':
unittest.main() |
3b91b9060bea612cb1456b921d46db1a0001850a | kaichimomose/CS1 | /Roulette_noclass.py | 5,115 | 3.6875 | 4 | import random
# x = random.randint()
random.seed(1)
# from random import randint
# x = randint()
# from random import randint as r
# x = r()
bank_account = 1000
bet_amount = 0
bet_color = None
bet_number = None
bet_even_odd = None
green = [0, 37]
red = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]
black = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35]
def take_bet(color, number, evenodd, amount):
bet_color = color
bet_number = number
bet_amount = amount
bet_even_odd = evenodd
return [bet_color, bet_number, bet_even_odd, bet_amount]
def roll_ball():
# returns a random number between 0 and 37
return random.randint(0, 37)
def check_results(bet, number_result):
# Compares bet_color to color rolled. Compares bet_number to number_rolled.
color_result = None
evenodd_result = None
if number_result in red:
color_result = "red"
else:
color_result = "black"
if number_result != 0:
if number_result % 2 == 0:
evenodd_result = "even"
else:
evenodd_result = "odd"
else:
evenodd_result = evenodd_result
print("Boll number is %s, it is %s and Color is %s" % (number_result, evenodd_result, color_result))
if bet[2] == evenodd_result:
if bet[0] == color_result:
if bet[1] == number_result:
return [True, True, True] # [evenodd, color, number]
else:
return [True, True, False]
else:
if bet[1] == number_result:
return [True, False, True]
else:
return [True, False, False]
else:
if bet[0] == color_result:
if bet[1] == number_result:
return [False, True, True]
else:
return [False, True, False]
else:
if bet[1] == number_result:
return [False, False, True]
else:
return [False, False, False]
def payout(check, bet):
# returns total amount won or lost by user based on results of roll.
if check[0] is True:
if check[1] is True:
if check[2] is True:
return bet[3] * 2 * 2 * 38
else:
return bet[3] * 2 * 2
else:
if check[2] is True:
return bet[3] * 2 * 38
else:
return bet[3] * 2
else:
if check[1] is True:
if check[2] is True:
return bet[3] * 2 * 38
else:
return bet[3] * 2
else:
if check[2] is True:
return bet[3] * 38
else:
if bet[3] is None:
return 0
else:
return -(bet[3])
def confirm_amount():
amount = input("Amount: ")
if amount != "":
amount = int(amount)
if amount < 10:
print("Minimum bet is $10.")
amount = confirm_amount()
elif amount > bank_account:
print("You do not have that much money.")
amount = confirm_amount()
else:
print("%s" % amount)
amount = amount
else:
amount = None
return amount
# def continue_bet():
# yes_or_no = input("Continue? Yes or No: ")
# if yes_or_no == "Yes" or yes_or_no == "yes":
# play_game()
# elif yes_or_no == "No" or yes_or_no == "no":
# pass
# else:
# print("Excuse me. Say again please?")
# continue_bet()
def play_game():
# This is the main function for the game.
# When this function is called, one full iteration of roulette, including:
# Take the user's bet. Roll the ball. Determine if the user won or lost.
# Pay or deduct money from the user accordingly.
print("Decide color(red or black), number(0 ~ 37) and even or odd. Keep it blank if you do not bet.")
color = input("Color (red or black): ")
if color != "red" and color != "black" and color != "":
print("Please choose from red, black or blank")
play_game()
else:
number = input("Number (0 ~ 37): ")
if int(number) in range(0, 38):
number = int(number)
elif number == "":
number = None
else:
print("Please choose a number from 0 to 37 or keep it blank")
play_game()
evenodd = input("Even or Odd: ")
if evenodd == "Even" or evenodd == "even" or evenodd == "Odd" or evenodd == "odd" or evenodd == "":
evenodd = evenodd
amount = confirm_amount()
else:
print("Even (even), Odd (odd) or Blank")
play_game()
bet = take_bet(color, number, evenodd, amount)
number_result = roll_ball()
check = check_results(bet, number_result)
money = payout(check, bet)
if money > 0:
print("YOU WON $%s!" % (money))
elif money == 0:
print("YOU DID NOT BET!!")
else:
print("YOU LOST $%s!" % (-money))
# continue_bet()
play_game()
|
7f4a41eab2cb6edd2ad5ba794baf18e8b840ab9c | philipenders/Mission_To_Mars | /m2m.py | 7,086 | 3.890625 | 4 | import random
"""The crew is made up of character objects"""
class Crew(object):
def __init__(self, full_crew_b=True):
if full_crew_b:
self.crew_roles = full_crew_list
else:
self.crew_roles = limited_crew_list
self.full_crew = {}
for role in self.crew_roles:
self.full_crew[role] = Character(role, self.crew_roles)
def char_select(self, crew_role):
return self.full_crew[crew_role]
def list_crew(self):
for crewmember in self.full_crew:
print self.full_crew[crewmember]
"""
Character objects store trait, description, and flag/trigger information about specific characters
Because the characters are part of an emergent story (hopefully), they will change with time.
"""
class Character(object):
def __init__(self, role, crew_reference):
# randomly generates a name from name lists and ensures no duplicates
self.name = ""
self.name_val_1 = random.randint(0, len(first_names)-1)
self.name_val_2 = random.randint(0, len(last_names)-1)
self.name = first_names.pop(self.name_val_1) + " " + last_names.pop(self.name_val_2)
self.role = role.lower()
self.role_description = ""
self.role_description = role_description[self.role]
self.traits = []
self.traits = role_trait_base[self.role]
# generate traits using the role_trait_base as a guideline
for i in range(len(self.traits)):
self.traits[i] = self.traits[i] + random.randint(1, 2)
self.INTELLIGENCE = self.traits[0]
self.PHYSICAL = self.traits[1]
self.MECHANICAL = self.traits[2]
self.SCIENCE = self.traits[3]
self.LEADERSHIP = self.traits[4]
self.CHARISMA = self.traits[5]
# beginning of relationship system
self.opinion = {}
for role in crew_reference:
self.opinion[role] = random.randint(0, 5) + 1
for role in self.opinion:
if role == self.role:
self.opinion[role] = 99
self.enemyList = {}
for role in crew_reference:
self.enemyList[role] = False
self.strain = 0
# The unambiguous representation should be name + role + what the role does + their specific stats
def __repr__(self):
return (self.name + ": " + self.role.capitalize() + " - " + self.role_description + ". Stats: "
+ str(self.traits) + '\n')
# The following methods are all for checking and changing relationship values
def check_rel(self, other):
if self.opinion[other] == 99:
return "N/A"
elif self.opinion[other] > 5:
return "friendly"
elif self.opinion[other] > 0:
return "good"
elif self.opinion[other] == 0:
return "neutral"
elif self.opinion[other] < -5:
return "sour"
else:
return "hostile"
def lower_rel(self, other, amount=1):
self.opinion[other] -= amount
def raise_rel(self, other, amount=1):
self.opinion[other] += amount
def become_enemy(self, other):
if other in self.enemyList:
self.enemyList[other] = True
else:
print ("invalid")
def emnity_ends(self, other):
if other in self.enemyList:
self.enemyList[other] = False
else:
print("invalid")
# The ship is where the action happens, it can sustain damage and must survive the journey
class Ship:
def __init__(self):
self.name = raw_input("Please enter the name of the ship: ")
self.difficulty = raw_input("Please enter difficulty of 1,2,3 or 4")
self.systems = systems_list
self.system_stats = {}
for system in self.systems:
self.system_stats[system] = 100
def system_status(self):
for item in self.system_stats.keys():
print (str(self.system_stats[item]) + "% : " + item)
# heavily under construction
class MainGame:
def __init__(self):
self.crew = Crew(True)
self.ship = Ship()
def status_report(self):
return self.ship.system_status()
systems_list = ["life support", "main engine", "maneuvering engines", "descent", "fuel systems"]
safeguards = ["life support safeguards", "main engine safeguards", "descent safeguards", "fuel systems safeguards"]
limited_crew_list = ["captain", "first officer", "mechanic", "science officer"]
full_crew_list = ["captain", "first officer", "mechanic", "science officer", "technician", "doctor", "soldier"]
role_description = {"captain": "The commander of the ship, the captain has high LEADERSHIP and CHARISMA",
"science officer": "Charged with leading the science mission, "
"the chief science officer has high SCIENCE and INTELLIGENCE",
"technician": "Knowing all of the technical systems of the ship, "
"the mechanic has high MECHANICAL and INTELLIGENCE",
"mechanic": "Being the primary repairperson on board, "
"the mechanic has high MECHANICAL and PHYSICAL",
"first officer": "The second in commmand, The first officer has high LEADERSHIP and INTELLIGENCE",
"doctor": "The chief Medical officer, the doctor has high INTELLIGENCE AND CHARISMA",
"soldier": "Along to protect the crew, the Soldier has very high PHYSICAL"
}
role_trait_base = {"captain": [2, 2, 2, 2, 4, 4],
"science officer": [4, 1, 2, 5, 2, 2],
"technician": [4, 2, 4, 2, 2, 2],
"mechanic": [2, 5, 4, 2, 2, 1],
"first officer": [4, 2, 2, 2, 4, 2],
"doctor": [4, 2, 1, 3, 2, 4],
"soldier": [2, 7, 2, 1, 2, 1]}
# last name list randomly generated by a website
first_names = ['Anneliese', 'Effie', 'Tyra', 'Bell', 'Kirk', 'Jerald', 'Yuonne', 'Leeanne', 'Lyndsey', 'Lura', 'Inger',
'Celestine', 'Melania', 'Tambra', 'Randy', 'Teena', 'Conchita', 'Gracia', 'Casandra', 'Olevia',
'Eufemia', 'Rita', 'Shanon', 'Lan', 'Hunter', 'Trinidad', 'Phillip', 'Merrie', 'Melony', 'Page',
'Teresia', 'Elfreda', 'Madaline', 'Exie', 'Hilton', 'Rodrick', 'Nu', 'Margot', 'Trina', 'Shalon', 'Zona',
'Marianne', 'Kaitlyn', 'Greta', 'Sergio', 'Del', 'Clinton', 'Caroline', 'Maynard', 'Marti', 'David',
'Adrian', 'Jim', 'John']
# last name list randomly generated by my... caboose
last_names = ['Smith', "Mombassa", "Carson", "Jackson", 'Dean', "Orwell", "Abe", "Cartwright", "Lee", "Ching", "Zhou",
"O'Leary", "White", "Brown", "Blackstone", "Yens", "Nordquist", "Wooster", "Butler", "Ivanov", "Roman",
"Yeng", "Dickey", "Zamboni", "Doctor", "Peters", "Patella", "Patel", "Chomsky", "Badiwallah", "Abdul",
"al Saud", "Hobbes", "Ali"]
MainGame()
|
e31da3ad567769dd36d4a9a84d9ebf239b8736c6 | hkapp/ML_course | /labs/ex02/template/costs.py | 427 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""a function used to compute the loss."""
import numpy as np
def compute_loss(y, tx, w, lossf = "MSE"):
"""Calculate the loss.
You can calculate the loss using mse or mae.
"""
e = y - tx.dot(w)
if (lossf == "MSE"):
return (1 /(2 * y.shape[0])) * e.T.dot(e)
elif (lossf == "MAE"):
return (1 /y.shape[0]) * np.sum(np.abs(e))
else:
raise ValueError
|
ffd8299ff4b1b1fe997a4e789e3d90cbf64238ed | Mallik-G/dataload | /sample/record_generator.py | 2,681 | 3.53125 | 4 | """
Sample record generator to be used on data-load.
"""
import sample.randomize
class SampleRecordGenerator():
"""
Class used to generate a sample record to data load.
"""
def __init__(self, args, configs):
self.configs = configs['sample']
self.fields = self.configs['fields']
self.__max_length = self.configs['max_length']
self.__min_length = self.configs['min_length']
self.__only_required = args.only_required
# Get the max length of a field. If not set, use the default.
def __get_max_lenght(self, field):
if 'max_length' in field:
return field['max_length']
return self.__max_length
# Get the max length of a field. If not set, use the default.
def __get_min_length(self, field):
if 'min_length' in field:
return field['min_length']
return self.__min_length
# Generate the random values using the defined fields.
def __generate_random_value(self, field, index):
# Add the necessary field attributes to generate
# the random field value.
field.update({
'max_length': self.__get_max_lenght(field),
'min_length': self.__get_min_length(field)
})
only_required = self.__only_required
func_name = "generate_random_{}".format(field['type'])
random_gen_func = getattr(sample.randomize, func_name,
'Method {} not found!'.format(func_name))
# Check if method exists and is callable before call it.
if callable(random_gen_func):
return random_gen_func(field, only_required=only_required,
index=index)
return random_gen_func
def generate_field_data(self, field, index):
"""
Generate the field record based on config file.
Args:
field: The field object.
index: The index from records number receive on arguments.
Returns:
The field value using the format or a random value.
"""
field_value = self.__generate_random_value(field, index=index)
return field_value
def generate_record(self, index):
"""
Generate the sample record row using the field configuratio.
Args:
index: The index from records number receive on arguments.
Returns:
The record complete row, populated with generated data.
"""
record_row = {}
for field in self.fields:
field_name = field['name']
record_row[field_name] = self.generate_field_data(field, index)
return record_row
|
3ef92f613e7b27e4e7120b43788c696913932bee | courtneyng/Intro-To-Python | /Mad-Libs/Mad-Libs.py | 1,577 | 4 | 4 | # Program ID: Mad-Libs
# Author: Courtney Ng
# Period 7
# Program Description: Making a mad lib based on the string functions
adj = input("Please input an adjective. ")
noun = input("Please input a noun. ")
verb = input("Please input a verb. ")
place = input("Please input a place. ")
line1 = "After the uprising, the world became a(n) adj cyberpunk society where technology is almost everything."
line2 = "While everyone sleeps, one adj person named Temperance Rebekah Wickham patrols the night to hack the system."
line3 = "Temperance uses a noun to hack into the system by distorting files and corrupting them so they rip."
line4 = "Her base is located in place."
line4a = "Her work space is very adj and shes proud of that."
line5 = "To get from place to place in this new blocked society, she also uses her noun."
line6 = "Her noun"
line7 = "Her noun can decode messages like this"
line8 = "Ixwixllxbxexatxtxhexschxooxlxtoxmorxrow."
line8a = "I will be at the school tomorrow"
line9 = "She goes to help out at the school after seeing this. "
line9a = "She works to liberate the adj humans of her time"
print(line1.replace("adj", adj))
print(line2.replace("adj", adj))
print(line3.replace("noun", noun))
print(line4.replace("place", place))
print(line4a.replace("adj", adj))
print(line5.replace("noun", noun))
print(line6.replace("noun", noun), "can do all sorts of amazing things")
print(line7.replace("noun", noun))
print(line8)
print(line8.split("x"))
print("She decodes it to see the message.", " ".join(line8a))
print(line9 + line9a.replace("adj", adj))
|
d68cab75e1f20ae09c2f37a297e2224bf6712e57 | KojoEAppiah/kata-pencil-durability | /kata-pencil-durability/Pencil.py | 2,811 | 3.625 | 4 | class Pencil():
def __init__(self, durability, length, eraser_durability):
self.paper =""
self.initial_durability = durability
self.durability = durability
self.length = length
self.eraser_durability = eraser_durability
self.last_erased = None
self.erased_position = None
def write(self, text):
char_index = 0
char_count = 0
while self.durability > 0 and char_count < len(text):
if text[char_index].isupper():
self.durability -= 2
elif text[char_index] == " " or text[char_index] == "\n":
pass
else:
self.durability -= 1
if self.durability >= 0:
self.paper += text[char_index]
char_count += 1
char_index += 1
char_index = char_count
while char_index < len(text):
self.paper += " "
char_index += 1
def sharpen(self):
if self.length > 0:
self.durability = self.initial_durability
self.length -= 1
def erase(self, word_to_erase): #Refactor?
if self.eraser_durability - len(word_to_erase.replace(" ", "")) >= 0:
word_index = self.paper.rfind(word_to_erase)
self.paper = self.paper[:word_index] + (" "*len(word_to_erase)) + self.paper[word_index + len(word_to_erase) : ]
self.eraser_durability -= len(word_to_erase.replace(" ", ""))
self.last_erased = word_to_erase
self.erased_position = word_index
else:
word_index = self.paper.rfind(word_to_erase)
self.last_erased = word_to_erase[(len(word_to_erase)-self.eraser_durability) : ]
self.erased_position = word_index + (len(word_to_erase)-self.eraser_durability)
self.paper = self.paper[ : word_index + (len(word_to_erase)-self.eraser_durability)] + (" "*self.eraser_durability) + self.paper[word_index + len(word_to_erase) : ]
self.eraser_durability = 0
def edit(self, word_to_add):
if(self.last_erased != None):
if len(word_to_add) <= len(self.last_erased):
self.paper = self.paper[:self.erased_position] + word_to_add + self.paper[self.erased_position + len(word_to_add):]
else:
new_word = ""
counter = 0
while counter < len(word_to_add):
if self.paper[self.erased_position + counter] != " ":
new_word += "@"
else:
new_word += word_to_add[counter]
counter += 1
self.paper = self.paper[:self.erased_position] + new_word + self.paper[self.erased_position + len(new_word):] |
eda6f93d61ec1f2aa864a029fb07e6e1df58200a | jerinsebastian521/python | /Cycle 5/C5.4 time.py | 563 | 4 | 4 | class Time:
def __init__(self, hour, minute, second):
self.__hour = hour
self.__minute = minute
self.__second = second
def __add__(self, other):
return self.__hour + other.__hour, self.__minute + other.__minute, self.__second + other.__second
a = int(input("enter 1st hour"))
b = int(input("enter 1st min"))
c = int(input("enter 1st sec"))
t1 = Time(a, b, c)
d = int(input("enter 2nd hour"))
e = int(input("enter 2nd min"))
f = int(input("enter 2nd sec"))
t2 = Time(d, e, f)
t3 = t1 + t2
print("sum of two time", t3)
|
5081b58e0ee599dacd81afd5d2a61a0c316ed4c1 | LITiGEM/Simulation | /Game of LIT/gameOfLIt.py | 1,713 | 3.71875 | 4 | import numpy as np
import random
#--------------------------------------------------------
# Object
#--------------------------------------------------------
class Agent: #defining a new class to provide the standard features, agent is the "player of the Game of Lit"
def __init__(self, A,B,C,D,E): #function to define the initial conditions of the agents A,B,C,D,E that will be used in the code later for each iteration
self.none = A
self.one = B
self.two= C
self.three= D
self.four= E
#--------------------------------------------------------
# Defining functions
#--------------------------------------------------------
def GenProb(numParam): #function for the probability of each generation
probArray = np.random.rand(1, numParam)
return probArray #return an array of random variables of shape 1, numParam
def GenAgent(numAgent): #generate an agent given that we have an agent class
agentArray = []
for num in range(numAgent):
instance = GenProb(5)
agentArray.append(Agent(instance[0][0] , instance[0][1] , instance[0][2], instance[0][3], instance[0][4]))
print(agentArray[3].three, agentArray[4].one) #we use [] to call a particular array (as now we are generating 100 agents
return agentArray
def Grid(length,height):
a=np.zeros(shape=(length,height))
return a
def FirstState(grid, agent):
return(agent)
def Simulation(newGrid, numGen):
return newGrid
#--------------------------------------------------------
# Running simulation
#--------------------------------------------------------
if __name__ == "__main__":
agentArray = GenAgent(100)
M=Grid (20,20)
N=FirstState(M,3)
|
ddd2a50ebff12e5b030cd9a2ecfba1e66c2322c6 | Icode4passion/practicepythonprogams | /even_odd.py | 245 | 4 | 4 | numbers = [1,2,3,4,5,6,7,8,9]
count_even = 0
count_odd = 0
for number in numbers:
if number % 2 == 0:
count_even = count_even+1
else :
count_odd = count_odd + 1
print "Count Even:", count_even
print "Count Even:", count_odd |
bc74b00a2d29957bbf21ed92da0daf306e2692bd | vesso8/Tuples-and-Sets | /01. Unique Usernames.py | 137 | 3.546875 | 4 | n = int(input())
unique_names = set()
for _ in range(n):
names = input()
unique_names.add(names)
print(*unique_names, sep= "\n") |
0ae1660aa6e48f85b462ebdb30265f8fd20f3ab0 | alf808/python-labs | /09_exceptions/09_04_files_exceptions.py | 2,121 | 4.15625 | 4 | '''
In this exercise, you will practice both File I/O as well as using Exceptions
in a real-world scenario.
You have a folder containing three text files of books from Project Gutenberg:
- war_and_peace.txt
- pride_and_prejudice.txt
- crime_and_punishment.txt
1) Open war_and_peace.txt, read the whole file content and store it in a variable
2) Open crime_and_punishment.txt and overwrite the whole content with an empty string
3) Loop over all three files and print out only the first character each. Your program
should NEVER terminate with a Traceback.
a) Which Exception can you expect to encounter? Why?
b) How do you catch it to avoid the program from terminating with a Traceback?
BONUS CHALLENGE: write a custom Exception that inherits from Exception and raise it if the
first 100 characters of any of the files contain the string "Prince".
'''
import os
# path script from https://stackoverflow.com/questions/51623506/python-os-listdir-no-such-file-or-directory
script_path = os.path.dirname(os.path.realpath(__file__))
books_path = os.path.join(script_path, "books")
#print(script_path)
#print(books_path)
book_files = os.listdir(books_path)
for bf in book_files:
if "copy" not in bf:
# Open crime_and_punishment.txt and overwrite with an empty string
if "crime_and_punishment" in bf:
crim = ""
with open(f"{books_path}/{bf}", "r") as fin:
crim = fin.readlines()
with open(f"{books_path}/{bf}", "w") as fout:
crim = ""
fout.write(crim)
# read content of war_and_peace into a variable
elif "war_and_peace" in bf:
with open(f"{books_path}/{bf}", "r") as fin:
warp = fin.readlines()
for bf in book_files:
if "copy" not in bf:
with open(f"{books_path}/{bf}", "r") as fin:
temp = fin.readline()
try:
first_char = temp[0:2]
except IndexError as ie:
print(f"something went wrong with book file {bf}: {ie} ")
else:
print(first_char)
|
232fbc19ecd77515d260f6d0f653f73ffb84551e | nguyenhuudat123/lesson8 | /bt8.py | 153 | 3.6875 | 4 | _2tuple = (4,6,9,0,0,0,0,0)
k = 1
for item in _2tuple:
if _2tuple[0] != item:
k = 0
break
print('giong all') if k == 1 else print('khong giong all') |
4e689bb332deffdbd2f719c48f2e6291d57718e7 | tylermargetts/05-Space-Shooter | /main1.py | 5,819 | 4.1875 | 4 | """
Move with a Sprite Animation
Simple program to show basic sprite usage.
Artwork from http://kenney.nl
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_move_animation
"""
import arcade
import random
import os
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Move with a Sprite Animation Example"
NUM_ENEMIES = 5
STARTING_LOCATION = (750,300)
BULLET_DAMAGE = 10
ENEMY_HP = 20
HIT_SCORE = 10
KILL_SCORE = 100
MOVEMENT_SPEED = 5
class Bullet(arcade.Sprite):
def __init__(self, position, velocity, damage):
'''
initializes the bullet
Parameters: position: (x,y) tuple
velocity: (dx, dy) tuple
damage: int (or float)
'''
super().__init__("assets/laser.png", 0.5)
(self.center_x, self.center_y) = position
(self.dx, self.dy) = velocity
self.damage = damage
def update(self):
'''
Moves the bullet
'''
self.center_x += self.dx
self.center_y += self.dy
class Player(arcade.Sprite):
def __init__(self):
super().__init__("assets/Spaceship.png", 0.25)
(self.center_x, self.center_y) = STARTING_LOCATION
class Enemy(arcade.Sprite):
def __init__(self, position):
super().__init__("assets/RightRun1.png", 0.75)
self.hp = ENEMY_HP
(self.center_x, self.center_y) = position
class MyGame(arcade.Window):
""" Main application class. """
def __init__(self, width, height, title):
super().__init__(width, height, title)
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
self.score = 0
self.enemy = None
self.set_mouse_visible(False)
self.bullet_list = arcade.SpriteList()
self.enemy_list = arcade.SpriteList()
self.player = Player()
self.score = 0
self.background = None
def setup(self):
self.enemy_list = arcade.SpriteList()
# Set up the players
self.score = 0
self.enemy = arcade.AnimatedWalkingSprite()
character_scale = 0.75
self.enemy.stand_right_textures = []
self.enemy.stand_right_textures.append(arcade.load_texture("assets/RightRun3.png",
scale=character_scale))
self.enemy.stand_left_textures = []
self.enemy.stand_left_textures.append(arcade.load_texture("assets/RightRun3.png",
scale=character_scale, mirrored=True))
self.enemy.walk_right_textures = []
self.enemy.walk_right_textures.append(arcade.load_texture("assets/RightRun1.png",
scale=character_scale))
self.enemy.walk_right_textures.append(arcade.load_texture("assets/RightRun2.png",
scale=character_scale))
self.enemy.walk_right_textures.append(arcade.load_texture("assets/RightRun3.png",
scale=character_scale))
self.enemy.walk_right_textures.append(arcade.load_texture("assets/RightRun3.png",
scale=character_scale))
self.enemy.texture_change_distance = 20
self.enemy.scale = 0.8
self.enemy.change_x = MOVEMENT_SPEED
for i in range(NUM_ENEMIES):
x = 50
y = random.randrange(0, 500)
enemy = Enemy((x,y))
self.enemy_list.append(enemy)
# Set the background color
self.background = arcade.load_texture("assets/background.png")
def on_key_press(self, key, modifiers):
"""
Called whenever a key is pressed.
"""
if key == arcade.key.UP:
self.enemy.change_x = MOVEMENT_SPEED
def on_draw(self):
arcade.start_render()
arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,
SCREEN_WIDTH, SCREEN_HEIGHT, self.background)
arcade.draw_text(str(self.score), 20, SCREEN_HEIGHT - 40, arcade.color.WHITE, 16)
self.player.draw()
self.bullet_list.draw()
self.enemy_list.draw()
def update(self, delta_time):
""" Movement and game logic """
self.bullet_list.update()
import time
import sys
for e in self.enemy_list:
collisions = e.collides_with_list(self.bullet_list)
for c in collisions:
c.kill()
self.score += 10
e.hp -= 10
if e.hp <= 0:
e.kill()
self.score += 100
if self.score >= 600:
sys.exit()
self.enemy_list.update()
self.enemy_list.update_animation()
def on_mouse_motion(self, x, y, dx, dy):
'''
The player moves left and right with the mouse
'''
self.player.center_y = y
# Generate a list of all sprites that collided with the player.
# Loop through each colliding sprite, remove it, and add to the score.
def on_mouse_press(self, x, y, button, modifiers):
if button == arcade.MOUSE_BUTTON_LEFT:
x = self.player.center_x - 50
y = self.player.center_y
bullet = Bullet((x,y),(-10,0),BULLET_DAMAGE)
self.bullet_list.append(bullet)
def main():
""" Main method """
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()
if __name__ == "__main__":
main() |
887b4ac4bfdc18cd0625a736e7c9733a18e92c5e | KalsaHT/lc_practice | /array_python/33.py | 1,806 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
@time: 2017/8/24
@author: leilei
"""
class Solution1(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums == []:
return -1
try:
return nums.index(target)
except ValueError:
return -1
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
if len(nums) == 1:
if nums[0] == target:
return 0
else:
return -1
rotate_index = -1
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
rotate_index = i
if rotate_index == -1:
return self.bisearch(nums, 0, len(nums) - 1, target)
if target < nums[0]:
index = self.bisearch(nums, rotate_index + 1, len(nums) - 1, target)
else:
index = self.bisearch(nums, 0, rotate_index, target)
return index
def bisearch(self, nums, low, high, target):
'''nums - list[int]'''
if high < low:
return -1
mid = low + (high - low) / 2
print mid
if nums[mid] == target:
return mid
else:
if nums[mid] < target:
low = mid + 1
return self.bisearch(nums, low, high, target)
else:
high = mid - 1
return self.bisearch(nums, low, high, target)
s = Solution()
print s.search([3, 1], 3)
# print s.bisearch([1, 3], 0, 1, 4)
# print a |
c72e226d15a142db283a666d8826575a806fe424 | CaveroBrandon/TicTacToe | /TicTacToe_V1.py | 4,652 | 3.75 | 4 | # Tic tac toe game, not ussing IA, just random numbers
# This version doesnt have a UI
from random import randint
import sys
global empty_spaces
empty_spaces = {}
def restart_game():
global empty_spaces
empty_spaces = {1: 1, 2: 2, 3: 3,
4: 4, 5: 5, 6: 6,
7: 7, 8: 8, 9: 9}
def show_table():
print('**************')
print('|', empty_spaces[1], '|', empty_spaces[2], '|', empty_spaces[3], '|')
print('-------------')
print('|', empty_spaces[4], '|', empty_spaces[5], '|', empty_spaces[6], '|')
print('-------------')
print('|', empty_spaces[7], '|', empty_spaces[8], '|', empty_spaces[9], '|')
print('-------------')
def validate_decision():
try:
value_to_validate = int(input("Your turn:"))
if 9 >= value_to_validate >= 1:
if empty_spaces[value_to_validate] == 'X' or empty_spaces[value_to_validate] == 'O':
validate_decision()
else:
empty_spaces[value_to_validate] = 'X'
show_table()
else:
validate_decision()
except ValueError:
print('Your play most be a number')
validate_decision()
def opponent_plays():
opponent_game = randint(1, 9)
if 9 >= opponent_game >= 1:
if empty_spaces[opponent_game] == 'X' or empty_spaces[opponent_game] == 'O':
opponent_plays()
else:
empty_spaces[opponent_game] = 'O'
show_table()
else:
opponent_plays()
def end_game_verification():
control = False
for ele in empty_spaces:
if str(empty_spaces[ele]).isdigit():
control = True
if empty_spaces[1] == empty_spaces[2] == empty_spaces[3] == 'X' or \
empty_spaces[4] == empty_spaces[5] == empty_spaces[6] == 'X' or \
empty_spaces[7] == empty_spaces[8] == empty_spaces[9] == 'X' or \
empty_spaces[1] == empty_spaces[4] == empty_spaces[7] == 'X' or \
empty_spaces[2] == empty_spaces[5] == empty_spaces[8] == 'X' or \
empty_spaces[3] == empty_spaces[6] == empty_spaces[9] == 'X' or \
empty_spaces[1] == empty_spaces[5] == empty_spaces[9] == 'X' or \
empty_spaces[3] == empty_spaces[5] == empty_spaces[7] == 'X':
print('CONGRATULATIONS YOU WIN')
game_control = input('Wanna play again Y/N:')
if game_control == 'Y' or 'y':
restart_game()
elif game_control == 'N' or 'n':
sys.exit()
elif empty_spaces[1] == empty_spaces[2] == empty_spaces[3] == 'O' or \
empty_spaces[4] == empty_spaces[5] == empty_spaces[6] == 'O' or \
empty_spaces[7] == empty_spaces[8] == empty_spaces[9] == 'O' or \
empty_spaces[1] == empty_spaces[4] == empty_spaces[7] == 'O' or \
empty_spaces[2] == empty_spaces[5] == empty_spaces[8] == 'O' or \
empty_spaces[3] == empty_spaces[6] == empty_spaces[9] == 'O' or \
empty_spaces[1] == empty_spaces[5] == empty_spaces[9] == 'O' or \
empty_spaces[3] == empty_spaces[5] == empty_spaces[7] == 'O':
print('YOU LOSE')
game_control = str(input('Wanna play again Y/N:'))
if game_control == 'Y' or 'y':
restart_game()
elif game_control == 'N' or 'n':
sys.exit()
if not control:
print('IT IS A TIE')
game_control = str(input('Wanna play again Y/N:'))
if game_control == 'Y' or 'y':
restart_game()
elif game_control == 'N' or 'n':
sys.exit()
def fun_button1():
if(boton1['text'] == '-'):
boton1.configure(text = 'X')
def fun_button2():
if(boton2['text'] == '-'):
boton2.configure(text = 'X')
def fun_button3():
if(boton3['text'] == '-'):
boton3.configure(text = 'X')
def fun_button4():
if(boton4['text'] == '-'):
boton4.configure(text = 'X')
def fun_button5():
if(boton5['text'] == '-'):
boton5.configure(text = 'X')
def fun_button6():
if(boton6['text'] == '-'):
boton6.configure(text = 'X')
def fun_button7():
if(boton7['text'] == '-'):
boton7.configure(text = 'X')
def fun_button8():
if(boton8['text'] == '-'):
boton8.configure(text = 'X')
def fun_button9():
if(boton9['text'] == '-'):
boton9.configure(text = 'X')
restart_game()
show_table()
while True:
end_game_verification()
validate_decision()
end_game_verification()
opponent_plays()
|
38f2e24de60d0de1c0d5f67a66f2fc77f34ffd1c | reynoldscem/aoc2017 | /05/2.py | 682 | 3.65625 | 4 | from argparse import ArgumentParser
from itertools import count
def build_parser():
parser = ArgumentParser()
parser.add_argument('filename')
return parser
def main():
args = build_parser().parse_args()
with open(args.filename) as fd:
data = fd.read().splitlines()
jumps = [int(entry) for entry in data]
index = 0
for steps in count(1):
next_index = index + jumps[index]
if jumps[index] >= 3:
jumps[index] -= 1
else:
jumps[index] += 1
index = next_index
if index < 0 or index >= len(jumps):
break
print(steps)
if __name__ == '__main__':
main()
|
0d1f41169ca3b57df82e69470ea71a94a69f2084 | pauldedward/100-Days-of-Code | /Day-20&21&24/snake_Game/snake.py | 2,022 | 3.625 | 4 | from turtle import Turtle, xcor
STEP_SIZE = 20
class Snake:
def __init__(self):
self.make_snake()
def make_snake(self):
self.body = []
for i in range(0, 3):
todd = Turtle()
todd.penup()
todd.color("white")
todd.shape("square")
todd.setx(STEP_SIZE - (i * STEP_SIZE))
self.body.append(todd)
self.head = self.body[0]
def move(self, heading):
head_heading = self.head.heading()
if heading != head_heading and abs(heading - head_heading) != 180:
self.head.setheading(heading)
prev_x = self.head.xcor()
prev_y = self.head.ycor()
self.head.forward(STEP_SIZE)
for i in range(1, len(self.body)):
current_x = self.body[i].xcor()
current_y = self.body[i].ycor()
self.body[i].goto(prev_x, prev_y)
prev_x = current_x
prev_y = current_y
def grow(self, direction):
x_offset = 0
y_offset = 0
if direction == 0:
x_offset = -STEP_SIZE
elif direction == 180:
x_offset = STEP_SIZE
elif direction == 90:
y_offset = STEP_SIZE
elif direction == 270:
y_offset = -STEP_SIZE
x_pos = self.body[-1].xcor() + x_offset
y_pos = self.body[-1].ycor() + y_offset
todd = Turtle()
todd.penup()
todd.color("white")
todd.shape("square")
todd.goto(x_pos, y_pos)
self.body.append(todd)
def check_bitself(self):
for i in range(1, len(self.body)):
if self.head.xcor() == self.body[i].xcor() and self.head.ycor() == self.body[i].ycor():
print("Game Over")
return True
return False
def reset_game(self):
for piece in self.body:
piece.clear()
piece.hideturtle()
self.make_snake() |
416d60e0178ef549f42aa00553b9910d0090e6b9 | sharmasaravanan/Machine_learning | /pythonCourse/module-8.py | 1,358 | 4.25 | 4 | # functions
# no arg no return
def operation():
a = int(input("Enter any number :"))
b = int(input("Enter any number :"))
print(a+b, a*b)
operation()
# no arg with return
def operation():
a = int(input("Enter any number :"))
b = int(input("Enter any number :"))
return a+b, a*b
s,m = operation()
print('sum is',s,', mul is',m)
s,m = operation()
print('sum is',s,', mul is',m)
s,m = operation()
print('sum is',s,', mul is',m)
# with arg with return
def operation(a,b):
return a+b, a*b
a = int(input("Enter any number :"))
b = int(input("Enter any number :"))
s,m = operation(b,a)
print('sum is',s,', mul is',m)
s,m = operation(b,a)
print('sum is',s,', mul is',m)
s,m = operation(b,a)
print('sum is',s,', mul is',m)
# prime number check
def isPrimeCheck(num):
for j in range(2, num):
if num % j == 0:
break
else:
return num
numbers = list(range(1,10))
print(numbers)
for i in numbers:
ans = isPrimeCheck(i)
if ans:
print(ans)
# with default value
def operation(a,b=10):
return a+b, a*b
a = int(input("Enter any number :"))
b = int(input("Enter any number :"))
s,m = operation(a)
s,m = operation(a,b)
print('sum is',s,', mul is',m)
add = lambda a,b,c : a+b+c
print(add(2,3,5))
upperCase = lambda string : string.upper()
print(upperCase('sharma'))
|
98bc247babc9be6d9ce316e94ef4ccd67e175c31 | chittella369/LearnPython | /ForLoops.py | 222 | 3.796875 | 4 | friends =["Jim","Carrey","Tom","Steve","Arnold"]
#range = len(friends)
for index in range(5):
if index==0:
print("first iteration")
else:
print("not first")
#print(friends[index])
#friends.
|
a24d7ca0d6bed29ffb079916d15dd6501ff24922 | salmasalem99/Sorting-Algorithms | /s1.py | 4,700 | 4.03125 | 4 | '''Merge Sort'''
def merge(array,s,m,e,length):
temparray =[0]*length
index1=s
index2=m+1
i=s
z=0
while i <= e:
z=i
if index1==(m+1):
while z <= e:
temparray[z]=array[index2]
index2+=1
z+=1
elif index2==(e+1):
while z<=e:
temparray[z]=array[index1]
index1+=1
z+=1
if z==(e+1):
break
elif array[index1] <= array[index2]:
temparray[i]=array[index1]
index1+=1
elif array[index2] < array[index1]:
temparray[i]=array[index2]
index2+=1
i+=1
i=s
while i<=e:
array[i]=temparray[i]
i+=1
def mergesort(array, start, end,length):
if start < end:
middle = int((start+end)/2)
mergesort(array,start,middle,length)
mergesort(array,middle+1,end,length)
merge(array,start,middle,end,length)
'''Selection Sort'''
def selectionsort(array2):
i=0
j=0
flag=0
index=0
minimum=0
while i<len(array2):
flag=0
minimum=array2[i]
j=i+1
while j<len(array2):
if array2[j]<=minimum:
minimum=array2[j]
index=j
flag=1
j+=1
if flag==1:
minimum=array2[index]
array2[index]=array2[i]
array2[i]=minimum
i+=1
'''Heap Sort'''
def max_heapify(array,i,n):
ch1=2*i+1
ch2=ch1+1
m=i
if ch1<=n:
if array[ch1]>array[m]:
m=ch1
if ch2<=n:
if array[ch2]>array[m]:
m=ch2
if m!=i:
temp=array[m]
array[m]=array[i]
array[i]=temp
max_heapify(array,m,n)
def Build_MH(array,n):
i=int((n-1)/2)
while i>=0:
max_heapify(array,i,n)
i-=1
def HS(array,n):
Build_MH(array,n)
temp=0
i=n
while i>0:
temp=array[i]
array[i]=array[0]
array[0]=temp
max_heapify(array,0,i-1)
i-=1
'''Main Function'''
import time
def read_file(path):
with open(path ,encoding = 'utf-8') as f2:
lines = f2.readlines()
array= [int(line) for line in lines]
return array
array1 = read_file("file1.txt")
array2 = read_file("file2.txt")
HS1=array1.copy()
HS2=array2.copy()
MS1=array1.copy()
MS2=array2.copy()
SS1=array1.copy()
SS2=array2.copy()
print('Heap sort')
l1=len(array1)-1
l2=len(array2)-1
start = time.time()*1000.0
HS(HS1,l1)
time.sleep(1)
elapsed_time = float(time.time()*1000.0 - start -1000)
print('Time taken by Heap sort algorithm',elapsed_time)
HS(HS2,l2)
print(HS1)
print(HS2)
print('Selection sort')
start = time.time()*1000.0
selectionsort(SS1)
time.sleep(1)
elapsed_time = float(time.time()*1000.0 - start -1000)
print('Time taken by Selection sort algorithm',elapsed_time)
selectionsort(SS2)
print(SS1)
print(SS2)
print('Merge sort')
start = time.time()*1000.0
mergesort(MS1,0,len(MS1)-1,len(MS1))
time.sleep(1)
elapsed_time = float(time.time()*1000.0 - start -1000)
print('Time taken by Merge sort algorithm',elapsed_time)
mergesort(MS2,0,len(MS2)-1,len(MS2))
print(MS1)
print(MS2)
i=0
flag=0
if len(MS1) != len(MS2) :
print('Files are not identical')
else:
while i< len(MS1) :
if MS1[i] != MS2[i]:
flag=1
if(flag):
print('Files are not identical')
break
i+=1
if flag==0:
print('Files are identical')
'''import matplotlib.pyplot as plt
import numpy as np
n = [1000 , 5000, 10000, 50000, 100000,200000,300000]
heaptime=[]
mergetime=[]
selectiontime=[]
for i in n:
arr = np.random.randint(1,100000,i)
ss=arr.copy()
hs=arr.copy()
ms=arr.copy()
start = time.time()
selectionsort(ss)
elapsed_time = float(time.time()- start)
selectiontime.append(elapsed_time)
start = time.time()
HS(hs,len(hs)-1)
elapsed_time = float(time.time()- start)
heaptime.append(elapsed_time)
start = time.time()
mergesort(ms,0,len(ms)-1,len(ms))
elapsed_time = float(time.time()- start)
mergetime.append(elapsed_time)
print(i, " is done")
plt.figure()
plt.title('Time Performance of Sorting Algorithms')
plt.plot(n, heaptime,label='Heap Sort')
plt.plot(n,mergetime,label='Merge Sort')
plt.plot(n,selectiontime,label='Selection Sort')
plt.legend()
plt.ylabel('Time(s)')
plt.xlabel('n')
plt.show()'''
|
762ed37e8da2d117515002119c370faf5a693c0b | Raj-kar/Python | /Project/rock_paper_scissors_v3.py | 896 | 4.09375 | 4 | from random import randint
while True:
print("\n..... rock .....\n..... paper .....\n..... scissors .....")
user1= input("\nEnter player 1's Choice :: ").lower()
rand_num=randint(0,2)
if(rand_num==0):
comp="rock"
elif(rand_num == 1):
comp="paper"
elif(rand_num == 2):
comp="scissors"
print(f"Computer choose :: {comp}")
if (user1 == "paper" or user1 == "rock" or user1 == "scissors"):
if(user1== "rock" and comp=="scissors"):
print("\nplayer 1 WIN")
elif(user1 == "paper" and comp=="rock"):
print("\nplayer 1 WIN")
elif(user1 == "scissors" and comp=="paper"):
print("\nplayer 1 WIN")
elif(user1 == comp):
print("\nIt's a Tie")
else:
print("\nComputer WIN")
else:
print("\nWrong Input ...!")
user_choice=input("\nDo you want to play Again ? (y/n) ")
if(user_choice == "y"):
pass
else:
print("\nThanks for playing with us ... ;)")
break
|
f557a9a8473d20f46db32667e40da90dbabce2a3 | atikhasan2090/newton-s-divided-difference-formula | /diivided difference.py | 764 | 3.75 | 4 | #Newtons Divided difference formula
n = int(input("Enter the number of data in dataset : "))
li = [[0 for i in range(n)]for i in range(n+1)]
for i in range(n):
li[0][i] = int(input("enter the value of x{} : ".format(i)))
li[1][i] = int(input("enter the value of y{} : ".format(i)))
x = int(input("enter the unknown value of x : "))
c = 1
for i in range(n-1):
for j in range(n-1-i):
li[i+2][j] = (-li[i+1][j]+li[i+1][j+1]) / (li[0][j+c]-li[0][j])
c = c+1
y = li[1][0]
for i in range(n-1):
temp_add = 1
for j in range(i+1):
temp_add = temp_add * (x-li[0][j])
y = y + ( temp_add * li[i+2][0] )
print("The value of y for {} is {}".format(x,y))
#print(li) |
d1fc075ca8ccdaf22f23698607fa5a01954e82d1 | Basstma/PathfindingAlgorithmWithPygame | /solver.py | 16,519 | 3.8125 | 4 | from maze import Maze
from linkedlist import Node, NodeGraph
from graph import Graph, Edge
from threading import Thread
import time
class Solver:
def __init__(self, maze: Maze, target):
"""
Basic Class for an Solver, that soves the maze
:param maze:
:param target:
"""
self.maze = maze
self.start = self.maze.start
self.target = self.maze.target
def run(self):
"""
Function have to get overwrite in each Child class. This function have to start the Thread for the solver
algorithm
:return:
"""
pass
def draw_way(self, nodes: dict, end_node: Node):
"""
draws the way from linked List with maze coordinates
:param nodes: All Nodes that are existing
:param end_node: last node
:return:
"""
self.maze.maze[end_node.y][end_node.x] = 4
self.maze.maze[self.start[0]][self.start[1]] = 3
node = end_node.privious
# From last node to node that was privous for the actual node
while node.privious:
self.maze.maze[node.y][node.x] = 5
node = nodes[str(node.privious)]
time.sleep(self.maze.delay)
def find_possible_next_steps(self, actual_possition: tuple) -> list:
"""
Conrtorls in maze in which direction its possible to go.
That means that there is no wall and the point isn't visited.
1|1|0 Part of Maze: X is actuall position.
1|X|0 The function looks from x in North, East, West and South direction and check if this filed is in
1|0|0 maze and if it is an Waypoint
The funktion possible ways to 11 for visualisation and so it dosn't get detected in this function.
If the Waypoint is 4 it's the target and it shouldn't get another color but should be an waypoint
:param actual_possition: touple with actual x and y coordiantes
:return: list with posible coordinates to go.
"""
next_steps = []
if actual_possition[1] + 1 < self.maze.size[1]:
if self.maze.maze[actual_possition[0]][actual_possition[1] + 1] == 1:
next_steps.append((actual_possition[0], actual_possition[1] + 1))
self.maze.maze[actual_possition[0]][actual_possition[1] + 1] = 11
elif self.maze.maze[actual_possition[0]][actual_possition[1] + 1] == 4:
next_steps.append((actual_possition[0], actual_possition[1] + 1))
if actual_possition[1] - 1 >= 0:
if self.maze.maze[actual_possition[0]][actual_possition[1] - 1] == 1:
next_steps.append((actual_possition[0], actual_possition[1] - 1))
self.maze.maze[actual_possition[0]][actual_possition[1] - 1] = 11
elif self.maze.maze[actual_possition[0]][actual_possition[1] - 1] == 1:
next_steps.append((actual_possition[0], actual_possition[1] - 1))
if actual_possition[0] + 1 < self.maze.size[0]:
if self.maze.maze[actual_possition[0] + 1][actual_possition[1]] == 1:
next_steps.append((actual_possition[0] + 1, actual_possition[1]))
self.maze.maze[actual_possition[0] + 1][actual_possition[1]] = 11
elif self.maze.maze[actual_possition[0] + 1][actual_possition[1]] == 1:
next_steps.append((actual_possition[0] + 1, actual_possition[1]))
if actual_possition[0] - 1 >= 0:
if self.maze.maze[actual_possition[0] - 1][actual_possition[1]] == 1:
next_steps.append((actual_possition[0] - 1, actual_possition[1]))
self.maze.maze[actual_possition[0] - 1][actual_possition[1]] = 11
elif self.maze.maze[actual_possition[0] - 1][actual_possition[1]] == 1:
next_steps.append((actual_possition[0] - 1, actual_possition[1]))
return next_steps
def maze_to_graph(self):
"""
Build an Graph from the actual maze.
:return: Return two dictionarys one contains all Nodes, its called graphs
The other one contains all edges
"""
def is_edge(y, x):
"""
Function that controlls if an point is an Node or an Edge.
:param y: y Value of the actual point in Maze
:param x: x value of the actual point in Maze
:return: True if it is an edge False if it is an Node
"""
#Declare Variables
w1, w2, w3, w4 = False, False, False, False
# Each if check if an point have an neighbor in Nort, East, West and South
# In inner if it controls if the neightboor is an Waypoint or an Node.
# If it is its an valid point in Maze(Node or Waypoint) than set the bool for this waypoint to True
if y > 0:
if self.maze.maze[y - 1][x] == 1 or self.maze.maze[y - 1][x] == 6:
w1 = True
if self.maze.size[0] > y + 1:
if self.maze.maze[y + 1][x] == 1 or self.maze.maze[y + 1][x] == 6:
w2 = True
if x > 0:
if self.maze.maze[y][x - 1] == 1 or self.maze.maze[y][x - 1] == 6:
w3 = True
if self.maze.size[1] > x + 1:
if self.maze.maze[y][x + 1] == 1 or self.maze.maze[y][x + 1] == 6:
w4 = True
# Returns True if the Point is no end, crossing or curve
# That means the Points are in an horizontal or vertical Line and nothing else
return ((w1 and w2) and not (w3 or w4)) or ((w3 and w4) and not (w1 or w2))
self.maze.maze[self.maze.target[0]][self.maze.target[1]] = 1
last_element = None
graphs = {}
for i in range(0, self.maze.size[0]):
for j in range(0, self.maze.size[1]):
if self.maze.maze[i][j] == 1:
# The following if is only for visualisation. It set the last visited element to the value
# it was before, so its possible to undo the last change, if it was an edge that gets controlled
if last_element:
if self.maze.maze[last_element[0][0]][last_element[0][1]] != 6:
self.maze.maze[last_element[0][0]][last_element[0][1]] = last_element[1]
last_element = ((i, j), self.maze.maze[i][j])
#time.sleep(self.maze.delay)
# Sets the actual visited point to 11 so its possible to see where the algorithm is actual checking
# for nodes
self.maze.maze[i][j] = 11
# If the actual Point is an Node an new Graph Element is created and added to the dictionary
# Set the corresponding point to 6 so it can be visualised as an Node in Maze
if not is_edge(i, j):
g = Graph((i, j))
graphs[str(g)] = g
self.maze.maze[i][j] = 6
# Undo the value change for last controlled point if its no Node
if last_element:
if self.maze.maze[last_element[0][0]][last_element[0][1]] != 6:
self.maze.maze[last_element[0][0]][last_element[0][1]] = last_element[1]
edges = {}
for graph in graphs.keys():
# move_direction is each direction an neighbor waypoint can be (West, East, South, North)
for move_direction in ((-1, 0), (1, 0), (0, -1), (0, 1)):
# Controls if the way is an valid point to go.
# 1. If it is in Maze y-size range
# 2. If it is in Maze x-size range
# 3. If the maze[y][x] is an valid point, where the way can go
if (self.maze.size[0] > graphs[graph].y + move_direction[0] >= 0) and \
(self.maze.size[1] > graphs[graph].x + move_direction[1] >= 0) and \
(self.maze.maze[graphs[graph].y + move_direction[0]][graphs[graph].x + move_direction[1]] in (1., 4., 6.)):
# initialise the variables for the next step
length = 1
x = graphs[graph].x + move_direction[1]
y = graphs[graph].y + move_direction[0]
# last element is for storing the information for the actual point
last_element = ((y, x), self.maze.maze[y][x])
# Controls how long the edge is. That means it goes in the direction until there is an Waypoint or
# the target and add 1 to length for each step.
while not (self.maze.maze[y][x] == 6 or self.maze.maze[y][x] == 4):
x += move_direction[1]
y += move_direction[0]
length += 1
self.maze.maze[last_element[0][0]][last_element[0][1]] = last_element[1]
# Creates an new ege for with the values from the upper while function and added it to the
# edges-dictionary
new_edge = Edge(graphs[graph], graphs[str(y) + ':' + str(x)])
new_edge.set_length(length)
graphs[graph].add_edge(graphs[str(y) + ':' + str(x)], new_edge)
edges[str(new_edge)] = new_edge
#time.sleep(self.maze.delay)
return graphs, edges
class WideSearchSolver(Solver):
def wide_search(self):
"""
Algorithm for WideSearch
:return:
"""
# Initialise all needed variables
waypoints = [self.start]
position = self.start
start_node = Node(None, position)
target = None
# nodes dict is only for visualisation
nodes = {str(start_node): start_node}
# Search while the actual position isn't target and there are possibles waypoints left
while self.maze.maze[position[0]][position[1]] != 4 and len(waypoints) != 0:
# Takes the first waypoint, this mean the "nearest"
position = waypoints[0]
self.maze.steps_to_solve += 1
# If it is target, the Node have to get generated
if self.maze.maze[position[0]][position[1]] == 4:
target = Node(nodes[str(position[0]) + ':' + str(position[1])], position)
# Adds all possible next waypoints from actual waypoint
for point in self.find_possible_next_steps(position):
# Add only to next waypoints if it isn't already in there.
if point not in waypoints:
# Added at end so the points that are added earlier are got visited earlier
waypoints.append(point)
new_node = Node(nodes[str(position[0]) + ':' + str(position[1])], point)
nodes[str(new_node)] = new_node
time.sleep(self.maze.delay)
# Remove the actual visited waypoint, so it can't be visited twice
waypoints.pop(0)
if target:
self.draw_way(nodes, end_node=nodes[str(target)])
def run(self):
running_thread = Thread(target=self.wide_search)
running_thread.start()
class DepthSearchSolver(Solver):
def depth_search(self):
"""
Algorithm for depth search
Could also be build recursive, but python has an limitation in max recursion depth and in bigger mazes this
can cause errors
:return:
"""
# Initialise all needed variables
waypoints = [self.start]
position = self.start
start_node = Node(None, position)
target = None
# nodes dict is only for visualisation
nodes = {str(start_node): start_node}
# Search while the actual position isn't target and there are possibles waypoints left
while self.maze.maze[position[0]][position[1]] != 4 and len(waypoints) != 0:
position = waypoints[0]
self.maze.steps_to_solve += 1
# If it is target, the Node have to get generated
if self.maze.maze[position[0]][position[1]] == 4:
target = Node(nodes[str(position[0]) + ':' + str(position[1])], position)
for point in self.find_possible_next_steps(position):
# Adds all possible next waypoints from actual waypoint
if point not in waypoints:
# Inserts the waypoint at index 1 in waypoints, that make it possible to finish an path until it
# hasn't possible next waypoints or it is an target.
# This is the alternative for recursion.
waypoints.insert(1, point)
new_node = Node(nodes[str(position[0]) + ':' + str(position[1])], point)
nodes[str(new_node)] = new_node
time.sleep(self.maze.delay)
# removes the actual used waypoint, so it doesn't get visited twice
waypoints.pop(0)
# If target is found it visualise the way to target
if target:
self.draw_way(nodes, end_node=nodes[str(target)])
def run(self):
running_thread = Thread(target=self.depth_search)
running_thread.start()
class DijkstraSolver(Solver):
def dijkstra(self):
"""
Start to search for Target with dijkstra algorithm
:return:
"""
# Initialise the needed variables
graphs, edges = self.maze_to_graph()
start = graphs[str(self.maze.start[0]) + ":" + str(self.maze.start[1])]
target = graphs[str(self.maze.target[0]) + ":" + str(self.maze.target[1])]
# In actual_ay all possible next nodes are stored
actual_way = {
str(start): NodeGraph(start, None, None)
}
# node_way contains all already visited nodes
node_way = {}
while str(target) not in actual_way.keys():
# Takes the node with smallest length, that isn't visited
neares_node = actual_way[min(actual_way, key=lambda k: actual_way[k].get_length())]
# Create all next possible Nodes, from the actual Node, with the edges that can be go from the actual node
for edge in neares_node.itself.edges:
node_to_add = neares_node.itself.edges[edge].node_two
new_node = NodeGraph(node_to_add, neares_node, neares_node.itself.edges[edge])
# Add only if not in nodes to visit and not in visited nodes so no node get's visited two times.
# If it is already visited there is an shorter way to reach this Node and cause the algorithm looks for
# the shortest way its not in need to visit this node again
if str(new_node.itself) not in list(actual_way.keys()) and \
str(new_node.itself) not in list(node_way.keys()):
new_node.add_length(neares_node.itself.edges[edge].get_length())
actual_way[str(new_node.itself)] = new_node
# Add the actual node to node_way and remove it from possible next waypoints
node_way[str(neares_node.itself)] = neares_node
actual_way.pop(str(neares_node.itself))
# For visualisation makes. Start by target, because the linked List works with previous Nodes
way = []
point = actual_way[str(target)]
# Starts to search for start of maze
while str(point.itself) != str(start):
way.append(point)
point = point.privious
# Add the start to way
way.append(node_way[str(start)])
# Change value of target, only for visualisation
self.maze.maze[self.maze.target[0]][self.maze.target[1]] = 4
# Reverse the list of waypoints and go through it, that means start at start and at end
for node in way[::-1]:
if node.itself and node.privious:
# Visualise each edge with time delay.
edge_way = node.edge.get_way()
self.maze.maze[node.edge.node_one.y][node.edge.node_one.x] = 2
for wp in edge_way:
self.maze.maze[wp[0]][wp[1]] = 5
time.sleep(self.maze.delay)
def run(self):
# Function for start dijkstra search algorithm
running_thread = Thread(target=self.dijkstra)
running_thread.start()
|
219e4b12d647c28e5472d07ccf113e778a389bcb | camarena2/camarena2.github.io | /name_generator.py | 460 | 3.734375 | 4 |
import random
first = ("Amy", "Bob", "Billy", "Ben", "Alyssa", "Natalie", "Mari", "Christian", "Cora", "Lalo", "Joel", "Eric", "Erika", "Eugene", "Mazikeen", "Linda", "Chloe", "Benneth")
second = ("James", "Kerry", "Mate", "Camino", "Flotando", "Botella", "Tableta", "Mesa", "Madera", "Dolbiniak", "Jenski", "Spy", "Anahi", "Brown")
firrst = random.choice(first)
seccond = random.choice(second)
name = (firrst + " " + seccond
)
print("Your name is: " + name)
|
de470ea20490a21a145eeb812ce64d5221d985c8 | nushrathumaira/Fall2017102 | /newlab3/lab3sol/is_sorted.py | 343 | 4.15625 | 4 | import sys
# python is_sorted.py <input_file>
with open(sys.argv[1], "r") as numbers:
arr = []
for line in numbers.readlines():
arr.append(int(line))
if all(a <= b for a,b in zip(arr[:-1], arr[1:])):
print("List of " + str(len(arr)) + " integers is sorted!\n")
else:
print("List is not sorted...\n")
|
3db5cf86a97f92af30e9c032c8b6f738f4fa6e97 | elenakaba/First_task_Ventilation-start_of_second | /with_rooms.py | 3,797 | 3.59375 | 4 | import math
import matplotlib.pyplot as plt
from shapely.geometry import Point
from ventilation_coverage import VentilationCoverage
from vent_body import VentBody
from building import Building
def plot_shape_graphics(shape):
_x, _y = shape.exterior.xy
plt.plot(_x, _y)
def create_and_plot_vent(_x, _y):
vent = VentBody(_x, _y)
vent_radius = VentilationCoverage(_x, _y)
plot_shape_graphics(vent.rectangle)
plot_shape_graphics(vent_radius.show_as_circle())
def calculate_vents_per_wall_length(distance, step):
vents = math.ceil((abs(distance) / abs(step)))
return vents
def user_input():
print("Hello Mr. Lagzdiņš, \n please insert how big your building you wish to be: \n (in meters)")
while True:
x = input("please insert the width of the building:")
if confirm_valid_input(x):
break
while True:
y = input("please insert the length of the building:")
if confirm_valid_input(y):
break
return int(x), int(y)
def confirm_valid_input(input_string):
if input_string.isdigit():
return True
print("Please only insert digits")
return False
def check_if_vent(polygon, coordinate_tuple):
if polygon.contains(Point(coordinate_tuple)):
return True
return False
class VentCalculator:
def __init__(self, building_dimensions=user_input()):
self.width_height = building_dimensions
self.room_width = 25
self.vertical_overlap_distance = 54
self.ventilated_area_radius = 30
self.building = Building(self.width_height)
if building_dimensions[0] < building_dimensions[1]:
self.height = building_dimensions[0]
self.building_width = building_dimensions[1]
else:
self.height = building_dimensions[1]
self.building_width = building_dimensions[0]
self.number_of_rooms = math.ceil(self.building_width / self.room_width)
self.rows = calculate_vents_per_wall_length((
self.height + self.ventilated_area_radius), self.vertical_overlap_distance)
self.vents = 0
self.non_vents = 0
def iterate_rooms(self):
for i in range(self.number_of_rooms):
if i == range(self.number_of_rooms)[-1]:
room_width = self.building_width % 25 if self.building_width % 25 != 0 else 25
else:
room_width = self.room_width
horizontal_offset = i * 25
room = Building((room_width, self.height), horizontal_offset)
plot_shape_graphics(room.rectangle)
self.distribute_vents(horizontal_offset)
def distribute_vents(self, horizontal_offset):
for row in range(self.rows):
coordinate_x = horizontal_offset + 12.5
if coordinate_x > self.building_width:
coordinate_x = self.building_width
coordinate_y = self.vertical_overlap_distance * row
if coordinate_y > self.height:
coordinate_y = self.height
create_and_plot_vent(coordinate_x, coordinate_y)
self.increment_vents(coordinate_x, coordinate_y)
def increment_vents(self, coordinate_x, coordinate_y):
if check_if_vent(self.building.rectangle, (coordinate_x, coordinate_y)):
self.vents += 1
else:
self.non_vents += 1
if __name__ == '__main__':
calc = VentCalculator()
calc.iterate_rooms()
print("There are " + str(calc.vents) + " vents.")
print("And " + str(calc.non_vents) + " windows or doors.")
print("Total sum =", calc.vents * 40 + calc.non_vents * 10, "EUR")
plt.show()
|
810a16454af623da8ccca0ac6d47e16de273bf12 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2_neat/16_0_2_Duy_revenge-of-the-pancakes.py | 1,449 | 3.796875 | 4 | #!python2.7
# Standard libs
import argparse
def get_min_flips(stack):
if not stack or '-' not in stack:
return 0
# Truncate the happy bottom of the stack
last_blank_index = stack.rindex('-')
part_we_still_need_to_flip = stack[:last_blank_index + 1]
# If the top of the stack is blank, we can make progress by flipping the
# entire rest of the stack. The run of blanks at the top will become a
# run of happy pancakes at the bottom.
if part_we_still_need_to_flip[0] == '-':
flipped = flip(part_we_still_need_to_flip)
return 1 + get_min_flips(flipped)
# Otherwise, we have a run of happy pancakes at the top. Flip those and
# we'll recurse into the first case in the next cycle.
first_blank_index = stack.index('-')
half_to_flip = part_we_still_need_to_flip[:first_blank_index]
half_to_not_flip = part_we_still_need_to_flip[first_blank_index:]
return 1 + get_min_flips(flip(half_to_flip) + half_to_not_flip)
def flip(stack):
return ''.join(['+' if p == '-' else '-' for p in stack[::-1]])
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input_file')
args = parser.parse_args()
with open(args.input_file) as f:
num_cases = f.readline()
for i, line in enumerate(f, start=1):
stack = line.strip()
print "Case #%d: %d" % (i, get_min_flips(stack))
if __name__ == "__main__":
main()
|
6df12eeedf2576ffa1172f783f848f8c7286ef88 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x13-qa_bot/1-loop.py | 419 | 4.25 | 4 | #!/usr/bin/env python3
"""
Create the loop
Script that takes in input from the user with the prompt Q:
and prints A: as a response.
If the user inputs exit, quit, goodbye, or bye, case insensitive,
print A: Goodbye and exit
"""
cases = ['exit', 'goodbye', 'bye']
while True:
ans = input('Q: ')
ans = ans.lower()
if ans in cases:
print('A: Goodbye')
exit(0)
else:
print('A: ')
|
47d9ef2eb60adbe870fa4d9f23427dbfa9d7f282 | LucasLeone/mochila-de-recursos | /ex4.py | 422 | 3.9375 | 4 | """
Determinar la palabra mas grande
(indicar criterios)
"""
print('El criterio para determinar la palabra mas grande es por la cantidad de letras.')
texto = input('Ingrese un texto: ')
palabras = texto.split(' ')
mayor = 'a'
for i in range(0, len(palabras)):
if i == 0:
mayor = palabras[0]
if len(palabras[i]) > len(mayor):
mayor = palabras[i]
print(f'La palabra mayor es: {mayor}') |
76a395da2ef8ad2df665a088cb06254063d93dcc | mohitgaggar/BullsandRights | /game.py | 1,017 | 3.6875 | 4 | a=input("Enter the string")
s=list(a)
import os
def cl():
os.system('cls')
flag=False
cl()
count=0
k=[]
q=[]
while flag!=True and count<len(s)*3:
print("Guess a",len(s),"letter word")
string=input()
if string=='igiveup':
print("The word was:",a)
break
if len(s)!=len(string):
print("Please enter valid word")
else:
l=list(string)
count+=1
bull=0
right=0
if l==s:
print("Hogaya Bhai!")
print("Chances taken=",count)
flag=True
else:
q=[]
for i in range(len(l)):
if l[i]==s[i]:
bull+=1
q.append(i)
w=[i for i in s]
for i in q:
w[i]='#'
l[i]='*'
for i in range(len(l)):
if l[i] in w:
right+=1
w.remove(l[i])
print("Rights=",right,end=' ')
print("Bulls=",bull)
cl()
print("All words guessed are:")
k.append(string+' rights = '+str(right)+' Bulls = '+str(bull))
for i in k:
print(i)
if(flag!=True and count>=len(s)*3):
print("Failed!")
|
0e9d57bfa49325be30cb66a9194aab74a2ffa9b1 | NielXu/algo | /greedy/shortest_path.py | 1,563 | 4.21875 | 4 | """
Problem:
Shortest path
Find the shortest paths from a given vertex to all
other vertices in the graph G.
Ideas:
We can solve this problem by the Dijkstra's algorithm.
Running Time:
O(|V|*|E|) where V is vertices and E is edges
Addition:
The following implementation uses list and dict for
storing data. A better implementation would be using
heap to perform extract_min, and change_key. In that
way, the running time can be reduced to O((|V|+|E|)log|V|).
"""
import math
def get_edges(s, e):
result = []
for i in e:
if i[0] == s:
result.append(i)
return result
def min_d(d, v, r):
m = None
for i in v:
if i not in r:
if not m:
m = i
else:
m = m if d[m] < d[i] else i
return m
def dijkstra_shortest_path(s, v, e):
r = []
d = {}
for i in v:
d[i] = math.inf
d[s] = 0
dep = 0
while len(r) != len(v):
node = min_d(d, v, r)
r.append(node)
for edge in get_edges(node, e):
start, end, wt = edge
if d[end] > d[node] + wt:
d[end] = d[node] + wt
return d
wt = dijkstra_shortest_path(
'a',
['a', 'b', 'c', 'd', 'e', 'f'],
[
('a', 'b', 1),
('a', 'c', 6),
('a', 'd', 4),
('b', 'c', 2),
('b', 'e', 1),
('c', 'b', 1),
('c', 'd', 2),
('c', 'f', 2),
('d', 'c', 1),
('d', 'f', 1),
('e', 'f', 4),
('f', 'd', 3),
('f', 'e', 1)
]
)
print(wt) |
ae13e64db7916ad89052f5bf6901771f5b91303d | stagadimples/hangman | /hangman.py | 997 | 3.71875 | 4 | import random
class Hangman:
words = [
'keyboard',
'comb',
'apple',
'table',
'house',
'bulldozer',
'hat',
'window',
'glue',
'bed',
'sticker',
'computer',
'snake',
]
incorrect = 0
def wordChoice(self):
self.current = self.words[random.randint(0, 12)]
self.ref = list(self.current)
def guess(self):
wordLength = len(self.ref)
self.blank = list('_' * wordLength)
while str(self.blank).find('_') != -1:
self.letter = input('Guess: ')
if self.letter not in self.ref:
self.incorrect += 1
else:
position = [pos for pos, letter in enumerate(self.ref) if letter == self.letter]
self.blank[position[0]] = self.letter
self.ref[position[0]] = '_'
print(str(self.blank))
hangman = Hangman()
hangman.wordChoice()
hangman.guess()
|
0564aa8eab4631210b6426b0b7233ed8c804ac58 | tomaszkajda/wdi2020-2021 | /wdi1/cw3.py | 670 | 3.921875 | 4 | #Zadanie 3. Proszę napisać program sprawdzający czy istnieje spójny podciąg ciągu Fibonacciego o zadanej
#sumie.
sum = 20
first1 = 1
first2 = 1
current1 = 1
current2 = 1
result = 1 #suma podciągu
if result != sum:
while result < sum:
result += current2 #dodajemy wyraz z prawej strony
current1, current2 = current2, current1 +current2 #ciąg fib
while result > sum:
result -= first1 #odejmujemy wyraz z lewej strony
first1, first2 = first2, first1 + first2 #ciąg fib
if first2==current2:
print('nie istnieje!')
exit(0)
print('istnieje!')
|
091b1538b90818390967896c38806e01c4122389 | pocokim/algo | /python/elice/chapter2/mission/1_findDifference.py | 1,802 | 3.703125 | 4 | def findDifference(str1, str2):
dic= {}
for ch in str2:
dic[ch] = dic.get(ch,0) + 1
# for ch in str2:
# if ch not in dic :
# return ch
# 딕셔너리만 가지고 if문을 사용할 수 있을까? : z와 같은 다른 원소가 포함된 경우 사용가능 할 수 있지만 , 추가된 원소가 p일경우 잡을 수 없다고 생각함.
for ch in str1:
if ch in dic :
dic[ch] -= 1
for ch in str2:
if dic[ch] ==1:
return ch
# 리스트 사용
# str1List = list(str1)
# str2List = list(str2)
# str1List.sort()
# str2List.sort()
# str1List.append('~')
# for i in range(len(str2List)):
# if str2List[i] != str1List[i]:
# return str2List[i]
# 풀이 2 딕셔너리 사용
# dic = {}
# for ch in str1:
# dic[ch] = dic.get(ch,0) + 1
# for ch in str2:
# if ch not in dic:
# return ch
# str1List = list(str1)
# str2List = list(str2)
# str1List.sort()
# str2List.sort()
# print(str1List)
# print(str2List)
# print(str2List[1])
# print(str2List[2])
# IndexError: list index out of range 배열 범위 문제가 계속 생김. 마지막 배열에 값을 넣어주어야할듯..
# elif str1List[i] != str2List[i]: 애초에 값에 i가 들어가지않음.
# for i in range(len(str2List)):
# if i == len(str1List) and str1List[i] == str2List[i]:
# return str2List[-1]
# elif str1List[i] != str2List[i]:
# # print(str2List[i])
# return str2List[i]
def main():
print(findDifference("apple", "aplppe"))
if __name__ == "__main__":
main()
|
45e2de7458ac70d042da70772157af3382c5d58c | TestAnalyst1/python-challenge | /PyBank/main.py | 3,065 | 3.828125 | 4 | import os,csv
from pathlib import Path
# Path to collect data from the Resources folder
budget_data_csv = os.path.join("budget_data.csv")
# def print_bankdata(dataRow):
# # The total number of months included in the dataset
# # total_no_of_months = len(dataRow[0])
# # print (" The total number of months = " + total_no_of_months)
# months = ','.join(dataRow[0])
# print(months)
# # The net total amount of "Profit/Losses" over the entire period
# # The average of the changes in "Pro[fit/Losses" over the entire period
# # The greatest increase in profits (date and amount) over the entire period
# # The greatest decrease in losses (date and amount) over the entire period
#Create empty lists
total_months = []
total_profit = []
monthly_profit_change = []
# Read in the CSV file
with open(budget_data_csv, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
# months_count = sum(1 for row in csvreader)
# print (months_count)
for row in csvreader:
total_months.append(row[0])
total_profit.append(int(row[1]))
# Iterate through the profits in order to get the monthly change in profits
for i in range(len(total_profit)-1):
# Take the difference between two months and append to monthly profit change
monthly_profit_change.append(total_profit[i+1]-total_profit[i])
# Obtain the max and min of the the montly profit change list
max_increase_value = max(monthly_profit_change)
max_decrease_value = min(monthly_profit_change)
max_increase_month = monthly_profit_change.index(max(monthly_profit_change)) + 1
max_decrease_month = monthly_profit_change.index(min(monthly_profit_change)) + 1
# Print Statements
print("----------------------------")
print(f"Total Months: {len(total_months)}")
print(f"Total: ${sum(total_profit)}")
print(f"Average Change: ${round(sum(monthly_profit_change)/len(monthly_profit_change),2)}")
print(f"Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_value))})")
print(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_value))})")
# Output files
output_file = os.path.join("Analysis_Summary.txt")
with open(output_file,"w") as file:
# Write methods to print to Financial_Analysis_Summary
file.write("Financial Analysis")
file.write("\n")
file.write("----------------------------")
file.write("\n")
file.write(f"Total Months: {len(total_months)}")
file.write("\n")
file.write(f"Total: ${sum(total_profit)}")
file.write("\n")
file.write(f"Average Change: {round(sum(monthly_profit_change)/len(monthly_profit_change),2)}")
file.write("\n")
file.write(f"Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_value))})")
file.write("\n")
file.write(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_value))})")
|
68ab3477e173475bfa13ac9a59d762aaa100333a | TOFUman404/Python | /Hello.py | 875 | 3.921875 | 4 | d=int(input())
h=int(input())
m=int(input())
if d == 1:
day = "sunday"
if d == 2:
day = "monday"
if d == 3:
day = "tuesday"
if d == 4:
day = "wednesday"
if d == 5:
day = "thursday"
if d == 6:
day = "friday"
if d == 7:
day = "saturday"
if (h == 4 and m > 0 or h > 4 and h < 12 or h == 12 and m ==0):
time = "morning"
elif h >= 12 and h < 18 or h == 18 and m == 0:
if (h == 12 and m > 0 or h >= 12 and h <= 18) and m < 60:
time = "afternoon"
elif h >= 18 and h < 22 or h == 22 and m == 0:
if (h == 18 and m > 0 or h == 22 and m == 0 or h >= 18 and h <= 22) and m < 60:
time = "evening"
elif h >= 22 and h <= 24 or h >= 0 and h < 4 or h == 4 and m == 0:
if (h == 22 and m > 0 or h == 4 and m == 0 or h >= 22 and h <= 24 or h >= 0 and h <= 4) and m < 60:
time = "night"
print("good-%s-%s.png" % (time,day))
|
bcaaa34ea1bcb4ccac269ac3f7bc20a0552a90db | derekjanni/derekjanni.github.io | /pyocr/app.py | 1,525 | 3.578125 | 4 | import flask
from sklearn.linear_model import LogisticRegression
import numpy as np
import pandas as pd
#---------- MODEL IN MEMORY ----------------#
# Read the scientific data on breast cancer survival,
# Build a LogisticRegression predictor on it
patients = pd.read_csv("haberman.data", header=None)
patients.columns=['age','year','nodes','survived']
patients=patients.replace(2,0) # The value 2 means death in 5 years
X = patients[['age','year','nodes']]
Y = patients['survived']
PREDICTOR = LogisticRegression().fit(X,Y)
#---------- URLS AND WEB PAGES -------------#
# Initialize the app
app = flask.Flask(__name__)
# Homepage
@app.route("/")
def viz_page():
"""
Homepage: serve our visualization page, awesome.html
"""
with open("index.html", 'r') as viz_file:
return viz_file.read()
# Get an example and return it's score from the predictor model
@app.route("/score", methods=["POST"])
def score():
"""
When A POST request with json data is made to this uri,
Read the example from the json, predict probability and
send it with a response
"""
# Get decision score for our example that came with the request
data = flask.request.json
x = np.matrix(data["example"])
score = PREDICTOR.predict_proba(x)
# Put the result in a nice dict so we can send it as json
results = {"score": score[0,1]}
return flask.jsonify(results)
#--------- RUN WEB APP SERVER ------------#
# Start the app server on port 80
# (The default website port)
app.run()
|
201bd8e0c439acd8e10847460b89fd459ca293ea | charanchakravarthula/python_practice | /lists.py | 1,250 | 4.21875 | 4 | # nuemeric data types int float and complex
integer_var=-1
float_var=1.0
complex_var=1+2j
print(type(integer_var),type(float_var),type(complex_var),sep="\n")
# playing with list
# creating an empty list
list_var=[]
# creating a list with some values
list_var2=[1,2,'a']
# adding elements to a list
list_var2.append(4)
# adding elements to a list dynamically
for i in range(5):
list_var.append(i)
print(list_var)
print(list_var2)
# removing last element from the list
list_var.pop()
print(list_var)
# removing an element at particular index
list_var.pop(2)
print(list_var)
# removing a given element
list_var2.remove('a')
print(list_var2)
# updating an element at particular index
list_var2[0]='ab'
print(list_var2)
# merging to lists
list_var.extend(list_var2)
print(list_var)
# insert a value at particular index
list_var.insert(1,"new")
print(list_var)
# getting the length or size of the list
print(len(list_var))
# clearing the list
list_var2.clear()
# deleting values at particular index range
del list_var[0:3]
print(list_var)
# nested list
list_var.append([2,3,4,5,6,7,9])
print(list_var)
# traversing over a list
for i in list_var:
print(i)
for i in range(0,len(list_var)):
print(list_var[i])
|
9d76bd12cfc6b0faf8fd3158e5db4908ac5117bc | silviordjr/exercicios-python | /contaSegundos/conta_segundos.py | 375 | 3.78125 | 4 | segundos = int(input("Por favor, entre com o número de segundos que deseja converter: "))
dias = segundos // (3600 * 24)
segundos = segundos - dias * (3600 * 24)
horas = segundos // 3600
segundos = segundos - horas * 3600
minutos = segundos // 60
segundos = segundos - minutos * 60
print(dias, "dias, ", horas, "horas, ", minutos, "minutos e ", segundos, "segundos")
|
d4f2ceff37d2b801cbb554d13f4c3c8b4c6982c7 | alewang/Projects | /python/numbers/next-prime.py | 324 | 3.765625 | 4 | #!/usr/bin/env python
import primes
primeList = [];
index = 0;
keepGoing = True;
while keepGoing:
inp = raw_input("Enter q to quit: ");
if inp == 'q':
keepGoing = False;
else:
if index == len(primeList):
primes.genPrimes(primeList);
print primeList[index];
index += 1;
print "Program complete. Exiting..."
|
8837f0ec30cae7dde823c85add9c5ceee14d1da1 | conanjm/Introduction-to-Computer-Science-and-Programming-Using-Python | /Problem-Set-1/countingBob.py | 260 | 4.0625 | 4 | '''
prints the number of times the string 'bob' occurs in s
'''
s = 'bobobobbob'
counter = 0
for s1 in range(0,len(s)+1):
for s2 in range(s1,len(s)+1):
if s[s1:s2] == "bob":
counter += 1
print 'Number of times bob occurs is:', counter
|
931d0ac4d8f5a209c03a4ae36e1bddcb64f426fc | RubenBS7/Cuatro-en-linea | /src/CuatroEnLinea.py | 6,309 | 3.65625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import math
import sys
import numpy as np
import pygame
#instalar numpy y pygame para interfaz de las matrices y la interface grafica (mediante la consola de comandos)
# pip install numpy y pip install pygame
NUM_FILA = 6
NUM_COLUMNA = 7
AMARILLO = (242, 230, 12)
ROJO = (219, 33, 0)
AZUL = (4, 76, 242)
NEGRO = (51, 35, 98)
# Crea el tablero (Matriz de 6 filas x 7 columnas)
def crear_tablero():
tablero = np.zeros((NUM_FILA,NUM_COLUMNA))
return tablero
def insertar_ficha(tablero, fila, col, ficha):
tablero[fila][col] = ficha
#Comprueba si esa posicion es ocupada por una ficha o no.
def validar_posicion(tablero, col):
return tablero[NUM_FILA-1][col] == 0
def obtener_siguiente_fila(tablero, col):
for r in range(NUM_FILA):
if tablero[r][col] == 0:
return r
def imprimir_tablero(tablero):
print(np.flip(tablero,0))
def movimiento_ganador(tablero, ficha):
#comprobar las posiciones HORIZONTALES para ganar la partida
for c in range(NUM_COLUMNA -3):
for r in range(NUM_FILA):
if tablero[r][c] == ficha and tablero[r][c+1] == ficha and tablero[r][c+2] == ficha and tablero[r][c+3] == ficha:
return True
#comprobar las posiciones VERTICALES para ganar la partida
for c in range(NUM_COLUMNA):
for r in range(NUM_FILA-3):
if tablero[r][c] == ficha and tablero[r+1][c] == ficha and tablero[r+2][c] == ficha and tablero[r+3][c] == ficha:
return True
#comprobar las posiciones Positivas de DIAGONALES para ganar la partida
for c in range(NUM_COLUMNA -3):
for r in range(NUM_FILA-3):
if tablero[r][c] == ficha and tablero[r+1][c+1] == ficha and tablero[r+2][c+2] == ficha and tablero[r+3][c+3] == ficha:
return True
#comprobar las posiciones Negativas de DIAGONALES para ganar la partida
for c in range(NUM_COLUMNA -3):
for r in range(3, NUM_FILA): #ese 3 indica apartir de que fila seria posible
if tablero[r][c] == ficha and tablero[r-1][c+1] == ficha and tablero[r-2][c+2] == ficha and tablero[r-3][c+3] == ficha:
return True
def dibujar_tablero(tablero):
for c in range(NUM_COLUMNA):
for r in range(NUM_FILA):
#Dibujamos el rectangulo azul del tablero y le doy una posicion
pygame.draw.rect(pantalla, AZUL, (c*tamanioTablero, r*tamanioTablero+tamanioTablero, tamanioTablero, tamanioTablero))
#Dibjuamos los circulos en el rectangulo azul ya creado
pygame.draw.circle(pantalla, NEGRO,(int(c*tamanioTablero+tamanioTablero/2), int(r*tamanioTablero+tamanioTablero+tamanioTablero/2)), radio)
for c in range(NUM_COLUMNA):
for r in range(NUM_FILA):
if tablero[r][c] == 1:
pygame.draw.circle(pantalla, ROJO,(int(c*tamanioTablero+tamanioTablero/2), altura-int(r*tamanioTablero+tamanioTablero/2)), radio)
elif tablero[r][c] == 2:
pygame.draw.circle(pantalla, AMARILLO,(int(c*tamanioTablero+tamanioTablero/2), altura-int(r*tamanioTablero+tamanioTablero/2)), radio)
pygame.display.update()
tablero = crear_tablero()
imprimir_tablero(tablero)
game_over = False
turno = 0
#Definimos el tamaño de la ventana
pygame.init()
tamanioTablero = 100
ancho = NUM_COLUMNA * tamanioTablero
altura = (NUM_FILA+1) * tamanioTablero
medidas = (ancho,altura)
radio = int(tamanioTablero/2 - 5)
pantalla = pygame.display.set_mode(medidas)
dibujar_tablero(tablero)
pygame.display.update()
fuente = pygame.font.SysFont("monospace", 75) #asignamos el estilo y tamaño la letra.
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#Dibujamos las fichas segun el turno en la parte superior del tablero
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(pantalla,NEGRO, (0, 0, ancho, tamanioTablero))
posx = event.pos[0]
if turno == 0:
pygame.draw.circle(pantalla, ROJO, (posx, int(tamanioTablero/2)), radio)
else:
pygame.draw.circle(pantalla, AMARILLO, (posx, int(tamanioTablero/2)), radio)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(pantalla,NEGRO, (0, 0, ancho, tamanioTablero))
#print(event.pos)
j1 = 0
j2 = 0
#Preguntar por turno del jugador 1
if turno == 0:
posx = event.pos[0]
col = int(math.floor(posx/tamanioTablero)) #almacenamos en la posicion del click una ficha (en esye caso un entero)
if validar_posicion(tablero, col):
fila = obtener_siguiente_fila(tablero, col)
insertar_ficha(tablero, fila, col, 1)
if movimiento_ganador(tablero, 1):
label = fuente.render("JUGADOR 1 GANA!!!", 1, (ROJO)) #imprimos cuando gana
pantalla.blit(label, (40, 10)) #posicion de donde se va a ver en la pantalla
game_over = True
#Preguntar por turno del jugador 2
else:
posx = event.pos[0]
col = int(math.floor(posx/tamanioTablero))
if validar_posicion(tablero, col):
fila = obtener_siguiente_fila(tablero, col)
insertar_ficha(tablero, fila, col, 2)
if movimiento_ganador(tablero, 2):
label = fuente.render("JUGADOR 2 GANA!!!", 1, (AMARILLO)) #imprimos cuando gana
pantalla.blit(label, (40, 10)) #posicion de donde se va a ver en la pantalla
game_over = True
imprimir_tablero(tablero)
dibujar_tablero(tablero)
turno +=1
turno = turno % 2 #Hacemos el mod de turno para que vaya alternando entre J1 y J2
pygame.time.wait(4000) |
5fba451353d1d134d7e57b4c6b99c5e2fbe1ecd0 | Hegemony/Python-Practice | /LeetCode practice/Other/501.findMode.py | 693 | 3.71875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findMode(self, root: TreeNode):
if not root:
return []
# 第一想法是哈希表记录
Hash = {}
def dfs(root, Hash):
if not root:
return
Hash[root.val] = Hash.get(root.val, 0) + 1
dfs(root.left, Hash)
dfs(root.right, Hash)
dfs(root, Hash)
mode = max(Hash.values())
return [key for key in Hash.keys() if Hash[key] == mode] |
abf9de670d9119e77b0ff6fc6081b13d6e06ff23 | mottaquikarim/pydev-psets | /pset_loops/loop_basics/p4.py | 335 | 4.34375 | 4 | """
Factorial
"""
# Find the factorial of a number input by a user. Then print out the factors within the factorial and then print out the actual numeric answer. Hint: The formula for a factorial is n! = (n-1)*n.
# Example output:
"""
8! = 8*7*6*5*4*3*2*1
8! = 40320
"""
user_input = input('Enter a number to find its factorial: ') |
5995d45cefcd88ffd2b1b4b123dfe427b4aae063 | tarantot/Final_task | /add_to_final_task_DB.py | 1,109 | 3.8125 | 4 | import sqlite3
import datetime
def add_to_final_task_DB():
for personal_ID = 0:
personal_ID+=1
emp_age = datetime.emp_bdate - datetime.date.today()
emp_sex = emp_sex.upper()
if emp_sex is not 'М' is not 'Ж':
print('Пожалуйста выберите корректное значение!')
for emp_phonenumber != 0:
data = json.load(open('countries&codes.json'))
for name in data['countries&codes'].items():
if emp_phonenumber==dial_code:
reply = input('Are you from {0}? Y / N'.format(name))
if reply=='Y':
emp_phonenumber = input('Please type your phone number with the country code +XXX : ')
else:
emp_phonenumber = input('Please type your valid phone number! ')
conn = sqlite3.connect("final_task_DB.db")
cursor = conn.cursor()
cursor.execute("""INSERT into employees VALUES (personal_ID, emp_full_name, emp_sex, emp_age, emp_phonenumber)""" )
conn.commit()
cursor.close()
conn.close()
final_task_DB()
|
ade282e3ba387f4fb1bf31a56f78a22b42862e0e | nisacchimo/challenge | /ch6_2.py | 223 | 3.875 | 4 | #http://tinyurl.com/hapm4dx
word1 = input("昨日書いたものは?:")
word2 = input("送付した人は?:")
message = "私は昨日、{}を書いて{}に送った!".format(word1,word2)
print(message)
|
b415872dca06c52afa8b64b54d28ea709a06723d | frclasso/python_examples_two | /newtontest.py | 131 | 3.71875 | 4 | #!/usr/bin/python
from newton import *
print("Enter a number: ")
number = int(input())
print(sqrt(number))
print(average(144, 9)) |
d73d39936d5cd96467423de8e7d2fcdc6718d17b | bluella/hackerrank-solutions-explained | /src/Arrays/Arrays: Left Rotation.py | 1,066 | 4.71875 | 5 | #!/usr/bin/env python3
"""
https://www.hackerrank.com/challenges/ctci-array-left-rotation
A left rotation operation on an array shifts each of the array's elements 1 unit to the left.
For example, if 2 left rotations are performed on array [1, 2, 3] then the array would become
[3, 2, 1]
Given an array
of integers and a number n perform n left rotations on the array.
"""
import math
import os
import random
import re
import sys
#
# Complete the 'rotLeft' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER_ARRAY a
#
def rotate_once(arr):
'''First to Last'''
arr.append(arr[0])
del arr[0]
def rotLeft(arr, n_rotations):
"""
Args:
arr (list): list of numbers.
n_rotations (int): rotate arr n times
Returns:
list: changed arr"""
for i in range(n_rotations):
rotate_once(arr)
return arr
if __name__ == "__main__":
ex_arr = [1, 2, 3]
rotations = 1
result = rotLeft(ex_arr, rotations)
print(result)
|
456fe93eb9e3d9e3d3f94538c1c0afd1c2734b77 | rafaelperazzo/programacao-web | /moodledata/vpl_data/10/usersdata/61/10344/submittedfiles/testes.py | 192 | 3.984375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a=input('Digite o valor de a: ')
if (a%3)==0:
print ('a é multiplo de 3')
else:
print ('a não é multiplo de 3')
|
5ad20eef5ff45a3903c5fed3ed2f669bd99cac70 | facufrau/beginner-projects-solutions | /solutions/magic_8ballgui.py | 2,986 | 4.40625 | 4 | # Beginner project 3.
'''
Simulate a magic 8-ball.
Allow the user to enter their question.
Display an in progress message(i.e. "thinking").
Create 20 responses, and show a random response.
Allow the user to ask another question or quit.
Bonus:
Add a gui.
It must have box for users to enter the question.
It must have at least 4 buttons:
ask
clear (the text box)
play again
quit (this must close the window)
'''
from time import sleep
from random import choice
import tkinter as tk
from tkinter import messagebox
def ask():
"""Ask the question to the magic ball and insert the
answer into lbl_answer.
"""
answers = ['It is certain.', ' It is decidedly so.', 'Without a doubt', 'Yes-definitely',
'You may rely on it.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Yes.',
'Signs point to yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not tell you now.',
'Cannot predict now.', 'Concentrate and ask again.', 'Don\'t count on it.', 'My reply is no.',
'My sources say no.', 'Outlook not so good.', 'Very doubtful.']
question = ent_question.get()
if question:
lbl_answer["text"] = f'{choice(answers)}'
btn_ask["state"] = 'disabled'
else:
messagebox.showwarning(message="Question field empty!", title="Empty field")
def clear():
"""
Clear and enable the text box.
"""
ent_question.delete(0, 'end')
def play_again():
"""
Clear answer label and enable the ask button to play again.
"""
lbl_answer["text"] = ''
btn_ask["state"] = 'normal'
def close():
"""
Exits the program.
"""
window.destroy()
window = tk.Tk()
window.title('Magic ball')
# Create a question frame: label and entry
frm_question = tk.Frame(master=window)
ent_question = tk.Entry(master=frm_question,state='normal', width=60)
lbl_question = tk.Label(master=frm_question, text='Your question: ')
# Create buttons frame and organize.
frm_buttons = tk.Frame(master=window)
btn_ask = tk.Button(frm_buttons, state='normal', text='Ask!', command=ask)
btn_clear = tk.Button(frm_buttons, text='Clear text box', command=clear)
btn_again = tk.Button(frm_buttons, text='Play again', command=play_again)
btn_quit = tk.Button(frm_buttons, text='Quit', command=close)
btn_ask.grid(row=0, column=0, padx=20, pady=10)
btn_clear.grid(row=0, column=1, padx=20, pady=10)
btn_again.grid(row=0, column=2, padx=20, pady=10)
btn_quit.grid(row=0, column=3, padx=20, pady=10)
# Create answer label.
lbl_answer = tk.Label(master=window, text='')
# Organize question entry and label, and answer label.
ent_question.grid(row=0, column=1, sticky='w')
lbl_question.grid(row=0, column=0, sticky='e')
lbl_answer.grid(row=1, column=0, padx=10, sticky='nw')
# Organize question and buttons frame.
frm_question.grid(row=0, column=0, padx=10)
frm_buttons.grid(row=2, column=0, padx=10)
# Execute main loop.
window.mainloop()
|
04a6ad3fe0df6cc55e995b105e9704d8350b8670 | tayabsoomro/CMPT317-GroupProject | /A1/src/unique.py | 965 | 3.703125 | 4 | import copy
"""
UniqueHashable class implementation. UniqueHashable implemented due to
requirements of uniqueness of states in Python dictionaries. Particular
classes can be made unique hashable by hashing the arguments, keyword
arguments, and class itself.
Authors: Mahmud Ahzam*, Tayab Soomro*, Flaviu Vadan*
Class: CMPT317
Instructor: Michael Horsch
Assignment: 1
* - all authors equally contributed to the implementation
"""
UNIQUE_INSTANCES = {}
class UniqueHashable:
def __new__(cls, *args, **kwargs):
if (args,cls) in UNIQUE_INSTANCES:
return UNIQUE_INSTANCES[(args,cls)]
else:
inst = super(UniqueHashable, cls).__new__(cls)
inst.__init__(*args, **kwargs)
UNIQUE_INSTANCES[(args,cls)] = inst
return inst
class Ab(UniqueHashable):
def __init__(self, a, b):
self.a = a
self.b = b
def __hash__(self):
return hash((self.a, self.b))
|
019ba9d216414b5bd2f7ea60c0ca379727c547ed | TorNATO-PRO/WA_COVID_DATA_TRACKER | /data_grabber.py | 2,059 | 3.734375 | 4 | from os import getcwd
from os import mkdir
from os import path
import requests
# Downloads a file from a url, saves it in
# a specified directory within the working
# directory with a given name
def download_file(url, directory, name):
# tries to get the requested file, exits if unable to do so
try:
requested_file = requests.get(url)
except requests.exceptions.Timeout:
print('Connection Timeout!')
return
except requests.exceptions.TooManyRedirects:
print('Too many redirects!')
return
except requests.exceptions.RequestException:
print('Failed to connect to the server, check your internet connection!')
return
else:
# verify that the file has been found at the given url
if requested_file:
print(f'Successfully found the file at the given url: {url}')
else:
print(f'An error has occurred while downloading the file, status code: {requested_file.status_code}')
return
file_dir = create_directory(directory)
file_name_with_directory = path.join(file_dir, name)
# writes the dataset to a file with the following format
# COVID-19_DATA_WASHINGTON_mm-dd-YYYY_hh_mm_ss
open(file=file_name_with_directory, mode='wb').write(requested_file.content)
print(f'Wrote the file: {file_name_with_directory}')
return file_name_with_directory
# Creates a directory with a specified name
# in the current working directory
def create_directory(directory_name):
# creates the directory at the current working directory
corrected_directory_name = f'{getcwd()}/{directory_name}'
if not path.isdir(corrected_directory_name):
try:
mkdir(corrected_directory_name)
except OSError:
print(f'Something went wrong! Unable to create directory {corrected_directory_name}')
return
else:
print(f'Successfully created the directory {corrected_directory_name}')
return corrected_directory_name
|
4a745dfc1a77fbff7346144809cd39018a62829c | cymerrad/aoc | /2019/1.py | 543 | 3.578125 | 4 | #!/usr/bin/python3
fuel_sum = 0
def fuel_for_mass(mass):
fuel = mass//3 - 2
if fuel < 0:
return 0
return fuel
def true_fuel_for_mass(mass):
if mass <= 0:
return 0
req = fuel_for_mass(mass)
return req + true_fuel_for_mass(req)
with open("input1") as fr:
for line in fr:
fuel_sum += true_fuel_for_mass(int(line.strip()))
print(fuel_sum)
# tests
cases = [(14,2), (1969,966), (100756, 50346)]
for n, exp in cases:
print(f"For {n} we got {true_fuel_for_mass(n)} and should be {exp}")
|
1400e7ec35a3ca827e6bc3c1a52804dc1e2936a7 | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/03.Estrutura de Repetição/03. validar nomes.py | 2,181 | 4 | 4 | #coding: utf-8
"""
Faça um programa que leia e valide as seguintes informações:
Nome: maior que 3 caracteres;
Idade: entre 0 e 150;
Salário: maior que zero;
Sexo: 'f' ou 'm';
Estado Civil: 's', 'c', 'v', 'd';
"""
cont = 'a'
x = 0
z = 0
n = "A"
i = 151
s = 0
sx = "d"
es = "a"
lf = "S - solteira, C - casada, V - viúva ou D - divorciada: "
lm = "S - solteiro, C - casado, V - viúvo ou D - divorciado: "
while x == 0:
while len(n) <= 3:
n = input("Informe seu nome: ")
if len(n) <= 3:
print("Nome inválido, o nome tem que ter mais que 3 caracteres.")
else:
print("Nome aceito!")
while z == 0:
i = int(input("Informe sua idade: "))
if i >= 0 and i <= 150:
print("Idade aceita!")
z = 1
else:
print("Idade inválida, informe novamente.")
z = 0
while s <= 0:
s = float(input("Informe seu salário: R$ "))
if s <= 0:
print("Salário inválido, informe novamente.")
else:
print("Salário aceito!")
while z == 0:
sx = input("Informe o sexo, F - Feminino ou M - Masculino: ")
sx = sx.upper()
if sx == "F" or sx == "M":
print("Sexo aceito!")
z = 1
else:
print("Sexo inválido, informe novamente.")
z = 0
while z == 0:
if sx == "F":
es = input("Informe o Estado Cívil, " + lf)
elif sx == "M":
es = input("Informe o Estado Cívil, " + lm)
es = es.upper()
if es == "S" or es == "C" or es == "V" or es == "D":
print("Estado Cívil aceito!")
z = 1
if sx == "F":
sx = "Feminino"
if es == "S":
es = "Solteira"
elif es == "C":
es = "Casada"
elif es == "D":
es = "Divorciada"
elif es == "V":
es = "Viúva"
elif sx == "M":
sx = "Masculino"
if es == "S":
es = "Solteiro"
elif es == "C":
es = "Casado"
elif es == "D":
es = "Divorciado"
elif es == "V":
es = "Viúvo"
else:
print("Estado Cívil inválida, informe novamente.")
z = 0
print()
print("Nome :", n)
print("Idade :", str(i))
print(f"Salário : R$ {s:.2f}")
print("Sexo :", sx)
print("Estado Cívil :", es)
print()
cont = input("Deseja validar outro? S - Sim ou N - Não: ")
cont = cont.upper()
n = cont
if cont == "N":
x = 1
input()
|
ae62bb8dda951933e3c902a2f381486bc739158c | lonelycloudy/python_study | /13.8.1-iter.py | 589 | 3.71875 | 4 | #!/usr/local/python/bin/python
#-*-coding:utf-8-*-
for element in [1,2,3]:
print element
for element in (4,5,6):
print element
for key in {'one':1,'two':2}:
print key
for char in "789":
print char
for line in open("/tmp/a.log"):
print line
"""
1
2
3
4
5
6
two
one
7
8
9
The third line:is write by code
"""
s = 'abc'
it = iter(s)
print it
a=0
while(a < 4):
a=a+1
print it.next()
"""
<iterator object at 0xb7ed7a8c>
a
b
c
Traceback (most recent call last):
File "13.8.1-iter.py", line 33, in <module>
print it.next()
StopIteration
"""
|
807d57cd8d1420d99e5463db3863f515648a05c2 | Louis192/Python_Challenge_1 | /function3.py | 375 | 4.28125 | 4 | # The code below will read a file and print out a count of each name inside the file
list_of_names=[]
def Name_count():
for line in open('file3.txt').readlines():
list_of_names.append(line.strip())
count_names=list(set(list_of_names))
for name in count_names:
print(name + ' occurred ' + list_of_names.count(name) + 'times')
Name_count()
|
6bd0e283186e09d270aaaddc31449de810b3b5fc | EvgeniyBudaev/python_learn | / cycles/cards_sum/cards_sum.py | 517 | 3.796875 | 4 | # Мой вариант
current_hand = [2, 3, 4, 10, 'Q', 5]
total = 0
for x in current_hand:
if x == 2 or x == 3 or x == 4 or x == 5 or x == 6:
total += 1
elif x == 7 or x == 8 or x == 9:
total += 0
elif x == 10 or x == 'J' or x == 'Q' or x == 'K' or x == 'A':
total += -1
print(f'total: {total}')
# Решение преподавателя
cards = {2:1, 3:1, 4:1, 5:1, 6:1, 7:0, 8:0, 9:0, 10: -1, 'J':-1, 'Q':-1, 'K':-1, 'A':-1}
result = sum([cards[x] for x in current_hand])
print(f'result: {result}') |
c2eec19443e8762f7f55b047067a289ab7b18503 | NikhilDusane222/Python | /FunctionalPrograms/primeFactorization.py | 341 | 4.125 | 4 | # Prime factorization
number=int(input("Enter the number :"))
def prime_factor(number):
prime_factors=[]
while number>1:
for factor in range(2,number+1):
if number%factor==0:
number=number//factor
prime_factors.append(factor)
return prime_factors
print(prime_factor(number)) |
331213255a2597eb5cdb2e55a174c08cc847e1f4 | Roiw/LeetCode | /Python/258_AddDigits.py | 310 | 3.5625 | 4 | class Solution:
def addDigits(self, num: int) -> int:
if num <= 9: return num
while num > 9:
answer = 0
while num > 0:
answer += num % 10
num = num // 10
if answer > 9: num = answer
return answer
|
edb4d4315bce6c406928bc63853f24e919ed880e | stephenmcnicholas/PythonExamples | /progs/SudokuChecker.py | 456 | 3.8125 | 4 | row = ' '
lst = []
valid = True
while(len(row)>0):
#print(lst)
row = input("Enter a row of nine digitsm then ENTER (or just ENTER to finish): ")
if(row.isdigit()):
lst.append(row)
if(len(lst)<9):
valid = False
else:
for elem in lst:
for i in range(1,10):
if(elem.find(str(i))==-1):
valid = False
break
if(valid):
print("valid sudoku")
else:
print("Invalid sudoku") |
86d8c9b80943d5e739da6b5f9792250657a8616e | TardC/books | /Python编程:从入门到实践/code/chapter-5/favorite_fruits.py | 429 | 4.0625 | 4 | favorite_fruits = ['apple', 'banana', 'watermelon']
if 'apple' in favorite_fruits:
print("You really like apples!")
if 'banana' in favorite_fruits:
print("You really like bananas!")
if 'watermelon' in favorite_fruits:
print("You really like watermelons!")
if 'orange' in favorite_fruits:
print("You really like oranges!")
if 'strawberry' in favorite_fruits:
print("You really like strawberrys!")
|
4c775a9b6a4a7eaf172a4441b079607904b7cc5b | Gchesta/assignment_day_4 | /find_missing.py | 250 | 3.765625 | 4 | def find_missing(list_1, list_2):
#creating sets
set_1 = set(list_1)
set_2 = set(list_2)
if set_1 == set_2:
return 0
#return the symmetric difference and then converts it into a list
else:
return list((set_1 ^ set_2))[0]
|
7b5286c3ed8e9a13bca49af60d01075ffb0fb44c | trvsed/100-exercicios | /ex046.py | 279 | 3.65625 | 4 | from time import sleep
start=str(input('Digite "começar" sem aspas para iniciar a contagem: ')).lower() .strip()
if start == 'começar':
for c in range(10, -1,-1):
print(c)
sleep(1)
print('Feliz ano novo!!!')
else:
print('Entrada Inválida!') |
410436994d50c3b996e5791d3c62a10affc8a697 | NikitaFedyanin/python_tests | /other/lamp_time.py | 1,954 | 3.875 | 4 | """На вход функции дан массив datetime объектов — это дата и время нажатия на кнопку.
Вашей задачей является определить, как долго горела лампочка. Массив при этом всегда отсортирован по возрастанию,
в нем нет повторяющихся элементов и количество элементов всегда четное число (это значит, что лампочка,
в конце концов, будет выключена).
"""
from datetime import datetime
from typing import List
def sum_light(els: List[datetime]) -> int:
"""
how long the light bulb has been turned on
"""
total_light = 0
on = None
for index, action in enumerate(els):
if index % 2 == 0:
on = action
else:
total_light += (action.timestamp() - on.timestamp())
return int(total_light)
if __name__ == '__main__':
assert sum_light([
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
]) == 1220
assert sum_light([
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
datetime(2015, 1, 12, 11, 10, 10),
datetime(2015, 1, 12, 12, 10, 10),
]) == 4820
assert sum_light([
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 0, 1),
]) == 1
assert sum_light([
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 0, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 13, 11, 0, 0),
]) == 86410
print("The first mission in series is completed? Click 'Check' to earn cool rewards!") |
5b9d25bce6edad29ac3a31c4f2cc65e6e5ea9691 | jcastillo7/GP_PRML_demos | /bayesdemo.py | 9,732 | 3.65625 | 4 | import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
def gaussian_process_demo(n=2,m=1000,fits=10):
"""
Using a gaussian process we can evaluate the weights across all measurements
but we cannot plot the most probable weights as they change for each location predicted.
This is what gives the gaussian process its flexibility
"""
#gaussian processes are a bit different compared to the counterpart used in bayesian learning
#the basis function is a "radial basis function" which takes into account only training points, i.e. no
#arbitrary interval is specified, and the number of data points is directly connected to the number of weights
#this is an example of a non-parametric models
return()
def demo_bayes_linear(n=2,m=1000,fits=10,alpha=2,beta=25,xtrain=None):
"""
Linear demo of gaussian process... shown in PRML pg. 155
"""
a0=-0.3
a1=0.5
#sample from function
if xtrain==None:
xtrain=np.random.uniform(-1,1,n)
ytrain=a0+a1*xtrain
#make design matrix
dmat=np.vstack((np.ones((1,n)),xtrain.reshape(1,n)))
PHImat=dmat.transpose()
#Sampling From the Prior (prior is a zero mean gaussian)
#alpha=2 #fixed
#beta=np.square(1.0/0.2) # fixed
c=np.eye(2)*1/alpha
m0=np.array([0,0]).transpose()
prior=np.random.multivariate_normal(m0,c,m)
#Sampling From the posterior (posterior is a gaussian that estimates the weights of the function)
Sninv=np.linalg.inv(c)+beta*np.dot(PHImat.transpose(),PHImat)
mn=beta*np.dot(np.linalg.inv(Sninv),np.dot(np.linalg.inv(c),m0)+np.dot(PHImat.transpose(),ytrain))
posterior=np.random.multivariate_normal(mn,np.linalg.inv(Sninv),m)
#plotting test values
test=np.arange(-1,1,0.1)
testmat=np.vstack((np.ones(test.shape),test))
ytest1=np.dot(posterior[np.random.randint(0,posterior.shape[0],fits),:],testmat)
fig=plt.figure()
ax=fig.add_subplot(111)
for y in ytest1:
ax.plot(test,y)
ax.scatter(xtrain,ytrain)
fig.show()
PHImat=dmat.transpose()
fig2=plot_demo(prior,posterior)
alpha,beta=evidence_func(PHImat,mn,ytrain,PHImat.transpose(),alpha,beta)
print(np.mean(posterior,axis=0))
return(xtrain,alpha,beta,fig,fig2)
def gaussian_basis(s=0.15,n=15,m=1000,fits=20,alpha=2,beta=7,itermax=5,Nbasis=9,plothist=False,demo="sin",xtrain=None):
"""
This uses a gaussian basis function at fixed locations...
i.e. 9 gaussian basis functions at equal intervals in the dataset
example pg. 157
Note:
A direct extension of this regression process is Relevance Vector machines,
-Relevance Vector machines allow the variance imposed of the prior distribution
of the weights to not be fixed-->therefore learning these parameters
results in an alpha for every weight (and results in sparse model as many weights
are driven to zero pg. 345 PRML)
--the changes are minor, but note while alpha is a matrix, beta is still a singular value
"""
if demo=="marathon_demo":
import pods
data=pods.datasets.olympic_marathon_men()
y=data["Y"].reshape(-1,) #size n
if xtrain==None:
xtrain=data["X"].reshape(-1,)#size n
ytrain=y-y.mean()
#makeup test set
xtest=np.linspace(xtrain.min(),xtrain.max(),100) #size n*
xtest.resize((100,1))
else:
#sample from function
if xtrain==None:
xtrain=np.random.uniform(-1,1,n)
xtest=np.arange(-1,1,0.05)
ytrain=np.sin(2*np.pi*xtrain)
#use a non-linear basis function
#in this case RBF=phi(x)=exp((x-mu_j)^2/(2s^2))
if Nbasis == None:
basis_location=xtrain
else:
basis_location=np.linspace(-1,1,Nbasis) #only use if want fixed location
def setRBF(xtrain,s=0.45):
def RBF_(x):
dmat=np.zeros((x.shape[0],np.max(xtrain.shape[0])))
for i in range(len(x)):
for j in range(len(xtrain)):
dmat[i,j]=np.exp(-np.square(np.linalg.norm(x[i]-xtrain[j]))/(2*np.square(s)))
return (dmat)
return(RBF_)
#if you want to use fixed locations for basis
RBF_=setRBF(basis_location,s)
n=len(basis_location)
#make design matrix
dmat=RBF_(xtrain)
PHImat=dmat
#Sampling From the Prior (prior is a zero mean gaussian)
#beta=np.square(1.0/0.2) # fixed
iter=0
fign=plt.figure()
ax1n=fign.add_subplot(121)
ax2n=fign.add_subplot(122)
while iter<itermax:
c=np.eye(n)*1/alpha
m0=np.zeros((n,))
#Our prior is z zero mean gaussian
prior=np.random.multivariate_normal(m0,np.linalg.inv(c),m)
#Sampling From the posterior (posterior is a gaussian that estimates the weights of the function)
Sninv=alpha*np.eye(n)+beta*np.dot(PHImat.transpose(),PHImat)
mn=beta*np.dot(np.linalg.inv(Sninv),np.dot(PHImat.transpose(),ytrain))
#posterior for the weights, i.e. sample all the weights.
posterior=np.random.multivariate_normal(mn,np.linalg.inv(Sninv),m)
alpha,beta=evidence_func(PHImat,mn,ytrain,RBF_(xtrain).transpose(),alpha,beta)
#print("Evidence function suggests set alpha= %.2f" % np.real(alpha))
#print("Evidence function suggests set beta= %.2f" % np.real(beta))
ax1n.scatter(iter+1,alpha)
ax2n.scatter(iter+1,beta)
iter=iter+1
#build testmat, i.e. solving for the testmatrix--> this is transforming all the inputs to gaussian
#space and multiplying by the weights found in the previous step
#the meaning of the weights are unclear in this context as they are weights of transformed data
ax1n.set_ylabel("Alpha vs iter")
ax2n.set_ylabel("Beta vs iter")
fign.show()
testmat=RBF_(xtest).transpose()
ytest1=np.dot(posterior[np.random.randint(0,posterior.shape[0],fits),:],testmat)
#build most likely function, i.e. expected value for the weights
yall=np.dot(posterior,testmat)
ymean=np.mean(yall,axis=0)
#if demo=="marathon_demo":
# ymean=ymean+y.mean()
# ytest1=ytest1+y.mean()
#print(wmean)
#print(testmat.shape())
#ymean=np.dot(wmean,testmat)
fig=plt.figure()
ax=fig.add_subplot(121)
for y in ytest1:
ax.plot(xtest,y)
if demo=="sin":
ax.set_ylim([-3,3])
ax.set_xlim([-1,1])
elif demo=="marathon_demo":
ax.set_xlim([xtrain.min(),xtrain.max()])
ax.set_ylim([ytrain.min()-1,ytrain.max()+1])
ax.scatter(xtrain,ytrain)
ax=fig.add_subplot(122)
ax.plot(xtest,ymean,"b")
if demo=="sin":
ax.set_ylim([-3,3])
ax.set_xlim([-1,1])
elif demo=="marathon_demo":
ax.set_xlim([xtrain.min(),xtrain.max()])
ax.set_ylim([ytrain.min()-1,ytrain.max()+1])
tmp=np.arange(-1,1,0.01)
if demo=="sin":
ax.plot(tmp,np.sin(2*np.pi*tmp),"r--")
ax.scatter(xtrain,ytrain)
fig.show()
PHImat=dmat.transpose()
if plothist==True:
fig2=plot_demo_rbf(prior,posterior)
#use evidence funciton to redetermine parameters maximizing likelihood of dataset
#-- that step maximizes the likelihood of the training dataset p(t|alpha,beta)
#effectively looking at p(alpha,beta|t)=p(t|alha,beta)p(alpha,beta)
return(xtrain,alpha,beta)
def evidence_func(PHImat,mn,ytrain,xtrain_,alpha,beta):
"""
Maximizing parameters based on training data only
"""
X=beta*np.dot(PHImat.transpose(),PHImat)
w,v=np.linalg.eig(X)
lam=np.diag(w)
gamma=np.sum(lam/(alpha+lam))
alpha=gamma/(np.dot(mn.transpose(),mn))
tmp=1/(xtrain_.shape[1]-gamma)*np.sum(np.square(ytrain-np.dot(mn,xtrain_)))
beta=1/tmp
return(alpha,beta)
def plot_demo_rbf(prior,posterior):
#mu, sigma = 100, 15
#x = mu + sigma*np.random.randn(10000)
# the histogram of the data
#n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
fig=plt.figure()
ax=fig.add_subplot(221)
n, bins, patches = ax.hist(posterior[:,0],15,normed="True")
plt.xlabel('Weights: w0')
plt.ylabel('Probability')
plt.grid(True)
ax=fig.add_subplot(222)
n, bins, patches = ax.hist(posterior[:,1],15,normed="True")
# add a 'best fit' line
#y = mlab.normpdf( bins, mu, sigma)
#l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Weights: w1')
plt.ylabel('Probability')
plt.grid(True)
ax=fig.add_subplot(223)
n, bins, patches = ax.hist(posterior[:,0],15,normed="True")
plt.xlabel('Weights: w2')
plt.ylabel('Probability')
plt.grid(True)
ax=fig.add_subplot(224)
n, bins, patches = ax.hist(posterior[:,1],15,normed="True")
# add a 'best fit' line
#y = mlab.normpdf( bins, mu, sigma)
#l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Weights: w3')
plt.ylabel('Probability')
plt.grid(True)
plt.show()
return(fig)
def plot_demo(prior,posterior):
#mu, sigma = 100, 15
#x = mu + sigma*np.random.randn(10000)
# the histogram of the data
#n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
fig=plt.figure()
ax=fig.add_subplot(121)
n, bins, patches = ax.hist(posterior[:,0],15,normed="True")
plt.xlabel('Weights: w0')
plt.ylabel('Probability')
plt.grid(True)
ax=fig.add_subplot(122)
n, bins, patches = ax.hist(posterior[:,1],15,normed="True")
# add a 'best fit' line
#y = mlab.normpdf( bins, mu, sigma)
#l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Weights: w1')
plt.ylabel('Probability')
plt.grid(True)
plt.show()
return(fig)
|
b61d3276ade3f2d4a460ca6c6f11195364cc9e37 | CompetitiveCode/hackerrank-python | /Practice/Regex and Parsing/Validating and Parsing Email Addresses.py | 456 | 4.0625 | 4 | #Answer to Validating and Parsing Email Addresses
import email.utils
import re
for i in range(int(input())):
b=input()
a=email.utils.parseaddr(b)
if bool(re.match(r'^[A-Za-z]{1}(\w|_|-|\.)*@[A-Za-z]+\.[A-Za-z]{1,3}$',a[1])):
print(b)
"""
Code:
import email.utils
print email.utils.parseaddr('DOSHI <DOSHI@hackerrank.com>')
print email.utils.formataddr(('DOSHI', 'DOSHI@hackerrank.com'))
produces this output:
('DOSHI', 'DOSHI@hackerrank.com')
DOSHI <DOSHI@hackerrank.com>
""" |
2e199536d4c40fad344064e2cea9a0ae052c673c | Rishi05051997/Python-Notes | /2-CHAPTER/Practice/01_add.py | 111 | 3.90625 | 4 | a = int(input('Enter first number'))
b = int(input ('enter second number'))
print("The value of a+b is ", a+b) |
90e47d3694a3513e46572b5f6f75fd8e509cabe5 | yusufibro/upload-project | /luas.py | 3,092 | 3.578125 | 4 | import math
import sys
def hitung_luas_lingkaran():
print("Menghitung luas lingkaran")
radius = int(input("jari-jari = "))
luas = 22 / 7 * radius * radius
print(("Luas= "), luas)
def hitung_luas_persegi_panjang():
print("Menghitung Luas Persegi Panjang")
panjang = int(input("panjang= "))
lebar = int(input("lebar= "))
luas = panjang * lebar
print(("Luas="), luas)
def hitung_luas_segitiga():
print("Menghitung luas Segitiga")
panjang = int(input("Panjang ="))
lebar = int(input("Lebar = "))
tinggi = int(input("Tinggi = "))
luas = panjang * lebar * tinggi
print("Luas = ", luas)
def segitiga():
print("\n---------------------------")
print(" Menghitung Luas Segitiga")
print("---------------------------")
a = int(input("Masukkan alas : "))
t = int(input("Masukkan tinggi : "))
luas = 0.5 * a * t
print("Luas Segitiga : ", luas)
tanya()
def fibonacci():
print("\n---------------------------")
print(" Segitiga Fibonacci")
print("---------------------------")
un = int(input("Masukkan suku : "))
hasil = (un-1)+(un-2)
print("Hasilnya Adalah :", hasil)
tanya()
def siku():
print("\n---------------------------")
print(" Segitiga Siku-Siku")
print("---------------------------")
sisi = input("Sisi yang ingin di cari [a, b, c] : ")
if sisi == "a":
b = int(input("Masukkan panjang sisi b : "))
c = int(input("Masukkan panjang sisi c : "))
a = math.sqrt((c*c)-(b*b))
print("Panjang sisi a adalah : " , a)
tanya()
elif sisi == 'b':
a = int(input("Masukkan panjang sisi a : "))
c = int(input("Masukkan panjang sisi c : "))
b = math.sqrt((c*c)-(a*a))
print("Panjang sisi b adalah : " , b)
tanya()
elif sisi == 'c':
a = int(input("Masukkan panjang sisi a : "))
b = int(input("Masukkan panjang sisi b : "))
c = math.sqrt((a*a)+(b*b))
print("Panjang sisi c adalah : " , c)
tanya()
else:
print("\nPilihan yang anda masukkan salah!")
siku()
# Program Utama
print("Menghitung luas")
print("1. Lingkaran")
print("2. Persegi panjang")
print("3. Segitiga")
print("4. Segitiga Fibonacci")
print("5. Segitiga Siku-Siku")
print("6. Exit")
pilihan = int(input("pilihan(1 , 2 , 3 , 4 , 5 , 6): "))
if pilihan == 1:
hitung_luas_lingkaran()
elif pilihan == 2:
hitung_luas_persegi_panjang()
elif pilihan == 3:
hitung_luas_segitiga()
elif pilihan == 4:
fibonacci()
elif pilihan == 5:
siku()
elif pilihan == 6:
print("Terima kasih sudah menggunakan aplikasi ini!")
sys.exit()
else:
print("Pilihan salah")
def tanya():
print("\n-----------------------------------------")
tanya = input(" Ingin mengulang aplikasi lagi? [y/t] : ")
print("-----------------------------------------")
if tanya == "y":
menu()
elif tanya == "t":
sys.exit()
else:
print("Pilihan yang anda masukan salah!") |
ce72f9758d200b5689dc491a5c886d827db99162 | SalvaJ/Python-Examples | /es_entero.py | 189 | 3.734375 | 4 | #!/usr/bin/env python
import math
def es_entero(x):
x = abs(x)
x2 = math.floor(x)
if (x2 - x) >= 0:
return True
else:
return False
print es_entero(-3.2)
|
0e9223c587570cf3920b25605658eaca59c5cfc3 | mmetsa/PythonProjects | /ex02_binary/binary.py | 1,136 | 4.09375 | 4 | """Converter."""
import math
def dec_to_binary(dec: int) -> str:
"""
Convert decimal number into binary.
:param dec: decimal number to convert
:return: number in binary
"""
list_bin = []
if dec == 0:
list_bin.append(0)
while dec != 0:
list_bin.append(dec % 2)
dec = math.floor(dec / 2)
binary_values = ""
for a in reversed(list_bin):
binary_values = binary_values + str(a)
return binary_values
def binary_to_dec(binary: str) -> int:
"""
Convert binary number into decimal.
:param binary: binary number to convert
:return: number in decimal
"""
current_position = len(binary)
total_value = 0
for number in binary:
total_value += 2 ** (current_position - 1) * int(number)
current_position -= 1
return total_value
if __name__ == "__main__":
print(dec_to_binary(0)) # -> 10010001
print(dec_to_binary(245)) # -> 11110101
print(dec_to_binary(255)) # -> 11111111
print(binary_to_dec("1111")) # -> 15
print(binary_to_dec("10101")) # -> 21
print(binary_to_dec("10010")) # -> 18
|
9de50d067eb3029451cd60634500c6c8df30ae65 | Alwayswithme/LeetCode | /Python/073-set-matrix-zeroes.py | 1,122 | 3.84375 | 4 | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2015-06-24 17:58:33
# Title : 73 set matrix zeroes
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
class Solution:
# @param {integer[][]} matrix
# @return {void} Do not return anything, modify matrix in-place instead.
def setZeroes(self, matrix):
first_row = reduce(lambda acc, i: acc or matrix[0][i] == 0, range(len(matrix[0])), False)
first_col = reduce(lambda acc, i: acc or matrix[i][0] == 0, range(len(matrix)), False)
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0], matrix[0][j] = 0, 0
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if first_col:
for i in range(len(matrix)):
matrix[i][0] = 0
if first_row:
for i in range(len(matrix[0])):
matrix[0][i] = 0
|
96ca3a7ed14fe1358aef074d620b4ed77b167393 | farrukhkhalid1/100Days | /Day22/scoreboard.py | 848 | 3.703125 | 4 | from turtle import Turtle
FONT = ("Arial", 30, "normal")
ALIGNMENT = "center"
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.penup()
self.score_left = 0
self.score_right = 0
self.hideturtle()
self.update_score()
def update_score(self):
self.clear()
self.goto(-60, 250)
self.write(arg=f"{self.score_left}", font=FONT, align=ALIGNMENT)
self.goto(60, 250)
self.write(arg=f"{self.score_right}", font=FONT, align=ALIGNMENT)
def l_score(self):
self.score_left += 1
self.update_score()
def r_score(self):
self.score_right += 1
self.update_score()
def game_over(self):
self.goto(0, 0)
self.write(arg="Game Over", font=FONT, align=ALIGNMENT)
|
d8a327600ba9f209850f80ee7611ece158b0e786 | liberbell/py08 | /cal.py | 638 | 3.5 | 4 | import calendar
import math
import random
cal = calendar.month(2019,10)
print(cal)
result = math.sqrt(49)
print(result)
number = random.randint(1, 100)
# print(number)
state1 = 0
state2 = 0
state3 = 0
state4 = 0
state5 = 0
for i in range(1000):
number = random.randint(1, 5)
# print(number)
if number == 1:
state1 += 1
elif number == 2:
state2 += 1
elif number == 3:
state3 += 1
elif number == 4:
state4 += 1
else:
state5 +=1
# print(number)
print('1 is: ', state1)
print('2 is: ', state2)
print('3 is: ', state3)
print('4 is: ', state4)
print('5 is: ', state5)
|
25064d3c6a782c27b726de5d41de79295a33e8e0 | aish2028/stack | /s2.py | 272 | 3.6875 | 4 | def searchLinear(lst,ele):
index= -1
for i in lst:
if i == ele:
return index
index += 1
return -1
ele=6
res=searchLinear([1,2,3,4,5,6,7,8],6)
if res == -1:
print(f"{ele} is not found")
else:
print(f"{ele} is found at:{res}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.