blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7a01608a5c8fb2414f8833eba007da11688ac094
nrgolden16/python
/위장.py
445
3.734375
4
#프로그래머스 LEVEL2 코딩테스트 연습 "위장" def solution(clothes): clothes_type_lst=[] for i,v in clothes: clothes_type_lst.append(v) clothes_type_set=set(clothes_type_lst) clothes_cnt=[] for j in clothes_type_set: clothes_cnt.append(clothes_type_lst.count(j)+1) def multi(lst): tot=1 for i in lst: tot*=i return tot return multi(clothes_cnt)-1
c3c4c7610c4755ca125ef868ad2ac55619264253
myllenaalves/Algoritmos-e-estruturas-de-dados
/arvoreBinaria.py
1,722
3.5
4
class No: def __init__(self, chave, valor, esq=None, dir=None,p=None): self.chave = chave self.valor = valor self.esq = esq self.dir = dir self.p = p class Arvore: def __init__(self): self.raiz = No(None,None) self.tamanho = 0 def __len__(self): return self.tamanho def __str__(self): x = self.raiz return self.em_ordem(x) def em_ordem(self,x): msg = "" if x!= None: msg += str(x.chave) self.em_ordem(x.esq) msg += str(x.chave) self.em_ordem(x.dir) msg += str(x.chave) return msg def inserir(self, chave, valor): y = None x = self.raiz no_inserir = No(chave, valor) while x!= None and x.chave != None: y = x if no_inserir.chave < x.chave: x = x.esq else: x = x.dir no_inserir.p = y if y == None: self.raiz = no_inserir elif no_inserir.chave < y.chave: y.esq = no_inserir else: y.dir = no_inserir self.tamanho += 1 def buscarIterativo(self, chave): x = self.raiz while x.chave != None and chave != x.chave: if chave < x.chave: x = x.esq else: x = x.dir return x.valor #def remover(self): #método remoção, aqui você deve implementar uma função que remove um elemento(chave,valor) a sua árvore tree = Arvore() tree.inserir(15,'quinze') tree.inserir(66,'sessenta e seis') tree.inserir(1,'um') tree.inserir(50,'cinquenta') tree.inserir(11,'onze')
8a31423c2e6874fcbc5dbec1aead865545fc46ba
dcorns/PyAssignments
/Chap8/prog1.py
235
3.671875
4
fname = raw_input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = open(fname) lst = list() for line in fh: ln = line.rstrip().split() for item in ln: if item not in lst: lst.append(item) lst.sort() print lst
abb44a36ffbe6b15698fd084154f071867747a79
Kio0/En.Words
/Основная_программа.py
2,536
3.53125
4
#основная программа import functions from tkinter import * from tkinter import messagebox def avtoriz(): global root s=functions.auth(name.get(),password.get()) Str=name.get() if s!='Вход выполнен': messagebox.showinfo("Error", s) else: messagebox.showinfo("Вход выполнен", "Позравляю, вы вошли!") def reg(): if functions.test_email(email.get())=='Валидный email': s=functions.registr(name2.get(),email.get(),password1.get(),password2.get()) messagebox.showinfo("Error", s[0]) else: messagebox.showinfo("Error", functions.test_email(email.get())) root = Tk() root.title("Войдите в аккаунт либо зарегестрируйтесь") root.geometry("500x300") name = StringVar() name2 = StringVar() password = StringVar() password1 = StringVar() password2 = StringVar() email = StringVar() name_label = Label(text="Введите логин:") password_label = Label(text="Введите пароль:") name_label.grid(row=0, column=0, sticky="w") password_label.grid(row=1, column=0, sticky="w") name_entry = Entry(textvariable=name) password_entry = Entry(textvariable=password) name_entry.grid(row=0,column=1, padx=5, pady=5) password_entry.grid(row=1,column=1, padx=5, pady=5) name2_label = Label(text="Введите логин:") email_label = Label(text="Введите email:") password1_label = Label(text="Введите пароль:") password2_label = Label(text="Введите пароль:") name2_label.grid(row=0, column=3, sticky="w") email_label.grid(row=1, column=3, sticky="w") password1_label.grid(row=2, column=3, sticky="w") password2_label.grid(row=3, column=3, sticky="w") name2_entry = Entry(textvariable=name2) email_entry = Entry(textvariable=email) password1_entry = Entry(textvariable=password1) password2_entry = Entry(textvariable=password2) name2_entry.grid(row=0,column=4, padx=5, pady=5) email_entry.grid(row=1,column=4, padx=5, pady=5) password1_entry.grid(row=2,column=4, padx=5, pady=5) password2_entry.grid(row=3,column=4, padx=5, pady=5) message_button1 = Button(text="Авторизация", command=avtoriz) message_button1.grid(row=2,column=1, padx=5, pady=5, sticky="e") message_button2 = Button(text="Регистрация", command=reg) message_button2.grid(row=4,column=3, padx=5, pady=5, sticky="e") root.mainloop()
86813c8baa2c14f0706c6d62be34f8d279dbbd8b
jacquarPL/Python-learn
/lab_5.1.11.8_anagram.py
386
3.734375
4
def str2list(strng): txt = "" for char in strng: txt += char + " " lst = txt.split() return lst #t1 = "arbuzy".lower() #t2 = "burza".lower() t1 = "Ranek".lower() t2 = "Nerka".lower() #print(str2list(t1)) l1 = sorted(str2list(t1)) l2 = sorted(str2list(t2)) if l1 == l2: print("To anagramy") else: print("To nie są anagramy")
e65c38d24933d00568fbdf9548be40721111fa72
Mica210/python_michael
/Lessons/Lab6.py
1,511
4.1875
4
''' Write a code that will show a menu: 1.Insert Number and ** it by 3. 2.insert 4 IPs to a list and print it. 3.Insert 4 Entries to dns_Dictionary and print it. 4.check if a string is polindrom if the user wont choose 1-4, you will tell him to insert ony 1-4. ''' from time import sleep print("Starting the menu... \n") sleep(1) choice=input("Menu\n______\n" + "1.Enter a number to ** it by 3: \n" + "2.Enter 4 IP Addresses and print them: \n" + "3.Enter 4 Entries to dns_Dictionary and print them: \n" + "4.check if a string is polindrom \n") if choice == "1": print("Your new number is: " + str((int(input("Enter a number: ")))**3)) elif choice == "2": IP_lists = [] IP_lists.append(input("Enter your IP:")) IP_lists.append(input("Enter your IP:")) IP_lists.append(input("Enter your IP:")) IP_lists.append(input("Enter your IP:")) sleep(1) print("\nYour IP lists is: " + str(IP_lists)) elif choice == "3": DNS_dict = {} DNS_dict.update({input("Enter your URL:"): input("Enter IP: ")}) DNS_dict.update({input("Enter your URL:"): input("Enter IP: ")}) DNS_dict.update({input("Enter your URL:"): input("Enter IP: ")}) DNS_dict.update({input("Enter your URL:"): input("Enter IP: ")}) sleep(1) print("\nYour DNS_Dictionary is:\n" + str(DNS_dict)) elif choice == "4": word = input("Enter a word: ") if word == word[::-1]: print("This is polindrom!!") else: print("This isn't polindrom!!") else: print("Enter 1-4 only!!!")
f08ea0fd685b93761086b423039734612ba5199a
Gustavo-Lourenco/Python
/Exercícios/ex053.py
627
3.703125
4
print('\033[35m{:-^40}\033[m'.format(' Verificador de Palíndromo !!')) f = str(input('Digite uma frase: ')).upper().split() f = ''.join(f) inverso = f[::-1] counter = 0 print(inverso) print('O inverso da {} é {}'.format(f, inverso)) #print('O inverso da {} é '.format(f), end='') '''for c in range(0, len(f)): print((f[len(f) - c - 1]), end='') if f[c] != f[(len(f) - c - 1)]: counter = counter + 1 ''' #para fazer o teste sem o for eu mudei o condicional do IF if f != inverso: print('\nA frase \033[1:31mNÃO\033[m é um palíndromo!') else: print('\nA frase \033[32:1mÉ\033[m um palíndromo!')
1769f1fbaa413ddb759670ce34fe1bf420ee055c
steve-thousand/advent_of_code_2017
/11/solution2.py
2,921
4.1875
4
import math class Movement: def __init__(self, north, direction=0): self.north = north self.direction = direction self.nextMovement = None def pushNextMovement(self, nextMovement): self.nextMovement = nextMovement def hasNextMovement(self): return self.nextMovement is not None def getNextMovement(self): return self.nextMovement def canReplace(self, potentialMovement): if self.north == potentialMovement.north: # same north but opposite directions? if math.fabs(self.direction - potentialMovement.direction) == 2: # combine example nw and ne to be n return Movement(self.north) elif self.direction == -potentialMovement.direction: # these are opposites! CANCEL >:( return None elif math.fabs(self.direction - potentialMovement.direction) == 1: # we have gone some non-zero direction, and then a zero direction. replace with direction in opposite north if potentialMovement.direction == 0: return Movement(potentialMovement.north, self.direction) else: return Movement(self.north, potentialMovement.direction) # -1 means can't replace return -1 def N(): return Movement(1) def NE(): return Movement(1, 1) def SE(): return Movement(0, 1) def S(): return Movement(0) def SW(): return Movement(0, -1) def NW(): return Movement(1, -1) MOVEMENTS_BY_DIRECTION = { 'n' : N, 'ne' : NE, 'se' : SE, 's' : S, 'sw' : SW, 'nw' : NW } DIRECTIONS = [] with open("/Users/conrad/Desktop/adventofcode2017/11/input.txt", "r") as f: DIRECTIONS = list(f.read().split(",")) # root is an empty north, ignore it later rootMovement = Movement(1) def addMovement(movementToAdd): # walk through the movements, see if we find one we can replace, else append previousMovement = None currentMovement = rootMovement replaced = False while currentMovement.hasNextMovement(): previousMovement = currentMovement currentMovement = currentMovement.nextMovement canReplaceMovement = currentMovement.canReplace(thisMovement) if canReplaceMovement != -1: replaced = True previousMovement.pushNextMovement(currentMovement.getNextMovement()) if canReplaceMovement is not None: addMovement(canReplaceMovement) break if not replaced: currentMovement.pushNextMovement(thisMovement) for direction in DIRECTIONS: if direction == 'n': x = 0 thisMovement = MOVEMENTS_BY_DIRECTION[direction]() addMovement(thisMovement) steps = 0 currentMovement = rootMovement while currentMovement.hasNextMovement(): currentMovement = currentMovement.getNextMovement() steps += 1 print steps
76b27bf542341b2f517fb70a15968ce0f75b48fc
barbaracalderon/curso-de-python3-do-curso-em-video
/mundo_2/desafio057.py
425
4.09375
4
# Faça um programa que leia o sexo de uma pessoa mas só aceite # os valores 'M' ou 'F'. Caso esteja errado, peça a digitação # novamente até ter um valor correto. sexo = str(input('Digite seu sexo [M/F]: ')).strip().upper()[0] while sexo not in 'MF': print('Opção inválida. Tente novamente.') sexo = str(input('Digite seu sexo [M/F]: ')).strip().upper()[0] print('Sua opção escolhida foi {}.'.format(sexo))
642fb691f58eb39b72d41346469e15758057ee7b
swimorsink/onecodingproblem
/src/remove-last-link-list.py
1,596
3.640625
4
#!/usr/bin/python2.7 import unittest from test import test_support class Node(object): def __init__(self, value): self.next = None self.value = value class LinkedList(object): def __init__(self): self.tail = None self.head = None def add(self, value): node = Node(value) if self.head == None: self.head = node self.tail = node else: self.tail.next = node self.tail = node def remove_last(self): if not self.tail or not self.head: return None if self.tail == self.head: val = self.tail.value self.tail = None self.head = None return val cur = self.head while cur.next: second_to_last = cur cur = cur.next value = self.tail.value self.tail = second_to_last self.tail.next = None return value def get_list(self): cur = self.head l = [] if not cur: return l while cur: l.append(cur.value) cur = cur.next return l def get_last(self): cur = self.head while cur.next: cur = cur.next class TestLinkedList(unittest.TestCase): def test_one(self): test_array = ['d', 'e', 'a', 'd', 'b', 'e', 'e', 'f'] l = LinkedList() for i in test_array: l.add(i) self.assertEqual(test_array, l.get_list()) new_list = [] while True: cur = l.remove_last() if not cur: break new_list.append(cur) test_array.reverse() self.assertEqual(test_array, new_list) if __name__ == '__main__': test_support.run_unittest(TestLinkedList)
dfb990d6e744374251ad446147986dea5f4fd34e
my0614/python
/key_event.py
641
3.65625
4
import turtle import random t = turtle.Turtle() sc = turtle.Screen() def move(): x = random.randint(-300,300) y = random.randint(-300,300) t.up() t.goto(x,y) t.down() def fill_circle(): move() t.color(random.choice(['red', 'blue', 'black'])) s = random.randint(10, 50) a = random.randint(1,3) t.begin_fill() if a == 1: t.circle(s) if a == 2: for i in range(3): t.fd(s) t.left(120) if a == 3: for i in range(4): t.fd(s) t.left(90) t.end_fill() sc.onkeypress(fill_circle, 'c') sc.listen()
f57b2eb9ca7834c2d783f7acf3026b817e63fd9b
MarRoar/Python-code
/00-sxt/03-reg/07-dmeo.py
1,147
3.5625
4
'''''' import re ''' 三个大引号就是真实存在的数据,内存在解析的时候,会解析出东西的 ''' s = '''<div> <p>岗位职责:</p> <p>完成推荐算法、数据统计、接口、后台等服务器端相关工作</p> <p><br></p> <p>必备要求:</p> <p>良好的自我驱动力和职业素养,工作积极主动、结果导向</p> <p>&nbsp;<br></p> <p>技术要求:</p> <p>1、一年以上 Python 开发经验,掌握面向对象分析和设计,了解设计模式</p> <p>2、掌握HTTP协议,熟悉MVC、MVVM等概念以及相关WEB开发框架</p> <p>3、掌握关系数据库开发设计,掌握 SQL,熟练使用 MySQL/PostgreSQL 中的一种<br></p> <p>4、掌握NoSQL、MQ,熟练使用对应技术解决方案</p> <p>5、熟悉 Javascript/CSS/HTML5,JQuery、React、Vue.js</p> <p>&nbsp;<br></p> <p>加分项:</p> <p>大数据,数理统计,机器学习,sklearn,高性能,大并发。</p> </div>''' result = re.sub(r'</?\w+>', '', s) print(result) # split 以某个字符来分割字符串 s = "marui:hello, python, c++, php" result = re.split(r":|,|", s) print(result)
0d702791abc0c6e073b443845f572086130050c3
BOTFerran/NN
/Tiny_NN/NeuralNetwork.py
3,268
4.1875
4
import numpy as np import random # We start implementing the sigmoid function and its derivative def sigmoid(x): return 1.0/(1+ np.exp(-x)) def sigmoid_derivative(x): return x * (1.0 - x) # Then let's go with the main class class NeuralNetwork(): """ We need to give our neural network an input data 'x' and the expected value for it 'y' """ def __init__(self,x,y): self.input = x self.y = y self.output = np.zeros(y.shape) # The output is initialized with 0's for future updates self.count = 0 # This counter will help us to check in which training episode we are """ We can initialize all the layer weights randomly but in purpose to learn a bit more about nn's i've implemented a way to start each neuron weight with some wanted value """ # self.weights1 = np.random.rand(self.input.shape[1],self.y.shape[0]) # self.weights2 = np.random.rand(self.y.shape[0],1) self.weights1 = np.zeros((self.input.shape[1],self.input.shape[0])) for i in range(self.weights1.shape[0]): for j in range(self.weights1.shape[1]): self.weights1[i][j] = 1 # random.random(); if u want it to be random [0,1] self.weights2 = np.zeros((self.y.shape[0],1)) for i in range(self.weights2.shape[0]): for j in range(self.weights2.shape[1]): self.weights2[i][j] = random.random() #i # random.random(); if u want it to be random [0,1] # If u want to check the initialized weights, just print them print self.weights1 print self.weights2 """ This feedforward function just gets the input and makes it go through all the layers until the output one. Then, if we choose it, will print every 'step' steps the current testing round and its loss """ def feedforward(self,msg=False,step=100): # In this case, we are assuming that the layer biases are 0 self.layer_1 = sigmoid(np.dot(self.input,self.weights1)) self.output = sigmoid(np.dot(self.layer_1, self.weights2)) self.count += 1 # I've set up some code to see how many tests you've done and # the current error. It'll only print them every 'step' steps # (it's set to 100 by default) if msg: if(self.count%100==0): print "Error at testing round "+str(self.count) print (self.y - self.output)**2 """ The backprop method uses the chain rule to find derivative of the loss function with respect weights2 and weights1, so it can update all weights from the nn """ def backprop(self): # To do so, it uses 'sigmoid_derivative' function coded at the beginning d_weights2 = np.dot(self.layer_1.T,(2*(self.y-self.output)* sigmoid_derivative(self.output))) d_weights1 = np.dot(self.input.T,(np.dot(2*(self.y-self.output)* sigmoid_derivative(self.output),self.weights2.T)* sigmoid_derivative(self.layer_1))) # time to update self.weights1 += d_weights1 self.weights2 += d_weights2 # Prints the predicted results from an input 'input' with the current values # of self.weights1 and self.weights2 """ To check the prediction we just feedforward the input through the nn """ def predict(self,input): self.layer_1 = sigmoid(np.dot(input,self.weights1)) self.output = sigmoid(np.dot(self.layer_1, self.weights2)) print "After",self.count,"testing rounds, the prediction is:" print self.output
632a8de5d58cb5076a01e1f235ae3eca4a5b53f8
daniel-reich/ubiquitous-fiesta
/u3kiw2gTY3S3ngJqo_7.py
197
3.8125
4
def superheroes(heroes): words_list=[] for word in heroes: if word[-3:]=="man" and word[-4]!="o": words_list.append(word) words_list.sort() return words_list
c310ecb080e7e021727c843723168e95bc62b869
Harshupatil/PythonPrograms-
/Armstrong.py
626
4.21875
4
#****************************************************************************** #Armstrong Number, is the number that is equal to sum of cube of it's degits. #For example 0, 1, 153, 370, 371, 407 are armstrong numbers. #*******************************************************************************/ def armstrong(): sum=0; n=int(input("Enter the number: ")) n1=n; while(n1!=0): d = n1%10; n1 = int(n1/10); sum = sum + d*d*d; if sum==n: print("Number is Armstrong number") else: print("Number is not Armstrong number") print(sum) armstrong()
d7c3e03303c0adbc46e5291d2372e74a2bb65813
Soyoung-Yang/se
/Python/exercise0/ex1-3.py
483
4.03125
4
txt = """ 안녕 나는 댕소야 너는 누구니? 나는 소댕이야 그렇구나 반가워 """ print(txt[11]) # 문자열의 요소 print(len(txt)) # 문자열 길이 print("소댕" in txt) # True print("sodang" in txt) # False print("유댕" not in txt) # True a = " Hello, Soyoung! " print(a.upper()) print(a.lower()) print(a.strip()) print(a.replace("Hello", "Goodbye")) print(a.split(",")) age = 24 txt = "My name is Soyoung, and I am {} years old." print(txt.format(age))
5b13d9b2fc20faafb6d2ae695f2de7900a7ab635
tsurendher/Innomatics_Intenship
/day_2/3_NestedLoop.py
400
3.578125
4
if __name__ == '__main__': nisted_list=[] marks_list=[] for _ in range(int(input())): name = input() score = float(input()) marks_list.append(score) nisted_list.append([name,score]) marks_list=sorted(set(marks_list)) nisted_list=sorted(nisted_list) for a in nisted_list: if a[1]==marks_list[1]: print(a[0])
076f78dc15575bb59c53cf039108ddd48c60acd3
lcmust/git6500py
/python/python_runtime.py
1,351
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- from time import time def test(): t = time() lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44] listb=[2,4,6,9,23] intersection=[] for i in range (1000000): for a in lista: for b in listb: if a == b: intersection.append(a) print "list in func(test), total run time:", time()-t def test_set(): t = time() lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44] listb=[2,4,6,9,23] intersection=[] for i in range(1000000): intersection.append(list(set(lista)&set(listb))) print "set in func(test_set), total run time:", time()-t t = time() lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44] listb=[2,4,6,9,23] intersection=[] for i in range (1000000): for a in lista: for b in listb: if a == b: intersection.append(a) print "list not in func, total run time:", time()-t ##runtime(db6sda8_python2.6.6: 19.9267392159) t = time() lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44] listb=[2,4,6,9,23] intersection=[] for i in range(1000000): intersection.append(list(set(lista)&set(listb))) print "set not in func, total run time:", time()-t #runtime(db6sda8_python2.6.6: 5.93210506439) test() ###runtime(db6sda8_python2.6.6: 10.7789461613) test_set() ###runtime(db6sda8_python2.6.6: 7.41557717323)
0db3f351dc1094bb65e2a62c7a5d82a39e7df66c
aleenaadnan15/official-assignment
/fibonacci.py
141
3.640625
4
#Question num 38: ''' Get the Fibonacci series between 0 to 50 ''' x = 0 y = 1 while y < 50: print(y) x,y = y , x + y
27443d6926ac804260993a0c504d97aa935875b2
jamircse/Complete-Python-3-Bootcamp
/Python-3/10.1 Tuple Example .py
286
4.25
4
data1=(1,2,3,4) data2=(20,30,40) data3=data1+data2; print(data3); print("Maximum value of tuple ",max(data3)); print("Minimum value of tuple ",min(data3)); print("Lenth value of tuple ",len(data3)); print("3rd value of tuple ",data3[2]); for i in data3: print(i);
6b07ab41c2f55ef6969a4500204f294065031ceb
lvshuy/Computer-Simulation-Book
/ch03/approx_prob_outcome.py
322
3.578125
4
from random import randint n = 1000000 # No. of times experiment is performed ne = 0 # Count the occurrences of event for i in range(n): outcome = randint(1, 6) if(outcome == 3): # Check for event of interest ne += 1 # ne = ne + 1 print("Prob = ", round(ne / n, 4)) # = 0.1667
af44c6e165bb3009d08288feabee8e34d5ccd8d8
AgiliaErnis/intro-to-py
/basics/wordplay.py
838
4.09375
4
from basics import scrabble for word in scrabble.wordlist: if "oo" in word and "aa" in word: print(word) print("==============================") for word in scrabble.wordlist: if "q" in word and "u" not in word: print(word) print("==============================") letters = "qwertyuiopasdfghjklzxcvbnm" def has_double(letter): for word in scrabble.wordlist: if letter+letter in word: return True return False for letter in letters: if not has_double(letter): print(letter + " never appears doubled") print("==============================") vowels = "aeiou" def has_all_vowels(word): for vowel in vowels: if vowel not in word: return False return True for word in scrabble.wordlist: if has_all_vowels(word): print(word)
1510ad4e1bc5172a7abae33117557f142e1a8bae
daniel-reich/ubiquitous-fiesta
/DG2HLRqxFXxbaEDX4_5.py
118
3.671875
4
def return_only_integer(lst): lst1 = [] for x in lst: if type(x) == int: lst1.append(x) return lst1
afdd59e71f41d9de941d1aac64d29a614e242040
YunJ1e/LearnPython
/MissingKnowledge.py
5,472
3.671875
4
""" Updated: 2020/07/12 Author: Yunjie Wang """ """ This file includes some basic Python knowledge I miss when I first learn Python 1. Difference Between Continue and Break (Line 18) 2. Passing by Reference, and the return of the function (Line 38) 3. OOP (Line 81) 4. Draw the Dynamics (Line 137) """ """ Difference Between Continue and Break """ def continue_or_break(): """ See the difference between continue and break Break will end the entire loop, instead the continue only skips the current iteration. """ # Will stop printing when meeting the space between first and last name for letter in "Yunjie Wang": if letter == " ": break print(letter, end="") print() # Will skip the space between first and last name for letter in "Yunjie Wang": if letter == " ": continue print(letter, end="") """ Passing by Reference... """ def foo1(x): x.append(1) x = [2] x.append(1) return x def foo2(x): x.append(1) x.append(1) x = [2] return x def foo3(x): x = [2] x.append(1) x.append(1) return x def call_foo(): x = [0] y = foo1(x) #Expected: [0,1], [2,1] print(x, y) x = [0] y = foo2(x) # Expected: [0,1,1], [2] print(x, y) x = [0] y = foo3(x) # Expected: [0], [2,1,1] print(x, y) """ OOP """ class ListNode(object): def __init__(self, value): self.next = None self.val = value def print_all_nodes(headNode): while headNode is not None: print(headNode.val, "->", end=" ") headNode = headNode.next print("None") def search_and_delete(headNode, target): current = ListNode(-1) fakeHead = current while headNode is not None: if headNode.val == target: # print("111") current.next = headNode.next headNode = headNode.next else: current.next = headNode current = current.next # print(current.val) headNode = headNode.next return fakeHead.next head = ListNode(1) head.next = ListNode(3) head.next.next = ListNode(4) print_all_nodes(search_and_delete(head, 1)) def merge_two_sorted_llist(headOne, headTwo): # Handle the corner cases, if one of them is empty, return the other(regardless empty or not) if headOne is None: return headTwo if headTwo is None: return headOne # General Case current = ListNode(None) newHead = current while headOne and headTwo: if headOne.val < headTwo.val: # When the value of the headOne is less than headTwo, we move on to compare the next on in the llist smallHead = headOne headOne = headOne.next else: smallHead = headTwo headTwo = headTwo.next current.next = smallHead current = current.next # Once they get out the while loop(at least one of them is empty) if headOne: current.next = headOne else: current.next = headTwo return newHead.next def test_merge(): llist_01 = ListNode(1) llist_01.next = ListNode(3) llist_02 = ListNode(2) print_all_nodes(llist_01) print_all_nodes(llist_02) newLlist = merge_two_sorted_llist(llist_01, llist_02) print_all_nodes(newLlist) """ Draw the Dynamics https://towardsdatascience.com/intro-to-dynamic-visualization-with-python-animations-and-interactive-plots-f72a7fb69245 """ def fermi(E: float, E_f: float, T: float) -> float: import numpy as np k_b = 8.617 * (10**-5) # eV/K return 1/(np.exp((E - E_f)/(k_b * T)) + 1) def static_plot_the_data(): import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # General plot parameters # I find sometimes these statements are confusing when you first look # Especially you are not familiar with the maplotlib # mpl.rcParams['font.family'] = 'serif' # mpl.rcParams['font.size'] = 10 # mpl.rcParams['axes.linewidth'] = 2 # mpl.rcParams['axes.spines.top'] = False # mpl.rcParams['axes.spines.right'] = False # mpl.rcParams['xtick.major.size'] = 10 # mpl.rcParams['xtick.major.width'] = 2 # mpl.rcParams['ytick.major.size'] = 10 # mpl.rcParams['ytick.major.width'] = 2 # Create figure and add axes fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) # Temperature values T = np.linspace(100, 1000, 10) # Get colors from coolwarm colormap colors = plt.get_cmap('coolwarm', 10) # Plot F-D data for i in range(len(T)): x = np.linspace(0, 1, 100) y = fermi(x, 0.5, T[i]) ax.plot(x, y, color=colors(i), linewidth=2.5) # Add legend labels = ['100 K', '200 K', '300 K', '400 K', '500 K', '600 K', '700 K', '800 K', '900 K', '1000 K'] ax.legend(labels, loc='upper right', frameon=False, labelspacing=0.2) # plt.show() def dynamic_plot_the_data(): import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Create figure and add axes fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) # Create variable reference to plot f_d, = ax.plot([], [], linewidth=2.5) # Add text annotation and create variable reference temp = ax.text(1, 1, '', ha='right', va='top', fontsize=24) # Temperature values T = np.linspace(100, 1000, 10) # Animation function def animate(i): import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt colors = plt.get_cmap('coolwarm', 10) x = np.linspace(0, 1, 100) y = fermi(x, 0.5, T[i]) f_d.set_data(x, y) f_d.set_color(colors(i)) temp.set_text(str(int(T[i])) + ' K') temp.set_color(colors(i)) # Create animation ani = FuncAnimation(fig=fig, func=animate, frames=range(len(T)), interval=500, repeat=True) plt.show() # continue_or_break() # call_foo() # plot_the_data() # dynamic_plot_the_data()
5712f3116ae0e48e779850a0dbfe61f5ad51e94b
Iso-luo/python-assignment
/practice/Ch4_interface design/turtle_基础.py
356
3.625
4
# -*- coding:UTF-8 -*- # !/usr/bin/env python import turtle bob = turtle.Turtle() # create an object print(bob) bob.fd(100) # forward 100 pixels 画线 bob.lt(90) # left turn 90 degrees 箭头方向 bob.bk(100) # backward 100 pixels 画线 bob.rt(90) # right turn 90 pixels 箭头方向 # turtle.mainloop() # call mainloop, do
0913f3e934cb073268da44bc837865acbdb2fd65
philoxmyu/pro-python
/polymorphic_test.py
853
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17-9-9 下午4:34 # @Author : philoxmyu # @Contact : philoxmyu@gmail.com ''' 多态的概念其实不难理解,它是指对不同类型的变量进行相同的操作,它会根据对象(或类)类型的不同而表现出不同的行为。 有了继承,才有了多态,不同类的对象对同一消息会作出不同的相应 ''' class Animal(object): def __init__(self, name): self.name = name def greet(self): print 'Hello, I am %s.' % self.name class Dog(Animal): def greet(self): print 'WangWang.., I am %s.' % self.name class Cat(Animal): def greet(self): print 'MiaoMiao.., I am %s' % self.name def hello(animal): animal.greet() if __name__ == "__main__": dog = Dog('dog') hello(dog) cat = Cat('cat') hello(cat)
e5ca079f8b95c88707b87d6a92269d87d33f2151
dundunmao/lint_leet
/mycode/lintcode/Binary Search/38 Search a 2D Matrix II.py
3,272
3.65625
4
# -*- encoding: utf-8 -*- # 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。 # # 这个矩阵具有以下特性: # # 每行中的整数从左到右是排序的。 # 每一列的整数从上到下是排序的。 # 在每一行或每一列中没有重复的整数。 # 您在真实的面试中是否遇到过这个题? Yes # 样例 # 考虑下列矩阵: # # [ # # [1, 3, 5, 7], # # [2, 4, 7, 8], # # [3, 5, 9, 10] # # ] # # 给出target = 3,返回 2 class Solution: """ @param matrix: An list of lists of integers @param target: An integer you want to search in matrix @return: An integer indicates the total occurrence of target in the given matrix """ # O(m * n) def searchMatrix(self, matrix, target): # write your code here if matrix is None or len(matrix) == 0: return 0 if matrix[0] is None or len(matrix[0]) == 0: return 0 if target < matrix[0][0]: return 0 m = len(matrix) n = len(matrix[0]) count = 0 for i in range(m): start = 0 end = n-1 while start + 1 < end: medium = start + (end - start) / 2 if target < matrix[i][medium]: end = medium elif target > matrix[i][medium]: start = medium elif target == matrix[i][medium]: count += 1 break #while里的用break因为一行就一个找到就可以找下一行了 if target == matrix[i][start]: count += 1 continue # for里的用continue elif target == matrix[i][end]: count += 1 continue return count # O(m+n) def searchMatrix1(self, matrix, target): if matrix is None or len(matrix) == 0: return 0 if matrix[0] is None or len(matrix[0]) == 0: return 0 if target < matrix[0][0]: return 0 m = len(matrix) n = len(matrix[0]) count = 0 x = n - 1 y = 0 while x >=0 and y<m: if matrix[x][y] < target: y+=1 elif matrix[x][y] > target: x -=1 else: count += 1 x -= 1 y += 1 return count def searchMatrix_leetcode(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if matrix is None or len(matrix) == 0: return False if matrix[0] is None or len(matrix[0]) == 0: return False m = len(matrix) n = len(matrix[0]) row = m-1 col = 0 while row >= 0 and col <= n - 1: if matrix[row][col] < target: col += 1 elif matrix[row][col] > target: row -= 1 else: return True return False if __name__ == "__main__": A = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]] target = 5 s = Solution() print s.searchMatrix(A,target)
f018d611f88eb6c4785161e1d86eb307b3292788
alhilario/python-stuff
/vac.py
715
3.90625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- def hotel_cost(nights): return nights * 140 def plane_ride_cost(city): if (city == "Charlotte"): return 183 elif (city == "Tampa"): return 220 elif (city == "Pittsburgh"): return 222 elif (city == "Los Angeles"): return 475 else: return 0 def rental_car_cost(days): cost = days * 40 if(days >= 7): return cost - 50 elif(days >= 3 and days < 7): return cost - 20 else: return cost def trip_cost(city, days, spending_money): return plane_ride_cost(city) + rental_car_cost(days) + hotel_cost(days) + spending_money print trip_cost("Los Angeles", 5, 600)
86f73eb1544abc472a2b52f423446ba24a1a7a7a
nrohankar29/Python
/parentheses_checker.py
354
4
4
def parentheses_checker(s): stack = [] for char in s: if char == '(' or char == '{' or char == '[': stack.append(char) if char == ')' or char == '}' or char == ']': stack.pop() if len(stack) == 0: print('balanced') else: print('not balanced') t = int(input()) for i in range(t): s = input() print(parentheses_checker(s))
2a2c448c5ce88835f2e367b5a2cf64c512587e97
zhangmeiling0611/OOP
/opp_demo.py
979
4.1875
4
#!/user/bin/env python3 # -*- coding:utf-8 -*- #定义一个类,类名为Student class Student(object): count = 0 #类属性,所有实例共享 def __init__(self,sno,name): '''初始化方法,或者叫构造器,对属性进行初始化 ''' self.sno = sno #实例属性,属于每个对象,每个对象都有一份 self.name = name Student.count += 1 def show(self): print(self.sno,self.name) s1 = Student(1001,"张三") #定义对象s1,将会调用__init__方法对属性进行初始化 s1.show() #调用s1的show方法 s1.age = 33 #给对象动态绑定属性 s1.qq = "134537" print(s1.age,s1.qq) s2 = Student(1002,"李四") #print(s2.qq) print(Student.count) print(s1.count) class Dog: def show(self): print("我是汪星人~~~") class Fish: def show(self): print("我是小鱼人") def show(p): p.show() show(s1) show(Dog()) #多态的体现 show(Fish())
85bda477158b893bc7a0d979b2ad55f100198009
satyam-seth-learnings/python_learning
/Geeky Shows/Core Python/2.Nested_While_Loop[37].py
163
4.28125
4
# Nested While Loop i=1 while i<=2: print("Outer Loop",i) i+=1 j=1 while j<=3: print("Inner Loop",j) j+=1 print("Rest Of The Code")
d94a060aadd68e93c463788ca257b3a5fe5cd50c
eugenechernykh/coursera_python
/week6_sort_by_count.py
822
3.96875
4
''' Дан список из N (N≤2*10⁵) элементов, которые принимают целые значения от 0 до 100 (100 включая). Отсортируйте этот список в порядке неубывания элементов. Выведите полученный список. Решение оформите в виде функции CountSort(A), которая модифицирует передаваемый ей список. Использовать встроенные функции сортировки нельзя. ''' def CountSort(A): count_list = [0] * 101 for item in A: count_list[item] += 1 for i in range(len(count_list)): print((str(i) + ' ') * count_list[i], end='') my_list = map(int, input().split()) CountSort(my_list)
e8dde7e51fda91a03e5c648d42f1a74c8b239fa3
hellge83/AI_alg_python
/les02/les02_06.py
937
4.15625
4
# -*- coding: utf-8 -*- """ 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться, больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, вывести ответ. """ import random number = random.randint(1, 100) for i in range(10): num = int(input('input your guess: ')) if num > number: print(f'{num} is more than number') elif num < number: print(f'{num} is less than number') else: print(f'you win! {num} is the number') break if num != number: print (f'The number is {number}')
0c2fdc8e4109a124c9ee30fda6e1dd7575d960be
MReeds/Interview-Prep
/Comprehension.py
753
4.4375
4
""" Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined""" # Create a new list of squared numbers from the original list original_list = [1,2,3,4,5,6,7,8,9] squared = [num*num for num in original_list] # print(squared) # l is the list of all numbers 2 times n where n is an item # in the (0, 1, 2) tuple, for which tuple element is greater than zero. i = [2 * n for n in (0,1,2) if n > 0] # print(i) # Print only odd numbers in the list odd = [num for num in [1, 2, 3, 4, 6, 8, 10, 12, 13, 17, 20, 22, 35, 27, 32, 47] if num % 2] # print(odd) my_list = [[m,n] for m in (5,6) for n in (3,4)] # print(my_list)
e2475054d336406594c21a096c31f4475d330bef
marlonprudente/DataMining
/Exemplos/coletaAPIs/streamingTwitter/processaExemplo1/exemploSimples1.py
732
3.765625
4
import simplejson as json # Arquivo com Tweets tweets_file = open('tweet.txt', "r") #le a linha do arquivo tweet_json = tweets_file.readline() #imprime a linha lida #print tweet_json #remove espacos em branco strippedJson = tweet_json.strip() #converte uma string json em um objeto python tweet = json.loads(strippedJson) print tweet['id'] # ID do tweet print tweet['created_at'] # data de postagem print tweet['text'] # texto do tweet print tweet['user']['id'] # id do usuario que postou print tweet['user']['name'] # nome do usuario print tweet['user']['screen_name'] # nome da conta do usuario #print tweet['entities'] #print tweet['entities']['hashtags'] #print tweet['entities']['hashtags'][0]['text']
5d9311824e0ae00f2142a4adb575b1bf4fc4c572
aalorro/python-projects
/for-loop.py
347
4.53125
5
#!/usr/bin/python3 # Python program that counts the number of characters in a given string print("This python program counts the number of characters in a string\n") string = input("Enter a string: ") count = 0 for letter in string: count += 1 print("You typed: " + string) print("The number of characters in the string is " + str(count))
b56db6e18070f7cb05d86042b4c8e1e69c62cec7
Amicond/AdaptivePython
/2.88.py
68
3.5
4
s=input() print(s.upper() if 97<=ord(s)<=122 and s.islower() else s)
b96855e07178f698664cf7455fd192271e804fb3
abanuelo/Intro-To-Code
/Week 3/introductions_revisited.py
850
4.09375
4
#give me your age age = 1000000 #give me your name name = "MY NAME GOES HERE" #Do a name check with basic if else if name == "MY NAME GOES HERE": print("You still have not changed your name") else: print("Nice to meet you!") #Do a more complex age check if age < 10: print("An elementary student taking my class! Right on!") elif age > 10 and age < 15: print("Middle schooler huh. Nice!") elif age > 15 and age < 30: print("Welcome to the real world sunny.") else: print("Age is but a number I guess.") #Try using input favorite_color = input("What is your favorite color? ") if favorite_color == "blue": print("I love blue!") elif favorite_color == "red": print("Red is aight") elif favorite_color == "green": print("No thank you. Just kidding. Nice color.") elif favorite_color == "pink": print("Pink is perfect.") else: print("Okay then....")
2e6ac79f018c1482906d17d205a17cebda87900e
ModeConfusion/Programming-With-Python-For-DevOps-Engineers-Course
/Lesson-2-Python-Basics/Labs/arithmatic-operators/add.py
77
3.625
4
x = 5 y = 10 def addition(x: int, y: int): print(x + y) addition(10, 5)
e94f898b777968c443069db7d36f4c31d7cf5403
yifang0-0/BADgoose
/8/day3 class.py
843
4.21875
4
class Test: def __init__(self, foo): self.__foo = foo def __bar(self): print(self.__foo) print('__bar') class Test2: def __init__(self,foo): # 定义初始化函数的时候一定要加双下划线,因为构造函数不应该被其他类访问 self.foo = foo def bar(self): print(self.foo) print('bar') def main(): test = Test('hello') # AttributeError: 'Test' object has no attribute '__bar' #test.__bar() # AttributeError: 'Test' object has no attribute '__foo' # print(test.__foo) test._Test__bar() print(test._Test__foo) #通过单个下划线引用类名直接跟两根下划线实现引用 test2 = Test2('hello2') test2.bar() print(test2.foo) if __name__ == "__main__": main()
dc23925be427219894ac1f34a99e4a114d701e4f
AkiraKane/Python
/examples/Web Browser/c_lexicalAnalyzer.py
1,131
3.546875
4
# Crafting Input # Define a variable called webpage that holds a string that causes our lexical # analyzer to produce the exact output below # LexToken(WORD,'This',1,0) # LexToken(WORD,'is',1,5) # LexToken(LANGLE,'<',2,11) # LexToken(WORD,'b',2,12) # LexToken(RANGLE,'>',2,13) # LexToken(WORD,'webpage!',2,14) webpage = """ This is \n webpage=""" import ply.lex as lex tokens = ('LANGLE', # < 'LANGLESLASH', # </ 'RANGLE', # > 'EQUAL', # = 'STRING', # "hello" 'WORD', # Welcome! ) t_ignore = ' ' # shortcut for whitespace def t_newline(token): r'\n' token.lexer.lineno += 1 pass def t_LANGLESLASH(token): r'</' return token def t_LANGLE(token): r'<' return token def t_RANGLE(token): r'>' return token def t_EQUAL(token): r'=' return token def t_STRING(token): r'"[^"]*"' token.value = token.value[1:-1] return token def t_WORD(token): r'[^ <>\n]+' return token htmllexer = lex.lex() htmllexer.input(webpage) while True: tok = htmllexer.token() if not tok: break print tok
40a04c20fd73ed82701252050566bb54f72e7088
rishavb123/MontyHallSimulation
/game.py
1,049
3.828125
4
import sys import numpy as np # Problem Setup num_doors = int(sys.argv[1]) if len(sys.argv) > 1 else 3 prize_door = np.random.choice(num_doors) # Choice choice = input(f"Choose a door number between 0 and {num_doors - 1}: ") while not choice.isdigit() or int(choice) < 0 or int(choice) >= num_doors: choice = input(f"Choose a door number between 0 and {num_doors - 1}:") choice = int(choice) # More Information if prize_door == choice: sudo_prize_door = np.random.choice(num_doors - 1) if sudo_prize_door >= choice: sudo_prize_door += 1 else: sudo_prize_door = prize_door for i in range(num_doors): if i != choice and i != sudo_prize_door: print(f"Door {i} is empty") # Switch? flip = input(f"Do you want to switch to door {sudo_prize_door}? (Y/n) ").lower() == "y" if flip: choice = sudo_prize_door # Results if choice == prize_door: print(f"Congrats! You won a million dollars! The prize was in door {choice}") else: print(f"Sorry door {choice} was empty. The prize was in door {prize_door}")
e565d461c7d914ecdfb0c51eca31f5ef6d86803b
victorrrp/Python-Intermediario
/aula37_curso.py
1,128
4.03125
4
''' Count - Itertools *Função que gera um contador que retorna um iterador O python já tem um contador próprio, basta colocar duas linhas de código: from itertools import count ''' from itertools import count contador = count() #iterador (pode-se colocar quantos quiser, pois é um iterador) print(next(contador)) print(next(contador)) print(next(contador)) print(next(contador)) print(next(contador)) #como é um iterador, o for pede o proximo valor e o contador obedece e cai no laço infinito for valor in contador: print(valor) #para parar o contador pode-se usar o if como limitador if valor >=10: break #é possível dar um inicio ao contador pré determinando um valor contador = count(start=5) for valor in contador: print(valor) if valor >= 10: break #pode-se usar o step para determinar de quanto em quanto pulará a contagem contador = count(start=10, step=1) #é possivel utilizar o step de forma negativa. ex.: (start = 9, step = -1) for valor in contador: print(valor) if valor >= 10: break
962eb10ecb2310e5538845bb7db28f0eaf7dbb54
gistable/gistable
/all-gists/9009867/snippet.py
267
3.75
4
def is_palindrome(x): x = str(x) return x == x[::-1] def find_palindromes(m, n): for i in xrange(m, n): for j in xrange(i, n): x = i * j if is_palindrome(x): yield x print max(find_palindromes(100, 1000))
9c4d06f31a7790cb41799c2a28dcc91071cb4cbe
AK-1121/code_extraction
/python/python_11536.py
194
3.828125
4
# how to replace punctuation in a string python? import string replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation)) text = text.translate(replace_punctuation)
a1eea68dcc1ee821df9ed1e6e4a10ae6c0dc73fd
prekshaa/Computer-Security
/cryptBreak/cryptBreak.py
1,928
3.546875
4
##### #Homework Number: 1 #Name: Prekshaa Veeraragavan #ECN login: pveerar #Due Date: January 28, 2021 ##### #!/usr/bin/env python 3.7) import sys from BitVector import * def cryptBreak(ciphertextFile, key_bv): PassPhrase = "Hopes and dreams of a million years" BLOCKSIZE = 16 numbytes = BLOCKSIZE // 8 # Reduce the passphrase to a bit array of size BLOCKSIZE: bv_iv = BitVector(bitlist=[0] * BLOCKSIZE) # (F) for i in range(0, len(PassPhrase) // numbytes): # (G) textstr = PassPhrase[i * numbytes:(i + 1) * numbytes] # (H) bv_iv ^= BitVector(textstring=textstr) # (I) # Create a bitvector from the ciphertext hex string: FILEIN = open(ciphertextFile) # (J) encrypted_bv = BitVector(hexstring=FILEIN.read()) # Create a bitvector for storing the decrypted plaintext bit array: msg_decrypted_bv = BitVector(size=0) # (T) # Carry out differential XORing of bit blocks and decryption: previous_decrypted_block = bv_iv # (U) for i in range(0, len(encrypted_bv) // BLOCKSIZE): # (V) bv = encrypted_bv[i * BLOCKSIZE:(i + 1) * BLOCKSIZE] # (W) temp = bv.deep_copy() # (X) bv ^= previous_decrypted_block # (Y) previous_decrypted_block = temp # (Z) bv ^= key_bv # (a) msg_decrypted_bv += bv # (b) # Extract plaintext from the decrypted bitvector: outputtext = msg_decrypted_bv.get_text_from_bitvector() # (c) # return output text return outputtext if __name__ == '__main__': for i in range(0,65536): trykey = chr(i) key_bv = BitVector(intVal=i, size=16) decryptedMessage = cryptBreak('encrypted.txt', key_bv) if ('Yogi Berra' in decryptedMessage): print('Encryption Broken!') print(i) print(decryptedMessage) break else: print('Not decrypted yet') print(i)
1f972608888ce67d2903e33fdaab87531ac4945c
GretaP/DayTracker
/DatabaseCreation.py
1,525
3.640625
4
#database creation file import psycopg2 import dbsettings #Creates initial database using connection to postgress server def createdatabase(): #create connection with postgress 'server'. note: under connect must include database=postgress conn = psycopg2.connect(user=dbsettings.user, host= dbsettings.host, password=dbsettings.password, database='postgres') #isolation level needs to be 0 in order to create a database #reason: psycopg wraps everything in a transaction automatically. Transaction ether completes fully or rollbacks. conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() #create database cur.execute("CREATE DATABASE " + dbsettings.database) conn.commit() cur.close() conn.close() #Creates table within existing database def createtable(): #create connection to an existing database conn = psycopg2.connect(user=dbsettings.user, host= dbsettings.host, password=dbsettings.password, database=dbsettings.database) cur = conn.cursor() #table mood create cur.execute("CREATE TABLE mood (id serial PRIMARY KEY, mood integer, datetime timestamp)") #commit changes, close communication with database conn.commit() cur.close() conn.close() #execute code (note: main check allows other code to be used elsewhere) if __name__ == "__main__": createdatabase() print("database created" + dbsettings.database) createtable() print("table mood created")
4693e2ec1e09bcb8f8d5cd4c28de2723c02822ff
DavidBitner/Aprendizado-Python
/Curso/ExMundo1/Ex002Nascimento.py
231
3.828125
4
dia = input('Qual o dia do seu aniversário?') mes = input('Qual o mês do seu aniversãrio?') ano = input('Em que ano você nasceu?') print(dia, '/', mes, '/', ano) print('Você nasceu no dia', dia, 'mês', mes, 'no ano de', ano)
9bdc82cdfd9854bffc47e2461dcc4226804028ba
greenbeen/IntroToPython
/Students/KHart/Session01/break_me.py
454
3.625
4
def name_error(): print a # a has not been defined yet def type_error(): "abc" / 2 # trying to perform operation inappropriate for type def syntax_error(): #While 1 < 2: print "error" #capitalized while when it should be lower case def attribute_error(): b = "string" b.fake_attribute #name_error() #type_error() #syntax_error() """ need to remove comment in function""" #attribute_error()
18dae5cb6c627cb426faa6cd67e88eddf8e5e79a
rkhullar/python-problems
/problems/max_profit.py
806
3.625
4
""" Given the history of prices for a stock, find the optimal time to buy and sell one share. scratch pads https://repl.it/repls/MiniatureRosybrownCommands https://repl.it/repls/FunnyAromaticParticle """ from typing import List, Dict def solution(data: List) -> Dict: min_idx, max_idx, buy_idx, sell_idx = 0, 0, 0, 0 max_profit = 0 for index, value in enumerate(data): if value < data[min_idx]: min_idx = index if value > data[max_idx]: max_idx = index if data[min_idx] < data[buy_idx]: buy_idx = min_idx new_profit = value - data[buy_idx] if new_profit > max_profit: sell_idx = index max_profit = new_profit return dict(buy_idx=buy_idx, sell_idx=sell_idx, max_profit=max_profit)
b3fdaad2bde9c56a471f5f0b522317d11dff620c
VictorSalazar10/prueba
/sexto.py
402
3.609375
4
import time hora=time.strftime("%H:%M:%S") x=(hora.split(':')) print(int x(0)) # def decorador(funcion): # def cambio(): # if int(x[0])>=10 and int(x[0])<=16: # funcion() # else: # print('No se mueve la mano pq no es el horario correcto') # return cambio # # @decorador # def mover_mano_robot(): # print('Moviendo mano robot') # # mover_mano_robot()
c614fa03d1ea01c4f51b205428785d79736e94e4
Jafet6/Jafet6.github.io
/computer-science/exercises/37_4/exercise5.py
507
4.09375
4
def binary_search(array, value): low_index = 0 high_index = len(array) while low_index < high_index: middle_index = (low_index + high_index) // 2 if array[middle_index] == value: return middle_index elif array[middle_index] < value: low_index = middle_index + 1 else: high_index = middle_index - 1 raise ValueError(f"{value} is not in list") array = [2, 3, 4, 10, 40] target = 80 print(binary_search(array, target))
cc7813394ca74c9b894b9c78aa4d1560fee61ca6
kevinelong/PM_2015_SUMMER
/StudentWork/DarWright/Python/Archive/tweet_bot.py
1,181
3.5625
4
import tweepy from Tools.get_weather import Weather # setting up tweedy api with keys and fun things. consumer_key = 'U8cqX60tkVaElYwi2tSF6juU3' consumer_secret = '5PvyrWArTnLRnEwvnrMXLAZW8MWlsnrXEOWy1lJEqNi7IGBM7A' access_token = '3253921376-59a5Q52Qm6FMDorvvHDSttQtp6vRYennGGhIPga' access_token_secret = 'NSprt2x9paoXQWpccbTU6bbyLJ7nnY7vBIlsfTItDSVO6' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # public_tweets = api.home_timeline() # for tweet in public_tweets: # print tweet.text user = api.get_user('classexamplebot') # print user.screen_name # print user.followers_count # for friend in user.friends(): # print friend.screen_name # # api.update_status("Holy cow its a #tweet!") # word search via twitter # interest = raw_input("What are you interested in?> ") # results = api.search(interest) # for x in results: # print x # get a name, find the weather at the twitter location of the name of the famous person name = raw_input("Gimmie a name or @Handle: ") results = api.search_users(name) print "I found\033[0;34m", results[0].name, "\033[0min\033[0;36m", results[0].location, "\033[0m" weather = Weather() print weather.get_weather(weather.get_id_by_location(results[0].location))
ce9143b13822e0fe93921cdabe89de24c94e7373
niki4/leetcode_py3
/medium/061_rotate_list.py
2,601
4
4
""" Given the head of a linked list, rotate the list to the right by k places. Example: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] """ from collections import deque from tools.linked_list import make_linked_list_from_iterable, traverse # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: """ Bruteforce solution using deque for storing and rotating values. Runtime: 40 ms, faster than 40.17% of Python3 Memory Usage: 14.3 MB, less than 10.84% of Python3 """ def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head: return values = deque() node = head while node: values.append(node.val) node = node.next shift = k % len(values) values.rotate(shift) node = head for v in values: node.val = v node = node.next return head class Solution2: """ Algorithm idea: close the ring once you reached the tail, at this point you will know the size of the list, then we calculate the shift to make a new tail (imagine list being rotated physically - tail will be moved as well) and a new head as a next node (after tail). The last step is to break the ring - just unlink new tail (set None). Runtime: 36 ms, faster than 71.20% of Python3 Memory Usage: 14.3 MB, less than 27.22% of Python3 Time complexity: O(n) Space complexity: O(1) """ def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head: return len_values = 1 node = head while node and node.next: len_values += 1 node = node.next old_tail = node old_tail.next = head # close the ring shift = len_values - (k % len_values) - 1 node = head idx = 0 while idx != shift: node = node.next idx += 1 new_tail = node new_head = node.next new_tail.next = None # break the ring return new_head if __name__ == '__main__': solutions = [Solution(), Solution2()] tc = [ ([1, 2, 3, 4, 5], 2, [4, 5, 1, 2, 3]), ([0, 1, 2], 4, [2, 0, 1]), ] for sol in solutions: for inp, rotate_count, exp in tc: inp_head = make_linked_list_from_iterable(inp) res = sol.rotateRight(inp_head, rotate_count) assert traverse(res) == exp, f'Want {exp}, got {traverse(res)}'
ae3b2a1394d51e16949b1b05042555616b4f7087
kheaney21/Final-Project
/Driver.py
1,944
3.953125
4
import sys from voter import voter class election: 'Driver for a simple questionnaire' def __init__(self): #list of voters self.electorate = [] #ballot for q1 self.b0 = [] #ballot for q2 self.b1 = [] #ballot for q3 self.b2 = [] def poll(): 'Prompt user for new votes or to tally' input = ("v - new vote, t - tally, q - quit") while(input != q): #check for valid input if(input == v): #new vote print("new vote \n") voter = voter() electorate.append(voter) #returns encrypted ballot temp = voter.vote() b0.append(temp[0]) b1.append(temp[1]) b2.append(temp[2]) elif(input == t): #tally print("tally \n") self.tally() elif(input == q): print("exit \n") break def tally(): 'Count votes cast' #b1 is false if empty if(not b1): print("no votes cast") total0 = 1 for i in b0: total0 = total0 * b0[i] total1 = 1 for i in b1: total1 = total1 * b1[i] total2 = 1 for i in b2: total2 = total2 * b2[i] #citrus vs berries total0 = electorate[0].decrypt(total0) if (total0 > len(b0)): print("berries has the most votes") elif(total0 < len(b0)): print("citrus has the most votes") else: #tie print("tie") print("results: citrus " + string(len(b0) - total0) + " berries " + string(total0)) #pancakes vs waffles total1 = electorate[0].decrypt(total1) if (total1 > len(b1)): print("waffles has the most votes") elif(total1 < len(b1)): print("pancakes has the most votes") else: #tie print("tie") print("results: pancakes " + string(len(b1) - total1) + " waffles " + string(total0)) #syrup vs jam total2 = electorate[0].decrypt(total2) if (total2 > len(b2)): print("jam has the most votes") elif(total2 < len(b2)): print("syrup has the most votes") else: #tie print("tie") print("results: syrup " + string(len(b2) - total2) + " jam " + string(total2))
2cb4b59e2a433118e87572851ec8205f0cdfb266
Esen9248/Python-Academy
/Examples/January/19.01.18/05.py
289
3.8125
4
res = input('Do you want to procced? (Y,N) ').upper() class ContinueCommandError(Exception): pass def f(): if res == 'Y': print('Yes') elif res == 'N': print('No') else: raise ContinueCommandError(res) try: f() except ContinueCommandError as e: print('Unknown command: ', e)
ccec675354711732b7ef25e967f28380dc895522
nikopoulospet/pythonScripts
/start.py
1,380
3.765625
4
#!/usr/bin/python import random class Nodes: def __init__(self): self.location = (-1,-1) self.searched = False self.neighbors = [] def create(self, location, neighbors): self.location = location self.neighbors = neighbors def assign_neigbors(self, size): if self.location[0] + 1 in range(size[0]): self.neighbors.append(((self.location[0] + 1, self.location[1]),random.random())) if self.location[0] - 1 in range(size[0]): self.neighbors.append(((self.location[0] - 1, self.location[1]),random.random())) if self.location[1] + 1 in range(size[1]): self.neighbors.append(((self.location[0], self.location[1] + 1),random.random())) if self.location[1] - 1 in range(size[1]): self.neighbors.append(((self.location[0], self.location[1] - 1),random.random())) def set_searched(self): self.searched = True def set_unsearched(self): self.searched = False class Map: def __init__(self): self.size = (10,10) def create_map(self): for y in range(self.size[0]): for x in range(self.size[1]): node = Nodes() node.create((x,y), []) node.assign_neigbors(self.size) print node.neighbors if __name__ == "__main__":
28f4689957253f7aca2f1da44320fd8f7ef15197
mariotalavera/ai_jetson_nano
/primer/pythonArraysTwo.py
1,081
4.09375
4
gradeArray=[] numGrades=int(input("How many grades do you have? ")) print("") for i in range(0,numGrades,1): grade=float(input("Input the grade: ")) gradeArray.append(grade) print("") for i in range(0,numGrades,1): print("Your ",i+1," grade is ", gradeArray[i]) print("") print("That's it boys; thank you for playing.") print("") print("The average grade is: ",sum(gradeArray)/len(gradeArray)) print("The lowest grade is ", min(gradeArray)) print("The highest grade is ", max(gradeArray)) print("") print("Now, we are going to do this once more with a more manual way!") print("") lowGrade=100 highGrade=0 for i in range(0,numGrades,1): if lowGrade > gradeArray[i]: lowGrade=gradeArray[i] if highGrade < gradeArray[i]: highGrade=gradeArray[i] print("The minimum grade, again, is ", lowGrade) print("The maximum grade, again, is ", highGrade) bucket=0 for i in range(0,numGrades,1): bucket=bucket+gradeArray[i] average=bucket/numGrades print("The average grade, again, is ", average) # Homwwork done. # now average all grades # give min grade # give max grade
d9d01be95165115cf4c8f2eeeef3438f02485ae8
rjcmarkelz/python_the_hard_way
/exercises/ex13.py
272
3.59375
4
from sys import argv script, first, second, third = argv age = float(raw_input("How old are you in years?")) print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your age in years is:\t", age
702e2a5de9a35852cf52c4d7f17fbba346e35feb
z3r0sw0rd/COMP2041
/test09/sort_words.py
200
3.65625
4
#!/usr/bin/python3 import sys import re for line in sys.stdin: line = line.strip() words = re.split(r'\s+', line) for word in sorted(words): print(word + " ", end = '') print()
168c8fe840a84bbc71181f15e397b5a87f99a5da
AmyBrowneDesigns/CC_RPS_FLASK_WEEKEND_HOMEWORK
/tests/game_test.py
482
3.5
4
import unittest from app.models.game import Game from app.models.player import Player class TestGame(unittest.TestCase): def setUp(self): self.player1 = Player('Amy', "rock") self.player2 = Player('Bob', 'scissors') self.banana = Player("matt", "paper") self.game = Game("Amy", "Bob") def test_game_output(self): self.assertEqual("Rock smashes scissors, Player1 wins!", self.game.rps(self.player1, self.player2))
25667927a66b41e6115c94013e78737e08cfa673
rheard/ProjectEuler
/p082.py
2,197
3.84375
4
""" The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994. ( 131 673'234'103'18' '201'96''342'965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 37 331 ) Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."), a 31K text file containing a 80 by 80 matrix, from the left column to the right column. """ import os from copy import deepcopy try: from .utils import output_answer except ImportError: from utils import output_answer with open('ProjectEuler/p081_matrix.txt', 'r') as rb: __GRID = [[int(x) for x in line.split(',')] for line in rb.readlines()] def solve(grid=None): """ We can use a similar process to problem 81, except that we need to go back for a second pass on the column to determine if moving upwards would be a better choice than downwards. And we modify the solution slightly to seek out the right column instead of the bottom right cell. """ grid = deepcopy(grid or __GRID) while len(grid[0]) > 1: # Step 1.1 Assume on the bottom row, we must go to the right grid[-1][-2] = [grid[-1][-2], grid[-1][-1]] # Step 1.2 Walk up the second to last column to determine if we should move down or to the right for i in reversed(range(len(grid) - 1)): grid[i][-2] = [grid[i][-2], min(sum(grid[i + 1][-2]), grid[i][-1])] # Step 2 Walk down the second to last column to determine if we should keep the current movement, or go up for i in range(1, len(grid)): grid[i][-2][1] = min(grid[i][-2][1], sum(grid[i - 1][-2])) # Step 3 convert second to last column to single integers and resize the grid for i in range(len(grid)): grid[i].pop() grid[i][-1] = sum(grid[i][-1]) return min(x[0] for x in grid) solve.answer = 260324 if __name__ == '__main__': output_answer(os.path.splitext(__file__)[0], solve)
a83f1ceaa3eb082117a883c4f815f435b68b0659
Jay168/ECS-project
/prog6.py
86
3.578125
4
celsius=float(input("Please provide temperature in degree celsius\n")) print(celsius)
56413d8f9c524b32745d3d917a9d1ceb026d8774
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/af7b69640e274d6d8a746f5ec4603bfe.py
200
3.734375
4
def hamming(s1, s2): hamming_distance = 0 for i, j in zip(s1+' '*(len(s2)-len(s1)), s2+' '*(len(s1)-len(s2))): if i != j: hamming_distance += 1 return hamming_distance
dea6624c859356ed196474cbb7f746f5d5b44dd8
DayGitH/Python-Challenges
/DailyProgrammer/DP20120808C.py
1,199
4.1875
4
""" [8/8/2012] Challenge #86 [difficult] (2-SAT) https://www.reddit.com/r/dailyprogrammer/comments/xx970/882012_challenge_86_difficult_2sat/ Boolean Satisfiability problems are problems where we wish to find solutions to boolean equations such as (x_1 or not x_3) and (x_2 or x_3) and (x_1 or not x_2) = true These problems are notoriously difficult, and k-SAT where k (the number of variables in an or expression) is 3 or higher is known to be NP-complete. However, [2-SAT](http://en.wikipedia.org/wiki/2-satisfiability) instances (like the problem above) are NOT NP-complete (if P!=NP), and even have linear time solutions. You can encode an instance of 2-SAT as a list of pairs of integers by letting the integer represent which variable is in the expression, with a negative integer representing the negation of that variable. For example, the problem above could be represented in list of pair of ints form as [(1,-3),(2,3),(1,-2)] Write a function that can take in an instance of 2-SAT encoded as a list of pairs of integers and return a boolean for whether or not there are any true solutions to the formula. """ def main(): pass if __name__ == "__main__": main()
d278d292850f2e9d4ae304f49290ddd4d6dd81aa
varununayak/refactoring
/04_inline_variable.py
764
4.0625
4
# Inline Variable class Order: def __init__(self, base_price: float) -> None: self.base_price = base_price def expensive_base(order: Order) -> bool: base_price = order.base_price return base_price > 1000 """ Sometimes the name of a variable that is declared before an expression doesn't really communicate more than the expression itself. In this case we can inline the variable We need to make sure that the right hand side of the assignment does not have any side effects """ def expensive_base_refactored(order: Order) -> bool: return order.base_price > 1000 if __name__ == "__main__": print(f"Expensive?: {expensive_base(Order(base_price=10))}") print(f"Expensive?: {expensive_base_refactored(Order(base_price=10))}")
0248933df015df076df258515cc6a3d1eae11f6e
filfilt/pythonRepository
/Part014 Identity and Membership.py
389
3.84375
4
#Identity & Membership # Identity: Is and Is not ''' lst1 = [] lst2 = [] lst3 = lst1 print(lst1 is lst2) # False b/s they are in diff place print(lst1==lst1) # True b/s they are empty print(lst3==lst1) # True they have the same value print(lst3 is lst1) # True they are in the same place ''' #Membership fruits = ['banana','apple'] print('orange' in fruits) print('orange' not in fruits)
3b1270caca775ddf7c91cefe1ca65f61a7d91930
PaulIsenberg/Election_Analysis
/PyPoll_Challenge.py
3,911
3.765625
4
# Add our Dependencies import csv import os # Assign a variable for the file to load and the path. file_to_load = os.path.join("Resources/election_results.csv") # Assign a variable to save the file to a path. file_to_save = os.path.join("analysis", "election_analysis.txt") # 1. Initialize a total vote counter. total_votes = 0 # Candidate Options candidate_options = [] ## CHALLENGE county_options = [] # Declare an empty dictionary to total candidadte votes. candidate_votes = {} ## CHALLENGE Declare an empty dictionary for total county votes county_votes = {} # Winning candidate and Winning Count Tracker. winning_candidate = "" winning_count = 0 winning_percentage = 0 ## CHALLENGE winning county and winning county tracker #largest_county_turnout = "" winning_county = "" county_count = 0 county_percentage = 0 # Open the election results and read the file. with open(file_to_load) as election_data: file_reader = csv.reader(election_data) headers = next(file_reader) #Print each row in the csv file. for row in file_reader: total_votes += 1 candidate_name = row[2] if candidate_name not in candidate_options: candidate_options.append(candidate_name) candidate_votes[candidate_name] = 0 candidate_votes[candidate_name] += 1 county_name = row[1] if county_name not in county_options: county_options.append(county_name) county_votes[county_name] = 0 county_votes[county_name] += 1 with open(file_to_save, "w") as txt_file: # Print the final vote count in terminal election_results = ( f"\nElection Results\n" f"-------------------------\n" f"Total Votes: {total_votes:,}\n" f"-------------------------\n") print(election_results, end="") txt_file.write(election_results) print("County Votes:") ## CHALLENGE Do for county votes here what I do for candidate votes below for county in county_votes: votes = county_votes[county] vote_percentage = float(votes) / float(total_votes) * 100 county_results = (f"{county}: {vote_percentage:.1f}% ({votes:,})\n") print(county_results) txt_file.write(county_results) ## CHALLENGE This is where I display the Largest County Turnout data. Mirrored of Winner Candidate logic ## CHALLENGE I not fully sure if the "County Winner" variables need to be unique to county or can copy the same variable names from the Candidate code if (votes > county_count) and (vote_percentage > county_percentage): county_count = votes county_percentage = vote_percentage winning_county = county winning_county_summary = ( #f" \n" CHALLENGE commented put due to terminal error, but this is what the assignment calls for f"-------------------------\n" f"Largest County Turnout: {winning_county}\n" f"-------------------------\n") print(winning_county_summary) txt_file.write(winning_county_summary) for candidate in candidate_votes: votes = candidate_votes[candidate] vote_percentage = float(votes) / float(total_votes) * 100 candidate_results = (f"{candidate}: {vote_percentage:.1f}% ({votes:,})\n") print(candidate_results) txt_file.write(candidate_results) if (votes > winning_count) and (vote_percentage > winning_percentage): winning_count = votes winning_percentage = vote_percentage winning_candidate = candidate winning_candidate_summary = ( f"-------------------------\n" f"Winner: {winning_candidate}\n" f"Winning Vote Count: {winning_count:,}\n" f"Winning Percentage: {winning_percentage:.1f}%\n" f"-------------------------\n") print(winning_candidate_summary) txt_file.write(winning_candidate_summary)
7473ea8c60e70f9205af8334e0215e527b4532c2
KKosukeee/CodingQuestions
/LeetCode/48_rotate_image.py
1,247
3.96875
4
""" Solution for 48. Rotate Image https://leetcode.com/problems/rotate-image/ """ class Solution: """ Runtime: 40 ms, faster than 74.53% of Python3 online submissions for Rotate Image. Memory Usage: 13.4 MB, less than 5.35% of Python3 online submissions for Rotate Image. """ def rotate(self, matrix): """ Main function to solve a question. Do not return anything, modify matrix in-place instead. Args: matrix: 2D matrix containing integer values. Returns: """ # Create a set for recording swapped indices swapped_indices = set() # Loop through for each element to swap them for i in range(len(matrix)): for j in range(len(matrix[0])): # Calculate new location new_col = len(matrix[0]) - i - 1 new_row = j # If current indices are not swapped already, then swap them if (i, j) not in swapped_indices: matrix[i][j], matrix[new_row][new_col] = matrix[new_row][new_col], matrix[i][j] # Now new_row and new_col are in right place, add it. swapped_indices.add((new_row, new_col))
b006f3f99e33f2c2fb7f7c3f5405863030225382
yesid23/python_class
/cajero automatico1.py
1,775
4.03125
4
#cajero automatico print("cajero automatico") atras = ("y") intentos = 3 saldo = 1.000.000 while intentos >= 0: clave = int(input("digite su clave:")) if clave == (1234): print("clave correcto ") while atras not in ("n", "no", "N", "No"): print("====menu===/n1-saldo/n2-retiro/n3-cambiarclave/n4-salir/n====") op = int(input()) if op == 1: print("su saldo actual es:" saldo) atras input("desea realizae otra operacion?[y/n]") if atras in ("n", "no", "N", "No"): print("") print("gracias...") exit() elif op == 2: retiro = int(input("/[10.000/n 20.000/n 50.000/n 100.000/n 200.000/n 400.000/n 600.000/n 1.000.000/n]: dijite la cantidad a retirar : ")) if retiro in [10.000, 20.000, 50.000, 100.000, 200.000, 400.000, 600.000, 1.000.000,]: saldo = retiro print("su saldo es ", saldo) atras = input("desea realizae otra operacion?[y/n]") if atras in ("n", "no", "N", "No"): print("") print("gracias...") exit() elif retiro = [10.000, 20.000, 50.000, 100.000, 200.000, 400.000, 600.000, 1.000.000,]: print("cantidad no valida") atras = input("desea realizae otra operacion?[y/n]") if atras in ("n", "no", "N", "No"): print("gracias...") exit() elif retiro == 1: retiro = int(input("intenta otra cantidad")) elif op == 3: cambiarclave= int(input("digite la cantidad a cambiar:")) clave = cambiarclave print("su nueva clave es", clave) if atras in ("n", "no", "N", "No"): print("") print("gracias...") exit() elif op==4: print("cerrando....") exit() elif clave = ('1234'): print("clave incorrecto") intentos = 1 if intentos == 0: print("no mas intentos, gracias por usar el cajero de **UNCENTAVOMAS**") break
a10a232f8856b5ac5cebef4f56ede22de8a935a6
crazywiden/Leetcode_daily_submit
/Widen/LC694_Number_of_Distinct_Islands.py
2,554
3.796875
4
""" LC694 -- number of distinct islands Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other. Example 1: 11000 11000 00011 00011 Given the above grid map, return 1. Example 2: 11011 10000 00001 11011 Given the above grid map, return 3. Notice that: 11 1 and 1 11 are considered different island shapes, because we do not consider reflection / rotation. Note: The length of each dimension in the given grid does not exceed 50. """ # bfs # Runtime: 252 ms, faster than 67.69% of Python3 online submissions for Number of Distinct Islands. # Memory Usage: 14.4 MB, less than 100.00% of Python3 online submissions for Number of Distinct Islands. import heapq class Solution: def numDistinctIslands(self, grid) -> int: if len(grid) == 0: return 0 directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] cnt = 0 islands = [] visited = set() n_row = len(grid) n_col = len(grid[0]) for i in range(n_row): for j in range(n_col): if (i, j) in visited: continue if grid[i][j] == 0: continue # use bfs to find all the island single_island = set() queue = [] heapq.heappush(queue, (i, j)) while queue: x, y = heapq.heappop(queue) for direction in directions: new_x = x + direction[0] new_y = y + direction[1] if (new_x, new_y) in visited: continue if new_x >=0 and new_x < n_row and new_y >= 0 and new_y < n_col: visited.add((new_x, new_y)) if grid[new_x][new_y] == 1: shift = (new_x - i, new_y - j) single_island.add(shift) heapq.heappush(queue, (new_x, new_y)) if single_island not in islands: cnt += 1 islands.append(single_island) return cnt
3a57b14deaec52ccfb1d95dc4f6c04422193c58a
michelleweii/Leetcode
/05_图dfs与bfs/1_回溯算法/3_子集问题/78-子集.py
1,163
3.734375
4
""" middle 2022-01-14 回溯法-子集问题(无重复元素) 子集问题,树枝上的所有节点都要(遍历整棵树)。解集不能包含重复的子集start_index+1。 输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ class Solution(object): def __init__(self): self.res = [] self.path = [] def subsets(self, nums): if not nums:return self.res self.dfs(nums,0) return self.res def dfs(self,nums,start_index): self.res.append(self.path[:]) # 与出口的前后顺序不能交换,否则包含最后一位的结果不会添加至res # 定义出口 if start_index>=len(nums): return # 树层for循环 for i in range(start_index, len(nums)): self.path.append(nums[i]) # 树枝递归 self.dfs(nums,i+1) # i+1 取过的位置,的下一位开始(元素不重复取) self.path.pop() if __name__ == '__main__': nums = [1, 2, 3] print(Solution().subsets(nums)) # [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
8fa3f522e409767302a5d80352ad8b88eae80a01
MDolinski/SamplePythonProjects
/NoughtsAndCrosses.py
3,096
3.84375
4
from random import randint class Board(object): def __init__(self, size): assert isinstance(size, int) self.size = size self.positions = [["-"] * self.size for i in range(self.size)] def __repr__(self): board_string = '\n'.join(['|'.join(self.positions[i]) for i in range(self.size)]) return 'I am board of size %i \n' % self.size + board_string def __getitem__(self, positions): return self.positions[positions[0]][positions[1]] def clear(self): self.positions = [[" -"] * self.size for i in range(self.size)] def insert(self, symbol_type, positions): assert (symbol_type == 'X' or symbol_type == 'Y') self.positions[positions[0]][positions[1]] = symbol_type def check_victory_conditions(self): rows = list(map(lambda x: ''.join(x), self.positions)) columns = list(map(lambda x: ''.join(x), zip(*self.positions))) antydiag = list(map(lambda x: ''.join(x), [[self.positions[i][j] for i in range(self.size) for j in range(self.size) if i + j == k] for k in range(2 * self.size - 1)])) diag = list(map(lambda x: ''.join(x), [[self.positions[i][j] for i in range(self.size) for j in range(self.size) if -i + j == k] for k in range(-self.size + 1, self.size)])) return 'X' * self.size in rows or 'Y' * self.size in rows \ or 'X' * self.size in columns or 'Y' * self.size in columns \ or 'X' * self.size in diag or 'Y' * self.size in diag \ or 'X' * self.size in antydiag or 'Y' * self.size in antydiag class NoughtsAndCorsses(object): def __init__(self, size): self.board = Board(size) def _play_turn(self, player_mark): assert player_mark in 'XY' fieldpos_x = randint(0, self.board.size - 1) fieldpos_y = randint(0, self.board.size - 1) while (self.board[fieldpos_x, fieldpos_y] != '-'): fieldpos_x = randint(0, self.board.size - 1) fieldpos_y = randint(0, self.board.size - 1) return (fieldpos_x, fieldpos_y) def play_bot_game(self): turn = 0 end = False while not end and turn < self.board.size ** 2: turn += 1 mark = 'X' if turn % 2 == 0 else 'Y' self.board.insert(mark, self._play_turn(mark)) print(self.board) end = self.board.check_victory_conditions() outcome = 'Winner is player %s' % mark if (turn < self.board.size ** 2) \ else "The game ended with draw" print(outcome) game = NoughtsAndCorsses(5) game.play_bot_game()
ac5705b3e4b760541a22ce49a67029ce07a3ee97
Cainuriel/Training-Python-
/ficheros permanentes.py
2,302
3.9375
4
import pickle class persona(): def __init__(self, nombre, genero, edad): self.nombre = nombre self.genero = genero self.edad = edad print("Se ha creado a una persona. Se llama: ", self.nombre) # metodo que crea una cadena de texto con la informacion de un objeto: def __str__(self): return "{}{}{}".format(self.nombre, self.genero, self.edad) # IMPORTANTE: CADA VEZ QUE EJECUTES ESTE PROGRAMA GUARDARA EN UN ARCHIVO EXTERNO # EL OBJETO QUE AQUI CREES. PRUEBA A CAMBIAR LAS CARACTERISTICAS DEL OBJETO PERSONA # Y EJECUTA EL PROGRAMA. COMPROBARAS COMO SE GUARDA PERMANENTE EN EL ARCHIVO. persona1 = persona("Antonio ","Hombre ",51) class listapersonas(): personas = [] # el constructor genera el archivo permanente en donde almacenaremos a las personas # el modo "ab+" permite agregar de forma binaria def __init__(self): fichero_personas = open("Ficheros Personas","ab+") # colocamos el cursor al principio para poder leer a todas las personas fichero_personas.seek(0) try: self.personas = pickle.load(fichero_personas) # cargamos datos en la lista print("Se cargaron {} personas del fichero externo".format(len(self.personas))) # indicamos numero de personas except: print("Fichero vacio") # mensaje de error en el caso de que el fichero este vacio finally: fichero_personas.close() del (fichero_personas) # siempre ejecutaremos estas dos instrucciones, independientemente de la excepcion. def agregarPersonas(self, p): # metodo "append" para agregar a la lista objetos self.personas.append(p) self.guardarpersonasenficheroexterno() # este metodo parece igual al de mostrarinfodeficheroexterno... ???? def mostrarPersonas(self): for p in self.personas: print(p) def guardarpersonasenficheroexterno(self): fichero_personas = open("Ficheros Personas","wb") pickle.dump(self.personas,fichero_personas) fichero_personas.close() del (fichero_personas) def mostrarinfodeficheroexterno(self): print("Informacion del fichero externo: ") for p in self.personas: print(p) # creamos un objeto que agregue a las personas a una lista: lista_personas = listapersonas() lista_personas.agregarPersonas(persona1) lista_personas.mostrarinfodeficheroexterno()
77fc096dcb75724e6a902f5a920de8bf219482e8
jrgosalia/Python
/problem3_gameOfLuckySeven.py
2,377
4
4
""" Program : problem3_gameOfLuckySeven.py Author : Jigar R. Gosalia Verion : 1.0 Course : CSC-520 (Homework 1) Prof. : Srinivasan Mandyam Game of lucky sevens -------------------- 1. Player enters bet. 2. Player presses enter to roll the dices. 3. If the dots count equal to 7 then player wins $4. 4. If the dots count not equal to 7 then player looses $1. 5. Repeat steps 1 to 4 till the player looses game i.e. amount is $0. """ from random import randint; # Constants LUCKY_SEVEN = 7; WIN_AMOUNT = 4; LOOSE_AMOUNT = 1; count = 0; bet = 0; print("Welcome to Game of Lucky Sevens.", end="\n\n"); print("Roll the dices, if you get 7 then you win else you loose!", end="\n\n"); input("Press ENTER to start execution ... \n"); # Get starting balance from the player. while (True): value = input("Please enter your bet: $"); if (value == "" or not value.isdigit() or int(value) <= 0): print("ERROR : Bet should be a whole number greater than $0 to start", end="\n\n"); else: amount = int(value); break; input("Press ENTER to roll the dices ... "); # Keep on playing game until either the amount is less than or equal to $0 and player looses. while(amount != 0): # Skip accepting bet for the first time as player has already entered bet amount. if (count != 0): betValue = input("Please enter your bet: $"); # Error appropriately if the bet is less than $0 or greater than balance. if (betValue == "" or not betValue.isdigit() or int(betValue) <= 0 or int(betValue) > amount): print("ERROR : Bet should be a whole number greater than $0 and less than max balance $%d" % (amount), end="\n\n"); continue; bet = int(betValue); input("Press enter to roll the dices ... "); amount = amount - bet; count += 1; # Roll the dices. diceOne = randint(1, 6); diceTwo = randint(1, 6); dotsCount = diceOne + diceTwo; # Check whether player WIN or LOOSE if (dotsCount == LUCKY_SEVEN) : amount = amount + bet + WIN_AMOUNT; result = "WIN" else: amount = amount + bet - LOOSE_AMOUNT; result = "LOOSE" # Display the results for the roll. print("Roll#(%d) DotsCount(%d) Win/Loose(%s) Balance($%d)\n" % (count, dotsCount, result, amount)); print("You Loose, Game Over!", end="\n\n"); input("Press ENTER to exit ... \n");
0d73fbe0cca9b55c913355f241c1b94c6be114f4
sdmunozsierra/barebones-python-module
/App/main_app.py
574
3.53125
4
"""Example file containing the main executable for an app.""" from logging import DEBUG from Logger import logging_config # Create a Logger for main_app MAIN_LOG = logging_config.get_simple_logger("main_logger", DEBUG) # Main program def __main__(): MAIN_LOG.info("Running Main Program inside main_app.py") MAIN_LOG.info("Using simple_function to add 1 to 1") simple_function(1) # Simple function to be tested def simple_function(real_number): """:returns: real_number + 1""" MAIN_LOG.debug("Adding 1 to %d", real_number) return real_number + 1
0b8e9818a762cfb359f0481032b16a5c66f7104f
this-josh/advent_of_code_2020
/code/day_6.py
1,073
3.53125
4
with open("./inputs/day_6.txt", "r") as f: input_data = f.readlines() input_data = [line.strip() for line in input_data] input_data.append("") #  don't miss the last line def common_values(people): from functools import reduce return list(reduce(lambda i, j: i & j, (set(x) for x in people))) def part_one(input_data): # Divide into groups # len(set(group)) this_group = "" number_of_yes = 0 for line in input_data: if line == "": this_group = set(this_group) number_of_yes += len(this_group) this_group = "" continue this_group += line return number_of_yes def part_two(input_data): people_in_group = [] number_of_all_yes = 0 for person in input_data: if person == '': number_of_all_yes +=len(common_values(people_in_group)) people_in_group = [] continue people_in_group.append(set(person)) return number_of_all_yes one = part_one(input_data) two = part_two(input_data) print(one) print(two)
680213be0bca440bd3f7172671b3e28046b89791
3123958139/20180920hwjj
/AutoSendBW163Email/src/test5.py
734
3.515625
4
def ___get_currency_price(list_currency=['BTC', 'EOS', 'ETH', 'XRP', 'BCH', 'LTC']): import urllib.request cur_price_dict = {} headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'} for cur in list_currency: req = urllib.request.Request(url='https://www.okex.com/api/v1/ticker.do?symbol=%s_usdt' % cur.lower(), headers=headers) cur_data = eval(urllib.request.urlopen(req).read()) print(cur_data) cur_price_dict[cur] = float(cur_data['ticker']['buy']) return cur_price_dict print(___get_currency_price())
a431f11214294f51248b4e16204fb9e78090df25
MrMace/PythonProjects
/gradient_bar.py
1,210
3.96875
4
#Matt Mace #BDAT610/week3 #gradient_bar import graphics as g #import for graphics library #creates screen winWidth = 400 #window width winHeight = 300 #window Height win = g.GraphWin("Gradient Bar", winWidth,winHeight) win.setBackground('red')#verifiy background is not seen under gradient #vars numBars = 12 #change this to change outcome barWidth = winWidth / numBars #sets width of bars colorChangeAmount = 255 / numBars #sets the number for colorchange startPointX = 0 startPointY = 0 endPointX = barWidth endPointY = winHeight #bottom of screen colorChanger = 0 #loops through and creates rectangles Fills them with color for index in range(numBars): #creates the rectangle gradientLine = g.Rectangle(g.Point(startPointX,startPointY),g.Point(endPointX,endPointY)) gradientLine.setFill(g.color_rgb(0,int(colorChanger),0)) #fills the rectangle gradientLine.setWidth(0) gradientLine.draw(win)#draws the Rectangle to screen startPointX = endPointX #sets starting position of next Rectangle endPointX = endPointX + barWidth #sets ending position next Rectangle colorChanger = colorChanger + colorChangeAmount #changes the color
6606d91ce412e3596642d99784712cfd198c9c29
SUJEONG999/Python_Practice
/day3/whileLab4.py
548
3.96875
4
while True: Month = int(input("월을 입력하시오(숫자만):")) if 1 <= Month <= 12: if Month == 12 or Month == 1 or Month == 2: print (Month, "월은 겨울",sep="") elif Month == 3 or Month == 4 or Month == 5: print(Month, "월은 봄",sep="") elif Month == 6 or Month == 7 or Month == 8: print(Month, "월은 여름",sep="") else: print(Month, "월은 가을",sep="") else : print("1~12 사이의 값을 입력하세요!") break
e54523ce4dca08e0a889e4ee6eacfd40cbb340b2
FarzanAkhtar/Intro-to-Webd
/Week 1 Practice Problems/4.py
455
4.03125
4
#Commas in number def addcommas(a): for element in a: b=insertCommas(element) print(b) def insertCommas(a): a=a[::-1] b=[] for i in range(len(a)): b.insert(0,a[i]) if (i+1)%3 == 0: b.insert(0,",") if b[0] == ",": b.pop(0) return ("".join(b)) a=[] n=int(input("No of numbers:")) for i in range(n): a.append((input())) print("Numbers with commas inserted:") addcommas(a)
e941cdb40f5852c9a01038c5e0db7bae7545883d
Zhouenze/learnPython
/code/ch15t17c1.py
5,269
3.5
4
# -*- coding: utf-8 -*- #中文注释需要 X = 99 L = [] def func(): L.append(5) #虽然改变了但不是赋值语句,L仍是全局变量不是本地变量 print L #全局版本 # L = 1 #解注释会和上面冲突:有赋值语句的话L在整个本地命名空间都是本地变量,和上面的全局变量用法冲突 # print X #解注释会和下面冲突:X由下面已确定是本地变量,还没产生就引用。这里无法引用到全局版本 X = 98 #X是本地变量与外界不冲突 print X #本地版本 global Z #不管是否有赋值语句,Z认为是全局变量 Z = 100 #原来没有,在全局新创建了 return func() print L, X, Z #全局版本 def func2(): print 3 #没有return自动返回None func3 = func2 #函数也是对象,可以多名引用 def func4(func): #函数也是对象,可以参数传递 func() return func3() func4(func2) from ch15t17c3 import c1var #会运行在ch15t17c3中所有代码并得到c1var,如在此基础上再import其他变量则不必运行直接获得 print c1var #通过ch15t17c3获得ch15t17c2,发现其中c1var的值和ch15t17c2代码书写的不同 # print X #该部分不展示,因为如下述会多很多意义不明的输出。此方法可以用但一般按照书上340的方法用 # def func5(): # import ch15t17c1 #在函数内引用全局变量且不与本地同名变量发生冲突的方法1,注意因为运行了ch15t17会多很多输出 # ch15t17c1.X += 1 # print ch15t17c1.X # import sys #方法2。如果ch15t17模块已经import过则可以使用这种方法 # thisMod = sys.modules['ch15t17c1'] # thisMod.X += 1 # print thisMod.X # X = 3 # print X # return # func5() #如果注释掉func5的方法1则这里的调用会失败因为方法2中所需的模块未打开,但如果按书上的方法调用则会成功因为已经打开 def g(): x = 1 def h(): # def h(x=x): #成功,x通过默认参数被保存 # def h(x=y): #失败,def及参数列表和默认参数在def运行时被评估,此时y还没出现 print x, y #y能看到,因为代码块在函数运行时评估,此时y已经出现,def运行时不出现没关系 # print z #失败,因为代码运行时z还没出现 y = 2 h() z = 3 extra() #调用一个之后才定义的函数是可行的,只要运行g时extra已经定义好就行,因为那时g的定义才被验证 return h def extra(): print 'extraFunc' return h = g() h() #x和y通过E作用域变量依赖被保存,可以在函数体中使用 L = [] for i in range(3): #嵌套作用域中的变量在嵌套定义的函数被调用时才进行查找,所以循环定义多个函数不用默认参数会造成所有函数相同 #因为他们都看同一个变量名i L.append((lambda x:x*i)) print i #for不构成一个单独的命名空间,因此上面三个lambda函数所指向的i和这里的和下面的都是同一个,导致最后i=4,L[0](2)=2*4=8 for i in range(3,5): L.append((lambda x, i = i:x*i)) #解决方法是用默认参数因为它在def运行时评估,能记住当时值 print L[0](2), L[1](2), L[3](2), L[4](2) def func6(x = []): #可变默认值很危险,因为默认值是以单一对象实现的,多次调用函数看到的是同一个列表,这个列表的内容可能变化 x.append(1) print x return func6() #如此处所示,可变默认值导致调用函数时看到的默认的x不一致 func6() def func7(x = None): #这三行是上述问题的解决方法,注意本行x=None不可省略因为否则x会强制有值 if x is None: x = [] x.append(1) print x return func7() func7() def func(a, b, c = 3, d = 3, *e, **f): #顺序:无默认,有默认,*,** print a,b,c,d,e,f return func(1, d = 4, e = 6, *[2], **{'g':4, 'h':5}) #顺序同上,先打散,再配顺序参数,再配关键字参数,*收集其他位置参数,**收集其他关键字参数,再配默认值,然后非*/**的参数要不重不漏则成功 #a顺序配1,b顺序配2,c默认配3,d关键字配4,e没收集到东西,f收集到e、g和h print map((lambda (a,b):a), [(1,2),(3,4),(5,6)]) #lambda中只有一个元组参数,隐含序列赋值语句用于解析列表 import operator #该模块提供内置表达式的函数 print map(operator.add, [1,5,9], [2,4,8]) #map将各个列表的元素取出来作为分开的参数调用函数 def gen(N): for i in range(N): yield i return gen1 = gen(2) #一个生成器函数可以构造多个生成器对象 gen2 = gen(3) gen3 = (i for i in range(3)) #生成器表达式类似列表解析,返回一个生成器 print gen1.next(), gen1.next(), gen2.next(), gen2.next(), gen3.next(), gen3.next()
24dec35d32ce75986c9a36ff009c51db13c6a4a1
aswinsajikumar/Python-Programs
/Permutation & Combination of a Number.py
272
3.578125
4
def fact(x): f=1 for i in range(x,1,-1): f=f*i return f n=int(input('Enter n:')) r=int(input('Enter r:')) d=n-r nf=fact(n) rf=fact(r) df=fact(d) ans=nf/(rf*df) print ('Combination(nCr)=',ans) ans1=ans*rf print ('Permutation(nPr)=',ans1)
c25f298bdd9bef1eefa7f22dd6b0f34cba101d8f
llgeek/leetcode
/105_ConstructBinaryTreeFromPreorderAndInorderTraversal/solution1.py
794
3.734375
4
""" speed up by preprocessing the indexes in preorder """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def helper(instart, inend): if instart > inend: return None nonlocal pos root = TreeNode(preorder[pos]) pos += 1 root.left = helper(instart, val2idx[root.val] - 1) root.right = helper(val2idx[root.val] + 1, inend) return root if not preorder: return None val2idx = {val : idx for idx, val in enumerate(inorder)} pos = 0 # idx in preorder return helper(0, len(inorder) - 1)
dcc5d11886fb68b3a0654dc0677873721c920c0a
doitfool/leetcode
/Pascal's Triangle II.py
1,074
4.0625
4
""" @Project: leetcode @file: Pascal's Triangle II.py @author: AC @time: 2016/5/10 @Description: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] """ class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ if rowIndex == 0: return [1] elif rowIndex == 1: return [1, 1] elif rowIndex > 1: pre, j = [1, 1], 1 while j < rowIndex: mid = [pre[i]+pre[i+1] for i in xrange(len(pre)-1)] pre = [1] + mid + [1] j += 1 return pre s = Solution() for i in xrange(10): print s.getRow(i)
eb74ccb8365739de446fb029f9bfa682dcc73abb
Rogerd97/mintic_class_examples
/P47/08-06-2021/lambda_function.py
948
4.09375
4
# reference # MLA, 8.ª edición (Modern Language Assoc.) # Romano, Fabrizio, et al. Python: Journey From Novice to Expert. Packt Publishing, 2016. # APA, 7.ª edición (American Psychological Assoc.) # Romano, F., Phillips, D., & Hattem, R. van. (2016). Python: Journey From Novice to Expert. Packt Publishing. # example 1: adder def adder(a, b): return a + b # is equivalent to: adder_lambda = lambda a, b: a + b # example 2: to uppercase def to_upper(s): return s.upper() # is equivalent to: to_upper_lambda = lambda s: s.upper() # Exercise: Transform to lambda type the below functions def is_multiple_of_five(n): return not n % 5 def get_multiples_of_five(n): return list( filter(is_multiple_of_five, range(n))) print(get_multiples_of_five(50)) # Write a Python program to filter a list of integers using Lambda that returns the even numbers nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = list(filter(lambda x: x % 2 == 0, nums))
5d963aea7e1a1ee053da10aad935e0bcb4aa5d6e
jhonathanmpg/clase-26
/src/ale/utils.py
1,439
3.984375
4
import math # Escribir una funcion que basado en el radio: # calcule la sup de un circulo # calcule la circunferencia # calcule la sup de una esfera # calcule el vol de una esfera def calcularCircunferencia(radio): """ calcularCircunferencia() -> float radio -- radio is in float """ circunferencia = math.pi * 2 * radio return circunferencia def sumatoria(x): resultado = (x * (x + 1)) / 2 return resultado def calVolumenParalelepipedo(x, y, z): # global resultado resultado = x * y * z return resultado # Esto sera una constante complex_zero = {0, 0} def complex(real=0.0, imag=0.0): """Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero def useless(func): #inner functions def other(x): x = x * 2 return func(x) return other def factorial_decorator(func): def checker(x): if type(x) == int and x >= 0: return func(x) else: raise TypeError("Error, no se puede realizar operacion") return checker #@useless #useless(factorial(4)) <- #reemaplaza en todas las a factorial @factorial_decorator def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) def division(x, y): assert y > 0 return x / y
88b1d5ec121975017041e29630caf808aad6b8c5
mohcinemadkour/ML_Programs
/ML_Basics/Logistic_Regression_GD.py
2,421
3.6875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Mar 10 12:17:26 2018 @author: Das """ import numpy as np import pandas as pd import matplotlib.pyplot as plt class Logistic_Regression: def fit(self, X, Y, theta, alpha, num_iter): train = Train() self.theta, J = train.gradient_descent(X, Y, theta, alpha, num_iter) return self.theta, J def predict(self, X): train = Train() return train.sigmoid(X, self.theta) def plot_Decision_Boundary(self, X, Y): plt.scatter(X[:, 0], X[:, 1], c=Y, s=100, alpha=0.5, cmap='coolwarm') plt.xlabel('Exam 1 score') plt.ylabel('Exam 2 score') plt.legend() x = np.linspace(-2, 2, 100) y = -(self.theta[0] * x + self.theta[2]) / self.theta[1] plt.plot(x, y, 'r') plt.show() def plotData(self, X, Y): plt.scatter(X[:, 0], X[:, 1], c=Y, s=100, alpha=0.5, cmap='coolwarm') plt.show() class Train: #sigmoid = 1 / 1+e-z def sigmoid(self, X, theta): z = np.dot(X, theta.T) return 1 / (1 + np.exp(-z)) def gradient_descent(self, X, Y, theta, alpha, num_iter): J = [] for i in range(num_iter): P = self.sigmoid(X, theta) theta = theta - alpha * np.dot(X.T, (P-Y))/Y.size if i%100 == 0: cost = self.cost_function(Y, P) rate = self.score(Y, P) print('Iteration: ' + str(i), 'Cost: ' + str(cost), 'Accuracy: ' + str(rate)) J.append(cost) return theta, J #cross entropy J = -Sigma(Ylog(P) + (1-Y)log(1-P)) def cost_function(self, Y, P): l1 = np.log(P) l2 = 1- np.log(P) return np.sum(-Y*l1 - (1-Y)*l2)/Y.size def score(self, Y, P): return 1 - np.mean(np.abs(np.round(P) - Y)) def normalize(X): for i in range(X.shape[1]-1): X[:, i] = (X[:, i] - np.mean(X[:, i]))/np.std(X[:, i]) return X df = pd.read_csv('Logistic_Regression.txt', sep=',', header=None) df.insert(2, 'A', np.ones(df.shape[0])) X = df.iloc[:, :-1] Y = df.iloc[:, -1] X = np.array(X) Y = np.array(Y) model = Logistic_Regression() model.plotData(X, Y) X = normalize(X) theta = np.zeros(3) alpha = 0.01 num_iter = 400 theta, J = model.fit(X, Y, theta, alpha, num_iter) P = model.predict(X) model.plot_Decision_Boundary(X, Y)
aeb031cdfac9891a5639191202472b30d5efb451
github-six06/project-1
/第十一章/11-1/test_cities.py
284
3.640625
4
import unittest from city_functions import city_country_name class CitysTestCase(unittest.TestCase): def test_city_country_name(self): """deal with message such as Santiago Chile""" name=city_country_name('santiago', 'chile') self.assertEqual(name,'Santiago Chile') unittest.main()
ece32db09d98f717a02176a42f4e2977a2c1afd6
13thZygrite/AdventOfCode2017
/day8.py
1,438
3.6875
4
#!/usr/bin/env python with open("input_day8") as f: input = f.readlines() input = [x.strip() for x in input] split = [line.split(" ") for line in input] registers = {} for instruction in split: registers[instruction[0]] = 0 max_value = 0 # Part 1 and 2 for instruction in split: condition_holds = False if (instruction[5] == "=="): condition_holds = (registers[instruction[4]] == int(instruction[6])) elif (instruction[5] == "!="): condition_holds = (registers[instruction[4]] != int(instruction[6])) elif (instruction[5] == ">"): condition_holds = (registers[instruction[4]] > int(instruction[6])) elif (instruction[5] == ">="): condition_holds = (registers[instruction[4]] >= int(instruction[6])) elif (instruction[5] == "<"): condition_holds = (registers[instruction[4]] < int(instruction[6])) elif (instruction[5] == "<="): condition_holds = (registers[instruction[4]] <= int(instruction[6])) if (not condition_holds): continue if (instruction[1] == "dec"): registers[instruction[0]] -= int(instruction[2]) elif (instruction[1] == "inc"): registers[instruction[0]] += int(instruction[2]) if (registers[instruction[0]] > max_value): max_value = registers[instruction[0]] print "Part 1:", max(registers.values()) print "Part 2:", max_value
f52b0674a57c0c8f06c48ff17ff2ada908d49def
aalicav/Exercicios_Python
/ex048.py
187
3.71875
4
acm1 = 0 acm2 = 0 for c in range(0,500): if c % 2 != 0 and c % 3 == 0: acm1 += 1 acm2 += c print('A soma dos {} numeros é {}'.format(acm1,acm2))
d09e0fa34338ce7773b55187e4e523b02cb90cd0
bhavesh622/Sem6
/Machine Learning/graddescentfunc.py
2,610
3.65625
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler def cost_func(theta, X, y): m = len(X) pred = X.dot(theta) cost = (1/m) * np.sum(np.square(pred - y)) return cost**(1/2) def gradientDescent(X_train, X_test, y_train, y_test, learning_rate=0.1, iteration=1000): m = len(y_train) theta = np.zeros(X_train.shape[1]).T rmse_train = np.empty(iteration) rmse_test = np.empty(iteration) it = np.arange(iteration) theta_history = np.zeros(X_train.shape[1]).T theta_history = np.reshape(theta_history,(1,2)) for i in range(iteration): pred = np.dot(X_train, theta) theta = theta - (1 / m) * learning_rate * (X_train.T.dot((pred - y_train))) rmse_train[i] = cost_func(theta, X_train, y_train) rmse_test[i] = cost_func(theta, X_test, y_test) theta_history = np.append(theta_history,np.reshape(theta,(1,2)),axis=0) plt.plot(it, rmse_train, c='red', label='Training RMSE') plt.plot(it, rmse_test, c='green', label='Testing RMSE') plt.xlabel('Iteration') plt.ylabel('RMSE') plt.legend() print('\n\nTheta0: {:0.3f}\nTheta1: {:0.3f}'.format(theta[0],theta[1])) plt.show() print(theta_history) theta0_history = theta_history.T[0,:] theta1_history = theta_history.T[1,:] it = np.arange(iteration+1) # plt.cla() plt.plot(it, theta0_history, c='red', label='theta0') plt.plot(it, theta1_history, c='green', label='theta1') plt.xlabel('Iteration') plt.ylabel('Theta') plt.legend() plt.show() return theta, rmse_train, rmse_test database = pd.read_csv('headbrain.csv') scaler = MinMaxScaler() database = scaler.fit_transform(database) X = database[:, 2] y = database[:, -1] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) X_train = np.c_[np.ones((len(X_train), 1), dtype='int'), X_train] X_test = np.c_[np.ones((len(X_test), 1), dtype='int'), X_test] theta1=np.empty(X_train.shape[1]) theta1= np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train theta, rmse_train, rmse_test = gradientDescent(X_train, X_test, y_train, y_test, 0.01, 2000) y_pred = theta[0] + theta[1] * X_test y_pred1= theta1[0]+ theta1[1] * X_test plt.plot(X_test, y_pred, color='r', label='Gradient Descent') plt.plot(X_test, y_pred1, color= 'blue', label= 'Closed form') X_train = X_train[:,1] plt.scatter(X_train, y_train) plt.xlabel('Head Size(cm^3)') plt.ylabel('Brain Weight(grams)') plt.legend() plt.show()
74d005d858b3c38555037ad546bee1228270a168
rjmarzec/Google-CSSI---Coursera
/Algorithmic Toolbox/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py
508
3.6875
4
# python3 import sys ''' 2 ''' def optimal_summands(n): summands = [] remaining_n = n current_num = 1 while current_num <= remaining_n: summands.append(current_num) remaining_n -= current_num current_num += 1 summands[len(summands) - 1] += remaining_n return summands if __name__ == '__main__': input = sys.stdin.read() n = int(input) summands = optimal_summands(n) print(len(summands)) for x in summands: print(x, end=' ')
dd83d7f6a74007ad3807019d8432dcbd69a5615d
EcoJuliet/Python-Projects
/Py files/CARTEIRA DE MOTORISTA.py
585
3.9375
4
# CALCULAR A IDADE DA PESSOA E VER SE ELA PODE TIRAR A CARTEIRA DE MOTORISTA from datetime import datetime print ('-----------------------') print ('DEPARTAMENTO DE TRÂNSITO') print ('-----------------------') now = datetime.now() print ('Nós estamos em', now.year) ano_nasci = int(input('Insira seu ano de nascimento (yyyy): ')) print ('------STATUS----------') print ('IDADE: ', now.year - ano_nasci) if now.year - ano_nasci >= 18: print ('APTO A TIRAR A CARTEIRA DE MOTORISTA') else: print ('Por favor, aguarde até ter 18 anos.') print ('---------------------')
d075184f0c3dc3b14a2cc659e4bc9dc52a70500c
Frank-tree/my_tool
/set_pic_opacity.py
403
3.5
4
from PIL import ImageEnhance def reduce_opacity(wm_pic, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if wm_pic.mode != 'RGBA': wm_pic = wm_pic.convert('RGBA') else: wm_pic = wm_pic.copy() alpha = wm_pic.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) wm_pic.putalpha(alpha) return wm_pic
66c1c24a5f4a85f4f544084fcee7d0e78b0eaca2
chaitanyamean/python-algo-problems
/Array/specialarrayProductsum.py
288
3.84375
4
'''Given a special non-empty array of integers, find the product of sum ''' def productArray(arr, multiplier = 1): sum = 0 for i in arr: if type(i) is list: sum += productArray(i, multiplier + 1) else: sum += i return sum * multiplier
fd13ab68137e412b701b71be99312b9a1afa3a9d
lizetheP/PensamientoC
/programas/LabLiz/8_strings/examenStrings2.py
410
3.828125
4
def cuenta_caracter_espacios(cadena, letra): cont = 0 for i in range(len(cadena)): if cadena[i].lower() == letra.lower() or cadena[i] == ' ': cont = cont + 1 return cont def main(): cadena = str(input("Introduce una cadena: ")) letra = str(input("Introduce la letra : ")) res = cuenta_caracter_espacios(cadena, letra) print("El resultado es ", res) main()
54d8ac27ee48ab33fb4c4c0b64009003bf633bb2
uciharis/Udemy-dletorey
/Python Programming Masterclass/Python/FlowControl/ranges.py
1,428
4.34375
4
# # exercise 60 iterating over a range # for i in range(1, 20): # this will go from 1 to 19 as the last number in the range is not included # print("i is now {}".format(i)) # # coding exercise 8 For Loop # # Write a program to print out all the numbers from 0 to 9. # for i in range(0, 10): # print(i) # #Exercise 61 more about ranges # # Part 1 # for i in range(10): # if you want to start at 0 then you can just add the end value # print("i is now {}".format(i)) # print("-" * 10) # for i in range(0, 10, 2): # if you want to step then you need to include a start value # print("i is now {}".format(i)) # print("-" * 10) # for i in range(10, -1, -1): # if you want to go backwards higher number first and then a negative step value # print("i is now {}".format(i)) # print("-" * 10) # #Part 2 # age = int(input("How old are you? ")) # # # if age >= 16 and age <= 65: # # if 16 <= age <= 65: # if age in range(16, 66): # print("Have a good day at work") # else: # print("Enjoy your free time") # # print("-" * 80) # # if age < 16 or age > 65: # print("Enjoy your free time") # else: # print("Have a good day at work") #Coding Exercise 9 for loop with step # Write a program to print out all the numbers from 0 to 100 that are divisible by 7. # Note that zero is considered to be divisible by all other integers, so your output should include zero. for i in range(0, 100, 7): print(i)
9a6583d6beb85a2e98c589f5fd63e25163036ef8
Sudeep-sudo/myrepo
/mypython/expense-tracker.py
1,377
3.71875
4
import sqlite3 as sql import datetime as dt from tabulate import tabulate con = sql.connect("exp.db"); #connected to a database cursor = con.cursor(); tab= '''CREATE TABLE IF NOT EXISTS tracker( Spent_on TEXT NOT null, Amount INTEGER NOT null, Comments TEXT NOT null );''' cursor.execute(tab) cur_e = cursor.execute('SELECT * FROM tracker') columns= cur_e.description columns = cur_e.description col = [] i=0 for row in columns: col.append(row[0]) i=i+1 noc = len(col); #number of columns in the table col_set= set(col) if not ("Date") in col_set: addColumn = "ALTER TABLE tracker ADD COLUMN Date INTEGER " cursor.execute(addColumn) #commit changes to the database ins = ''' INSERT INTO tracker(Spent_on, Amount, Comments, Date) VALUES(?, ?, ?, ?);''' category = input("Where you spent the amount? ") amt = input ("How much did you spent? ") cmt = input ("Give some short description ") when= dt.date.today() data= [category, amt, cmt, when] cursor.execute(ins, data) con.commit(); #FETCHING contents from the table and printing it sel=cursor.execute("SELECT * FROM tracker") rows = sel.fetchall() print (tabulate(rows, headers= col)) con.close; #closing the database
8869656e93a6d8d9cbc99a32165c9eb5b1f6a53c
Rashmin528/BST-Algorithm
/bst_insertion.py
898
4
4
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(root, node): if root is None: root = node else: if root.data > node.data: if root.left is None: root.left = node else: insert(root.left, node) else: if root.right is None: root.right = node else: insert(root.right, node) def in_order(root): if not root: return in_order(root.left) print root.data in_order(root.right) root = Node(12) insert(root, Node(10)) insert(root, Node(8)) insert(root, Node(99)) insert(root, Node(62)) insert(root, Node(54)) insert(root, Node(26)) insert(root, Node(30)) insert(root, Node(4)) insert(root, Node(171)) insert(root, Node(0)) print in_order(root)