blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2bc497d9e1a1a89d48a6f9c684febbd65074d200 | jameszhan/hotchpotch_pythons | /builtin/lang_features/desciptor.py | 825 | 3.578125 | 4 | #!/usr/bin/env python
class mydescriptor(object):
def __call__(cls):
print('new me')
#i'm going to be bound!!!
def __get__(self, new_self, Type = None):
#let us bind it!!!
print('__get__')
return self.__call__
#oh no.... i'm being override..
def __set__(self, new_self, value):
print('__set__')
#nonono i won't
#raise AttributeError
class host(object):
data = mydescriptor()
def __init__(self):
self.data = mydescriptor()
self.data1 = mydescriptor()
h = host()
print(h.__dict__)
h.data()
h.data1()
print('----------')
#functions are natural descriptors, cuz they have __get__
#to bind values in order
def foo_func(x, y):
return x + 2 * y
#50
foo_func(10, 20)
#41
bar_func = foo_func.__get__(1)
bar_func(20)
|
c5409bbe6d655ee6e95b99e80cd02b997b5d02ed | saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174- | /Introduction to Programming Exercises/ex15.py | 572 | 4.4375 | 4 | '''
Exercise 15: Distance Units
In this exercise, you will create a program that begins by reading a measurement
in feet from the user. Then your program should display the equivalent distance in
inches, yards and miles. Use the Internet to look up the necessary conversion factors
if you don’t have them memorized.
'''
feet = float(input('Enter your distance in feet: '))
print('The equivalent distance in inches is', feet * 12)
print('The equivalent distance in yards is', feet * 0.333333)
print('The equivalent distance in miles is', feet * 0.000189394) |
0bd204847851f9006a893dd354c738a4412bfae4 | tickhcj/mystuff | /ex3.py | 706 | 4.03125 | 4 | # What to do
print "I will now count my chickens:"
# The number of chickens
print "Hens", 25.0 + 30.0 / 6.0
print "Roosters", 100 - 25.0 * 3.0 % 4.0
# cout the eggs
print "Now I will count the eggs:"
# The calculation results
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# To determine the size
print "Is it true that 3 + 2 < 5 - 7?"
# To compare
print 3 + 2 < 5 - 7
# Comparing the two groups of Numbers
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
# The results of
print "Oh, that's why it's False."
# How about some more
print "How about some more,"
# The comparison of more
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2 |
61fddbaafa4fbe3e2d1e72eb0b2f1289d99d5819 | kellystroh/Word_Ladder | /game_app/init_db.py | 560 | 3.9375 | 4 | #imports sqlite
import sqlite3
#connects it to the books-collection database
conn = sqlite3.connect('game-records.db')
#creates the cursor
c = conn.cursor()
#executes the query which inserts values in the table
c.execute("INSERT INTO game VALUES( 1, '[dinner, time, machine, learning, experience, required, reading, material, world, peace]', '', '[0, 9]', '[1, 8]', 0, 0, 0, 1, 0, 0, 0)")
c.execute("INSERT INTO turn VALUES( 1, 1, 1, 1, '[0,0]', 0, '', 1, 0, '', '', 1, '', 0, 0 )")
#commits the executions
conn.commit()
#closes the connection
conn.close() |
88c960b1337389666ce1c86a8a52720a7c734278 | SarthakSharma660/Python_Practice | /BIll_Splitter.py | 438 | 4.21875 | 4 | print("Welcome to the tip calculator")
# asking for total bill
bill=float(input("What is the total bill :\n"))
# asking for tip %
percent=int(input("What percentage tip would you like to give? 10,12 or 15\n"))
#asking for number of people
no_people=int(input("How many people to split bill ?\n"))
# calculations
total_bill=(bill+(bill*percent/100))/no_people
total_bill=round(total_bill , 2)
print(f"Each person should pay: {total_bill}") |
fcce75d3d358a2e83b76ecc2d52f7cf15bb22776 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/3858/codes/1644_2704.py | 97 | 3.6875 | 4 | nt = float(input())
m = input()
m = m.upper()
if(m == "S"):
print(nt+(nt*0.10))
else:
print(nt) |
f279abd7c1b0453d127b5e2fa729e0e4fa081cc7 | ethanjpkamus/zoo-o-mathematics | /animals.py | 682 | 3.90625 | 4 | # Arithmetic Computational Game - Zoo-o-mathematics!
# set of arrays - animals for each corresponding level of difficulty
from arithmeticFunc import *
listOfAnimals = [
"hare",
"lion",
"camel",
"koala",
"lemur",
"otter",
"panda",
"sloth",
"tiger",
"zebra",
"dragon",
"gorilla",
"jaguar",
"penguin",
"ostrich",
"serpent",
"orangutan",
"lochness monster"
]
def getAnimal(num):
if num >= 0.90:
animal = random.choice(listOfAnimals)
print("Congratulations! You have earned a new friend: ", animal.upper(), "!")
else:
print("Oh shucks. Better look next time fellow Zookeeper!")
|
739684680bc6e4a66c985b1f576ee3fbb0c8f794 | 44378/Iteration | /Itteration rev ex - python school 4.py | 260 | 4.03125 | 4 | #Jack Scaife
#31/10/14
#Rogue cancel for addition
total = 0
value = int(input("Enter a number to add to the total: "))
while value > 0 :
value = int(input("Enter a number to add to the total: "))
total = total+value
print("The total is {0}".format(total))
|
3989b665f074cfc3132eef0397f0febe9103d7bf | manpreetsran93/movies_db | /find.py | 1,798 | 4.40625 | 4 | import printcol
def find(dict1):
"""Finds movie/s from collection based attribute searched by user
:param dict1: dictionary contains movies as keys and their attributes in a nested dictionary
:return:
"""
if dict1 != {}:
search = input("Which attribute would you like to search by? Enter: Year, Director, or Shelf\n\n")
# if user is searching by year, print out movies by that year from the collection
if search.lower() == "year":
year = int(input("Enter Year: "))
for i in dict1:
if dict1[i]['Year'] == year:
printcol.print_collection(dict1, i)
else:
print("No movies from the year {year} in collection\n".format(year=year))
# if user is searching by director, print out movies by that director from the collection
elif search.lower() == "director":
director = input("Enter Director Name: ")
for i in dict1:
if dict1[i]['Director'] == director:
printcol.print_collection(dict1, i)
else:
print("No movies from the director {director} in collection\n".format(director=director))
# if user is searching by shelf number, print out movies from that shelf number from the collection
elif search.lower() == "shelf":
shelf = input("Enter shelf number: ")
for i in dict1:
if dict1[i]['Shelf'] == shelf:
printcol.print_collection(dict1, i)
else:
print("No movies from the year {shelf} in collection\n".format(shelf=shelf))
else:
print("Not A Valid Attribute!\n")
else:
print("Collection is empty!\n")
|
8516132ce3cbb26fff2360bc5d522403387c569a | simran0963/python | /search.py | 551 | 3.984375 | 4 | li = list(map(int,input("enter the list elements separated by spaces in a non decreasing order: ").split())) # to enter a list
key = int(input("enter the key : "))
# print('List is ' , li)
# print('Key is ', key)
# print(key in li)
def linearSearch(li,key)->bool:
for i in li:
if i == key:
return True
return False
def binarySearch(li,key)->bool:
low , high = 0 , len(li)-1
while(low <= high):
mid = ( low + high ) // 2
if li[mid] == key:
return True
elif li[mid] > key:
high = mid - 1
else:
low = mid + 1
return False
|
a591fa25b377692e64340ec17750f55b41bdb68d | kiranmahi2593/Projects | /dictonary_module.py | 865 | 4.15625 | 4 | def Add(x):
Udict = dict()
for i in range(x):
DKey = input("Enter the Key:")
DValue = input("Enter the Value:")
Udict[DKey] = DValue
print("Dictionary",Udict)
return Udict
def Remove(x):
val = input("enter the key name to remove dict:")
x.pop(val)
print("Dictionary after removing values:",x)
return x
def Remove_last(x):
n=list(x.keys())[-1]
x.pop(n)
print("Dictionary after removing values:",x)
return x
def Get_keys(x):
Lkeys = x.keys()
print("Keys are:",Lkeys)
return Lkeys
def Get_Values(x):
Lval = x.values()
print("values are:",Lval)
return Lval
def Replace(x):
val=input("Enter the key value to replace:")
new_var = x[val]
print("new replace value:",new_var)
|
fd6ed5bdc98130b9d4b876f8253f1204ab749540 | Dearyyyyy/TCG | /data/3920/AC_py/519774.py | 195 | 3.65625 | 4 | # coding=utf-8
line = input()
number = int(line)
number_list = list(line)
cal = 0
for i in range(3):
cal += int(number_list[i]) ** 3
if cal == number:
print("YES")
else:
print("NO") |
2e354d494a3b76c0a6811628e5a238770f5c324a | pippylam/python | /dientich.py | 233 | 3.625 | 4 | chieudai = int(input("Nhap chieu dai hinh chu nhat: "))
chieurong = int(input("Nhap chieu rong hinh chu nhat: "))
print ("Chu vi hinh chu nhat la: ", (chieudai+chieurong)*2)
print ("Dien tich hinh chu nhat la: ", chieudai*chieurong)
|
b1f55ae6cce0a19be382d81a116aadda9ad8c4e7 | Shivani3012/PythonPrograms | /conditional ass/ques32.py | 215 | 4.21875 | 4 | #Write a Python program to check whether an alphabet is a vowel or consonant.
ch=input("Enter the character:")
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':
print("Vowel")
else:
print("Consonent")
|
6af428efd7c0a97ff30ca3bf2d37444a3d236e95 | saurav188/python_practice_projects | /bianary_tree_iterative_inorder_traversal.py | 805 | 3.953125 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(self):
stack=[]
current=self
result=""
while True:
if current!=None:
stack.append(current)
current=current.left
elif len(stack)>0:
current=stack.pop()
result+=current.val+"=>"
current=current.right
else:
break
return result
tree = Node('a')
tree.left = Node('b')
tree.right = Node('c')
tree.left.left = Node('d')
tree.left.right = Node('e')
tree.right.left = Node('f')
tree.right.right = Node('g')
print(tree.inorder())
# a
# / \
# b c
# / \ / \
# d e f g |
d4d536e733df1a149691d7e9b0cce9b7649cc7ab | bFraley/python-examples | /jason_mize.py | 1,136 | 3.828125 | 4 | print ("=" * 10)
#This module allows you to ouput calendars.
#It has built in functions to help.
import calendar
def calendar_example ():
#prints the day you have set to be the start of the week
#in this case the default is 0 for Monday
print (calendar.firstweekday())
#prints what day of the week the date was on
#0 = Monday, 1 = Tuesday, etc.
print (calendar.weekday(2016, 8, 28))
calendar_example()
print ("=" * 10)
#This module identifies image file types.
import imghdr
def imghdr_example ():
#Takes the image, considers the byte-stream, identifies type.
print(imghdr.what('pizza2.jpg'))
imghdr_example()
print ("=" * 10)
#This module allows the manipulation of dates and times
import datetime
def datetime_example ():
#fetches the current dates/times
info = datetime.datetime.now()
print("Year: {}".format(info.year))
print("Month: {}".format(info.month))
print("Day: {}".format(info.day))
print("Hour: {}".format(info.hour))
print("Minute: {}".format(info.minute))
print("Second: {}".format(info.second))
print("Microsecond: {}".format(info.microsecond))
datetime_example()
print ("=" * 10)
|
83449302e04e40941dbf5ffc8e16996186203e9c | hariharanragothaman/codeforces-solutions | /contests/339/339A-Helpful-Maths.py | 99 | 3.765625 | 4 | string = input().split('+')
string = sorted(c for c in string)
print('+'.join(c for c in string))
|
d792e0c8b5964c2b4c8590dc124b27112184fc45 | mebarile02/Python- | /explode_seq.py | 449 | 4 | 4 | """
This is a function that takes in a natural number n. It assumes the user will
enter an integer, but not necessarily a natural number.
"""
def explode_seq(n):
cond = True
while cond:
if n > 0:
cond = False
else:
n = int(input('Enter an integer greater than 0: '))
if n == 1:
return 1
elif n == 2:
return 2
else: return explode_seq(n-1)+explode_seq(n-2)
|
130fa7cc423067efacecf6dbe66590772ae94e18 | tanx16/blindfold-chess | /user_input.py | 2,641 | 4 | 4 | from pieces import *
from game import *
import sys
new_chessboard = Chessboard()
new_game = Game(new_chessboard)
column_names = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7}
def start():
print("Hi! Welcome to Blind Chess, a challenging game where neither side can see the chessboard!\n")
answer = input("Would you like to play? Y/N\n")
if answer.lower() == "y":
print("Here are the instructions.")
print("To input a coordinate, enter the first letter of the piece, and then the column and number you want and where the piece comes from. Ex. Pb2b3 to move pawn to b3 from b2.\n")
print("To castle, type qcastle or kcastle for the appropriate side.")
print("Since knight and king both start with k, use n for knight. Have fun!")
begin()
elif answer.lower() == "n":
sys.exit("Okay, Bye!")
else:
print("Please enter either y or n.")
start()
def begin():
while not new_game.over:
new_game.board.display()
answer = input("%s's turn. Please input a coordinate.\n" % new_game.board.turn)
if answer == "quit()":
sys.exit("Okay, Bye!")
if answer[:3] == "get":
col = column_names[answer[4]]
row = int(answer[5]) - 1
piece = new_chessboard.getPiece(col, row)
print(piece, piece.color if piece else piece)
if answer == "qcastle" or answer == "kcastle":
if new_game.board.turn == "white":
new_game.board.white_side_castle(answer[0])
continue
else:
new_game.board.black_side_castle(answer[0])
continue
try:
orig_row = int(answer[2]) - 1
new_row = int(answer[4]) - 1
name = answer[0]
except (ValueError, IndexError):
print("Please enter a valid command. (ValueError/IndexError occurred.)")
begin()
if orig_row > 7 or orig_row < 0 or new_row > 7 or new_row < 0:
print("Please enter a valid row.")
continue
try:
orig_col = column_names[answer[1]]
new_col = column_names[answer[3]]
piece = new_game.board.getPiece(orig_col, orig_row)
if piece.name != name.lower():
print("There is no such piece there.")
continue
new_game.board.move(piece, new_col, new_row)
except (KeyError, AttributeError):
print("Please enter a valid command. (KeyError/AttributeError occurred.)")
start()
|
af6f41cc78f216617bb43df6b87192ac916adf98 | ptsiampas/Exercises_Learning_Python3 | /07_Iteration/Exercise_7.26.15.py | 1,338 | 4.09375 | 4 | # Write a function num_even_digits(n) that counts the number of even digits in n. These tests should pass:
#
# test(num_even_digits(123456), 3)
# test(num_even_digits(2468), 4)
# test(num_even_digits(1357), 0)
# test(num_even_digits(0), 1)
import sys
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
.format(linenum, expected, actual))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(num_even_digits(123456), 3)
test(num_even_digits(2468), 4)
test(num_even_digits(1357), 0)
test(num_even_digits(0), 1)
def is_even(n):
if (n % 2) == 0:
return True
return False
def num_even_digits(n):
if n == 0: # FixMe if its 0 then its always going to be 1 digit, stops while loop atm, needs fixing.
return 1
count = 0
n=abs(n) # Handle Negative Numbers
while n != 0:
if is_even(n):
count = count + 1
n = n // 10
return count
test_suite() |
20635e7f48d2ed356a5d6eb749db95e35e97bf0a | tomasmariconde/EDA_with_Python | /EDA.py | 8,785 | 4 | 4 | #Analisis exploratorio (EDA) de protestas de campesinos sudamericanos con Python
#PASO 1 - Carga de librerias
#Importamos las librerias que utilizaremos para generar nuestro analisis
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#PASO 2 - Carga de datos
#Cargamos nuestra base de datos a un DataFrame de pandas al que renombramos "df" mediante la creacion de una nueva variable
pd.read_csv("/Users/elCONDEMARI/Desktop/Python/mmALL_073119_csv.csv")
df=pd.read_csv("/Users/elCONDEMARI/Desktop/Python/mmALL_073119_csv.csv")
print(df)
#Vemos la cantidad de filas y columnas
df.shape
#Vemos los tipos de variable y otra info
df.info()
#PASO 3 - Limpieza general de datos
#Filtramos las columnas del DataFrame para quedarnos con las siguientes solamente:
#country (name)
#year (year of protest)
#region (country region)
#protest (was there a protest in the relevant period?)
#protestnumber (protest number in year)
#startday
#startmonth
#startyear
#endday
#endmonth
#endyear
#protesterviolence (did protesters engage in violence against the state?)
#location
#participants (number of participants)
#staterespone1
#staterespone2
#staterespone3
#staterespone4
#staterespone5
#staterespone6
#staterespone7
df=df.loc[:,["country", "year", "region", "protest", "protestnumber", "startday", "startmonth", "startyear", "endday", "endmonth", "endyear", "protesterviolence", "location", "participants", "stateresponse1", "stateresponse2", "stateresponse3", "stateresponse4", "stateresponse5", "stateresponse6", "stateresponse7"]]
print(df)
#Filtramos las columnas "region" y "year" para quedarnos con la region sudamericana y datos a partir del año 2009 (hasta el 2014)
df=df[df["region"]=="South America"]
df=df[df["year"]>=2009]
print(df)
#Eliminamos las columnas "stateresponse2", "stateresponse3", "stateresponse4", "stateresponse5", "stateresponse6" y "stateresponse7" debido a que solo nos interesa conocer las primeras reacciones de los estados ante los conflictos
df.drop("stateresponse2", axis=1, inplace=True)
df.drop("stateresponse3", axis=1, inplace=True)
df.drop("stateresponse4", axis=1, inplace=True)
df.drop("stateresponse5", axis=1, inplace=True)
df.drop("stateresponse6", axis=1, inplace=True)
df.drop("stateresponse7", axis=1, inplace=True)
print(df)
#Reestructuramos el DataFrame de modo que los valores contenidos en las columnas "startday", "startmonth" y "startyear" se agrupen bajo un nueva y unica columna llamada "startdate"
#En primer lugar, eliminamos los valores nulos de la columna "startyear"
df=df.dropna(subset=["startyear"])
print(df)
#En segundo lugar, convertimos el total de las columnas en int para quitar los decimales previo a agruparlas
df["startday"]=df.startday.apply(int)
df["startmonth"]=df.startmonth.apply(int)
df["startyear"]=df.startyear.apply(int)
print(df)
#Por ultimo, agrupamos las tres columnas bajo una nueva llamada "startdate" utilizando la funcion to_datetime
df["startdate"]=pd.to_datetime(df["startday"].apply(str) + "/" + df["startmonth"].apply(str) + "/" + df["startyear"].apply(str), format="%d/%m/%Y", infer_datetime_format=True, errors="coerce")
print(df)
#Reestructuramos el DataFrame de modo que los valores contenidos en las columnas "endday", "endmonth" y "endyear" se agrupen bajo un nueva y unica columna llamada "enddate"
#En primer lugar, convertimos el total de las columnas en int para quitar los decimales previo a agruparlas. No es necesario eliminar los valores nulos como hicimos anteriormenete ya que por esa accion quedaron eliminados en este caso también
df["endday"]=df.endday.apply(int)
df["endmonth"]=df.endmonth.apply(int)
df["endyear"]=df.endyear.apply(int)
print(df)
#Luego agrupamos las tres columnas bajo una nueva llamada "enddate" utilizando la funcion to_datetime
df["enddate"]=pd.to_datetime(df["endday"].apply(str) + "/" + df["endmonth"].apply(str) + "/" + df["endyear"].apply(str), format="%d/%m/%Y", infer_datetime_format=True, errors="coerce")
print(df)
#Reiniciamos el indice a fin de poder trabajar en el siguiente paso con mayor comodidad
df.reset_index(level=0, inplace=True)
print(df)
#Eliminamos el indice anterior que se convirtio en columna y por tanto no nos sirve
df.drop("index", axis=1, inplace=True)
print(df)
#PASO 4 - Preparacion de datos para su graficación
#Duración de las protestas (¿Fueron mas largas que la Argentina?)
#Calculamos la duración exacta de las protestas y creamos una nueva columna llamada "daysofconflict"
df["daysofconflict"]=df["enddate"]-df["startdate"]
print(df)
#Convertimos los días de la columna "daysofconflict" en int
df["daysofconflict"]=df["daysofconflict"].astype(str)
df["daysofconflict"]=df["daysofconflict"].str.strip("days").astype(int)
#Extension territorial de las protestas (¿Se extendieron mayoritariamente a nivel nacional?)
#Reenombramos todos aquellos valores similares a "National level" para que queden todos bajo ese mismo nombre
df["location"]=df["location"].replace({"national":"National level", "National":"National level", "national level":"National level", "nation wide":"National level", "Nation wide":"National level", "nationwide":"National level"})
print(df)
#Reemplazamos todas las localidades que no sean "National level" por "Local level" ya que solo nos interesa saber si fueron a nivel nacional o a nivel local, mas no las especificidades de estas ultimas
location_changes=df["location"]!="National level"
df.loc[location_changes, "location"]="Local level"
print(df)
#Virulencia de las protestas (¿Participaron los manifestantes de actos de violencia contra el Estado?)
#Reemplazamos los valores 0 y 1 por las respuesta "No" y "Si" respectivamente (asumiendo que esos valores corresponden a esas respuestas en base al manual de usuario compartido, en particular la variable "protest" de similar construccion)
df["protesterviolence"]=df["protesterviolence"].replace({1:"Si"})
protesterviolence_changes=df["protesterviolence"]!= "Si"
df.loc[protesterviolence_changes, "protesterviolence"]= "No"
print(protesterviolence_changes)
#PASO 5 - Analisis de datos
#Duración de las protestas (¿Fueron las protestas mas largas que la argentina del 2008?)
#Obtenemos información general como ser el promedio
print(df.daysofconflict.describe())
print("El promedio de duracion de las protestas es de:", df.daysofconflict.mean())
print("La mediana de duracion de las protestas es:", df.daysofconflict.median())
print("El valor minimo de duracion de las protestas es", df.daysofconflict.min())
print("El valor maximo de duracion de las protestas es", df.daysofconflict.max())
#Graficamos la distribucion de los valores
fig, ay = plt.subplots()
ay.boxplot(df.daysofconflict)
plt.show()
#Duplicamos la columna "daysofconflict" en una nueva que creamos llamada "daysofconflict_duplicated". En ella intercambiamos los elementos originales por nuevas categorias que los agrupan, que nos permiten graficar un "pie" mas legible.
dayofconflict_conditions=[
(df["daysofconflict"]<1),
(df["daysofconflict"]>=1) & (df["daysofconflict"]<=5),
(df["daysofconflict"]>5) & (df["daysofconflict"]<=10),
(df["daysofconflict"]>=11)
]
daysofconflict_values=["Menos de 24 hs", "Entre 1 y 5 dias", "Entre 6 y 10 dias", "Mas de 10 dias"]
df["daysofconflict_duplicated"]=np.select(dayofconflict_conditions, daysofconflict_values)
colors=["#EE6055","#60D394","#AAF683","#FFD97D"]
desfase= (0.1, 0, 0, 0)
daysofconlict_duplicated_plot=df["daysofconflict_duplicated"].value_counts().plot(kind="pie",colors=colors, explode=desfase, autopct="%1.1f%%", fontsize=12, figsize=(6,6), title="Duracion de las protestas")
plt.show()
#Extension territorial de las protestas (¿Se extendieron las protestas mayoritariamente a nivel nacional?)
location_plot=df["location"].value_counts().plot(kind="barh", color="cadetblue", fontsize=12, figsize=(6,6), title="Distribucion territorial de las protestas")
plt.show()
#Virulencia de las protestas (¿Participaron los manifestantes de actos de violencia contra el Estado?)
colors2=["#6B8ba4","#9dbcd4"]
desfase2 = (0.1, 0)
protesterviolence_plot=df["protesterviolence"].value_counts().plot(kind="pie",colors=colors2, explode=desfase2, fontsize=12, autopct="%1.1f%%", figsize=(6,6), title="¿Participaron los manifestantes de actos de violencia contra el Estado?")
plt.show()
#Respuesta frente a las protestas (¿Cuál fue la primera respuesta más extendida por parte de los Estados frente al conflicto?)
stateresponse1_plot=df["stateresponse1"].value_counts().plot(kind="bar", color="palegreen", fontsize=12, figsize=(6,6), title="¿Cuál fue la primera respuesta más extendida por parte de los Estados frente al conflicto?")
plt.xticks(rotation=75)
plt.show()
|
256d2fe77046027509078e5c1c990b40466bfa67 | ejrinkus/netris | /game/gameover.py | 2,518 | 3.765625 | 4 | ################################################################################
#
# Contains the Pause class. This class is responsible for displaying and
# removing the pause screen overlay during a game (will not be needed in modes
# with more than one human player, since pausing won't be allowed).
#
################################################################################
__author__ = 'Eric'
import pygame
from consts import *
# Class containing information for drawing the pause screen overlay
# self.game: reference to the game currently being played
# self.next_cover: covers the next piece box
# self.hold_cover: covers the hold piece box
# self.board_cover: covers the playing board
class GameOver(object):
# Constructor
# game: reference to the game being played
def __init__(self, game):
self.game = game
self.next_cover = pygame.Surface((BOX_SIZE*5, BOX_SIZE*5))
self.next_cover.fill(BLACK)
self.hold_cover = pygame.Surface((BOX_SIZE*5, BOX_SIZE*5))
self.hold_cover.fill(BLACK)
self.board_cover = pygame.Surface((BOX_SIZE*10-9, BOX_SIZE*20))
self.board_cover.fill(BLACK)
game_label = pauseFont.render("Game", False, LIGHT_GREY)
self.board_cover.blit(game_label,
(BOX_SIZE*5-game_label.get_width()/2, BOX_SIZE*10-game_label.get_height()/2))
over_label = pauseFont.render("Over", False, LIGHT_GREY)
self.board_cover.blit(over_label,
(BOX_SIZE*5-over_label.get_width()/2, BOX_SIZE*10-game_label.get_height()/2+over_label.get_height()))
# Displays the pause overlay (which should hide the board, next piece box, and hold piece box)
def gameover(self):
disp.blit(self.board_cover, (self.game.board.location[0], self.game.board.location[1]+BOX_SIZE*2-2))
disp.blit(self.hold_cover, (self.game.hold_box.location[0], self.game.hold_box.location[1]))
disp.blit(self.next_cover, (self.game.next_box.location[0], self.game.next_box.location[1]))
score = self.game.score
name = GAME_DATA["User Name"][0]
for i in range(1,11):
if int(GAME_DATA["Score "+str(i)][1]) < score:
temp_score = score
score = int(GAME_DATA["Score "+str(i)][1])
GAME_DATA["Score "+str(i)][1] = str(temp_score)
temp_name = name
name = GAME_DATA["Score "+str(i)][0]
GAME_DATA["Score "+str(i)][0] = temp_name
|
40588e030ac43c8883bd039a9569d38305b5eb46 | salotz/boar | /macrotests/txtmatch.py | 2,821 | 3.578125 | 4 | #!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
# Copyright 2012 Mats Ekberg
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from builtins import range
import sys
import os
import re
from optparse import OptionParser
def read_file(filename):
if filename == "-":
lines = sys.stdin.readlines()
else:
with open(filename, "r") as f:
lines = f.readlines()
return [s.rstrip("\n\r") for s in lines]
def match_line(pattern, text, magic_string):
if pattern.startswith(magic_string):
repattern = pattern[len(magic_string):]
return (re.match("^" + repattern + "$", text) != None)
else:
return (pattern == text)
def txtmatch(pattern_lines, text_lines, magic_string = None):
def print_error(pattern_lines, text_lines):
for line in pattern_lines:
print("expected:", line)
for line in text_lines:
print("actual :", line)
if len(pattern_lines) != len(text_lines):
print("*** Length mismatch")
print_error(pattern_lines, text_lines)
return False
for i in range(0, len(pattern_lines)):
text = text_lines[i]
pattern = pattern_lines[i]
if not match_line(pattern, text, magic_string):
print("Mismatch at line", i, "(magic = '%s')" % magic_string)
print_error(pattern_lines, text_lines)
return False
return True
def main():
args = sys.argv[1:]
if len(args) == 0:
args = ["--help"]
parser = OptionParser(usage="usage: txtmatch.py [-c <magic string>] <pattern file> <text file>")
parser.add_option("-c", "--magic", action="store", dest = "magic", type="string", default="!",
help="The initial string that indicates that this line is a regular expression. Default is '!'")
(options, args) = parser.parse_args(args)
if len(args) == 1:
args.append("-")
pattern_file, text_file = args
assert not (pattern_file == "-" and text_file == "-"), "Only one input can be stdin"
pattern_lines = read_file(pattern_file)
text_lines = read_file(text_file)
if not txtmatch(pattern_lines, text_lines, magic_string = options.magic):
print("*** Text mismatch", file=sys.stderr)
sys.exit(1)
sys.exit(0)
main()
|
cec09409b89fcd3dcc844731a5a000b380bfd5c8 | guildenstern70/PythonLearn | /src/pydiskutils/filesdeleter.py | 1,323 | 3.84375 | 4 | """
FilesDeleter.py
Usage: python FilesDeleter.py [initial_dir] [string]
Walks every subdirectory starting from
[initial_dir] and deletes every file in it that
contains in its file name 'string'
Example: python FilesDeleter.py . .class
Deletes every .class file in all subdirs starting from current.
"""
import os
import sys
def deletefiles(dst, extension):
for root, dirs, files in os.walk(dst):
for name in files:
# If name ends with 'extension' kill it
if name.rfind(extension)>0:
print('deleting', os.path.join(root, name))
try:
os.remove(os.path.join(root, name))
except WindowsError:
print("Access Denied: leaving it alone...")
if __name__ == "__main__":
print("FilesDeleter v.0.2")
if len(sys.argv)>1:
deletefiles(sys.argv[1],sys.argv[2])
else:
print("""
FilesDeleter.py
Usage: python FilesDeleter.py [initial_dir] [string]
Walks every subdirectory starting from
[initial_dir] and deletes every file in it that
contains in its file name 'string'
Example: python FilesDeleter.py . .class
Deletes every .class file in all subdirs starting from current.
""")
|
72ce8099acb5cc296426a23eb4f9bd5c9ca9b754 | zeylanica/programmers | /Level1_수박수박수박수박수박수.py | 260 | 3.671875 | 4 | #https://programmers.co.kr/learn/courses/30/lessons/12922?language=python3
def solution(n):
string = "수박"
if(n % 2 == 0):
answer = string * (n//2)
else:
answer = string * (n//2+1)
answer = answer[0:-1]
return answer |
253654fc55a5a161b731d27044a34c9dc5ef0378 | akhildraju/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,069 | 4.34375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
if len(arr) == 0:
return -1
if target < arr[start] or target > arr[end]:
return -1
slice = arr[start:end]
minIndex = 0
maxIndex = len(slice) - 1
midIndex = int(maxIndex / 2)
midValue = slice[midIndex]
if target > midValue:
return binary_search(arr, target, midIndex+1, end)
if target < midValue:
return binary_search(arr, target, start, midIndex)
if target is midValue:
return arr.index(target)
else:
return -1
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
# def agnostic_binary_search(arr, target):
# Your code here
|
22bf75f98127604df26dac5c4a3bf674b48bf3a1 | DavidHan6/Week2 | /Week2/ImageProcessing.py | 4,275 | 3.515625 | 4 | from PIL import Image
from PIL import ImageFilter
print(" What is your request? ")
print(" a is invert")
print(" b is darken")
print(" c is brigten")
print(" d is greyscale")
print(" e is posterize")
print(" f is solarize")
print(" g is denoise1")
print(" h is denoise2")
print(" i is denoise3")
print(" j is blur")
print(" k is sharpen")
print(" l is crop")
mudder = input(" ")
def apply_filter(image, filter):
pixels = [ filter(p) for p in image.getdata() ]
nim = Image.new("RGB",image.size)
nim.putdata(pixels)
return nim
def open_image(filename):
image = Image.open(filename)
if image == None:
print("Specified input file " + filename + " cannot be opened.")
return Image.new("RGB", (400, 400))
else:
print(str(image.size) + " = " + str(len(image.getdata())) + " total pixels.")
return image.convert("RGB")
def identity(pixel):
r,g,b = pixel
return (r,g,b)
def invert(pixel):
r,g,b = pixel
return (255-r, 255-g, 255-b)
def darken(pixel):
r,g,b = pixel
return (int((9/10) * r), int((9/10) * g), int((9/10)* b))
def brighten(pixel):
r,g,b = pixel
return (int((1000000/10) * r), int((1000000/10) * g), int((100000/10)* b))
def gray_scale(pixel):
r,g,b = pixel
gry = (r + g + b) / 3
return (int(gry), int(gry), int(gry))
def posterize(pixel):
r,g,b = pixel
if r >= 0 and r <= 63:
r = 50
if r >= 64 and r <= 127:
r = 100
if r >= 128 and r <= 191:
r = 150
if r >= 192 and r <= 255:
r = 200
if g >= 0 and g <= 63:
g = 50
if g >= 64 and g <= 127:
g = 100
if g >= 128 and g <= 191:
g = 150
if g >= 192 and g <= 255:
g = 200
if b >= 0 and b <= 63:
b = 50
if b >= 64 and b <= 127:
b = 100
if b >= 128 and b <= 191:
b = 150
if b >= 192 and b <= 255:
b = 200
return (r,g,b)
def solarize(pixel):
r,g,b = pixel
if r < 128:
r = 255 - r
if g < 128:
g = 255 - g
if b < 128:
b = 255 - b
return (r,g,b)
def denoise(pixel):
(r,g,b) = pixel
return(r*10, g*0, b*0)
'''def denoise2(pixel):
def denoise3(pixel):'''
def blur(pixel):
num = int(input("What is your blur power: "))
original_image = Image.open(input_file)
blurred_image = original_image.filter(ImageFilter.GaussianBlur(num))
blurred_image.show()
exit()
def sharpen(pixel):
original_image = Image.open(input_file)
sharpened_image = original_image.filter(ImageFilter.SHARPEN)
sharpened_image.show()
exit()
def crop(pixel):
coord1 = input("what is your first x")
coord2 = input("what is your first y")
coord3 = input("what is your second x")
coord4 = input("what is your second y")
allcords = (coord1, coord2, coord3, coord4)
original_image = Image.open(input_file)
blurred_image = original_image.crop(allcords)
blurred_image.show()
exit()
def load_and_go(fname,filterfunc):
print("Loading ...")
image = open_image(fname)
nimage = apply_filter(image,filterfunc)
#image.show()
#nimage.show()
'''
processedImage.jpg is the name of the file
the image is saved in. The first time you do
this you may have to refresh to see it.
'''
nimage.save("processedImage.jpg")
if __name__ == "__main__":
''' Change the name of the file and the function
to apply to the file in the line below
'''
input_file = input("What file would you like?")
if mudder == "a":
mudder = invert
if mudder == "b":
mudder = darken
if mudder == "c":
mudder = brighten
if mudder == "d":
mudder = gray_scale
if mudder == "e":
mudder = posterize
if mudder == "f":
mudder == solarize
if mudder == "g":
mudder = denoise
if mudder == "h":
mudder = denoise2
if mudder == "i":
mudder == denoise3
if mudder == "j":
mudder = blur
if mudder == "k":
mudder = sharpen
if mudder == "l":
mudder = crop
load_and_go(input_file, mudder)
|
0e513decfbab90b4bfca5e57e25bce946c6bae22 | ethan-haynes/coding-problems | /python/src/isunique.py | 705 | 4.25 | 4 | """
implement algorithm to determine if string has all unique
characters with no additional data structurs.
"""
def isunique(s):
last = ''
for i in sorted(s):
if i == last: return False
else: last = i
return True
print(isunique('abcde'))
print(isunique('abcdee'))
print(isunique('aaaa'))
"""
implement algorithm to determine if string has all unique
characters with additional data structurs.
"""
def is_unique_with_dict(s):
hash_table = {}
for i in s:
if i in hash_table: return False
else: hash_table[i] = i
return True
print(is_unique_with_dict('abcde'))
print(is_unique_with_dict('abcdee'))
print(is_unique_with_dict('aaaa'))
|
89473bafaa239848b24ca170eec55d3044a747cf | yiss13/CursoDeMatematicasParaDataScience-CalculoBasico_Platzi | /piecewise_function.py | 651 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def piecewiseFunction(x):
y = np.zeros(len(x))
for idx, x in enumerate(x):
if x >= 0:
y[idx] = 1.0
return y
def plot(x, y):
fig, ax = plt.subplots()
plt.xlim(-10, 10)
plt.ylim(-1, 2)
ax.plot(x, y)
ax.grid()
# ax.axhline(y = 0, color = "g")
# ax.axvline(x = 0, color = "g")
plt.xlabel("x-Independiente")
plt.ylabel("y-Dependiente")
plt.show()
def run():
x = np.linspace(-10.0, 10.0, num = 1000)
y = piecewiseFunction(x)
print("La función es: x^2")
plot(x, y)
if __name__ == "__main__":
run() |
d84f80020e3a44bf7a026e250f3bf1706eebb11a | Letian-Wang/CS61A-Structure-and-Interpretation-of-Computer-Programs | /2.2-4-iteration.py | 634 | 4.0625 | 4 | ''' iteration '''
def fib(n):
""" Compute fibonachi number """
pred, curr = 0, 1
k = 1
while k < n:
pred, curr = curr, pred + curr
k = k + 1
return curr
Function:
1. exactly one job
2. no repeatation
3. generally
python -i file.py
assert 3 > 2, "Math is broken"
''' Use a function name '''
def cube(x) :
return pow(x, 3)
def summation(n, term):
total, k = 0 ,1
while k < 10:
total, k = total + term(k), k + 1
return total
summation(2,cube)
'''fuction returns a function'''
def make_adder(n):
def adder(k):
return k + n
return adder
make_adder(1)(2)
|
8f719280695ac658200268046789953812fff787 | rmayherr/python | /list_recursion.py | 219 | 3.734375 | 4 | def list_sum(some_list):
if some_list == []:
return 0
elif len(some_list) == 1: # base case
return some_list[0]
else:
return some_list.pop() + list_sum(some_list) # recursive case
|
6d41d3acfdb15c9c299e7aad22c64dd100548ac5 | andresilmor/Python-Exercises | /Ficha N7/ex05___.py | 578 | 3.953125 | 4 | #Crie um ficheiro com o nome “texto.txt”. Escreva nesse ficheiro um qualquer conteúdo
#com um número de linhas entre 20-30 (Pode ser um copy de um texto qualquer). De
#seguida, implemente e teste uma função capaz de retornar o número de vezes que
#uma dada palavra, fornecida pelo utilizador, aparece no referido texto.
def REGwordcont():
registo=open('texto.txt','r')
cont=0
word=str(input('Indique a palavra pela qual procura: '))
for line in registo:
print('A palavra \"%s\" foi encontrada %d vezes.' %(word,cont))
REGwordcont() |
0787a5c88d909f876f1da3155a976075ba59c611 | robinsxdgi/Machine-Learning | /Spell-Checking-System-by-K-Nearest-Neighbor/costTest.py | 4,293 | 3.78125 | 4 | # EECS 349 Machine Learning, Spell Checking System, P3.1
# Ding Xiang
# October,1,2017
#########################
# python spellcheck.py '/Users/Rockwell/PycharmProjects/MLHW2/3esl.txt' 3esl.txt
# python spellcheck.py '/Users/Rockwell/PycharmProjects/MLHW2/wrongwords.txt' 3esl.txt
# python spellcheck.py '/Users/Rockwell/PycharmProjects/MLHW2/wikipediatypoclean.txt' 3esl.txt
# python spellcheck.py '/Users/Rockwell/PycharmProjects/MLHW2/wikicompact.txt' 3esl.txt
import numpy
import sys
import csv
import re
import time
def find_closest_word(string1, dictionary, deletion_cost, insertion_cost, substitution_cost): # dictionary is a list of strings consists of correct words
closestWord = dictionary[0]
closestDistance = levenshtein_distance(string1, dictionary[0], deletion_cost, insertion_cost, substitution_cost)
for i in range(len(dictionary)):
if closestDistance > levenshtein_distance(string1, dictionary[i], deletion_cost, insertion_cost, substitution_cost): # We first consider the case that three costs equal to 1, if the new word has closer distance to the word, then we replace the closest word by this new one.
closestWord = dictionary[i]
closestDistance = levenshtein_distance(string1, dictionary[i], deletion_cost, insertion_cost, substitution_cost)
return closestWord
# Levenshtein_distance function
def levenshtein_distance(string1, string2, deletion_cost, insertion_cost, substitution_cost):
M = numpy.zeros((len(string1) + 1, len(string2) + 1)) # M has (m+1) by (n+1) values
for i in range(len(string1) + 1):
M[i][0] = i * deletion_cost # Distance of any 1st string to an empty 2nd string
for j in range(len(string2) + 1):
M[0][j] = j * insertion_cost # Distance of any 2nd string to an empty 1st string
for j in range(1, len(string2) + 1):
for i in range(1, len(string1) + 1):
if string1[i-1] == string2[j-1]:
M[i][j] = M[i-1][j-1] # No operation cost, because they match
else:
M[i][j] = min(M[i-1][j]+deletion_cost, M[i][j-1]+insertion_cost, M[i-1][j-1]+substitution_cost)
return M[len(string1), len(string2)] # Return distance
# Define measure error function
def measure_error(typos, trueWords, dictionaryWords, deletion_cost, insertion_cost, substitution_cost):
errorNumber = 0
for index, word in enumerate(typos):
if find_closest_word(word, dictionaryWords, deletion_cost, insertion_cost, substitution_cost) != trueWords[index]: # If the true word doesn't match the closest word then add 1 to error number
errorNumber += 1
errorRate = float(errorNumber) / float(len(typos)) # Calculate the error rate
return errorRate
def main():
wordCheckedAndTrue = open('wikicompact.txt') # Input the file to be spell-checked
checkedAndTrueWords = csv.reader(wordCheckedAndTrue)
wordDictionary = open('3esl.txt') # Input the dictionary word list
dictionaryWords = csv.reader(wordDictionary)
# Create a list of words in dictionary
dictionaryWordList = []
for row in dictionaryWords:
dictionaryWordList.append(row[0])
# Create a wrong word list and a true word list
# Here we use part of the 'wikipediatypoclean.txt' as input file
# Note: Except for 'tab'(\t) and 'return'(\r), there's no other special characters in this file
wrongWordList = []
trueWordList = []
for row in checkedAndTrueWords:
eachCheckedAndTrueWord = re.split('\t',row[0])
wrongWordList.append(eachCheckedAndTrueWord[0])
trueWordList.append(eachCheckedAndTrueWord[1])
# Calculate the error rate of spell check
print 'Please wait, the error rate is calculating...'
for deletion_cost in [0, 1, 2, 4]:
for insertion_cost in [0, 1, 2, 4]:
for substitution_cost in [0, 1, 2, 4]:
# Start time
start = time.time()
errorRate = measure_error(wrongWordList, trueWordList, dictionaryWordList, deletion_cost, insertion_cost, substitution_cost)
# Count the total spelling check time
print 'In cost combination', deletion_cost, insertion_cost, substitution_cost, 'The total time is:', time.time() - start
if __name__ == '__main__':
main()
|
0a801023a32ce773a46fe7aef6b5c78c817a3939 | forkcodeaiyc/skulpt_parser | /run-tests/t185.py | 301 | 3.671875 | 4 | class Wee:
def __init__(self):
self.called = False
def __iter__(self):
return self
def __next__(self):
print("in next")
if not self.called:
self.called = True
return "dog"
raise StopIteration
for i in Wee():
print(i)
|
836c8621791565038fe44c60168be5ec0d14df0b | CMWelch/Python_Projects | /Python/General_Projects/Black Jack/Game.py | 3,752 | 3.9375 | 4 | import Classes
def wager(player):
'''
:param player: Player that is placing the bet
:return: The bet amount
'''
while True:
try:
b = int(input("Place a bet: "))
if b <= player.chips:
player.bet(b)
return b
else:
print(f"You don't have that many chips. Enter a valid number.\nPlayer chip total is: {player.chips}")
except:
print("Please enter a number")
def print_players(player, dealer, num=0):
'''
:param player: Player Object
:param dealer: Dealer object
:return: Nothing
'''
print(player.__str__())
print("Player's total is: ", player.total, "\n")
if num == 1:
print(dealer.__str__(), "\nUnknown")
else:
print(dealer.__str__())
print("Dealer's total is: ", dealer.total, "\n")
print("------------------------------------------\n")
def run():
#This variable initializes player chips and keeps track of chip totals when creating new player objects
player_chips = 100
while True:
print("Welcome to Black Jack: ")
#Initialize Deck Object
deck = Classes.Deck()
deck.shuffle()
#Initialize Player Objects
dealer = Classes.Player("Dealer")
player = Classes.Player("Player", player_chips)
#Ask user for bet amount
print("Player Chips: ", player.chips)
amount = wager(player)
#Deal Cards
print("Dealing Cards!\n")
player.hand(deck.deal())
dealer.hand(deck.deal())
player.hand(deck.deal())
facedown = deck.deal()
stay = False
#Hit or Stay for player
while player.total < 21 and not stay:
print_players(player, dealer, 1)
stay = False
action = input("Would you like to hit or stay? H for hit, S for stay: ").upper()
print(action)
while action != "H" and action != "S":
action = input("Please enter H or S: ").upper()
if action == "H":
player.hand(deck.deal())
elif action == "S":
stay = True
#Checks if player busted
if player.total > 21:
print("Player Bust, you lose")
else:
dealer.hand(facedown)
print_players(player, dealer)
if dealer.total > player.total:
print("Dealer wins")
#Dealer hits until 21, PUSH, or Bust
while dealer.total < 21:
dealer.hand(deck.deal())
print_players(player, dealer)
if dealer.total > 21:
print("Dealer Bust, YOU WIN!")
win = amount + amount
player.win(win)
elif dealer.total == 21 and player.total == 21:
print("Both 21, PUSH.")
elif 21 > dealer.total > player.total:
print("Dealer wins")
break
elif dealer.total == 21:
print("Dealer 21, dealer wins")
#Update global player chip variable
player_chips = player.chips
#Check game state
if player.chips == 0:
print("Out of chips. Game Over!")
break
else:
action = input("Would you like to keep playing? Y or N: ").upper()
print(action)
while action != "Y" and action != "N":
action = input("Please enter Y or N: ").upper()
if action == "N":
break
run()
|
51ce3e629ef73d65d4d948afa1373dd2fb1565e3 | maxwelldantas/learning-python3 | /aprendendo_a_sintaxe/dicionarios.py | 575 | 3.90625 | 4 | # Listas tipo chave:valor - dict(dicionário)
# Criando um dicionário vazio
livros = {}
# Forma de adicionar chave e valor no dicionário
livros['titulo'] = 'Aprenda a programar em python em 6hs'
livros['ano'] = 2018
# Criando um dicionário com chaves e valores
pessoa = {'nome': 'José da Silva', 'idade': 30, 'altura': 1.8, 'peso': 93}
'''
Os métodos do dicionário são parecidos com uma função,
possuem parâmetros e retornam valores, mas a sintaxe é diferente.
'''
pessoa.keys() # Retorna a lista com os índices
pessoa.values() # Retorna a lista com os valores
|
47556b713b2b0c01a9febd413ab6a26d5cc4fa3d | filipmalecki94/Python | /Task_lists/pazdziernik/pazdz32.py | 827 | 3.671875 | 4 | import math
wybor = int(input("1. Kartezjanskie -> Sferyczne\n2. Sferyczne -> Kartezjanskie\n-> "))
def sfer2kart(r,theta,phi):
#return (x,y,z)
return r*math.sin(theta)*math.cos(phi),r*math.sin(theta)*math.sin(phi),r*math.cos(theta)
def kart2sfer(x,y,z):
#return (r,theta,phi)
return math.sqrt(x**2+y**2+z**2),(math.atan(math.sqrt(x**2+y**2)/z))**-1,(math.atan(y/x))**-1
def input():
if wybor == 1:
X = 1.1#float(input("Podaj x= "))
Y = 1.2#float(input("Podaj y= "))
Z = 1.3#float(input("Podaj z= "))
return kart2sfer(X,Y,Z)
elif wybor == 2:
R = 1.1#float(input("Podaj r= "))
T = 1.2#float(input("Podaj theta= "))
P = 1.3#float(input("Podaj phi= "))
if R >= 0.0 and P >= 0.0 and P < 2*math.pi() and T >= 0.0 and T <= math.pi():
return sfer2kart(R,T,P)
else:
print("error")
print(input()) |
10774f733307c6b9f0bf9a5859f5f907cea688a7 | krajeshkumar11/Test | /cspp1-practice/m4/p2/bob_counter.py | 629 | 4.03125 | 4 | '''Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2'''
def main():
s = raw_input()
# the input string is in s
# remove pass and start your code here
char = "bob"
count = 0
print(s)
index = 0
while(index < len(s)):
print(s[0] + "RAJESH")
if(s[index] == char[0]):
if((pos+len(char) <= len(s)) and newst[pos:pos+len(char)] == char):
count = count + 1
index = pos
index += 1
print(count)
if __name__== "__main__":
main()
|
221a1b13d353885119ce598638e506d9764a6f8f | WilliamKulha/learning_python | /files_and_exceptions/addition.py | 649 | 4.15625 | 4 | def add_two_digits(num1, num2) :
"""Add two numbers"""
try :
num1 = int(num1)
num2 = int(num2)
except ValueError :
print("Hey, one of those isn't a number!")
else :
result = num1 + num2
print(f"The result is: {result}")
print("enter 'q' to quit at anytime.")
print("Please enter two numbers")
while True :
num1 = input("Enter the first number ")
if (num1 == 'q'):
break
else :
num2 = input("Enter the second number ")
if (num2 == 'q') :
break
else :
print(f"Number one is {num1}")
print(f"Number two is {num2}")
add_two_digits(num1, num2)
|
1dbe8f2ed6518b3eb02bde221300924d671eae20 | gautam4941/Machine_Learning_Codes | /Pre Processing/Topic 3 - MatPlotLib/3. Histogram.py | 4,416 | 3.828125 | 4 | #When we work with histogram then we need to have only one data which will be x-axis data
#and y will be the freq. occurance of each element in x-axis data
import matplotlib.pyplot as plt
import random
import pandas as pd
# Syntax for Random,
# random.randrange(start_value, End_value, incrementation)
# random.randrange( 20, 50, 3 ) -> 20, 23, 26, 29, ... , 48
roll_no = []
for i in range(1, 41): # 1, 2, .., 39, 40
roll_no.append( random.randrange(1, 11, 1) )
print(f"roll_no = {roll_no}\n")
"""
plt.hist( roll_no, label = 'Roll_no V/s Count - Graph 1')
plt.xlabel('roll_no')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph' )
plt.legend()
plt.show()
plt.hist( roll_no, rwidth=0.9, label = 'Roll_no V/s Count - Graph 2')
plt.xlabel('roll_no')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph' )
plt.legend()
plt.show()
#bin is about the no of categories belong to some to some range.
#Ex :- Out of 40. 15 data are belonging from 1 to 4 range
#Ex :- Out of 40. 12 data are belonging from 4 to 7 range
#Ex :- Out of 40. 13 data are belonging from 7 to 10 range
plt.hist( roll_no, rwidth=0.9, bins = 3, label = 'Roll_no V/s Count - Graph 2')
plt.xlabel('roll_no')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph' )
plt.legend()
plt.show()
"""
#If we want to give custom ranges
marks = []
for i in range( 1, 50 ):
marks.append( random.randrange(1, 101, 10) )
print( f"marks = { marks }\n" )
# 1 to 35 -> Fail
# 36 to 60 -> Just Pass
# 61 to 70 -> Pass
# 71 to 80 -> Good
# 81 to 90 -> Very Good
# 91 to 100 -> Excellent
"""
plt.hist( marks, rwidth=0.9, bins = [ 1, 36, 61, 71, 81, 91, 101 ], label = 'Roll_no V/s Count - Graph 2')
plt.xlabel('Marks')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph - Marks Distribution' )
plt.legend()
plt.show()
plt.hist( marks
, rwidth=0.9
, bins = [ 1, 36, 61, 71, 81, 91, 101 ]
, color = 'green'
, histtype = 'step'
, label = 'Roll_no V/s Count - Graph 2')
plt.xlabel('Marks')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph - Marks Distribution' )
plt.legend()
plt.show()
"""
"""
#plotting Multiple data at a time
class_A_marks = marks.copy()
class_B_marks = []
for i in range( 1, 50 ):
class_B_marks.append( random.randrange(1, 101, 10) )
print( f"class_A_marks :- \n{ class_A_marks }\n" )
print( f"class_B_marks :- \n{ class_B_marks }\n" )
plt.hist( [ class_A_marks, class_B_marks ]
, rwidth = 0.9
, bins = [ 1, 36, 61, 71, 81, 91, 101 ]
, color = [ 'red', 'green' ]
, label = ['Class A', 'Class B'] )
plt.xlabel('Class A V/s Class B')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph - Marks Distribution' )
plt.legend()
plt.show()
plt.hist( [ class_A_marks, class_B_marks ]
, rwidth = 0.9
, bins = [ 1, 36, 61, 71, 81, 91, 101 ]
, color = [ 'red', 'green' ]
, label = ['Class A', 'Class B']
, orientation = 'horizontal'
)
plt.xlabel('Class A V/s Class B')
plt.ylabel('Occurance Freq')
plt.title( 'Histogram Graph - Marks Distribution' )
plt.legend()
plt.show()
"""
hr_data = pd.read_csv( r"C:\Users\gauta\PycharmProjects\MachineLearning\Pre Processing\Topic 3 - MatPlotLib\Data\hrdata.csv" )
'''
import pandas as pd
print( f"hr_data.head() :- \n{ hr_data.head() }\n" )
print( f"hr_data.columns = { hr_data.columns }\n" )
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.2, label = 'alpha = 0.2' )
plt.legend()
plt.show()
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.3, label = 'alpha = 0.3' )
plt.legend()
plt.show()
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.4, label = 'alpha = 0.4' )
plt.legend()
plt.show()
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.5, label = 'alpha = 0.5' )
plt.legend()
plt.show()
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.6, label = 'alpha = 0.6' )
plt.legend()
plt.show()
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.7, label = 'alpha = 0.7' )
plt.legend()
plt.show()
plt.hist( hr_data['Income'], bins = 10, color = 'red', alpha = 0.8, label = 'alpha = 0.8' )
plt.legend()
plt.show()
#alpha range is from 0 to 1
''' |
6382d54128664403ed41f6dca96ecf8e34d621e8 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2447/60738/313279.py | 383 | 3.65625 | 4 | a=input()
b=input()
c=input()
try:
d=input()
except:
string=""
if a=="10 2":
print("7 26 ",end="")
elif a=="10 3":
if d=="3 9" and c=="2 7":
print("2 3 1 ",end="")
elif d=="3 6":
print("2 3 1 ",end="")
elif d=="6 6":
print("4 6 5 ",end="" )
elif a=="10 5":
print("4 4 4 2 2 ",end="")
elif a=="15 1":
print(2)
else:
print(a) |
61da7894fefae38ddb2e4d514779a14aa22a7b55 | nolderosw/estdados | /prova1/q1.py | 1,732 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 09:35:14 2017
@author: wesley150
"""
class Lista:
def __init__(self):
self.referencia = None
def inserirFim(self,valor):
novoNo = no(valor)
if(self.referencia == None):
self.referencia = novoNo
else:
tempNo = self.referencia
while(tempNo.proximo != None):
tempNo = tempNo.proximo
tempNo.proximo = novoNo
def imprimirLista(self):
tempReferencia = self.referencia
while (tempReferencia != None):
tempNo = tempReferencia
print (tempNo.valor)
tempReferencia = tempReferencia.proximo
def deslocaUltimoParaPrimeiro(self):
if(self.referencia == None):
print('Lista Vazia')
return
if(self.referencia.proximo == None):
print('Lista apenas com um elemento, troca não ocorre')
return
if(self.referencia.proximo.proximo == None):
inicio = self.referencia
self.referencia = inicio.proximo
self.referencia.proximo = inicio
inicio.proximo = None
return
tempRef = self.referencia
segundo = self.referencia.proximo
primeiro = self.referencia
while(tempRef.proximo.proximo != None):
tempRef = tempRef.proximo
self.referencia = tempRef.proximo
self.referencia.proximo = segundo
primeiro.proximo = None
tempRef.proximo = primeiro
class no:
def __init__(self,valor):
self.valor = valor
self.proximo = None |
5a5da05a2c56aa5b59174e38aa51741e33294514 | stepheneldridge/Advent-of-Code-2019 | /Day 03.py | 1,981 | 3.515625 | 4 | # Day 3
import math
INPUT = open('Day 03.txt', 'r')
data = []
directions = {
"D": [0, -1],
"U": [0, 1],
"L": [-1, 0],
"R": [1, 0]
}
for line in INPUT:
p = line.split(",")
current = [0, 0]
path = [(0, 0)]
for i in range(len(p)):
d = directions[p[i][0]]
dist = int(p[i][1:])
x = current[0] + d[0] * dist
y = current[1] + d[1] * dist
current = [x, y]
path.append((x, y))
data.append(path)
INPUT.close()
def find_intersect(a1, a2, b1, b2):
if a1 == b1 or a1 == b2:
return a1
if a2 == b1 or a2 == b2:
return a2
axis = a1[1] == a2[1]
if axis != (b1[1] == b2[1]):
if b1[not axis] <= max(a1[not axis], a2[not axis]) and b1[not axis] >= min(a1[not axis], a2[not axis]):
if a1[axis] <= max(b1[axis], b2[axis]) and a1[axis] >= min(b1[axis], b2[axis]):
return (b1[not axis], a1[axis])
else:
if a1[axis] == b1[axis]:
if a1[not axis] <= max(b1[not axis], b2[not axis]) and a1[not axis] >= min(b1[not axis], b2[not axis]):
return a1
if a2[not axis] <= max(b1[not axis], b2[not axis]) and a2[not axis] >= min(b1[not axis], b2[not axis]):
return a2
return None
def path(p):
dist = 0
for i in range(len(p) - 1):
dist += abs(p[i][0] - p[i + 1][0]) + abs(p[i][1] - p[i + 1][1])
return dist
best1 = 1 << 32
best2 = 1 << 32
for i in range(len(data[0]) - 1):
for j in range(len(data[1]) - 1):
inter = find_intersect(data[0][i], data[0][i + 1], data[1][j], data[1][j + 1])
if inter:
cost = path(data[0][:i + 1] + [inter]) + path(data[1][:j + 1] + [inter])
if cost == 0:
continue
best1 = min(abs(inter[0]) + abs(inter[1]), best1)
best2 = min(cost, best2)
print("part_1:", best1)
print("part_2:", int(best2))
|
3c03df5ae872c1b03b1d3061cb7adff1abbb5404 | nileshzend/PythonNZ | /8_calc.py | 1,468 | 4.28125 | 4 | # print("2+3") dont use ""
print(2+3) # ANS : 5
print(2+3*4) # ANS : 14
print(2+3*4-1) # ANS : 13
print(4/2) # ANS : 2.0 # floting print devision
print(2/4) # ANS : 0.5
print(4//2) # ANS : 2 # integre division
print(2//4) # ANS : 0
print(2**3) # ANS : 8 # double multiply means double power
print(2**0.5) # ANS : 1.4142135623730951
# Using round function
print(round(2**0.5,4)) # ANS : 1.4142 # 2 power 0.5 times & round or see 4 chracter
print(round(2**3.4,3)) # ANS : 10.556 # 2 power 3 times & round or see 3 chracter
# Precedence rule
# OPERATORS PRECEDENCE AND ASSOCIATIVITY RULE
# PARENTHESE (Bracket) HIGHEST
# EXPONENT RIGHT TO LEFT
# * , / , //, % LEFT TO RIGHT
# +, - LEFT TO RIGHT
# % means modulo
print(2**3/2*6-4*(3-4/2)) # ANS: 20.0 # in this case it will firstly calulate
# inside the bracket then it will go left to right
# 1st (3-4/2)
# 2nd 2**3 = 8
# 3rd 8/2 = 4
# 4th 4*6 = 24
# 5th 24-4 = 20
# 6th 20*1.0 = 20.0
print(3%2) # ANS : 1 # % modulo give remiander
print(3-1*2) # ANS : 1
print((3-1)*2) # ANS : 4
print((2+3)*2) # ANS : 10
print((2+3)/2) # ANS : 2.5
# 2+3 = 5/2
print((2+3)*5/2%6) # ANS : 0.5
# 5 * 5 / 2 % 6
# 25 /2 % 6
# 12.5 % 6
print(12.5 % 6) # ANS : 0.5
# exponenets (**) double star means exponents
print(2**3**2) #ANS : 512
# (2**9)
print(2**9) |
dfbfa7405a6b4f80ab61db86d87e027fc03d3d2e | cipher813/dsp | /python/hackerrank/35set.py | 179 | 3.71875 | 4 | def intersect_lists_2(list1, list2):
for e in list2:
list1.append(e)
print(list1)
s = set(list1)
print(s)
return s
intersect_lists_2([1,2,3],[3,4,5])
|
79208fd23e131d46ccc1034c01bb5900dd0437e5 | xblh2018/LeetcodePython | /longest_valid_parentheses.py | 1,585 | 4.09375 | 4 | #!/usr/bin/env python
'''
Leetcode: Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()",
which has length = 4.
'''
from __future__ import division
import random
### Use a stack to keep track of the positions of non-matching '('s.
### Also need to keep track of the position of the last ')'.
def longest_valid_parentheses(s):
max_len = 0
start = end = -1
last = -1 # the position of the last ')'
stack_lefts = [] # positions of non-matching '('s
for i, p in enumerate(list(s)):
if p == '(':
stack_lefts.append(i)
elif not stack_lefts:
# for ')': no matching left
last = i
else:
# for ')': find a matching pair
stack_lefts.pop()
cur_start = stack_lefts[-1]+1 if stack_lefts else last+1
cur_len = i-cur_start+1
if cur_len > max_len:
max_len = cur_len
start = cur_start
end = i
print s, ':', max_len, s[start:end+1]
return max_len
if __name__ == '__main__':
longest_valid_parentheses(")()()(()()())())))")
longest_valid_parentheses("(()")
longest_valid_parentheses("")
longest_valid_parentheses(")()(()(()(")
longest_valid_parentheses("(((()(((")
longest_valid_parentheses("))))))(((((")
|
ee8352a3ddef6e59b4b2e0b1102de0f1f0b8d3ef | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/MicahBraun/Lesson 10/Great_Circle/great_circle_v0.py | 956 | 3.703125 | 4 | # -------------------------------------------------------------------------------------
# PROJECT NAME: great_circle_v0.py
# NAME: Micah Braun
# DATE CREATED: 11/30/2018
# UPDATED:
# PURPOSE: Lesson 10 final
# DESCRIPTION: Function is left un-optimized for the C/static language (no type dec-
# -larations before assignment, standard Python library imports.
# This is the first run to get time benchmarks on further optimizations.
#
# ON RUN: Program took 8.130s to complete processes on 64-bit OS with 16 GB RAM
# -------------------------------------------------------------------------------------
import math
# -- Version 0 --
def great_circle(lon1, lat1, lon2, lat2):
radius = 3956 # miles
x = math.pi / 180.0
a = (90.0 - lat1) * (x)
b = (90.0 - lat2) * (x)
theta = (lon2 - lon1) * (x)
c = math.acos((math.cos(a) * math.cos(b)) + (math.sin(a) * math.sin(b) * math.cos(theta)))
return radius * c
|
ee6f4d725081191d530c477fc2033eece319db04 | nao37/Project_Euler | /0-9/problem4.py | 873 | 3.5625 | 4 | def main():
a, b, c = '9', '8', '9'
while True:
division_num = 999
num_array = [a, b, c, c, b, a]
integer = ''
for i in num_array:
integer += i
while division_num >= 100:
if int(integer) / division_num >= 1000:
break
elif int(integer) % division_num == 0:
print(int(integer), division_num, int(int(integer) / division_num))
return False
division_num -= 1
if not int(c) == 0:
c = str(int(c) - 1)
else:
c = '9'
if not int(b) == 0:
b = str(int(b) - 1)
else:
b = '9'
if not int(a) == 1:
a = str(int(a) - 1)
else:
return False
if __name__ == '__main__':
main()
|
5daaee1a7da1a224c9fcb5f18a168416833b4e20 | zhanghuihb/python | /python/test/Test4.py | 239 | 3.9375 | 4 | import time;
# 判断现在是这一年的第几天?
print(time.localtime(time.time()))
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
print("it is the ", time.strftime("%j", time.localtime(time.time())), " day") |
1ff936d07c46b4ca5f258df76bc0cb982d269c7c | carlosafdz/pensamiento_computacional_python | /primitivos/ciclos.py | 304 | 3.953125 | 4 |
a = int(input("primer numero: "))
b = int(input("numero maximo: "))
while a<=b:
print(a)
a=a+1
frutas = ['manzana', 'pera', 'nanranja', 'sandia']
objeto = {'nombre':'carlos', 'apellido':'alberto','edad':21}
print(objeto.keys())
for i in range(b):
print(i)
for i in frutas:
print(i)
|
5b21e204906659200bbee803d444f7f4dfcec2f6 | huangj485/binary-division | /main.py | 668 | 3.625 | 4 | import argparse
import division
# Initialize parser
parser = argparse.ArgumentParser(description = "Multiply A and B with Booth's Algorithm")
# Define args
parser.add_argument("-A", type=int, required=True, help = "dividend")
parser.add_argument("-B", type=int, required=True, help = "divisor")
parser.add_argument("--s", dest = "s", action='store_true', help = "flag to save instead of print to console")
# Read args
args = parser.parse_args()
A = args.A #multiplicand
B = args.B #multiplier
n = max([A.bit_length(), B.bit_length()])
value = division.div(A, B, n)
if args.s:
f = open("saved.txt", "w")
f.write(value)
f.close()
else:
print(value)
|
4eed52830cbd94e693731e549bfb9e7f69f06d0d | jdavisson87/Udemy_AutomatedTesting | /PythonRefresher/01_variables/code.py | 152 | 3.625 | 4 | # x = 15
# price = 9.99
# discount = 0.2
# result = price * (1 - discount)
# print(result)
a = 25
b = a
print(a)
print(b)
a = 16
print(a)
print(b) |
346c2d07ac34b1ef307df0fe1fe64f96572968db | bio-chris/Python | /LeetCode/LongestCommonPrefix.py | 400 | 3.5 | 4 | """"
Write a function to find the longest common prefix string amongst an array of strings.
"""
array = ["endanger", "irregulgar", "undo", "tricycle", "triangle"]
from difflib import SequenceMatcher
from difflib import get_close_matches
"""
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
print(similar("triangle","tricycle"))
"""
print(get_close_matches('enda', array))
|
22c95200d48d0fb6f8c9ae09d27c5894bbe58085 | olyzhang/leetcode_python | /array/888 Fair Candy Swap.py | 417 | 3.640625 | 4 | class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
diff = (sum(A) - sum(B)) / 2
A = set(A)
for b in set(B):
if int(diff + b) in A:
return (int(diff + b), b)
if __name__ == "__main__":
A = [1, 2, 5]
B = [2, 4]
print(Solution().fairCandySwap(A, B))
|
68eb31e2915b3aaeee8f89939d95c6e81c960703 | JakaMale/p1 | /Naloge/Dnrazredi.py | 977 | 3.65625 | 4 |
class Rezalnik:
def __init__(self):
self.s = []
self.dol = 2
def razrezi(self,s):
new = []
self.s=s
for i in range(0, len(s), self.dol):
new.append(s[i: i + self.dol])
return new
def nastavi_dolzino(self,dol):
self.dol=dol
#################################################################
import unittest
class TestRezalnik(unittest.TestCase):
def test_rezalnik(self):
rezalnik1 = Rezalnik()
rezalnik2 = Rezalnik()
s = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.assertEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9]],
rezalnik1.razrezi(s))
rezalnik1.nastavi_dolzino(4)
self.assertEqual([[1, 2, 3, 4], [5, 6, 7, 8], [9]],
rezalnik1.razrezi(s))
self.assertEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9]],
rezalnik2.razrezi(s))
if __name__ == "__main__":
unittest.main()
|
e0120bf76359dabbe71f7cae8d6b5594e5f744b0 | DhruvBhagadia/Tic-Tac-Toe-Python- | /Tic-Tak-Toe.py | 2,313 | 4.03125 | 4 | import random
def drawOnBoard(whatToDraw):
k = 0
index = -1
while(k<=6):
if(k%2 == 0):
i = 1
while(i<=3):
print(" --- ", end="")
i = i+1
print(" ", end="\n")
else:
j = 1
while(j<=4):
if(j <= 3):
index = index + 1
print("| " + whatToDraw[index] + " ", end=" ")
else:
print("|")
j = j+1
k = k+1
def checkIfSomeoneWon():
for i in winningPositions:
j = i[0]
k = i[1]
l = i[2]
if(board[j] == board[k] == board[l]) and (board[j] != ' '):
if board[j] == 'X':
return 'X'
else:
return 'O'
def checkIfItsADraw():
for i in board:
if i == ' ':
return False
return True
def findAppropriatePositionForX():
position = int(input("At which position do you want to insert 'X'?"))
if (position > 8):
print("Out of range of board")
elif (board[position] == ' '):
board[position] = 'X'
else:
print("O already exists try another position")
findAppropriatePositionForX()
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
winningPositions = [[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]]
gameActive = True
won = False
i = 0
j = 1
while (gameActive):
position = int(input("At which position do you want to insert 'X'?"))
if position > 8:
print("Out of range of board")
elif board[position] == ' ':
board[position] = 'X'
else:
print("X or O already exists try another position")
findAppropriatePositionForX()
if j != 5:
compPosition = random.randint(0, 8)
while board[compPosition] is not(' '):
compPosition = random.randint(0, 8)
board[compPosition] = 'O'
drawOnBoard(board)
X_or_Y = checkIfSomeoneWon()
if(X_or_Y == 'X' or X_or_Y == 'O'):
won = True
draw = checkIfItsADraw()
if(won or draw):
gameActive = False
if(won):
print(X_or_Y + " Won")
else:
print("Draw")
j = j+1
|
edd562ec214a7c70d94b4f0ce63852e049d69912 | minimum-hsu/tutorial-python | /lesson-06/02/without_exception.py | 401 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
def throw_exception():
names = ['Alice', 'Bob', 'Charlie']
for i in range(3):
print(names[i])
if __name__ == '__main__':
try:
throw_exception()
except IndexError as err:
print('[Error]', err, file = sys.stderr)
else:
print('no exception launched')
finally:
print('finally block is always executed')
|
59e7f2e078328eac5c25f2a05c74bc95c6a63ccf | siikamiika/scripts | /filename-fix.py | 1,010 | 3.609375 | 4 | #!/usr/bin/env python3
import os
import sys
REPLACEMENTS = {}
for c in 'öäåÖÄÅ':
REPLACEMENTS[c.encode('utf-8').decode('latin-1')] = c
def fix_path(path):
for r in REPLACEMENTS:
path = path.replace(r, REPLACEMENTS[r])
return path
def rename_path(path, subdir):
new_path = fix_path(path)
if new_path != path:
user_input = input('{} --> {} (Y/n): '.format(path, new_path))
if user_input == '' or user_input == 'Y':
src = os.path.join(subdir, path)
dst = os.path.join(subdir, new_path)
try:
os.rename(src, dst)
except FileExistsError:
if input('{} exists. Continue? (Y/n)'.format(dst)) in ['', 'Y']:
pass
else:
sys.exit()
def main():
for subdir, dirs, files in os.walk(sys.argv[1]):
print(subdir)
for path in files + dirs:
rename_path(path, subdir)
if __name__ == '__main__':
main()
|
cf51d34419ce3108ecdcb4e87b757d6a174d4173 | pranavj1001/CompetitiveProgramming | /Python/queensAttack2.py | 3,161 | 3.5625 | 4 | # The question for this solution can be found at https://www.hackerrank.com/challenges/queens-attack-2/problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the queensAttack function below.
def queensAttack(n, k, r_q, c_q, obstacles):
count = 0
if n == 1:
return count
# Co-ordinates of obstacle in up, right, down, left direction
uR = -1
uC = -1
rR = -1
rC = -1
dR = -1
dC = -1
lR = -1
lC = -1
# Co-ordinates of obstacle in up-right, right-down, down-left, left-up direction
urR = -1
urC = -1
rdR = -1
rdC = -1
dlR = -1
dlC = -1
luR = -1
luC = -1
for obj in obstacles:
oR = obj[0]
oC = obj[1]
# check in up direction
if (oR > r_q and oC == c_q) and (uR == -1 or oR < uR):
uR = oR
uC = oC
# check in up-right direction
elif ((oR - r_q == oC - c_q) and oR > r_q and oC > c_q) and (urR == -1 or oR < urR):
urR = oR
urC = oC
# check in right direction
elif (oC > c_q and oR == r_q) and (rC == -1 or oC < rC):
rR = oR
rC = oC
# check in right-down direction
elif ((r_q - oR == oC - c_q) and oR < r_q and oC > c_q) and (rdC == -1 or oC < rdC):
rdR = oR
rdC = oC
# check in down direction
elif (oR < r_q and oC == c_q) and (dR == -1 or oR > dR):
dR = oR
dC = oC
# check in down-left direction
elif ((r_q - oR == c_q - oC) and oR < r_q and oC < c_q) and (dlC == -1 or oC > dlC):
dlR = oR
dlC = oC
# check in left direction
elif (oC < c_q and oR == r_q) and (lC == -1 or oC > lC):
lR = oR
lC = oC
# check in left-up direction
elif ((oR - r_q == c_q - oC) and oR > r_q and oC < c_q) and (luR == -1 or oR < luR):
luR = oR
luC = oC
print(uR, uC)
print(urR, urC)
print(rR, rC)
print(rdR, rdC)
print(dR, dC)
print(dlR, dlC)
print(lR, lC)
print(luR, luC)
# calculate distance from obstacle in each direction
count += uR - r_q - 1 if (uR != -1) else n - r_q
count += urR - r_q - 1 if (urR != -1) else min(n - r_q, n - c_q)
count += rC - c_q - 1 if (rC != -1) else n - c_q
count += rdC - c_q - 1 if (rdR != -1) else min(r_q - 1, n - c_q)
count += r_q - dR - 1 if (dR != -1) else r_q - 1
count += r_q - dlR - 1 if (dlR != -1) else min(r_q - 1, c_q - 1)
count += c_q - lC - 1 if (lC != -1) else c_q - 1
count += c_q - luC - 1 if (luC != -1) else min(n - r_q, c_q -1)
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = int(nk[0])
k = int(nk[1])
r_qC_q = input().split()
r_q = int(r_qC_q[0])
c_q = int(r_qC_q[1])
obstacles = []
for _ in range(k):
obstacles.append(list(map(int, input().rstrip().split())))
result = queensAttack(n, k, r_q, c_q, obstacles)
fptr.write(str(result) + '\n')
fptr.close()
|
dc2be5e32f1185d6f40a8a583dfd5b29ecc89970 | Covax84/CodeWars | /alphabet_position.py | 299 | 3.921875 | 4 | def alphabet_position(text: str) -> str:
""" Input: text as string
Output: string with every letter replaced with its position in the alphabet
replaced characters separated by one space
"""
return ' '.join([str(ord(x.lower()) - 96) for x in text if x.isalpha()])
|
846a3fe03af5caddc7a2f8091e4fe1f8ea6fde3f | harrisonheld/SystemsOfEquations | /solvingSystemsOfEquations.py | 806 | 4 | 4 | from sympy import *
from sympy.plotting import (plot, plot_parametric)
import mpmath
# declare your variables
a,b = symbols('a,b')
# set up your equations. these are assumed to be equal to zero
# so if you wanted a = 2b, you would rearrange it into a - 2b (= 0)
# and if you wanted a + b = 12, you would rearrange for a + b - 12 (= 0)
# so you'd write
eq1 = a - 2*b
eq2 = a + b - 12
# use the solve command like this.
sol = solve([eq1, eq2], [a, b])
# the result will be a dictionary
print("The solution dictionary:", sol)
# access values by using the symbol as a key, like this
print("The value of 'a' is", sol[a])
print("The value of 'b' is", sol[b])
# also -
# to convert degrees to radians:
angle_deg = 180
angle_rad = mpmath.radians(angle_deg)
print(angle_deg, "deg =", angle_rad, "rad")
|
e8be94c1326674aab4ca141591f04e85fcc5588b | acttx/Python | /Comp Fund 2/Project1/sort_search_funcs.py | 5,064 | 4.3125 | 4 | def bubble_sort(obj_list):
sorted = False
n = len(obj_list) - 1
while not sorted and n > 0:
sorted = True
for i in range(n):
if obj_list[i].compare(obj_list[i + 1]) > 0:
sorted = False
obj_list[i], obj_list[i + 1] = obj_list[i + 1], obj_list[i]
n -= 1
def selection_sort(obj_list):
"""
Add code to do a seclection sort
"""
for i in range(len(obj_list)):
min_Index = i
for j in range(i + 1, len(obj_list)):
if obj_list[min_Index].compare(obj_list[j]) == 1:
min_Index = j
obj_list[i], obj_list[min_Index] = obj_list[min_Index], obj_list[i]
def insertion_sort(obj_list):
"""
Add code to do an insertion sort
"""
for i in range(1, len(obj_list)):
key = obj_list[i]
j = i - 1
while j >= 0 and key.compare(obj_list[j]) == -1:
obj_list[j + 1] = obj_list[j]
j -= 1
obj_list[j + 1] = key
def merge_sort(obj_list):
"""
Add code to do a merge sort
"""
if len(obj_list) <= 1:
return obj_list
mid = len(obj_list) // 2
left = obj_list[:mid]
right = obj_list[mid:]
left_list = merge_sort(left)
right_list = merge_sort(right)
return merge(left_list, right_list, obj_list)
def merge(left_list, right_list, temp_list):
"""
Add code to merge left_list and right_list into temp_List
"""
i, j, k = 0, 0, 0
while i < len(left_list) and j < len(right_list):
if left_list[i].compare(right_list[j]) == -1:
temp_list[k] = left_list[i]
i += 1
else:
temp_list[k] = right_list[j]
j += 1
k += 1
while i < len(left_list):
temp_list[k] = left_list[i]
k += 1
i += 1
while j < len(right_list):
temp_list[k] = right_list[j]
k += 1
j += 1
return temp_list
def quick_sort(obj_list):
"""
Add code to do a quick sort
"""
q_sort(obj_list, 0, len(obj_list) - 1)
def q_sort(obj_list, left, right):
if left >= right:
return
pivot = partition(obj_list, left, right)
q_sort(obj_list, left, pivot - 1)
q_sort(obj_list, pivot + 1, right)
def partition(obj_list, left, right):
"""
Add code to partition obj_list into left and right
"""
# This algorithm assumes the pivot is the first element
# Picking the middle works best when files are sorted already
# Swap middle with first
pivot = left + (right - left) // 2
obj_list[left], obj_list[pivot] = obj_list[pivot], obj_list[left]
pivot = left
left += 1
while right >= left:
while left <= right and obj_list[left].compare(obj_list[pivot]) != 1:
left += 1
while left <= right and obj_list[right].compare(obj_list[pivot]) == 1:
right -= 1
if left <= right:
obj_list[left], obj_list[right] = obj_list[right], obj_list[left]
left += 1
right -= 1
else:
break
obj_list[right], obj_list[pivot] = obj_list[pivot], obj_list[right]
return right
def heapify(obj_heap, size, root):
"""
Add code to heapify a list
"""
largest = root
left = (2 * root) + 1
right = (2 * root) + 2
if left < size and obj_heap[left].compare(obj_heap[root]) > 0:
largest = left
if right < size and obj_heap[right].compare(obj_heap[largest]) > 0:
largest = right
if largest != root:
obj_heap[root], obj_heap[largest] = obj_heap[largest], obj_heap[root]
heapify(obj_heap, size, largest)
def heap_sort(obj_list):
"""
Add code to do a heap_sort
"""
size = len(obj_list)
for i in range(size, -1, -1):
heapify(obj_list, size, i)
for i in range(size - 1, 0, -1):
obj_list[0], obj_list[i] = obj_list[i], obj_list[0]
heapify(obj_list, i, 0)
# search for an object
def binary_search(obj_list, obj):
left = 0
right = len(obj_list) - 1
while left <= right:
mid = (left + right) // 2
# Check if obj exists at mid
if obj_list[mid].compare(obj) == 0:
return mid
# If obj at mid is smaller, ignore left half
elif obj_list[mid].compare(obj) < 0:
left = mid + 1
# obj is greater, ignore right half
else:
right = mid - 1
return -1
# search for an object
def binary_search_rec(obj_list, obj, left=0, right=None):
if right is None:
right = len(obj_list) - 1
if left > right:
return -1
mid = (left + right) // 2
if obj_list[mid].compare(obj) == 0:
return mid
if obj_list[mid].compare(obj) > 0:
return binary_search_rec(obj_list, obj, left, mid - 1)
return binary_search_rec(obj_list, obj, mid + 1, right)
# search for an object
def linear_search(obj_list, obj):
for i in range(len(obj_list)):
if obj_list[i].compare(obj) == 0:
return i
return -1
|
f850aed56b0f8dacf57616dee5ea10716692dc02 | CraxY-Codes/cmp104 | /assignment.py | 1,593 | 3.953125 | 4 | import math
msg = input('what shape would you like to find the area?')
#msg triangle
if msg == 'triangle':
base = int(input('what is the base?'))
height = int(input('what is the height?'))
area = 1/2 * (base * height)
print('the area of {}= {}'.format(msg, area))
#msg rectangle
elif msg == 'rectangle':
length = int(input('what is the length?'))
breadth = int(input('what is the breadth?'))
area = length * breadth
print('the area of {}= {}'.format(msg, area))
#msg square
elif msg == 'square':
length = int(input('what is the length?'))
area = length ** 2
print('the area of {}= {}'.format(msg, area))
#msg circle
elif msg == 'circle':
radius = int(input('what is the radius?'))
pie = math.pi
area = pie * radius ** 2
area = round(area, 2)
print('the area of {}= {}'.format(msg, area))
#msg kite
elif msg == 'kite':
diagonal_1 = int(input('what is the diagonal_1?'))
diagonal_2 = int(input('what is the diagonal_2?'))
area = diagonal_1 * diagonal_2 / 2
print('the area of {}= {}'.format(msg, area))
#msg parallelogram
elif msg == 'parallelogram':
base = int(input('what is the base?'))
height = int(input('what is the height?'))
area = base * height
print('the area of {}= {}'.format(msg, area))
#msg rhombus
elif msg == 'rhombus':
diagonal_1 = int(input('what is the diagonal_1?'))
diagonal_2 = int(input('what is the diagonal_2?'))
area = diagonal_1 * diagonal_2 / 2
print('the area of {}= {}'.format(msg, area))
|
073b6c9873aee4c8a7c4464c881a5c3d9a89b25c | chansen736/sudokudo | /src/solver.py | 1,041 | 3.53125 | 4 | import sudoku
class Solver:
def __init__(self):
self._puzzle = sudoku.Sudoku()
def load(self, filename):
"""
Reads a puzzle from a file. The file is of the format:
<size of puzzle: N>
<row1 of puzzle>
...
<rowN of puzzle>
"""
f_in = open(filename, 'rb')
# The first line should be the size of the puzzle
puzzle_size = int(f_in.readline())
# The rest of the lines are the data
puzzle_data = f_in.readlines()
self._puzzle = sudoku.Sudoku(size=puzzle_size, rows=puzzle_data)
f_in.close()
def export(self, filename):
"""
Exports the current puzzle to a file.
"""
f_out = open(filename, 'wb')
f_out.write(self._puzzle.export())
f_out.close()
def getCurrentPuzzleString(self):
"""
Returns a string representing the solved portion of the puzzle.
"""
return str(self._puzzle)
#EOF
|
812b4baa153affb542468c72640cc7093de8853e | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_shubhamkrm_coin.py | 1,187 | 3.609375 | 4 | import math
def convert(num,base):
rev=1
output=0
while(num>0):
digit = num%base;
rev = rev*10+digit
num/=base
while (rev>0):
digit = rev%10
output = output*10+digit
rev/=10
output/=10
return output
def interpret(num,base):
i=0
output = 0
while (num>0):
output+=(num%10)*(base**i)
i+=1
num/=10
return output
def isPrime(num):
i=2
while i<=int(math.sqrt(num)):
if (num%i==0):
return 0
i+=1
return 1
def main():
bases = [2,3,4,5,6,7,8,9,10]
t = input()
for i in range(t):
print "Case #%d:"%(i+1)
n,j = raw_input().split()
n = int(n)
j = int(j)
count_primes=0
num = (1<<(n-1))+1
upper_limit = 1<<n
while num<upper_limit and count_primes<j:
proofs = [0]*9
count_factors=0
if (isPrime(num)==0):
num2=convert(num,2)
for base in bases:
new_num=interpret(num2, base)
k=2
while (k<=math.sqrt(new_num)):
if (new_num%k==0):
proofs[base-2]=k
break
k+=1
for proof in proofs:
if proof>0:
count_factors+=1
if count_factors==9:
count_primes+=1
print convert(num,2),
for proof in proofs:
print proof,
print
num+=2
main()
|
ffaa1a2f8115310f0d622da6553003d3bc45628e | cookie223/startingtocode | /strStr.py | 256 | 3.5625 | 4 | import sys
def strStr(haystack,needle):
try:
return haystack.index(needle)
except:
return -1
if __name__=="__main__":
if len(sys.argv)==3:
print strStr(sys.argv[1],sys.argv[2])
else :
print "Invalid input" |
162ed23153a6921e9e1f17934269efc5848f0fe6 | Alvin2580du/alvin_py | /business/stepTwo/blocking/comparision/comparison.py | 12,913 | 3.53125 | 4 | """ Module with functionalities for comparison of attribute values as well as
record pairs. The record pair comparison function will return a dictionary
of the compared pairs to be used for classification.
"""
Q = 2 # Value length of q-grams for Jaccard and Dice comparison function
# =============================================================================
# First the basic functions to compare attribute values
def exact_comp(val1, val2):
"""Compare the two given attribute values exactly, return 1 if they are the
same (but not both empty!) and 0 otherwise.
"""
# If at least one of the values is empty return 0
#
if (len(val1) == 0) or (len(val2) == 0):
return 0.0
elif (val1 != val2):
return 0.0
else: # The values are the same
return 1.0
# -----------------------------------------------------------------------------
def jaccard_comp(val1, val2):
"""Calculate the Jaccard similarity between the two given attribute values
by extracting sets of sub-strings (q-grams) of length q.
Returns a value between 0.0 and 1.0.
"""
# If at least one of the values is empty return 0
#
if (len(val1) == 0) or (len(val2) == 0):
return 0.0
# If both attribute values exactly match return 1
#
elif (val1 == val2):
return 1.0
# ********* Implement Jaccard similarity function here *********
jacc_sim = 0.0 # Replace with your code
# Add your code here
# ************ End of your Jaccard code *************************************
assert jacc_sim >= 0.0 and jacc_sim <= 1.0
return jacc_sim
# -----------------------------------------------------------------------------
def dice_comp(val1, val2):
"""Calculate the Dice coefficient similarity between the two given attribute
values by extracting sets of sub-strings (q-grams) of length q.
Returns a value between 0.0 and 1.0.
"""
# If at least one of the values is empty return 0
#
if (len(val1) == 0) or (len(val2) == 0):
return 0.0
# If both attribute values exactly match return 1
#
elif (val1 == val2):
return 1.0
# ********* Implement Dice similarity function here *********
dice_sim = 0.0 # Replace with your code
# Add your code here
# ************ End of your Dice code ****************************************
assert dice_sim >= 0.0 and dice_sim <= 1.0
return dice_sim
# -----------------------------------------------------------------------------
JARO_MARKER_CHAR = chr(1) # Special character used in the Jaro, Winkler comp.
def jaro_comp(val1, val2):
"""Calculate the similarity between the two given attribute values based on
the Jaro comparison function.
As described in 'An Application of the Fellegi-Sunter Model of Record
Linkage to the 1990 U.S. Decennial Census' by William E. Winkler and Yves
Thibaudeau.
Returns a value between 0.0 and 1.0.
"""
# If at least one of the values is empty return 0
#
if (val1 == '') or (val2 == ''):
return 0.0
# If both attribute values exactly match return 1
#
elif (val1 == val2):
return 1.0
len1 = len(val1) # Number of characters in val1
len2 = len(val2) # Number of characters in val2
halflen = int(max(len1, len2) / 2) - 1
assingment1 = '' # Characters assigned in val1
assingment2 = '' # Characters assigned in val2
workstr1 = val1 # Copy of original value1
workstr2 = val2 # Copy of original value1
common1 = 0 # Number of common characters
common2 = 0 # Number of common characters
for i in range(len1): # Analyse the first string
start = max(0, i - halflen)
end = min(i + halflen + 1, len2)
index = workstr2.find(val1[i], start, end)
if (index > -1): # Found common character, count and mark it as assigned
common1 += 1
assingment1 = assingment1 + val1[i]
workstr2 = workstr2[:index] + JARO_MARKER_CHAR + workstr2[index + 1:]
for i in range(len2): # Analyse the second string
start = max(0, i - halflen)
end = min(i + halflen + 1, len1)
index = workstr1.find(val2[i], start, end)
if (index > -1): # Found common character, count and mark it as assigned
common2 += 1
assingment2 = assingment2 + val2[i]
workstr1 = workstr1[:index] + JARO_MARKER_CHAR + workstr1[index + 1:]
if (common1 != common2):
common1 = float(common1 + common2) / 2.0
if (common1 == 0): # No common characters within half length of strings
return 0.0
transposition = 0 # Calculate number of transpositions
for i in range(len(assingment1)):
if (assingment1[i] != assingment2[i]):
transposition += 1
transposition = transposition / 2.0
common1 = float(common1)
jaro_sim = 1. / 3. * (common1 / float(len1) + common1 / float(len2) + \
(common1 - transposition) / common1)
assert (jaro_sim >= 0.0) and (jaro_sim <= 1.0), \
'Similarity weight outside 0-1: %f' % (jaro_sim)
return jaro_sim
# -----------------------------------------------------------------------------
def jaro_winkler_comp(val1, val2):
"""Calculate the similarity between the two given attribute values based on
the Jaro-Winkler modifications.
Applies the Winkler modification if the beginning of the two strings is
the same.
As described in 'An Application of the Fellegi-Sunter Model of Record
Linkage to the 1990 U.S. Decennial Census' by William E. Winkler and Yves
Thibaudeau.
If the beginning of the two strings (up to first four characters) are the
same, the similarity weight will be increased.
Returns a value between 0.0 and 1.0.
"""
# If at least one of the values is empty return 0
#
if (val1 == '') or (val2 == ''):
return 0.0
# If both attribute values exactly match return 1
#
elif (val1 == val2):
return 1.0
# First calculate the basic Jaro similarity
#
jaro_sim = jaro_comp(val1, val2)
if (jaro_sim == 0):
return 0.0 # No common characters
# ********* Implement Winkler similarity function here *********
jw_sim = jaro_sim # Replace with your code
# Add your code here
# ************ End of your Winkler code *************************************
assert (jw_sim >= jaro_sim), 'Winkler modification is negative'
assert (jw_sim >= 0.0) and (jw_sim <= 1.0), \
'Similarity weight outside 0-1: %f' % (jw_sim)
return jw_sim
# -----------------------------------------------------------------------------
def bag_dist_sim_comp(val1, val2):
"""Calculate the bag distance similarity between the two given attribute
values.
Returns a value between 0.0 and 1.0.
"""
# If at least one of the values is empty return 0
#
if (len(val1) == 0) or (len(val2) == 0):
return 0.0
# If both attribute values exactly match return 1
#
elif (val1 == val2):
return 1.0
# ********* Implement bag similarity function here *********
# Extra task only
bag_sim = 0.0 # Replace with your code
# Add your code here
# ************ End of your bag distance code ********************************
assert bag_sim >= 0.0 and bag_sim <= 1.0
return bag_sim
# -----------------------------------------------------------------------------
def edit_dist_sim_comp(val1, val2):
"""Calculate the edit distance similarity between the two given attribute
values.
Returns a value between 0.0 and 1.0.
"""
# If at least one of the values is empty return 0
#
if (len(val1) == 0) or (len(val2) == 0):
return 0.0
# If both attribute values exactly match return 1
#
elif (val1 == val2):
return 1.0
# ********* Implement edit distance similarity here *********
# Extra task only
edit_sim = 0.0 # Replace with your code
# Add your code here
# ************ End of your edit distance code *******************************
assert edit_sim >= 0.0 and edit_sim <= 1.0
return edit_sim
# -----------------------------------------------------------------------------
# Additional comparison functions for: (extra tasks for students to implement)
# - dates
# - ages
# - phone numbers
# - emails
# etc.
# =============================================================================
# Function to compare a block
def compareBlocks(blockA_dict, blockB_dict, recA_dict, recB_dict, attr_comp_list):
"""Build a similarity dictionary with pair of records from the two given
block dictionaries. Candidate pairs are generated by pairing each record
in a given block from data set A with all the records in the same block
from dataset B.
For each candidate pair a similarity vector is computed by comparing
attribute values with the specified comparison method.
Parameter Description:
blockA_dict : Dictionary of blocks from dataset A
blockB_dict : Dictionary of blocks from dataset B
recA_dict : Dictionary of records from dataset A
recB_dict : Dictionary of records from dataset B
attr_comp_list : List of comparison methods for comparing individual
attribute values. This needs to be a list of tuples
where each tuple contains: (comparison function,
attribute number in record A, attribute number in
record B).
This method returns a similarity vector with one similarity value per
compared record pair.
Example: sim_vec_dict = {(recA1,recB1) = [1.0,0.0,0.5, ...],
(recA1,recB5) = [0.9,0.4,1.0, ...],
...
}
"""
print('Compare %d blocks from dataset A with %d blocks from dataset B' % \
(len(blockA_dict), len(blockB_dict)))
sim_vec_dict = {} # A dictionary where keys are record pairs and values
# lists of similarity values
# Iterate through each block in block dictionary from dataset A
#
for (block_bkv, rec_idA_list) in blockA_dict.items():
# Check if the same blocking key occurs also for dataset B
#
if (block_bkv in blockB_dict):
# If so get the record identifier list from dataset B
#
rec_idB_list = blockB_dict[block_bkv]
# Compare each record in rec_id_listA with each record from rec_id_listB
#
for rec_idA in rec_idA_list:
recA = recA_dict[rec_idA] # Get the actual record A
for rec_idB in rec_idB_list:
recB = recB_dict[rec_idB] # Get the actual record B
# generate the similarity vector
#
sim_vec = compareRecord(recA, recB, attr_comp_list)
# Add the similarity vector of the compared pair to the similarity
# vector dictionary
#
sim_vec_dict[(rec_idA, rec_idB)] = sim_vec
print(' Compared %d record pairs' % (len(sim_vec_dict)))
print('')
return sim_vec_dict
# -----------------------------------------------------------------------------
def compareRecord(recA, recB, attr_comp_list):
"""Generate the similarity vector for the given record pair by comparing
attribute values according to the comparison function and attribute
numbers in the given attribute comparison list.
Parameter Description:
recA : List of first record values for comparison
recB : List of second record values for comparison
attr_comp_list : List of comparison methods for comparing attributes,
this needs to be a list of tuples where each tuple
contains: (comparison function, attribute number in
record A, attribute number in record B).
This method returns a similarity vector with one value for each compared
attribute.
"""
sim_vec = []
# Calculate a similarity for each attribute to be compared
#
for (comp_funct, attr_numA, attr_numB) in attr_comp_list:
if (attr_numA >= len(recA)): # Check there is a value for this attribute
valA = ''
else:
valA = recA[attr_numA]
if (attr_numB >= len(recB)):
valB = ''
else:
valB = recB[attr_numB]
valA = valA.lower()
valB = valB.lower()
sim = comp_funct(valA, valB)
sim_vec.append(sim)
return sim_vec
# -----------------------------------------------------------------------------
# End of program.
|
9b0e7daceb49492e0894e8ba34d58715c5127edb | kj808/2019Probably-Interesting-Data | /libraries/kmeans.py | 1,628 | 3.5625 | 4 | def assign(data,centroids):
import numpy as np
#print("----ASSIGN----")
#for all points
for point in data:
#create an array with all the distances from the point to the centroids
dist=np.sqrt(np.sum((point[1:]-centroids)**2, axis=1))
#Grab the centorid that's closest
cluster=np.argmin(dist)
#Record the closest centroid cluster
point[0]=cluster
def update(data,centroids):
import numpy as np
#print("----UPDATE----")
change=False
#Calculate the totals for each different clusters
for i in range(len(centroids)):
filtered=data[data[:,0]==i]
item=np.mean(filtered[:,1:], axis=0)
#If there was a change
if not np.array_equal(centroids[int(i)],item) and not np.isnan(item).any():
centroids[int(i)]=item
change=True
#Check if centroid already located in calculated spot
if change==True:
return True
else: #keep going!
return False
def kmean(data, k):
import random
import numpy as np
#Create column representing clusters to the data
clusterlist = np.zeros((1,(len(data))))
newdata=np.append(arr=clusterlist.T,values=data, axis=1)
#Create the list of centroids with random starting locations
columns=len(data[0])
cents=k
centroids = np.random.rand(cents,columns)
#Start assigning the points to clusters
#Keeps track of when to stop
changed=True
while changed==True:
assign(newdata, centroids)
changed=update(newdata, centroids)
return (newdata,centroids)
|
c08367d0545f2db93efbf5aee2c972133fbadec5 | VYatharth/Algorithms-N-DS | /DataStructures/Linked Lists/Implementation.py | 5,018 | 4.1875 | 4 | class Node():
def __init__(self, data): #When instantiating a Node, we will pass the data we want the node to hold
self.data = data #The data passed during instantiation will be stored in self.data
self.next = None #This self.next will act as a pointer to the next node in the list. When creating a new node, it always points to null(or None).
class LinkedList():
def __init__(self):
self.head = None
self.tail = self.head
self.length = 0
def append(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
self.tail = self.head
self.length = 1
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
self.length += 1
def print_list(self):
if self.head == None:
print("Empty")
else:
current_node = self.head
while current_node!= None:
print(current_node.data, end= ' ')
current_node = current_node.next
print()
def insert(self, position, data):
if position >= self.length:
if position>self.length:
print("This position is not available. Inserting at the end of the list")
new_node = Node(data)
self.tail.next = new_node
self.tail = new_node
self.length += 1
return
if position == 0:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
self.length += 1
return
if position < self.length:
new_node = Node(data)
current_node = self.head
for i in range(position-1):
current_node = current_node.next
new_node.next = current_node.next
current_node.next = new_node
self.length += 1
return
#Time complexity is pretty clearly O(n)
def delete_by_value(self, data):
if self.head == None:
print("Linked List is empty. Nothing to delete.")
return
current_node = self.head
if current_node.data == data:
self.head = self.head.next
if self.head == None or self.head.next==None:
self.tail = self.head
self.length -= 1
return
while current_node!= None and current_node.next.data != data:
#if current_node.data == data:
# previous_node.next = current_node.next
# return
current_node = current_node.next
if current_node!=None:
current_node.next = current_node.next.next
if current_node.next == None:
self.tail = current_node
self.length -= 1
return
else:
print("Given value not found.")
return
def delete_by_position(self, position):
if self.head == None:
print("Linked List is empty. Nothing to delete.")
return
if position == 0:
self.head = self.head.next
if self.head == None or self.head.next == None:
self.tail = self.head
self.length -= 1
return
if position>=self.length:
position = self.length-1
current_node = self.head
for i in range(position - 1):
current_node = current_node.next
current_node.next = current_node.next.next
self.length -= 1
if current_node.next == None:
self.tail = current_node
return
#We will import this file while reversing a linked list. So we must make sure that it runs only
#when it is the main file being run and not also when it is being imported in some other file.
if __name__ == '__main__':
my_linked_list = LinkedList()
my_linked_list.print_list()
#Empty
my_linked_list.append(5)
my_linked_list.append(2)
my_linked_list.append(9)
my_linked_list.print_list()
#5 2 9
my_linked_list.prepend(4)
my_linked_list.print_list()
#4 5 2 9
my_linked_list.insert(2,7)
my_linked_list.print_list()
#4 5 7 2 9
my_linked_list.insert(0,0)
my_linked_list.insert(6,0)
my_linked_list.insert(9,3)
my_linked_list.print_list()
#This position is not available. Inserting at the end of the list
#0 4 5 7 2 9 0 3
my_linked_list.delete_by_value(3)
my_linked_list.print_list()
#0 4 5 7 2 9 0
my_linked_list.delete_by_value(0)
my_linked_list.print_list()
#4 5 7 2 9 0
my_linked_list.delete_by_position(3)
my_linked_list.print_list()
#4 5 7 9 0
my_linked_list.delete_by_position(0)
my_linked_list.print_list()
#5 7 9 0
my_linked_list.delete_by_position(8)
my_linked_list.print_list()
#5 7 9
print(my_linked_list.length)
#3 |
28175fd121a7e73d76cd12eaa473afbb3013cc96 | RadkaValkova/SoftUni-Web-Developer | /Programming Advanced Python/Tuples and sets exercise/04 count_symbols.py | 381 | 3.6875 | 4 | def get_unique_symbols(text):
symbols_dict = {}
for symbol in text:
if symbol not in symbols_dict:
symbols_dict[symbol] = 0
symbols_dict[symbol] += 1
return symbols_dict
def print_results(result):
for key,value in sorted(result.items()):
print(f'{key}: {value} time/s')
text = input()
print_results(get_unique_symbols(text)) |
3e9355354b7c3e3c5cc209bf74b659bb8e2dc4f0 | honghen15/checkio_ | /number-radix.py | 1,134 | 3.75 | 4 | def checkio(str_number, radix):
dict_base = { '0':0, '1':1,'2':2,'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9,
'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, 'G':16, 'H':17,
'I':18, 'J':19, 'K':20, 'L':21, 'M':22, 'N':23, 'O':24, 'P':25,
'Q':26, 'R':27, 'S':28, 'T':29, 'U':30, 'V':31, 'W':32, 'X':33,
'Y':34, 'Z':35}
num = 0
if(str_number.isdigit()):
if(int(str_number) == 0):
return 0
for n in range(len(str_number)):
if ( dict_base[str_number[len(str_number)-n-1]] >= radix ):
return -1
num+= dict_base[str_number[len(str_number)-n-1]]*(radix**n)
return num
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print( checkio("AF", 16) )#== 175, "Hex"
print( checkio("101", 2) )#== 5, "Bin"
print( checkio("101", 5) )#== 26, "5 base"
print( checkio("Z", 36) )#== 35, "Z base"
print( checkio("AB", 10) )#== -1, "B > A = 10"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
eeae916ba4ba7c625dd42484a6205362083b1034 | uit-no/python-course-2016 | /notebooks/data_in_python/pet_1.py | 620 | 3.640625 | 4 | class Pet:
def __init__(self, name):
self.name = name
self.hunger = 0
self.age = 0
self.pets_met = set()
def advance_time(self):
self.age += 1
self.hunger += 1
def feed(self):
self.hunger = 0
def meet(self, other_pet):
print("{} meets {}".format(self.name, other_pet.name))
self.pets_met.add(other_pet)
other_pet.pets_met.add(self)
def print_stats(self):
print("{o.name}, age {o.age}, hunger {o.hunger}, met {n} others".
format(o = self, n = len(self.pets_met)))
|
92d4564d0af80fa4637de470af47832927458f6f | atomr3/389Rfall18 | /week/4/writeup/stub.py | 2,681 | 3.5 | 4 | """
Use the same techniques such as (but not limited to):
1) Sockets
2) File I/O
3) raw_input()
from the OSINT HW to complete this assignment. Good luck!
"""
import socket
import re
host = "cornerstoneairlines.co" # IP address here
port = 45 # Port here
# I like color in my shell
class textcolor:
PINK = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLINK = '\033[5m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def menu():
print (textcolor.PINK + " shell" + textcolor.ENDC + " Drop into an interactive shell and allow users to gracefully exit")
print (textcolor.RED + " pull" + textcolor.ENDC + " <remote-path> <local-path> Download files")
print (textcolor.YELLOW + " help" + textcolor.ENDC + " Shows this help menu")
print (textcolor.OKBLUE + " quit" + textcolor.ENDC + " Quit the shell")
pass
def execute_cmd(cmd):
c = "; " + cmd + "\n"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
# garbage message
data = s.recv(1024)
s.send(str.encode(c))
data = s.recv(1024)
# getting some weird stuff if i dont decode
data = data.decode('ascii')
# not adding the strip made me turn this in late...
return data.strip()
def shell():
wd = "/"
c = ">"
while True:
cmd = input(textcolor.PINK + wd.strip()+c + textcolor.ENDC).strip()
if cmd == "exit":
break
elif re.match('^cd$',cmd):
wd = "/"
# valid cd into dir
elif re.match('^cd.*$',cmd):
d = cmd.split()
if d[1][0] != "/" and wd !="/":
d = wd + "/" + d[1]
# elif d[1][0] == "/" and wd =="/":
# d =
else:
d = wd + d[1]
s = "cd " + d + " ; pwd"
wd = execute_cmd(s)
else:
co = "cd " + wd + " ; " + cmd
r = execute_cmd(co)
if r == "Good! Here's your flag: CMSC389R-{p1ng_as_a_$erv1c3}":
a = textcolor.BLINK + "Nice Job!" + textcolor.ENDC
print(a)
print(r)
if __name__ == '__main__':
c = ">"
while True:
cmd = input(c)
if cmd == "quit":
break
elif cmd == "help":
menu()
elif cmd == "shell":
shell()
elif re.match('^pull +(\S+) +(\S+)',cmd):
t = cmd.split()
r = t[1]
l = t[2]
with open(l,'w') as w:
w.write(execute_cmd("cat " + r))
else:
menu()
|
3b92ce9e509bcff38f87806b4abc41dbe72b3ee6 | JagadeeshmohanD/PythonTutorials | /loopsDemo/forloopDemo4.py | 180 | 3.53125 | 4 | l1=["Rahul","Rajeev","Raji"]
l2=["python","java","js"]
l3=["India","Australia","USA"]
for a in l1:
for b in l2:
for c in l3:
print(a + " " + b + " " + c)
|
f7f2ff3f23557a7a1844ec21ea84fadd0fdfa104 | agungap22/Latihan | /6_task.py | 993 | 3.78125 | 4 |
# def factorial(n) :
# if n == 0:
# return 1
# elif n == 1:
# return 1
# else:
# i = n
# hasil = 1
# while i != 1:
# hasil *= i
# i -= 1
# return hasil
# n = int(input("Nilai "))
# print (factorial(n))
# def fizz(n):
# for i in range (1,n+1):
# if i % 3 == 0 and i % 5 == 0:
# print ("Fizzbuzz")
# elif i % 5==0:
# print ("Buzz")
# elif i % 3 == 0:
# print ("Fizz")
# else :
# print(i)
# n = int(input ("Masukkan angka : "))
# fizz(n)
# for
# x = input("Masukkan Kata :")
# if x[0] == x[4] and x[1] == x[3]:
# print (f"Is world {x} a palindrome = True")
# else :
# print (f"Is world {x} a palindrome = false")
# x = input ("Masukkan Segitiga = ")
# def segitiga(n):
# hasil = ""
# for i in range (n):
# hasil += " * "
# print(hasil)
# segitiga(10) |
6ac43b6bc7ff61430f95d47efac1ba44abd38688 | ramohse/dsp | /math/matrix_algebra.py | 2,133 | 3.546875 | 4 | # Matrix Algebra
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 5 18:26:06 2016
@author: ramohse
Defines matrices and vectors and uses Python/numpy to check the hand-written
work done on linear algebra
"""
import numpy as np
A = np.matrix([[1, 2, 3], [2, 7, 4]])
B = np.matrix([[1, -1], [0, 1]])
C = np.matrix([[5, -1], [9, 1], [6, 0]])
D = np.matrix([[3, -2, -1], [1, 2, 3]])
u = np.array([6, 2, -3, 5])
v = np.array([3, 5, -1, 4])
w = np.array([[1], [8], [0], [5]])
### 06.01 Matrix Dimensions
## 06.01.01
#print('1.1) ', A.shape)
# (2, 3)
## 06.01.02
#print('1.2) ', B.shape)
# (2, 2)
## 06.01.03
#print('1.3) ', C.shape)
# (3, 2)
## 06.01.04
#print('1.4) ', D.shape)
# (2, 3)
## 06.01.05
#print('1.5) ', u.shape)
# (4,)
## 06.01.06
#print('1.6) ', w.shape)
# (4, 1)
#print('\n')
### 06.02 Vector Operations
## 06.02.01
#ans0201 = u + v
#rint('2.1) ', ans0201)
# [9, 7, -4, 9]
## 06.02.02
#ans0202 = u - v
#print('2.2) ', ans0202)
# [3, -3, -2, 1]
## 06.02.03
#ans0203 = 6 * u
#print('2.3) ', ans0203)
# [36, 12, -18, 30]
## 06.02.04
#ans0204 = np.dot(u, v)
#print('2.4) ', ans0204)
# 51
## 06.02.05
#ans0205 = np.linalg.norm(u)
#print('2.5) ', ans0205)
# 8.602325
#print('\n')
### 06.03 Matrix Operations
## 06.03.01
#ans0301 = A + C
#print('3.1) ', ans0301)
# not defined
## 06.03.02
#ans0302 = A + C.T
#print('3.2) ', ans0302)
# [[6, 11, 9]
# [1, 8, 4]]
## 06.03.03
#ans0303 = C.T + (3 * D)
#print('3.3) ', ans0303)
# [[14, 3, 3]
# [2, 7, 9]]
## 06.03.04
#ans0304 = np.dot(B, A)
#print('3.4) ', ans0304)
# [[-1, -5, -1]
# [2, 7, 4]]
## 06.03.05
#ans0305 = np.dot(B, A.T)
#print('3.5) ', ans0305)
# not defined
#print('\n')
### 06.03 Optional
## 06.03.06
#ans0306 = np.dot(B, C)
#print('3.6) ', ans0306)
# not defined
## 06.03.07
#ans0307 = np.dot(C, B)
#print('3.7) ', ans0307)
# [[5, -6]
# [9, -8]
# [6, -6]]
## 06.03.08
#ans0308 = B^(4)
#print('3.8) ', ans0308)
# [[5, -5]
# [4, 5]]
## 06.03.09
#ans0309 = np.dot(A, A.T)
#print('3.9) ', ans0309)
# [[14, 28]
# [28, 69]]
## 06.03.10
#ans0310 = np.dot(D.T, D)
#print('3.10) ', ans0310)
# [[10, -4, 0]
# [-4, 8, 8]
# [0, 8, 10]]
|
3a2fe3959d5a522b7da2992cf41b81206482b54f | PhilipeRLeal/Classes_and_Objects_in_Python | /Classes/Classes_e_funcoes_1.py | 3,002 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 20 11:29:24 2018
@author: Philipe Leal
"""
class Point: # definicao de classe
def __init__(self, x=0, y=0): # funcao de iinicializacao da classe criada
self.x = x # self.x e self.y são atributos do objeto Point
self.y = y # self.x e self.y são atributos do objeto Point
def __eq__(self, other): # verifica se um dado atributo do Point eh igual ao seguinte retornando True
return self.x==other.x and self.y == other.y
def distancia_da_origem(self): # propriedade da Classe Point
import math
# math.hypot fornece a distância euclidiana do ponto em relacao ao ponto (0,0)
return math.hypot(self.x, self.y) # retorna a distância da origem
def __repr__(self): # funcao que permite ao usuario checar qual eh o tipo de objeto
""" Esta função é utilizada para retornar uma string com o Tipo da classe definida e sua instância.
Permite que ao usuário transformar esta string retornada (ou qualquer outra de mesmo formato) em instância:
"""
return ("Point ({0.x!r}, {0.y!r})".format(self))
class Circle(Point):
def __init__(self, radius, x=0, y=0):
super().__init__(x,y)
self.radius = radius
def edge_distance_from_origin(self):
return (self.distancia_da_origem() - self.radius)
def area(self):
import math
return (math.pi * (self.radius**2))
def circumference(self):
import math
return 2 * math.pi * self.radius
def __eq__(self, other):
return (self.radius== other.radius and super().__eq__(other))
def __str__(self):
return (repr(self))
def __repr__(self): # funcao que permite ao usuario checar qual eh o tipo de objeto, além de retornar uma string com o tipo do objeto
""" Esta função é utilizada para retornar uma string com o Tipo da classe definida e sua instância.
Permite que ao usuário transformar esta string retornada (ou qualquer outra de mesmo formato) em instância:
Ex:
P = Shape.Point(3,9)
repr(p) # retornará 'Point(3,9)
q = eval(p.__module__ + "." + repr(p))
repr(q) # Retorna 'Point(3,9)
"""
return ("Circle ({0.radius!r}, {0.x!r}, {0.y!r})".format(self))
def Distancia_entre_pontos(P1, P2):
import math
Distancia = math.sqrt( ((P1.x - P2.x)**2) + ((P1.y - P2.y)**2) )
return Distancia
A = Point(2.0,2.0)
B = Point(3.0,2.0)
C = Circle(5.0, 2.0, 2.0)
print(A.distancia_da_origem())
print(Distancia_entre_pontos( A, B))
print(C.area())
print(C.distancia_da_origem()) # notar como a funcao da classe objeto também é válida para sua subclasse Circle
|
efe9b7a7dda2a3d2a983f008e67171bf547a14c3 | Bertram-Liu/Note | /NOTE/02_PythonBase/day11/exercise/mysum_recursion.py | 378 | 3.796875 | 4 | # 练习:
# 用递归的方式求和
# def mysum_recursion(n):
# ...
# print(mysum_recursion(100)) # 5050
# def mysum_recursion(n):
# if n == 1:
# return 1
# r = n + mysum_recursion(n - 1)
# return r
def mysum_recursion(n):
if n == 1:
return 1
return n + mysum_recursion(n - 1)
print(mysum_recursion(100)) # 5050 |
be5d0976fa48799d3cba7aa30a49f347d70f4611 | tensorbro400/learning-python | /fizzbuzz.py | 355 | 3.765625 | 4 | #This code is best for future use of this program
for i in range(1, 101):
fizz = 3
buzz = 5
fizzbuzz = fizz * buzz
if i % fizzbuzz == 0:
print("FizzBuzz")
continue
elif i % fizz == 0:
print("Fizz")
continue
elif i % buzz == 0:
print("Buzz")
continue
else:
print(i)
|
94aed0ec5e9abcc1b6882fedf44c3858d4940bbb | thminh179/TruongHoangMinh-Fundamental-C4E18 | /Session 3/add_and_update_list.py | 509 | 4.0625 | 4 | hobby=["car", "tech", "grill"]
# #add
# add = input("Name one thing you want to add. ")
# hobby.append(add)
# print("here are your favorite things so far:", end='')
# print((*hobby), sep=', ')
# #update
for index, item in enumerate(hobby):
print("{0}. {1}".format(index+1, item))
position = int (input("Which position do you want to update?"))
new = input("What is your new favorite thing?")
hobby[position-1] = new
for index, item in enumerate(hobby):
print("{0}. {1}".format(index+1, item))
|
439b7c67ff065f42d883402fe60b1221fcba56be | shweta2425/ML-Python | /Week2/List12.py | 250 | 3.8125 | 4 | # Write a Python program to get the difference between the two lists
from Week2.Utilities import utility
class List12:
lst1 = [1, 2, 3, 4, 5, 6]
lst2 = [32, 2, 4, 65, 2, 1]
obj = utility.User.Diff(lst1, lst2)
print(obj)
|
c4732d63492c06e01dbf9868ec7caaa1720a6817 | mikeodf/Python_Graphics_Animation | /ch2_prog7_ball_collisions_class_1.py | 4,682 | 4.0625 | 4 | """
Program name: ball_collisions_class_1.py
Objective: Two balls moving under the influence of gravity.
Keywords: canvas, class, ball, bounce, gravity, time, movement
============================================================================79
Explanation: A simplified equation of motion that inclused the influence of gravity in incorporated. Note that because of the conventions used for screen(canvas) reference positions the acceleration due to gravity
has a plus sign.
There is a numerical loss of 'energy' each time the ball hits a barrier
Tested on: Python 2.6, Python 2.7.3, Python 3.2
Author: Mike Ohlson de Fine
"""
#from Tkinter import *
from tkinter import * # For Python version 3.2 and higher.
root = Tk()
root.title("Ball Collisions using Classes")
cw = 350 # canvas width
ch = 300 # canvas height
GRAVITY = 1.5
canvas_1 = Canvas(root, width=cw, height=ch, background="black")
canvas_1.grid(row=0, column=0)
cycle_period = 80 # Time between new positions of the ball (milliseconds).
time_scaling = 0.2 # This governs the size of the differential steps
# when calculating changes in position.
class BallBounce:
""" The behaviors and properties of bouncing balls.
"""
def __init__(self, posn_x, posn_y, velocity_x, velocity_y, kula):
""" Initialize values at instantiation.
"""
self.posn_x = posn_x # x position of box containing the ball (bottom).
self.posn_y = posn_y # x position of box containing the ball (left edge).
self.velocity_x = velocity_x # amount of x-movement each cycle of the 'for' loop.
self.velocity_y = 100.0 # amount of y-movement each cycle of the 'for' loop.
self.color = kula # color of the ball
self.ball_width = 20.0 # size of ball - width (x-dimension).
self.ball_height = 20.0 # size of ball - height (y-dimension).
self.coef_restitution = 0.90
def detectWallCollision(self):
""" Collision detection with the walls of the container
"""
if self.posn_x > cw - self.ball_width: # Collision with right-hand container wall.
self.velocity_x = -self.velocity_x * self.coef_restitution # reverse direction.
self.posn_x = cw - self.ball_width * 1.1 # anti-stick to the wall
if self.posn_x < 1: # Collision with left-hand wall.
self.velocity_x = -self.velocity_x * self.coef_restitution
self.posn_x = 2 # anti-stick to the wall
if self.posn_y < self.ball_height: # Collision with ceiling.
self.velocity_y = -self.velocity_y * self.coef_restitution
self.posn_y = self.ball_height * 1.1 # ceiling collision anti-stick
if self.posn_y > ch - self.ball_height * 1.1 : # Floor collision.
self.velocity_y = - self.velocity_y * self.coef_restitution
self.posn_y = ch - self.ball_height * 1.1 # anti-stick. Prevents out-of-bounds ball loss (stickiness)
def diffEquation(self):
""" An approximate set of differential equations of motion for the balls
"""
self.posn_x += self.velocity_x * time_scaling
self.velocity_y = self.velocity_y + GRAVITY # a crude equation incorporating gravity.
self.posn_y += self.velocity_y * time_scaling
canvas_1.create_oval( self.posn_x, self.posn_y, self.posn_x + self.ball_width,
self.posn_y + self.ball_height, fill= self.color)
self.detectWallCollision() # Has the ball collided with any container wall?
# Creating instances of three balls.
ball_1 = BallBounce(25.0, 25.0, 30.0, -25.0, "dark orange" )
ball_2 = BallBounce(475.0, 25.0, -30.0, -25.0, "red")
ball_3 = BallBounce(475.0, 475.0, -50.0, -15.0, "yellow")
for i in range(1,2000): # End the program after 1000 position shifts.
ball_1.diffEquation()
ball_2.diffEquation()
ball_3.diffEquation()
canvas_1.update() # This refreshes the drawing on the canvas.
canvas_1.after(cycle_period) # This makes execution pause for 200 milliseconds.
canvas_1.delete(ALL) # This erases everything on the canvas.
root.mainloop()
|
e2b144b45b79ad1c89b68aded6591661ae2aa37c | nahgnaw/data-structure | /exercises/string/anagram_grouping.py | 945 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
"""
class Solution(object):
# O(nLlogL)
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
if not strs:
return []
sorted_strings = {}
for s in strs:
sorted_strings.setdefault(tuple(sorted(s)), []).append(s)
for key in sorted_strings:
sorted_strings[key] = sorted(sorted_strings[key])
return sorted_strings.values()
if __name__ == '__main__':
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
sol = Solution()
print sol.groupAnagrams(strs)
|
9d7ef7fa81faa988232f153a145cdf9155ced240 | big-wave-dave/basics4fun | /08_fileIO.py3 | 1,259 | 4.5 | 4 | # Basically, file input is reading from a file and output is writing to one.
# To start, we need a file to read from and one to write to.
# input.txt is what we read from and output.txt is what we write to.
# There are a few flags that can be used when opening files for io that
# tell python what to do with the file:
# r = read (default)
# w = write/truncate (trunc overwrites)
# r+ = read and write
# w+ = read and write/truncate (trunc overwrites)
# a+ = read and append
# If the file does not exist, opening to write to it creates it.
# Opening with "with" makes sure the files close properly if the script crashes
infile = open("input.txt", 'r')
outfile = open("outfile.txt", 'a+')
# Read the whole file into a variable
text = infile.read()
print(f"{text}")
# To read in a file character by character, treat it as a list
for line in text:
# Tell the printer when the line ends
print(f"{line}", end='')
# Alternatively, convert the file contents to listed lines with list()
lines = list(infile)
for line in lines:
print(f"{line}")
# Writing is super easy, just write a string to the file.
outfile.write("This string will be appended because of how I opened the file handle.\n")
# Close the files manually
infile.closed
outfile.closed |
b8d3e09130ad36f8f647c9f1f5b391a24b263f11 | abhro/exercism-solutions | /python/pangram/pangram.py | 179 | 4.09375 | 4 |
from string import ascii_lowercase
def is_pangram(s):
s = s.lower()
for letter in ascii_lowercase:
if letter not in s:
return False
return True
|
06d77135dda0129709f3d692b3fe5e1224c3d5ff | Mahalinoro/python-ds-implementations | /linked lists/singly_linked_list.py | 7,309 | 4.34375 | 4 | # Linked Lists (with a tail reference) + relevant primary methods
# Node Class
class Node:
def __init__(self, value = None):
self.value = value
self.next = None
# Method which returns the value of a node
# Time Complexity => O(1)
# Space Complexity => O(1)
def getValue(self):
return self.value
# Method which returns the next node
# Time Complexity => O(1)
# Space Complexity => O(1)
def getNext(self):
return self.next
# Method which set a new value to the current node value
# Time Complexity => O(1)
# Space Complexity => O(1)
def setValue(self, newval):
self.value = newval
# Method which set the next node value to a new value
# Time Complexity => O(1)
# Space Complexity => O(1)
def setNext(self, newval):
self.next = newval
# Linked List class
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
# Method returning the head node
# Time Complexity => O(1)
# Space Complexity => O(1)
def headNode(self):
if self.head == None:
return None
else:
return self.head.getValue()
# Method returning the tail node
# Time Complexity => O(1)
# Space Complexity => O(1)
def tailNode(self):
if self.tail == None:
return None
else:
return self.tail.getValue()
# Method checking whether the linked list is empty or not
# Time Complexity => O(1)
# Space Complexity => O(1)
def isEmpty(self):
return self.head == None
# Method returning all the nodes within the Linked List
# Time Complexity => O(n) because the worst case implies traversing each elements depending on the size of the linked list
# Space Complexity => O(n) because it stores the nodes into a list values which can be n size
def __str__(self):
values = []
currentNode = self.head
while currentNode:
values.append(currentNode.value)
currentNode = currentNode.getNext()
return " => ".join(map(str, values))
# Method transforming the value as the head and the current head as the 2nd node
# Time Complexity => O(1)
# Space Complexity => O(1)
def prepend(self, value):
newNode = Node(value)
currentNode = self.head
if self.head == None:
self.head = newNode
else:
newNode.setNext(self.head)
self.head = newNode
# Method transforming the value as the tail and the current tail become the 2nd last node
# Time Complexity => O(n) since we don't know the previous node, it needs to traverse through each node
# Space Complexity => O(1)
def append(self, value):
newNode = Node(value)
if self.head == None:
self.head = newNode
return
current = self.head
while current.next:
current = current.next
current.next = newNode
self.tail = newNode
# Method transforming the 2nd node to become the head
# Time Complexity => O(1)
# Space Complexity => O(1)
def popFirst(self):
currentHead = self.head
self.head = currentHead.getNext()
# Method transforming the 2nd last node to become the tail
# Time Complexity => O(n) since the previous node is now know, it has to traverse until it reaches the tail
# Space Complexity => O(1)
def pop(self):
previousNode = None
currentNode = self.head
while currentNode.next:
previousNode = currentNode
currentNode = currentNode.next
self.tail = previousNode
previousNode.next = None
currentNode = None
# Method returning the size of the Linked List
# Time Complexity => O(n) because it has to traverse untill it reaches the tail
# Space Complexity => O(1) because it is only a simple variable
def size(self):
currentNode = self.head
size = 0
while currentNode != None:
size += 1
currentNode = currentNode.getNext()
return size
# Method accessing the value of a specific index in the Linked List
# Time Complexity => O(n) if the index is out of reach
# Space Complexity => O(1)
def index(self, index):
currentNode = self.head
count = 0
while currentNode:
count += 1
if count == index:
return currentNode.getValue()
else:
currentNode = currentNode.getNext()
# Method checking wether a value is in the Linked List or not, returning True if found, false otherwise
# Iterative Method
# Time Complexity => O(n) if the node is not in the linked list
# Space Complexity => O(1)
def search(self, value):
currentNode = self.head
found = False
while currentNode is not None and not found:
if currentNode.getValue() == value:
found = True
return found
else:
currentNode = currentNode.getNext()
if not found:
return 'Value not present in the List'
# Method checking wether a value is in the Linked List or not, returning True if found, false otherwise
# Recursive Method
# Time Complexity => O(n)
# Space Complexity => O(n)
def searchR(self, head, value):
if head == None:
return False
elif head.getValue() == value:
return True
return self.searchR(head.next, value)
# Method inserting a value at a specific index
# Time Complexity => O(n) if it has to traverse until the tail and we do not know about the previous Node
# Space Complexity => O(1)
def insert(self, value, index):
newNode = Node(value)
currentNode = self.head
previousNode = None
count = 0
if self.head == None:
self.head = newNode
elif index == 0 or index == 1:
newNode.setNext(self.head)
self.head = newNode
else:
while currentNode:
count += 1
if count == index - 1:
previousNode = currentNode
nextNode = previousNode.next
currentNode.next = newNode
newNode.next = nextNode
return count
else:
currentNode = currentNode.getNext()
# Method deleting a value in the Linked List
# Time Complexity => O(n) since the previous Node is unknown, it has to traverse through the linked list
# Space Complexity => O(1)
def delete(self, value):
currentNode = self.head
previousNode = None
found = False
while not found:
if currentNode.getValue() == value:
found = True
else:
previousNode = currentNode
currentNode = currentNode.getNext()
if previousNode == None:
self.head = currentNode.getNext()
else:
previousNode.setNext(currentNode.getNext())
|
1713aa6e0fa02384f155054f2d3c42252efcc206 | helenaj18/Gagnaskipan | /Tímadæmi/Tímadæmi 4/power.py | 130 | 3.703125 | 4 |
def power(base, exp):
if exp == 0:
return 1
else:
return base * power(base, exp-1)
print(power(2,-3))
|
3f56c9edefcef6a49582a6edab900dc5de4a0bac | Utkarshmalik99/DSA-GeeksforGeeks | /Recursion/Possible Words From Phone Digits.py | 975 | 4.03125 | 4 | #User function Template for python3
phone = ["abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
def printString(digits,n,res,string="",index=0):
if index == n:
res.append(string)
return
for i in range(len(phone[digits[index]-2])):
string += phone[digits[index]-2][i]
printString(digits,n,res,string,index+1)
string = list(string)
string.pop()
string = ''.join(string)
##Complete this function
def possibleWords(a,N):
res=list()
printString(a,N,res)
return res
#{
# Driver Code Starts
#Initial Template for Python 3
import math
def main():
T=int(input())
while(T>0):
N=int(input())
a=[int(x) for x in input().strip().split()]
res = possibleWords(a,N)
for i in range (len (res)):
print (res[i], end = " ")
print()
T-=1
if __name__=="__main__":
main()
# } Driver Code Ends
|
1ce7d65bba75e56d076e2d9fffceed6d882d76d9 | hschilling/dln_rover | /dln_rover.py | 1,614 | 3.625 | 4 | '''
This is the file that defines all the objects the
students will create and call methods on.
The methods, in turn, will send BlueTooth messages
to the NXT
'''
import nxt.locator
class Robot(object):
'''The driving part of the rover'''
def __init__(self, brick):
self.brick = brick
def timeDrive(self, direction, speed, time):
time = time * 1000; #adjust for 1/1000ths of a second
self.brick.send_command("btimeDrive %s %i %f " % (direction, speed, time))
# Direction: forward, backward; Speed: 0-100%; Time: seconds
def rotationDrive(self, direction, speed, degrees):
self.brick.send_command("brotationDrive %s %i %f " % (direction, speed, degrees))
# Direction: forward, backward; Speed: 0-100%; Rotations: rotations of motor
def ultrasonicDrive(self, direction, speed, distance):
self.brick.send_command("bultrasonicDrive %s %i %f " % (direction, speed, distance))
# Direction: forward, backward; Speed: 0-100%; (centimeters)
print "Message sent"
def timeTurn(self, direction, speed, time):
time = time * 1000;
self.brick.send_command("btimeTurn %s %i %f " % (direction, speed, time))
# Direction: leftTurn, RightTurn; Speed: 0-100%; Time: seconds
def gyroTurn(self, direction, speed, heading):
self.brick.send_command("bgyroTurn %s %i %f " % (direction, speed, heading))
# Direction: leftTurn, rightTurn; Speed: 0-100%; Gyro
def cameraHeading(self, speed, degrees):
self.brick.send_command("bcameraHeading %s %i %f " % ("right", speed, degrees))
|
6eab42cb6a6ebefe0e49cd3c61be957dad172eae | wuruchi/nand2tetris1 | /assembler/symboltable.py | 1,447 | 3.734375 | 4 | #!/usr/bin/python
class SymbolTable():
"""
Stores memory addresses and variable values
"""
def __init__(self):
self._table = {"SP": 0,
"LCL": 1,
"ARG": 2,
"THIS": 3,
"THAT": 4,
"R0": 0,
"R1": 1,
"R2": 2,
"R3": 3,
"R4": 4,
"R5": 5,
"R6": 6,
"R7": 7,
"R8": 8,
"R9": 9,
"R10": 10,
"R11": 11,
"R12": 12,
"R13": 13,
"R14": 14,
"R15": 15,
"SCREEN": 16384,
"KEYBOARD": 24576}
self._values = {}
self.counter = 16
def addEntry(self, name, address):
# self._table[name] = self.counter
self._values[name] = address
#self.counter += 1
def addEntryVar(self, name):
self._table[name] = self.counter
self.counter += 1
def contains(self, name):
return name in self._table or name in self._values
def getAddress(self, name):
if name in self._table:
return self._table.get(name, None)
return self._values.get(name, None)
|
e1b1dc5a3e6c62da8869015f8ef3e88777d1cfec | MilanaShhanukova/programming-2021-19fpl | /shapes/square.py | 268 | 3.65625 | 4 | """
Programming for linguists
Implementation of the class Square
"""
from shapes.rectangle import Rectangle
class Square(Rectangle):
"""
A class for squares
"""
def __init__(self, uid: int, length: int):
super().__init__(uid, length, length)
|
08a0d7b77bf11da438467dd2f5d32ac3b5a2a40a | janakuz/Project-Euler | /P9.py | 503 | 3.671875 | 4 | #a=m**2-n**2, b=2mn, c=m**2+n**2
#m**2+mn=tripleSum/2, m and n coprime, m-n odd
import math
def gcd(a,b):
while (a != b):
if (a > b):
a -= b
else:
b -= a
return a
def pythagoreanTriples(tripleSum):
m = int(round(math.sqrt(tripleSum/2)))
while (m>0):
n = (tripleSum/2 - m**2)/float(m)
print m, n
if (int(n)==n and n > 0):
return [m**2-n**2, 2*m*n, m**2+n**2]
m -= 1
return []
|
a960bca7ff17a16b60e58796bd7e3f04d9de3920 | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção07-Coleções/Collections_Deque.py | 500 | 3.890625 | 4 | """
Módulo Collections - Deque
Podemos dizer que o Deque é uma lista de alta performance
"""
# Fazendo o import
from collections import deque
# Criando deques
deq = deque('geek')
print(deq)
# Adicionando elementos no deque
deq.append('y') # Adiciona no final da lista
print(deq)
deq.appendleft('k') # Adiciona no começo da lista
print(deq)
# Remover elementos
print(deq.pop()) # Remove o ultimo elemento
print(deq)
print(deq.popleft()) # remove e retorna o primeiro elemento
print(deq)
|
227024d1547c354e5c3ad2c130409bfdd86c51a4 | huntermthws/advent-of-code-2018 | /day1.py | 761 | 3.875 | 4 |
#Part 1
#Open file input.txt and read line by line. Adding the value of the line to frequency. Print frequency.
def part1(values):
frequency = 0
for value in values:
frequency += value
print(frequency)
def part2(values):
individual_frequency = set()
frequency = 0
while True:
for value in values:
frequency += int(value)
if frequency in individual_frequency:
print(frequency)
return
individual_frequency.add(frequency)
if __name__ == "__main__":
values = []
with open("input.txt") as f:
for line in f:
values.append(int(line))
part1(values)
part2(values) |
4c84bc0f21edc9c36b3e30dd70663c011259825a | maciejwieczorek/python | /lekcja_1/zad_5.py | 662 | 3.8125 | 4 | print('Podaj ilosc liczb :')
n = int(input())
i = 0
j = 0
tablica=[]
for i in range((n)):
liczba = input()
tablica.append(int(liczba))
print('Wpisz 1 posortuje rosnaco')
print('Wpisz 2 posortuje malejaco')
wybor = int(input())
print('wybierz zakres sortowania')
print('Zakres od : ')
zakres = int(input())
print('Zakres do :')
zakresDo = int(input())
zakresVol2 = zakres
if( wybor == 1):
tablica.sort()
for zakres in range(zakresDo):
print(tablica[zakres])
elif(wybor == 2):
tablica.sort()
tablica.reverse()
for zakresVol2 in range(zakresDo):
print(tablica[zakresVol2])
|
879ec38f74a20936b74f9f1f0d9b019eb14ab698 | wzz482436/python_Text | /07day/03-输入一个数判断大小.py | 227 | 3.578125 | 4 | number = int(input("请输入一个数字"))
'''
= 赋值运算符 a = 1
== 条件判等 a == 1
'''
if number == 50:#判断你输入进来的数是不是等于50
print("哈哈哈")
else:
print("呵呵呵")
|
74a31d4a315675d62614630aac25ffb3a9822682 | howeltri/miscrepo-howeltri | /dictComprehensionExamples.py | 723 | 3.765625 | 4 | new_dict = {num: num**2 for num in [1,2,3,4,5]}
instructor = {'name': "sam", 'city': 'ashburn', 'pal': 'scout'}
yelling_instructor = {key.upper():val.upper() for key, val in instructor.items()}
yelling_instructor_logic = {(key.upper() if key == "pal" else key):val.upper() for key, val in instructor.items()}
answer = {list1[i]:list2[i] for i in range(0, len(list1))}
person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
#The three of these would work
answer = {persons[0]:persons[1] for persons in person}
answer = {k:v for k,v in person}
answer = dict(person)
answer = {letter:0 for letter in 'aeiou'}
answer = {asc:chr(asc) for asc in range(65,91)}
return {letter: value.count(letter) for letter in value} |
2c7eff7af6d5fce54d88c03f85fc291f0c2676d1 | ms-shakil/52-problems-and-solve | /problem_eighteen.py | 167 | 3.9375 | 4 | # word count by input sentence
value = input("Enter the sentence:")
def MyFunction(val):
value = val.split(" ")
print("count = ",len(value))
MyFunction(value)
|
ed122ddfaa239f9a2b617a743bf44e00369055d2 | eazow/leetcode | /405_convert_a_number_to_hexadecimal.py | 461 | 3.546875 | 4 | class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
map = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
hex = ""
for i in range(8):
hex = map[num & 0xf] + hex
num = num >> 4
return hex.lstrip("0")
assert Solution().toHex(-1) == "ffffffff"
assert Solution().toHex(26) == "1a" |
da9db7611acb298e917383a038f1187b55ad32af | rwehner/rl | /homework/Python2_Homework03/src/countext.py | 850 | 3.671875 | 4 | """
Examine the contests of CWD and print out how may files
of each extension are there.
"""
import glob
import os
def countext():
files = glob.glob('*')
extensions = {}
for file in files:
name, ext = os.path.splitext(file)
extensions[ext] = extensions.get(ext, 0) + 1
return [i for i in extensions.items()]
def printextcount():
pwd = os.path.abspath(os.path.curdir)
extensions = countext()
if not extensions:
print("No files in %s" % pwd)
return
extensions.sort(key=lambda item: item[1], reverse=True)
print("In %s:" % pwd)
print('Ext \tCount')
print('----\t-----')
for ext in extensions:
if ext[0] == '':
ext = ('<none>', ext[1])
print("%s\t%s" % ext)
if __name__ == "__main__":
printextcount() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.