blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d287f23e43f1a5d17ad986c3cf70ed55ae1f1dad | yash-learner/py-tricks | /py-trick0.py | 274 | 3.734375 | 4 | l1 = [1,5,4,8]
l2 = [8,4,5,9,8]
l3 = [8,8,7,5,4]
# TODO: method: 1
s1 = sum(l1)
s2 = sum(l2)
s3 = sum(l3)
print(s1,s2,s3)
# TODO: method: 2
s1, s2, s3 = sum(l1), sum(l2), sum(l3)
print(s1,s2,s3)
# TODO: method: 3
s1, s2, s3 = map(sum,(l1,l2,l3))
print(s1,s2,s3)
|
132740d093039564b28abe9113140c13215e00e5 | natancamenzind/kurs_pythona_APE | /4/numbers.py | 264 | 3.578125 | 4 | from random import randint
random_number = randint(1, 10)
user_numer = input("Podaj liczbe od 1 do 10")
tries = 1
while int(user_numer) != random_number:
tries += 1
user_numer = input('Sporóbuj jeszcze raz!')
print('KONIEC po {} próbach'.format(tries))
|
f18748b830ae0b122a62bb99c50b436e014d0b3c | natancamenzind/kurs_pythona_APE | /regexp/regex.py | 872 | 3.625 | 4 | # importujemy bibliotekę odpowiedzialną za wyrażenia regularne
import re
# przykładowy teskt
text = "My name is Loren and my email is loren@gmail.com"
# wyrażenie regularne opisujące struktrę maila
mail_regex = re.compile(r'\w+@\w+.\w+')
# znajdź w danym tekscie pierwsze wyrażenie, które spełnia moje wymagania
# operacja zwraca nieczytelny obiekt typu:
# <_sre.SRE_Match object; span=(42, 56), match='loren@gmail.com'>
search_object = mail_regex.search(text)
# pokaż czytelny obiekt
email_address = search_object.group()
print(email_address)
# loren@gmail.com
# a co jeśli kilka?
rubbish = "asdfas@wp.pl asdfadsf adsfas a loren@gmail.com, sadfasdfiohiuj @pw.pl jan@wp.pl"
# wtedy używamy metody findall()
emails = mail_regex.findall(rubbish)
# zwróci nam listę
print(emails)
# ['asdfas@wp.pl', 'loren@gmail.com', 'jan@wp.pl']
# ściąga z zasadmi regexów:
# https://www.rexegg.com/regex-quickstart.html
|
36258ae41c33a29c742a51f26e46a557714d8670 | chris-graham/dsp | /python/advanced_python_csv.py | 375 | 3.703125 | 4 | import csv
from advanced_python_regex import Faculty
# Create a new Faculty object and get the list of emails from the data file
f = Faculty('faculty.csv')
emails = f.get_emails()
# Create emails.cvs and write each email as a row in the file
with open ('emails.csv', 'wb') as csv_file:
email_writer = csv.writer(csv_file, delimiter='\n')
email_writer.writerows([emails])
|
a340f4d57da7fc9b33db96f2c50fbb9d8a77fd0b | maryellenphil/CE232 | /HW22_Phillips.py | 3,105 | 4.40625 | 4 | #Follow the instruction on this page, create the Node Class and the linkedList Class. Instantiate a linked list object from the linkedList Class and test all the methods designed in the class.
# Node Class
class Node:
def __init__(self,data):
self.data = data
self.next = None
# Linked List Class
class LinkedList:
def __init__(self):
self.head = None
def append(self,data):
#To append data to a list, you must wrap the data into a Node object first:
newNode = Node(data)
#If linked list is empty, assign newNode to the Head pointer & terminate.
if self.head == None:
self.head = newNode
return
#move Head pointer to the last Node and assign newNode to the last Node's 'next' pointer.
else:
lastNode = self.head #duplicate Head pointer
while lastNode.next != None:
lastNode = lastNode.next
lastNode.next = newNode
def prepend(self,data):
newNode = Node(data) # wrap data into a Node object
if self.head == None: # set newNode as the Head Node if list is already empty
self.head = newNode
return
else:
newNode.next = self.head # connect old self.head pointer to tail of new node
self.head = newNode # set newNode as address for new Head pointer
def insertAfterNode(self, prevNode, data):
newNode = Node(data)
newNode.next = prevNode.next
prevNode.next = newNode
def printList(self):
curNode = self.head #duplicate so you are not losing 'self.head'
while curNode != None:
print(curNode.data)
curNode = curNode.next
def deleteNode(self, key):
curNode = self.head #duplicate the head pointer first
if curNode != None and curNode.data == key: #the head node is the one to be deleted
self.head = curNode.next
curNode = None
return
else:
prev = None
while curNode != None and curNode.data != key:
prev = curNode
curNode = curNode.next
if curNode == None: #why it is not curNode.next == None???? If the original linkedlist is empty, then there is no curNode.next at all. If the scan pointer 'curNode' is already pointing to the 'None' after the last node, then there is no None.next as well
pritn('The data is not found i nthe list')
return
else:
prev.next = curNode.next
curNode = None #Why it is not curNode.next = None??? When you don't need this node anymore, just point the entire Node to None....
#Test append
team = LinkedList()
team.append('P')
team.append('i')
team.append('r')
team.append('a')
team.append('t')
team.append('e')
team.append('s')
team.printList()
print()
#Test prepend
team.prepend('Z')
team.printList()
print()
#Test deletenode
team.deleteNode('Z')
team.printList()
print()
#Test insertafternode
team.insertAfterNode(team.head.next,'Z')
team.printList()
|
e3e8af1efd0adbca06cba83b769bc93d10c13d69 | jalalk97/math | /vec.py | 1,262 | 4.125 | 4 | from copy import deepcopy
from fractions import Fraction
from utils import to_fraction
class Vector(list):
def __init__(self, arg=None):
"""
Creates a new Vector from the argument
Usage:
>> Vector(), Vector(None) Vector([]) creates empty vector
>> Vector([5, 6, 6.7, Fraction(5, 6)]) creates vector with elements as list
"""
if arg is None:
super().__init__()
elif isinstance(arg, list):
super().__init__(to_fraction(arg))
elif isinstance(arg, Vector):
self = deepcopy(arg)
else:
raise TypeError('Invalid argument type:', arg)
def __getitem__(self, arg):
"""
Uses the basic list indexing
Usage:
>> v[0] returns the firt element
>> v[-1] returns the last element
>> v[:] shallow copy of vector elements
>> v[4:8] returns a sclice of the vectors element from 4 to 8
"""
return super().__getitem__(arg)
def __setitem__(self, arg, value):
"""
Uses the basic list indexing to set values
Usage:
>>
>>
>>
>>
"""
value = to_fraction(value)
super().__setitem__(arg, value)
|
35d7d4a2fe0c6cd7a6d77356788fe737f158a672 | Masterroy1210/python-codes | /snake.py | 1,020 | 3.65625 | 4 | import turtle
from random import randrange
from freegames import square,vector
food=vector(0,0)
snake =[vector(10,0)]
aim = vector(0,-10)
def change(x,y):
aim.x =x
aim.y = y
def inside(head):
return-200<head.x<190 and -200<head.y,190
def move():
head = snake[-1].copy()
head.move(aim)
if not inside(head)or head in snake:
square(head.x,head.y,9,'red')
update()
return
snake.append(head)
if head==food:
print('Snake',len(snake))
food.x=randrange(-15,15)*10
food.y=randrange(-15,15)*10
else:
snake.pop(0)
clear()
for body in snake:
square(body.x,body.y,9,'black')
square(food.x,food.y,9,'green')
ontimer(move,100)
setup(420,420,370,0)
hideturtle()
tracer(False)
listen()
onkey(lambda:change(10,0),'Right')
onkey(lambda:change(-10,0),'Left')
onkey(lambda:change(0,10),'Up')
onkey(lambda:change(0,-10),'Down')
move()
done()
|
57d5b147631c2b58a3bcf08e7703830594f09506 | MLPMario/Mision-08 | /listas.py | 3,112 | 3.828125 | 4 | #Autor: Luis Mari Cervantes Ortiz
#Descripcion: Uso de listas, regreso de otras listas y numeros
def sumarAcumulado(lista): #Sumar del numero anterior de la lista
lis=[]
for k in range (1,len(lista)+1):
lis.append(sum(lista[:k]))
return lis
def recortarLista(lista): #Borrar el primer y ultimo valor de la lista
list=[]
for k in range(1,len(lista)-1):
list.append(lista[k])
return list
def estanOrdenados (lista): #Demostrar que una lista estsa ordenada
var=True
for k in range(1,len(lista)):
if lista[k]>lista[k-1]:
var= True
if not lista[k]>lista[k-1]:
var= False
break
return var
def sonAnagramas(primerapalabra,segundapalabra): #Demostrar que 2 palabras son anagramas
if sorted(primerapalabra.lower())==sorted(segundapalabra.lower()):
return True
else:
return False
def hayDuplicados(lista): #Demostrar si hay duplicados en una lista
if len(lista) == len(list(set(lista))):
return False
else:
return True
def borrarDuplicados(lista): #Borrar los numeros duplicados en una lista
lista=list(set(lista))
return lista
def main(): #Ejecutar las listas
print("Ejercicio 1")
lista1 = [1,2,3,4,5]
lista2 =[]
lista3=[5]
print("La lista", lista1,"regresa",sumarAcumulado(lista1))
print("La lista", lista2, "regresa", sumarAcumulado(lista2))
print("La listta", lista3, "regresa",sumarAcumulado(lista3))
print()
print("Ejercicio 2")
lista4= [1,2,3,4,5]
print("La lista original",lista4, "regresa",recortarLista(lista4))
lista5=[1,2,]
print("La lista original", lista5, "regresa", recortarLista(lista5))
lista6=[]
print("La lista original", lista6, "regresa", recortarLista(lista6))
print()
print("Ejercicio 3")
lista7=[1,2,3,4,5]
print("La lista", lista7,"es ", estanOrdenados(lista7))
lista8= [7,5,2,3]
print("La lista", lista8, "es ", estanOrdenados(lista8))
lista9=[1]
print("La lista", lista9, "es ", estanOrdenados(lista9))
print()
print("Ejercicio 4")
print("Las palabras, Fiesta y termo son anagramas?", (sonAnagramas("fiesta","termno")))
print("Las palabras, Roma y Mora son anagramas?", (sonAnagramas("Roma", "Mora")))
print("Las palabras, Hola y Hello son anagramas?", (sonAnagramas("hOLa", "Hello")))
print()
print("Ejercicio 5")
lista10=[1,2,3,1,4,5]
print("La lista", lista10,"tiene números duplicados?",hayDuplicados(lista10))
lista11=[5,7,4,6,10]
print("La lista", lista11, "tiene números duplicados?", hayDuplicados(lista11))
lista12=[1]
print("La lista", lista12, "tiene números duplicados?", hayDuplicados(lista12))
print("Ejercicio 6")
lista13=[1,8,7,5,3,1,8]
print("La lista",lista13, "da",borrarDuplicados(lista13))
lista14=[4,5,6,7,8,9]
print("La lista", lista14, "da", borrarDuplicados(lista14))
lista15=[]
print("La lista", lista15, "da", borrarDuplicados(lista15))
main()
|
9c0600a587a6a221406f7295247f241e5b7c690a | crawftv/lambdata | /lambdata_crawftv/ClassificationVisualization.py | 1,529 | 3.59375 | 4 | import sklearn
from sklearn import metrics
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
"""
IMPORTANT must upgrade Seaborn to use in google Colab.
Classification_report is just the sklearn classification report
Classification_report will show up in the shell and notebooks
Results from confusion_viz will appear in notebooks only
"""
def classification_visualization(y_true,y_pred):
"""
Prints the results of the functions. That's it
"""
print(classification_report(y_true,y_pred))
print(confusion_viz(y_true,y_pred))
def confusion_viz(y_true, y_pred):
"""
Uses labels as given
Pass y_true,y_pred, same as any sklearn classification problem
Inspired from code from a Ryan Herr Lambda School Lecture
"""
y_true = np.array(y_true).ravel()
labels = unique_labels(y_true,y_pred)
matrix = confusion_matrix(y_true, y_pred)
graph = sns.heatmap(matrix, annot=True,
fmt=',', linewidths=1,linecolor='grey',
square=True,
xticklabels=["Predicted\n" + str(i) for i in labels],
yticklabels=["Actual\n" + str(i) for i in labels],
robust=True,
cmap=sns.color_palette("coolwarm"))
plt.yticks(rotation=0)
plt.xticks(rotation=0)
return graph
|
852697b63672abe67766d8e45986884fbd89b9d3 | Handagege/stdpyTest | /algorithm/mergeSort.py | 650 | 4.03125 | 4 | #!/usr/bin/python
def mergeSort(a):
mi = len(a)/2
if len(a) > 2:
return merge(mergeSort(a[0:mi]),mergeSort(a[mi:len(a)]))
else:
return merge(a[0:mi],a[mi:len(a)])
def merge(a,b):
i,j,z = len(a)-1,len(b)-1,len(a)+len(b)
mergeResult = [0]*z
while i > -1 and j > -1:
z -= 1
if a[i] > b[j]:
mergeResult[z] = a[i]
i -= 1
else:
mergeResult[z] = b[j]
j -= 1
if i == -1:
for index in range(j+1):
mergeResult[index] = b[index]
else:
for index in range(i+1):
mergeResult[index] = a[index]
return mergeResult
if __name__=='__main__':
a = range(0,30)
import random
random.shuffle(a)
print a
print mergeSort(a)
|
a658488db211b33e2722357d169b9ef3654bafad | Handagege/stdpyTest | /algorithm/LIS.py | 534 | 3.703125 | 4 | #!/usr/bin/python
import sys
def binarySearch(a,r,i):
right = r
left = 0
while(left <= right):
mid = (left+right)/2
if a[mid] == i:
return mid
elif a[mid] < i:
left = mid+1
else:
right = mid-1
return left
def LIS(a):
ans = [0]*len(a)
ans[0] = a[0]
l = 0
for index,value in enumerate(a):
if value > ans[l]:
l += 1
ans[l] = value
else:
ans[binarySearch(ans,l,value)] = value
print index,ans
return ans
if __name__ == '__main__':
a = [2,3,6,45,10,12,5,9,11,17,13,14,15]
print LIS(a)
|
e7f58e8914dc7a95d8d9570d9770856d6bf7bf0d | hyuntaedo/Python_generalize | /GUI_Basic/6_listbox.py | 763 | 3.546875 | 4 | from tkinter import *
from typing import List
root = Tk()
root.title("CodeBasic")
root.geometry("640x480")
listbox = Listbox(root, selectmode="extended", height=0)
listbox.insert(0, "사과")
listbox.insert(1, "딸기")
listbox.insert(2, "바나나")
listbox.insert(END, "수박")
listbox.insert(END, "포도")
listbox.pack()
def btncmd():
# listbox.delete(0)
# 갯수 확인
print("리스트에는", listbox.size(), "개가있음")
# 항목 확인
print("1번~3번항목까지는", listbox.get(0, 2), "가 있음")
# 선택된 항목 확인 (index 값으로 반환)
print("선택된 항목은", listbox.curselection())
btn = Button(root, text="click", command=btncmd)
btn.pack()
root.mainloop()
|
237d6097bb1712a441b007e8065e963c0ff77988 | TestowanieAutomatyczneUG/laboratorium-8-Plastikowy-Metal | /tests/sample/test_get_meals_functions.py | 10,175 | 3.703125 | 4 | from src.sample.main import *
import unittest
class MealTest(unittest.TestCase):
# SET UP
def setUp(self):
self.temp = Meal()
# BY NAME
def test_get_meals_by_name1(self):
self.assertEqual(self.temp.get_meals_by_name("Steak"), ['Steak Diane', 'Steak and Kidney Pie'])
def test_get_meals_by_name2(self):
self.assertEqual(self.temp.get_meals_by_name("Beef"),
['Beef Lo Mein', 'Szechuan Beef', 'Beef Wellington', 'Beef stroganoff', 'Minced Beef Pie', 'Beef Bourguignon', 'Beef Sunday Roast', 'Beef Dumpling Stew', 'Braised Beef Chilli', 'Massaman Beef curry', 'Beef and Oyster pie', 'Beef and Mustard Pie', 'Jamaican Beef Patties', 'Beef Brisket Pot Roast', 'Corned Beef and Cabbage', 'Beef Banh Mi Bowls with Sriracha Mayo, Carrot & Pickled Cucumber'])
def test_get_meals_by_name_not_found1(self):
self.assertEqual(self.temp.get_meals_by_name("Rapapara"), "No meals found")
def test_get_meals_by_name_not_found2(self):
self.assertEqual(self.temp.get_meals_by_name("Ching chang"), "No meals found")
def test_get_meals_by_name_exception1(self):
with self.assertRaises(ValueError):
self.temp.get_meals_by_name(1231)
def test_get_meals_by_name_exception2(self):
with self.assertRaises(ValueError):
self.temp.get_meals_by_name({})
def test_get_meals_by_name_exception3(self):
with self.assertRaises(ValueError):
self.temp.get_meals_by_name(None)
# BY FIRST LETTER
def test_get_meal_by_first_letter1(self):
self.assertEqual(self.temp.get_meal_by_first_letter("a"),
['Apple Frangipan Tart', 'Apple & Blackberry Crumble'])
def test_get_meal_by_first_letter2(self):
self.assertEqual(self.temp.get_meal_by_first_letter("e"),
['Eton Mess', 'Eccles Cakes', 'English Breakfast', 'Escovitch Fish', 'Egg Drop Soup', 'Egyptian Fatteh'])
def test_get_meal_by_first_letter_not_found1(self):
self.assertEqual(self.temp.get_meal_by_first_letter("ź"), "Wrong char")
def test_get_meal_by_first_letter_not_found2(self):
self.assertEqual(self.temp.get_meal_by_first_letter("ą"), "Wrong char")
def test_get_meals_by_first_letter_exception1(self):
with self.assertRaises(ValueError):
self.temp.get_meal_by_first_letter(1231)
def test_get_meals_by_first_letter_exception2(self):
with self.assertRaises(ValueError):
self.temp.get_meal_by_first_letter("siema")
def test_get_meals_by_first_letter_exception3(self):
with self.assertRaises(ValueError):
self.temp.get_meal_by_first_letter(None)
# BY ID
def test_get_meal_by_id1(self):
self.assertEqual(self.temp.get_meal_by_id(52772), ['Teriyaki Chicken Casserole'])
def test_get_meal_by_id2(self):
self.assertEqual(self.temp.get_meal_by_id(52775), ['Vegan Lasagna'])
def test_get_meal_by_id_not_found1(self):
self.assertEqual(self.temp.get_meal_by_id(997), "No meals found")
def test_get_meal_by_id_not_found2(self):
self.assertEqual(self.temp.get_meal_by_id(1337), "No meals found")
def test_get_meals_by_id_exception1(self):
with self.assertRaises(ValueError):
self.temp.get_meal_by_id(-100)
def test_get_meals_by_id_exception2(self):
with self.assertRaises(ValueError):
self.temp.get_meal_by_id("siema")
def test_get_meals_by_id_exception3(self):
with self.assertRaises(ValueError):
self.temp.get_meal_by_id(None)
# RANDOM MEAL
def test_get_meal_random1(self):
self.assertIsNot(self.temp.get_meal_random(), [])
def test_get_meal_random2(self):
self.assertIsNot(self.temp.get_meal_random(), [])
def test_get_meal_random3(self):
self.assertEqual(len(self.temp.get_meal_random()), 1)
def test_get_meal_random4(self):
self.assertEqual(len(self.temp.get_meal_random()), 1)
# MEAL CATEGORIES
def test_get_meal_categories1(self):
self.assertEqual(self.temp.get_meal_categories(),
['Beef', 'Chicken', 'Dessert', 'Lamb', 'Miscellaneous', 'Pasta', 'Pork', 'Seafood', 'Side', 'Starter', 'Vegan', 'Vegetarian', 'Breakfast', 'Goat'])
# MAIN INGREDIENT
def test_get_meal_by_main_ingredient1(self):
self.assertEqual(self.temp.get_meal_filter_by_main_ingredient('chicken_breast'),
['Chick-Fil-A Sandwich', 'Chicken Couscous', 'Chicken Fajita Mac and Cheese', 'Chicken Ham and Leek Pie', 'Chicken Quinoa Greek Salad', "General Tso's Chicken", 'Honey Balsamic Chicken with Crispy Broccoli & Potatoes', 'Katsu Chicken curry', 'Rappie Pie'])
def test_get_meal_by_main_ingredient2(self):
self.assertEqual(self.temp.get_meal_filter_by_main_ingredient('cabbage'),
['Bigos (Hunters Stew)', 'Corned Beef and Cabbage', 'Crispy Sausages and Greens', 'Gołąbki (cabbage roll)', 'Rosół (Polish Chicken Soup)', 'Yaki Udon'])
def test_get_meals_by_main_ingredient_not_found1(self):
self.assertEqual(self.temp.get_meal_filter_by_main_ingredient("Rapapara"), "No meals found")
def test_get_meals_by_main_ingredient_not_found2(self):
self.assertEqual(self.temp.get_meal_filter_by_main_ingredient("Daswidanja"), "No meals found")
def test_get_meals_by_main_ingredient_exception1(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_main_ingredient(123)
def test_get_meals_by_main_ingredient_exception2(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_main_ingredient(["siema"])
def test_get_meals_by_main_ingredient_exception3(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_main_ingredient(None)
# CATEGORY get_meal_filter_by_category('Lamb')
def test_get_meals_by_category1(self):
self.assertEqual(self.temp.get_meal_filter_by_category('Lamb'), ['Kapsalon', 'Keleya Zaara', 'Lamb and Lemon Souvlaki', 'Lamb and Potato pie', 'Lamb Biryani', 'Lamb Rogan josh', 'Lamb Tagine', 'Lamb tomato and sweet spices', 'Lamb Tzatziki Burgers', 'Lancashire hotpot', 'McSinghs Scotch pie', 'Rigatoni with fennel sausage sauce', 'Stuffed Lamb Tomatoes', 'Tunisian Lamb Soup'])
def test_get_meals_by_category2(self):
self.assertEqual(self.temp.get_meal_filter_by_category('Chicken'), ['Brown Stew Chicken', 'Chick-Fil-A Sandwich', 'Chicken & mushroom Hotpot', 'Chicken Alfredo Primavera', 'Chicken Basquaise', 'Chicken Congee', 'Chicken Couscous', 'Chicken Enchilada Casserole', 'Chicken Fajita Mac and Cheese', 'Chicken Ham and Leek Pie', 'Chicken Handi', 'Chicken Karaage', 'Chicken Marengo', 'Chicken Parmentier', 'Chicken Quinoa Greek Salad', 'Coq au vin', 'Crock Pot Chicken Baked Tacos', 'French Onion Chicken with Roasted Carrots & Mashed Potatoes', "General Tso's Chicken", 'Honey Balsamic Chicken with Crispy Broccoli & Potatoes', 'Jerk chicken with rice & peas', 'Katsu Chicken curry', 'Kentucky Fried Chicken', 'Kung Pao Chicken', 'Nutty Chicken Curry', 'Pad See Ew', 'Potato Gratin with Chicken', 'Rappie Pie', 'Rosół (Polish Chicken Soup)', 'Shawarma', 'Tandoori chicken', 'Teriyaki Chicken Casserole', 'Thai Green Curry'])
def test_get_meals_by_category_wrong_category1(self):
self.assertEqual(self.temp.get_meal_filter_by_category('Dadadada'), "No meals found")
def test_get_meals_by_category_wrong_category2(self):
self.assertEqual(self.temp.get_meal_filter_by_category('Ffffffffffff'), "No meals found")
def test_get_meals_by_category_wrong_category_exception1(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_category(123)
def test_get_meals_by_category_wrong_category_exception2(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_category(["siema"])
def test_get_meals_by_category_wrong_category_exception3(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_category(None)
# AREA
def test_get_meals_by_area1(self):
self.assertEqual(self.temp.get_meal_filter_by_area('Polish'), ['Bigos (Hunters Stew)', 'Gołąbki (cabbage roll)', 'Paszteciki (Polish Pasties)', 'Pierogi (Polish Dumplings)', 'Polskie Naleśniki (Polish Pancakes)', 'Rogaliki (Polish Croissant Cookies)', 'Rosół (Polish Chicken Soup)', 'Sledz w Oleju (Polish Herrings)'])
def test_get_meals_by_area2(self):
self.assertEqual(self.temp.get_meal_filter_by_area('French'), ['Beef Bourguignon', 'Boulangère Potatoes', 'Brie wrapped in prosciutto & brioche', 'Chicken Basquaise', 'Chicken Marengo', 'Chicken Parmentier', 'Chinon Apple Tarts', 'Chocolate Gateau', 'Chocolate Souffle', 'Coq au vin', 'Duck Confit', 'Fennel Dauphinoise', 'Fish Stew with Rouille', 'Flamiche', 'French Lentils With Garlic and Thyme', 'French Omelette', 'French Onion Soup', 'Pear Tarte Tatin', 'Pork Cassoulet', 'Prawn & Fennel Bisque', 'Provençal Omelette Cake', 'Ratatouille', 'Steak Diane', 'Summer Pistou', 'Tarte Tatin', 'Three-cheese souffles', 'Tuna Nicoise', 'White chocolate creme brulee'])
def test_get_meals_by_area_wrong_area1(self):
self.assertEqual(self.temp.get_meal_filter_by_area('Gibberish'), "No meals found")
def test_get_meals_by_area_wrong_area2(self):
self.assertEqual(self.temp.get_meal_filter_by_area('Mascarpone'), "No meals found")
def test_get_meals_by_area_wrong_area_exception1(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_area(123)
def test_get_meals_by_area_wrong_area_exception2(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_area(["siema"])
def test_get_meals_by_area_wrong_area_exception3(self):
with self.assertRaises(ValueError):
self.temp.get_meal_filter_by_area(None)
# TEAR DOWN
def tearDown(self):
self.temp = None
if __name__ == '__main__':
unittest.main()
|
64344c5fe201898e58386d0b58588e1cd4d055f6 | jackgene/amazebot | /public/templates/level4.py | 2,108 | 3.78125 | 4 | # The maze is much more complex in this level.
#
# To help you navigate this map, you have been given a new
# tool - the sonar.
#
# The sonar detects how far walls are from the robot.
#
# There are sonars in three directions:
# - left
# - right
# - center (front)
#
# A new method has been introduced that uses sonar:
# - move_forward_to_wall()
#
# Look at the "move_forward_to_wall()" function and try and
# understand how the sonar works.
from time import sleep
from org.jointheleague.ecolban.rpirobot import SimpleIRobot, Sonar
robot = SimpleIRobot()
sonar = Sonar()
def move_forward():
"""Move the robot forward approximately one square"""
# Move left and right wheels 500mm/s forward
robot.driveDirect(500, 500)
# Let the robot move for 1.642 seconds
sleep(1.642)
# Stop moving
robot.stop()
def move_forward_to_wall():
"""Move the robot forward until it is one square away
from the next wall."""
# Read front sonar distance (in centimeters)
distance_remaining = sonar.readSonar("center")
# More than one square from the next wall...
while distance_remaining > 66:
if distance_remaining > 108:
# Go fast and far if wall is far away
robot.driveDirect(500, 500)
sleep(1)
elif distance_remaining > 72:
# Don't go as far as wall gets closer
robot.driveDirect(500, 500)
sleep(0.1)
else:
# Slow down when wall is really close
robot.driveDirect(200, 200)
sleep(0.03)
# Read front sonar distance again
distance_remaining = sonar.readSonar("center");
robot.stop()
def curve_left():
"""Move the robot approximately 90 degrees left in a curve."""
# Move robot 500mm/s forward,
# with a radius of 417mm (1/2 square) to the left
robot.drive(500, 417);
# Let the robot move for 1.65 seconds
sleep(1.65)
# Stop moving
robot.stop()
def curve_right():
"""Move the robot approximately 90 degrees right in a curve."""
# Move robot 500mm/s forward,
# with a radius of 417mm (1/2 square) to the right
robot.drive(500, -417);
# Let the robot move for 1.65 seconds
sleep(1.65)
# Stop moving
robot.stop()
move_forward_to_wall()
# Your code here...
|
7650c660b7c6eabf23af7b9b5c6f2e166b05b2a4 | DasVisual/projects | /aToBeCompleted/sampledefinitionkgtolbs/sampledefinitionkgtolbs.py | 199 | 4.25 | 4 | #! python3
def calculate_kg_to_lbs(kg):
answer = (kg) * (2.2)
print(answer)
print('Enter your weight in kilograms')
kg = int(input())
print('Your weight in pounds is: ')
calculate_kg_to_lbs(kg)
|
a84f6776548484ef96ab81e0107bdd36385e416e | DasVisual/projects | /temperatureCheck/tempCheck2.py | 338 | 4.125 | 4 | #! python 3
# another version of temperature checker, hopefully no none result
print('What is the current temperature of the chicken?')
def checkTemp(Temp):
if Temp > 260:
return 'It is probably cooked'
elif Temp < 260:
return 'More heat more time'
Temp = int(input())
Result = checkTemp(Temp)
print(Result)
|
3c5e07ca784b470d32025573a9926bc82a7fb872 | DasVisual/projects | /FirstNameLastName(funny)/firstLastName.py | 823 | 4.09375 | 4 | #! python 3
# ask for the first name
print('What is your first name strangerrr?')
firstname = str(input())
# ask for the last name
print('What is your last name?')
lastname = str(input())
# list of random funny names/job titles
print('Type a number from 0 to 6 and press ENTER')
def funnyjobs(number):
if number == 0:
return 'the Cowboy'
elif number == 1:
return 'the Stripper'
elif number == 2:
return 'the Magician'
elif number == 3:
return 'the Belly Dancer'
elif number == 4:
return 'the Farming Disco'
elif number == 5:
return 'the Astronaut/Pilot'
elif number == 6:
return 'the Panda 🐼 <--(that is you)'
number = int(input())
# print the first and last name
print('You are: ', firstname, lastname, funnyjobs(number)) |
929dd3a95dc260f624a43363353c287d475cf800 | pak21/aoc2018 | /20/20.py | 1,554 | 3.5 | 4 | #!/usr/bin/python3
import collections
import sys
directions = {
'E': (1, 0),
'N': (0, 1),
'W': (-1, 0),
'S': (0, -1)
}
stack = []
with open(sys.argv[1]) as f:
for regex in f:
regex = regex.strip()
current = (0, 0)
stack = []
valid_moves = collections.defaultdict(set)
for c in list(regex):
if c == '^' or c == '$':
pass
elif c in directions:
d = directions[c]
new = (current[0] + d[0], current[1] + d[1])
valid_moves[current].add(new)
current = new
elif c == '(':
stack.append(current)
elif c == '|':
current = stack[-1]
elif c == ')':
current = stack.pop()
moves = 1
start = (0, 0)
seen_locations = set()
current_locations = set()
seen_locations.add(start)
current_locations.add(start)
far_away = 0
while current_locations:
new_locations = set()
for l in current_locations:
for m in valid_moves[l]:
if m not in seen_locations:
if moves >= 1000:
far_away += 1
new_locations.add(m)
seen_locations.add(m)
moves += 1
current_locations = new_locations
print('{}: Part 1: {}, Part 2: {}'.format(regex, moves - 2, far_away))
|
aadf02bc8b2b9c5bd8e2dab02f1143ec9e2cb853 | CS486-Group64/Onitama-AI | /game/engine_bitboard.py | 19,323 | 4.0625 | 4 | """Onitama game engine. Note that (x, y) goes right and down. Blue uses positive numbers, red uses negative numbers.
Bitboard has red on the most significant side"""
import numpy as np
import random
from typing import List, NamedTuple, Optional
BOARD_WIDTH = 5
BOARD_HEIGHT = 5
class Point(NamedTuple):
x: int
y: int
def to_algebraic_notation(self):
return chr(ord("a") + self.x) + str(5 - self.y)
@classmethod
def from_algebraic_notation(cls, location):
x = ord(location[0]) - ord("a")
y = BOARD_HEIGHT - int(location[1])
return cls(x, y)
def to_index(self):
"""Indices go from bottom right to top left due to bit ordering"""
return (BOARD_HEIGHT - 1 - self.y) * BOARD_HEIGHT + (BOARD_WIDTH - 1 - self.x)
@classmethod
def from_index(cls, index):
x = BOARD_WIDTH - 1 - index % BOARD_WIDTH
y = BOARD_HEIGHT - 1 - index // BOARD_HEIGHT
return cls(x, y)
class Card:
def __init__(self, name, starting_player, *moves: List[Point]):
"""Moves are represented as a table of destination squares reachable from each origin square"""
self.name = name
self.starting_player = starting_player
self.moves = moves
self.move_table = np.zeros((2, BOARD_HEIGHT * BOARD_WIDTH), dtype=np.int64) # player, square
self.precompute_move_table()
def precompute_move_table(self):
# player 0 is red, player 1 is blue
for player_index in range(2):
# a bit confusing since index goes left and up
for point_index in range(BOARD_WIDTH * BOARD_HEIGHT):
board = 0
for move in self.moves:
player = player_index * 2 - 1
point = Point.from_index(point_index)
new_x = point.x + player * move.x
new_y = point.y + player * move.y
dest = Point(new_x, new_y)
if new_x in range(BOARD_WIDTH) and new_y in range(BOARD_HEIGHT):
board |= 1 << dest.to_index()
self.move_table[player_index][point_index] = board
def visualize(self, reverse=False):
# Cards are displayed with board centre (2, 2) at (0, 0)
output = [["."] * BOARD_WIDTH for _ in range(BOARD_HEIGHT)]
output[BOARD_HEIGHT // 2][BOARD_WIDTH // 2] = "O"
for move in self.moves:
if reverse:
output[BOARD_HEIGHT // 2 - move.y][BOARD_WIDTH // 2 - move.x] = "X"
else:
output[move.y + BOARD_HEIGHT // 2][move.x + BOARD_WIDTH // 2] = "X"
return "\n".join("".join(row) for row in output)
def __repr__(self):
return f"Card({self.name!r},\n{self.visualize()})"
def visualize_bitboard(bitboard):
s = f"{bitboard:0{BOARD_HEIGHT * BOARD_WIDTH}b}"
output = [s[i:i+BOARD_WIDTH] for i in range(0, BOARD_HEIGHT * BOARD_WIDTH, BOARD_HEIGHT)]
return "\n".join(output)
def count_trailing_zeroes(num):
# adapted from https://stackoverflow.com/a/56320918
if not num:
return 32
num &= -num # keep only right-most 1
count = 0
if num & 0xAAAAAAAA:
count |= 1 # binary 10..1010
if num & 0xCCCCCCCC:
count |= 2 # binary 1100..11001100
if num & 0xF0F0F0F0:
count |= 4
if num & 0xFF00FF00:
count |= 8
if num & 0xFFFF0000:
count |= 16
return count
def count_bits(n):
# adapted from https://stackoverflow.com/a/9830282 for 32 bits
n = (n & 0x55555555) + ((n & 0xAAAAAAAA) >> 1)
n = (n & 0x33333333) + ((n & 0xCCCCCCCC) >> 2)
n = (n & 0x0F0F0F0F) + ((n & 0xF0F0F0F0) >> 4)
n = (n & 0x00FF00FF) + ((n & 0xFF00FF00) >> 8)
n = (n & 0x0000FFFF) + ((n & 0xFFFF0000) >> 16)
return n
class Move(NamedTuple):
start: int
end: int
card: str
def __str__(self):
return f"{self.card} {Point.from_index(self.start).to_algebraic_notation()} {Point.from_index(self.end).to_algebraic_notation()}"
def serialize(self):
result = self.start
result <<= BOARD_HEIGHT
result |= self.end
result <<= 4 # 16 cards = 4 bits
result |= INDEX_CARD[self.card]
return result
@classmethod
def from_serialized(cls, representation):
card_index = representation & ((1 << 4) - 1)
representation >>= 4
end_index = representation & ((1 << BOARD_HEIGHT) - 1)
representation >>= BOARD_HEIGHT
start_index = representation
return cls(start_index, end_index, CARD_INDEX[card_index])
class Game:
WIN_SCORE = 50
WIN_BITMASK = [0b00000_00000_00000_00000_00100, 0b00100_00000_00000_00000_00000]
CENTRE_PRIORITY_BITMASKS = [
0b01010_10001_00000_10001_01010,
0b00100_01010_10001_01010_00100,
0b00000_00100_01010_00100_00000,
0b00000_00000_00100_00000_00000
]
def __init__(self, *, red_cards: Optional[List[Card]] = None, blue_cards: Optional[List[Card]] = None,
neutral_card: Optional[Card] = None, starting_player=None,
bitboard_king: Optional[List[int]] = None, bitboard_pawns: Optional[List[int]] = None):
"""Represents an Onitama game. Generates random cards if missing red_cards, blue_cards,
or neutral_card. If starting_player is not specified, uses neutral_card.starting_player."""
if not (red_cards and blue_cards and neutral_card):
cards = set(ONITAMA_CARDS)
card1, card2 = random.sample(cards, k=2)
red_cards = [ONITAMA_CARDS.get(card1), ONITAMA_CARDS.get(card2)]
cards -= {card1, card2}
card1, card2 = random.sample(cards, k=2)
blue_cards = [ONITAMA_CARDS.get(card1), ONITAMA_CARDS.get(card2)]
cards -= {card1, card2}
card = random.sample(cards, k=1)[0]
neutral_card = ONITAMA_CARDS.get(card)
cards.remove(card)
if starting_player is None:
starting_player = neutral_card.starting_player
self.red_cards = red_cards
self.blue_cards = blue_cards
self.neutral_card = neutral_card
self.current_player = starting_player
# board
self.bitboard_king = bitboard_king or [0b00100_00000_00000_00000_00000, 0b00000_00000_00000_00000_00100]
self.bitboard_pawns = bitboard_pawns or [0b11011_00000_00000_00000_00000, 0b00000_00000_00000_00000_11011]
@classmethod
def from_string(cls, board, red_cards, blue_cards, neutral_card, starting_player=None):
red_cards = [ONITAMA_CARDS.get(card) for card in red_cards]
blue_cards = [ONITAMA_CARDS.get(card) for card in blue_cards]
neutral_card = ONITAMA_CARDS.get(neutral_card)
bitboard_king = [0, 0]
bitboard_pawns = [0, 0]
for y, row in enumerate(board.split("\n")):
for x, char in enumerate(row):
pos = Point(x, y).to_index()
if char == "R":
bitboard_king[0] |= 1 << pos
elif char == "B":
bitboard_king[1] |= 1 << pos
elif char == "r":
bitboard_pawns[0] |= 1 << pos
elif char == "b":
bitboard_pawns[1] |= 1 << pos
return cls(red_cards=red_cards, blue_cards=blue_cards, neutral_card=neutral_card,
bitboard_king=bitboard_king, bitboard_pawns=bitboard_pawns,
starting_player=starting_player)
def get_piece_char_mapping(self):
return {
"R": self.bitboard_king[0],
"r": self.bitboard_pawns[0],
"b": self.bitboard_pawns[1],
"B": self.bitboard_king[1],
}
def visualize_board(self):
output = [["."] * BOARD_WIDTH for _ in range(BOARD_HEIGHT)]
for char, bitfield in self.get_piece_char_mapping().items():
for i, c in enumerate(f"{bitfield:0{BOARD_WIDTH * BOARD_HEIGHT}b}"):
if c == "1":
# i should go from 24 to 0
point = Point.from_index(BOARD_WIDTH * BOARD_HEIGHT - 1 - i)
output[point.y][point.x] = char
return "\n".join("".join(row) for row in output)
def visualize(self):
fancy_board = [" abcde"]
for i, line in enumerate(self.visualize_board().split("\n")):
fancy_board.append(f"{5 - i} {line} {5 - i}")
fancy_board.append(" abcde")
fancy_board_str = "\n".join(fancy_board)
return (f"serialized: {self.serialize()}\n"
f"current_player: {'blue' if self.current_player > 0 else 'red'}\n"
f"red_cards: {' '.join(card.name for card in self.red_cards)}\n" +
"\n".join(f"{c1}\t{c2}" for c1, c2 in zip(self.red_cards[0].visualize(reverse=True).split("\n"), self.red_cards[1].visualize(reverse=True).split("\n"))) +
f"\n{fancy_board_str}\n"
f"neutral_card: {self.neutral_card.name}\n"
f"{self.neutral_card.visualize(reverse=self.current_player == 0)}\n"
f"blue_cards: {' '.join(card.name for card in self.blue_cards)}\n" +
"\n".join(f"{c1}\t{c2}" for c1, c2 in zip(self.blue_cards[0].visualize().split("\n"), self.blue_cards[1].visualize().split("\n")))
)
def copy(self):
return Game(red_cards=self.red_cards.copy(), blue_cards=self.blue_cards.copy(), neutral_card=self.neutral_card,
starting_player=self.current_player,
bitboard_king=self.bitboard_king.copy(), bitboard_pawns=self.bitboard_pawns.copy())
def __str__(self):
return f"Game(\n{self.visualize()}\n)"
def __repr__(self):
return (f"Game(red_cards={self.red_cards[0].name, self.red_cards[1].name!r}, blue_cards={self.blue_cards[0].name, self.blue_cards[1].name!r}, "
f"neutral_card={self.neutral_card.name!r}, current_player={self.current_player!r}, "
f"bitboard_king={self.bitboard_king!r}, bitboard_pawns={self.bitboard_pawns!r})")
def serialize(self):
serialized = self.current_player
for i in range(2):
serialized <<= BOARD_WIDTH * BOARD_HEIGHT
serialized |= self.bitboard_king[i]
serialized <<= BOARD_WIDTH * BOARD_HEIGHT
serialized |= self.bitboard_pawns[i]
# sort cards
red_1, red_2 = sorted(INDEX_CARD[card.name] for card in self.red_cards)
serialized <<= 4
serialized |= red_1
serialized <<= 4
serialized |= red_2
blue_1, blue_2 = sorted(INDEX_CARD[card.name] for card in self.blue_cards)
serialized <<= 4
serialized |= blue_1
serialized <<= 4
serialized |= blue_2
serialized <<= 4
serialized |= INDEX_CARD[self.neutral_card.name]
return serialized
@classmethod
def from_serialized(cls, serialized):
neutral_card = ONITAMA_CARDS.get(CARD_INDEX[serialized & ((1 << 4) - 1)])
serialized >>= 4
blue_2 = ONITAMA_CARDS.get(CARD_INDEX[serialized & ((1 << 4) - 1)])
serialized >>= 4
blue_1 = ONITAMA_CARDS.get(CARD_INDEX[serialized & ((1 << 4) - 1)])
serialized >>= 4
blue_cards = [blue_1, blue_2]
red_2 = ONITAMA_CARDS.get(CARD_INDEX[serialized & ((1 << 4) - 1)])
serialized >>= 4
red_1 = ONITAMA_CARDS.get(CARD_INDEX[serialized & ((1 << 4) - 1)])
serialized >>= 4
red_cards = [red_1, red_2]
bitboard_king = [0, 0]
bitboard_pawns = [0, 0]
for i in (1, 0):
bitboard_pawns[i] = serialized & ((1 << BOARD_WIDTH * BOARD_HEIGHT) - 1)
serialized >>= BOARD_WIDTH * BOARD_HEIGHT
bitboard_king[i] = serialized & ((1 << BOARD_WIDTH * BOARD_HEIGHT) - 1)
serialized >>= BOARD_WIDTH * BOARD_HEIGHT
starting_player = serialized
return cls(red_cards=red_cards, blue_cards=blue_cards, neutral_card=neutral_card,
starting_player=starting_player,
bitboard_king=bitboard_king, bitboard_pawns=bitboard_pawns)
def legal_moves(self):
# adapted from https://github.com/maxbennedich/onitama/blob/master/src/main/java/onitama/ai/MoveGenerator.java
cards = self.red_cards if self.current_player == 0 else self.blue_cards
has_valid_move = False
player_bitboard = self.bitboard_king[self.current_player] | self.bitboard_pawns[self.current_player]
start_pos = -1
start_trailing_zeroes = -1
# Loop over current player's pieces
while True:
# pop last piece
player_bitboard >>= start_trailing_zeroes + 1
start_trailing_zeroes = count_trailing_zeroes(player_bitboard)
if start_trailing_zeroes == 32:
break
start_pos += start_trailing_zeroes + 1
for card in cards:
move_bitmask = card.move_table[self.current_player][start_pos]
# prevent moving onto own pieces
move_bitmask &= ~self.bitboard_pawns[self.current_player]
move_bitmask &= ~self.bitboard_king[self.current_player]
end_pos = -1
end_trailing_zeroes = -1
while True:
# pop move
move_bitmask >>= end_trailing_zeroes + 1
end_trailing_zeroes = count_trailing_zeroes(move_bitmask)
if end_trailing_zeroes == 32:
break
end_pos += end_trailing_zeroes + 1
has_valid_move = True
yield Move(start_pos, end_pos, card.name)
if not has_valid_move:
# pass due to no piece moves, but have to swap a card
for card in cards:
yield Move(0, 0, card.name)
def apply_move(self, move: Move):
start_mask = 1 << move.start
end_mask = 1 << move.end
card = move.card
cards = self.red_cards if self.current_player == 0 else self.blue_cards
card_idx = 0 if cards[0].name == card else 1
if self.bitboard_pawns[1 - self.current_player] & end_mask:
# captured opponent pawn
self.bitboard_pawns[1 - self.current_player] &= ~end_mask
if self.bitboard_king[1 - self.current_player] & end_mask:
# captured opponent king
self.bitboard_king[1 - self.current_player] &= ~end_mask
if self.bitboard_pawns[self.current_player] & start_mask:
# moved own pawn
self.bitboard_pawns[self.current_player] &= ~start_mask
self.bitboard_pawns[self.current_player] |= end_mask
elif self.bitboard_king[self.current_player] & start_mask:
# moved own king
self.bitboard_king[self.current_player] &= ~start_mask
self.bitboard_king[self.current_player] |= end_mask
else: # TODO: remove since could have no "valid" move
raise AssertionError("invalid move", str(move), self)
self.neutral_card, cards[card_idx] = cards[card_idx], self.neutral_card
self.current_player = 1 - self.current_player
def determine_winner(self):
"""Returns -1 for red win, 1 for blue win, 0 for no win"""
for i in range(2):
# Way of the Stone (capture opponent master)
if not self.bitboard_king[i]:
return 1 - i * 2
# Way of the Stream (move master to opposite square)
if self.bitboard_king[i] == self.WIN_BITMASK[i]:
return i * 2 - 1
return 0
def piece_evaluate(self):
"""Evaluates a given board position. Very arbitrary.
Each piece is worth 2, king is worth 4.
"""
evaluation = 0
for player in range(2):
player_sign = player * 2 - 1
evaluation += player_sign * 4 * count_bits(self.bitboard_king[player])
evaluation += player_sign * 2 * count_bits(self.bitboard_pawns[player])
return evaluation
def centre_priority_evaluate(self):
"""Evaluates a given board position
More points are given to pieces closer to the centre of the board
"""
evaluation = 0
for player in range(2):
player_sign = player * 2 - 1
for i in range(4):
score = i + 1
evaluation += player_sign * score * count_bits(self.bitboard_king[player] &
self.CENTRE_PRIORITY_BITMASKS[i])
evaluation += player_sign * score * count_bits(self.bitboard_pawns[player] &
self.CENTRE_PRIORITY_BITMASKS[i])
return evaluation
def evaluate(self, mode=0):
"""Evaluates a given board position.
uses different evaluation heuristic depending on mode
Assigns a win to +/-50.
"""
winner = self.determine_winner()
if winner:
return winner * self.WIN_SCORE
if mode == 1:
return self.centre_priority_evaluate()
elif mode == 2:
return 0.5 * (self.centre_priority_evaluate() + self.piece_evaluate())
else:
return self.piece_evaluate()
ONITAMA_CARDS = {
# symmetrical
"tiger": Card("tiger", 1, Point(0, -2), Point(0, 1)),
"dragon": Card("dragon", 0, Point(-2, -1), Point(2, -1), Point(-1, 1), Point(1, 1)),
"crab": Card("crab", 1, Point(0, -1), Point(-2, 0), Point(2, 0)),
"elephant": Card("elephant", 0, Point(-1, -1), Point(1, -1), Point(-1, 0), Point(1, 0)),
"monkey": Card("monkey", 1, Point(-1, -1), Point(1, -1), Point(-1, 1), Point(1, 1)),
"mantis": Card("mantis", 0, Point(-1, -1), Point(1, -1), Point(0, 1)),
"crane": Card("crane", 1, Point(0, -1), Point(-1, 1), Point(1, 1)),
"boar": Card("boar", 0, Point(0, -1), Point(-1, 0), Point(1, 0)),
# left-leaning
"frog": Card("frog", 0, Point(-1, -1), Point(-2, 0), Point(1, 1)),
"goose": Card("goose", 1, Point(-1, -1), Point(-1, 0), Point(1, 0), Point(1, 1)),
"horse": Card("horse", 0, Point(0, -1), Point(-1, 0), Point(0, 1)),
"eel": Card("eel", 1, Point(-1, -1), Point(1, 0), Point(-1, 1)),
# right-leaning
"rabbit": Card("rabbit", 1, Point(1, -1), Point(2, 0), Point(-1, 1)),
"rooster": Card("rooster", 0, Point(1, -1), Point(-1, 0), Point(1, 0), Point(-1, 1)),
"ox": Card("ox", 1, Point(0, -1), Point(1, 0), Point(0, 1)),
"cobra": Card("cobra", 0, Point(1, -1), Point(-1, 0), Point(1, 1)),
}
CARD_INDEX = list(ONITAMA_CARDS)
INDEX_CARD = {card: i for i, card in enumerate(CARD_INDEX)} |
7beb9513f2a745fc7bbdecae583da956cd317a75 | pombredanne/victims-lib-python | /test_cases/3.x tests/classesAndImports2.py | 380 | 3.515625 | 4 | #This program prints hello world twice
import sys
class HelloWorldGenerator():
"""Wooo a docstring"""
def __init__(self):
#functions might not just have comments
print("HelloWorld")
self.str = "Hello World"
def sayHello(self,string:'wow_an_annotation'):
print(self.str)
def main():
hwg = HelloWorldGenerator()
hwg.sayHello()
if __name__ == '__main__':
main() |
55b4ec53a56a23c88096f026f57e4e598bae30b0 | pranavtailor/LoginPage | /LoginGui.py | 3,476 | 3.65625 | 4 | import tkinter as tk
import tkinter.font as font
root = tk.Tk()
HEIGHT = 400
WIDTH = 300
# Create account Page
def createAccount():
topCreate = tk.Toplevel(height = HEIGHT, width = WIDTH)
topCreate.title("Register")
# put info in text doc
def storeData():
Users = open('Users.txt', 'a')
username = user_login_entry.get()
password = pass_login_entry.get()
Users.write(username + ', ' + password + "\n")
Users.close()
topCreate.destroy()
# Enter username
user_login_label = tk.Label(topCreate, text = "Enter Username: ")
user_login_label.place(relx = .3, rely = .1)
user_login_label['font'] = myFont
user_login_entry = tk.Entry(topCreate)
user_login_entry.place(relx = .3, rely = .2, relwidth = .4, relheight = .1)
# Enter password
pass_login_label = tk.Label(topCreate, text = "Enter Password: ")
pass_login_label.place(relx = .3, rely = .4)
pass_login_label['font'] = myFont
pass_login_entry = tk.Entry(topCreate)
pass_login_entry.place(relx = .3, rely = .5, relwidth = .4, relheight = .1)
# Enter button
enter_login_button = tk.Button(topCreate, text = "Enter", command = storeData)
enter_login_button.place(relx = .3, rely = .7, relwidth = .4, relheight = .1)
# Login page
def login():
topLogin = tk.Toplevel(height = HEIGHT, width = WIDTH)
topLogin.title("Login")
# check login info with text doc
def checkData():
Users = open('Users.txt', 'r')
text = Users.readlines()
newList = []
for line in text:
newList.append(line.strip())
username = user_login_entry.get()
password = pass_login_entry.get()
cred = (username + ', ' + password)
v = tk.StringVar()
successLabel = tk.Label(topLogin, textvariable = v)
successLabel.place(relx = .1, rely = .85, relwidth = .8)
if cred in newList:
v.set("Login successful!")
successLabel.configure(fg = 'green')
else:
v.set("Invalid credentials, try again.")
successLabel.configure(fg = 'red')
Users.close()
# Enter username
user_login_label = tk.Label(topLogin, text = "Enter Username: ")
user_login_label.place(relx = .3, rely = .1)
user_login_label['font'] = myFont
user_login_entry = tk.Entry(topLogin)
user_login_entry.place(relx = .3, rely = .2, relwidth = .4, relheight = .1)
# Enter password
pass_login_label = tk.Label(topLogin, text = "Enter Password: ")
pass_login_label.place(relx = .3, rely = .4)
pass_login_label['font'] = myFont
pass_login_entry = tk.Entry(topLogin)
pass_login_entry.place(relx = .3, rely = .5, relwidth = .4, relheight = .1)
# Enter button
enter_login_button = tk.Button(topLogin, text = "Enter", command = checkData)
enter_login_button.place(relx = .3, rely = .7, relwidth = .4, relheight = .1)
# define font
myFont = font.Font(family = 'Helvetica', size = 12)
# Homepage
canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()
login_button = tk.Button(canvas, text = "Login", command = login)
login_button.place(relx = .3, rely = .3, relwidth = .4, relheight = .1)
create_button = tk.Button(canvas, text = "Create an account", command = createAccount)
create_button.place(relx = .3, rely = .5, relwidth = .4, relheight = .1)
root.mainloop()
|
9649b2243dd2b2f593fcf5943f6fea83699b39ae | z-mac/MyFirstWork | /src/test/add.py | 439 | 3.59375 | 4 | '''
Created on 2018年2月23日
@author: Administrator
'''
class Adder():
def __init__(self, start = []):
self.data = start
def add(self, y):
print('Not Implemented')
def __add__(self, other):
return self.add(self.data, other)
class ListAdder(Adder):
def add(self, y):
return self.data + y
class DictAdder(Adder):
def add(self, y):
pass
|
a803ef403052f87a2825f4b54c66dbb382ff35bd | hornsbym/WarGame | /_modules/Label.py | 3,966 | 4.0625 | 4 | """
author: Mitchell Hornsby
file: Label.py
purpose: Provides an object that displays text on a Pygame surface.
"""
import pygame as pg
class Label(object):
def __init__(self, text, position, font, fontColor=(0,0,0), bgColor=(255,255,255), padding=(10, 6), transparent=False, visible=True):
""" text = String describing what to write
position = Tuple of x-y values describing where to create the label
font = Pygame Font object describing how to write the text
fontColor = (Optional) Color the text should appear as
bgColor = (Optional) Background color the text should be mounted on
padding = (Optional) Tuple describing how much space should be between the text and the border
"""
self.text = text
self.position = position
self.font = font
self.fontColor = fontColor
self.bgColor = bgColor
self.xPadding = padding[0]
self.yPadding = padding[1]
self.transparent = transparent
self.visible = visible
self.surface = None
self.textWidth = None
self.textHeight = None
self.width = None
self.height = None
self.create()
def __str__(self):
""" For testing purposes."""
return "<Label text:'%s' position:(%i, %i)>" % (self.text, self.position[0], self.position[1])
def getWidth(self):
""" Returns Int."""
return self.width
def getHeight(self):
""" Returns Int."""
return self.height
def isHovering(self, coords):
""" Accepts a tuple of (x, y) coordinates.
Checks whether these coordinates are within range of the label's width/height.
Returns True is the coordinates are within the bounds of the width/height.
Returns False if otherwise."""
xRange = self.getPosition()[0] + self.getWidth()
yRange = self.getPosition()[1] + self.getHeight()
if coords[0] > self.getPosition()[0] and coords[0] < xRange and self.active == True:
if coords[1] > self.getPosition()[1] and coords[1] < yRange:
return True
return False
def getTextWidth(self):
"""Returns Int."""
return self.textWidth
def getTextHeight(self):
"""Returns Int."""
return self.textHeight
def getPosition(self):
"""Returns tuple of form (x, y)"""
return self.position
def hide(self):
""" Tells the widget not to show itself."""
self.visible = False
def unHide(self):
""" Tells the widget to show itself."""
self.visible = True
def move(self, newCoords):
""" Accepts a tuple of x-y values.
Moves the label to that new position."""
self.position = newCoords
self.create()
def create(self):
""" Creates the label upon initilization."""
font = self.font
self.surface = font.render(self.text, True, self.fontColor)
self.textWidth = self.surface.get_width()
self.textHeight = self.surface.get_height()
self.width = self.textWidth + self.xPadding
self.height = self.textHeight + self.yPadding
def show(self, display):
""" Accepts a Pygame display.
Draws the label on the provided display.
If position is 'None', this methods does nothing."""
if self.visible == True:
if self.position != None:
if self.transparent == False:
pg.draw.rect(display, self.bgColor, (self.position[0], self.position[1], self.width, self.height))
display.blit(self.surface, (self.position[0] + self.xPadding/2, self.position[1] + self.yPadding/2))
def updateText(self, string):
""" Accepts a String.
Changes the label's text to reflect this string."""
self.text = string
self.create() |
82e800234cfedfc6a350df2090302a27a039fa01 | iain-waugh/iw_pyutils | /array_extras.py | 5,417 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Extend the standard Numpy array manipulation routines,
particularly for 2D array operations.
Copyright (C) 2021 - Iain Waugh, iwaugh@gmail.com
"""
from __future__ import print_function, division
import numpy as np
__version__ = "1.0.0"
def shift_2d(arr, shifts, stride=0):
"""
Shift a 2D array by rows/columns and either pad the new data with zeros or
copy existing data from the trailing edge of the shift.
Parameters
----------
arr : 2D numpy array
The input arrray
shift_row
How many rows to shift up/down
shift_col
How many columns to shift left/right
stride
How many of the previous rows/columns to repeat
0 = fill with zeros (default)
1 = copy the last row/column
2 = copy the last 2 rows/columns (good for working with Bayer paterns)
Returns
-------
An array that is shifted by 'shift_row' and 'shift_col', with new data determined by 'stride'
"""
(shift_row, shift_col) = shifts
row_arr = np.zeros_like(arr)
if stride > 0:
quot = abs(shift_row) // stride
rem = shift_row % stride
if rem != 0:
quot += 1
if shift_row > 0:
if stride > 0:
stride_arr = np.tile(arr[:stride, :], (quot, 1))[-shift_row:, :]
row_arr = np.vstack((stride_arr, arr[:-shift_row, :]))
else:
row_arr[shift_row:, :] = arr[:-shift_row, :]
elif shift_row < 0:
if stride > 0:
stride_arr = np.tile(arr[-stride:, :], (quot, 1))[:-shift_row, :]
row_arr = np.vstack((arr[-shift_row:, :], stride_arr))
else:
row_arr[:shift_row, :] = arr[-shift_row:, :]
else:
row_arr[:, :] = arr[:, :]
# Shift the Columns
if stride > 0:
quot = abs(shift_col) // stride
rem = shift_col % stride
if rem != 0:
quot += 1
new_arr = np.zeros_like(arr)
if shift_col > 0:
if stride > 0:
stride_arr = np.tile(row_arr[:, :stride], (1, quot))[:, -shift_col:]
new_arr = np.hstack((stride_arr, row_arr[:, :-shift_col]))
else:
new_arr[:, shift_col:] = row_arr[:, :-shift_col]
elif shift_col < 0:
if stride > 0:
stride_arr = np.tile(row_arr[:, -stride:], (1, quot))[:, :-shift_col]
new_arr = np.hstack((row_arr[:, -shift_col:], stride_arr))
else:
new_arr[:, :shift_col] = row_arr[:, -shift_col:]
else:
new_arr[:, :] = row_arr[:, :]
return new_arr
def add_border_2d(arr, border_width, stride=0):
"""
Expand the border of a Numpy array by replicating edge values
Parameters
----------
arr : Numpy ndarray
The ndarray that you want to enlarge.
border_width : integer
How many rows and columns do you want to add to the edge of the ndarray?
stride : integer
How many of the previous rows/columns to repeat
0 = fill with zeros (default)
1 = copy the last row/column
2 = copy the last 2 rows/columns (good for working with Bayer paterns)
Returns
-------
A version of `arr` with borders.
"""
new_x = arr.shape[0] + border_width * 2
new_y = arr.shape[1] + border_width * 2
new_dtype = arr.dtype
new_arr = np.zeros((new_x, new_y), dtype=new_dtype)
new_arr[border_width:-border_width, border_width:-border_width] = arr
if stride > 0:
# We want to copy data from existing rows/columns to into the new border
quot = border_width // stride
rem = border_width % stride
if rem != 0:
quot += 1
# Fill the top
arr_t = new_arr[border_width : border_width + stride, :]
new_arr[:border_width,] = np.tile(
arr_t, (quot, 1)
)[:border_width, :]
# Fill the botton
arr_b = new_arr[-(border_width + stride) : -border_width, :]
new_arr[-border_width:,] = np.tile(
arr_b, (quot, 1)
)[:border_width, :]
# Fill left
arr_l = new_arr[:, border_width : border_width + stride]
new_arr[:, :border_width] = np.tile(arr_l, (1, quot))[:, :border_width]
# Fill the right
arr_b = new_arr[:, -(border_width + stride) : -border_width]
new_arr[:, -border_width:] = np.tile(arr_b, (1, quot))[:, :border_width]
return new_arr
if __name__ == "__main__":
aRow, aCol = (6, 6) # Number of rows and columns
arr = np.arange(1, aRow * aCol + 1).astype("uint16").reshape(aRow, aCol)
print("Original array\n", arr)
n1 = shift_2d(arr, (1, 0), 1)
s1 = shift_2d(arr, (-1, 0), 1)
w1 = shift_2d(arr, (0, 1), 1)
e1 = shift_2d(arr, (0, -1), 1)
print("North 1\n", n1)
print("South 1\n", s1)
print("East 1\n", e1)
print("West 1\n", w1)
n2 = shift_2d(arr, (2, 0), 2)
s2 = shift_2d(arr, (-2, 0), 2)
w2 = shift_2d(arr, (0, 2), 2)
e2 = shift_2d(arr, (0, -2), 2)
print("North 2\n", n2)
print("South 2\n", s2)
print("East 2\n", e2)
print("West 2\n", w2)
print(
"Adding a border of 2 rows/columns, copying data from the outermost row/column"
)
print(add_border_2d(arr, 2, 1))
print(
"Adding a border of 3 rows/columns, copying data from the 3x outermost rows/columns"
)
print(add_border_2d(arr, 3, 3))
|
3369b53aa0325ae1104dd941025cff8ef06593cd | ahmedMshaban/MITx-6.00.1x- | /helloworld.py | 316 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 13:14:05 2019
@author: ahmedshaban
"""
count = 0
s = 'azcbobobegghakl'
for letter in s:
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
count += 1
print ("Number of vowels: " + str(count)) |
a34aa5e03ca7177a6455364c394fb1d6a1c7c866 | springrolldippedinsoysauce/pythonshit | /FileIO/Main.py | 2,064 | 3.609375 | 4 | import FileIO.StockDriver as stockDriver
def menu():
loop = False
driver = None
while not loop:
print("==========================================================================")
print("Welcome to the Stock Exchange!")
print("==========================================================================")
print("\nWhat would you like to do?")
print(
"1. Add STOCK file\n2. Display STOCK information\n3. Serialize a file\n4. Read a serialised file\n5. Exit")
choice = str(input("Enter one of the choice > "))
loop = (choice == "5")
if choice == "1":
if driver is None:
driver = pass_file(driver)
else:
overwrite = str(input("File has been written, overwrite?\n[Y/N]\n"))
if overwrite == "Y" or overwrite == "y":
pass_file(driver)
elif overwrite == "N" or overwrite == "n":
print("...Returning to interface...")
else:
print("Y or N, things you see when you have eyes")
elif choice == "2":
if driver is not None:
driver.display()
elif choice == "3":
if driver is not None:
driver.pickling(str(input("Enter the name for the pickled file > ")))
elif choice == "4":
driver = stockDriver.unpickling(str(input("Enter the name of the file for unpickling > ")))
elif choice == "5":
print("//..Exiting..//")
else:
print("Error: Incorrect user input, try again.")
menu()
def pass_file(driver):
file = str(input("Enter a valid stock file > "))
save = str(input("Enter the name of the save file > "))
if file is None or file == "":
print("Invalid file import!")
pass_file(driver)
else:
driver = stockDriver.StockDriver(file, save)
print("File added!")
return driver
menu() |
b14efeb7a750b4de30abc061fbbeb62ba94fe2f0 | springrolldippedinsoysauce/pythonshit | /Hashing/HashTable.py | 5,880 | 4 | 4 | class HashEntry:
empty = None
key = None
value = None
used = None
def __init__(self):
self.empty = True
self.used = False
self.key = ""
self.value = None
class HashTable:
def __init__(self, max_size):
if max_size < 1:
print("Nah")
# Returns the next lower prime greater than max size unless capacity is prime
self.capacity = self.next_prime(max_size)
self.size = 0
self.hash_table = []
for i in range(self.capacity):
self.hash_table.append(HashEntry())
self.max_step = 0
self.set_max_step()
def set_max_step(self):
self.max_step = self.next_prime(self.capacity / 2)
def get_size(self):
return self.size
def load_factor(self):
return float(self.size) / float(self.capacity)
def resize(self):
# Increase/decrease capacity in order to make load
print("Current load factor is ", self.load_factor())
old_capacity = self.capacity
self.capacity = self.next_prime(int(float(self.size) / 0.5))
print("New capacity is ", self.capacity)
self.set_max_step() # Calculate new step from new capacity
self.size = 0
old_table = self.hash_table
self.hash_table = []
for i in range(self.capacity):
self.hash_table.append(HashEntry) # New table
for j in range(old_capacity):
if old_table[j].empty is False:
self.put(old_table[j].key, old_table[j].value)
print("Resize called ==> new capacity: ", self.capacity)
def next_prime(self, start):
if start % 2 == 0: # Even numbers aren't prime
prime = start + 1
else:
prime = start
is_prime = self.check_prime(prime) # Check if already prime
while is_prime is False:
prime += 2
is_prime = self.check_prime(prime)
return prime
# Generates a unique integer index from passed key
def hash(self, key):
hash_idx = hash(key)
return hash_idx % self.capacity
# Generates a second index for double hashing
@staticmethod
def probe_hash(key):
hash_idx = hash(key)
return hash_idx
# Insert value into hash table
# Returns true if passed int is prime
@staticmethod
def check_prime(prime):
i = 3
is_prime = True
while i * i <= prime and prime is True:
if prime % i == 0:
is_prime = False
i += 2
return is_prime
def put(self, key, value):
if self.load_factor() >= 0.6:
self.resize()
index = self.hash(key)
step = self.probe_hash(key)
if self.hash_table[index].empty is True:
print(f'Inserting {value} with key {key} at index {index}')
self.hash_table[index].key = key
self.hash_table[index].value = value
self.hash_table[index].empty = False
self.hash_table[index].used = True
self.size += 1
else:
self.insert_linear_probing(index, key, value, step)
def insert_linear_probing(self, index, key, value, step):
loop = False
while loop is False:
index = (index + step) % self.capacity
if self.hash_table[index].empty is True:
loop = True # Replacement for Do-While
print(f'Inserting {value} with key {key} at index {index}')
self.hash_table[index].key = key
self.hash_table[index].value = value
self.hash_table[index].empty = False
self.hash_table[index].used = True
self.size += 1
def find(self, key):
index = self.hash(key)
step = self.probe_hash(key)
if self.hash_table[index].key == key:
value = self.hash_table[index].value
else:
value = self.find_linear_probing(index, key, step)
return value
def find_linear_probing(self, index, key, step):
value = None
loop = False
while loop is False:
if self.hash_table[index].used is False:
raise NoSuchElementError(f'No element with key {key} exists in the table.\n')
index = (index + step) % self.capacity
if self.hash_table[index].key == key:
value = self.hash_table[index].value
loop = True
return value
def remove(self, key):
if self.load_factor() <= 0.4:
self.resize()
index = self.hash(key)
step = self.probe_hash(key)
if self.hash_table[index].key == key:
self.hash_table[index].key = ""
self.hash_table[index].value = None
self.hash_table[index].empty = True
self.size -= 1
else:
self.remove_linear_probing(index, key, step)
def remove_linear_probing(self, index, key, step):
loop = False
while loop is False:
if self.hash_table[index].used is False:
raise NoSuchElementError(f'No element with key {key} exists in the table.\n')
index = (index + step) % self.capacity
if self.hash_table[index].key == key:
loop = True
self.hash_table[index].key = ""
self.hash_table[index].value = None
self.hash_table[index].empty = True
self.size -= 1
class Error(Exception):
pass
class NoSuchElementError(Error):
"""Exception raised if list encounters an error.
Attributes:
message --- explanation of the error
"""
def __init__(self, message):
self._message = message
|
0cb6b2083d80d47a117d55dc33f50b0379afcd6f | Olayinka2020/ds_wkday_class | /practice.py | 4,012 | 4.125 | 4 | # Given a two integer numbers return their product and if the product is greater than 1000, then return their sum
# a = int(input("First integer: "))
# b = int(input("Second integer: "))
# product = (a * b)
# sum = (a + b)
# if(product <= 1000):
# print(product)
# else:
# print("The product is more than 1000, hence the sum is: ", sum)
# def hello_world(num):
# return num * num * num
# print(hello_world(5))
# Create a function that can accept two arguments name and age and print its value
# def demo(name, age):
# return name, age
# print(demo('Yinka', 27))
# def adder(x, y):
# return x + y
# print(adder(5, 3))
# Define a function that converts from temperatures in Fahrenheit to temperatures in Kelvin, and another function that converts back again.
# def Kelvin(fah):
# return (fah - 32) * (5/9) + 273.15
# print(Kelvin(75))
# def cal(a, b):
# return a + b, a - b
# print(cal(5, 6))
# def func1(args):
# for arg in args:
# print(arg)
# def emp(name, salary):
# return name, salary
# if(salary == 0 ):
# print(9000)
# elif print(emp("Yinka", 10000)):
# else:
# print(name, salary)
# Question 1: Print First 10 natural numbers using while loop
# i = 1
# while (i <= 10):
# print(i, end = " ")
# i += 1
# for i in range (1, 6):
# print(i, len(i), end = " ")
# print()
# x = int(input("Enter a number: "))
# sum = 0
# for i in range(1, x + 1, 1):
# sum = sum + i
# print("\n")
# print( sum)
# sum1 = 0
# n = int(input("Please enter number "))
# for i in range(1, n + 1, 1):
# sum1 += i
# print("\n")
# print("Sum is: ", sum1)
#6 x = input("Enter a number: ")
# print(len(x))
# list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
# for i in list1:
# if i <= 150 and i % 5 == 0:
# print(i)
# list1 = [10, 20, 30, 40, 50]
# list1.reverse()
# print(list1)
# x = int(input("Enter a number: "))
# i = 1
# while i <= 12:
# product = x * i
# i += 1
# print(product, end =" ")
# i = 1
# while i <= 4:
# print("Hello World")
# i += 1
# x, y = 2, 6
# x, y = y, x + 2
# print(x, y)
# x = '''This is a multiline
# string
# written in
# three liness'''
# print(x)
# x = 0
# y = 0
# def incr(x):
# y = x + 1
# return y
# incr(5)
# print(x, y)
# pi = 3.14
# def area (r):
# return pi * (r * r)
# print(area(6))
# numcalls = 0
# def square (x):
# global numcalls
# numcalls = numcalls + 1
# return x * x
# print(square(6))
# x = 1
# def f():
# return x
# print(x)
# print(f())
# def count_digits(x):
# return len(x)
# print(count_digits(6567))
# x = int(input("Enter the first integer: "))
# y = int(input("Enter the second integer: "))
# product = x * y
# sum = x + y
# if product < 1000:
# print(product)
# else:
# print("The product is greater than 1000, so the sum is: ", sum)
# def pro_sum(x, y):
# product = x * y
# sum = x + y
# if product <= 1000:
# return product
# else:
# return sum
# print(pro_sum(123, 34))
# def removechars(str, n):
# return str[n:]
# print("Removing n number of chars")
# print(removechars("pynative", 4))
# def isfirst_and_last_same(numberlist):
# print("Given list is ", numberlist)
# firstElement = numberList[0]
# lastElement = numberlist[-1]
# if firstElement == lastElement:
# return True
# else:
# return False
# numList = [10, 20, 30, 40, 10]
# print("The result is: ", isfirst_and_last_same(numList))
# list = [10, 20, 33, 46, 55]
# for i in list:
# if i % 5 == 0:
# print (i)
# for num in range (10):
# for i in range (num):
# print (num, end = " ")
# print("\n")
# num = 121
# if
# for i in range (1, 11):
# for j in range (1, 11):
# print(i * j, end = " ")
# print("\t\t") |
2d8d833c7ef4ea7411848251e673088c3ea18c88 | GauravKTri/-All-Python-programs | /calculator.py | 334 | 4.28125 | 4 | num1=float(input("Enter the first number"))
num2=float(input("Enter the second number"))
num3=input("input your operation")
if num3=='+':
print(num1+num2)
if num3=='+':
print(num1+num2)
if num3=='-':
print(num1-num2)
if num3=='/':
print(num1/num2)
if num3=='*':
print(num1*num2)
if num3=='%':
print(num1%num2)
|
777e2b1f0f996f15264480824925ca5887b2d67b | GauravKTri/-All-Python-programs | /if-else.py | 105 | 3.875 | 4 | v=8
print("enter a number")
v2=int(input())
if(v2>v):
print("greater")
else:
print("smaller") |
740df03bac4c0b8d7513cff0d73344133cd83f92 | GauravKTri/-All-Python-programs | /pattern wrong.py | 261 | 4.0625 | 4 | print("pattern printing")
a=int(input("Enter how many rows you want:\n"))
print("Enter 1 or 0")
b=bool(input("1 for true and 0 for false:\n"))
if b=="1":
for i in range(0,a+1):
print("*"*i)
if b=="0":
for i in range(a,0,-1):
print("*"*i) |
764f75c9c2cdcbf001efd9cd958a1708a07b02af | GauravKTri/-All-Python-programs | /function.py | 411 | 3.78125 | 4 | def avg(a,b):
"""This is doc type of a function in
which we write for what we have made the function"""
average=(a+b)/2
#print(average)
return average #return is must to get value,not to get none
""" this is not doc type ,this is comment
for multi line """
''' this is also a multi line comment to check that
single cote also works'''
v=avg(6,8)
print(v)
print(avg.__doc__) |
979920ae73ed9e7dde27d8749c20e2d93a473d4f | sandhoefner/sandhoefner.github.io | /6034/lab3/toytree.py | 6,304 | 3.59375 | 4 | # MIT 6.034 Lab 3: Games
from game_api import *
from copy import deepcopy
class ToyTree :
def __init__(self, label=None, score=None) :
self.score = score
self.label = label
self.children = []
self.zipper = []
self.sibling_index = None
# sibling index records how many left siblings this node has.
self.sibling = None
def __eq__(self, other) :
return [self.score, self.label, self.children, self.zipper] == [other.score, other.label, other.children, other.zipper]
def __str__(self, tab=0) :
ret = ""
for x in self.children :
ret += x.__str__(tab+1)
ret = ("-" * 3 * tab) + (" " * (tab > 0) ) + (self.label or "node") + ("("+str(self.score)+")" if self.score is not None else "") + "\n" + ret
return ret
def copy(self):
return deepcopy(self)
def describe_previous_move(self) :
return "Took branch "+str(self.sibling_index) if self.sibling_index is not None else "[none]"
def get_score(self) :
return self.score
def set_score(self, score) :
self.score = score
return self
def append(self, child) :
"""Append a ToyTree child node to the end of the list of children."""
child.zipper = []
child.sibling_index = len(self.children)
self.children.append(child)
if len(self.children) > 1 :
self.children[-2].sibling = child
return self
def sub(self, label=None, value=None) :
return self.append(ToyTree(label, value))
def is_leaf(self) :
return not self.children
# moving around
def down(self) :
"""Visit the first child."""
child = self.children[0]
child.zipper = self.zipper + [self]
return child
def up(self) :
"""Visit parent."""
parent = self.zipper[-1]
parent.zipper = self.zipper[:-1]
return parent
def right(self) :
"""Visit sibling."""
assert self.sibling
self.sibling.zipper = self.zipper
return self.sibling
def top(self) :
"""Visit root."""
if self.zipper :
return self.zipper[0]
else :
return self
def create_toy_tree(name_to_score, nested_list) :
"""Creates a ToyTree from two inputs:
1. a dict mapping node names to scores, eg {"A":3, "B":2}
2. a nested list of node names. A well-formed nested list is a pair whose
first element is a node name, and whose second element is a (possibly empty)
list containing well-formed nested lists, each of which represents a subtree.
If a node is not in the the input dict, its score is assumed to be 0.
"""
label, sublists = nested_list
root = ToyTree(label, name_to_score.get(label, 0))
children = [create_toy_tree(name_to_score, sublist) for sublist in sublists]
for child in children:
root.append(child)
return root
# OR EQUIVALENTLY:
# return reduce(lambda parent, child : parent.append(child),
# map(lambda x : create_toy_tree(score_dict, x), nested_list[1]),
# ToyTree(nested_list[0], score_dict.get(nested_list[0])))
def wrapper_toytree(score_dict, nested_list) :
tree = create_toy_tree(score_dict, nested_list)
return AbstractGameState(snapshot = tree,
is_game_over_fn = toytree_is_game_over,
generate_next_states_fn = toytree_generate_next_states,
endgame_score_fn = toytree_endgame_score)
# TREE FOR ALL SEARCHES
tree4 = ToyTree()
tree4.sub().sub().sub().sub()
tree4.down().sub(None,7).sub(None,11).sub(None, 3).sub(None, 10)
tree4.down().right().sub(None,4).sub(None,9).sub(None, 14).sub(None, 8)
tree4.down().right().right().sub(None,5).sub(None,2).sub(None, 12).sub(None, 16)
tree4.down().right().right().right().sub(None,15).sub(None,6).sub(None, 1).sub(None, 3)
# If max goes first, 4 is the minimax score, and alpha-beta prunes 3 nodes.
# If min goes first, 11 is the minimax score, and alpha-beta prunes 5 nodes.
# [[[7],[11],[3],[10]],[[4],[9],[14],[8]], [[5],[2],[12],[16]], [[15],[6],[1],[13]]]
def toytree_is_game_over(tree) :
return tree.children == []
def toytree_generate_next_states(tree) :
return tree.children
def toytree_endgame_score_fn(tree, is_current_player_maximizer) :
return tree.score
GAME1 = AbstractGameState(tree4,
toytree_is_game_over,
toytree_generate_next_states,
toytree_endgame_score_fn)
def toytree_heuristic_fn(tree, is_current_player_maximizer) :
return tree.score
# 2013 final part 1D
tree5 = ToyTree("A",10) # static values at all levels
tree5.sub("B",11).sub("C",2).sub("D",3).sub("E",6)
tree5.down().sub("F",10).sub("G",12)
tree5.down().down().right().sub("K",7).sub("L",11)
tree5.down().right().sub("H",9).sub("I",12)
tree5.down().right().down().right().sub("M",12).sub("N",13)
tree5.down().right().right().right().sub("J",7).down().sub("O",8)
GAME_STATIC_ALL_LEVELS = AbstractGameState(tree5,
toytree_is_game_over,
toytree_generate_next_states,
toytree_endgame_score_fn)
tree6 = ToyTree("A")
tree6.sub("B").sub("C")
tree6.down().sub("D").sub("E")
tree6.down().right().sub("F").sub("G")
tree6.down().down().sub("H").sub("I")
tree6.down().down().right().sub("J").sub("K")
tree6.down().right().down().sub("L").sub("M")
tree6.down().right().down().right().sub("N")
tree6.down().down().down().sub("O",3).sub("P",17)
tree6.down().down().down().right().sub("Q",2).sub("R",12)
tree6.down().down().right().down().sub("S",15)
tree6.down().down().right().down().right().sub("T",25).sub("U",0)
tree6.down().right().down().down().sub("V",2).sub("W",5)
tree6.down().right().down().down().right().sub("X",3)
tree6.down().right().down().right().down().sub("Y",2).sub("Z",14)
# A tree that checks exit condition of alpha = beta.
GAME_EQUALITY_PRUNING = AbstractGameState(tree6,
toytree_is_game_over,
toytree_generate_next_states,
toytree_endgame_score_fn)
|
215ea7fc3c7f1911948258214c20c25bfe91bee5 | sandhoefner/sandhoefner.github.io | /6034/lab6/lab6.py | 7,609 | 3.6875 | 4 | # MIT 6.034 Lab 6: Neural Nets
# Written by Jessica Noss (jmn), Dylan Holmes (dxh), Jake Barnwell (jb16), and 6.034 staff
from nn_problems import *
from math import e
INF = float('inf')
#### NEURAL NETS ###############################################################
# Wiring a neural net
nn_half = [1]
nn_angle = [2, 1]
nn_cross = [2, 2, 1]
nn_stripe = [3, 1]
nn_hexagon = [6, 1]
nn_grid = [4, 2, 1]
# Threshold functions
def stairstep(x, threshold=0):
"Computes stairstep(x) using the given threshold (T)"
if x >= threshold:
return 1
return 0
def sigmoid(x, steepness=1, midpoint=0):
"Computes sigmoid(x) using the given steepness (S) and midpoint (M)"
return float(1) / (1 + e ** (-steepness * (x - midpoint)))
def ReLU(x):
"Computes the threshold of an input using a rectified linear unit."
if x < 0:
return 0
return x
# Accuracy function
def accuracy(desired_output, actual_output):
"Computes accuracy. If output is binary, accuracy ranges from -0.5 to 0."
diff = actual_output - desired_output
# from lecture notes (performance, not accuracy)
return -0.5 * (diff ** 2)
# Forward propagation
def node_value(node, input_values, neuron_outputs): # STAFF PROVIDED
"""Given a node, a dictionary mapping input names to their values, and a
dictionary mapping neuron names to their outputs, returns the output value
of the node."""
if isinstance(node, basestring):
return input_values[node] if node in input_values else neuron_outputs[node]
return node # constant input, such as -1
def forward_prop(net, input_values, threshold_fn=stairstep):
"""Given a neural net and dictionary of input values, performs forward
propagation with the given threshold function to compute binary output.
This function should not modify the input net. Returns a tuple containing:
(1) the final output of the neural net
(2) a dictionary mapping neurons to their immediate outputs"""
# for a single neuron:
# each input into the neuron is multiplied by the weight on the wire
# the weighted inputs are summed together
# the sum is passed through a specified threshold function to produce the output
sorted_net = net.topological_sort()
ret = {}
while sorted_net:
node = sorted_net[0]
del sorted_net[0]
neighbors = net.get_incoming_neighbors(node)
total = 0
for neighbor in neighbors:
wire = net.get_wires(neighbor, node)
if neighbor in ret:
total += ret[neighbor] * wire[0].get_weight()
elif isinstance(neighbor, int):
total += neighbor * wire[0].get_weight()
else:
total += input_values[neighbor] * wire[0].get_weight()
ret[node] = threshold_fn(total)
return (ret[net.get_output_neuron()], ret)
# Backward propagation warm-up
def gradient_ascent_step(func, inputs, step_size):
"""Given an unknown function of three variables and a list of three values
representing the current inputs into the function, increments each variable
by +/- step_size or 0, with the goal of maximizing the function output.
After trying all possible variable assignments, returns a tuple containing:
(1) the maximum function output found, and
(2) the list of inputs that yielded the highest function output."""
ret = inputs[:]
maxi = -INF
options = [-step_size, 0, step_size]
for a in options:
for b in options:
for c in options:
if maxi < func(inputs[0] + a, inputs[1] + b, inputs[2] + c):
ret = [inputs[0] + a, inputs[1] + b, inputs[2] + c]
maxi = func(inputs[0] + a, inputs[1] + b, inputs[2] + c)
return (maxi, ret)
def get_back_prop_dependencies(net, wire):
"""Given a wire in a neural network, returns a set of inputs, neurons, and
Wires whose outputs/values are required to update this wire's weight."""
nodes = []
ret = [wire, wire.endNode]
wires = [wire]
while wires:
w = wires[0]
del wires[0]
b = w.endNode
a = w.startNode
ret = ret + [a]
ret = ret + [b]
if b != net.get_output_neuron() and b not in nodes:
wires.extend(net.get_wires(b, None))
ret = ret + net.get_wires(b, None)
nodes = nodes + [a]
nodes = nodes + [b]
return set(ret)
# Backward propagation
def calculate_deltas(net, desired_output, neuron_outputs):
"""Given a neural net and a dictionary of neuron outputs from forward-
propagation,
computes the update coefficient (delta_B) for each
neuron in the net.
Uses the sigmoid function to compute neuron output.
Returns a dictionary mapping neuron names to update coefficient (the
delta_B values). """
ret = {}
sorted_net = net.topological_sort()
for node in sorted_net[::-1]:
if node == net.get_output_neuron():
ret[node] = ((1 - neuron_outputs[node]) * neuron_outputs[node]
* (desired_output - neuron_outputs[node]))
else:
total = 0
for neighbor in net.get_outgoing_neighbors(node):
wire = net.get_wires(node, neighbor)
total = total + wire[0].get_weight() * ret[neighbor]
ret[node] = (1 - neuron_outputs[node]) * neuron_outputs[node] * total
return ret
def update_weights(net, input_values, desired_output, neuron_outputs, r=1):
"""Performs a single step of back-propagation. Computes delta_B values and
weight updates for entire neural net, then updates all weights. Uses the
sigmoid function to compute neuron output. Returns the modified neural net,
with the updated weights."""
deltas = calculate_deltas(net, desired_output, neuron_outputs)
for wire in net.get_wires(None, None):
b = wire.endNode
w = wire.get_weight()
a = wire.startNode
if a in input_values:
wire.set_weight(w + r * input_values[a] * deltas[b])
elif isinstance(a, int):
wire.set_weight(w + r * a * deltas[b])
else:
wire.set_weight(w + r * neuron_outputs[a] * deltas[b])
return net
def back_prop(net, input_values, desired_output, r=1, minimum_accuracy=-0.001):
"""Updates weights until accuracy surpasses minimum_accuracy. Uses the
sigmoid function to compute neuron output. Returns a tuple containing:
(1) the modified neural net, with trained weights
(2) the number of iterations (that is, the number of weight updates)"""
fwd = forward_prop(net, input_values, sigmoid)
counter = 0
currentAccuracy = accuracy(desired_output, fwd[0])
while currentAccuracy < minimum_accuracy:
counter += 1
net = update_weights(net, input_values, desired_output, fwd[1], r)
fwd = forward_prop(net, input_values, sigmoid)
currentAccuracy = max(currentAccuracy, accuracy(desired_output, fwd[0]))
return (net, counter)
# Training a neural net
ANSWER_1 = 35
ANSWER_2 = 35
ANSWER_3 = 6
ANSWER_4 = 250
ANSWER_5 = 40
ANSWER_6 = 1
ANSWER_7 = 'checkerboard'
ANSWER_8 = ['small', 'medium', 'large']
ANSWER_9 = 'b'
ANSWER_10 = 'd'
ANSWER_11 = ['a','c']
ANSWER_12 = ['a','e']
#### SURVEY ####################################################################
NAME = 'Evan Sandhoefner'
COLLABORATORS = 'Ryan Kerr'
HOW_MANY_HOURS_THIS_LAB_TOOK = 12
WHAT_I_FOUND_INTERESTING = 'Getting under the hood of a neural net'
WHAT_I_FOUND_BORING = 'writing helper functions'
SUGGESTIONS = None
|
c29e30dc572cf85aa394b2902922383a74539529 | tabatagloria/exercicios-uri | /Python/1018.py | 178 | 3.5625 | 4 | n = int(input())
lista = [100, 50, 20, 10, 5, 2, 1]
print('{}'.format(n))
for i in lista:
notas = n // i
n = n % i
print('{} nota(s) de R$ {},00'.format(notas, i))
|
bd44668fbed826ab124e7a45ee67f15937d42c9d | tabatagloria/exercicios-uri | /Python/1010.py | 231 | 3.578125 | 4 | cod1 = int(input())
pecas1 = int(input())
valor1 = float(input())
cod2 = int(input())
pecas2 = int(input())
valor2 = float(input())
total = pecas1 * valor1 + pecas2 * valor2
print('VALOR A PAGAR: R$ {}'.format(round(total, 2)))
|
2101666625cd541714b52dbfca46491650f46ccf | dariansk/files-sorted | /main.py | 1,055 | 3.6875 | 4 | def convert_file_to_list(file):
with open(file, 'r', encoding='utf-8') as f:
text_list = f.readlines()
return text_list
# сортируем файлы и записываем их в результирующий файл
# спасибо гуглу за подсказку, как сортировать словарь по значениям
def write_to_sorted_file():
files = {'1.txt': convert_file_to_list('1.txt'), '2.txt': convert_file_to_list('2.txt'),
'3.txt': convert_file_to_list('3.txt')}
sorted_list = sorted(files.items(), key= lambda value: len(value[1]))
files_sorted_dict = {item[0]:item[1] for item in sorted_list}
with open('file_sorted.txt', 'w', encoding='utf-8') as file:
for item in list((files_sorted_dict.keys())):
file.write(f'{item}\n')
file.write(str(len(files_sorted_dict.setdefault(item))) + '\n')
for str_dict in files_sorted_dict[item]:
file.write(str_dict)
file.write('\n')
write_to_sorted_file()
|
cd3b288dc03da30a69439727191cb18e429d943a | olympiawoj/Algorithms | /stock_prices/stock_prices.py | 1,934 | 4.3125 | 4 | #!/usr/bin/python
"""
1) Understand -
Functions
- find_max_profit should receive a list of stock prices as an input, return the max profit that can be made from a single buy and sell. You must buy first before selling, no shorting
- prices is an array of integers which represent stock prices and we need to find the max, the min, and subtract
- TO solve this, we need to find out the max profit and minimum
[1, 3, 2]
Max profit = 2
3-2 = 1
[4, 8, 1]
I have to buy 4
Sell 8
Max profit = 4
So we start with the maxProfit = arr[1] - arr[0]
We need to track the min price arr[0]
TO DO
- Iterate through array prices
- For each current_price, if that price - min price > maxProfit, then define a new max
- For each current price, if that cur price is less than the min price, define a new min
- Update variables if we find a higher max profit and/or a new min price
"""
import argparse
def find_max_profit(prices):
# Tracks min price and current max profit
minPrice = prices[0]
maxProfit = prices[1] - minPrice
# could also do
# for currentPrice in prices[1:]
for i in range(1, len(prices)):
print('loop', prices[i])
print('i', i)
maxProfit = max(prices[i] - minPrice, maxProfit)
minPrice = min(prices[i], minPrice)
print('min', minPrice)
print('maxProfit', maxProfit)
return maxProfit
if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(
description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(
profit=find_max_profit(args.integers), prices=args.integers))
# print(find_max_profit([1050, 270, 1540, 3800, 2]))
|
9391b65636aebee9a50ed4aa57430319a5a07d81 | roymatchuu/LoanCal | /LoanHandler.py | 2,593 | 3.5625 | 4 | import openpyxl
import os
from Loan import *
from datetime import datetime
# method for calculating the number of days for subsidized a subsidized loan
def calculateDays(loan):
today = datetime.today().strftime("%m/%d/%y")
borDate = datetime.strftime(loan.dateBorrowed.value, "%m/%d/%y")
a = datetime.strptime(borDate, "%m/%d/%y")
b = datetime.strptime(today, "%m/%d/%y")
dTime = b - a
return b - a
# method for calculating the loan
def loanCal(l):
amount = 0
print("Please answer the next question using Y or N.\n")
inSchool = input("Are you currently in school? ")
for i in range(len(l)):
loanType = l[i].type.value
if inSchool == 'Y' or inSchool == 'y':
if loanType[0] == 'S':
# print("In Subsidized if")
# print("added value: ", l[i].amount.value)
amount += l[i].amount.value
elif loanType[0] == 'U':
temp = calculateDays(l[i])
numDays = temp.days
tempAmt = (l[i].interest.value/36500) * l[i].amount.value
# print("accrued interest: ", l[i].interest.value/36500)
# print("tempAmt: ", tempAmt)
# print(numDays)
# print("accrued interest: ", tempAmt * numDays)
# print("testVal: ", l[i].amount.value + (tempAmt * numDays))
# # print("t2: ", tempAmt * numDays)
# # print(amount + (tempAmt * numDays))
# print(l[i].name.value, ": ", l[i].amount.value)
# print("added unsub value: ", (tempAmt * numDays) + l[i].amount.value)
amount += (tempAmt * numDays) + l[i].amount.value
print("Your total amount of loans is approximately worth $", "%.2f" % amount)
def main():
os.chdir('D:\Documents - HDD')
wb = openpyxl.load_workbook('Loan_Spreadsheet.xlsx')
type(wb)
# changing the sheet to the "List" sheets where the loans are
wb.active = 1
sheet = wb.active
loanList = []
# creates the "Loan" object and appends to a list
for x in range(sheet.max_row):
name = sheet.cell(x+1, 1)
t = sheet.cell(x+1, 2)
amt = sheet.cell(x+1, 3)
interest = sheet.cell(x+1, 4)
dateBorrowed = sheet.cell(x+1, 5)
print(name.value, " | ", t.value, " | ", amt.value, " | ", interest.value, " | ", dateBorrowed.value)
l = Loan(name, t, amt, interest, dateBorrowed)
loanList.append(l)
print("\n")
loanCal(loanList)
if __name__ == "__main__":
main()
|
fc11217e6b71a26134d39ca4506b71e64bb22e6b | wlazlok/Python_small_university_projects | /Average_mark.py | 2,430 | 3.765625 | 4 | class Pupil:
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.marks = {}
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
if len(name) >= 3:
self.__name = name
else:
print("Zbyt krótkie imie!")
@property
def surname(self):
return self.__surname
@surname.setter
def surname(self, surname):
if len(surname) >= 3:
self.__surname = surname
else:
print("Zbyt krótkie nazwisko")
def complete_marks(self, subject, mark):
if 1 <= mark <= 6:
self.marks[subject] = mark
else:
print("Ocena poza zakresem")
def print_marks(self):
print(self.marks)
def mean(self):
sums = 0
for key in self.marks:
sums += self.marks[key]
length = len(self.marks)
return sums/length
def getMark(self):
return self.marks
def __str__(self):
return "Imie: {} Nazwisko: {} Srednia ocen: {}".format(self.name, self.surname, self.mean())
class Student(Pupil):
def __init__(self, name, surname):
super().__init__(name, surname)
self.weights = {}
def complete_weights(self):
tmp = Pupil.getMark(self)
for key in tmp:
print("Podaj wage dla przedmiotu: " + key)
weight = input()
if 0 < float(weight) <=1:
self.weights[key] = weight
print("DODANO")
else:
print("Zła waga, ustawiono domyślna wage 0,5")
self.weights[key] = 0.5
def mean(self):
total = 0.0
weight = 0.0
tmp = Pupil.getMark(self)
for key, value in tmp.items():
for key_1, value_1 in self.weights.items():
if key == key_1:
total += float(value) * float(value_1)
weight += float(value_1)
return str(round(float(total/weight), 2))
def __str__(self):
return super().__str__()
pu = Pupil("Karol", "Wlazlo")
stu = Student("Karol", "Test")
pu.complete_marks("Polski", 2)
pu.complete_marks("Matematyka", 5)
pu.complete_marks("WF", 2)
stu.complete_marks("Polski", 2)
stu.complete_marks("Matematyka", 5)
stu.complete_marks("WF", 2)
stu.complete_weights()
print(pu)
print(stu)
|
4a2b41034fe078c06fdc064b07909cf6b7ee1aa3 | wlazlok/Python_small_university_projects | /Dice_game.py | 1,173 | 3.90625 | 4 | import random
class Die:
def __init__(self, sides):
self._sides = sides
self._value = None
def roll(self):
self._value = random.randint(1, self._sides)
def get_sides(self):
return self._sides
def get_value(self):
return self._value
die_computer = Die(8);
die_user = Die(6)
sum_comuter = 0
sum_user = 0
next_throw = True
while next_throw == True and sum_user < 21:
die_user.roll()
sum_user += die_user.get_value()
if sum_comuter not in range(18, 21):
die_computer.roll()
sum_comuter += die_computer.get_value()
print("Score: ", sum_user)
if sum_user >= 21 or sum_comuter >= 21:
break
choice = input("Thorw (y/n)")
next_throw = True if choice == 'y' or choice == "Y" else False
while sum_comuter < sum_user < 22:
die_computer.roll()
sum_comuter += die_computer.get_value()
print("Your score: ", sum_user)
print("Computer score: ", sum_comuter)
if sum_user > 21:
print("You lose")
elif sum_comuter > 21:
print("You win")
elif sum_comuter == sum_user:
print("Draw")
elif sum_user > sum_comuter:
print("You win")
else:
print("You lose") |
f1df24378ddad1aa027eac2f45172d7dc121635b | GTC7788/pythonCrawler | /parserWiki.py | 1,703 | 3.625 | 4 | import re
import urlparse
from bs4 import BeautifulSoup
# This is a basic parser program, by using BeautifulSoup, it can find all URLs in the form: wikipedia.org/wiki/***
# Those URLs are added to the URLmanager for further crawl.
#
# Wikipedia html content example:
class HtmlParser(object):
def _get_new_urls(self, page_url, soup):
new_urls = set() # Set avoid duplicate URLs
links = soup.find_all('a', href = re.compile(r"/wiki/(\w)")) # The regular expression here still need improve.
for link in links:
new_url = link['href']
new_full_url = urlparse.urljoin(page_url, new_url)
new_urls.add(new_full_url)
return new_urls
def _get_new_data(self, page_url, soup):
res_data = {}
res_data['rul'] = page_url
# <h1 id="firstHeading" class="firstHeading" lang="en">Recursive neural network</h1>
# title_node = soup.find('h1', class_= "firstHeading"
title_node = soup.find('div', class_= "mw-body").find("h1", class_ = "firstHeading")
res_data['title'] = title_node.get_text()
# <div class="lemma-summary" label-module="lemmaSummary">
"mw-content-ltr"
summary_node = soup.find('div', class_ = "mw-body-content").find('div', class_ = "mw-content-ltr").find("p")
res_data['summary'] = summary_node.get_text()
return res_data
def parse(self, page_url, html_cont):
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'html.parser')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return new_urls, new_data
|
778630f3c8b1b6a9cf1ce955f6e5317a54b4593f | davearonson/exercism-solutions | /teams/gnarly/python/two-fer/two_fer.py | 779 | 4.03125 | 4 | default_name = "you"
def two_fer(name=default_name):
if isinstance(name, str):
name = name.strip()
if name == "": name = default_name
else:
# If it's not even a string, just go with the default
# name. We COULD skip the "else" and just go with
# whatever the param's string equivalent is, but I'm
# being deliberately paranoid, albeit not quite enough
# to raise an error. :-) I'm doing these exercises as
# part of teaching some juniors to code and test, and we
# do security software, so all my entries in this series
# will probably have much more bulletproofing than an
# academic exercise would justify.
name = default_name
return f"One for {name}, one for me."
|
1fc954955401cfa8784c05a8725bd1693ec46f02 | 2470370075/- | /pra.py | 192 | 3.609375 | 4 | #不可变类型 int float str tuple
#可变 list dic
print('aaa'.ljust(6),'bbb'.ljust(6),'ccc'.ljust(6))
print('aaa'.ljust(6),'bbb'.ljust(6),'ccc'.ljust(6))
print(7/2)
print(7//2)
print(7%2)
|
9b41b7f866d07f57016a438d529b15fe91dea892 | hungcu/beautiful-strings | /beautifulStrings.py | 1,869 | 3.890625 | 4 | # Problem:
# String s is called unique if all the characters of s are different.
# String s2 is producible from string s1 if we can remove some characters of s1
# to obtain s2.
# String s1 is more beautiful than string s2 if s1 is longer than s2 or
# they have equal length and s1 is lexicographically greater than s2.
# Given a string s find the most beautiful unique string producible from s.
# Solution:
# Obvioulsy we want exactly one representative of each character in the input.
# Suppose for concreteness that the alphabet is a-z. We must pick the last 'a'
# in the string. If there is a 'b' before the 'a' that we pick, we must pick
# the last such. Otherwise, pick the last 'b' in the string. Having chosen k
# letters, they divide the original string into k+1 subtrings. For the (k+1)st
# letter, choose the last occurrence in the first substring it appears in.
#
# We will take the non-whitespace printable ASCII characters as the alphabet.
# These are ! (hex 21) through ~ (hex 7E).
from collections import defaultdict
def beaut(input):
index = defaultdict(list)
for idx, char in enumerate(input):
index[char].append(idx)
found = [len(input)]
for seek in map(chr, range(0x21, 0x7f)):
if not index[seek]: continue
r = [f for f in found if f > index[seek][0]][0]
# r is right-hand endpoint of first substring containing seek,
# so we want the largest element of index[seek] that is less than r
p = [x for x in index[seek] if x < r][-1]
found.append(p)
found.sort()
return ''.join([input[k] for k in found[:-1]])
def main():
with open("beauts.txt", 'w') as fout:
with open("strings.txt") as fin:
for line in fin:
fout.write(beaut(line))
if __name__ == '__main__':
main() |
da6e5034ab9652b4ab98874be9daef9ba7efa9ff | espag/CS-555-Gedcom-Parser | /Sprint 1/US02.py | 980 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 02 12:52:45 2017
@author: rishi
"""
import sqlite3
import datetime
conn=sqlite3.connect('GEDCOM_DATA.db')
conn.text_factory = str
def Story02():
query1="select NAME,BIRTHDAY,MARRIED from INDIVIDUAL AS I,FAMILY AS F where I.ID=F.HUSBAND_ID OR I.ID=F.WIFE_ID"
result1=conn.execute(query1)
value=result1.fetchall()
first=value[0]
i=0
for row in value:
first_row=value[i]
a=datetime.datetime.strptime(first_row[1],'%d %b %Y')
a.strftime('%d %m %Y')
b=datetime.datetime.strptime(first_row[2],'%d %b %Y')
a.strftime('%d %m %Y')
i+=1
# print (first_row)
if(a > b):
print ("ERROR : US02 :: "+first_row[0].replace("/"," ")+" is born after their own marriage which is not possible ")
#else:
# print ("ERROR : US02 "+first_row[0].replace("/","")+" is born before marriage")
Story02() |
51fc935081356e32b0f1a24d9987c05a42046637 | tonyiovino/helloworld | /paridisp.py | 194 | 4.09375 | 4 | print("Scrivi un numero e ti dirò se è pari o dispari!")
num = input("Numero: ")
num = int(num)
if num%2 == 0:
print("Questo numero è pari!")
else:
print("Questo numero è dispari!") |
a39c1637e05acd2522518aa8e202cb8d124b9e4c | amatsuraki/CheckiO | /Elementary/FizzBuzz.py | 347 | 3.640625 | 4 | def checkio(number: int) -> str:
if number % 15 == 0:
number = "Fizz Buzz"
elif number % 5 == 0:
number = "Buzz"
elif number % 3 == 0:
number = "Fizz"
else:
pass
return str(number)
test = [15, 6, 5, 7]
for i in range(len(test)):
item = test[i]
print(checkio(item))
|
b1118a012245df733a1e78abc55e8e0e519dfff7 | amatsuraki/CheckiO | /Elementary/FirstWord.py | 651 | 4 | 4 | # -*- coding: utf-8 -*-
"""returns the first word in a given text."""
def first_word(text: str) -> str:
print(text)
text = text.replace(",", " ").replace(".", " ")
text = text.strip().split()
return text[0]
test = [
"Hello world", " a word ", "don't touch it", "greetings, friends",
"... and so on ...", "hi", "Hello.World"
]
"""
test1 = "Hello world"
test2 = " a word "
test3 = "don't touch it"
test4 = "greetings, friends"
test5 = "... and so on ..."
test6 = "hi"
test7 = "Hello.World"
"""
for i in range(len(test)):
test_item = test[i]
print(first_word(test_item))
|
109c984ec4e49eafe310f5b60c5b52d2cb14b053 | Xu-Yuefangzhou/Advanced-Programming-note-exercise | /Exercise.py | 1,514 | 3.609375 | 4 |
# coding: utf-8
# In[1]:
2 + 2
# In[2]:
2.0 + 2.5
# In[3]:
2 + 2.5
# In[4]:
a = 0.2
# In[5]:
s = "Hello!"
s
# In[6]:
s = '''Hello! '''
s
# In[9]:
s = '''hello
world'''
print (s)
# In[10]:
s = "hello" + "world"
s
# In[11]:
s[0]
# In[12]:
s[-1]
# In[13]:
s[0:5]
# In[14]:
s.split()
# In[15]:
s='hello world'
s.split()
# 也可以用符号来分割
# In[19]:
s='hello / world'
s.split('/')
# In[20]:
s='hello / world'
s.split(' / ')
# 列表List
# In[21]:
a = [1,2.0,'hello',5+10]
a
# In[22]:
a+a
# In[23]:
s={2,3,4,2}
s
# In[24]:
len(s)
# In[26]:
s.add(1)
s
# In[27]:
a = {1,2,3,4}
b = {2,3,4,5}
a & b
# In[28]:
a ^ b
# In[29]:
d = {'dogs':5, 'cats':4}
d
# In[30]:
len(d)
# In[32]:
d["dogs"]=2
d
# In[34]:
d.keys()
# In[35]:
d.items()
# In[36]:
d.values()
# In[37]:
from numpy import array
a=array([1,2,3,4])
a
# In[38]:
a+2
# In[39]:
get_ipython().magic('matplotlib inline')
from matplotlib.pyplot import plot
plot(a,a**2)
# In[40]:
line = '1 2 3 4 5'
fields = line.split()
fields
# In[41]:
total = 0
for field in fields:
total += int(field)
total
# In[42]:
cd ~
# In[43]:
def poly(x, a, b, c):
y = a * x ** 2 + b * x + c
return y
x = 1
poly(x, 1, 2, 3)
# In[44]:
x = array([1, 2, 3])
poly(x, 1, 2, 3)
# In[45]:
from numpy import arange
def poly(x, a = 1, b = 2, c = 3):
y = a*x**2 + b*x + c
return y
x = arange(10)
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# In[46]:
poly(x)
|
0affe2658592fab3415002287c348ef24ae372bb | Swaraajain/learnPython | /learn.python.loops/calc.py | 384 | 4.1875 | 4 | a= int(input("provide first number : "))
b= int(input("provide second number : "))
sign= input("the operation : ")
def calc(a,b):
if sign == '+':
c= a+b
elif sign== '-':
c= a-b
elif sign=='*':
c= a*b
elif sign=='/':
c= a/b
else:
print("This option is not available")
return c
print("the answer is : ",calc(a,b))
|
17209e6ac514e763706e801ef0fb80a88ffb56b7 | Swaraajain/learnPython | /learn.python.loops/stringQuestions.py | 457 | 4.1875 | 4 | # we have string - result must be the first and the last 2 character of the string
name = "My Name is Sahil Nagpal and I love Programming"
first2index = name[:2]
last2index = name[len(name)-2:len(name)]
print(first2index + last2index)
#print(last2index)
#string.replace(old, new, count)
print(name.replace('e','r',2))
# question - find the longest word and print the word and length of the z
# question - remove the nth index element from the string
|
8d895964bd49c9b70d02da96c01d1fa5e935caa3 | Swaraajain/learnPython | /learn.python.loops/lisOperations.py | 729 | 4.125 | 4 | # list1, list2 = [123, 'xyz'], [456, 'abc', 'ade', 'rwd', 'ghhg']
#
# print(list1[1])
# print(list2[2:4])
# list2[2]=123
# print(list2)
# #del list2[2]
# print(list2)
# print(len(list2))
# print(list1+list2)
# print(456 in list2)
# for x in list2:
# print(x)
# def cmp(a,b):
# return (a > b) - (a < b)
#
# list1 = [1, 2, 4, 3,8,5,6]
# list2 = [1, 2, 5, 8,'5']
# list3 = [1, 2, 5, 8, 10]
# list4 = [1, 2, 4, 3]
#
# # Comparing lists
# print("Comparison of list2 with list1 :")
# print(cmp(list2, list1))
# print(len(list1))
# print(max(list1))
# print(min(list1))
# print(tuple(list1))
# list1[7]=10
# print(list1)
# write a program to swap the last element with first element
# example [1,2,3,4,5] --> [5,2,3,4,1]
|
18e0f9e51fbacbf3e168c52e11e9ae07c5e12d47 | Nikita0102/homework_4_volotov | /3.4.py | 227 | 3.609375 | 4 | A = int(input("Input A:"))
B = int(input("Input B:"))
if A < B:
a = []
for i in range(A, B+1):
a.append(1)
print(a)
if A > B:
b = []
for k in range(B, A+1):
b.append((A + 1) - k)
print(b) |
15827661617839596229859a1a6d99c5c20d89b3 | hershsingh/manim-dirichlet | /play.py | 10,400 | 3.921875 | 4 | #!/bin/python
###
# from manim import *
import manim
class Example(manim.Scene):
def construct(self):
circle = manim.Circle() # create a circle
circle.set_fill(manim.PINK, opacity=0.5) # set the color and transparency
anim = manim.Create(circle)
self.play( anim ) # show the circle on screen
# class Complex:
# def __init__(self, real, imag):
# # print("Inside constructor")
# self.real = real
# self.imag = imag
# def __repr__(self):
# return "{:f} + i{:f}".format(self.real, self.imag)
# def __add__(self, z):
# real = self.real + z.real
# imag = self.imag + z.imag
# return Complex(real, imag)
# class ComplexUnit(Complex):
# def __init__(self, real, imag):
# super().__init__(real, imag)
# self.norm = (self.real**2 + self.imag**2)**(0.5)
# self.real /= self.norm
# self.imag /= self.norm
# self.norm = 1.0
# def __add__(self, z):
# real = self.real + z.real
# imag = self.imag + z.imag
# return ComplexUnit(real, imag)
# x = ComplexUnit(2.0, 3.0)
# y = ComplexUnit(2.0, 3.0)
# ###
# # Complex() =>
# # 1. Allocate memory for object "x" of type "Complex"
# # 2. Call the function: Complex.__init__(x)
# # x = Complex(1.0, 2.0)
# # y = Complex(1.0, 2.0)
# # x + y => x.__add__(y)
# # x + y => add(x,y) => add_int(x, y)
# # x + y => x.add(y)
# # add(x,y)
# # add(int, int) => add_int()
# # add(float, float) => add_float()
# # add(float, int) => add_float_int()
# # add(int, float) ..
# # add(str, str) ..
# # import random
# # import numpy as np
# # import scipy as sp
# # from matplotlib import pyplot as plt
# # # vertices =[
# # # np.array([0,0, 0]),
# # # np.array([0 ,0 ,0]),
# # # np.array([4,1,0]),
# # # np.array([2 ,0 ,0])
# # # ]
# # # vertices =[
# # # np.array([-1]),
# # # np.array([0]),
# # # np.array([-4]),
# # # np.array([2])
# # # ]
# # # circle = Circle() # create a circle
# # # circle.set_fill(PINK, opacity=0.5) # set the color and transparency
# # # self.play(Create(circle)) # show the circle on screen
# # # cubicBezier = CubicBezier(*vertices)
# # # # self.play(Create(cubicBezier))
# # # p1 = np.array([-3, 1, 0])
# # # p1b = p1 + [1, 0, 0]
# # # d1 = Dot(point=p1).set_color(BLUE)
# # # l1 = Line(p1, p1b)
# # # p2 = np.array([3, -1, 0])
# # # p2b = p2 - [1, 0, 0]
# # # d2 = Dot(point=p2).set_color(RED)
# # # l2 = Line(p2, p2b)
# # # bezier = CubicBezier(p1b, p1b + 2*RIGHT + 2*UP, p2b - 3 * RIGHT, p2b)
# # # self.add(l1, d1, l2, d2, bezier)
# # # self.add(bezier)
# # # self.add(bezier)
# # # points = [p1]
# # # points += [points[-1] + 2*RIGHT+2*UP]
# # # points += [points[-1] + 1*RIGHT]
# # axes = Axes(
# # x_range=[-2, 10, 1],
# # y_range=[-2, 10, 1],
# # # x_length=10,
# # axis_config={"color": GREEN},
# # # x_axis_config={
# # # "numbers_to_include": np.arange(-10, 10.01, 2),
# # # "numbers_with_elongated_ticks": np.arange(-10, 10.01, 2),
# # # },
# # tips=False,
# # )
# # # axes_labels = axes.get_axis_labels()
# # # sin_graph = axes.get_graph(lambda x: np.sin(x), color=BLUE)
# # # cos_graph = axes.get_graph(lambda x: np.cos(x), color=RED)
# # # sin_label = axes.get_graph_label(
# # # sin_graph, "\\sin(x)", x_val=-10, direction=UP / 2
# # # )
# # # cos_label = axes.get_graph_label(cos_graph, label="\\cos(x)")
# # # vert_line = axes.get_vertical_line(
# # # axes.i2gp(TAU, cos_graph), color=YELLOW, line_func=Line
# # # )
# # # line_label = axes.get_graph_label(
# # # cos_graph, "x=2\pi", x_val=TAU, direction=UR, color=WHITE
# # # )
# # plot = VGroup(axes)
# # # labels = VGroup(axes_labels, sin_label, cos_label, line_label)
# # grid = NumberPlane((-2, 10), (-2, 10))
# # # self.add(grid)
# # # self.wait()
# # # p1 = ORIGIN
# # # points = [p1, p1 + 2*RIGHT+2*UP]
# # # handles = [[2*UP + RIGHT, -RIGHT - UP]]
# # # points += [points[-1] + 1*RIGHT]
# # # handles += [[-handles[-1][1], -RIGHT - UP]]
# # # points += [points[-1] + 1*RIGHT]
# # # handles += [[-handles[-1][1], -RIGHT - UP]]
# # # # handles += [[2*UP + RIGHT, 0*LEFT]]
# # self.x = 1
# # num_points = 2
# # def get_new_point():
# # sign = random.choice([-1,1])
# # if random.randint(0,1) == 0:
# # return [sign, random.random(), 0.0]
# # else:
# # return [random.random(), sign, 0.0]
# # # k = 0
# # # N = 10
# # origin = [1.,1.,0.]
# # def point_generator(N=10):
# # k = 0
# # r = 3
# # first = []
# # while k <= N:
# # if k==N:
# # yield first
# # x = origin[0] + r*(np.cos(k*2*np.pi/N))
# # y = origin[1] + r/2*np.sin(k*2*np.pi/N)
# # noise = np.array([random.random(), random.random(), 0.0])
# # noise = 0.2*(2*noise - 1)
# # dd = random.random()*0.5 + 0.5
# # dx = -dd*np.sin(k*2*np.pi/N)
# # dy = dd/2*np.cos(k*2*np.pi/N)
# # p = np.array([x,y,0.0])+ noise
# # dp = np.array([dx, dy, 0.0])
# # if k==0:
# # first = [p, dp]
# # k += 1
# # yield np.array([x,y,0.0])+ noise, np.array([dx, dy, 0.0])
# # N = 10
# # pts = point_generator(N=N)
# # def get_new_point():
# # return next(pts)
# # # print("points")
# # # print(next(pts))
# # # print(next(pts))
# # # print(next(pts))
# # # print(next(pts))
# # # print(next(pts))
# # # return
# # def get_dx():
# # xx= np.array([1.0, 0.3*random.random(), 0.0])
# # # return 0.4 * xx/sum(xx**2)
# # return 0.4 * xx/sum(xx**2)
# # # dx1 = RIGHT + UP
# # # last_dx = dx1 + get_dx()
# # # last_dx =
# # # bez = BezierCurve(ORIGIN, dx1, p1 + get_new_point(), last_dx )
# # x, dx = get_new_point()
# # x2, dx2 = get_new_point()
# # bez = BezierCurve(x, dx, x2, dx2)
# # # print(dx1, last_dx)
# # # bez.add_point_delta(RIGHT+UP, 0.5*(RIGHT+UP))
# # for i in range(N-1):
# # # last_dx += get_dx()
# # x,dx = get_new_point()
# # # print(i, pt)
# # bez.add_point(x, dx)
# # # last_dx += get_dx()
# # # bez.add_point_delta(get_new_point(), get_dx())
# # self.bez = bez
# # # grp = VGroup([bez.get_bezier(i) for i in range(N)])
# # # self.play(Create(grp))
# # # self.play(Create(*[bez.get_bezier(i) for i in range(N)]))
# # self.bl = [bez.get_bezier(i) for i in range(N)]
# # # self.play(Create(self.bl[0]), Create(self.bl[1]))
# # b = self.bl[0]
# # b.add(*self.bl[1:])
# # grp = VGroup(*self.bl)
# # # self.play(FadeIn(grid))
# # self.play(Create(plot), run_time=2)
# # # self.play(Create(grid))
# # self.play(Create(grp), run_time=3, rate_func=rate_functions.linear)
# # grid_config = {
# # # "axis_config": {
# # # "stroke_color": WHITE,
# # # "stroke_width": 2,
# # # "include_ticks": False,
# # # "include_tip": False,
# # # "line_to_number_buff": SMALL_BUFF,
# # # "label_direction": DR,
# # # "number_scale_val": 0.5,
# # # },
# # # "y_axis_config": {
# # # "label_direction": DR,
# # # },
# # "background_line_style": {
# # "stroke_color": BLUE_D,
# # "stroke_width": 2,
# # "stroke_opacity": 1,
# # },
# # # Defaults to a faded version of line_config
# # # "faded_line_style": None,
# # # "x_line_frequency": 1,
# # # "y_line_frequency": 1,
# # # "faded_line_ratio": 1,
# # # "make_smooth_after_applying_functions": True,}
# # }
# # grid = NumberPlane((-2, 10), (-2, 10), **grid_config)
# # self.play(FadeIn(grid))
# # # self.add(grid)
# # # Line
# # self.wait(1)
# # # for i in range(bez.get_length()-1):
# # # # for i in range(1):
# # # # self.add(bez.get_bezier(i))
# # # # self.add(*bez.get_handles(i))
# # # self.play(Create((bez.get_bezier(i))))
# # # # self.add(*bez.get_handles(i))
# # # # self.play(bez) # show the circle on screen
# # # s = Example()
# # # s.construct()
# # # print("adsd")
# # ##
# # p = np.array([3.0,2.1])
# # def check_int(p):
# # """Return 0,1,2,3 depending on whether either of (x,y) is an integer"""
# # return sum(np.isclose(p%1, 0)*[2,1])
# # def check_entry_exit(p, theta):
# # """Whether a line is entering or exiting depends on the slope"""
# # c = check_int(p)
# # if c==1: # (x,y) y is integer. Intersects horizontal grid
# # if theta>0 and theta<np.pi:
# # return 0 # entry
# # else:
# # return 1 # exit
# # elif c==2: # Intersects vertical grid
# # if theta>PI/2 and theta < (3/2)*PI:
# # return 0 # entry
# # else:
# # return 1 # exit
# # else:
# # return -1 # At a strange place
# # def get_next_bdy(p):
# # # check whether we intersect vertical or horizontal grid
# # c = check_int(p)
# # # choices = [[]]
# # print(check_int(p))
# # ###
# # n = 10
# # [1]*n + [-1]*n
|
acd213987246915ac800f0ec5203d21ad6d32e73 | Anisha2510/tkinter-miles_to_km | /main.py | 705 | 4.03125 | 4 | from tkinter import *
def miles_to_km():
miles = float(miles_input.get())
km = miles * 1.689
km_result.config(text=f"{km}")
window = Tk()
window.title("Miles to km Converter")
window.minsize(width=300, height=100)
window.config(padx=20, pady=20)
miles_input = Entry(width=7)
miles_input.grid(column=1, row=0)
miles_label = Label(text="Miles")
miles_label.grid(column=2, row=0)
is_equal_to = Label(text="Is equal to: ")
is_equal_to.grid(column=0, row=1)
km_result = Label(text="0")
km_result.grid(column=1, row=1)
km_label = Label(text="km")
km_label.grid(column=2, row=1)
cal_button = Button(text="Calculate", command=miles_to_km)
cal_button.grid(column=1, row=2)
window.mainloop()
|
d049ca74673235d9d3ba02356692b1aae1d30573 | egbertcw0711/MachineLearning | /Coding/solutions.py | 5,825 | 3.96875 | 4 | def question1(s, t):
""" determine whether some anagram of t is a substr of s
input: string s, string t
output: True or False """
# dictionary counts for t
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
dt = {c:0 for c in alphabet}
for c in t: # O(len(t))
dt[c] += 1
# print(dt)
# construct all possible consecutive substring sets in s
length_s = len(s)
substrs = [s[i:j+1] for i in range(length_s) for j in range(i,length_s)]
# check any of the substring in s is anagram of t
for sstr in substrs: # O(len(substrs))
for c in (range(65, 91) + range(97, 123)): # O(1)
if dt[chr(c)] != sstr.count(chr(c)): # O(len(s))
break
if c == 122:
return True
return False # no such substring
# below is the test case for question1
print('test question1 ...')
s = "udacity"
t = "ad"
print(question1(s,t)) # True
s = "Apple"
t = "elp"
print(question1(s,t)) # True
s = "Apple"
t = "ple"
print(question1(s,t)) # True
s = "MachineLearning"
t = "ML"
print(question1(s,t)) # False
def question2(a):
""" find the longest palindromic substring contained in a
input: string
output: longest palindromic substring
NOTE: here if there exists more than one longest palindromic
substring, the first one will be returned"""
# speical cases
if(len(a) == 0): return ""
if(len(set(a)) == len(a)): return a[0]
# general cases
P = ""
for i in range(len(a)):
P += ("0"+a[i])
P += "0"
# print(P)
# print('--------')
center = 1 # center of the longest palindrome
radius = 1 # the radius of the longest palindrome
for i in range(2, len(P)-2):
idx = 1
# check the index is not out of the range and the chars are symmetric
while (i-idx >= 0 and i+idx <= len(P)-1):
if(P[i-idx] != P[i+idx]):
break
else:
idx += 1
idx -= 1
if(idx > radius):
center = i
radius = idx
return P[center-radius+1:center+radius+1:2]
# below the test case for question2
print('\ntest question2 ...')
print(question2("substringnirtsbus")) # substringnirtsbus
print(question2("apple")) # pp
# special cases
print(question2("")) # []
print(question2("a")) # ["a"]
print(question2("pine")) # ["p"]
def question3(G):
""" find MST within graph G
Using the Kruskal's algorithm
input: adjacency list (graph)
output: adjacency list (MST) """
dics = {} # {val:[from, to]}
# the two for loop visit all edges in the graph: O(E)
for node_from in G:
for node_to, value in G[node_from]:
dics[value] = [node_from, node_to]
# O(ElogE)
sorted(dics.keys())
result = {}
# O(E)
for dist in dics:
# if not form a circle
result[dics[dist][0]] = [(dics[dist][1], dist)]
return result
# test cases (the order does not matter)
print('\ntest question3 ...')
G = {}
print(question3(G)) # {}
G = {'A': [(None, None)]}
print(question3(G)) # {'A': [(None, None)]}
G = {'A':[('B',2)],
'B': [('A',2)]}
print(question3(G)) # {'A': [('B', 2)]}
G = {'A':[('B',2)],\
'B':[('A',2), ('C',5)],\
'C':[('B',5)]}
print(question3(G)) # {'A':[('B',2)], 'B':[('C',5)]}
# test cycle in the graph
G = {'A':[('B',2)], 'B':[('A',2),('C',5)],\
'C':[('B',5),('A',10)]}
print(question3(G)) # A-B-C
def question4(T, r, n1, n2):
""" Find the least common ancester between two nodes on a bst.
Inputs: T: matrix representation of a bst
r: non-negative integer representing the root
n1,n2: the value of the two nodes in no particular order
"""
if((n1 <= r and n2 >= r) or (n1 >= r and n2 <= r)):
return r
# print(r)
children = [i for i, v in enumerate(T[r]) if v == 1]
if(len(children) == 2):
if(n1 < r and n2 < r):
child = children[0]
else:
child = children[1]
elif(len(children) == 0):
child = None
else:
child = children
lca = question4(T,child,n1,n2)
return lca
# test cases
print('\ntest question4 ...')
print(question4([[0,1,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[1,0,0,0,1],
[0,0,0,0,0]],
3,1,4)) # 3
print("the correct answer should be 3\n ")
print(question4([[0,0,0,0,0],
[1,0,1,0,0],
[0,0,0,0,0],
[0,1,0,0,1],
[0,0,0,0,0]],
3,0,2)) # 1
print("the correct answer should be 1\n ")
print(question4([[0,0,0,0,0],
[1,0,1,0,0],
[0,0,0,0,0],
[0,1,0,0,1],
[0,0,0,0,0]],
3,4,2)) # 3
print("the correct answer should be 3\n ")
print(question4([[0,0,0,0,0],
[1,0,1,0,0],
[0,0,0,0,0],
[0,1,0,0,1],
[0,0,0,0,0]],
3,4,1)) # 3
print("the correct answer should be 3\n ")
print(question4([[0,0,0,0,0],
[1,0,1,0,0],
[0,0,0,0,0],
[0,1,0,0,1],
[0,0,0,0,0]],
3,1,2)) # 1
print("the correct answer should be 1\n ")
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def question5(ll,m):
""" Find the element in a singly linked list
that m element from the end
Inputs: ll:the first node of a linked list
m: mth number from the end.
Output: the value of the node at that position
Note: assuming all the inputs are valid and m is chosen
correctly(i.e not out of the boundary of linked list)."""
# find the length of the linked list
length = 1
tmp = ll
while tmp.next != None:
tmp = tmp.next
length += 1
# find the value of the node at the position
tmp = ll
for i in range(length-m):
tmp = tmp.next
return tmp.data
# test cases
print('\ntest question5 ...')
# one node
n1 = Node(1)
print("my output: " + str(question5(n1,1))) # 1
print("correct output: 1")
n2 = Node(2)
n1.next = n2
print("my output: " + str(question5(n1,1))) # 2
print("correct output: 2")
print("my output: " + str(question5(n1,2))) # 1
print("correct output: 1")
|
309dc04376ecf8ebd54c85dcc75ed4ea003a88b1 | LizaM19/name | /app.py | 2,714 | 4 | 4 | # Импорт необходимых библиотек
from tkinter import *
import random
#Функция сортировки вставками
def sorting(list):
for i in range(1, len(list)):
current = list[i]
f = i-1
while f>=0:
if current < list[f]:
list[f+1] = list[f]
list[f] = current
f = f-1
else:
break
a[]
#Генерация рандомного списка
a = []
for i in range (11):
x = random.randrange(10, 100)
a.append(x)
#Размещение списка в файле input.txt
address = open('input.txt', 'w')
for item in a:
address.write("%s\n" % item)
address.close()
#Открытие списка из файла на чтение
with open('input.txt') as f:
content = f.readlines()
b = [x.strip() for x in content]
address.close()
#Функция вывода списка после сортировки
def printafter():
sorting(b)
afterlabel = Label(root, text="список после сортировки вставками", fg="black")
afterlabel.grid(row=0, column=3, padx=10)
after = Label (root, text=b, fg="black", bg='#DCDCDC')
after.grid(row=1, column=3, padx=10, pady=10)
#Размещение сортированного списка в файле output.txt
addressout = open('output.txt', 'w')
for item in b:
addressout.write("%s\n" % item)
addressout.close()
#Создание главного окна приложения
root = Tk()
root.title("insertion sort")
#Вывод рандомного списка и заголовка к нему
beforelabel = Label (root, text="рандомно сгенерированный список", fg="black")
beforelabel.grid(row=0, column=1, padx=10)
before = Label (root, text=a, fg="black", bg='#DCDCDC')
before.grid(row=1, column=1, padx=10, pady=10)
#Кнопка, при нажатии которой выполняется сортировка, и выводится отсортированный список
arrow = Button(root, text="->", command=printafter, bg = '#C0C0C0', font="Helvetica 10", relief = 'groove', activebackground='#A9A9A9')
arrow.grid(row=1, column=2, padx=10, pady=10)
#Ячейки, которые заполняются при нажатии на кнопку
afterlabel1 = Label(root, text="список после сортировки вставками", fg="black")
afterlabel1.grid(row=0, column=3, padx=10)
after1 = Label(root, text=b, fg="#DCDCDC", bg='#DCDCDC')
after1.grid(row=1, column=3, padx=10, pady=10)
root.mainloop() |
e0121a988808867f6c317b7123b908833a029d44 | RaduEmanuel92/ctfs | /aeroctf/crypto/magic1/task.py | 7,530 | 4.03125 | 4 | #!/usr/bin/env python3.7
import numpy as np
import math
from itertools import chain
import numpy as np
import string
# Python program to generate
# odd sized magic squares
# A function to generate odd
# sized magic squares
def generateSquare(n):
# 2-D array with all
# slots set to 0
magicSquare = [[0 for x in range(n)]
for y in range(n)]
# initialize position of 1
i = n / 2
j = n - 1
# Fill the magic square
# by placing values
num = 1
while num <= (n * n):
if i == -1 and j == n: # 3rd condition
j = n - 2
i = 0
else:
# next number goes out of
# right side of square
if j == n:
j = 0
# next number goes
# out of upper side
if i < 0:
i = n - 1
if magicSquare[int(i)][int(j)]: # 2nd condition
j = j - 2
i = i + 1
continue
else:
magicSquare[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1 # 1st condition
# Printing magic square
print ("=============")
print ("Sum of each row or column", n * (n * n + 1) / 2, "\n")
'''
print ("Magic Squre for n =", n)
for i in range(n):
for j in range(n):
print('%2d ' % (magicSquare[i][j]), end = '')
# To display output
# in matrix form
if j == n - 1:
print()
'''
return magicSquare
class Cipher(object):
def __init__(self, key: int, canary: int):
self._key = key
self._canary = canary
return
@property
def key(self) -> int:
return self._key
@property
def canary(self) -> int:
return self._canary
def encrypt(self, message: bytes) -> bytes:
plaintext = int.from_bytes(message, 'big')
# print("KEY length")
# print(self._key.bit_length())
# print("PT length")
# print(plaintext.bit_length())
#print("key: {}".format(self._key))
assert self._key.bit_length() >= plaintext.bit_length()
ciphertext = self._key ^ plaintext
length = (ciphertext.bit_length() + 7) // 8
return ciphertext.to_bytes(length, 'big')
def decrypt(self, message: bytes) -> bytes:
ct = int.from_bytes(message, byteorder='big')
leng = (ct * 8 - 7)
leng = leng.bit_length()
#leng = ct.bit_length()
#print(leng)
#assert self._key.bit_length() >= ct.bit_length()
# print("[decr] KEY:")
# print(self._key)
flag = self._key ^ ct
#print(flag)
return flag.to_bytes(leng, 'big')
#raise NotImplementedError
@classmethod
def create(cls, source: np.ndarray) -> 'Cipher':
assert len(set(source.shape)) == 1
line = source.reshape(-1)
assert len(line) == len( set(line) & set(range(len(line))) )
keys = set(map(sum, chain.from_iterable((*s, np.diag(s)) for s in [source, source.T])))
print(len(line))
assert len(keys) == 1
key = int(keys.pop())
print("_key:")
print(key)
print("_can:")
print(key % len(line))
return cls(key, key % len(line))
def compute_key(n):
# return int((n * (n*n + 1)/2) - n)
return int((n * (n*n + 1)//2) - n)
def gen_cand(c, r):
var = math.sqrt(c*c - r + 1)
if isinstance(var, int):
return c + var
else:
return -1
def ver_key(ct, idx, crib):
cand_key = compute_key(idx)
#if cand_key % idx*idx == canary:
#print("[*] try key {} -> {} bits".format(cand_key, cand_key.bit_length()))
print("[***] try key {} -> {} -> {} bits".format(idx, cand_key, cand_key.bit_length()))
cand_pt = ct ^ cand_key
#length = (cand_pt.bit_length() + 7) // 8
leng = (ct * 8 - 7)
leng = leng.bit_length()
cand_pt = cand_pt.to_bytes(leng, 'big')
if crib in cand_pt :
print("[+] found candidate key {} {}".format(cand_key,cand_pt ))
return cand_pt
# cipher = Cipher.create(cand_secr)
# plaintext = cipher.decrypt(secr_enc)
# print(plaintext)
def find_square(r) :
k = 1
while True:
c = k*k + r - 1
if isinstance(math.sqrt(c), int):
print(c)
break
else:
c += 1
return 1
def main():
#from secret import SECRET, FLAG
#cipher = Cipher.create(SECRET)
#print(cipher.encrypt(FLAG).hex())
#print(cipher.canary)
# test
can = 1501
candidate = generateSquare(can)
#print(candidate)
for idx in range(can):
for idy in range(can):
candidate[idx][idy] -= 1
cand_secr = np.array(candidate)
cipher = Cipher.create(cand_secr)
print("Canary:")
print(cipher.canary)
print("Key:")
print(cipher.key)
flag = b"A{d}"
print("test encrypt")
encr = cipher.encrypt(flag)
print(encr)
print("test decrypts")
print(cipher.decrypt(encr))
SECRET_ENCR = "d9a103a6006bfba17074ef571011d8eededdf851b355bdc4795616744066433695b9e9201f6deff7577c03ba690d4d517bdaae"
canary = 5405053190768240950975482839552589374748349681382030872360550121041249100085609471
secr_enc = bytes.fromhex(SECRET_ENCR)
ct = int.from_bytes(secr_enc, byteorder='big')
crib = b'Aero{'
crib2 = b'oreA'
flag = ''
key = ''
# lil smaller than the cananry bit len
#can_value = 2211108169930076950954187620
m = 103971661434914474977947909929808181577819
#idx = 1
# lil smaller than the enc bit len
#idx = 2 ** 136 + 1
# idx = can_value
# while True:
# cand_key = compute_key(idx)
# if cand_key % idx*idx == canary:
# #print("[*] try key {} -> {} bits".format(cand_key, cand_key.bit_length()))
# print("[***] try key {} -> {} -> {} bits".format(idx, cand_key, cand_key.bit_length()))
# cand_pt = ct ^ cand_key
# #length = (cand_pt.bit_length() + 7) // 8
# leng = (ct * 8 - 7)
# leng = leng.bit_length()
# cand_pt = cand_pt.to_bytes(leng, 'big')
# if crib in cand_pt :
# print("[+] found candidate key {} {}".format(cand_key,cand_pt ))
# cipher = Cipher.create(cand_secr)
# plaintext = cipher.decrypt(secr_enc)
# print(plaintext)
# break
# else:
# idx -= 2
#find_square(canary)
print("bla")
c = int(canary/2)
while True:
if (c*c - canary + 1 < 0):
print("bayud")
pass
key = gen_cand(c, canary )
if key == -1:
pass
elif key % 2 == 0:
print("wrong {}".format(key))
pass
else:
print(key)
ver_key(ct, key, crib)
c += 1
# correction
# for idx in range(cand):
# for idy in range(cand):
# candidate[idx][idy] -= 1
# cand_secr = np.array(candidate)
# print("---")
# print(cand)
# cipher = Cipher.create(cand_secr)
# print(cipher.canary)
# plaintext = cipher.decrypt(secr_enc)
# if crib in plaintext or crib2 in plaintext:
# print(plaintext)
if __name__ == '__main__':
main()
|
550fc4a7bfcad18a559b99b2d0838455b45478be | RaduEmanuel92/ctfs | /onlinectf/basecption/catch.py | 1,883 | 3.515625 | 4 | #!/usr/bin/env python
import sys
ct = "KRSWE4TJNNWGK4RBEBAW2YJAMJ2SA23BMRQXEIDLN5WGC6JAN5WG2YLZMFRWC2ZAHIUSACQKKZDVM2LDNVWHEYSHKZ4USRDPOBEUKSRRMJXFKZ3BI5DHESKHKYYGIR3MOVEUGMBLKBVDIZ2SNN4EEURTORFFQMKJPJJDCSL2KZDDSR2VNJBE4WBQJJBFKMCVGJHEQMB"
bigrams = ["TH", "HE", 'IN', 'OR', 'HA', 'ET', 'AN', 'EA', 'IS', 'OU', 'HI', 'ER', 'ST', 'RE', 'ND']
# this is the list of monograms, from most frequent to less frequent
monograms = ['E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H', 'D', 'L', 'U', 'C', 'M', 'F', 'Y', 'W', 'G', 'P', 'B', 'V', 'K', 'X', 'Q', 'J', 'Z']
print ct
ct2 = ct
bigrams = {}
global subst_table
def create_bigrams():
for index in range(0,len(ct2)):
bigram = ct2[index]
#print bigram
if bigram in bigrams:
bigrams[bigram] +=1
else:
bigrams.update({bigram : 1})
print "Dictionary with values created"
for key, value in sorted(bigrams.iteritems(), key=lambda (k,v): (v,k)):
print "%s: %s" % (key, value)
print "-------------------------"
def adjust():
index = 0
subst_table = {}
subst_table['A'] = 'K'
subst_table['B'] = 'N'
subst_table['C'] = 'S'
subst_table['D'] = 'W'
subst_table['F'] = 'C'
subst_table['G'] = 'V'
subst_table['J'] = 'G'
subst_table['I'] = 'Y'
subst_table['K'] = 'T'
subst_table['M'] = 'D'
subst_table['N'] = 'I'
subst_table['P'] = 'W'
subst_table['Q'] = 'E'
subst_table['R'] = 'H'
subst_table['S'] = 'U'
subst_table['T'] = 'A'
subst_table['U'] = 'G'
subst_table['W'] = 'R'
subst_table['X'] = 'F'
subst_table['Y'] = 'B'
subst_table['E'] = 'L'
print subst_table
ct3 = ['0' for x in range(len(ct2)+1)]
index2=0
for index in range(0,len(ct2)):
bigram = ct2[index]
if bigram in subst_table:
ct3[index2] = subst_table[bigram]
index2 +=1
print ct3
print "Decrypt attempt:"
for char in ct3:
sys.stdout.write(char+ ' ')
print "\n"
if __name__ == '__main__':
create_bigrams()
adjust() |
30b00fa63b7e9b96a1023dbd23525da69509d791 | colingalvin/RPSLSPython | /main.py | 1,490 | 3.71875 | 4 | from human import Human
from ai import AI
def compare_gestures(gesture1, gesture2):
if gesture1.name == gesture2.name:
return "tie"
elif gesture1.name == "Rock":
if gesture2.can_beat_rock:
return "lose"
elif gesture1.name == "Paper":
if gesture2.can_beat_paper:
return "lose"
elif gesture1.name == "Scissors":
if gesture2.can_beat_scissors:
return "lose"
elif gesture1.name == "Lizard":
if gesture2.can_beat_lizard:
return "lose"
elif gesture1.name == "Spock":
if gesture2.can_beat_spock:
return "lose"
return "win"
def display_result(gesture_result):
if gesture_result == "tie":
print("Tie round!")
elif gesture_result == "lose":
print(f"{ai.name} wins this round!")
ai.score += 1
else:
print(f"{colin.name} wins this round!")
colin.score += 1
if __name__ == '__main__':
colin = Human("Colin")
ai = AI()
while colin.score < 2 and ai.score < 2:
print(f"{colin.name}: {colin.score} // {ai.name}: {ai.score}")
colin_gesture = colin.choose_gesture()
ai_gesture = ai.choose_gesture()
print(f"{colin.name} chose {colin_gesture.name}, {ai.name} chose {ai_gesture.name}")
result = compare_gestures(colin_gesture, ai_gesture)
display_result(result)
else:
print(f"Final results: {colin.name}: {colin.score}, {ai.name}: {ai.score}")
|
33b368e1050fc87f3f791ab2ac75530fe0c9cd71 | aaaaaaaaaron/encrypton | /encrypt.py | 1,361 | 4.0625 | 4 | """
Credit: https://www.thepythoncode.com/article/encrypt-decrypt-files-symmetric-python
"""
from cryptography.fernet import Fernet
from encrypt_gen import *
import time
def encrypt(filename, key):
"""
Given a filename (str) and key (bytes), it encrypts the file and write it
"""
f = Fernet(key)
with open(filename, "rb") as file:
# read all file data
file_data = file.read()
# encrypt data
encrypted_data = f.encrypt(file_data)
# write the encrypted file
with open(filename, "wb") as file: # write to SAME FILE to override. nice.
file.write(encrypted_data)
if __name__=="__main__":
# generate and write a new key
write_key()
# load the previously generated key
key = load_key()
# initialize the Fernet class
f = Fernet(key)
# file = "toEncrypt.txt"
file = "C:/Users/Aaron/Documents/Encryption\EncryptTheseFiles/toEncrypt.txt"
encrypt(file, key)
# # encodes a string to make it suitible for encryption (utf-8 codec)
# message = "some secret message".encode()
# # encrypt the message
# encrypted = f.encrypt(message)
#
# # print how it looks
# print(encrypted) # prints some crazy string o:
#
# # decrypts and encrypts using same class
# decrypted_encrypted = f.decrypt(encrypted)
# print(decrypted_encrypted) |
45f9b5ee0016aa045ab26d0e1672342da2386939 | mallimuondu/vote | /vote.py | 411 | 4.09375 | 4 | def work():
while True:
try:
age = int(input("pls input your age: "))
except ValueError:
print("sorry i did'nt understund that")
continue
else:
if age < 18:
print("you can not vote")
elif age>18:
print("you can vote")
elif age == 18:
print("you cant vote")
work() |
ec0ffabb1915e05653e3c710fdcbe2a25d5b6af8 | satyanrb/Mini_Interview_programs | /Base.py | 242 | 3.71875 | 4 | from functools import reduce
nums = [3, 2, 4, 6, 8, 9]
evens = list(filter(lambda n:n%2==0, nums))
doubles = list(map(lambda n:n*2, evens))
sum = reduce(lambda a,b: a+b, doubles)
print(evens)
print(doubles)
print(sum)
|
6abd6b9ab84d8d7d1403f6823c68bf5dc188e679 | satyanrb/Mini_Interview_programs | /Stopwatch.py | 518 | 3.765625 | 4 | import time
while True:
try:
print(" Press Enter to Start the Timer and CTRL-C to end the timer")
start_time = time.time()
print(" The timer is started")
while True:
print("time elapsed = ", round(time.time() - start_time, 0), 'secs', end='\n')
time.sleep(1)
except KeyboardInterrupt:
print("Time is Stopped")
end_time = time.time()
print(" Elapsed time is", round(start_time - end_time, 2), 'secs')
break
|
85118d5cea1ed16ca198b40e82b62ab9e508d54e | mcalidguid/quiz-FRIENDS | /quiz-FRIENDS-show.py | 2,767 | 3.65625 | 4 | import json
import random
def quiz(no_of_question):
score = 0
with open("questions.json", 'r') as f:
question_list = json.load(f)
for i in range(no_of_question):
total_questions = len(question_list)
# print(total_questions)
question = random.randint(0, total_questions - 1)
print(f'\nQ{i + 1}. {question_list[question]["question"]}')
for option in question_list[question]["options"]:
print(option)
answer = input(">>> Enter your answer: ")
if question_list[question]["answer"][0] == answer[0].upper():
print("\(*゚∀゚*)/ You were right!")
score += 1
else:
# print("Close but not quite... ヾ( ̄◇ ̄)ノ")
print("ヾ( ̄◇ ̄)ノ Hmmm... close but not quite... ")
del question_list[question]
final_score = (score/no_of_question)*100
print("..")
print("...")
print("You scored %.f" % final_score, "%")
if final_score < 80:
print("You failed. Could this quiz BE any harder?")
print("The required score is 80%.")
print("It's time for you to have a FRIENDS marathon again,.. then try this quiz again!")
elif final_score == 100:
print("Wow!")
print("Only the truest of fans can get a perfect score!")
else:
print("You passed! Congratulations~")
print("Just binge watch the show anyway because who doesn't want to relive those moments?!")
def message(error):
print("Error Type:", type(error), "is occurring. Please try again.\n")
print("""-------------------------------------------------------------------
~#--------------#~ Are You A True FRIENDS Fan? ~#--------------#~
It’s been 25 years since the show aired and we’re still watching it.
Either way, do you know enough about Friends? Let’s find out!
Choose level of difficulty:
Enter \'1\' for Easy \"I think so. I have watched FRIENDS!\"
Enter \'2\' for Medium \"You bet! I know enough about FRIENDS.\"
Enter \'3\' for Hard \"Ahaa! I'm a true FRIENDS superfan!\"
Enter \'4\' for Quit \"Dang! I'm scared!\"
-------------------------------------------------------------------""")
try:
user_input = int(input(">>>: "))
if user_input == 1:
number_of_question = 5
quiz(number_of_question)
elif user_input == 2:
number_of_question = 10
quiz(number_of_question)
elif user_input == 3:
number_of_question = 20
quiz(number_of_question)
elif user_input == 4:
exit()
else:
print("Invalid input.")
except ValueError as e:
message(e)
|
b1c010b5007a8331300fa9bd43d0b16556b07b62 | Mamata720/List | /list out of integer.py | 126 | 3.5625 | 4 | a=[1,2,3,"12a","13s",12,"sd"]
i=0
b=[]
while i<len(a):
if type(a[i])==type(i):
b.append(a[i])
i=i+1
print(b)
|
8e54970cecaccf8a20a7723968d5d17b4e596811 | JYOTIPALARIYA/Module5_WebSraping | /scrap2.py | 1,833 | 3.765625 | 4 | import requests #To Obtain the information we use requests
from bs4 import BeautifulSoup #to parse that information we ue beautiful soup and with the help of beautifulsoup we
#can target different links to extract Information
url="https://finance.yahoo.com/quote/GOOGL?p=GOOGL&.tsrc=fin-srch&guccounter=1"
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36'}
html_page=requests.get(url)#now again and again if we try to fetch data from the site then it will understand that
#its a bot so will use header element and in that my user agent.
# print(html_page)
# now will create soup obj and pass html page content and parser ..here we r passing lxml which is fastest.
soup=BeautifulSoup(html_page.content,'lxml')#we can know abt parsers through beautiful soup documentation.
print(soup.title)#not a good one so can use find method
headerin=soup.find_all("div",id="quote-header-info")[0]
soup_title=headerin.find("h1",class_="D(ib) Fz(18px)").get_text()
print(soup_title)
soup_value=headerin.find("div",class_="D(ib) Mend(20px)").find("span").get_text()
print(soup_value)
soup_tablev=soup.find_all("div",class_="D(ib) W(1/2) Bxz(bb) Pend(12px) Va(t) ie-7_D(i) smartphone_D(b) smartphone_W(100%) smartphone_Pend(0px) smartphone_BdY smartphone_Bdc($seperatorColor)")[0].find_all("tr")
# previousCloseHeading=soup_tablev[0].find_all("span")[0].getText()
# previousCloseValue=soup_tablev[1].find_all("span")[1].getText()
# print(previousCloseHeading +" "+previousCloseValue)
#-------------------now using for Loop
for i in range(0,8):
Heading=soup_tablev[i].find_all("td")[0].getText()
Value=soup_tablev[i].find_all("td")[1].getText()
print(Heading +" "+Value)
|
94fadec437cfa9039d216d55814c62f251629a63 | miltonsarria/teaching | /basics/ex3.py | 324 | 3.875 | 4 | #Programa para ilustrar como manipular texto
#asignar variables con valores especificos
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
#imprimir variables de forma individual
print(word1, word2)
#crear una nueva variable sumando los valores anteriores
sentence = word1 + " " + word2 + " " + word3
print(sentence)
|
49592f7c88c7fbeeca3e84f1817401b32dfa9383 | aidaFdez/Cipher | /Cipher.py | 4,419 | 3.875 | 4 | from tkinter import *
abc = ['a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K',
'l','L','m','M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w', 'W',
'x','X','y', 'Y','z', 'Z']
ciph = "Here will be the output"
###########################
# Functions for ciphering #
###########################
#Uses the Caesar cipher. It shifts the letters the times given.
def caesar ():
result = Toplevel()
result.title("Caesar")
input = toCip.get()
num = int(caesarN.get())
ciphered = ""
for letter in input:
if letter in abc:
ind = abc.index(letter)
ciphered = ciphered + abc[(ind+(num*2) )%52]
else:
ciphered = ciphered + letter
output = Label(result, text = ciphered)
output.grid()
#The same function as Caesar but taking arguments, so it can be called from Vigenere
def caeHelp(input, num):
ciphered = ""
for letter in input:
if letter in abc:
ind = abc.index(letter)
ciphered = ciphered + abc[(ind+(num*2) )%52]
else:
ciphered = ciphered + letter
return ciphered
#Uses the Vigenere cipher. It uses a square table, which in essence is just applying Caesar a different number of times
#depending on the letter of the keyword being used at the moment.
def vigenere ():
result = Toplevel()
result.title("Vigenere")
input = toCip.get()
keyword = vigKey.get()
ciphered = ""
i = 0
while i <len(input):
for letter in input:
if letter in abc:
ciphered = ciphered + caeHelp(letter, round((abc.index(keyword[i%len(keyword)])/2)))
else:
ciphered = ciphered + letter
i = i+1
output = Label(result, text = ciphered)
output.grid()
#Uses the frquencies of letters in English. Depending on it, it gives it a number. This uses Lewand's ordering.
def frequency():
result = Toplevel()
result.title("By frequency")
input = toCip.get()
#Order of the alphabet from most frequent to least frequent
abcFreq = ['e','t','a','o','i','n','s','h','r','d','l','c','u','m','w','f','g','y','p','b','v','k','j','x','q','z'
'E','T','A','O','I','N','S','H','R','D','L','C','U','M','W','F','G','Y','P','B','V','K','J','X','Q','Z']
ciphered = ""
for letter in input:
if letter in abcFreq:
ciphered = ciphered + str((abcFreq.index(letter) %26)+1 + " ")
else:
ciphered = ciphered + letter
output = Label(result, text = ciphered)
output.grid()
#Uses the polialphabetical ordering. There are three alphabets (there could be more) and alternates them
def polialphabetical():
result = Toplevel()
result.title("Polialphabetical")
input = toCip.get()
ciphered = ""
output = Label(result, text = ciphered)
output.grid()
############################
# Settings for the display #
############################
window = Tk()
window.title("Cipher")
window.geometry("500x300")
#Introductory message.
mPrinc = Message(window, text = "Hi! Fill in the necessary data and then choose the kind of ciphering you want! \n")
mPrinc.config(width = 200)
mPrinc.grid()
#Text to be ciphered
msg = Message(window, text = "Text to cipher ")
msg.config(width = 100)
msg.grid(sticky = "w")
toCip = Entry(window)
toCip.grid(sticky = "w", row = 1, column = 1)
#Necessary inputs for Caesar
msgC = Message(window, text = "Number (only Caesar) ")
msgC.grid(sticky = "w", row = 2, column = 0)
caesarN = Entry(window)
caesarN.grid(row = 2, column = 1)
#Necessary inputs for Vigenere
msgV = Message(window, text = "Key (only Vigenere) ")
msgV.grid(row = 3, sticky = "w")
vigKey = Entry(window)
vigKey.grid(row = 3, column = 1)
#Necessary inputs for polialphabetical
msgP = Message(window, text = "Order of alphabets (Polialphabetical only)")
msgP.grid(row = 4, sticky = "w")
order = Entry(window)
order.grid(row = 4, column = 1)
#Buttons for getting the ciphered text.
Button(window, text = "Caesar", command = caesar).grid(row = 7)
Button(window, text = "Vigenere", command = vigenere).grid(row = 7, column = 1)
Button(window, text = "Frequency", command = frequency).grid(row = 7, column = 2)
Button(window, text = "Polialphabetical", command = polialphabetical).grid(row = 8, column = 1)
window.mainloop()
|
4dfbbc90cc00427f5f699cc282f7fe53890eab18 | shalgrim/advent_of_code_2017 | /day01_1.py | 367 | 3.578125 | 4 | def main(number):
digits = [int(c) for c in number]
matching_digits = [c for i, c in enumerate(digits[:-1]) if c == digits[i+1]]
if digits[-1] == digits[0]:
matching_digits.append(digits[-1])
return sum(matching_digits)
if __name__ == '__main__':
with open('data/input01.txt') as f:
data = f.read().strip()
print(main(data))
|
aa8cef657ef3278cf948499f1e70b8720f7a5239 | shalgrim/advent_of_code_2017 | /day03_2.py | 1,040 | 3.6875 | 4 | from collections import defaultdict
def get_next_xy(x, y, values):
if x == 0 and y == 0:
return 1, 0
elif values[(x - 1, y)] and not values[(x, y - 1)]:
return x, y - 1
elif values[(x, y+1)] and not values[(x-1, y)]:
return x-1, y
elif values[(x+1, y)] and not values[(x, y+1)]:
return x, y+1
elif values[(x, y-1)] and not values[(x+1, y)]:
return x+1, y
def set_xy(x, y, values):
values[(x, y)] = (
values[(x - 1, y)]
+ values[(x + 1, y)]
+ values[(x, y - 1)]
+ values[(x, y + 1)]
+ values[(x - 1, y - 1)]
+ values[(x - 1, y + 1)]
+ values[(x + 1, y - 1)]
+ values[(x + 1, y + 1)]
)
return values[(x, y)]
def main(innum):
values = defaultdict(lambda: 0)
thisval = 0
x = 0
y = 0
values[(x, y)] = 1
while thisval < innum:
x, y = get_next_xy(x, y, values)
thisval = set_xy(x, y, values)
return thisval
if __name__ == '__main__':
print(main(368078))
|
fbc2b174ff0abcb78531105634d19c6ec9022184 | 40309/Files | /R&R/Task 5.py | 557 | 4.28125 | 4 | checker = False
while checker == False:
try:
user_input = int(input("Please enter a number between 1-100: "))
except ValueError:
print("The value entered was not a number")
if user_input < 1:
print("The number you entered is too low, Try again")
elif user_input > 100:
print("The number you entered is too high, Try again")
else:
print()
print("The Number you entered is good")
print(user_input)
checker = True
print()
print()
print("End of Program")
|
aa645875aad41809e87f75462965d0ef49ce3519 | ThomasGarm/Simon_Game | /sequence.py | 247 | 3.546875 | 4 | from random import randint
class Sequence:
def __init__(self):
self.number = []
self.last_number = None
def random_sequence(self): #get a random integer
self.number.append(randint(0, self.last_number)) |
136df2aff65fa8667228b6bbab1812df388510fb | munawwar22HU/CS-351-Artificial-Intelligence | /Assignment01/ma04289_Ass1/Task 1/routePlanning.py | 3,412 | 3.5625 | 4 | import csv
import sys
from search import *
# Maps Cities to their ids
Cities = {}
# Map Cities to their heuristics
Heuristics = {}
# Map Cities to their neighbours
Connections = {}
def load_data(directory):
"""
Load data from CSV files into memory.
"""
with open(f"{directory}/cities.csv", encoding="utf-8") as f:
reader = csv.DictReader(f,fieldnames=["City"])
index = 0
for row in reader:
Cities[row["City"]]=index
index+=1
with open(f"{directory}/Connections.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
count = 0
for row in reader:
del row['']
Connections[count] = dict()
for key,value in row.items():
Connections[count][Cities[key]]=int(value)
count+=1
with open(f"{directory}/heuristics.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
count = 0
for row in reader:
del row['']
Heuristics[count] = dict()
for key,value in row.items():
Heuristics[count][Cities[key]]=int(value)
count+=1
def main():
if len(sys.argv) > 2:
sys.exit("Usage: python degrees.py [directory]")
directory = sys.argv[1] if len(sys.argv) == 2 else "CSV"
# Load data from files into memory
print("Loading data...")
load_data(directory)
print("Data loaded.")
source = city_id_for_name(input("Source: "))
if source is None:
sys.exit("City not found.")
target = city_id_for_name(input("Target: "))
if target is None:
sys.exit("City not found.")
RouteSearchProblem = RoutePlanning(source,target)
path = aStarSearch(RouteSearchProblem)
for i in path:
print(city_name_for_id(i.current))
def city_name_for_id(id):
for key,value in Cities.items():
if value == id: return key
def city_id_for_name(name):
"""
Returns the IMDB id for a person's name,
resolving ambiguities as needed.
"""
if name not in Cities: return False
else: return Cities[name]
class RoutePlanning(SearchProblem):
def __init__(self,source,target):
self.start = Node(source)
self.target = Node(target)
def getStartState(self):
"""
Returns the start state for the search problem.
"""
return self.start
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state.
"""
return state.current== self.target.current
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost' is
the incremental cost of expanding to that successor.
"""
Successors = []
City_id = state.current
for key,value in Connections[City_id].items():
if value !=-1 and value!=0:
x = Node(key)
Successors.append ((x,key,value))
return Successors
def getHeuristic(self,state):
return Heuristics[state.current][self.target.current]
if __name__ == "__main__":
main()
|
f8b1f4263226bbff9d98bec916648cdfebd4bb3b | Nickolasjucker/Cp1404-Practicals | /prac_04/intermediate exercises.py | 581 | 4.0625 | 4 | def main():
number_list = []
number_sum = 0
for i in range(5):
number_input = int(input("Enter a number: "))
number_list.append(number_input)
number_sum += number_list[i]
number_average = number_sum / 5
print("The first number is {}".format(number_list[0]))
print("The last number is {}".format(number_list[4]))
number_list.sort()
print("The smallest number is {}".format(number_list[0]))
print("The largest number is {}".format(number_list[4]))
print("The average of the numbers is {}".format(number_average))
main() |
8b83b53c42c1499f6b0313b9d2b921e17f488abf | Nickolasjucker/Cp1404-Practicals | /prac_01/electric_bill_2.0.py | 559 | 3.9375 | 4 | TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff_per_kwatt = int(input("Which tariff? 11 or 31: "))
daily_usage_kwatt = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
if tariff_per_kwatt == 11:
estimated_bill = TARIFF_11 * daily_usage_kwatt * billing_days
print ("Estimated bill: ${:.2f}".format(estimated_bill))
elif tariff_per_kwatt == 31:
estimated_bill = TARIFF_31 * daily_usage_kwatt * billing_days
print ("Estimated bill: ${:.2f}".format(estimated_bill))
else:
print("Not valid") |
7fcba95cd54cd8f4564b71a1a4150cb95918aa58 | smorenburg/python | /src/print_pyramid.py | 274 | 3.875 | 4 | def print_pyramid(num):
"""
>>> print_pyramid(5)
o
oo
ooo
oooo
ooooo
>>> print_pyramid(3)
o
oo
ooo
"""
for num in range(num):
line = 'o'
for num in range(num):
line += 'o'
print(line)
|
7d8e675e90f20c96366cd6c6ab2f3c9f9caf6c72 | smorenburg/python | /src/old/acloudguru/lambdas-and-collections/collection_funcs.py | 563 | 3.734375 | 4 | from functools import reduce
domain = [1, 2, 3, 4, 5]
# f(x) = x * 2
our_range = map(lambda num: num * 2, domain)
print(list(our_range))
evens = filter(lambda num: num % 2 == 0, domain)
print(list(evens))
the_sum = reduce(lambda acc, num: acc + num, domain, 0)
print(the_sum)
words = ['Boss', 'a', 'Alfred', 'fig', 'Daemon', 'dig']
print('Sorting by default')
print(sorted(words))
print('Sorting with a lambda key')
print(sorted(words, key=lambda s: s.lower()))
print('Sorting (reverse) with a method')
words.sort(key=str.lower, reverse=True)
print(words)
|
8534ccc5fceb5827a2e2c49cd7b2d561be89bad0 | smorenburg/python | /src/old/acloudguru/python_objects/car.py | 682 | 3.515625 | 4 | from vehicle import Vehicle
class Car(Vehicle):
default_tire = 'tire'
def __init__(
self,
engine,
tires=None,
distance_traveled=0,
unit='kilometers',
**kwargs
):
super().__init__(
distance_traveled=distance_traveled,
unit=unit,
**kwargs
)
if not tires:
tires = [
self.default_tire,
self.default_tire,
self.default_tire,
self.default_tire
]
self.tires = tires
self.engine = engine
def drive(self, distance):
self.distance_traveled += distance
|
577fc65755df718ed2aa9d22b08c3d01d2887032 | smorenburg/python | /src/old/contains.py | 541 | 3.890625 | 4 | #!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(
description='contains: Search for words including partial word.'
)
parser.add_argument(
'snippet',
help='partial (or complete) string to search for in words'
)
parser.add_argument(
'--version',
'-v',
action='version',
version='%(prog)s 1.0'
)
args = parser.parse_args()
snippet = args.snippet.lower()
with open('/usr/share/dict/words') as f:
words = f.readlines()
print([word.strip() for word in words if snippet in word.lower()])
|
064f159df2974e2dc1b7bf012e44a780437f2e29 | smorenburg/python | /src/old/exam-practice.py | 1,866 | 3.59375 | 4 | #!/usr/bin/env python3
ages = {
'Keith': 30,
'Levi': 25,
'John': 20,
}
del ages['Keith']
print(ages)
values = ['Kevin Bacon', 60, '555-555-5555', False]
val = not values[-1]
print(val)
ages = {
'Keith': 30,
'Levi': 25,
'John': 20,
}
output = [str(value) for value in ages.values()]
print(output)
names = ['Alice', 'Lance', 'Bob', 'Mike']
all_names = names
names.append('Brock')
print(sorted(all_names))
num = 12
num2 = num
num = num + 1
num2 = num2 / 2
print(num2)
for num in range(10):
print(num)
if num % 2 == 0:
continue
else:
break
num = 15.1
num2 = num / 4
num2 //= 2
num2 + 1
print(num2)
def fizz(num):
if num % 3 == 0 and num % 5 == 0:
return print('FizzBuzz')
elif num % 3 == 0:
return 'Fizz'
elif num % 5 == 0:
return 'Buzz'
else:
return num
fizz(15)
num = 5
message = 'Hello'
print(message, num)
names = ['Alice', 'Bob', 'Lance', 'Mike']
names[1:2] = []
print(names)
ages = {'Keith': 30, 'Levi': 25, 'John': 20}
age = ages.get('Kevin')
print(age)
num = 9
if num < 10:
print("Less than 10")
if num > 10:
print("Greater than 10")
else:
print("Less than 10")
def fib(n):
a, b = 0, 1
for _ in range(1, n):
a, b = b, a + b
yield a
fib_gen = fib(1)
print(fib_gen)
val = 1 or '2'
val *= 3
print(val)
names = ['Alice', 'Bob', 'Lance', 'Mike']
names[:3]
print(names)
letter = 'a'
if letter < 'b':
print("First")
if letter == 'b' or letter > 'c':
print("Second")
elif letter <= 'a':
print("Third")
else:
print("Fourth")
num = input("Enter a float value: ")
new_num = float(num) // 100 * 1.0
print(new_num)
num = 10
if num > 20 or num >= 10:
print("First")
elif num <= 10:
print("Second")
else:
print("Third")
def add_five(num1, num2=5):
return num1 + 5
print(add_five(1, 2))
|
c4ff4cd5e5f17c70f7527be634cddda045db972f | smorenburg/python | /src/old/exam-practice3.py | 2,104 | 4 | 4 | #!/usr/bin/env python3
def greeting(name=""):
print("Hello", name)
greeting()
numbers = [[1, 2, 3]]
initializer = 1
for i in range(1):
initializer *= 10
for j in range(1):
numbers[i][j] *= initializer
print(numbers)
x = 0
for i in range(10):
for j in range(-1, -10, -1):
x += 1
print(x)
a = 0b1011
b = 0b1001
print(bin(a ^ b))
x = 100
def glob():
global x
x = 20
glob()
print(x)
print("Python"*2, sep=',')
if not(True):
print("Hello, World!")
else:
print("Python is Awesome!")
num = [1, 2, 3, 4]
num.append(5)
print(num)
s1 = "Hello Mr Smith"
print(s1.capitalize())
if 1 == 1.0:
print("Values are the same")
else:
print("Values are different")
t1 = (1, 2, 3)
t2 = ('apples', 'banana', 'pears')
print(t1 + t2)
num = [1, 2, 3]
for i in range(len(num)):
num.insert(i, i+1)
print(num)
print(end='', sep='--')
i = 0
while i > 3:
i += 1
print("Yes")
else:
i -= 1
print("No")
print(10/5)
print(9 % 2 ** 4)
def my_print(*val):
print(val)
my_print("Peter", "Piper", "Pickled", "Pepper")
def fun(a=3, b=2):
return b ** a
print(fun(2))
marks = 55
if marks > 70 and marks < 80:
print("First Class")
elif marks > 60 and marks < 70:
print("Second Class")
elif marks > 50 and marks < 60:
print("Third Class")
else:
print("No Class")
a = 'apple'
b = 'banana'
x, y = b, a
print(x, y, sep="::")
my_list = ["apples", "bananas", ""]
my_list.remove("apples")
print(my_list)
my_tuple = tuple('Python World!')
print(my_tuple[:-7])
def my_function(num):
if num >= 4:
return num
else:
return my_function(1) * my_function(2)
print(my_function(4))
d = {'one': 2, 'two': 2}
d['one'] = 1
print(d)
def triple(num):
def double(num):
return num * 2
num = double(num)
return num * 3
print(triple(2))
print("Peter", "Piper", sep=",")
val = 5
print("less than 10") if val < 10 else print("greater than 10")
def func(num):
while num > 0:
num = num - 1
num = 3
func(num)
lst1 = [1, 4, 8, 16]
lst2 = [4, 16, 8, 1]
print(lst1 == lst2)
|
7e9c168b30e2ef6b98fd6d36f0f70ae2e57ecba4 | Marinagansi/PythonLabPractice | /practiceq/class/patternq.n2.py | 162 | 3.5625 | 4 | ascii_number=65
for i in range(4):
for j in range(i+1):
character=chr(ascii_number)
print(character, end=" ")
ascii_number +=1
print() |
102821abda68058175455a06bae24169ffae610a | Marinagansi/PythonLabPractice | /pythonProject1/q.1.py | 155 | 3.90625 | 4 | #check wheather 5 is in list of first natural number or not Hint list>=[1,2,3,4,5]
list=(1,2,3,4,5,6,7)
if 5 in list:
print("yes")
else:
print("no")
|
543721c9305979661f6c83e16d3d90e0a1496c91 | Marinagansi/PythonLabPractice | /practiceq/class/evn.py | 109 | 3.96875 | 4 | for i in range(0,10):
if i%2==0:
print (i,"even number")
else:
print (i,"odd number")
|
ccb9085a49b2c86e8ba038127e386205e0e06133 | Marinagansi/PythonLabPractice | /qn6.py | 107 | 4.21875 | 4 | '''given a integer number, print it last digit'''
num=int(input("enter the number:"))
rem=num%10
print(rem) |
aad05d66c26fa07d7b9ea7b59ca719af4f456248 | Marinagansi/PythonLabPractice | /practiceq/pythonProject1/fucntion/q1.py | 225 | 4.1875 | 4 | ''' to print multipliacation table of a given number by using fuction'''
def multi(a):
product=1
for i in range(11):
product=a*i
print (f"{a}*{i}={product}")
a=int(input("enter the nnumber"))
multi(a)
|
8adef0dd43f92dd18d064ed8c52b9be6a290cc29 | Marinagansi/PythonLabPractice | /practiceq/pythonProject1/fucntion/qfactorial.py | 186 | 4.21875 | 4 | '''find factorial num'''
def fact(a):
product=1
for i in range(2,a+1):
product=product*i
return product
a=int(input("enter the number:"))
c=fact(a)
print(f"the ans is{c}") |
a31e24fc138ca9767e2709f3ec3b2b376783dd6b | Marinagansi/PythonLabPractice | /practiceq/pythonProject1/fucntion/function5.py | 163 | 3.578125 | 4 | '''have parameter and return type'''
def dev(a,b):
return a/b
a=int(input("enter the num:"))
b=int(input("enter the num:"))
c=dev(a,b)
print(f"the ans is {c}") |
fb154305fee8fbb0d9f8ba861c0e633d54bffde8 | Marinagansi/PythonLabPractice | /practiceq/class/q.5 pattern.py | 170 | 3.9375 | 4 | alphabet= ord("A")
for i in range (6,1,-1):
for j in range(1,i-1):
character=chr(alphabet)
print(character, end=" ")
alphabet +=1
print()
|
e28269d4d872492ed3133fd2b8c9a7a96e34c62b | sabina2/DEMO3 | /Hurray.py | 138 | 3.953125 | 4 | num1 = int(input("Enter your 1st number"))
num2 = int(input("Enter your 2nd number"))
if num1==num2 or num1+num2==7:
print("Hurray")
|
32c1121ea0baa887256bde8e45d8c3e1017b5b11 | pritamnegi/Machine-Learning-in-Python | /Day 3/Session 1/Multiple_Regression_Using_Train_and_Test_Split.py | 1,541 | 3.703125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as stats
import sklearn
# Importing the dataset
marketing = pd.read_csv("C:\\Users\\app\\Desktop\\marketing.csv")
# Getting first five rows of the marketing dataset
marketing.head()
# Getting type marketing dataset
type(marketing)
# Getting columns in marketing dataset
marketing.columns
# Getting value of correlation between all columns
marketing.corr()
# Setting the features and target variables
X = marketing.as_matrix(['youtube', 'facebook'])
Y = marketing.sales
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.20, random_state = 5)
# Fitting the model
lm.fit(X_train, Y_train)
# Slope
print(lm.coef_)
# X intercept
print(lm.intercept_)
# Variance score i.e. how much variation is captured by the model
print(lm.score(X, Y))
Y_pred = lm.predict(X_test)
from sklearn.metrics import mean_squared_error
mse = np.mean((Y_test-Y_pred)**2)
mse = mean_squared_error(Y_test, Y_pred)
# Visualizing the Y and Y_pred
plt.title("Comparison of Y values and the Prediced values")
plt.xlabel("Testing Set")
plt.ylabel("Predicted values")
plt.scatter(Y_pred, Y_test, color = "black")
plt.scatter(X, Y)
min_X = min(X)
max_X = max(X)
m = lm.coef_[0]
b = lm.intercept_
plt.plot([min_X, max_X], [b, m*max_X + b], 'r')
plt.title("Fitted Regression Line")
plt.xlabel("X")
plt.ylabel("Y")
|
7dfe63d7af4f0bbb3ff0bb6798c55c4c0e5563d8 | CaravanPassenger/pytorch-learning-notes | /image_classification/core/simpleNet.py | 1,462 | 3.5 | 4 | # -*-coding: utf-8 -*-
"""
@Project: pytorch-learning-tutorials
@File : simpleNet.py
@Author : panjq
@E-mail : pan_jinquan@163.com
@Date : 2019-03-09 13:59:49
"""
import torch
from torch import nn
from torch.nn import functional as F
class SimpleNet(torch.nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
# 卷积层conv1
self.conv1 = torch.nn.Sequential(
nn.Conv2d(3, 32, 3, 1, 1),
nn.ReLU(),
nn.MaxPool2d(2))
# 卷积层conv2
self.conv2 = torch.nn.Sequential(
nn.Conv2d(32, 64, 3, 1, 1),
nn.ReLU(),
nn.MaxPool2d(2))
# 卷积层conv3
self.conv3 = nn.Sequential(
nn.Conv2d(64, 64, 3, 1, 1),
nn.ReLU(),
nn.MaxPool2d(2))
# 全连接层dense
self.dense = nn.Sequential(
nn.Linear(64 * 3 * 3, 128),
nn.ReLU(),
nn.Linear(128, 10)
)
def forward(self, x):
conv1_out = self.conv1(x)
conv2_out = self.conv2(conv1_out)
conv3_out = self.conv3(conv2_out)
res = conv3_out.view(conv3_out.size(0), -1)
out = self.dense(res)
return out
def test_net():
model = SimpleNet()
tmp = torch.randn(2, 3, 28, 28)
out = model(tmp)
print('resnet:', out.shape)
if __name__ == '__main__':
test_net() |
2c21e4855b3463c2330a2081b93f556d0ac6fb3e | zhigang0529/PythonLearn | /src/main/operation/File.py | 1,331 | 3.734375 | 4 | #!/usr/bin/python
# _*_ coding: UTF-8 _*_
import psutil
from io import open
file_path = "content.txt"
# 写文件内容
content = u'''Python is a programming language that lets you work quickly
and integrate systems more effectively.'''
f1 = open(file_path, "a") # a是追加文件内容
f1.write(content)
f1.write(u"\n")
f1.close()
'''
#读文件内容
f2 = open(file_path, 'r')
#不带参数的read()函数一次读入文件的所有内容
print(f2.read())
f2.close()
'''
'''
#将数据进行分块,直到所有字符被写入
fout = open(file_path, "w")
size = len(content)
offset = 0
chunk = 100
while True:
if offset > size:
break
fout.write(content[offset:offset+chunk])
offset += chunk
fout.close()
'''
'''
#readline()每次读入文件的一行,通过追加每一行拼接成原来的字符串:
ct = ""
fin = open(file_path, "r")
while True:
line = fin.readline()
if not line:
break
ct += line
fin.close()
print(ct)
'''
'''
# 函数readlines()调用时每次读取一行,并返回单行字符串的列表
f3 = open(file_path, "r")
lines = f3.readlines()
f3.close()
for line in lines:
print(line) # print(line, end="")
'''
print("Writer number to file")
f4 = open("number.txt", "w+")
for i in range(10):
f4.write(u'write ' + str(i) + '\n')
f4.flush()
f4.close() |
66bb84f9550a7dcc3828abb09a13bf9e536b6e29 | senseyluiz/estudopython | /exercicios/ex006.py | 290 | 4.03125 | 4 | # Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.
num = int(input("Digite um número: "))
dob = num * 2
tri = num * 3
rai = num ** (1/2)
print(f"O dobro de {num} é {dob}\n"
f"O triplo de {num} é {tri}\n"
f"A raiz quadrada de {num} é {rai}")
|
916e91fff916b3c759185524bf71d2d4c8591592 | senseyluiz/estudopython | /exercicios/ex012.py | 327 | 3.671875 | 4 | # Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
pAtual = float(input("Qual o preço do produto: R$ "))
nPreco = pAtual * 0.95
print(f"O produto que custa R$ {pAtual:.2f}, com 5% de desconto, custará R$ {nPreco:.2f}\n"
f"O desconto total foi de R$ {pAtual * 0.05:.2f}")
|
8e2d656729f0671a1994d903e6ce858394477bc7 | senseyluiz/estudopython | /exercicios/ex031.py | 385 | 3.9375 | 4 | # Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem,
# cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
dis = int(input("Qual a distância da viagem? "))
if dis <= 200:
valor = dis * 0.50
else:
valor = dis * 0.45
print(f"Você fará uma viagem de {dis} Km e pagará R$ {valor:.2f}")
|
a6ed1a1ebd769832c55f0ba000e05812ac01c63f | senseyluiz/estudopython | /exercicios/ex039.py | 695 | 3.84375 | 4 | # Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade,
# se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento.
# Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
from datetime import date
ano = date.today().year
nasc = int(input("Ano de nascimento: "))
idade = ano - nasc
if idade < 18:
print(f"Ainda não é hora de se alistar. Faltam {18 - idade} anos")
elif idade == 18:
print("Você precisa se alistar imediatamente. BOA SORTE!!!")
elif idade > 18:
print(f"Seu alistamento foi em {nasc + 18} há {ano - (nasc + 18)} anos atrás.")
|
707681af05d6cb4521bf4f729290e96e6c347287 | Dirac26/ProjectEuler | /problem004/main.py | 877 | 4.28125 | 4 | def is_palindromic(num):
"""Return true if the number is palindromic and false otehrwise"""
return str(num) == str(num)[::-1]
def dividable_with_indigits(num, digits):
"""Returns true if num is a product of two integers within the digits range"""
within = range(10 ** digits - 1)
for n in within[1:]:
if num % n == 0:
if num / n <= 10 ** digits - 1:
return True
return False
def largest_mult(digits):
"""Returns the largest palindromic number that is the product of two numbers with certain digits number"""
num = (10 ** digits - 1) ** 2
found = False
while not found:
if is_palindromic(num):
if dividable_with_indigits(num, digits):
return num
num -= 1
def main():
"""main funtion"""
print(largest_mult(3))
if __name__ == "__main__":
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.