blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
ea6d2459eaf9c7d23f770566185fea4beac997b0 | lfalsetti16/Python_Challenge | /PyBank/PyBank.py | 1,591 | 3.703125 | 4 | import os
import csv
csvpath = os.path.join("Resources/budget_data.csv")
txtpath = os.path.join("Analysis/budget_data.txt")
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next (csvreader)
print(header)
total_months = 0
total_amount = 0
previous = 0
change = 0
change_list = []
maxchange = 0
maxdate = ""
minchange = 99999999
mindate = ""
#loop through to find total of months
for row in csvreader:
total_months= total_months +1
total_amount= total_amount + int(row[1])
change=int(row[1])- previous
change_list.append(change)
previous = int(row[1])
if change>maxchange:
maxchange=change
maxdate=row[0]
if change<minchange:
minchange=change
mindate=row[0]
average_change = sum (change_list[1:])/len (change_list[1:])
print(f"Total Months: {total_months}")
print(f"Total Amount: {total_amount}")
# print (change_list)
print(f"Average Change: {average_change}")
print(f"Greatest Increase {maxchange}{maxdate}")
print(f"Greatest Decrease {minchange}{mindate}")
with open(txtpath,'w') as txtwriter:
txtwriter.write(f"Total Months: {total_months} \n")
txtwriter.write(f"Total Amount: {total_amount} \n")
txtwriter.write(f"Average Change: {average_change}\n")
txtwriter.write(f"Greatest Increase {maxchange}{maxdate}\n")
txtwriter.write(f"Greatest Decrease {minchange}{mindate}\n") |
743f6fa86595028e721e9d223257154213077deb | dziec/macierze2 | /multipl.py | 1,414 | 4.09375 | 4 | def matrix_input():
matrix1_dim1 = int(input("Enter first dimension of first matrix: "))
matrix1_dim2 = int(input("Enter second dimension of first matrix: "))
matrix2_dim1 = int(input("Enter first dimension of second matrix: "))
matrix2_dim2 = int(input("Enter second dimension of second matrix: "))
if matrix1_dim2 != matrix2_dim1:
print("You can't multiply entered matrix.")
print("Please enter correct value ")
print("(second dimension of first matrix must ")
print("be the same as first dimension of second matrix)")
return matrix_input()
else:
dim = [
[matrix1_dim1, matrix1_dim2],
[matrix2_dim1, matrix2_dim2]
]
matrix1 = [[int(input("Enter values in first matrix (in lines): ")) for row in range(0, dim[0][1])] for col in range(0, dim[0][0])]
matrix2 = [[int(input("Enter value: in second matrix (in lines): ")) for row in range(0, dim[1][1])] for col in range(0, dim[1][0])]
result = [matrix1, matrix2, dim]
return result
def matrix_mul(mtrx):
mtrx1 = mtrx[0]
mtrx2 = mtrx[1]
dim = mtrx[2]
result = []
n = dim[0][0]
m = dim[1][-1]
result = [0] * n
for i in range(n):
result[i] = [0] * m
result = [[sum(a * b for a, b in zip(X_row, Y_col)) for Y_col in zip(*mtrx2)] for X_row in mtrx1]
return result
print(matrix_mul(matrix_input()))
|
43cad915a96d1de7a7960ef321d6ebff62208124 | rickyle327/CSCI4930-Assignment-02 | /Assigned/tasks/Q_03.py | 1,212 | 3.828125 | 4 | def Q_03(self, full_dataset):
# Task 3: Given the full_dataset (Pandas Dataframe), check if there are missing values, and if yes,
# count how many, and impute the missing values with corresponding mean values.
# Finally, return the counting result as a Pandas dataframe with 2 columns
# {variable_name,num_of_missing_values). Please make sure the result lists all the variables
# (including the target) in the given dataset. Also, return the revised full_dataset after the missing
# value imputations is done. Return these two pandas dataframe as tuple.
import pandas as pd
import numpy as np
missing_count = pd.DataFrame()
revised_full_dataset = pd.DataFrame()
# YOUR CODE HERE
revised_full_dataset = full_dataset
dict = {'Name': [], 'MissingCount': []}
for name, series in full_dataset.iteritems():
dict['Name'].append(name)
dict['MissingCount'].append(series.isnull().sum())
mean = np.mean(series.array)
revised_full_dataset.loc[:, name] = full_dataset.loc[:, name].fillna(mean)
missing_count = pd.DataFrame(dict)
# for i in len(full_dataset.columns):
return (missing_count, revised_full_dataset)
|
229c6fd1ebb06f2f3f8a5fb591e36123eee61bcd | jungleQi/leetcode-sections | /classification/data structure/3-tree/binary tree/single tree/222-M☆. Count Complete Tree Nodes.py | 416 | 3.890625 | 4 | def getLength(self, root):
if root == None:
return 0
return self.getLength(root.left) + 1
def countNodes(root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None: return 0
left = getLength(root.left)
right = getLength(root.right)
if left == right:
return 2 ** left + countNodes(root.right)
else:
return 2 ** right + countNodes(root.left)
|
23a528b97beadf5ae71955260cbb38c299ef39ec | zsoltkebel/university-code | /python/CS1527/practicals/p06/remove_comments.py | 617 | 3.78125 | 4 | # Author: Zsolt Kébel
# Date: 04/03/2021
# Removes python comments starting with # from a file
try:
source_name = input('Source file: ')
with open(source_name, 'r') as file_source:
target_name = input('Target file: ')
with open(target_name, 'w') as file_target:
lines = file_source.readlines()
for line in lines:
if line.__contains__(' #'): # changing line if it contains comment
line = line[0:line.find(' #')]
line += '\n'
file_target.write(line)
except IOError:
print('Something is not good') |
d36253a603ca12d0e65e1aa5d1ac52d0ac4602c0 | 12045630/Programming | /Python/Homework/27.11/defHOME.py | 6,219 | 3.671875 | 4 | def Autopassword(pw):
import random
str0 = ".,:;!_*-+()/#¤%&"
str1 = "0123456789"
str2 = "qwertyuiopasdfghjklzxcvbnm"
str3 = str2.upper()
str4 = str0 + str1 + str2 + str3
ls = list(str4)
random.shuffle(ls)
# Извлекаем из списка 12 произвольных значений
pw1 = "".join([random.choice(ls) for x in range(12)])
pw.append(pw1)
print(f"Ваш пароль - {pw1}")
def ManualPassword(pw):
str0 = ".,:;!_*-+()/#¤%&"
str1 = "0123456789"
str2 = "qwertyuiopasdfghjklzxcvbnm"
str3 = str2.upper()
st0 = list(str0)
st1 = list(str1)
st2 = list(str2)
st3 = list(str3)
print(
"Пароль должен содержать цифры, буквы в нижнем и верхнем регистре, спец. символы."
)
while True:
pw1 = input("Придумайте пароль - ")
pw_list = list(pw1)
if list(set(pw_list) & set(st0)):
if list(set(pw_list) & set(st1)):
if list(set(pw_list) & set(st2)):
if list(set(pw_list) & set(st3)):
print(f"Ваш пароль {pw1}")
pw.append(pw1)
else:
print("Пароль должен содержать буквы верхнего регистра.")
continue
else:
print("Пароль должен содержать буквы нижнего регистра.")
continue
else:
print("Пароль должен содержать цифры. ")
continue
else:
print("Пароль должен содержать спец. символы.")
continue
break
# def TryTry():
# answ2 = input("Введите ваш логин ")
# print("У вас будет 3 попытки, чтобы вспомнить свои данные. ")
# while answ3 not in pw:
# try:
# tru = 3
# while tru <= 3 and tru >= 1:
# try:
# answ3 = input("Введите ваш пароль ещё раз ")
# if answ3 in pw:
# print(f"Добо пожаловать - {answ2}")
# break
# else:
# tru = tru - 1
# print(f"Неправильно, у вас {tru} попыток !")
# if tru == 0:
# print("К сожалению, у вас закончились попытки.")
# break
# except:
# TypeError
# break
# except:
# TypeError
def Login(lg, pw):
answ2 = input("Введите ваш логин ")
if answ2 in lg:
answ3 = input("Введите ваш пароль ")
if answ3 in pw:
print(f"Добро пожаловать - {answ2}")
else:
print(
"Вы ввели неправильный пароль. У вас есть 3 попытки, чтобы вспомнить "
)
while answ3 not in pw:
try:
tru = 3
while tru <= 3 and tru >= 1:
try:
answ3 = input("Введите ваш пароль ещё раз ")
if answ3 in pw:
print(f"Добо пожаловать - {answ2}")
break
else:
tru = tru - 1
print(f"Неправильно, у вас {tru} попыток !")
if tru == 0:
print("К сожалению, у вас закончились попытки.")
break
except:
TypeError
break
except:
TypeError
else:
print("Вы ввели неправильный логин или же его не существует. ")
vopr = int(input("\n 1. Попробовать ещё раз \n 2. Регистрация "))
if vopr == 1:
print("У вас будет 3 попытки, чтобы вспомнить свой логин. ")
while answ2 not in lg:
try:
tru = 3
while tru <= 3 and tru >= 1:
try:
answ2 = input("Введите логин ещё раз ")
if answ2 in lg:
pw1 = input("Введите ваш пароль ")
if pw1 in pw:
print(f"Добо пожаловать - {answ2}")
break
else:
print("К сожалению, пароль неправильый. ")
else:
tru = tru - 1
print(f"Неправильно, у вас {tru} попыток !")
if tru == 0:
print("К сожалению, у вас закончились попытки.")
break
except:
TypeError
break
except:
TypeError
def registr(lg, pw):
lg.append(input("Придумайте логин - "))
answ2 = int(
input(
"Выберите дальнейшее действие \n 1. Автомотическое создание пароля \n 2. Самостоятельное создание пароля "
)
)
if answ2 == 1:
Autopassword(pw)
elif answ2 == 2:
ManualPassword(pw) |
62411d8a3f62a81c16360ce309c455e7154b209b | M-Dos/Program_Init | /Python/Conv_Seg_x_DHms.py | 356 | 3.578125 | 4 | seg_str = input("Por favor, Entre com o número de segundos que deseja converter em Dias, Horas, Minutos e Segundos:")
tt_segs = int(seg_str)
dias = tt_segs // 86400
tt_segs = tt_segs % 86400
horas = tt_segs // 3600
tt_segs = tt_segs % 3600
min = tt_segs // 60
tt_segs = tt_segs % 60
print(dias,"dias,",horas,"horas,",min,"minutos e",tt_segs,"segundos.") |
546a71b288dbfc7a1a8169a391e39e43f3c1ffee | PangYunsheng8/LeetCode | /剑指offer/链表中倒数第k个结点.py | 1,389 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 解法一,时间复杂度O(N), 空间复杂度O(1)
# 思路:先遍历链表,计算出链表长度,再获得倒数第k个结点的正数index,重新遍历链表直到index
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
num = 0
node = head
while node:
num += 1
node = node.next
index = 1
node_k = head
while index <= (num - k):
node_k = node_k.next
index += 1
return node_k
# 解法二,时间复杂度O(N), 空间复杂度O(1)
# 思路:双指针。两个指针pre, cur相距k个结点,每次同时移动,若cur为None时,pre刚好为第k个结点
# 时间复杂度解析,对于cur,需要先提前走k个结点,再和pre走(length - k)个结点,length为链表长度,
# 因此时间复杂度为O(N), 相比较于第一种,时间复杂度没有减少,但是实际的运行时间会减少。
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
node = head
while k > 0:
node = node.next
k -= 1
pre, cur = head, node
while cur:
cur = cur.next
pre = pre.next
return pre |
d73a57f1caa94f2fa698a6ce753637b935340cab | khacvu0505/Python_Basic | /py_json.py | 496 | 3.890625 | 4 | # JSON is commonly used with data APIS. Here how we can parse JSON into a Python dictionary
import json
# Sample JSON
userJSON = '{"first_name":"Vu", "last_name":"Nguyen","age":30}'
# Parse to dict
# json.loads(): giúp parse từ json string to dictionary
user = json.loads(userJSON)
print(user)
print(user['age'])
# dicitionary to JSON
# json.dumps(): help convert Json Object to Json String
car = {'make': 'Ford', 'model': 'Mustang', 'year': 2021}
carJSON = json.dumps(car)
print(carJSON)
|
35e5fc9c151916b6e3f2df117f6ac3bab354f0d8 | mahmoodasiddiqui/python-first | /practice3.py | 208 | 3.609375 | 4 | class human(object):
def __eq__(self,age):
#print("__eq__ called")
return self.value == age
a=human()
a.value = 3
b=human()
b.value = 4
print("a.value and b.value is equal")
print(a==b)
|
fae63832e01dac3a831c3cb1b25fa46ca62d51c6 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 06/06.23 - Programa 6.8 - Pilha de pratos.py | 1,332 | 4.375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 06\06.23 - Programa 6.8 - Pilha de pratos.py
# Descrição: Programa 6.8 - Pilha de pratos
##############################################################################
# Programa 6.8 - Pilha de pratos
prato = 5
pilha = list(range(1, prato + 1))
while True:
print(f"\nExistem {len(pilha)} pratos na pilha")
print(f"Pilha atual: {pilha}")
print("Digite E para empilhar um novo prato,")
print("ou D para desempilhar. S para sair.")
operação = input("Operação (E, D ou S):")
if operação == "D":
if len(pilha) > 0:
lavado = pilha.pop(-1)
print(f"Prato {lavado} lavado")
else:
print("Pilha vazia! Nada para lavar.")
elif operação == "E":
prato += 1 # Novo prato
pilha.append(prato)
elif operação == "S":
break
else:
print("Operação inválida! Digite apenas E, D ou S!")
|
1337361327202d56bd8374e354e79f60a2a2763d | bryanwspence/DEVASC-divisors | /divisors.py | 431 | 4.21875 | 4 | # Create emtpy list that will store Divisors
divisors = []
# Ask user for number, store as integer in number variable
number = int(input("Please enter a number: "))
# Print user's number
print("\nYour number is {}".format(number))
# Calculate Divisors
for x in range(1, number + 1):
if number % x == 0:
divisors.append(x)
print("\nThe number {} is divisible by the following numbers {}".format(number, divisors))
|
8a73a01aec1343456b9e4df148dd5a35dfb3fc27 | lucemia/euler | /36.py | 240 | 3.65625 | 4 |
def is_palindromes(n):
return n == int(''.join(reversed(bin(n)[2:])), 2) and n == int(''.join(reversed(str(n))))
assert is_palindromes(585)
total = 0
for i in range(1000000):
if is_palindromes(i):
total += i
print total
|
882da5d62b9649a9479355a7ab2b6f4e7b1cfe6a | squeakus/bitsandbytes | /photobooth/onscreenkeyboard.py | 2,624 | 4.3125 | 4 | """
Simple on-screen keyboard using tkinter
Author : Ajinkya Padwad
Version 1.0
"""
import tkinter as tk
from tkinter import Entry
def main():
"""Create a keyboard and output the submission"""
keyboard = OnscreenKeyboard()
keyboard.keyboard.mainloop()
print("hello!")
print(keyboard.username)
class OnscreenKeyboard:
"""
touch screen keyboard for handling input on raspiTFT
"""
def __init__(self):
self.keyboard = tk.Tk()
self.keyboard.title("Enter User Name:")
self.username = ""
self.keyboard.resizable(0, 0)
self.entry = Entry(self.keyboard, width=50)
self.entry.grid(row=0, columnspan=15)
self.buttons = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'BACK',
'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'CANCEL',
'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', '_', 'DONE']
self.create_keyboard()
def select(self, value):
"""
Map buttons to alphanumeric buttons to keypress, handle delete
cancel and submit options as well.
"""
if value == "BACK":
self.entry.delete(len(self.entry.get())-1, tk.END)
elif value == "CANCEL":
self.keyboard.destroy()
elif value == 'DONE':
self.username = self.entry.get()
self.keyboard.destroy()
else:
self.entry.insert(tk.END, value)
def create_keyboard(self):
""" Add the buttons to a gridlayout 9 wide"""
row = 1 # leave room for the text box
col = 0
for button in self.buttons:
def command(x=button):
"""mapping button to function"""
return self.select(x)
if button == "CANCEL" or button == "DONE" or button == "BACK":
tk.Button(self.keyboard, text=button, width=6, bg="#3c4987", fg="#ffffff",
activebackground="#ffffff", activeforeground="#3c4987",
relief='raised', padx=1, pady=1, bd=1,
command=command).grid(row=row, column=col)
else:
tk.Button(self.keyboard, text=button, width=4, bg="#3c4987", fg="#ffffff",
activebackground="#ffffff", activeforeground="#3c4987",
relief='raised', padx=1, pady=1, bd=1,
command=command).grid(row=row, column=col)
col += 1
# 9 buttons per row
if col > 9:
col = 0
row += 1
if __name__ == '__main__':
main()
|
b86d7844549c73d4578be80336b71c0013b21fef | tommyg0d/Pyton-Domashka | /lesson_4/str_n.py | 294 | 3.859375 | 4 | def f(s,n):
if len(s) > n:
return s.upper()
else: return s
s = input('Введите строку:\n')
n = input('Введите число: ')
if s:
if n:
print(f(s,int(n)))
else: print('Введите число!')
else: print('Введите строку!') |
1b3236868b1889ca53cc1a65828dc3e190d6bee3 | xpessoles/Informatique | /Exercices/03_tableaux/TAB-011/Kaprekar.py | 608 | 3.625 | 4 | def int2list(n):
"""Donne la liste des chiffres de n en base 10"""
x = n
L = []
while x >=10:
L.append(x%10)
x = x//10
L.append(x)
L.reverse()
return L
def list2int(L):
"""Donne l'entier décrit en base 10 par la liste de chiffres L"""
n = 0
for c in L:
n = c + 10*n
return n
def K(n):
"""Kaprekar de n"""
c = int2list(n)
d = int2list(n)
c.sort()
d.sort(reverse = True)
return list2int(d)-list2int(c)
def Kaprekar(n):
x = n
L = []
while not (x in L):
L.append(x)
x = K(x)
return L
|
be49d13a2901279041aeacb3fc651564ca80e724 | ggsant/pyladies | /iniciante/Mundo 02/Exercícios Corrigidos/Exercício 042.py | 735 | 4.125 | 4 | """
EXERCÍCIO 042: Analisando Triângulos v2.0
Refaça o EXERCÍCIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
- Equilátero: todos os lados iguais
- Isósceles: dois lados iguais
- Escaleno: todos os lados diferentes
"""
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos acima PODEM FORMAR um triângulo ', end='')
if r1 == r2 == r3:
print('EQUILÁTERO!')
elif r1 != r2 != r3 != r1:
print('ESCALENO!')
else:
print('ISÓSCELES!')
else:
print('Os segmentos acima NÃO PODEM FORMAR triângulo!')
|
94cf791cdadfa101e0e7f613fab4d1a3ca9b2a93 | Mustafa-Agha/python-random-movie-names | /src/normalize.py | 434 | 3.59375 | 4 | import unicodedata
import re
def normalize(string: str) -> str:
"""
Takes a string and normalize it.
:param string: containing accents chars
:return: normalized string
"""
return ''.join([c for c in unicodedata.normalize('NFD', re.sub("""[\u0300-\u036f`~!#$-@%^&*()|+=÷¿?;.:'"\\s,<>{}]"""
, "", string)) if not unicodedata.combining(c)])
|
66054e4babfacecd0b0ffa5c8a0ee86e044d6505 | clevelandhighschoolcs/p4mawpup-DexterCarpenter | /Notes/webdata.py | 4,213 | 3.71875 | 4 | #
# Web Data
"""
#MAIN SNIPPET:
def main():
if __name__ == "__main__":
main()
"""
"""
#Internet Data
import urllib2
def main():
# open a connection to a URL using urllib2
webUrl = urllib2.urlopen("http://mrwalker.clevelandhighschool.com") #this can be any website
# get the result code and print it
print "result code: " + str(webUrl.getcode())
# read the data from the URL and print it
data = webUrl.read()
print data
if __name__ == "__main__":
main()
"""
"""
#JSON data
import urllib2
import json
def printResults(data):
# Use the json module to load the string data into a dictionary
theJSON = json.loads(data)
# now we can access the contents of the JSON like any other Python object
if "title" in theJSON["metadata"]:
print theJSON["metadata"]["title"]
# output the number of events, plus the magnitude and each event name
count = theJSON["metadata"]["count"];
print str(count) + " events recorded"
# for each event, print the place where it occurred
for i in theJSON["features"]:
print i["properties"]["place"]
# print the events that only have a magnitude greater than 4
for i in theJSON["features"]:
if i["properties"]["mag"] >= 4.0:
print "%2.1f" % i["properties"]["mag"], i["properties"]["place"]
# print only the events where at least 1 person reported feeling something
print "Events that were felt:"
for i in theJSON["features"]:
feltReports = i["properties"]["felt"]
if (feltReports != None) & (feltReports > 0):
print "%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times"
# Open the URL and read the data
webUrl = urllib2.urlopen(urlData)
print webUrl.getcode()
if (webUrl.getcode() == 200):
data = webUrl.read()
# print out our customized results
printResults(data)
else:
print "Received an error from server, cannot retrieve results " + str(webUrl.getcode())
"""
"""
#HTML
def main():
# import the HTMLParser module
from HTMLParser import HTMLParser
metacount = 0;
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
# function to handle an opening tag in the doc
# this will be called when the closing ">" of the tag is reached
def handle_starttag(self, tag, attrs):
global metacount
print "Encountered a start tag:", tag
if tag == "meta":
metacount += 1
pos = self.getpos() # returns a tuple indication line and character
print "At line: ", pos[0], " position ", pos[1]
if attrs.__len__ > 0:
print "\tAttributes:"
for a in attrs:
print "\t", a[0],"=",a[1]
# function to handle the ending tag
def handle_endtag(self, tag):
print "Encountered an end tag:", tag
pos = self.getpos()
print "At line: ", pos[0], " position ", pos[1]
# function to handle character and text data (tag contents)
def handle_data(self, data):
print "Encountered some data:", data
pos = self.getpos()
print "At line: ", pos[0], " position ", pos[1]
# function to handle the processing of HTML comments
def handle_comment(self, data):
print "Encountered comment:", data
pos = self.getpos()
print "At line: ", pos[0], " position ", pos[1]
# open the sample HTML file and read it
f = open("samplehtml.html")
if f.mode == "r":
contents = f.read() # read the entire file
parser.feed(contents)
print "%d meta tags encountered" % metacount
if __name__ == "__main__":
main()
"""
"""
# Here is the code for the earthquake data taking thing using JSON files.
# If the code is not here, check on moodle // ask walker where the code is.
# you asked him to put it up there
#I have kinda lost the code for this one
def main():
if __name__ == "__main__":
main()
"""
"""
#------------HTML------------#
"""
# --- XML ---
import xml.dom.minidom
def main():
# use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("samplexml.xml");
# print out the document node and the name of the first child tag
print doc.nodeName
print doc.firstChild.tagName
if __name__ == "__main__":
main()
|
771ef5080bec5a79f143ede4943b2184bdf54b70 | Martin9527/LeetCodeTest | /romanToInt.py | 1,010 | 3.53125 | 4 | class Solution(object):
def romanToInt(self,s):
'''
'''
length = len(s)
if length <= 0:
return 0
num = 0
i = 0
while i < length:
if s[i] == 'M':
num += 1000
elif s[i] == 'D':
num += 500
elif s[i] == 'C':
if i + 1 < length:
if s[i+1] == 'D':
num += 400
i += 2
continue
elif s[i+1] == 'M':
num += 900
i += 2
continue
num += 100
elif s[i] == 'L':
num += 50
elif s[i] == 'X':
if i + 1 < length:
if s[i+1] == 'L':
num += 40
i +=2
continue
elif s[i+1] == 'C':
num += 90
i += 2
continue
num += 10
elif s[i] == 'V':
num += 5
elif s[i] == 'I':
if i + 1 < length:
if s[i+1] == 'V':
num += 4
i += 2
continue
elif s[i+1] == 'X':
num += 9
i += 2
continue
num += 1
else:
raise
i+= 1
return num
if __name__ == '__main__':
s = Solution()
rom = s.romanToInt("MCMXCIV")
print 'int: ',rom
|
17e45afe1c84cf7ad7b114d3ab898c762b88eeae | eoinlees/pyprimes | /primes.py | 299 | 4 | 4 | # Eoin Lees
# Computing the primes.
from functions import isprime
# My list of Primes - TBD
P = []
# Loop through all of the numbers we're checking for Primality.
for i in range(2,100):
# If i is prime, then append to P.
if isprime(i):
P.append(i)
# Print out our list
print(P)
|
b8516e2b61394773a2beeba63092e2df5ed695bf | pcarswell/gitDemo-Team1 | /WordFrequencyUrl.py | 1,998 | 3.578125 | 4 | ##date: 05/21/2016
##programmer: Carswell
##submission: May COhPy
##program: counts the frequency of words in web text content
import requests as req
def prePare(aStr):
"""
do two splits to get the middle
"""
headTest = "*** START OF THIS PROJECT GUTENBERG EBOOK"
tailTest = "*** END OF THIS PROJECT GUTENBERG EBOOK"
head = aStr.split(headTest)
tail = head[1].split(tailTest)
return tail[0]
def wordFreq(parseThis):
"""
wordFreq() will delete punctuation, convert all words to lower case, and
keep the count of each word in a dictionary.
"""
freq = {}
nono = ('"', "'", '%', '$', '!', '.', '?', '-', ','
, '\n', '\t', '\r', ':', ';')
for c in nono:
parseThis = parseThis.replace(c, " ")
words = parseThis.split()
for word in words:
temp = word.lower()
freq[temp] = freq.get(temp, 0) + 1
return freq
def printWds(webDict):
"""
printWds() takes the dictionary of frequency counts and sorts and
prints the results. A lambda is used to create a list of the top
10 word frequencies then print the frequency from the dictionary.
"""
topEntries = sorted(webDict, key=lambda k: (-webDict[k], k))
byFreq = sorted(webDict.values(), reverse=True)
print(byFreq[:10])
for wd in topEntries[:10]:
print("\t", wd, " :: ", webDict[wd])
def main():
chExit = 'n'
while chExit != 'y':
webAddr = input("What web text file do you want to process? ")
reqText = req.get(webAddr)
if reqText.status_code >= 200 and reqText.status_code < 300:
if 'text/plain' in reqText.headers['content-type']:
printWds(wordFreq(prePare(reqText.text)))
else:
print("Not text content")
else:
print("Unsuccessful!")
chExit = input("Do you want to exit the program? (y|n) ")
if __name__ == "__main__":
main()
|
7c7aa6fb68056ceb8638f2143795d39e7219a16b | Dplo1514/ploaistudy | /1-2주차 복습/210803 복사.py | 330 | 3.734375 | 4 | #정수형 (int)는 불변타입이기 때문에 x값을 변경했을 때에도 y에 할당된 x값은 그대로
x = 5
y = x
x = 29
print(x)
print(y)
#리스트형 데이터타입은 가변이기 때문에 a값을 변경하면 b값도 자동 변경됨
a = [2,4,6]
b = a
print(a)
print(b)
a[0] = 99
print(a)
print(b) |
e1327e487139ff647557ea7cea0798bc2692bc6e | prateekg/imap-import | /load.py | 993 | 3.515625 | 4 | import json
def load_accounts():
"""A helper function that initializes this module's `accounts` variable.
`accounts` is initialized from the `accounts.json` file, and `pass_var` is
initialized appropriately for each account.
"""
global accounts
with open('accounts.json', 'r') as f:
accounts = json.load(f)
accounts = _to_str(accounts)
accounts['m_to']['pass_var'] = 'M_TO_PASS'
for i in range(len(accounts['m_froms'])):
account_from = accounts['m_froms'][i]
account_from['pass_var'] = 'M_FROM' + str(i) + '_PASS'
def _to_str(d):
"""Returns `d` with unicode objects converted to str objects.
`d` can be a `dict`, `list`, or string."""
if isinstance(d, dict):
return {_to_str(key): _to_str(value) for key, value in d.iteritems()}
elif isinstance(d, list):
return [_to_str(element) for element in d]
elif isinstance(d, unicode):
return d.encode('utf-8')
else:
return d
|
0a7252d75fa187698d828158fcc1dd30db0f8a50 | navkant/ds_algo_practice | /datastructures/array_practice/maximum_nonnegative_subarray.py | 469 | 3.65625 | 4 | import sys
def maxset(arr):
array_list = []
sub_array = []
for i in range(len(arr)):
if arr[i] >= 0:
sub_array.append(arr[i])
else:
array_list.append(sub_array)
sub_array = []
array_list.append(sub_array)
print(array_list)
max_sum = -sys.maxsize
ret_arr = []
for i in array_list:
if sum(i) > max_sum:
max_sum = sum(i)
ret_arr = i
return ret_arr
|
1d75a02349dfca63af55e9c8d2fc93a8f3885872 | GianlucaTravasci/Algoritmi-StruttureDati | /Algoritmi/Traversal/DFS.py | 6,454 | 3.984375 | 4 | # Binary trees implementation for start the BFS algorithm
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
return str(self.data)
class BST:
def __init__(self):
self.root = None
self.number_of_nodes = 0
def lookup(self, data):
if self.root is None:
return 'Tree is empty'
else:
current_node = self.root
while True:
if current_node == None:
return 'Value not found'
if current_node.data == data:
return f'Found value {data}'
elif current_node.data > data:
current_node = current_node.left
elif current_node.data < data:
current_node = current_node.right
def insert(self, data):
new_node = Node(data)
if self.root is None:
self.root = new_node
self.number_of_nodes += 1
return
else:
current_node = self.root
while (current_node.left != new_node) and (current_node.right != new_node):
if new_node.data > current_node.data:
if current_node.right is None:
current_node.right = new_node
else:
current_node = current_node.right
elif new_node.data < current_node.data:
if current_node.left is None:
current_node.left = new_node
else:
current_node = current_node.left
self.number_of_nodes += 1
return
def remove(self, data):
if self.root is None:
return 'Tree is empty'
current_node = self.root
parent_node = None
while current_node is not None:
if current_node.data > data:
# current node is greater then the value we are looking for so check to the left
parent_node = current_node
current_node = current_node.left
elif current_node.data < data:
# current node is less then the value we are looking for so check into the right
parent_node = current_node
current_node = current_node.right
else: # we found the node the we wanna delete but we have to manage multiple cases
if current_node.right is None: # the node we want to delete have only a left child
if parent_node is None:
self.root = current_node.left
return
else:
if parent_node.data > current_node.data:
parent_node.left = current_node.left
return
else:
parent_node.right = current_node.left
return
elif current_node.left is None: # the node we want to delete have only a right child
if parent_node is None:
self.root = current_node.right
return
else:
if parent_node.data > current_node.data:
parent_node.left = current_node.right
return
else:
parent_node.right = current_node.right
elif current_node.left is None and current_node.right is None: # the node has no child
if parent_node is None:
current_node = None
return
if parent_node.data > current_node:
parent_node.left = None
return
else:
parent_node.right = None
return
elif current_node.left is not None and current_node.right is not None: # node has left and rigth child
del_node = current_node.right
del_node_parent = current_node.right
while del_node.left is not None: # loop to reach the left most node of the right subtree of the current node
del_node_parent = del_node
del_node = del_node.left
current_node.data = del_node.data # the value to be replaced
if del_node == del_node_parent: # if the node to be replaced is the exact right of the current node
current_node.right = del_node.right
return
if del_node.right is None: # if the left most node of the right subtree of the current node has
# no right subtree
del_node_parent.left = None
else: # if it has a right subtree, we simply link it to the parent of the del_node
del_node_parent.left = del_node.right
return
return 'Not Found'
# Now we'll implement the three kinds of DFS Traversals.
def DFS_Inorder(self):
return inorder_traversal(self.root, [])
def DFS_Preorder(self):
return preorder_traversal(self.root, [])
def DFS_Postorder(self):
return postorder_traversal(self.root, [])
def inorder_traversal(node, result):
if node.left:
inorder_traversal(node.left, result)
result.append(node.data)
if node.right:
inorder_traversal(node.right, result)
return result
def preorder_traversal(node, result):
result.append(node.data)
if node.left:
preorder_traversal(node.left, result)
if node.right:
preorder_traversal(node.right, result)
return result
def postorder_traversal(node, result):
if node.left:
postorder_traversal(node.left, result)
if node.right:
postorder_traversal(node.right, result)
result.append(node.data)
return result
my_bst = BST()
my_bst.insert(5)
my_bst.insert(3)
my_bst.insert(7)
my_bst.insert(1)
my_bst.insert(13)
my_bst.insert(65)
my_bst.insert(0)
my_bst.insert(10)
print(f"DFS inorder: {my_bst.DFS_Inorder()}")
print(f"DFS preorder: {my_bst.DFS_Preorder()}")
print(f"DFS postorder: {my_bst.DFS_Postorder()}")
|
f736858de643d08fa89db3d2a9cf4bce15e6ff84 | Jinyu97/python | /1116/실습/n4.py | 400 | 3.75 | 4 | class point:
def __init__(self,_x=0,_y=0, _z=0):
self.x=_x
self.y=_y
self.z = _z
def equal(self,other):
if (self.x==other.x and self.y==other.y and self.z==other.z):
print('eq')
else:
print('not eq')
p1=point(int(input()),int(input()),int(input()))
p2=point(int(input()),int(input()),int(input()))
p1.equal(p2)
|
e19c6c161a5c4cc414914df8ee0c07da9213d141 | AllenPengK/2021-more-code-smells | /before.py | 4,347 | 3.890625 | 4 | """
Basic example of a Vehicle registration system.
"""
from dataclasses import dataclass
from enum import Enum, auto
from random import *
from string import *
class FuelType(Enum):
"""Types of fuel used in a vehicle."""
ELECTRIC = auto()
PETROL = auto()
class RegistryStatus(Enum):
"""Possible statuses for the vehicle registry system."""
ONLINE = auto()
CONNECTION_ERROR = auto()
OFFLINE = auto()
taxes = {FuelType.ELECTRIC: 0.02, FuelType.PETROL: 0.05}
@dataclass
class VehicleInfoMissingError(Exception):
"""Custom error that is raised when vehicle information is missing for a particular brand."""
brand: str
model: str
message: str = "Vehicle information is missing."
@dataclass
class VehicleModelInfo:
"""Class that contains basic information about a vehicle model."""
brand: str
model: str
catalogue_price: int
fuel_type: FuelType
production_year: int
@property
def tax(self) -> float:
"""Tax to be paid when registering a vehicle of this type."""
tax_percentage = taxes[self.fuel_type]
return tax_percentage * self.catalogue_price
def get_info_str(self) -> str:
"""String representation of this instance."""
return f"brand: {self.brand} - type: {self.model} - tax: {self.tax}"
@dataclass
class Vehicle:
"""Class representing a vehicle (electric or fossil fuel)."""
vehicle_id: str
license_plate: str
info: VehicleModelInfo
def to_string(self) -> str:
"""String representation of this instance."""
info_str = self.info.get_info_str()
return f"Id: {self.vehicle_id}. License plate: {self.license_plate}. Info: {info_str}."
class VehicleRegistry:
"""Class representing a basic vehicle registration system."""
def __init__(self) -> None:
self.vehicle_models: list[VehicleModelInfo] = []
self.online = True
def add_vehicle_model_info(
self,
brand: str,
model: str,
catalogue_price: int,
fuel_type: FuelType,
year: int,
) -> None:
"""Helper method for adding a VehicleModelInfo object to a list."""
self.vehicle_models.append(
VehicleModelInfo(brand, model, catalogue_price, fuel_type, year)
)
def generate_vehicle_id(self, length: int) -> str:
"""Helper method for generating a random vehicle id."""
return "".join(choices(ascii_uppercase, k=length))
def generate_vehicle_license(self, _id: str) -> str:
"""Helper method for generating a vehicle license number."""
return f"{_id[:2]}-{''.join(choices(digits, k=2))}-{''.join(choices(ascii_uppercase, k=2))}"
def register_vehicle(self, brand: str, model: str) -> Vehicle:
"""Create a new vehicle and generate an id and a license plate."""
for vehicle_info in self.vehicle_models:
if vehicle_info.brand == brand:
if vehicle_info.model == model:
vehicle_id = self.generate_vehicle_id(12)
license_plate = self.generate_vehicle_license(vehicle_id)
return Vehicle(vehicle_id, license_plate, vehicle_info)
raise VehicleInfoMissingError(brand, model)
def online_status(self) -> RegistryStatus:
"""Report whether the registry system is online."""
return (
RegistryStatus.OFFLINE
if not self.online
else RegistryStatus.CONNECTION_ERROR
if len(self.vehicle_models) == 0
else RegistryStatus.ONLINE
)
if __name__ == "__main__":
# create a registry instance
registry = VehicleRegistry()
# add a couple of different vehicle models
registry.add_vehicle_model_info("Tesla", "Model 3", 50000, FuelType.ELECTRIC, 2021)
registry.add_vehicle_model_info("Volkswagen", "ID3", 35000, FuelType.ELECTRIC, 2021)
registry.add_vehicle_model_info("BMW", "520e", 60000, FuelType.PETROL, 2021)
registry.add_vehicle_model_info("Tesla", "Model Y", 55000, FuelType.ELECTRIC, 2021)
# verify that the registry is online
print(f"Registry status: {registry.online_status()}")
# register a new vehicle
vehicle = registry.register_vehicle("Volkswagen", "ID3")
# print out the vehicle information
print(vehicle.to_string())
|
c21b45cbb938e39333cdfe08c608d1781e2ba5b4 | pckhoi/datavalid | /datavalid/date.py | 3,769 | 3.5625 | 4 | import datetime
import pandas as pd
from .exceptions import BadConfigError, BadDateError
class DateParser(object):
"""Parse dates from a table.
"""
def __init__(self, year_column: str or None = None, month_column: str or None = None, day_column: str or None = None) -> None:
"""Creates a new instance of DateParser
Args:
year_column (str): year column name
month_column (str): month column name
day_column (str): day column name
Raises:
BadConfigError: There's a problem with passed-in arguments
Returns:
no value
"""
if year_column is None or type(year_column) is not str:
raise BadConfigError([], '"year_column" should be a column name')
self._year = year_column
if month_column is None or type(month_column) is not str:
raise BadConfigError([], '"month_column" should be a column name')
self._month = month_column
if day_column is None or type(day_column) is not str:
raise BadConfigError([], '"day_column" should be a column name')
self._day = day_column
def parse(self, df: pd.DataFrame) -> pd.DataFrame:
"""Produces a date dataframe (including date, year, month, day column) from the given data.
Args:
df (pd.DataFrame): data to derive date from
Raises:
BadDateError: Impossible dates detected
Returns:
a date dataframe
"""
today = datetime.date.today()
year = df[self._year].astype('Int64')
month = df[self._month].astype('Int64')
day = df[self._day].astype('Int64')
rows = df.loc[month.notna() & ((month < 1) | (month > 12))]
if rows.shape[0] > 0:
raise BadDateError('impossible months detected', rows)
rows = df.loc[
(year > today.year)
| (
(year == today.year)
& (
(month.notna() & (month > today.month))
| (day.notna() & (month == today.month) & (day > today.day))
)
)
]
if rows.shape[0] > 0:
raise BadDateError('future dates detected', rows)
rows = df.loc[day < 0]
if rows.shape[0] > 0:
raise BadDateError('negative days detected', rows)
leap_year = (year % 400 == 0) | ((year % 4 == 0) & (year % 100 != 0))
rows = df.loc[
(month.isin([1, 3, 5, 7, 8, 10, 12]) & (day > 31))
| (month.isin([4, 6, 9, 11]) & (day > 30))
| ((month == 2) & (
(~leap_year & (day > 28))
| (leap_year & (day > 29))
))
]
if rows.shape[0] > 0:
raise BadDateError('impossible dates detected', rows)
dates = df[[self._year, self._month, self._day]]
dates.columns = ["year", "month", "day"]
dates.loc[:, 'date'] = pd.to_datetime(dates)
for col in ["year", "month", "day"]:
dates.loc[:, col] = dates[col].astype('Int64')
return dates
def parse_single_date(date_str: str) -> datetime.datetime:
"""Parses date value and raise error if format isn't right
Args:
date_str (str): date string in format YYYY-MM-DD
Raises:
BadConfigError: date_str is not a string or format is wrong.
Returns:
parsed datetime
"""
if type(date_str) is not str:
raise BadConfigError(
[], 'date must be a string matching format "YYYY-MM-DD"',
)
try:
return datetime.datetime.strptime(date_str, '%Y-%m-%d')
except ValueError as e:
raise BadConfigError([], 'date must match format "YYYY-MM-DD"')
|
9f93c11bfeb1227508ac8fc7ccf65547dcf92951 | eldojk/Workspace | /WS/G4G/Problems/bst/find_triplet_with_sum_zero.py | 1,277 | 3.9375 | 4 | """
amzn, msft : triplets adding to given val in array -> sort the array and do the same
http://www.geeksforgeeks.org/find-if-there-is-a-triplet-in-bst-that-adds-to-0/
http://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/
"""
from G4G.Problems.bst.merge_two_balanced_bst import get_inorder_array, Node
def get_doubles_with_sum(array, start, end, _sum):
while start < end:
if array[start] + array[end] == _sum:
return start, end
elif array[start] + array[end] < _sum:
start += 1
else:
end -= 1
return None, None
def triplets_adding_to_zero(array, sm):
for i in range(len(array) - 2):
expected_pair_sum = sm - array[i]
start = i + 1
end = len(array) - 1
m, n = get_doubles_with_sum(array, start, end, expected_pair_sum)
if m is None:
continue
else:
return array[i], array[m], array[n]
return None, None, None
if __name__ == '__main__':
r = Node(6)
r.left = Node(-13)
r.right = Node(14)
r.left.right = Node(-8)
r.right.left = Node(13)
r.right.right = Node(15)
r.right.left.left = Node(7)
in_order = get_inorder_array(r, [])
print triplets_adding_to_zero(in_order, 0)
|
b9715529813384fb816d21c7fa7325fc20a14554 | zspo/PythonPractice | /untitled/two.py | 585 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding = utf-8 -*-
import math
def quadratic(a, b, c):
r = b*b - 4*a*c
if r < 0:
print('方程没有实根')
elif r == 0:
print('方程只有一个实根:', -b/(2*a))
else:
print('方程有两个实根:')
print('x1 = ', (-b + math.sqrt(r)) / (2 * a))
print('x2 = ', (-b - math.sqrt(r)) / (2 * a))
def main():
a = int(input('请输入第一个系数:'))
b = int(input('请输入第二个系数:'))
c = int(input('请输入第三个系数:'))
quadratic(a, b, c)
main()
|
5e7ac595c1ebd11d88ed17fd1e20bf9218617a88 | AshMano/movie-recommendation-system | /app.py | 1,014 | 3.546875 | 4 | from flask import Flask, request, render_template
from movie_recommendation import *
# create the flask app
app = Flask(__name__)
# @app.route is used to map the specific URL with the associated function that is intended to perform some task
@app.route("/")
def home():
return render_template('home.html')
@app.route('/', methods=['GET','POST'])
def recommend_movies():
if request.method == 'POST':
# get the movie_name from the input in html file associated to the 'movie' name
movie_name = request.form['movie']
result = results(movie_name)
# if the movie is not present in the dataset I display the notFound html page
# that indicates to user to enter another movie
if result == 'Movie not in Database':
return render_template('notFound.html', name=movie_name)
else:
recommendations = get_name(result)
return render_template('show.html', movies = recommendations)
if __name__ == '__main__':
app.run(debug=True)
|
47930b572bb15703779dd688ef25be61f0c5a04b | cmibarnwell/python | /dataStructures/old/InterviewPractice/baseConvert.py | 403 | 3.734375 | 4 | def baseConvert(base2):
base4 = ""
temp = ""
i = 1
for num in base2:
i += 1
print(num)
if(i%2 == 0):
if(temp == "0" and num== "0"):
base4 = base4 + "0"
if(temp == "1" and num== "0"):
base4 = base4 + "1"
if(temp == "0" and num== "1"):
base4 = base4 + "2"
if(temp == "1" and num=="1"):
base4 = base4 + "3"
temp = num
return base4
print(baseConvert("1010101010")) |
a05af100906f069f8c59c5001740a18be8119b84 | bloomfieldfong/Mancala | /prueba_mancala.py | 5,430 | 3.875 | 4 | from funciones import valid_move, print_board, play, winner, corrida_juego, possible_movess
import random
import copy
# Funciona porque el random es uniforme y esto hace que en muchas
# iteraciones el valor esperado sea aproximado a 1/6 de la cantidad de iteraciones
##Define el board que tendremos y el turno del jugador
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3
#board = [0,0,0,1,0,0,0,4,4,4,4,4,4,0]
board = [4,4,4,4,4,4,0,4,4,4,4,4,4,0]
turn = 0
prueba = [9,10,11,12,8,7]
contador= [0,0,0,0,0,0]
iteracion = 10000
porcentaje = []
over = True
#Inicio del juego
print_board( board[7:14], board[0:7])
while(over):
if turn == 0 and over == True:
move = int(input("Ingrese su movimiento (0-5): "))
if move <6 and valid_move(board, move):
## nos indica quien es el turno
board, turn, over = play(0,board, move)
print("##########################################")
print("Movimiento nuestro", move)
print_board( board[7:14], board[0:7])
elif turn == 1 and over == True:
#move = int(input("Ingrese su movimiento (0-5):v "))
##regresa los posibles movimiento para el board actual
contador = [0, 0, 0, 0, 0, 0]
porcentaje = []
##MONTE CARLO##
for i in range(0, iteracion):
## quien fue el ganador de todo el juego que se esta simulando
try:
boardTry = copy.deepcopy(board)
possible_move = possible_movess(boardTry, prueba)
move = random.choice(possible_move)
if move in possible_move:
if valid_move(boardTry, move):
winner = corrida_juego(boardTry, move)
##AQUI
if move == 7 and winner == 1:
contador[0] = contador[0] + winner
elif move == 8 and winner == 1:
contador[1] = contador[1] + winner
elif move == 9 and winner == 1:
contador[2] = contador[2] + winner
elif move == 10 and winner == 1:
contador[3] = contador[3] + winner
elif move == 11 and winner == 1:
contador[4] = contador[4] + winner
elif move == 12 and winner == 1:
contador[5] = contador[5] + winner
except:
a =1
movimiento = max(contador)
if valid_move(board, (contador.index(movimiento) + 7)) and turn == 1:
if contador.index(movimiento) == 0:
board, turn, over = play(1,board, 7)
print(turn)
print("##########################################")
contador.reverse()
print(contador)
print("##########################################")
print("Movimineto de IA: 7" )
print_board( board[7:14], board[0:7])
elif contador.index(movimiento) == 1:
board, turn, over = play(1,board, 8)
print(turn)
print("##########################################")
contador.reverse()
print(contador)
print("##########################################")
print("Movimineto de IA: 8")
print_board( board[7:14], board[0:7])
elif contador.index(movimiento) == 2:
board, turn, over = play(1,board, 9)
print(turn)
print("##########################################")
contador.reverse()
print(contador)
print("##########################################")
print("Movimineto de IA: 9",)
print_board( board[7:14], board[0:7])
elif contador.index(movimiento) == 3:
board, turn, over = play(1,board, 10)
print(turn)
print("##########################################")
contador.reverse()
print(contador)
print("##########################################")
print("Movimineto de IA: 10")
print_board( board[7:14], board[0:7])
elif contador.index(movimiento) == 4:
board, turn, over = play(1,board, 11)
print(turn)
print("##########################################")
contador.reverse()
print(contador)
print("##########################################")
print("Movimineto de IA: 11")
print_board( board[7:14], board[0:7])
elif contador.index(movimiento) == 5:
board, turn, over = play(1,board, 12)
print(turn)
print("##########################################")
contador.reverse()
print(contador)
print("##########################################")
print("Movimineto de IA: 12")
print_board( board[7:14], board[0:7])
#valid_move(board,12)
#print(corrida_juego(board, 12)) |
5adb3bbc683e191b6e09fdf8fd77aeb93ad5b116 | NhutNguyen236/Intro-to-Machine-learning | /ML_04012021/how_sexy_is_your_name.py | 1,103 | 3.984375 | 4 | # A dictionary of scores for each letter
scores = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3,
'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25,
'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405,
'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23}
# Python can access to each character in a string so try typing name[0] it will return the first character in your name
def sexy_name(name):
# Initial score is 0
score = 0
# rannking
rank = ""
for i in range(0,len(name)):
score = score + scores[name[i]]
if(score <= 60):
rank = 'NOT TOO SEXY'
elif(score >= 61 and score <=300):
rank = 'PRETTY SEXY'
elif(score >= 301 and score <=599):
rank = 'VERY SEXY'
elif(score >= 600):
rank = 'THE ULTIMATE SEXY'
return rank
example_name = 'DONALD TRUMP'
# remove all spaces in string
example_name = example_name.replace(" ", "")
# uppercase everything in string
example_name = example_name.upper()
print(example_name)
print(sexy_name(example_name))
|
47ec4060cddf572435f2f88ec05391c365790e70 | alstndhffla/PythonAlgorithm_Practice | /DataStructure_Arrangement/card_conv_verbose.py | 1,276 | 3.65625 | 4 | # 10진수 정수값을 입력받아 2~36진수로 변환하여 출력
def card_conv(x: int, r: int) -> str:
"""정수 x를 r 진수로 변환한 뒤 그 수를 나타내는 문자열을 반환"""
d = '' # 변환 뒤 문자열
dchar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n = len(str(x)) # 변환하기 전의 자릿수
print(f'{r:2} | {x:{n}d}')
while x > 0:
print(' +' + (n + 2) * '-')
if x // r:
print(f'{r:2} | {x // r:{n}d} … {x % r}')
else:
print(f' {x // r:{n}d} … {x % r}')
d += dchar[x % r] # 해당하는 문자를 꺼내 결합
x //= r
return d[::-1] # 역순으로 반환
if __name__ == '__main__':
print('10진수를 n 진수로 변환')
while True:
while True:
no = int(input('음수가 아닌 양의 정수를 입력하세요:'))
if no > 0:
break
while True:
n = int(input('변환활 진수를 입력하세요(2~36진수 입력):'))
if 2 <= n <= 36:
break
print(f"{no}를 {n}진수로 변환하면 {card_conv(no, n)}입니다.")
retry = input("한번 더 할래? Y or N:")
if retry in ['N', 'n']:
break
|
6a852acdd15f2eebb19d3380d43e3f861ab31f14 | Ildarik/5_lang_frequency | /lang_frequency.py | 756 | 3.59375 | 4 | from collections import Counter
from sys import argv
import string
def load_data(filepath):
with open(filepath, "r") as textfile:
text = textfile.read()
return text
def get_most_frequent_words(text, count):
clean_text = text.translate(str.maketrans("", "", string.punctuation))
lowercase_text = clean_text.lower()
words = lowercase_text.split()
collection = Counter(words)
return collection.most_common(count)
if __name__ == '__main__':
filepath = argv[1]
text = load_data(filepath)
top_number = 10
print("{} самых популярных слов в файле:\n{}".format(top_number, filepath))
for value, count in get_most_frequent_words(text, top_number):
print(count, value) |
bb846f5bb4f85e45f381f83ec64638a6974223a7 | gaobiyun/day1 | /day2/Mlist.py | 662 | 4.15625 | 4 | if __name__ == '__main__':
#两种方式创建列表
mlist=list()
mlist1 = []
print(type(mlist))
print(type(mlist1))
#末尾追加数据
mlist.append("贾梦瑶")
print(mlist)
#指定位置加入数据 即索引 下标
mlist.insert(0,"小傻蛋")
print(mlist)
#添加元素
mlist.insert(1, "小傻蛋")
print(mlist)
#删除元素
mlist.pop()
print(mlist)
#根据索引删除元素
del mlist[2]
print(mlist)
#移除该数据 如果该元素不存在 则报错
mlist.remove("小傻蛋")
print(mlist)
#清空列表内容 留下对象
mlist.clear()
print(mlist) |
c6146a319a656971eeac390fef1ee99b7c41b792 | Linkin-1995/test_code1 | /day05/homework/exercise02(输入5数个取平均for).py | 393 | 3.90625 | 4 | """
在终端中循环录入5个人的年龄,
最后打印平均年龄(总年龄除以人数)
"""
sum_of_ages = 0
count_of_person = 5
for __ in range(count_of_person): # 0 1 2 3 4
age = int(input("请输入年龄:"))
sum_of_ages += age
# print("平均年龄是:" + str(sum_of_ages / count_of_person) + "岁")
print("平均年龄是:%d岁" % (sum_of_ages / count_of_person))
|
7afe4216390ed8b7b60c25ebb5999920eafaec04 | etuardu/numbeancoder | /numbeancoder.py | 2,113 | 3.71875 | 4 | #!/usr/bin/env python3
"""
numbeancoder - A number to EAN13-code encoder/decoder with some security
This module provides facilities to create a EAN13-code from an integer
and decode it back. The codes are signed against a salt in order to
allow the verification that they belong to a given scope, i.e. that
they were created using that specific salt.
The integer must be up to 4 digits long.
Usage (cli, encoding only):
$ ./numbeancoder.py test 45
0045245903365
Usage (python interpreter):
>>> import numbeancoder
>>> ean = numbeancoder.Numbeancoder('test')
>>> ean.encode(45)
'0045245903365'
>>> ean.decode('0045245903365')
45
The structure of the resulting EAN13-code is the following:
0045 24590336 5
| | |
| | +- EAN checksum
| |
| +- signature
|
+- input number
"""
import hashlib
import sys
class Numbeancoder:
def __init__(self, salt):
self.salt = salt
def encode(self, n):
str_n = str(n)
if len(str_n) > 4:
raise ValueError('Input number longer than 4 digits: {}'.format(n))
# 8-digits decimal salted hash of n
str_hash = str(
int(
hashlib.sha256(
(self.salt + str_n).encode('utf-8')
).hexdigest()[:8],
16 # from base
)
)[:8].zfill(8)
str_n_hash = str_n.zfill(4) + str_hash
return str_n_hash + self.eanMakeChecksum(str_n_hash)
def decode(self, code):
if not self.eanVerifyChecksum(code):
raise ValueError([-1, 'Checksum error'])
n = int(code[:4])
if code != self.encode(n):
raise ValueError([-2, 'Hash mismatch'])
return n
def eanVerifyChecksum(self, code):
return self.eanMakeChecksum(code[:-1]) == code[-1]
def eanMakeChecksum(self, number):
"""Return the checksum for a EAN-13 code
@param {string} number - The first 12 digits of a EAN-13 code
@return {int} The checksum to be appended"""
return str((10 - sum(
(3, 1)[i % 2] * int(n)
for i, n in enumerate(reversed(number))
)) % 10)
if __name__ == '__main__':
ean = Numbeancoder(sys.argv[1])
print(ean.encode(sys.argv[2]))
|
f59a64e17515591812341d4bf58d467bc8018c5f | Grayer123/agr | /Tree/Medium/144-Binary-Tree-Preorder-Traversal/solution_iterative.py | 860 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# version 2: no adding a helper method
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# iteration + stack
# tc:O(n); sc:O(h)
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
# since stack is FILO, so put in right first, and it would be popped last
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
|
b89cc36db18cd4d24249e2009495ed0d03e909ee | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/bhrmie001/question3.py | 207 | 4.21875 | 4 | import math
i=math.sqrt(2)
pi=2
while 2/i!=1:
pi=pi*2/i
i=math.sqrt(2+i)
print("Approximation of pi:", round(pi, 3))
r=eval(input("Enter the radius:\n"))
print("Area:", round(pi*r**2, 3)) |
246bacac6cf55c90172251fc417318926bdc72d3 | Tanish74/Code-and-Compile | /Pattern printing-floyd triangle.py | 179 | 3.625 | 4 | """
input:
5
ouput:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
"""
n=int(input())
a=1
for i in range(1,n+1):
for j in range(1,i+1):
print(a,end=" ")
a+=1
print()
|
ada4239debbb5030bce6ea00d7182c638ccda05b | zhangmeilu/VIP8study | /推导式.py | 3,862 | 3.953125 | 4 | # 作用:用一个表达式创建一个有规律的列表或控制一个有规律的列表
# 列表推导式又叫列表生成式
# 需求:创建一个0-10的列表
# while循环实现
from homework import num
list1 = []
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
# for循环实现
list1 = []
for i in range(10):
list1.append(i)
print(list1)
# 带if的列表推导式
# 需求:创建0-10的偶数列表
# 方法一:range()步长实现
list1 = [i for i in range(0,10,2)]
print(list1)
list2 = [i for i in range(1,10,2)]
print(list2)
# 方法2:if实现
list1 = [i for i in range(10) if i % 2 == 0]
print(list1)
list2 = [i for i in range(10) if i % 2 == 1]
print(list2)
# 多个for循环实现列表推导式
# 需求:创建列表如下:
# [(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
list1 = [(i,j) for i in range(1,3) for j in range(3)]
print(list1)
# 字典推导式
# 思考:如果有如下两个列表:
# list1 = ['name','age','gender']
# list2 = ['Tom',20,'男']
# 如何快速合并为一个字典:字典推导式
# 创建一个字典:字典key是1-5数字,value是这个数字的2次方
dict1 = {i: i**2 for i in range(1,5)}
print(dict1)
# 将两个列表合并为一个字典
list1 = ['name','age','gender']
list2 = ['Tom',20,'男']
dict1 = {list1[i]: list2[i] for i in range(len(list2))}
print(dict1)
# 提取字典中目标数据
counts = {'MBP': 268,'HP': 125,'DELL': 201,'Lenovo': 199,'acer': 99}
count1 = {key: value for key,value in counts.items() if value <= 200}
print(count1)
# 集合推导式
# 需求:创建一个集合,数据为下方列表的2次方
# list1 = [1,1,2]
# set1 = {i ** 2 for i in list1}
# print(set1)
# password = input('请输入密码: ')
# print(f'您输入得密码是:{password}')
# print(type(password))
#
# num = input('请您输入您的幸运数字:')
# print(f"您的幸运数字是{num}")
# print(type(num))
# print(type(int(num)))
# mystr = "hello"
# print(mystr.split(' ',5))
# mystr = ['h','e','l','l','o']
# print(''.join(mystr))
mystr = "hello world and you"
print(mystr.lstrip('h'))
# list1 = [1,2,3,4,5,5,2,3,4,2,4]
# print(set(list1))
# 思考:坐公交:如果有钱可以上⻋,没钱不能上⻋;上⻋后如果有空座,则可以坐下;如果没空座,就要站着。怎么书写程序?
# money = 1表示有钱,money = 0表示没钱
# seat = 0表示没座,seat = 1 表示有座
# money = 1
# # seat = 0
# # input('请投币:')
# # input('是否有座位: ')
# # if money == 1:
# # print('请上车')
# # if seat == 1:
# # print('有空位,请坐')
# # else:
# # print('请站稳扶好')
# # else:
# # print('余额不足,请充值,不得上车')
# money = 1
# seat = 0
# if money == 1:
# print('⼟豪,不差钱,顺利上⻋')
# if seat == 1:
# print('有空座,可以坐下')
# else:
# print('没有空座,站等')
# else:
# print('没钱,不能上⻋,追着公交⻋跑')
# import random
# random.randint()
#
# a = 1
# b = 2
# c = a if a > b else b
# print(c)
# list1 = [i for i in range(100) if i % 3 == 0]
# print(list1)
# list1 = [i for i in range(0,100,3)]
# print(list1)
# list1 = [3,2,1,5,4,0,2]
# for i in list1:
# i = i ** 2
# print(list1)
# list1 = [3,2,1,5,4,0,2]
# set1 = {1 ** 2 for i in list1}
# print(set1)
#
# list1 = ['name']
# list2 = ['Tom']
# list3 = list1 + list2
# print(list3)
# print(dict{list3})
# 3 + 2 + 1
# def sum_numbers(num):
# if num == 1:
# return 1
# return num + sum_numbers(num - 1)
# sum_result = sum_numbers(4)
# print(sum_result)
# 1,1,2,3,5,8,11,19...
# def sum_numbers(num):
# if num == 1:
# return 1
# list1 = [1,2,3,4,5,5,2,3,2,4]
# print(set(list1))
# list1 = [i for i in range(100) if i % 3 == 0]
# print(list1)
|
a9e97c3df6722493db1757cfe17aa8e686128487 | grecoe/teals | /3_example_programs/400_war_2020revised.py | 8,642 | 4.03125 | 4 | """
Card game of WAR
Uses several global variables to track card values but decks and players built
up during game execution.
There are 7 functions in total that allow the game play to be condensed into
a smaller logical unit towards the end of the file.
The actual game play is between lines 218 and 302 (and that's the short version).
Imagine how long that one loop would be if you tried to include ALL of the functionality
into a single giant loop and how confusing it would be if something went wrong!
"""
import random
# Face value of cards
card_values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
# Clubs, Spades, Diamonds, Hearts
card_suit = ['\u2663', '\u2660', '\u2666', '\u2665']
# Indexes to player list
PLAYER_1 = 0
PLAYER_2 = 1
# Indexes to card list
CARD_WEIGHT = 0
CARD_FACE = 1
CARD_SUIT = 2
# Maximum number of allowed turns before game ends
MAX_TURN_COUNT = 400
def build_deck(shuffle_count=7):
"""
Build a deck of 52 cards and shuffle them
for a game.
Parameters:
shuffle_count:
int - Number of times to shuffle
Returns:
List of cards where a card is a list of
[weight, face, suit]
"""
# Build the deck by adding in each value with each suit
deck = []
for suit in range(len(card_suit)):
for value in range(len(card_values)):
card = [value, card_values[value], card_suit[suit]]
deck.append(card)
# Now loop through the number of shuffles to mix them up
for unused_var in range(shuffle_count):
random.shuffle(deck)
# Return the deck
return deck
def deal_cards(deck):
"""
Provide a full deck (52 cards), and divvy them
up into two player decks.
Parameters:
deck - List of cards
Returns:
A list of lists (one for each player)
"""
# List of lists to hold player cards
players = [[], []]
# Split all the cards in the deck between each player
for card_num in range(len(deck)):
players[card_num % 2].append(deck[card_num])
# Return the players decks
return players
def game_over(player_decks):
"""
Determines if either of the player decks are empty
and if so, game is over.
Parameters:
player_decks -
Decks for each player
Returns:
True if either deck is empty, False otherwise
"""
return_value = False
for deck in player_decks:
if len(deck) == 0:
print("GAME OVER")
return_value = True
break
return return_value
def compare_cards(risk_cards):
"""
Return index of winning card or -1 if tied
Parameters:
risk_cards -
Cards that are in play
Returns:
Index of winning card, -1 in case of tie (war)
"""
return_value = -1
if risk_cards[PLAYER_1][CARD_WEIGHT] > risk_cards[PLAYER_2][CARD_WEIGHT]:
return_value = PLAYER_1
elif risk_cards[PLAYER_1][CARD_WEIGHT] < risk_cards[PLAYER_2][CARD_WEIGHT]:
return_value = PLAYER_2
return return_value
def prepend_cards(deck, cards):
"""
Add cards to a deck. Insert at 0 so it's at the
bottom of the deck.
Parameters:
deck -
Player list of cards
cards -
List of cards to prepend to deck
"""
for card in cards:
deck.insert(0, card)
def format_risk_cards(risk_cards):
return "(P1) {}{} vs. (P2) {}{}".format(
risk_cards[PLAYER_1][CARD_FACE], risk_cards[PLAYER_1][CARD_SUIT],
risk_cards[PLAYER_2][CARD_FACE], risk_cards[PLAYER_2][CARD_SUIT]
)
def do_war(player_decks, turn_cards=3):
"""
Do war happens when both players turn equally weighted cards
and have to "war". War consists of turn_cards cards being played
face down, then flipping again.
This continues until someone wins or someone runs out of cards and
has to forfeit.
Parameters:
player_decks -
Player card decks
turn_cards -
Number of cards to play face down before continuing.
Returns:
Index of winner
"""
return_value = []
all_risk_cards = []
current_risk_cards = []
if len(player_decks[PLAYER_1]) < (turn_cards + 1):
print("Player 1 forfiets WAR due to lack of cards.")
player_decks[PLAYER_2].extend(player_decks[PLAYER_1])
player_decks[PLAYER_1] = []
return_value = PLAYER_2
elif len(player_decks[PLAYER_2]) < (turn_cards + 1):
print("Player 2 forfiets WAR due to lack of cards.")
player_decks[PLAYER_1].extend(player_decks[PLAYER_2])
player_decks[PLAYER_2] = []
return_value = PLAYER_1
else:
# Each have enough to add to the risk cards, first collect face down
for unused_counter in range(turn_cards):
all_risk_cards.append(player_decks[PLAYER_1].pop())
all_risk_cards.append(player_decks[PLAYER_2].pop())
# Now get the final turn card
current_risk_cards = [player_decks[PLAYER_1].pop(), player_decks[PLAYER_2].pop()]
# Add these to the bounty as whomever wins gets all cards, face down and up
all_risk_cards.extend(current_risk_cards)
# Tell user what the war flip is (good reuse of format_risk_cards)
print("WAR FLIP : {}".format(format_risk_cards(current_risk_cards)))
# See who won... status is -1 for tie, otherwise index to players list for winner
return_value = compare_cards(current_risk_cards)
if return_value == -1:
# In a tie AGAIN, we have to do it again...
print("CONTINUE WAR.....")
return_value = do_war(player_decks)
# If we get here we know return value has a value that is NOT -1 and hence can
# continue to move cards to winners pile.
player_id = "Player1" if return_value == 0 else "Player2"
print("Player {} won the war with {}{}!".format(player_id, current_risk_cards[return_value][CARD_FACE], current_risk_cards[return_value][CARD_SUIT]))
prepend_cards(player_decks[return_value], all_risk_cards)
# Return the index of whomever won the war so they can take original risk cards
return return_value
"""
Game starts below.......
"""
# Create a deck (shuffled)
playing_deck = build_deck()
# Deal the cards out
player_decks = deal_cards(playing_deck)
# General statistics to print at the end
game_turn = 0
war_count = 0
win_stats = [0, 0]
# Game ends when someone is out of cards....
while not game_over(player_decks):
# Each loop through increment game count
game_turn += 1
# Current face up cards to compare
risk_cards = [player_decks[PLAYER_1].pop(), player_decks[PLAYER_2].pop()]
# String representation of risk cards
played_cards = format_risk_cards(risk_cards)
# Status is -1 for tie, otherwise index to players list for winner
status = compare_cards(risk_cards)
if status == -1:
# War - Tie, have to break tie...
print("{} : WAR! with {}".format(game_turn, played_cards))
# Run the war, guaranteed a winner before it returns
war_winner = do_war(player_decks)
# Whoever won the war gets the initial risk cards
prepend_cards(player_decks[war_winner], risk_cards)
# Update stats
war_count += 1
win_stats[war_winner] += 1
else:
# Show results of round as we have a winner
print("{} : {} - {}{} wins round".format(
game_turn,
played_cards,
risk_cards[status][CARD_FACE],
risk_cards[status][CARD_SUIT]
))
# Give winner the cards
prepend_cards(player_decks[status], risk_cards)
# Update stats
win_stats[status] += 1
if game_turn > MAX_TURN_COUNT:
# At MAX_TURN_COUNT turns, just bail out or it may run too long
print("Game exceeded {} turns! Auto quit....".format(MAX_TURN_COUNT))
break
if game_turn % 10 == 0:
# Every 10th turn, show how many cards each player has
print("P1 card count : {} , P2 card count {}".format(
len(player_decks[PLAYER_1]),
len(player_decks[PLAYER_2])
))
# Game has ended or aborted on MAX_TURN_COUNT so show general stats
print("""
STATS:
P1 card count : {}
P2 card count {}
Turn Count: {}
War Count: {}
Win Stats [P1, P2]: {}
""".format(
len(player_decks[PLAYER_1]),
len(player_decks[PLAYER_2]),
game_turn,
war_count,
win_stats))
|
9fddd013bbfe2c9eaaa1f1d07e7962e15f14b5c5 | vuminhph/randomCodes | /maxOfMinPairs.py | 194 | 3.59375 | 4 | def max_of_min_pairs(nums):
nums = sorted(nums)
sum = 0
for i in range(len(nums) - 2, -1, -2):
sum += nums[i]
return sum
# print(max_of_min_pairs([1, 3, 2, 6, 5, 4]));
|
58b19c8268fb5af02c81ec342e0bfb3b856810bc | includeMaple/py_history | /data_structure/14queue.py | 618 | 4.03125 | 4 | from collections import deque
q = deque()
# 队尾进队,队首出队
q.append(1)
q.popleft()
# 队首进队,队尾出队
q.appendleft(2)
q.pop()
# 创建队列,上面没有传递任何值创建了一个空队列,也可以如下
q1 = deque([1,3,4])
# 第二个参数是最大长度,上面简单代码实现的单向队列队满再进队是提示,这里是自动出队一个
q2 = deque([1,3,4,5,6], 5)
q2.append(9)
print(q2.popleft())
def tail(n):
print('----')
f = open('test.txt', 'r')
q = deque(f, n)
return q
# with open('test.txt', 'r') as f
print(tail(5))
|
0f4df5d1cd6327fb72288b85b2d6cc6f9c515cb2 | JohnHero13/Python4e | /test4.py | 218 | 3.6875 | 4 | def computepay(h,r):
if h<41:
return h*r
elif h>40:
return (h-40)*1.5*r+40*r
hrs = input("Enter Hours:")
rte = input("Enter Rate:")
h = float(hrs)
r = float(rte)
p = computepay(h,r)
print("Pay",p)
|
5ddcbc81d7aae059d17376d0bd9ddf9042ffff73 | SrishtiGrover/nyu-cv | /Assignments/Assign0/Assignment_0_Analysis.py | 7,758 | 4.1875 | 4 |
# coding: utf-8
# # Computer Vision CSCI-GA.2271-001 - Assignment 0
# Due date: Monday September 18th 2017
# Given on: September 7, 2017
#
# ## 1 Introduction
# The purpose of this assignment is two-fold: (i) to ensure that you have the pre-requisite knowledge necessary for the rest of the course and (ii) to help you get experience with PyTorch, the language we will be using in the course.
#
# To install PyTorch, follow the directions at http://pytorch.org. This also contains a number of tutorials that it might be helpful to work through.
# To turn in the assignment, please zip your code into a file named lastname firstname assign1.zip and email it to the grader Utku Evci (ue225@nyu.edu), cc’ing me (fergus@cs.nyu.edu).
#
# In[1]:
import torch
import matplotlib.pyplot as plt
# import seaborn
# In[2]:
data_path = "assign0_data.py"
# ## 2 Whitening Data
# Pre-processing is an important part of computer vision and machine learning algorithms. One common approach is known as whitening in which the data is transformed so that it has zero mean and is decorrelated.
#
# You should implement a PyTorch function that:
# * Load up the 2D dataset from the file assign1 data.py.
# * Visualize it by making a 2D scatter plot (e.g. using matplotlib).
# * Translates the data so that it has zero mean (i.e. is centered at the origin).
# * Decorrelates the data so that the data covariance is the identity matrix.
# * Plot the whitened data.
# * As a comment in your code, discuss the dependencies present in the whitened data.
# ### Helper Functions for plotting
# In[3]:
def plot_2d(tensor2d, title, limit, color=None, clubbed=False):
'''
A helper function to plot a 2-D Tensor with title and axes limits.
'''
plt.scatter(tensor2d[:,0].numpy(),tensor2d[:,1].numpy(), c=color)
plt.title(title, fontsize=18)
plt.xlim(-limit,limit)
plt.ylim(-limit,limit)
if not clubbed:
plt.show()
def clubbed_plot(limit=None, *tensors_with_head):
'''
Function for plotting a single figure with multiple graphs
'''
legends = []
p = []
plt.xlim(-limit,limit)
plt.ylim(-limit,limit)
for tensor_with_head in tensors_with_head:
x = tensor_with_head[0]
legends.append(tensor_with_head[1])
c = tensor_with_head[2]
p.append(plt.scatter(x[:,0].numpy() , x[:,1].numpy(), c=c))
plt.legend(p, legends, fontsize=12)
plt.show()
# ### Required Function for Whitening
# In[4]:
def whitening_data(data_path):
'''
Input: data address
Prints: Orginal
'''
# 1. loading the data
x = torch.load(data_path)
# using same limit for all plots to make visual comparisons easy
limit = max(abs(x.min()), x.max())
limit = int(limit) + int(limit**(0.5))
# 2. Visualise data
plot_2d(x, "Original Data", limit, 'brown')
# 3. zero-center the data
X = x - x.mean(0).expand_as(x)
cov = torch.mm(X.t(), X) / X.size()[0] # get the data covariance matrix
U, S, V = torch.Tensor(cov).svd()
# 4. decorrelate the data
Xrot = torch.mm(X, U)
plot_2d(Xrot, "Decorrelated Data", limit, 'green')
# 5. Whiten the data:
# divide by the eigenvalues (which are square roots of the singular values)
Xwhite = Xrot / (torch.sqrt(S + 1e-5).expand_as(Xrot))
# Note that we’re adding 1e-5 (or a small constant) to prevent division by zero
plot_2d(Xwhite, "Whitened Data", limit, )
clubbed_plot(limit,(x, "Original Data", "brown"), (Xrot, "Decorrelated Data", "green"), (Xwhite, "Whitened Data", "blue"))
print("Covaraince of whitened data:")
print(torch.mm(Xwhite.t(), Xwhite) / Xwhite.size()[0])
# 6. Dependencies present in the whitened data:
'''
Second-order dependencies have been removed by the whitening process.
However, higher order dependencies might still exist.
The eigenvalues represent the variance in the data.
'''
# In[5]:
whitening_data(data_path)
# ## 3 Fitting a 1D function with a simple neural net
# In PyTorch, generate the function y = cos(x) over the interval −π ≤ x ≤ π, at discrete intervals of 0.01. Adapting the examples from http://pytorch.org/tutorials/beginner/pytorch_with_examples.html, implement a neural net that regresses this function. I.e. takes as input x and produces an estimate yˆ, where ∥y − yˆ∥2 is minimized. The network should have a single hidden layer with 10 units and a single tanh() non-linearity. Make a plot of the true function y, with the network output yˆ before and after training overlaid (please use different colors for each).
# In[6]:
import numpy as np
# Create input and output data
step = 0.01
x = torch.arange(-np.pi, np.pi, step)
y = torch.cos(x)
# In[7]:
from torch.autograd import Variable
# N is batch size
N = 17*37
# Reshape input and output data according to the batch_size
x = Variable(x.view(N, -1))
y = Variable(y.view(N, -1), requires_grad=False)
print(x.size())
# D_in is input dimension; H is hidden dimension; D_out is output dimension.
D_in, H, D_out = x.size()[1], 10, x.size()[1]
# Use the nn package to define our model as a sequence of layers. nn.Sequential
# is a Module which contains other Modules, and applies them in sequence to
# produce its output. Each Linear Module computes output from input using a
# linear function, and holds internal Variables for its weight and bias.
model = torch.nn.Sequential(
torch.nn.Linear(D_in, H),
torch.nn.Tanh(),
torch.nn.Linear(H, D_out),
)
# The nn package also contains definitions of popular loss functions; in this
# case we will use Mean Squared Error (MSE) as our loss function.
loss_fn = torch.nn.MSELoss(size_average=False)
loss_values = []
learning_rate = 1e-4
for t in range(500):
# Forward pass: compute predicted y by passing x to the model. Module objects
# override the __call__ operator so you can call them like functions. When
# doing so you pass a Variable of input data to the Module and it produces
# a Variable of output data.
y_pred = model(x)
# Compute and print loss. We pass Variables containing the predicted and true
# values of y, and the loss function returns a Variable containing the
# loss.
loss = loss_fn(y_pred, y)
loss_values.append(loss.data.tolist()[0])
# print(t, loss.data[t])
if t ==0:
y_before_training = y_pred
# Zero the gradients before running the backward pass.
model.zero_grad()
# Backward pass: compute gradient of the loss with respect to all the learnable
# parameters of the model. Internally, the parameters of each Module are stored
# in Variables with requires_grad=True, so this call will compute gradients for
# all learnable parameters in the model.
loss.backward()
# Update the weights using gradient descent. Each parameter is a Variable, so
# we can access its data and gradients like we did before.
for param in model.parameters():
param.data -= learning_rate * param.grad.data
print("Final Loss", loss[-1])
plt.plot(loss_values, c='red')
plt.title("Loss", fontsize=18)
plt.ylabel('Loss Value')
plt.xlabel('Number of iterations')
plt.show()
# ### Plotting true, untrained & trained value
# In[8]:
# Reshape to 1D
X = x.view(-1,)
Y_pred = y_pred.view(-1,)
Y_before_training = y_before_training.view(-1,)
Y = y.view(-1,)
s = [8]* len(X)
p_true = plt.scatter(X.data.tolist() , Y.data.tolist(), s=s)
p_pred = plt.scatter(X.data.tolist() , Y_pred.data.tolist(), s=s)
p_org = plt.scatter(X.data.tolist() , Y_before_training.data.tolist(), s=s)
plt.legend((p_true,p_pred, p_org),
('True Value', 'After Training', 'Before Training'), fontsize=12)
plt.show()
|
1fc39930bccc315b3d9afdca1d1d94bbfaa7c7df | huskyin/python34 | /aljabarlinear.py | 5,499 | 4.125 | 4 | #Aljabar Linear , mencari nilai X, dibuat oleh Rian Irawan hariadi (www.rianhariadi.com)
'''
Cara termudah:
http://docs.sympy.org/0.7.1/modules/solvers/solvers.html
http://stackoverflow.com/questions/10499941/how-can-i-solve-equations-in-python
Operasi string:
http://stackoverflow.com/questions/8270092/python-remove-all-whitespace-in-a-string
'''
print("Fungsi ini untuk mencari Nilai 'X' pada persamaan aljabar linier \n seperti waktu di SD, dibuat oleh Rian Irawan Hariadi")
print (" Masukkan notasi aljabar dengan variabel X pangkat 1 \n (contoh: '4 - 3x = 28 - 5X ') ")
notasi = input('Masukkan notasi:')
notasi = notasi.strip()
notasi = notasi.replace(" ","")
PASS = True
def printnotasi(notasi):
notasi = notasi.upper()
for char in notasi:
print (char)
def findNotNumber(notasi):
notasi = notasi.upper()
result = True
for char in notasi:
detect = char.isalpha()
if detect == True :
if char != 'X':
result = False
break
return result
# http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python
def pisahkanTanda(notasi):
index = 0
while index < len(notasi):
index = notasi.find('+',index)
if index == -1:
break
index_a = index + 1
notasi = notasi[:index]+'aT'+ notasi[index_a:]
index = 0
while index < len(notasi):
index = notasi.find('-',index)
if index == -1:
break
index_a = index + 1
notasi = notasi[:index]+'aK'+ notasi[index_a:]
return notasi
def PecahkanNotasi(notasi):
pecah = notasi.split('a')
return pecah
def TukarPosisi(notasi_kiri,notasi_kanan):
i =0
while (i < len(notasi_kiri) ):
if notasi_kiri[i].find('X') == -1:
#print('ruas kiri dihapus: ',notasi_kiri[i])
if notasi_kiri[i].find('T') != -1 :
notasi_kiri[i] = notasi_kiri[i].replace('T','-')
else:
notasi_kiri[i] = notasi_kiri[i].replace('K','')
notasi_kanan.append(notasi_kiri[i])
del (notasi_kiri[i])
elif notasi_kiri[i] == '':
del (notasi_kiri[i])
else:
i = i + 1
i = 0
while (i < len(notasi_kanan) ):
if notasi_kanan[i].find('X') != -1:
#print('ruas kanan dihapus:',notasi_kanan[i])
if notasi_kanan[i].find('T') != -1 :
notasi_kanan[i] = notasi_kanan[i].replace('T','-')
else:
notasi_kanan[i] = notasi_kanan[i].replace('K','')
notasi_kiri.append(notasi_kanan[i])
del (notasi_kanan[i])
elif notasi_kanan[i] == '':
del (notasi_kanan[i])
else:
i = i + 1
#print ('Setelah dipindahkan,..Notasi kiri: ',notasi_kiri)
#print ('Setelah dipindahkan,..Notasi_kanan: ',notasi_kanan)
return notasi_kiri, notasi_kanan
def AtasiX(notasi_kiri):
i = 0
notasi_kiri = [a.replace('KX','K1X') for a in notasi_kiri]
notasi_kiri = [a.replace('TX','T1X') for a in notasi_kiri]
return notasi_kiri
def NilaiKiri(notasi_kiri):
notasi_kiri = [a.replace('X','') for a in notasi_kiri]
notasi_kiri = [a.replace('K','-') for a in notasi_kiri]
notasi_kiri = [a.replace('T','') for a in notasi_kiri]
nilai = 0
nilai_kiri = ''
for i in range (len(notasi_kiri)):
nilai = int(notasi_kiri[i]) + nilai
nilai_kiri = nilai_kiri + notasi_kiri[i]+'X' + ' + '
nilai_kiri = nilai_kiri[:-2]
print ('Setelah dipindahkan, sisi kiri: ',nilai_kiri)
return nilai
def NilaiKanan(notasi_kanan):
notasi_kanan = [a.replace('K','-') for a in notasi_kanan]
notasi_kanan = [a.replace('T','') for a in notasi_kanan]
nilai = 0
nilai_kanan = ''
for i in range (len(notasi_kanan)):
nilai = int(notasi_kanan[i]) + nilai
nilai_kanan = nilai_kanan + notasi_kanan[i] + ' + '
nilai_kanan = nilai_kanan[:-2]
print ('Setelah dipindahkan, sisi kanan: ',nilai_kanan)
return nilai
#cek apakah ada tanda yang dilarang
if notasi.count('=') > 1 :
print ("Error, tanda 'sama dengan / =' dengan hanya boleh ada 1")
PASS = False
if notasi.count('^') != 0:
PASS = False
print ('Error, hanya boleh pangkat 1 !')
if notasi.count('/') != 0:
PASS = False
print ('Error, tidak boleh ada operator pembagian !')
if notasi.count('*') != 0:
PASS = False
print ('Error, tidak boleh ada operator perkalian !')
if (notasi.count(' 0 ') != 0) or (notasi.count(' 0X ') != 0) :
PASS = False
print ('Error, tidak boleh ada angka nol sendirian !')
if findNotNumber(notasi) == False:
PASS = False
print ('Error, tidak boleh ada huruf selain X !')
if PASS != False:
#print (findNotNumber(notasi))
#print (printnotasi(notasi))
#print('Fungsi dilanjutkan... besok ya... :-)')
#print('Pisahkan tanda tambah , menjadi...')
#print('Pisahkan ruas kiri dan ruas kanan')
ruas_notasi = notasi.split('=')
notasi_kiri = ruas_notasi[0]
notasi_kanan = ruas_notasi[1]
if notasi_kiri[0] != '-':
notasi_kiri = '+' + notasi_kiri
if notasi_kanan[0] != '-':
notasi_kanan = '+' + notasi_kanan
#print (pisahkanTandaTambah(notasi))
notasi_kiri = pisahkanTanda(notasi_kiri)
notasi_kanan = pisahkanTanda(notasi_kanan)
#print('Notasi kiri setelah dipecah: ')
notasi_kiri = PecahkanNotasi(notasi_kiri)
notasi_kiri = AtasiX(notasi_kiri)
#print(notasi_kiri)
#print('...')
#print('Notasi kanan setelah dipecah: ')
notasi_kanan = PecahkanNotasi(notasi_kanan)
notasi_kanan = AtasiX(notasi_kanan)
#print(notasi_kanan)
TukarPosisi(notasi_kiri,notasi_kanan)
print('..................')
#print('Notasi kiri: ',notasi_kiri)
#print('Notasi kanan: ',notasi_kanan)
nilaikiri = NilaiKiri(notasi_kiri)
nilaikanan = NilaiKanan(notasi_kanan)
print('Nilai di sisi kiri = ',str(nilaikiri)+'X')
print('NIlai di sisi kanan =',nilaikanan)
print('Solusi: X = ',float(nilaikanan/nilaikiri))
|
82b056f3be3a8f27103672514fcc02b71f978c29 | daravi/code_challanges | /project_euler/problem-032.py | 1,483 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Pandigital products
Problem 32
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once;
for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier,
and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
"""
import itertools
#1 2 3 4
#4 3 2 1
permutations = list(itertools.permutations(range(1,10), 5))
product_sum = set([])
for permutation in permutations:
for i in range(1, 5):
multiplicand = 0
for j in range(i):
multiplicand *= 10
multiplicand += permutation[j]
multiplier = 0
for k in range(i, 5):
multiplier *= 10
multiplier += permutation[k]
product = multiplicand * multiplier
product_digit_list = [int(char) for char in str(product)]
digits_list = list(permutation) + product_digit_list
if set(digits_list) == set(range(1,10)) and len(digits_list) == 9:
#product_sum.add((multiplicand, multiplier, product))
product_sum.add(product)
print sum(list(product_sum)) |
94e402e1f2d1d3e0dbcdbfa3a8da6156eeeabd81 | MiYoShi8225/python_program | /sec4-test-/1-test.py | 1,591 | 3.75 | 4 | import random
import string
def hangma(word):
stages = [
"",
"__________ ",
"| ",
"| | ",
"| O ",
"| /|/ ",
"| // ",
"| "
]
worng_cnt = len(stages)
count = 1
result = False
disp = ["_"] * len(word)
print(disp)
answer = list(word)
while count < worng_cnt:
user_answer = input("1文字入力:")
if user_answer in answer:
print("正解です")
leng = answer.index(user_answer)
disp[leng] = user_answer
answer[leng] = "XX"
print(disp)
else:
print("間違いです。")
print(disp)
count += 1
for i in range(0,count):
print(stages[i])
if "_" not in disp:
result = True
break
print("##answer: " + word)
if result is True:
print("##CLEAR!##")
else:
print("##NOT CLEAR##")
def GetRandomStr(num):
global word
#digits:数字 ascii_lowercase:小文字英語 ascii_uppercase:大文字英語
word_data = string.digits + string.ascii_lowercase #+ string.ascii_uppercase
print(word_data)
#random choiceは1文字(後ろに格納されているリスト?)を取り出す
#for i in range(0,num):
word = "".join([random.choice(word_data)for i in range(num)])
return word
word = str
num = int(input("Please input number:"))
hangma(GetRandomStr(num))
|
739bbb498290e61dfe55f2e39d3650723a843fc2 | KDiggory/pythondfe | /PYTHON/practice_programs/vegetation.py | 2,706 | 3.921875 | 4 | from abc import ABC, abstractmethod
class vegetation(ABC):
@abstractmethod
def location(self):
pass
@abstractmethod
def growthSpeed(self):
pass
#@abstractmethod
# def seasonal():
# pass
@abstractmethod
def latinName(self):
pass
class tree(vegetation):
def location(self, location):
self.location = location
if "tropical" in location:
print("Grows in tropical regions")
elif "temperate" in location:
print("Grows in temporate regions")
elif "cold" in location:
print("Grows in cold regions")
elif "artic" in location:
print("Grows in the artic conditions!")
else:
print("Sorry I didnt catch that, please try and enter location again")
def latinName(self, latinName):
self.latinName = latinName
print(f"The latin name for this tree is {latinName}")
def growthSpeed(self, speed):
self.speed = speed
if "fast" in self.speed:
print("This is a fast growing species of tree")
elif "medium" in self.speed:
print("This is a medium speed growing species of tree")
elif "slow" in self.speed:
print("This is a slow growing species of tree")
else:
print("Sorry I didnt catch that, please try and speed of growth again")
#def seasonal(self, type):
#self.type = type
#if "dec" in self.type:
# print("A deciduous tree")
#elif "ever" in self.type:
# print("An evergreen tree")
# else:
# print("Sorry I didnt catch that, please try and enter seasonal type again")
#return self.type
def fruit(self, bearsFruit):
self.bearsFruit = bearsFruit
if bearsFruit == False:
print("This tree isnt a fruit tree")
elif bearsFruit == True:
print("This is a fruit tree")
else:
print("I'm not sure if that tree bears fruit")
def foliage(self, colour):
self.colour = colour
print (f"This tree has {colour} leaves")
apple = tree()
leaves = apple.foliage("light green")
fruit = apple.fruit(True)
latin = apple.latinName("Malus domestica")
growth = apple.growthSpeed("medium")
#season = apple.seasonal("deciduous")
zone = apple.location("temperate")
#class flowers():
#def __init__(self):
# def location(self):
# def growthSpeed(self):
# def prennial(self):
# def colour(self):
# def foliage(self):
#def shrubs():
# def __init__(self):
# def location():
#def growthSpeed():
#def height():
# def spiky(): |
b073c48e26f8f537e10069b6a0740b200fc64dd8 | P1R0H/itstuff | /currency_converter/currency_converter.py | 6,856 | 3.5625 | 4 | """
Currency Converter CLI
python3.5
current exchange rates are obtained by forex-python module:
https://github.com/MicroPyramid/forex-python
get forex:
% pip3 install forex-python
usage: currency_converter.py [-h] [-i [INFO]] [--amount AMOUNT]
[--output_currency OUT_CURR]
[--input_currency IN_CURR] [--file PATH]
optional arguments:
-h, --help show this help message and exit
-i [INFO], --info [INFO]
prints out known currencies
--amount AMOUNT amount of input currency to be converted, 1.0 if not
present
--output_currency OUT_CURR
output currency symbol or code, all known currencies
if not present
--input_currency IN_CURR
output currency symbol or code
--file PATH output file path
created by Andrej Dravecky
7. 4. 2018
"""
import argparse
import json
from forex_python.converter import CurrencyRates, CurrencyCodes, RatesNotAvailableError
from forex_python.bitcoin import BtcConverter
class CurrencyConverter:
"""
CurrencyConverter class
:raises ValueError in case when input currency is None or not recognized
:raises RatesNotAvailableError from forex-python module
"""
def __init__(self):
# Dictionary of symbols and matching currencies, conflicting values use alternative symbols
self.__dict = {
"$" : "USD",
"kr" : "NOK",
"¥" : "CNY",
"₪" : "ILS",
"₹" : "INR",
"R$" : "BRL",
"Kr.": "DKK",
"₺" : "TRY",
"L" : "RON",
"zł" : "PLN",
"฿" : "THB",
"Kč" : "CZK",
"RM" : "MYR",
"Fr.": "CHF",
"€" : "EUR",
"S$" : "SGD",
"R" : "ZAR",
"£" : "GBP",
"₽" : "RUB",
"Rp" : "IDR",
"₩" : "KRW",
"kn" : "HRK",
"Ft" : "HUF",
"₱" : "PHP",
"Ƀ" : "BTC",
# alternative symbols
"A$" : "AUD",
"M$" : "MXN",
"C$" : "CAD",
"NZ$": "NZD",
"HK$": "HKD",
"JP¥": "JPY",
"Ikr": "ISK",
"Skr": "SEK"
}
def print_known_currencies(self):
"""
currency information print
"""
rev_dict = {v: k for k, v in self.__dict.items()}
print("List of known currencies:", end="\n\n")
print("CODE SYMBOL CURRENCY", end="\n\n")
c = CurrencyCodes()
for code in sorted(self.__dict.values()):
of = " " * (4 - len(rev_dict[code]))
print("'{}' [{}]".format(code, rev_dict[code]), end=of)
if code == "BTC":
print("- BitCoin", end="\n")
continue
print("- {}".format(c.get_currency_name(code)), end="\n")
def __get_currency(self, arg):
if arg is None:
return None
if arg in self.__dict.values():
return arg
if arg in self.__dict.keys():
return self.__dict[arg]
raise ValueError("Currency '{}' not recognized".format(arg))
def __build_output(self, amount, inc, outc):
if inc == "BTC":
# BTC input handling
if outc is not None:
return {outc: BtcConverter().convert_btc_to_cur(amount, outc)}
# BitCoin conversion uses USD rates, amount is changed accordingly
amount = BtcConverter().convert_btc_to_cur(amount, "USD")
out_data = CurrencyRates().get_rates("USD")
out_data["USD"] = 1.0
else:
# classic input handling + add BTC
out_data = CurrencyRates().get_rates(inc)
out_data["BTC"] = BtcConverter().convert_to_btc(1, inc)
if outc is not None:
out_data = {outc: out_data[outc]}
# recalculate money amount against all rates (round to 5 places after floating point)
for key in out_data.keys():
out_data[key] = round(out_data[key] * amount, 5)
return out_data
def convert(self, amount, incurr, outcurr = None):
"""
handles currency conversion and JSON structure construction
:param amount: amount of money to be converted
:param incurr: input currency symbol or 3 letter code
:param outcurr: output currency symbol or 3 letter code, defaults to None -> pick all currencies
:return: JSON structured data as JSON dump string
"""
# check codes and get codes from symbols
input_currency = self.__get_currency(incurr)
if input_currency is None:
raise ValueError("incurr cannot be None")
output_currency = self.__get_currency(outcurr)
# creating structured data for JSON structure
in_data = {"amount": amount, "currency": input_currency}
out_data = self.__build_output(amount, input_currency, output_currency)
return json.dumps({"input": in_data, "output": out_data}, sort_keys=True, indent=4)
def prepare_parser():
"""
prepares argument parser for main function
:return: parser as ArgumentParser object
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--info", dest="info", const=True, default=False,
nargs='?', help="prints out known currencies")
parser.add_argument("--amount", type=float, default=1.0, dest="amount",
help="amount of input currency to be converted, 1.0 if not present")
parser.add_argument("--output_currency", dest="out_curr",
help="output currency symbol or code, all known currencies if not present")
parser.add_argument("--input_currency", type=str, dest="in_curr",
help="output currency symbol or code")
parser.add_argument("--file", type=str, dest="path", help="output file path")
return parser
def main():
"""
main function calls parser, calls CurrencyConverter class methods and handles output
"""
try:
args = prepare_parser().parse_args()
if args.info:
CurrencyConverter().print_known_currencies()
else:
json_dump = CurrencyConverter().convert(args.amount, args.in_curr, args.out_curr)
open(args.path, 'w').write(json_dump) if args.path is not None else print(json_dump)
# catching unrecognized currency exception
except ValueError as v:
print(v)
# catching RateNotAvailable if Forex cannot get rates for whatever reason
except RatesNotAvailableError as r:
print(r)
if __name__ == "__main__":
main()
|
33b75c886770b905b4389d0d9b36bc4cf57914ee | conormccauley1999/CompetitiveProgramming | /Kattis/candlebox.py | 361 | 3.5625 | 4 | diff = int(input())
ruth_candle = int(input())
theo_candle = int(input())
theo_age = 3
while True:
ruth_age = theo_age + diff
ruth_exp = (ruth_age * (ruth_age + 1) // 2) - 6
theo_exp = (theo_age * (theo_age + 1) // 2) - 3
if ruth_candle + theo_candle == ruth_exp + theo_exp:
print(ruth_candle - ruth_exp)
break
theo_age += 1
|
708e526b28d1aabd1221c0fa0c5da734fd776963 | YogeshwaranaPachiyappan/Python | /practice16.py | 146 | 3.59375 | 4 | from itertools import permutations
n=input()
x=int(input())
y=permutations(n,x)
z=sorted(y)
for i in z:
print(''.join(i))
print("\n")
|
4e1f19ae1becc203ce35103f0817da22cb2c43c2 | LalithK90/LearningPython | /privious_learning_code/String/String title() Method.py | 407 | 4.125 | 4 | str = "this is string example....wow!!!"
print(str.title())
# Description
#
# The method title() returns a copy of the string in which first characters of all the words are capitalized.
# Syntax
#
# Following is the syntax for title() method −
#
# str.title();
#
# Parameters
#
# NA
#
# Return Value
#
# This method returns a copy of the string in which first characters of all the words are capitalized.
|
95011a42a3522a92113c7d5d82421aed2b64b25e | nantsou/udacity-data-analyst | /proj-3-wrangle-open-street-map-data/src/get_postcode_API.py | 1,279 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# get_postcode_API.py
# Nan-Tsou Liu
"""
- The given address is assumed to be valided for the API website, which match following regex format:
ur'..市..區(.+里)?(.+鄰)?(.+路(.+段)?|.+街)(.+巷)?(.+弄)?(\d+號)'
- The return is the postal code only.
"""
import json
import requests
import time
from urllib import quote, unquote
BASE_URL = "http://zip5.5432.tw/zip5json.py?adrs="
def query_site(addr):
"""Return a json document (dictionary) if API work normally."""
r = requests.get(BASE_URL+addr)
if r.status_code == requests.codes.ok:
return r.json()
else:
r.raise_for_status()
def get_postcode(full_addr):
"""Return the postal code if exists. Otherwise, return None."""
# to avoid sending large amount requests in a short time
time.sleep(2)
# convert utf-8 string into urlencoding string
addrurl = quote(full_addr.encode('utf8'))
result = query_site(addrurl)
postcode = ''
if isinstance(result, dict):
if 'zipcode' in result:
postcode = result['zipcode']
else:
postcode = None
else:
postcode = None
return postcode
def test():
full_addr = u'臺北市大安區羅斯福路四段1號'
print get_postcode(full_addr)
if __name__ == '__main__':
test()
|
4d9f19a0b1a0f7f3a6073ff52f5a3e55a00ae5d6 | Thomas1981Lang/SmartNinja-SWD1-Lesson_09-10 | /example_00511_while_loop.py | 517 | 4.15625 | 4 | # write a while loop to check if input with following symbols *,+,-,/ is correct
# if yes exit loop
# while True:
# var = input('Bitte gib ein Symbol an')
# if '*' in var or '+' in var or '-' in var or '/' in var:
# break
# solution b
# while True:
# var = input('Bitte gib ein Symbol an')
# if var in "+-*/":
# print('ok')
# break
# solution c
while True:
var = input('Bitte gib ein Symbol an: ')
if var in ["+", "-", "*", "/"]:
print('ok')
break |
5a3ab57bc5311816089fc62366a68bf0b25c2355 | jwyx3/practices | /python/remove-duplicates-from-sorted-array.py | 352 | 3.59375 | 4 | class Solution:
"""
@param A: a list of integers
@return an integer
"""
def removeDuplicates(self, A):
if not A:
return 0
start = 0
for i in range(len(A)):
if i > 0 and A[i] == A[i - 1]:
continue
A[start] = A[i]
start += 1
return start
|
6d837927226b1ec1fcc22aa3da92012463ff0e7b | sidcarrollworks/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 584 | 4.03125 | 4 | #!/usr/bin/python3
"""
This module is used to add things
"""
def add_integer(a, b):
"""Add integer function
Args:
a: an int
b: an int
Return:
the sum of a and b
"""
if isinstance(a, float):
a = int(a)
if isinstance(b, float):
b = int(b)
if not isinstance(a, int):
raise TypeError('a must be an integer')
if not isinstance(b, int):
raise TypeError('b must be an integer')
return (a + b)
if __name__ == "__main__":
import doctest
doctest.testfile("tests/0-add_integer.txt")
|
034a5003ef0dafc955756f3225d0f0df6e92ac56 | sdas13/DSA-Problems | /string/easy/12. reverse-letters.py | 898 | 3.875 | 4 | """
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
https://leetcode.com/problems/reverse-only-letters/solution/
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
"""
class Solution:
def reverseOnlyLetters(self, S: str) -> str:
i = 0
j = len(S) - 1
S = list(S)
while i < j:
if not S[i].isalpha():
i += 1
elif not S[j].isalpha():
j -= 1
else:
S[i], S[j] = S[j], S[i]
i += 1
j -= 1
return ''.join(S)
# print(Solution().reverseOnlyLetters('ab-cd'))
# print(Solution().reverseOnlyLetters('a-bC-dEf-ghIj'))
print(Solution().reverseOnlyLetters('Test1ng-Leet=code-Q!'))
|
760d9324070f8ce140f5e048b377ef75cffdc4ca | dvbridges/webKrawler | /webkrawler.py | 6,998 | 3.515625 | 4 | #!/usr/bin/python3
# Script Name : webKrawler.py
# Author : David Bridges
# Email : david-bridges@hotmail.co.uk
# Created : 11th October 2016
# Last Modified : 16th October 2016
# Version : 1.0
# Description : Web crawler and search engine
import urllib.request
def get_page(url):
"""
Get webpage and decode bytes to string
"""
try:
if url == "http://www.udacity.com/cs101x/index.html":
return ('<html> <body> This is a test page for learning to crawl! '
'<p> It is a good idea to '
'<a href="http://www.udacity.com/cs101x/crawling.html">learn to '
'crawl</a> before you try to '
'<a href="http://www.udacity.com/cs101x/walking.html">walk</a> '
'or <a href="http://www.udacity.com/cs101x/flying.html">fly</a>. '
'</p> </body> </html> ')
elif url == "http://www.udacity.com/cs101x/crawling.html":
return ('<html> <body> I have not learned to crawl yet, but I '
'am quite good at '
'<a href="http://www.udacity.com/cs101x/kicking.html">kicking</a>.'
'</body> </html>')
elif url == "http://www.udacity.com/cs101x/walking.html":
return ('<html> <body> I cant get enough '
'<a href="http://www.udacity.com/cs101x/index.html">crawling</a>! '
'</body> </html>')
elif url == "http://www.udacity.com/cs101x/flying.html":
return ('<html> <body> The magic words are Squeamish Ossifrage! '
'</body> </html>')
elif url == "http://top.contributors/velak.html":
return ('<a href="http://top.contributors/jesyspa.html">'
'<a href="http://top.contributors/forbiddenvoid.html">')
elif url == "http://top.contributors/jesyspa.html":
return ('<a href="http://top.contributors/elssar.html">'
'<a href="http://top.contributors/kilaws.html">')
elif url == "http://top.contributors/forbiddenvoid.html":
return ('<a href="http://top.contributors/charlzz.html">'
'<a href="http://top.contributors/johang.html">'
'<a href="http://top.contributors/graemeblake.html">')
elif url == "http://top.contributors/kilaws.html":
return ('<a href="http://top.contributors/tomvandenbosch.html">'
'<a href="http://top.contributors/mathprof.html">')
elif url == "http://top.contributors/graemeblake.html":
return ('<a href="http://top.contributors/dreyescat.html">'
'<a href="http://top.contributors/angel.html">')
elif url == "A1":
return '<a href="B1"> <a href="C1"> '
elif url == "B1":
return '<a href="E1">'
elif url == "C1":
return '<a href="D1">'
elif url == "D1":
return '<a href="E1"> '
elif url == "E1":
return '<a href="F1"> '
except:
return ""
return ""
# try:
# response=urllib.request.Request(url_req, headers={'User-Agent': 'Mozilla/5.0'})
# with urllib.request.urlopen(response) as f:
# return f.read().decode('utf-8')
# except UnicodeDecodeError:
# print("File not utf-8 encoded, switching to cp1252 decoding")
# try:
# response=urllib.request.Request(url_req, headers={'User-Agent': 'Mozilla/5.0'})
# with urllib.request.urlopen(response) as f:
# return f.read().decode('cp1252')
# except UnicodeDecodeError:
# print("File not cp1252 encoded, switching to Latin1 decoding")
# response=urllib.request.Request(url_req, headers={'User-Agent': 'Mozilla/5.0'})
# with urllib.request.urlopen(response) as f:
# return f.read().decode('Latin-1')
def get_next_target(s):
"""
Find all links in a html file and return url and last known endpoint
"""
start_link=s.find("<a href=")
# If no links, return None, position 0
if start_link==-1:
return None, 0
# Parse URL from HTML
start_quote=s.find('"', start_link)
end_quote=s.find('"',start_quote+1)
url=s[start_quote+1:end_quote]
#Return URL and last known end position
return url, end_quote
def get_all_links(page):
"""
Print all links in a html file
"""
links=[]
while True:
# If URL exists, get the URL from get_next_target
url, end_pos=get_next_target(page)
if url:
links.append(url)
page=page[end_pos:]
else: break
return links
def union(old,new):
"""
Union function checks whether page is in tocrawl list.
If not in list, append
"""
for i in new:
if i not in old:
old.append(i)
def krawl_web(seed, max_pages, max_depth):
"""
Maintains list of urls to crawl. Max_pages determines number of unique pages to search, and max_depth determines depth
Operations:
1) Fill tocrawl with all seed links
2) while tocrawl has urls and depth < max_depth, loop
3) if page is not in previously crawled and crawled is shorter than max pages
- fill new_depth with all urls from each url link in tocrawl. Continue until tocrawl is empty
- add pages visited to crawled
4) If tocrawl is empty, fill tocrawl with links from next_depth. Depth +=1. This advances crawler to next depth
"""
tocrawl=get_all_links(get_page(seed))
crawled=[]
next_depth=[]
index={}
depth=0
graph={}
while tocrawl and max_depth >=1:
page=tocrawl.pop()
if page not in crawled and len(crawled)<=max_pages:
content=get_page(page)
add_page_to_index(index, page, content)
outlinks=get_all_links(content)
graph[page]=outlinks
union(next_depth,outlinks)
crawled.append(page)
if not tocrawl:
tocrawl,next_depth=next_depth,[]
max_depth-=1
return index,graph
def add_page_to_index(index, url, content):
"""
Takes all words from webpage, and adds to index linking URL to keyword
"""
words = content.split()
for word in words:
add_to_index(index, word, url)
def add_to_index(index, keyword, url):
"""
Takes all words from webpage, and adds to index linking URL to keyword
"""
if keyword in index:
index[keyword].append(url)
else:
index[keyword]=[url]
def lookup(index, keyword):
"""
Looks up keyword in index, returns URL if found, None if not found
"""
if keyword in index:
return index[keyword]
return None
def compute_ranks(graph):
"""
Function for computing ranked web pages
"""
d = 0.8 # damping factor
numloops=10
ranks={}
npages=len(graph)
for page in graph:
ranks[page]=1.0/npages
for i in range(0,numloops):
newranks={}
for page in graph:
newrank=(1-d)/npages
for node in graph:
if page in graph[node]:
newrank=newrank+d*(ranks[node]/len(graph[node]))
newranks[page]=newrank
ranks=newranks
return ranks
def get_topRank(rank):
"""
Function for sorting and returns highest ranked pages, and ranking
"""
maxRank=[]
best=[]
for page in rank:
maxRank.append(rank[page])
maxRank.sort(reverse=True)
for page in rank:
if rank[page]==maxRank[0]:
best.append(page)
return best, maxRank[0]
def Main():
seed='http://www.udacity.com/cs101x/index.html'
index,graph = krawl_web(seed,10,6)
# Look up page
print ("The word {} can be found at {}\n".format('good',lookup(index,'good')))
# Get page ranks
ranks = compute_ranks(graph)
print ("The page ranks are:\n {}\n".format((ranks)))
# Get highest ranking page
highest = get_topRank(ranks)
print("The highest ranking pages from the search are: \n{}\n".format(highest))
if __name__=='__main__':
Main() |
6ee723ddfa528e8af6e75af2929182eb58e63e46 | Nthnlkhy-sys/Python-exercise | /suit.py | 928 | 3.875 | 4 | while True:
playerone = input("Choose your fighter playerone: ")
playertwo = input("Choose your fighter plyaertwo: ")
a= "scissor"
b= "paper"
c= "rock"
if playerone == a and playertwo == a:
print("Draw")
elif playerone == a and playertwo == b:
print("Player One Win")
elif playerone == a and playertwo == c:
print("Player Two wins")
elif playerone == b and playertwo == a:
print("player two Wins")
elif playerone == b and playertwo == b:
print("draw")
elif playerone == b and playertwo == c:
print("player one win")
elif playerone == c and playertwo == a:
print("Player one win")
elif playerone == c and playertwo == b:
print("Player two wins")
elif playerone == c and playertwo == c:
print("draw")
ans = input("Want to replay? ")
if ans == "yes":
continue
else:
break |
85198258c91cf99d84e9682adaaadf884b83bbb6 | kiransivasai/hackerearth_problems | /indent_ruby.py | 152 | 3.640625 | 4 | a=''
while True:
try:
s=input()
if(s==''):
break
a+=s+'\n'
except:
break
print(a.replace(' ',' '))
|
7dff561064b87ff10104f4c31745f9594262b3d7 | Noaarhk/algorithm_pr | /programmers_pr/h_index.py | 1,587 | 3.625 | 4 | class My_Solution():
def is_True(self, arr, h):
bigger_num = []
for num in arr:
if num >= h:
bigger_num.append(num)
if len(bigger_num) >= h:
return True
else:
return False
def is_True_2(self, arr, h):
if len(list(filter(lambda x: x >= h, arr))) >= h:
return True
else:
return False
def solution(self, citation):
cnt = 0
while True:
if len(citation) == 1 or int("".join(map(str, citation))) == 0:
return 0
elif self.is_True_2(citation, cnt):
cnt += 1
else:
cnt -= 1
break
return cnt
def solution_2(self, citation):
cnt = 0
while True:
if self.is_True_2(citation, cnt):
cnt += 1
else:
cnt -= 1
break
return cnt
class Other_Solution():
def counting(self, l, n):
return len(list(filter(lambda x: x >= n, l)))
def solution(self, citations):
answer = 0
for i in range(max(citations)):
if self.counting(citations, i) >= i:
answer = i
else:
break
return answer
if __name__ == '__main__':
citation = [3, 0, 6, 1, 5]
result = 3
solution_1 = My_Solution()
solution_2 = Other_Solution()
print(solution_1.solution(citation))
print(solution_1.solution_2(citation))
print(solution_2.solution(citation))
|
3bbb6eb338bd7a67384871d82e39471aa2c4ee3e | moontree/leetcode | /version1/201_Bitwise_And_Of_Numbers_Range.py | 917 | 3.984375 | 4 | """
Given a range [m, n] where 0 <= m <= n <= 2147483647,
return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
"""
def range_bitwise_and(m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
# res = m & n
# if m == n:
# return res
# rest = len(bin(n - m)) - 2
# res = res >> rest << rest
# return res
i = 0
while m != n:
n >>= 1
m >>= 1
i += 1
return m << i
examples = [
{
"m": 5,
"n": 7,
"res": 4
}, {
"m": 4,
"n": 7,
"res": 4
}, {
"m": 0,
"n": 2147483647,
"res": 0
}, {
"m": 6,
"n": 7,
"res": 6
}, {
"m": 57,
"n": 63,
"res": 56
}
]
for example in examples:
print range_bitwise_and(example["m"], example["n"])
|
e460e206e82edd863d7c806fec1fe9ebe9f50318 | Dysio/ZadaniaDodatkowe | /closest_power.py | 517 | 4.0625 | 4 | def closest_power(base, num):
"""
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
Returns the exponent.
"""
pass
if __name__ == '__main__':
assert closest_power(4, 12) == 2
assert closest_power(3, 12) == 2
assert closest_power(4, 1) == 0 |
7e4397c15183bc25d05c023beb7a059cb15c2a99 | agalyaabarna/abarna | /ag.py | 157 | 3.9375 | 4 | A1,B2,C3=input().split()
if (A1 > B2) and (A1 > C3):
largest = A1
elif (B2 > A1) and (B2 > C3):
largest = B2
else:
largest = C3
print('',largest)
|
2bd045440326c2ee706d6b81bab17d95e959b1cf | hieubz/Crack_Coding_Interview | /leetcode_2/easy/third_largest_element.py | 479 | 4.4375 | 4 | """
given an array of n integers, find the third largest element
"""
def get_third_largest_ele(arr):
max1, max2, max3 = arr[0], arr[0], arr[0]
for num in arr:
if num > max1:
max3 = max2
max2 = max1
max1 = num
elif num > max2:
max3 = max2
max2 = num
elif num > max3:
max3 = num
return max3
arr = [2, 4, 5, 6, 8, 9, 10, 17]
num = get_third_largest_ele(arr)
print(num) |
797f33de1a64d5e33dfc6b7dc588ddb24afdddc6 | DomFC/alpha-zero-general | /checkers_terminal.py | 1,258 | 3.625 | 4 | from string import ascii_uppercase
from checkers.Board import _1D_to_2D_board
DIM = 8
whitespace_prefix = ' ' * 10
coordinates_list = list(ascii_uppercase)[:DIM]
coordinates_dict = {letter:ind for ind, letter in enumerate(coordinates_list)}
upper_lines = '┌' + ('───┬' * (DIM - 1)) + '───┐'
middle_lines = '├' + ('───┼' * (DIM - 1)) + '───┤'
bottom_lines = '└' + ('───┴' * (DIM - 1)) + '───┘'
def char_to_print(c):
if c == 1:
return 'w'
if c == 2:
return 'W'
if c == -1:
return 'b'
if c == -2:
return 'B'
return ' '
def display(_1D_board):
board = _1D_to_2D_board(_1D_board)
print()
# Print horizontal coordinates
print(whitespace_prefix, end=' ')
for coord in coordinates_list:
print(' {} '.format(coord), end='')
print()
print(whitespace_prefix, ' ', upper_lines)
for y in range(DIM):
print(whitespace_prefix, coordinates_list[y], end=' ')
for x in range(DIM):
print('│ ', char_to_print(board[y][x]), ' ', end='', sep='')
print('│')
if y != DIM - 1:
print(whitespace_prefix, ' ', middle_lines)
print(whitespace_prefix, ' ', bottom_lines)
|
8e735502edcdd91d5de13a32551f02842560fd90 | abhishek-sengar/Snake-Water-Gun-game | /snake_water_game.py | 1,039 | 3.5 | 4 | # Snake-Water-Gun-game
import random
c=0
p=0
for i in range(5):
a=random.choice(['s','w','g'])
n=input('Enter s: snake w: water g: gun\n')
if(n=='s' or n=='w' or n=='g'):
if(a=='s'):
if(n=='g'):
print('You Won ','cpu choice ',a)
p=p+10
elif(n=='w'):
print('You Lose ','cpu choice ',a)
c=c+10
else:
print('Tie ','cpu choice ',a)
elif(a=='w'):
if(n=='s'):
print('You Won ','cpu choice ',a)
p=p+10
elif(n=='g'):
print('You Lose ','cpu choice ',a)
c=c+10
else:
print('Tie ','cpu choice ',a)
else:
if(n=='w'):
print('You Won ','cpu choice ',a)
p=p+10
elif(n=='s'):
print('You Lose ','cpu choice ',a)
c=c+10
else:
print('Tie ','cpu choice ',a)
else:
print('Enter Valid Input')
print('Your Final Score ',p)
print('cpu final score ',c)
if(p>c):
print('You won this series by',p-c,' points')
elif(p<c):
print('You lose this series by',c-p,' points')
else:
print('Series Tie')
|
c28fb6feb6aa5438761067e21bb9b46f7d93796f | karthikpalameri/PythonLearn | /Strings/string_manipulation.py | 3,394 | 4.09375 | 4 | from builtins import print, set
Str = "something is \"fagfag\" "
first="nyc test temp"[5:-5]
second=Str[0]
print(Str)
print(first)
print(second)
"""
STRING FUNCITONS
len()
lower()
upper()
str()
"""
stri="this is MiXed Case"
print("**************************************")
print("converting to lower case:"+stri.lower())
print("converting to Upper case:"+stri.upper())
print("len(str) and converting it to string " + str(len(stri)))
"""
String concatination
"""
print("concatinating->""hell"+" "+"world")
"""
string replace
"""
print("string replace...")
a="1abc2abc3abc4abc"
print("a->"+a)
print("Replacing 1st 2 instance only using a.replace(\"abc\",\"xyz\",2) ->"+a.replace("abc","xyz",2))
print("Replacing all instance using a.replace(\"abc\",\"xyz\",-1) ->"+a.replace("abc","xyz",-1))
"""
Sub-String
"""
print("Sub-String...")
a="1abc2abc3abc4abc"
#0123456789
print("a->"+a)
print("Substing a[0]->"+a[0])
print("Substing a[-1] will print last chatacter->"+a[-1])
print("Substing a[1:5] will print from 1st index chatacter to 4th index character leaving the 5th index character->"+a[1:5])
"""
Sub-String with step
Starting index is inclusive
Ending index is exclusive
"""
print("Sub-String with STEP...")
print("a->"+a)
print("Substing with STEP a[1:5:1]->"+a[1:5:1])
print("Substing with STEP a[1:5:2]->"+a[1:5:2])
print("Substing with STEP a[1:5:3]->"+a[1:5:3])
"""
Slicing
slicing is quick and used in lot of programming
"""
print("Slicing...")
a="This Is A Sting"
print("a->"+a)
print("Slicing with a[:]->"+a[:])
print("Slicing with a[1:]->"+a[1:])
print("Slicing with a[:6]->"+a[:6])
print("Slicing with a[len(a)-1]->"+a[len(a)-1])
print("Slicing with a[-1]->"+a[-1])
print("Slicing with a[-2]->"+a[-2])
print("Slicing with steps...")
print("a->"+a)
print("Slicing with Steps a[::1]->"+a[::1])
print("Slicing with Steps a[::2]->"+a[::2])
print("STRING REVERSE || Slicing with Steps a[::-1]->"+a[::-1])
print("Slicing with Steps a[::-2]->"+a[::-2])
print("String are immutable . It does not store after manipulating->"+a[0])
"""
we cant do a[0]="x" because strings
"""
"""
String Formatting
"""
print("String Formatting ...")
city = "nyc"
event = "show"
print("welcome to "+city+"and enjoy the "+event)
#print with
print("welcome to %s and enjoy the %s" %(city,event))
"""
LISTS
"""
print("*"*60)
print("List...")
cars = ["benz", "honda", "audi"]
empty_list = []
print(empty_list)
num_list = [1, 2, 3]
sum_num = num_list[0] + num_list[1]
print("".join(str(num_list)))
print(" Sum of first two values in the list->"+str(sum_num))
print("cars -> %s"%(cars))
cars[0] = "bmw"
print("Assigning bmw to index 1 and replacing benz, cars[1]=\"bmw\" -> %s" %(cars))
"""
Printing a list
"""
print("*"*60)
print("printing a list using for loop->")
for x in range(len(cars)):
print (cars[x])
print("printing a list using loops printing the list using * operator seperated by space print(*cars) ->")
print(*cars)
print("printing a list using loops printing the list using * operator seperated by comma print(*cars, sep=", ") ->")
print(*cars, sep=", ")
print("printing a list using loops printing the list using * operator seperated by \n print(*cars, sep=", ") ->")
print(*cars, sep="\n")
print("printing the list using join function \" \".join(cars)->"+" ".join(cars))
print("printing the list using join function \" \".join(cars)->"+"-".join(cars))
|
a91a47e11997b4ed4925753e2fbb62002755351a | GuySadoun/HW3_computer_network_event_simulator | /main.py | 4,686 | 3.796875 | 4 | import sys
import numpy as np
import random as rand
class Simulation:
def __init__(self, T, M, Lambda, Mu, probs):
self.total_time = T
self.num_of_vaccines = M
self.lambda_arrival = Lambda
self.mu_service = Mu
self.probabilities = probs
self.q_len = len(probs)
self.clock = 0.0 # simulation clock
self.customers_in_q = 0 # customers in queue - First in q gets service
self.num_arrivals = 0 # total number of arrivals
self.t_arrival = self.gen_next_arrival() # time of next arrival
self.t_departure = float('inf') # time of next departure
self.queues_len_time = np.zeros(shape=self.q_len, dtype=float) # current state of each station
self.current_q_id = self.choose_vaccine() # vaccine chosen by costumers/current queue
self.lost_customers = 0 # customers who left without service
self.t_last_vaccine = 0 # time of last vaccine given
def simulate(self):
while self.clock <= self.total_time:
self.time_adv()
self.print_result()
def time_adv(self):
t_next_event = min(self.t_arrival, self.t_departure)
t_waiting = (t_next_event - self.clock)
self.clock = t_next_event
self.queues_len_time[self.customers_in_q] += t_waiting
if self.clock == self.t_arrival:
self.arrival()
else:
self.depart()
def arrival(self):
self.num_arrivals += 1
self.t_arrival += self.gen_next_arrival()
if self.customers_in_q == 0: # no one is waiting or getting service
self.current_q_id = self.choose_vaccine()
self.customers_in_q += 1
self.t_departure = self.clock + self.gen_service_time()
elif self.customers_in_q < self.q_len:
assert self.customers_in_q > 0
prob = np.random.uniform(low=0.0, high=1.0)
if prob < self.probabilities[self.customers_in_q]:
self.customers_in_q += 1
else:
self.lost_customers += 1
def depart(self):
self.t_last_vaccine = self.clock
self.customers_in_q -= 1
if self.customers_in_q > 0:
self.t_departure = self.clock + self.gen_service_time()
else:
self.t_departure = float('inf')
def print_result(self):
served = self.num_arrivals - self.lost_customers
total_waiting_time = sum((self.queues_len_time[x]*(x-1)) for x in range(2, self.q_len))
total_service_time = sum(self.queues_len_time[1:])
total_time = sum(self.queues_len_time)
X, Y, T, T0 = served, self.lost_customers, self.t_last_vaccine, self.queues_len_time[0]
T_w = total_waiting_time / served
T_s = total_service_time / served
lambda_A = served / total_time
print(f'{X} {Y} {"%.2f" % T} {"%.3f" % self.queues_len_time[0]}', end=' ')
for i in range(1, self.q_len): # print A_Ti's including A_T0
print(f'{"%.3f" % (self.queues_len_time[i] / self.num_of_vaccines)}', end=' ')
print(f'{"%.6f" % (self.queues_len_time[0] / total_time)}', end=' ')
for i in range(1, self.q_len): # print Z_Ti's
print(f'{"%.6f" % ((self.queues_len_time[i] / total_time) / self.num_of_vaccines)}', end=' ')
print(f'{"%.7f" % T_w} {"%.7f" % T_s} {"%.2f" % lambda_A}')
# print(f'X: {X} Y: {Y} T\': {"%.2f" % T}', end=' ')
# print(f'T_0: {"%.3f" % self.queues_len_time[0]}', end=' ')
# for i in range(1, self.q_len): # print A_Ti's including A_T0
# print(f'T_{i}: {"%.3f" % (self.queues_len_time[i]/self.num_of_vaccines)}', end=' ')
# print(f'Z_0: {"%.6f" % (self.queues_len_time[0]/total_time)}', end=' ')
# for i in range(1, self.q_len): # print Z_Ti's
# print(f'Z_{i}: {"%.6f" % ((self.queues_len_time[i]/total_time)/self.num_of_vaccines)}', end=' ')
# print(f'T_w: {"%.7f" % T_w}', end=' ')
# print(f'T_s: {"%.7f" % T_s}', end=' ')
# print(f'Lambda_mean: {"%.2f" % lambda_A}')
def gen_next_arrival(self): # function to generate arrival times using inverse transform
return rand.expovariate(self.lambda_arrival)
def gen_service_time(self):
return rand.expovariate(self.mu_service)
def choose_vaccine(self):
return np.random.randint(low=0, high=self.num_of_vaccines)
def main():
# args = sys.argv[1:]
args = [1000, 2, 60, 30, 1, 0.8, 0.5, 0]
s = Simulation(float(args[0]), int(args[1]), float(args[2]), float(args[3]), np.array(args[4:], dtype=float))
s.simulate()
if __name__ == '__main__':
main()
|
3bd118b0a4f91d6f4f16509ede44260443b7ca13 | JensPfeifle/a-tale-of-event-loops | /04_timers.py | 1,985 | 3.59375 | 4 | # sleeping and timers
from heapq import heappop, heappush
from time import sleep as _sleep
from timeit import default_timer
from types import coroutine
# global clock
clock = default_timer
@coroutine
def sleep(seconds):
# awaitable which sleeps for a certain number of seconds
print(" sleep: about to sleep")
yield ("sleep", seconds) # "please reschedule me in n seconds"
print(" sleep: back from sleep")
async def main():
print(" main: started")
await sleep(3)
print(" main: finished")
def run_until_complete(task):
tasks = [(task, None)]
timers = [] # sleeping tasks
while tasks or timers:
print("___________________________________")
if not tasks:
# sleep until we have to wake the first timer
_sleep(max(0.0, timers[0][0] - clock()))
# schedule tasks when their timer has elapsed
# timers[0] accesses first item of priority queue
while timers and timers[0][0] < clock():
_, task = heappop(timers)
tasks.append((task, None))
queue, tasks = tasks, []
for task, data in queue:
try:
print(f"loop: send {data} into {task.__name__}")
data = task.send(data)
print(f"loop: received {data} from {task.__name__}")
except StopIteration as res:
pass
except Exception as exp:
# catch all to prevent loop exit
print(repr(exp))
else:
if data:
req, _ = data
if req == "sleep":
delay = data[1]
# don't reschedule right away, but set a timer instead
heappush(timers, (clock() + delay, task))
else:
# reshedule the task
tasks.append((task, None))
if __name__ == "__main__":
run_until_complete(main())
|
cc904f77502acddb55af04fd55427be9b08127da | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/projecteuler/euler026.py | 1,189 | 3.640625 | 4 | #!/usr/bin/env python
"""
Solution to Project Euler Problem 26
http://projecteuler.net/
by Apalala <apalala@gmail.com>
(cc) Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
A unit fraction contains 1 in the numerator. The decimal representation of the
unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be
seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle
in its decimal fraction part.
"""
def long_division_pattern(d):
seen = {}
r = 1
k = 0
while r:
k += 1
seen[r] = k
r = r * 10 % d
if r in seen:
return k - seen[r]
return 0
def find_longest_recurring(m):
return max((long_division_pattern(i), i) for i in range(2, m))
def test():
assert 7 == find_longest_recurring(10)[1]
def run():
print(find_longest_recurring(1000)[1])
if __name__ == "__main__":
test()
run()
|
f1bb08e7fa03c9722902142894b76a3d7e93b2e4 | momochang/animate-database | /delete.py | 646 | 3.734375 | 4 | #delete sql query
def del_num(table_name, col_name):
sql = """Delete from """ + table_name
del_whe = input("Enter your requirement(where): ")
#sql = sql + " " + "where" + " " + sel_whe
sql = sql + " " + "where" + " " + del_whe
return sql
#delete your database data
def delete(cursor, mysqldb, table_name, col_na):
print("語法: Delete table_name where xxx")
sql = del_num(table_name, col_na)
try:
print(sql)
cursor.execute(sql)
mysqldb.commit()
print("Delete successul")
except:
print("Delete error")
mysqldb.rollback()
|
ae52cb6a96bb0106123c45d57826b5c4f72d8387 | gustavobr44/metodos-numericos-ii | /Tarefa 3/testeNewtonCotes.py | 867 | 3.703125 | 4 | from integraisNewtonCotes import iterar
import math
a = 0
b = 1
e = 10**-6
f1 = lambda x: (2*x)**3 #Resposta 2
f2 = lambda x: math.cos(4*x) #Resposta -0.1892006
f3 = lambda x: (math.sin(2*x) + 4*(x**2) + 3*x)**2 #Resposta 17.8764703
f4 = lambda x: (x + (3*x)**2 - math.cos(4*x**1.5) + math.e**(x/3)) #Resposta 4.62323
f = [f1, f2, f3, f4]
for i in range(len(f)):
print("Cálculo da integral da função f", i + 1, " com erro de ", e, ":", sep='')
print(" Filosofia Fechada:")
for j in range(1, 5):
I, div = iterar(f[i], a, b, e, j, 0)
print(" Grau ", j, " com ", div, " divisões: ", round(I, 7), sep="")
print(" Filosofia Aberta:")
for j in range(1, 5):
I, div = iterar(f[i], a, b, e, j, 1)
print(" Grau ", j, " com ", div, " divisões: ", round(I, 7), sep="")
print() |
b6d36081a120f5f4c0f1f6f5d44c2653cd239994 | myleneh/code | /oreilly_python1/greeting.py | 342 | 4.34375 | 4 | #
# greeting.py
#
"""This program prompts user for first and last names
and prints a greeting."""
first = input("Please enter your first name: ")
last = input("Please enter your last name: ")
# This capitalizes the first letters.
firstcap = first.capitalize()
lastcap = last.capitalize()
print("I am pleased to meet you,",firstcap,lastcap) |
22d606ad0cc2cccff683d3366e18056e54ee8418 | ultra-boy3/CMPM-146-Assignment2 | /P__export/src/p2_pathfinder.py | 3,329 | 3.828125 | 4 | import heapq
def find_path (source_point, destination_point, mesh):
#Mesh is a dictionary with box dimensions and lists of adjacent boxes
#Source and dest are POINTS! Not boxes!
"""
Searches for a path from source_point to destination_point through the mesh
Args:
source_point: starting point of the pathfinder
destination_point: the ultimate goal the pathfinder must reach
mesh: pathway constraints the path adheres to
Returns:
A path (list of points) from source_point to destination_point if exists
A list of boxes explored by the algorithm
"""
#First thing we want to try is returning a list of boxes
"""
Pseudocode
Scan through the boxes in mesh to find source_box and dest_box
for each box in mesh:
if source_point(x) is between top and bottom right x
if source_point(y) is between top and bottom right y
source_box = this box
create a priority queue, push source_point
create a dictionary came_from containing previous locations
while priority queue is not empty:
current_box = queue.pop
if current_box = destination
create list path_taken
using came_from, starting at the desintation,
add boxes to path_taken
return path_taken
for each neighbor of current_box (using mesh)
(There are no distances so we don't have to worry about that rn)
if neighbor is not in came_from:
came_from.append(neighbor)
queue.push(neighbor)
(did not find a path)
return None
"""
source_box = (0, 0, 0, 0)
dest_box = (0, 0, 0, 0)
for box in mesh['boxes']:
#print(box)
if source_point[0] >= box[0] and source_point[0] <= box[1]:
if source_point[1] >= box[2] and source_point[1] <= box[3]:
source_box = box #This might not get the key
if destination_point[0] >= box[0] and destination_point[0] <= box[1]:
if destination_point[1] >= box[2] and destination_point[1] <= box[3]:
dest_box = box #This might not get the key
#for box in mesh['adj']:
#print(box)
#print(" this a box")
#The keys for both parts of the mesh are quadruples
path = []
boxes = {}
path_taken = []
frontier = []
heapq.heapify(frontier) #Not sure but a different queue type might be better?
heapq.heappush(frontier, source_box)
boxes[source_box] = None
while(len(frontier) > 0):
current_box = heapq.heappop(frontier)
if current_box == dest_box:
# Insert current_box into boxes, w/ previous as value
while(current_box != None):
path_taken.append(current_box)
current_box = boxes[current_box] #destination point should already have something in boxes
break
neighbors = mesh['adj'][current_box] #Hopefully this gets the neighbor list?
for neighbor in neighbors:
if(neighbor not in boxes):
boxes[neighbor] = current_box #Add neighbor to list of boxes
heapq.heappush(frontier, neighbor)
print(path_taken)
return path, path_taken #Replaced boxes.keys() w/ path_taken
|
91b9d2f85d1246c9a32ded0bb22f4b5f8b3e0007 | muskan13-tech/python | /hello1.py | 214 | 4.0625 | 4 | n=int(input("Enter the number of your choice : "))
i=0
total=0
while i<=n :
i = i+1
total += i
print(total)
n=int(input("Enter any number : "))
total = 0
for i in range(1,n):
print(i)
|
6b3d21bdec46036c29795a8b4a76ae7a6b43cd44 | Svinci131/data_cube_code_challenge | /src/flight_data_calculator.py | 1,600 | 3.8125 | 4 | """
Contains functions for calculating the distance
between two locations with the Haversine Formula and
the approx. amount of time it would take a plane to fly
the distance.
"""
import math
from src.google_utils import get_geocode
def _kMtoUSNauticalMiles(num):
return num / 1.852
def _deg2rad(deg):
return deg * (math.pi / 180)
def _getDistanceFromLatLonInMeters(lat1, lon1, lat2, lon2):
R = 6371 # Radius of the earth in km
dLat = _deg2rad(lat2 - lat1) # deg2rad below
dLon = _deg2rad(lon2 - lon1)
a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(_deg2rad(lat1)) * \
math.cos(_deg2rad(lat2)) * math.sin(dLon / 2) * math.sin(dLon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance_in_km = R * c # Distance in km
distance_in_m = int(distance_in_km) * 1000
return distance_in_m
def get_flight_duration_in_secs(distance_in_m):
"""
Takes is the distance in meters and
calculates the approx duration of a flight in secs
assuming an average cruising speed is 878 km/h
(approx. 224 m/s).
:type distance: int
:rtype: int
"""
approx_mps = 224
duration_in_secs = distance_in_m / approx_mps
return duration_in_secs
def get_flight_distance_in_meters(origin, dest):
origin = get_geocode(origin)
dest = get_geocode(dest)
lon1 = origin.get('lng', None)
lon2 = dest.get('lng', None)
lat1 = origin.get('lng', None)
lat2 = dest.get('lng', None)
R = 3440
dInKm = _getDistanceFromLatLonInMeters(lat1, lon1, lat2, lon2)
return dInKm
|
3a920ce3d3b11b79daadaa11872885967f9467ea | vidhyaveera/vidhyaveeradurai | /vowels1.py | 177 | 3.625 | 4 | n=input()
l=list(n)
for i in range(0,len(n)):
if n[i]=='a' or n[i]=='e' or n[i]=='i' or n[i]=='o'or n[i]=='u':
print("yes")
break
else:
print("no")
|
f5feffcb62ad430d69fee4e26c291766c0779dac | waltermblair/CSCI-220 | /getNumbers.py | 861 | 3.859375 | 4 | import math
def getNumbers():
nums=[]
xStr=input("Enter a number (<Enter> to quit) >> ")
while xStr != "":
x=eval(xStr)
nums.append(x)
xStr=input("Enter a number (<Enter> to quit) >> ")
return nums
def mean(nums):
sum=0.0
for x in nums:
sum=sum+x
return sum/len(nums)
def stdev(nums,avg):
sumDevSq=0.0
for num in nums:
dev = avg-num
sumDevSq=sumDevSq+dev**2
return math.sqrt(sumDevSq/len(nums)-1)
def median(nums):
nums.sort()
if len(nums)%2==0:
return (nums[len(nums)//2-1]+nums[len(nums)//2+1])/2
else:
return nums[len(nums)//2]
def main():
data=getNumbers()
print("The mean is ",mean(data))
print("The standard deviation is ",stdev(data,mean(data)))
print("The median is ",median(data))
if __name__=="__main__": main()
|
4be8c5f6150c3151f43a149fd3ff93a11bf2de2c | stevehb/exp | /PyRandomNumbers/PyRandomNumbers.py | 679 | 3.9375 | 4 | #!/usr/bin/python
import random
def getRandInt(lo, hi):
diff = hi - lo
retVal = int(random.random() * diff) + lo
return retVal
remaining = 3
hasWon = False;
secretNumber = getRandInt(1, 10)
print "~~~RandomNumbers~~~"
for i in range(3, 0, -1):
print "You have " + str(i) + " guesses left."
guess = raw_input("Guess: ")
guess = int(guess)
if guess == secretNumber:
print "You Win!"
hasWon = True
break
elif guess < secretNumber:
print "Too low."
else:
print "Too high."
print ""
if hasWon == True:
print "Congrats"
else:
print "Too bad. The secret number was " + str(secretNumber) + "."
|
743d09feb36db9b73faff9198276e88e1e66d393 | anna-bogatko/PycharmProjects | /PythonTutorial/controlstructure/boolean-precedence.py | 453 | 3.5625 | 4 | """
1. not
2. and
3. or
"""
bool_output = True or not False and False
"""
True (not False)
True and False --> False
True or False --> True
"""
print(bool_output)
bool_output1 = 10 == 10 or not 10 > 10 and 10 > 10
"""
True (not False)
True and False --> False
True or False --> True
"""
print(bool_output1)
bool_output2 = (10 == 10 or not 10 > 10) and 10 > 10
"""
True (not False)
True or True --> True
True and False --> False
"""
print(bool_output2) |
88b3e42e47fe8708e9b307a9a3803ba0cc5e41ac | Boberkraft/Data-Structures-and-Algorithms-in-Python | /chapter7/C-7.37.py | 917 | 3.609375 | 4 | """
Implement a function that accepts a PositionalList L of n integers sorted
in nondecreasing order, and another value V, and determines in O(n) time
if there are two elements of L that sum precisely toV. The function should
return a pair of positions of such elements, if found, or None otherwise
"""
from PositionalList import PositionalList
def find_pair(l, v):
start, end = l.first(), l.last()
while 1:
start_val, end_val = start.element(), end.element()
if end_val > v:
end = l.before(end)
elif end_val + start_val < v:
start = l.after(start)
if start is None:
return None
elif end_val + start_val > v:
return None
else:
print('its a match', end_val, start_val)
return end_val, start_val
a = PositionalList()
for b in range(0,100,3):
a.add_last(b)
find_pair(a, 33) |
3d6f38eaa3785422f8aab2861a36e081dbd8800c | SantiagoGonzalezR/ACE-base | /plant.py | 1,526 | 4.0625 | 4 | class plant:
def __init__ (self):
self.incorrectas = []
self.oyr={}
self.plantilla=()
self.ID_plantilla=input('Ingrese el codigo de la plantilla a crear: ')
self.enunciado=input('Ingrese el enunciado de la plantilla a crear: (el espacio a rellenar debe estar escrito y separado entre espacios como: /// ) ')
x=int(input('¿Cuántas variantes de la plantilla quiere hacer? (Cuántas preguntas basadas en esta plantilla) '))
self.oyr={}
#Definir cuántas variaciones de la plantilla se van a dar
temp=0
while temp<x:
Opcion=input('Escriba una posible opcion para rellenar el espacio en blanco: ')
Respuesta=input('Ingrese la respuesta a la anterior opcion ')
self.oyr[Opcion] = Respuesta
temp=temp+1
print(self.oyr)
self.incorrectas=[]
##agregar la respuesta a la lista de posibles respuestas
pregunta= int (input("digita 1 si va a ser selección multiple, y digite 2 si la pregunta es libre"))
if pregunta == 1:
cantidad_malas=int(input('Ingrese cantidad de opciones incorrectas para la respuesta. (minimo 3, máximo 7) '))
if cantidad_malas<3:
while cantidad_malas<3:
cantidad_malas=int(input('Cantidad menor a la necesitada, ingrese un numero mayor o igual a 3'))
bucle=0
while bucle<cantidad_malas:
opcion=input("ingreso opcion incorrecta: ")
self.incorrectas.append(opcion)
bucle=bucle+1
if pregunta == 2:
opcion=" "
self.incorrectas.append(opcion) |
11f6e3cb4527bd4d28a9c7dbe406f0d5b96ec849 | Deanwinger/python_project | /python_fundemental/121_max_nonrepeat_sub_string.py | 2,275 | 3.765625 | 4 | # leetcode 3. 无重复字符的最长子串
# 剑指offer(2) 题 48 最长不包含重复字符的子串
'''
题目解析
方法一:
建立一个 HashMap ,建立每个字符和其最后出现位置之间的映射,然后再定义两个变量
res 和 left ,其中 res 用来记录最长无重复子串的长度,left 指向该无重复子串左边
的起始位置的前一个,一开始由于是前一个,所以在初始化时就是 -1。
接下来遍历整个字符串,对于每一个遍历到的字符,如果该字符已经在 HashMap 中存在了,
并且如果其映射值大于 left 的话,那么更新 left 为当前映射值,然后映射值更新为
当前坐标i,这样保证了left始终为当前边界的前一个位置,然后计算窗口长度的时候,
直接用 i-left 即可,用来更新结果 res 。
方法二:
建立一个256位大小的整型数组 freg ,用来建立字符和其出现位置之间的映射。
维护一个滑动窗口,窗口内的都是没有重复的字符,去尽可能的扩大窗口的大小,窗口不停的向右滑动。
(1)如果当前遍历到的字符从未出现过,那么直接扩大右边界;
(2)如果当前遍历到的字符出现过,则缩小窗口(左边索引向右移动),然后继续观察当前遍历到的字符;
(3)重复(1)(2),直到左边索引无法再移动;
(4)维护一个结果res,每次用出现过的窗口大小来更新结果 res,最后返回 res 获取结果。
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
rec = {}
n = len(s)
dp = [0]*n
cur = 0
for i in range(n):
if rec.get(s[i]) is None:
rec[s[i]] = i
dp[i] = dp[i-1] + 1
else:
pre = rec[s[i]]
distance = i-pre
if distance > dp[i-1]:
dp[i] = dp[i-1] + 1
else:
dp[i] = distance
rec[s[i]] = i
if dp[i] > cur:
cur = dp[i]
return cur
if __name__=='__main__':
s = "abba"
solu = Solution()
print(solu.lengthOfLongestSubstring(s)) |
fbf644d08c5091a0fd467077996f2797557e3522 | vaclav0411/algorithms | /Задания 13-го спринта/Простые задачи/K. Рекурсивные числа Фибоначчи.py | 371 | 3.984375 | 4 | def recursion_fibonacci(i: int, array: list, n=2):
if i in (0, 1):
return 1
array[0] = 1
array[1] = 1
if n == i:
return array[n-1] + array[n-2]
array[n] = array[n-1] + array[n-2]
return recursion_fibonacci(i, array, n+1)
if __name__ == '__main__':
i = int(input())
array = [0] * i
print(recursion_fibonacci(i, array)) |
4a2dddcee84a7525c6ba2352d52170c2a60ebff4 | sol20-meet/sub2p | /Labs_1-7/Lab_6/Lab_6.py | 628 | 3.921875 | 4 | from turtle import *
import random
import turtle
import math
class Ball(Turtle):
def __init__(self,radius , color , speed):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
self.color(color)
self.speed(speed)
ball1 = Ball(50 , "red" , 50)
ball2 = Ball(50 , "green" , 70)
ball2.penup()
ball2.goto(69,69)
def Check_Collisions(ball1 , ball2):
d = math.sqrt(math.pow(ball1.xcor() - ball2.xcor() , 2) + math.pow(ball1.ycor() - ball2.ycor() , 2))
r1 = ball1.radius
r2 = ball2.radius
if r1 + r2 >= d :
print("Collisions")
Check_Collisions(ball1 , ball2)
turtle.mainloop() |
8a2dd45d86c72fcf9d6846cb889c7dd66819431f | bariis/leetcode-python | /Top_100_Liked_Questions/3.py | 689 | 3.84375 | 4 | """
3. Longest Substring Without Repeating Characters
@Level: Medium
Given a string, find the length of the longest substring without repeating characters.
"""
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
mySet = set()
i, j, ans = 0, 0, 0
while(i < n and j < n):
# extend the range [i, j]
if(s[j] not in mySet):
mySet.add(s[j])
j += 1
ans = max(ans, j - i)
else:
if s[i] in mySet:
mySet.remove(s[i])
i += 1
return ans |
435300d27c0ea674b28e1d4536c41ac0e8955353 | th3layman/school | /breakloop.py | 289 | 3.828125 | 4 | #Name: Richard Janssen
#Date: 1/5/2021
#Description: this script demonstrates how to break a loop
from math import sqrt
for i in range(1001, 0, -1):
root = sqrt(i)
# #This evaluates when the root is an integer
# if root == int(root):
# print(root)
# break |
f6ea4c4f44f1b386e17712b3f20a76dfa7c9774f | lslewis1/Python-Labs | /Week 2 Py Labs/Angle Addition.py | 1,048 | 4.1875 | 4 | #9/10/14
#This program will display the sum of two angles in terms of circles, degrees, minutes, and seconds
#60 secs is a minute
#60 mins is a degree
#360 degrees is a circle
#c is circles
#s is seconds
#s1 and s2 for the two angles
#d is degrees
#d1 and d2 for the two angles
#m is minutes
#m1 and m2 for the two angles
#st for total seconds
#mt for total minutes
#dt for total degrees
#m3 for left over minutes
d1=int(input("Please type in the degrees of the first angle:"))
d2=int(input("Please type in the degrees of the second angle:"))
m1=int(input("Please type in the minutes of the first angle:"))
m2=int(input("Please type in the minutes of the second angle:"))
s1=int(input("Please type in the seconds of the first angle:"))
s2=int(input("Please type in the seconds of the second angle:"))
m3=(s1+s2)//60
st=(s1+s2)%60
d3=(m1+m2+m3)//60
mt=(m1+m2+m3)%60
c=(d1+d2+d3)//360
dt=(d1+d2+d3)%360
print("The sum of the two angles results in:", c,"circles,", dt,"degrees,", mt,"minutes, and", st,"seconds.")
|
cb86a2829ebf3cf8f75fadf268823d615ea517a8 | nurshahjalal/python_exercise | /dunder_magic_method/dunder_magic.py | 799 | 3.765625 | 4 | class FirstHundredGenerator:
def __init__(self):
self.number = 0
def __next__(self):
if self.number < 100:
current = self.number
self.number += 1
return current
else:
raise StopIteration
# To make cl_gen instance iterable
# this special __iter__ will make any class iterable
def __iter__(self):
return self
# All generator is iterator not itarable
cl_gen = FirstHundredGenerator()
# Next method is calling special method __next__ and remember the last generator
# cl_gen is iterator and not iterable
print(next(cl_gen)) # Generating 0
print(next(cl_gen)) # Generating 1
print(next(cl_gen)) # Generating 2
print(sum(FirstHundredGenerator()))
for i in FirstHundredGenerator():
print(i)
|
974f4b873899a4585746b4c0c21387a89d46001c | ahermassi/Programming-Interviews-Exposed | /trees_graphs/graph_adjacency_matrix.py | 1,639 | 4.3125 | 4 | """
Python 3 implementation of a graph using Adjacency Matrix
"""
class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.adj_matrix = [[-1] * num_vertices for _ in range(num_vertices)]
self.vertices = {}
self.vertices_list = [0] * num_vertices
def set_vertex(self, vertex, vertex_id):
if vertex in range(self.num_vertices + 1):
self.vertices_list[vertex] = vertex_id # set_vertex(0, 'a') results in vertices_list[0] = 'a'
self.vertices[vertex_id] = vertex # set_vertex(0, 'a') results in an entry {'a': 0} in the dictionary
def set_edge(self, frm, to, cost=0):
from_vertex = self.vertices[frm]
to_vertex = self.vertices[to]
self.adj_matrix[from_vertex][to_vertex] = cost
# Adjacency matrix of an undirected graph is symmetric
self.adj_matrix[to_vertex][from_vertex] = cost
def get_vertices(self):
return self.vertices_list
def get_edges(self):
"""
This method returns a list of tuples.
For example, if there is an edge 'a' -> 'b' of cost 10, edges list contains a tuple ('a', 'b', 10).
vertices_list is used as a mapping from a vertex position in adjacency matrix to actual vertex name.
:return:
"""
edges = [(self.vertices_list[i], self.vertices_list[j], self.adj_matrix[i][j])
for i in range(self.num_vertices)
for j in range(self.num_vertices)
if self.adj_matrix[i][j] != -1]
return edges
def get_matrix(self):
return self.adj_matrix
|
ae401b5f472b4ed6637618993a19b33d34abbfef | BrettMcGregor/w3resource | /basic1-20.py | 278 | 3.9375 | 4 | # Write a Python program to get a string which is n (non-negative integer) copies of a given string.
user_string = input("Please enter a sentence string: ")
user_int = int(input("Please enter a positive integer: "))
string_copies = user_string * user_int
print(string_copies)
|
cae2b38074ee7b5da488ded30cb300745e495859 | n18007/programming-term2 | /src/algo-p1/task20180801_q01.py | 369 | 3.53125 | 4 | # 変数を使ってみよう
greeting = print("こんにちは")#変数greetingに文字列「こんにちは」を代入してください
greeting = 7
print(greeting)#変数greetingの値を出力してください
number = print("7")#変数numberに数値の7を代入してください
number = 7
print(number)#変数numberの値を出力してください
|
9e8a375da3d599374a94d62b977f5fefdf9d82cc | crystal-mullins/fsw-200 | /week5/lamda.py | 833 | 3.96875 | 4 | # adder = lambda x, y: x + y
# print (adder (11, 22))
# #What a lambda returns
# x='some kind of a useless lambda'
# (lambda x : print(x))(x)
# sequences = [10,2,8,7,5,4,3,11,0, 1]
# filtered_result = map (lambda x: x*x, sequences)
# print(list(filtered_result))
# from functools import reduce
# sequences = [1,2,3,4,5]
# product = reduce (lambda x, y: x*y, sequences)
# print(product)
# a function that takes one argument, and that argument will be multiplied with an unknown given number
def func_compute(n):
return lambda x : x * n
result = func_compute(2)
print("Double the number of 15 =", result(15))
result = func_compute(3)
print("Triple the number of 15 =", result(15))
result = func_compute(4)
print("Quadruple the number of 15 =", result(15))
result = func_compute(5)
print("Quintuple the number 15 =", result(15)) |
d9c730121eb24af8b0498a0f2b37e70d075ad79e | silan1993/python-numpy | /6.py | 383 | 3.578125 | 4 | import numpy as np
a = np.array([[1, 2, 3, 4, 4], [3, 3, 4, 5, 6]])
# Displaying the array
print('Array:\n', a)
file = open("file1.txt", "w+")
# Saving the array in a text file
content = str(a)
file.write(content)
file.close()
# Displaying the contents of the text file
file = open("file1.txt", "r")
content = file.read()
print("\nContent in file1.txt:\n", content)
file.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.