blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5cdf628644e7b70b84559de0a8cec6b58cb3df58
Israelfluz/Tensorflow-e-Deep-learn-com-python
/redes neurais artificiais/rna classificação regressão/mnist.py
4,351
3.890625
4
# ====== Construção de uma rede neural para fazer a classificação dos dígitos de 0 até 9 ===== # Importando para o tensorflow from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('mnist/', one_hot = True) # Carregando os dados da pasta mnist/ x_treinamento = mnist.train.images x_treinamento.shape x_teste = mnist.test.images y_treinamento = mnist.train.labels y_treinamento[0] y_teste = mnist.test.labels # Visualizando as imagens da base de dados import matplotlib.pyplot as plt import numpy as np plt.imshow(x_treinamento[102].reshape((28, 28)), cmap = 'gray') # cmap = 'gray' deixa o fundo preto e o núemro cinza # Visualizando a classe plt.title('Classe: ' + str(np.argmax(y_treinamento[102]))) # Definindo o tamanho do batch x_batch, y_batch = mnist.train.next_batch(64) # Esse número pode alterar x_batch.shape # ======= Construindo a rede neural ======== # Passando a quantidade de atributos previsores neuronios_entrada = x_treinamento.shape[1] neuronios_entrada # Definindo os neurônios da camada oculta, aqui teremos três neuronios_oculta1 = int((x_treinamento.shape[1] + y_treinamento.shape[1]) / 2) neuronios_oculta1 neuronios_oculta2 = neuronios_oculta1 neuronios_oculta3 = neuronios_oculta1 # Definindo o neurônio da camada de saída neuronios_saida = y_treinamento.shape[1] neuronios_saida # 784 neurônios na camada de entrada que estaram ligados -> 397 neurônios da primeira camada oculta, # estaram ligados -> 397 neurônios da segunda camada oculta, que estaram ligas 397 neurônios da terceira camada oculta, # que estaram ligados -> 10 da camada de saída. # Construindo a estrutura acima citada import tensorflow as tf # Criando a variável W que representa os pesos no formato de dicionário w = {'oculta1': tf.Variable(tf.random_normal([neuronios_entrada, neuronios_oculta1])), 'oculta2': tf.Variable(tf.random_normal([neuronios_oculta1, neuronios_oculta2])), 'oculta3': tf.Variable(tf.random_normal([neuronios_oculta2, neuronios_oculta3])), 'saida': tf.Variable(tf.random_normal([neuronios_oculta3, neuronios_saida])) } # Adcionando a camada BIAS com os seus pesos b = {'oculta1': tf.Variable(tf.random_normal([neuronios_oculta1])), 'oculta2': tf.Variable(tf.random_normal([neuronios_oculta2])), 'oculta3': tf.Variable(tf.random_normal([neuronios_oculta3])), 'saida': tf.Variable(tf.random_normal([neuronios_saida])) } # Criando os placesholders (previsores) para receber os dados xph = tf.placeholder('float', [None, neuronios_entrada]) # Criando o placeholder para receber as respostas yph = tf.placeholder('float', [None, neuronios_saida]) # Criando o modelo por meio de uma função def mlp(x, w, bias): camada_oculta1 = tf.nn.relu(tf.add(tf.matmul(x, w['oculta1']), bias['oculta1'])) # Calculo das camandas camada_oculta2 = tf.nn.relu(tf.add(tf.matmul(camada_oculta1, w['oculta2']), bias['oculta2'])) camada_oculta3 = tf.nn.relu(tf.add(tf.matmul(camada_oculta2, w['oculta3']), bias['oculta3'])) camada_saida = tf.add(tf.matmul(camada_oculta3, w['saida']), bias['saida']) return camada_saida # Criando o modelo modelo = mlp(xph, w, b) # Criando fórmula para verificar o erro erro = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = modelo, labels = yph)) otimizador = tf.train.AdamOptimizer(learning_rate = 0.0001).minimize(erro) # Previsões previsoes = tf.nn.softmax(modelo) previsoes_corretas = tf.equal(tf.argmax(previsoes, 1), tf.argmax(yph, 1)) # Calculo para a previsão de acertos taxa_acerto = tf.reduce_mean(tf.cast(previsoes_corretas, tf.float32)) # Realizado testes with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoca in range(5000): # fazendo os testes com 5000 epocas x_batch, y_batch = mnist.train.next_batch(128) _, custo = sess.run([otimizador, erro], feed_dict = {xph: x_batch, yph: y_batch}) # Treinamento do algoritmo if epoca % 100 == 0: acc = sess.run([taxa_acerto], feed_dict = {xph: x_batch, yph: y_batch}) print('epoca: ' + str((epoca + 1 )) + 'erro: ' + str(custo) + 'acc: ' + str(acc)) print('\n') print('Treinamento concluído') print(sess.run(taxa_acerto, feed_dict = {xph: x_teste, yph: y_teste}))
cbe8c45e8b2524afdf228819cef51ee154d111c7
saikhurana98/dist_search
/src/search/search.py
648
3.765625
4
import sqlite3 import json with open ('../src/Data/index.json') as f: index = json.load(f) def main(): filepath = os.path.join('../src/Data/Movie.db') conn = sqlite3.connect(filepath) c = conn.cursor() c.execute("SELECT id FROM Movie;") data = c.fetchall() def lookup_tags(output): output = output.split() # year = [] if output == -1: print("Error, no input") else: for i in range (len(output)): # for j in range (2020): # print(output[i]) print (index[output[i]]) return output = input("Enter: ") lookup_tags(output)
97cd293823ba4efda41d404e553f495f754662dd
senorhimanshu/Machine-Learning
/simple_perceptron.py
1,013
4.3125
4
# Single Layer Perceptron Learning Rule : OR Gate Example # https://blog.dbrgn.ch/2013/3/26/perceptrons-in-python/ from random import choice from numpy import array, dot, random from pylab import plot, ylim # unit step as an activation function by using lambda unit_step = lambda x: 0 if x < 0 else 1 # training data as : x1 x2(inputs) b(bias) O(output) training_data = [ (array([0,0,1]), 0), (array([0,1,1]), 1), (array([1,0,1]), 1), (array([1,1,1]), 1), ] # print training_data # some random initial weights w = random.rand(3) # print w errors = [] eta = 0.2 #learning constant n = 100 #maximum iterations for i in xrange(n): x, expected = choice(training_data) result = dot(w, x) error = expected - unit_step(result) errors.append(error) w += eta * error * x # w <- final weights # Test for x, _ in training_data: # print x result = dot(x, w) print("{}: {} -> {}".format(x[:2], result, unit_step(result))) ylim([-1,1]) plot(errors)
093805341f15883a14f84aa573e67e426fbba5f4
shivhudda/python
/29_Writing_And_Appending.py
597
3.984375
4
# write mode f = open('29_myfile.txt', 'w') a = f.write('lorem ipsum dollar sit amet.\n') f.write('shivhudda') '''There is a certain limitation to the write mode of the opening file that it overrides the existing data into the file.''' print (a) #its return number of written characters f.close() # append mode f = open('29_myfile2.txt','a') a = f.write('shivhudda is a programmer.\n') print (a) #its return number of written characters f.close() # read and write mode combo f = open('29_myfile3.txt','r+') print(f.read()) f.write('\n so let\'s starting to learn file io.') f.close()
9b9752def360e0c4b010c3b10923e76eb942a52e
dlrgy22/Boostcamp
/2주차/2021.01.27/예제/data_selection.py
499
3.53125
4
import pandas as pd import numpy as np df = pd.read_excel("./excel-comp-data.xlsx") print(df.drop("name", axis=1)) print(df.head(2).T) print(df[["account", "street", "state"]].head()) account_series = df["account"] print(df[account_series > 200000]) df.index = df["account"] print(df[["name", "street"]].iloc[:2]) matrix = df.values print(matrix[:, -3:].sum(axis=1)) s = pd.Series(np.nan, index=range(10, 0, -1)) print(s.loc[:3]) print(s.iloc[:3]) print(df["account"][df["account"] < 200000])
a3b1d6f474ae20024f776352b448b260c509578c
gx20161012/leetcode
/easy/MajorityElement.py
700
3.9375
4
''' Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. ''' class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) set1 = set() for i in range(length): if nums[i] in set1: continue if nums.count(nums[i]) > length / 2: return nums[i] else: set1.add(nums[i]) s = Solution() nums = [2, 2, 1, 1, 2] print(s.majorityElement(nums))
ad52a9db50b57d5d97b7ce78c8ab652658971b43
addriango/curso-python
/sintaxis-basica/12.bucles-for.py
827
4
4
## los bucles nos ayudan a ejecutar codigo repetitivo en pocas lineas ##esto no es eficiente print ("hola mundo") print ("hola mundo") print ("hola mundo") print ("hola mundo") print("") ##esto si es eficiente ##bucle determianado (sabemos cuantas veces se va a realizar) for cadaNumero in range(4): print (cadaNumero) print("") ##recorrer un string con bucle determinado user_email = input("Introduce tu email: ") contador_email = 0 for cadaLetra in user_email: if cadaLetra == "@": contador_email+=1 if cadaLetra == ".": contador_email+=1 if contador_email == 2: print("Email correcto") else: print("Email incorrecto") print("") #bucle indetermiando, no sabemos (recorre toda la lista) nombres = ["pablo","maria","juana","johan","miguel"] for nombre in nombres: print(nombre)
4e5fddbf7083e669b03145877ccc7160a1834c08
dg5921096/Books-solutions
/Python-For-Everyone-Horstmann/Chapter6-Lists/P6.4C.py
515
4.3125
4
# Write list functions that carry out the following tasks for a list of integers. For each # function, provide a test program. # c. Replace all even elements with 0. # FUNCTIONS def replaceEven_with_Null(list): for i in range(len(list)): if list[i] % 2 == 0: list[i] = 0 return list # main def main(): exampleList = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] replaceEven_with_Null(exampleList) print("Even numbers replaced with 0") print(exampleList) # PROGRAM RUN main()
d6fdf35d255b315fbf9bb85495feff0ff6c42d45
petrooha/NLP-notes
/Computing with NL/All Preprocessing in one function (HTML tags, lowerase, non-letters, stopwords, stem, tokenize).py
1,092
3.75
4
# BeautifulSoup to easily remove HTML tags from bs4 import BeautifulSoup # RegEx for removing non-letter characters import re # NLTK library for the remaining steps import nltk nltk.download("stopwords") # download list of stopwords (only once; need not run it again) from nltk.corpus import stopwords # import stopwords from nltk.stem.porter import * stemmer = PorterStemmer() def review_to_words(review): """Convert a raw review string into a sequence of words.""" # TODO: Remove HTML tags and non-letters, # convert to lowercase, tokenize, # remove stopwords and stem text = BeautifulSoup(review, "html5lib").get_text() text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower()) words = text.split() words = [w for w in words if w not in stopwords.words("english")] words = [PorterStemmer().stem(w) for w in words] # Return final list of words return words review_to_words("""This is just a <em>test</em>.<br/><br /> But if it wasn't a test, it would make for a <b>Great</b> movie review!""")
f0c1934711d886f6221b0fdf7b4f22fd412305bb
Achyu02/20176081
/String matching 2 - Copy.py
2,102
4.03125
4
import os class stringM(object): ''' class stringM consists of multiple methods used to calculate plagiarism for multiple files ''' def __init__(self,arg): '''Initializer automatically calls when you create a new instance of class''' self.arg=arg def pieces(p1): ''' Input : files functionality : appends the multiple string permutations to list output : returns the list ''' s="" l=[] for i in range(len(p1)): s='' for j in range(i,len(p1)): s=s+p1[j] l.append(s) return l def combine(l,l1): ''' Input : two lists Functionality : Appends the similar values to the list and removes spaces front and end of the values Output : List ''' z=[] for i in l: if i in l1: z.append(i) #print(z) for i in range(len(z)): d=z[i] c=z[i] for j in range(len(z[i])): if(c[0]==" "): d=d[1:] elif(c[len(c)-1]==" "): d=d[:len(c)-1] elif(c[0]==" "or c[len(c)-1]==" "): d=d[:(len(z[i])-1)]+d[1:] z[i]=d #print("string matching for ",file1,file2,z) return z obj=stringM(object) path=input("Enter the path") fils=os.chdir(path) files=[z for z in (os.listdir()) if z.endswith(".txt")] print(files) li=[] temp=[] li.append('filenames') for i in files: li.append(i) temp.append(li) for k in range(len(files)): g=[] g.append(files[k]) for j in range(len(files)): if(k==j): g.append(0) else: file1=files[k] file2=files[j] p1=open(file1,'r').read().lower() p2=open(file2,'r').read().lower() x=len(p1) y=len(p2) l=stringM.pieces(p1) l1=stringM.pieces(p2) if(len(l)==0 and len(l1)==0): g.append(100) else: z=stringM.combine(l,l1) l2=[] for p in z: l2.append(len(p)) if len(l2)==0: g.append(0) else: m=max(l2) #print(m) calculation=((m*2)/(x+y))*100 g.append(round(calculation,2)) #file1.close() #file2.close() temp.append(g) print('\n'.join([' '.join(['{:8}'.format(y1) for y1 in row]) for row in temp]))
a4cb7edd17e6954a1dc7d383d5a96d835379d1d3
shannonmlance/leetcode
/solved/removeLinkedListElements.py
3,271
3.96875
4
# Remove all elements from a linked list of integers that have value val. # Example: # Input: 1->2->6->3->4->5->6, val = 6 # Output: 1->2->3->4->5 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head, val): # set the front runner at the head current = head # loop through as long as the front runner exists while current != None: # if the front runner's value is equal to the target value if current.val == val: # and if the front runner is at the head of the list if current == head: # increment the head, thereby removing the original head head = head.next # reset the front runner at the new head current = head # and if the front runner is not at the head of the list else: # increment the front runner current = current.next # set the back runner to point to the incremented front runner, thereby removing the front runner previous.next = current # if the front runner's value is not equal to the target value else: # increment both runners forward previous = current current = current.next return head class mySolution: def removeElements(self, head, val): # loop as long as the head exists and the head's value is the target value while head != None and head.val == val: # move the head forward, thereby removing the original head head = head.next # if there is now no head, return if head == None: return head # set up two runners, one at the head and one at the head's next previous = head current = head.next # loop through until the front runner doesn't exist while current != None: # if the front runner's value is equal to the target value if current.val == val: # set the back runner to point to the front runner's next, thereby removing the front runner previous.next = current.next # reset the front runner to the next node current = current.next # if the front runner's value does not equal the target value else: # increment both runners forward previous = previous.next current = current.next return head # stuff for making and checking the list def printAll(node): print("*"*10) current = node while current != None: print(current.val) current = current.next print("*"*10) one = ListNode(6) two = ListNode(6) three = ListNode(6) four = ListNode(6) five = ListNode(6) six = ListNode(6) seven = ListNode(6) eight = ListNode(6) nine = ListNode(6) ten = ListNode(6) one.next = two two.next = three three.next = four four.next = five five.next = six six.next = seven seven.next = eight eight.next = nine nine.next = ten s = Solution() printAll(one) a = s.removeElements(one, 6) printAll(a)
163ceba2642904c3f169c0ce9b0fec77af58265b
m-j-hacker/Data-Structures
/doubly_linked_list/doubly_linked_list.py
3,818
4.40625
4
"""Each ListNode holds a reference to its previous node as well as its next node in the List.""" class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next """Wrap the given value in a ListNode and insert it after this node. Note that this node could already have a next node it is point to.""" def insert_after(self, value): current_next = self.next self.next = ListNode(value, self, current_next) if current_next: current_next.prev = self.next """Wrap the given value in a ListNode and insert it before this node. Note that this node could already have a previous node it is point to.""" def insert_before(self, value): current_prev = self.prev self.prev = ListNode(value, current_prev, self) if current_prev: current_prev.next = self.prev """Rearranges this ListNode's previous and next pointers accordingly, effectively deleting this ListNode.""" def delete(self): if self.prev: self.prev.next = self.next if self.next: self.next.prev = self.prev """Our doubly-linked list class. It holds references to the list's head and tail nodes.""" class DoublyLinkedList: def __init__(self, node=None): self.head = node self.tail = node self.length = 1 if node is not None else 0 def __len__(self): return self.length def add_to_head(self, value): new_node = ListNode(value, None) # Case for empty linked list if not self.head: self.head = new_node self.tail = new_node elif not self.head.next: new_node.next = self.head self.head = new_node else: self.insert_before(value) def remove_from_head(self): # If the linked list is empty it will not have a head if not self.head: return None # This condition means that we only have 1 item in our list if not self.head.next: head = self.head self.head = None self.tail = None return head.value # This condition is for a list with more than 1 item else: value = self.head.value self.head = self.head.next return value def add_to_tail(self, value): new_node = ListNode(value) # This case is for empty lists if self.tail is None: self.head = new_node self.tail = new_node else: # We will set the current reference's next to the new reference and make that the tail self.tail.next = new_node self.tail = new_node def remove_from_tail(self): # If there is no tail, the list is empty if not self.tail: return None # This condition is for only 1 item in the list if not self.tail.prev: tail = self.tail self.head = None self.tail = None return tail.value else: tail = self.tail self.tail.prev.next = None self.tail = self.tail.prev return tail.value def move_to_front(self, node): # This function should move a given node to the front of the list, it will remove the node and add it to the head # If there is no head, the list is empty if not node: return None # If there is only one item, make no change elif self.head == self.tail: pass # Otherwise, move an item to the front else: self.head.prev = node node.next = self.head node.prev = None self.head = node def move_to_end(self, node): self.tail.next = node node.next = None node.prev = self.tail self.tail = node def delete(self, node): if not node: return None else: node.delete() def get_max(self): current = self.head current_max = 0 while current.next: if self.value > current_max: current_max = self.value return current_max
e74da0c57f093e3799de94d741e8c2e098a39b54
graphql-python/graphql-core
/tests/utils/gen_fuzz_strings.py
378
3.59375
4
from itertools import product from typing import Generator __all__ = ["gen_fuzz_strings"] def gen_fuzz_strings(allowed_chars: str, max_length: int) -> Generator[str, None, None]: """Generator that produces all possible combinations of allowed characters.""" for length in range(max_length + 1): yield from map("".join, product(allowed_chars, repeat=length))
55630d6a3badf0e38d4fadba96a646aa11059733
voitenko-lex/leetcode
/Python3/30-day-leetcoding-challenge/week-6/Trie.py
3,909
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings. """ import unittest from typing import List, Set, Tuple, Dict # import math class Trie: value: str = None childs: Dict = None end: bool = False def __init__(self, value): """ Initialize your data structure here. """ self.value = value self.childs = {} def __str__(self): desc = f"\n{id(self):x} value: {self.value} childs: [{self.childs}] end={self.end}" result = desc for child in self.childs: result = result + f"{self.childs[child]}" return result def insert(self, word: str) -> None: """ Inserts a word into the trie. """ if len(word): char = word[0] word = word[1:] if not char in self.childs: temp = Trie(char) self.childs[char] = temp self.childs[char].insert(word) else: self.end = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ result = False if len(word): char = word[0] word = word[1:] if char in self.childs: result = self.childs[char].search(word) else: if self.end: result = True return result def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ result = False if len(prefix): char = prefix[0] prefix = prefix[1:] if char in self.childs: result = self.childs[char].startsWith(prefix) else: result = True return result class TestMethods(unittest.TestCase): def trie_test(self, methods: List[str], args: List[List[str]]): print(f"\n\nmethods: {methods}\nargs:{args}") result = [] trie = Trie("") for method, arg in zip(methods, args): try: func = getattr(trie, method) result.append(func(*arg)) except AttributeError: pass print(f"trie:") print(trie) return result def test_sample00(self): self.assertEqual([], self.trie_test( ["Trie","insert","search","search","startsWith","insert","search"], [[],["apple"],["apple"],["app"],["app"],["app"],["app"]] ) ) if __name__ == '__main__': do_unittests = False if do_unittests: unittest.main() else: # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix) test = TestMethods() # out = test.trie_test( ["insert","search","search"], # [["apple"],["app"],["apple"]]) # out = test.trie_test( ["insert","startsWith","search","search"], # [["apple"],["app"],["apple"],["app"]]) out = test.trie_test( ["Trie","insert","search","search","startsWith","insert","search"], [[],["apple"],["apple"],["app"],["app"],["app"],["app"]]) print(out)
8d8abd496e64a683dd12d2e0ab8f48e8c863be03
Iftikhar-Shams-Niloy/URI-Python-Solutions
/URI 1116.py
204
3.625
4
N = int(input()) i = 0 while i < N : X,Y = list(map(int,input().split(" "))) if Y == 0: print("divisao impossivel") else: result = X/Y print(result) i += 1
f52cb677fa25db780c5c10eb36bfcf9207846ed5
yahaa/Python
/basis/com/zihua/test5.py
266
3.671875
4
import datetime time=raw_input('Enter a date (mm/dd/yyyy):') moth=['January','February','March','April','May','June','July','August','Septemper','October','November','December'] t=time.split('/') print ' The converted date is: '+moth[int(t[0])-1]+' '+t[1]+', '+t[2]
b77661631958f0470fa7edc41158aff28de06489
yw9142/Solving-algorithmic-problems
/Programmers/Level1/나누어 떨어지는 숫자 배열.py
323
3.609375
4
def solution(arr, divisor): possible_divide = [] for i in arr: if i % divisor == 0: possible_divide.append(i) if len(possible_divide) == 0: possible_divide.append(-1) return possible_divide else: possible_divide.sort() return possible_divide
e4af45c0d40bbb305fe35f2eeceeedc45ef579ec
aminhp93/python_fundamental
/strings.py
589
4.4375
4
print "this is a sample string" name = "Zen" print "my name is " + name first_name = "Zen" last_name = "coder" print "My nameis {} {}".format(first_name, last_name) my_string = 'hello world' print my_string.capitalize() my_string = "HELO WEOflD" print my_string.lower() my_string = "Hello WORLD" print my_string.swapcase() my_string = 'hello world' print my_string.upper() my_string = "hello world" print my_string.find("e l") my_string = "hello world" print my_string.replace("world", "kitty") my_string = "egg, egg, Spam, egg and Spam" print my_string.replace("egg", "Spam", 2)
d4723e2fdeff34b0646f42985161b592d35c8493
ananthuk7/Luminar-Python
/Django tut/functionalprograming/lamdafunction.py
1,554
3.640625
4
# lamda function # def add(num1,num2): # return num1+num2 # # print(add(5,6)) # # add = lambda num1, num2: num1 + num2 # print(add(5,6)) # lst = [1, 2, 3, 4, 5, 6, 7] # sq=[] # for i in lst: # sq.append(i**2) # print(sq) # map(function,itreatable) # def square(num1): # return num1 ** 2 # # # squares = list(map(square, lst)) # print(squares) # squares = list(map(lambda num1: num1 ** 2,lst)) # print(squares) # print all product details availave <250 # pd = list(filter(lambda product:product["mrp"]<250,products)) # print(pd) # num1=10 # num2=20 # res=num1 if num1>num2 else num2 # num=1 # res="odd" if num%2!=0 else "even" # num2 # res="+ve" if num >0 else "-ve" # #lst =[2,3,4,8,10,7] if num<5 num-1 else num+1 # lst =[2,3,4,8,5,10,7] # # op=[] # # for i in lst: # # if i <5: # # op.append(i-1) # # else: # # op.append(i+1) # # print(op) # # # op=list(map(lambda num:num+1 if num>5 else num-1,lst)) # # print(op) # # op=list(map(lambda num: num+1 if num>5 else num-1 if num <5 else num,lst)) # print(op) # reduce # dont have enough reach # from functools import reduce # lst=[1,2,3,4,5,6,7] # total=reduce(lambda num1,num2:num1+num2,lst) # print(total) # largest # largest=reduce(lambda num1,num2:num1 if num1>num2 else num2,lst) # print(largest) def some(**kwargs): name=kwargs["name"] age=kwargs["ag"] print(name,age) # def abc(*args): # print(args) # print(sum(args)) # def um(*args): # print(sum(args)) some(name="abc",ag=1 ) # abc(1, 2, 3, 4, 5, 6)
dd2213bf157aaebd1207803e0db0e0ba75bc54c4
caimimao/project-euler
/200/112.py
1,396
3.5
4
# -*- coding: utf-8 -*- __title__ = "Bouncy numbers" def solve(): from common import log def get_non_bouncy_number(n): ff = [0] + range(9, 0, -1) gg = [9] + range(9, 0, -1) s = 99 # 1-99 are non bouncy m = 3 while m <= n: # f(m, 0) = 0 f = [0] for d in range(1, 10): # f(m, d) f.append(sum(ff[d:10])) g = [] for d in range(0, 10): # g(m, d) g.append(sum(gg[d:10])) s += sum(f) + sum(g) - 9 #print f #print g ff = f gg = g m = m + 1 return s def is_bouncy(n): origin = n inc = False dec = False n, last = divmod(n, 10) while n>0: n, next = divmod(n, 10) if next > last: inc = True elif next < last: dec = True last = next if dec and inc: return True return dec and inc c = get_non_bouncy_number(6) log([c, 100-100.0*c/10**6]) i = 10**6-1 count = 10**6-c-1 while True: i = i + 1 if is_bouncy(i): count = count + 1 if 100*count >= 99*i: return i
873818b49699745fdbc4cfd161f583f811d19833
RafaelBuchser/Chess-AI
/WeakMiniMaxEngine.py
1,041
3.734375
4
from MiniMaxEngine import MiniMaxEngine from King import King """ This class is a subclass of the MiniMax-engine. The only difference between the other engine is the evaluation function. To evaluate a position it just adds up the values of the pieces. The more pieces from the opposite player are missing the higher evaluated it gets and the more piece from the own player are missing the lower the value gets.""" class WeakMiniMaxEngine(MiniMaxEngine): def __init__(self, player): super().__init__(player) def calculateValueOfMove(self, game): gameValue = 0 for row in range(8): for column in range(8): piece = game.board.board[row][column] if piece is not None: if not isinstance(piece, King): gameValue += self.getValueOfPiece(piece) return gameValue def getValueOfPiece(self, piece): value = piece.miniMaxValue return value if piece.pieceColor == self.player.playerColor else -value
30f05b9424ba6455656abb0265b3227546e4980b
Sjaiswal1911/PS1
/python/functions/basics.py
928
4.15625
4
# functions # is a block of organised, reusable code to perform a single , related action # syntax # def functionname( parameters ): # "function_docstring" # function_suite # return [expression] # Defining a function def printme( str ): "This prints a passed string into this function" print (str) return # Calling a function printme("This is first call to the user defined function!") printme("Again second call to the same function") # Pass by Reference # default way in python # change in parameter passed , reflects back in the calling function def changeme( mylist ): "This changes a passed list into this function" print ("Values inside the function before change: ", mylist) mylist[2]=50 print ("Values inside the function after change: ", mylist) return # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
c99641bcb8fcd5093dcc2e5d8bf6523b515f7bea
rahul-gopinath-datapsych/python_coursera
/Python/asgn11_dictionary.py
1,430
3.546875
4
# Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. # The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates # a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary # is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer. #File Name: mbox-short_v2.txt import os #Initializig file location dir_path=os.path.dirname(os.path.realpath(__file__)) dir_path=dir_path.replace("\\",'/') file_name="mbox-short.txt" input_filename=dir_path+'/input_files/'+file_name try: #Reading the file fhandler=open(input_filename,'r') except: print("Provided file name",file_name,"is not available in the path",dir_path) quit() output_dict=dict() #Counting Number of time the each email occured and saving it in for of a dictinoary for line in fhandler: if line.startswith('From '): data_list=line.split() output_dict[data_list[1]]=output_dict.get(data_list[1],0)+1 #finding the maximum number of times an email occcured. max_count=None max_email=None for key,value in output_dict.items(): if max_email is None or value>max_count: max_email=key max_count=value print(max_email,max_count)
547668609a94be048112b0545b96416d76a799a6
surajbnaik90/devops-essentials
/PythonBasics/PythonBasics/PickleAndShelves/pickle1.py
1,349
4
4
#Using 'Pickle' to write binary files #Imp Note : Pickle make use of protocols while dumping and reading data. import pickle tupleObject = ('Microsoft', 'Azure', 'Satya Nadella') with open("testfile.pickle","wb") as pickle_file: pickle.dump(tupleObject, pickle_file) #Read the binary file with open("testfile.pickle", "rb") as pickle_file: obj = pickle.load(pickle_file) print(obj) #Dump tuple and some integer values to the binary file print("-" * 60) print("Dump tuple and some integer values to the binary file...") even_numbers = list(range(0,10,2)) odd_numbers = list(range(1,10,2)) with open("testfile.pickle","wb") as pickle_file: pickle.dump(tupleObject, pickle_file) # or pickle.dump(tupleObject, pickle_file, protocol=pickle.DEFAULT_PROTOCOL) # or pickle.dump(tupleObject, pickle_file, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump(even_numbers, pickle_file) pickle.dump(odd_numbers,pickle_file) pickle.dump("Some text", pickle_file) print("Done") print("Now read from the file created...") #No read the entire binary file with open("testfile.pickle", "rb") as pickle_file: obj = pickle.load(pickle_file) even_list = pickle.load(pickle_file) odd_list = pickle.load(pickle_file) sometext = pickle.load(pickle_file) print(obj) print(even_list) print(odd_list) print(sometext) print("-" * 60)
6ab06c31c438166533c8b96c098041c8de516328
tellefs/ML-projects
/project3/src/neuralnetwork.py
6,686
3.75
4
import numpy as np from .activation_functions import * class NeuralNetwork: def __init__( self, X_data, Y_data, n_hidden_layers = 1, n_hidden_neurons=[50], n_categories=1, epochs=1000, batch_size=5, eta=0.001, hidden_act_func = "sigmoid", out_act_func= "linear", lmbd=0.0): ''' Feed forward neural network with back propagation mechanism hidden_act_func takes values "sigmoid", "tanh", "relu", "leaky relu",Leaky ReLU,ReLU eta=0.00001, epochs=10000 (100000 for better results), sigmoid and tanh - 0.001, 1000 out_act_func takes values "linear" or "softmax" ''' self.X_data_full = X_data self.Y_data_full = Y_data self.n_inputs = X_data.shape[0] self.n_features = X_data.shape[1] self.n_hidden_layers = n_hidden_layers self.n_hidden_neurons = n_hidden_neurons self.n_categories = n_categories self.hidden_layers = [] self.hidden_act_func = hidden_act_func self.out_act_func = out_act_func self.epochs = epochs self.batch_size = batch_size self.iterations = self.n_inputs // self.batch_size self.eta = eta self.lmbd = lmbd # initializing hidden layers for i in range(self.n_hidden_layers): if(i==0): layer = HiddenLayer(self.n_hidden_neurons[i], self.n_features, self.hidden_act_func) else: layer = HiddenLayer(self.n_hidden_neurons[i], self.n_hidden_neurons[i-1], self.hidden_act_func) layer.create_biases_and_weights() self.hidden_layers.append(layer) # initializing weights and biases in the output layer self.create_output_biases_and_weights() def create_output_biases_and_weights(self): ''' Creating of the initial weights and biases in the output layer''' self.output_weights = np.random.randn(self.hidden_layers[self.n_hidden_layers-1].n_hidden_neurons, self.n_categories) self.output_bias = np.zeros(self.n_categories) + 0.01 def feed_forward(self): '''feed-forward for training Running over all hidden layers''' for i, layer in enumerate(self.hidden_layers): if(i == 0): a_in = self.X_data else: a_in = self.hidden_layers[i-1].a_h layer.z_h = np.matmul(a_in, layer.hidden_weights) + layer.hidden_bias layer.a_h = layer.hidd_act_function(layer.z_h) # Output layer self.z_o = np.matmul(self.hidden_layers[self.n_hidden_layers-1].a_h, self.output_weights) + self.output_bias self.a_o = set_activation_function(self.z_o, self.out_act_func) def backpropagation(self): ''' Back propagation mechanism''' # This line will be different for classification if(self.out_act_func=="linear"): error_output = self.a_o - self.Y_data[:,np.newaxis] else: error_output = self.a_o - self.Y_data self.error_output = error_output # Calculate gradients for the output layer self.output_weights_gradient = np.matmul(self.hidden_layers[self.n_hidden_layers-1].a_h.T, error_output) self.output_bias_gradient = np.sum(error_output, axis=0) if self.lmbd > 0.0: self.output_weights_gradient += self.lmbd * self.output_weights # Update weights and biases in the output layer self.output_weights -= self.eta * self.output_weights_gradient self.output_bias -= self.eta * self.output_bias_gradient for i, layer in reversed(list(enumerate(self.hidden_layers))): if(i == (self.n_hidden_layers-1)): forward_error = error_output forward_weights = self.output_weights else: forward_error = self.hidden_layers[i+1].error forward_weights = self.hidden_layers[i+1].hidden_weights layer.error = np.matmul(forward_error, forward_weights.T) * layer.hidd_act_function_deriv(layer.z_h) if(i == 0): backward_a = self.X_data else: backward_a = self.hidden_layers[i-1].a_h layer.hidden_weights_gradient = np.matmul(backward_a.T, layer.error) layer.hidden_bias_gradient = np.sum(layer.error, axis=0) if self.lmbd > 0.0: layer.hidden_weights_gradient += self.lmbd * layer.hidden_weights layer.hidden_weights -= self.eta * layer.hidden_weights_gradient layer.hidden_bias -= self.eta * layer.hidden_bias_gradient def train(self): ''' Training of the neural network, includes forward pass and backpropagation''' data_indices = np.arange(self.n_inputs) for i in range(self.epochs): for j in range(self.iterations): # pick datapoints without replacement chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False) # minibatch training data self.X_data = self.X_data_full[chosen_datapoints] self.Y_data = self.Y_data_full[chosen_datapoints] self.feed_forward() self.backpropagation() def predict(self, X): ''' Predicting value for regression''' self.X_data = X self.feed_forward() return self.a_o def predict_class(self, X): ''' Predicting value for classification''' self.X_data = X self.feed_forward() return np.argmax(self.a_o, axis=1) class HiddenLayer: def __init__(self, n_neurons, n_features, activation_function): ''' Initializing neurons, features and activation functions in the hidden layer''' self.n_hidden_neurons = n_neurons self.n_features = n_features self.activation_function = activation_function def hidd_act_function(self, x): ''' Setting activation function''' return(set_activation_function(x, self.activation_function)) def hidd_act_function_deriv(self, x): ''' Setting derivative of activation function''' return(set_activation_function_deriv(x, self.activation_function)) def create_biases_and_weights(self): ''' Initializing weights and biases for a hidden layer''' self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
5e8f51f22f2b539125dbab79cc3c0c55cb9ec763
Rlizaran/python-challange
/PyPoll/main.py
2,346
3.96875
4
import os import csv # main function def main(): # This path goes to the directory Resources and select the budget_data.csv file filepath = os.path.join('Resources', 'election_data.csv') totalVotes = [] candidates = [] votes = [0, 0, 0, 0] # Opens csv file as read mode with open(filepath, 'r') as file: csv_reader = csv.reader(file, delimiter=',') # This skips the firts row of the CSV file next(csv_reader) # Append total amount fo votes to totalVotes and if the candidate is not in candidates list # append it as well. for row in csv_reader: totalVotes.append(row[2]) if row[2] not in candidates: candidates.append(row[2]) # Calculate total votes for each candidate for person in totalVotes: if person == candidates[0]: votes[0] += 1 elif person == candidates[1]: votes[1] += 1 elif person == candidates[2]: votes[2] += 1 elif person == candidates[3]: votes[3] += 1 # Calculate percents of votes won for each candidates firstCandidate = (votes[0]/len(totalVotes))*100 secondCandidate = (votes[1]/len(totalVotes))*100 thirdCandidate = (votes[2]/len(totalVotes))*100 fourthCandidate = (votes[3]/len(totalVotes))*100 # Find candidate winner winnercandidate = candidates[votes.index(max(votes))] # Create variable to hold values to be printed into terminal and text document toprint = ("Election Results\n----------------------------\n" f"Total Votes: {len(totalVotes)}\n----------------------------\n" f"{candidates[0]}: {firstCandidate:9.3f}% ({votes[0]})\n" f"{candidates[1]}: {secondCandidate:7.3f}% ({votes[1]})\n" f"{candidates[2]}: {thirdCandidate:11.3f}% ({votes[2]})\n" f"{candidates[3]}: {fourthCandidate:1.3f}% ({votes[3]})\n" f"----------------------------\nWinner: {winnercandidate}\n" "----------------------------") # Print to terminal print(toprint) # Open path to text file in which the values will be recorded and write those values output = os.path.join('analysis','analysis.txt') with open (output,'w') as text: text.write(toprint) # Run main function if __name__ == "__main__": main()
e8ddec968c9ccf4fff6913d9cbd579cdd9ad3587
djaychela/playground
/codefights/arcade/python/drilling_the_lists/math_practice.py
204
3.671875
4
import functools def mathPractice(numbers): return functools.reduce(lambda acc, x: (acc + x[1] if x[0] % 2 else acc * x[1]), enumerate(numbers), 1) print(mathPractice(numbers=[1, 2, 3, 4, 5, 6]))
f9e6c2763170012b96dedc094e95fd1d29e80892
krishnadhara/my-programs
/krishna/Reddy/python/function_utilities.py
1,540
3.765625
4
#map,filter,reduce #map(function_object,iterable1,iterable2) def mul(x): return x*2 c=mul(4) print(c) a=map(lambda x:x*2, [1,2,3,4]) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(a.__next__()) print(list(map(lambda x:x*2, [1,2,3,4]))) dict=[{'name':'python','points':10},{'name':'java',"points":8}] print(list(map(lambda x:x['name'],dict))) print(list(map(lambda x:x["points"]*10,dict))) print(list(map(lambda x:x['name']=='python',dict))) print(list(map(lambda x,y:x+y,[3,4,5],[6,7,8]))) dict=({'name':'python','points':10},{'name':'java',"points":8}) print(tuple(map(lambda x:x['name'],dict))) print(tuple(map(lambda x,y:x+y,(3,4,5),(6,7,8)))) print(set(map(lambda x,y:x+y,{3,4,5},{6,7,8}))) #filter f=[0,1,1,2,12,3,4,5,2,3,4,5,6,7,8,21,23,34,4,5,66,44] odd_num=list(filter(lambda x:x%2!=0,f)) evn_num=tuple(filter(lambda x:x%2==0,f)) evn_num_set=set(filter(lambda x:x%2==0,f)) print(odd_num,evn_num,evn_num_set) #recursion def fact(x): if x==1: return 1 else: return (x*fact(x-1)) a=fact(5) print(a) #closers def kri(a,b): return a+b def dha(fun): print(fun(2,4)) print(fun(3,5)) dha(kri) def contains_factory(x): def contains(lst): return x in lst return contains contains_15 = contains_factory(15) print(contains_15([1,2,3,4,5])) print(contains_15([13,14,15,16,17])) def outerfunc(x): def innerfunc(): print(x) innerfunc() outerfunc(7) def outerfunc(x): def innerfunk(): print(x) return innerfunk my=outerfunc(7) my()
3dd24143907bf4ca535d5d96c22eb812705ed693
MaryanneNjeri/pythonModules
/.history/repeated_20200903104547.py
520
3.890625
4
def repeated(s): # soo umm we supposed to check if the string can be # made from its substring if len(s) == 0: return False n = len(s) for i in range(n// 2,0,-1): newStr = s[0:i] print(new) count = 1 while len(newStr) <= n: newStr = s[0:i] * count if newStr == s: return True count +=1 return False print(repeated("abcdabcd"))
8729f7ed2327a1a9b47466aa749ea7e7d235badc
prathammehta/interview-prep
/SumOfIntegers.py
354
4.125
4
# https://www.geeksforgeeks.org/ways-to-write-n-as-sum-of-two-or-more-positive-integers/ def sum_of_integers(num): possibilites = [0 for _ in range(num + 1)] possibilites[0] = 1 for i in range(1,num): for j in range(i, num+1): possibilites[j] = possibilites[j] + possibilites[j - i] pass return possibilites[num] print(sum_of_integers(5))
e7cf1b9bc1fe5ee8bb6aff718c325abe51c58695
banana-galaxy/challenges
/challenge4(zipcode)/PinkFluffyUnicorn.py
282
3.6875
4
def validate(zipCode): if isinstance(zipCode,int) and len(str(zipCode)) == 5: s = str(zipCode) temp = [a for a, b in zip(s, s[2:]) if a == b] if len(temp) == 0: return True else: return False else: return False
4583b4a5c68b8611fb890659847fa3b649ebee8f
AAliAbidi/Python-Code
/01_Welcome.py
100
3.78125
4
# print("Hey now brown cow") x = input("Enter name: ") print ("Hey " + x) input("Press<enter>")
ca80ac09b2bc16e7b996ef0210b6115a5585a0db
MysteryMS/tpa-lista5
/ex07.py
221
3.828125
4
n1 = int(input("Insira o primeiro número: ")) n2 = int(input("Insira o segundo número: ")) inter = [] count = n1+1 while count < n2: inter.append(str(count)) count += 1 print(f"Resultado: {' '.join(inter)}")
0eebdf5a25bac022805349f549c6a5cdac5e521b
mcwills-clemson/Darknet
/CityScapes_Conversion/scripts/pyscript.py
1,396
3.578125
4
#Pseudo Code for Python OpenCV Bounding Boxes # Courtesy of Carlos Piza-Palma import cv2 import numpy as np #import image #note: you may wish to make copies of the original image as # some functions are destructive. ################Part I Masks############################################# #Use masks to extract only relevant parts of the image we are interested in #note: HSV color space mask ranges may become obsolete with original images #convert image to hsv colorspace #Red mask (for pedestrians) #note: red hsv has to color ranges you will need to make two masks and # add them together for the full range #lower mask (0-10) #upper mask (170-180) #final mask in full range #Yellow mask #Blue Mask #restore color #This restores the original color back to the masked images #display images #Note: You could display all the images up to this point here or # display them after each step. #################Part II Contours###############3########################### #Find contours for the desired objects #convert image to gray #blur image #edge detection (optional) #erosion (optional) #thresholding #closing (optional) #find contours #draw contours ################Part III Bounding Boxes###################################### #drawing bounding boxes #exit stuff #note:this closes all windows after a keypress k = cv2.waitKey(0) & 0xFF if k == 27: cv2.destroyAllWindows()
d941a98bcaae0dc7d40d0ec6fce1b84c382267b5
FreddyBarcenas123/Python-lesson-2-
/Excercise2.py
215
4.15625
4
#FreddyB-Exercise 3: Write a program to prompt the user for hours and rate per hour to compute gross pay. print("Enter hours:") print("Enter Rate:") print("Pay:") Hours = "35" Rate = "2.75" Pay = "96.25"
625414b6cab5f9919c4a89c7e82bff7a77853c36
mkd/uic_cli
/main.py
4,291
3.953125
4
#!/usr/bin/python # Valeriy Volodenkov, Eva Rio, Claudio M. Camacho # T-121.5300 User Interface Construction # Aalto University, School of Science import sys import sqlite3 ERROR_OPTION_DOES_NOT_EXIST = 991 DB = "products.db" # keep the number of items in the current cart items = [ ] shopping_cart = { } #goods fetched by search query temp_goods_list = [] # list of actions actions = { 'add_item' : "Add item", 'edit_item' : "Edit item", 'remove_item' : "Remove item", 'checkout' : "Check out", 'empty_cart' : "Empty cart", 'find_product' : "Find products", 'quit' : "Quit" } ## # Exit the program. def quit(): print "\nGoodbye!" exit() ## # Sub-program to help the user find a product. def find_product(): print "\n" filter_str = raw_input("Enter a product name or description: ") result = search(filter_str) if result.count > 0: global temp_goods_list temp_goods_list = result print result ## # Sub-program to help the user find a product. # # @param filter_str String containing a filter for the SQL query. # # @return a list of tuples with the products that match the filter_str. def search(filter_str): conn = sqlite3.connect(DB) cursor = conn.cursor() # first find all products inside a related category cursor.execute("select code from category where name like '%" + filter_str + "%'") cats = [ ] for c in cursor.fetchall(): cats.append(str(c[0])) categories = ', '.join(cats) cursor.execute("select code,name from product where category in (" + categories + ") or name like '%" + filter_str + "%' order by name asc") return cursor.fetchall() ## # Display a list of options and return the selected option. # # @return the name of the callback to execute. def get_menu_option(options): count = 1 for o in options: print str(count) + ". " + actions[o] count += 1 # sanitize input try: opt = int(raw_input("Your choice: ")); except: opt = 0 if opt > len(options) or opt < 1: return ERROR_OPTION_DOES_NOT_EXIST return options[opt - 1]; ## # Display the initial main menu with the major options to the user. def main_menu(): #not sure what are items, added shopping cart #print "Items in the cart: " + str(len(items)) + "\n" print "Items in the cart: " + str(len(shopping_cart)) + "\n" # looks messy # if we have any item found we can add it option_list = [] if(len(temp_goods_list) > 0): option_list = ['add_item', 'quit'] else: option_list = ['find_product', 'quit'] if (len(shopping_cart) > 0): print "!!!!!something is in the cart!!!!!!" option_list.extend (['edit_item','checkout','empty_cart']) option = get_menu_option(option_list) return option ## # ToDo:Check code before adding def add_item(): print "Enter item's code to add it to the cart" for item in temp_goods_list: print str(item[0]) + ". " + item[1] print "\n" code = -1 try: code = int(raw_input("Your choice")); add_to_cart(code) except: code = -1 ## # Add item or increase number of item by adding it def add_to_cart(code): try: shopping_cart[str(code)] += 1 # count = shopping_cart[str(code)] #if count >= 0: except: shopping_cart[str(code)] = 1 ## # Just showing shopping list for now def checkout(): print "Here is you shopping cart" print shopping_cart #tem in shopping_cart: #print [x[1] for x in temp_goods_list if x[0]==item] #temp_goods_list[item] #We need to store items' names somewhere del temp_goods_list[:] def edit_item(): print "editing..." def empty_cart(): shopping_cart.clear() del temp_goods_list[:] # main program opt = "" while 1 is 1: # show the main menu and get an option from the user opt = main_menu() # if the option did not exist in the menu, print the menu again if opt == ERROR_OPTION_DOES_NOT_EXIST: print "\nWrong option.\n" continue # load the callback associated with the given option self_module = sys.modules[__name__] getattr(self_module, opt)()
c5fc5a6b6a323f1857703c975e6aaf4aaa2b427b
Distributed-SLSH/Distributed-SLSH
/distributed_SLSH/middleware/utils/generate_data.py
2,081
3.53125
4
''' File containing the methods to generate datasets and store them into files. ''' import numpy as np import sys def generate_identity(D, folder, prediction=False): """ Generate identity matrix. :param D: dimensionality :param folder: folder to store the dataset to :return: nothing """ pred_string = "" X = np.eye(D) if prediction: labels = np.ones((1, D)) X = np.append(X, labels, axis=0) pred_string = "labeled_" filename = folder + pred_string + "identity_{}".format(D) write_matrix_to_file(filename, X, prediction=prediction) def generate_isotropic_gaussian(d, n, folder): ''' Generate identity matrix. :param d: dimensionality :param folder: folder to store the dataset to :return: nothing ''' # Data generation. mean = 0 std = 20 X_shape = (d, n) X = np.random.normal(mean, std, X_shape) # Generate dataset. filename = folder + "gaussian_{}x{}".format(d, n) write_matrix_to_file(filename, X) def write_matrix_to_file(filename, X, prediction=False): """ Write the matrix to a file. Each line is a point, separated by spaces. :param filename: filename :param X: the input numpy matrix :return: nothing """ f = open(filename, 'w') for i in range(np.shape(X)[1]): line = "" for j in range(np.shape(X)[0]): line += str(X[j, i]) if not prediction: if j != np.shape(X)[0] - 1: line += " " else: if j <= np.shape(X)[0] - 3: line += " " elif j == np.shape(X)[0] - 2: line += " - " print(line, file=f) f.close() if __name__ == "__main__": # Format: type n d folder = "./datasets/" type = sys.argv[1] n = int(sys.argv[2]) d = int(sys.argv[3]) if type == "identity": generate_identity(d, folder, prediction=True) elif type == "gaussian": generate_isotropic_gaussian(d, n, folder)
5c246326341f131f989831cd5c69f7e1308d89dd
poojaisabelle/python-challenge
/PyBank/main.py
3,081
4
4
# Import modules import os import csv # Set the path to input the budget_data.csv budget_data = os.path.join("Resources", "budget_data.csv") # Open input csv and read with open(budget_data, "r", encoding="utf-8") as input_csv_file: csvreader = csv.reader(input_csv_file, delimiter = ",") # Skip the header row csv_header = next(csvreader) # List for storing the columns to facilitate calculations data_months = list() data_profit_loss = list() profit_loss_change = list() # Use for loop to read through rows and add the data to the newly defined lists for rows in csvreader: data_months.append(rows[0]) data_profit_loss.append(int(rows[1])) # 1. Calculate the total number of months included in the dataset total_months = len(data_months) # 2. Calculate the net total amount of Profit/Losses over the entire period total_profit_loss = sum(data_profit_loss) # Subtract every subsequent value with the value before it to determine each change that occurs month-to-month for x in range(1, len(data_profit_loss)): profit_loss_change.append((int(data_profit_loss[x]) - int(data_profit_loss[x-1]))) # 3. Calculate the average of the changes in "Profit/Losses" over the entire period average_change = sum(profit_loss_change) / len(profit_loss_change) # 4. Calculate the greatest increase in profits (date and amount) over the entire period greatest_increase = max(profit_loss_change) # Obtain the date associated with greatest increase date_greatest_increase = data_months[profit_loss_change.index(greatest_increase)+1] # 5. Calculate greatest decrease in losses (date and amount) over the entire period greatest_decrease = min(profit_loss_change) # Obtain date associated with greatest decrease date_greatest_decrease = data_months[profit_loss_change.index(greatest_decrease)+1] # Print all financial results print("Financial Analysis") print("--------------------------------------------------") print(f"Total Months: {total_months} ") print(f"Net Total Profit/Loss: ${total_profit_loss}") print(f"Average Change in Profit/Loss: ${average_change:.2f}") print(f"Greatest Increase in Profits: {date_greatest_increase} ${greatest_increase} ") print(f"Greatest Decrease in Profits: {date_greatest_decrease} ${greatest_decrease} ") # Export results to a new text file analysis_path = "Analysis/financial_results.txt" with open(analysis_path, 'w') as f: f.write("Financial Analysis" + "\n") f.write("--------------------------------------------------" + "\n") f.write(f"Total Months: {total_months} " + "\n") f.write(f"Net Total Profit/Loss: ${total_profit_loss}" + "\n") f.write(f"Average Change in Profit/Loss: ${average_change:.2f}" + "\n") f.write(f"Greatest Increase in Profits: {date_greatest_increase} ${greatest_increase} " + "\n") f.write(f"Greatest Decrease in Profits: {date_greatest_decrease} ${greatest_decrease} " + "\n")
f7133938af39b35af3692bff0b98a7f962d7863e
mfguerreiro/Python
/Introdução/ex1Aula6.py
275
4.03125
4
n = int(input("Digite um número:")) while n >= 0: if n == 0: print("1") else: fatorial = n i = n - 1 while i > 1: fatorial = fatorial * i i -= 1 print(fatorial) n = int(input("Digite um número:"))
f0388e36939ac32be0300373efba7a1bcaa350c1
Built00/Leetcode
/Populating_Next_Right_Pointers_in_Each_Node_II.py
1,503
4.3125
4
# -*- encoding:utf-8 -*- # __author__=='Gan' # Follow up for problem "Populating Next Right Pointers in Each Node". # What if the given tree could be any binary tree? Would your previous solution still work? # Note: # You may only use constant extra space. # For example, # Given the following binary tree, # 1 # / \ # 2 3 # / \ \ # 4 5 7 # After calling your function, the tree should look like: # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ \ # 4-> 5 -> 7 -> NULL # Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None # BFS, use dummy pointer to point the head of next level. # 61 / 61 test cases passed. # Status: Accepted # Runtime: 92 ms # Your runtime beats 51.02 % of python submissions. class Solution: # @param root, a tree link node # @return nothing def connect(self, root): dummy = tail = TreeLinkNode(0) while root: tail.next = root.left if tail.next: tail = tail.next tail.next = root.right if tail.next: tail = tail.next root = root.next if not root: tail = dummy root = dummy.next if __name__ == '__main__': root = TreeLinkNode(1) root.right = TreeLinkNode(2) print(Solution().connect(root))
8622bb61191de9577b9544e9485393e9e8283b1b
tcoln/NowCoder
/阿里链表中间元素2.py
733
3.796875
4
class Node(object): def __init__(self, val): self.data = val self.next = None def print_middle_element(head): if not head: return None p1 = None p2 = head while p2 and p2.next: if not p1: p1 = head else: p1 = p1.next p2 = p2.next.next if p2: if not p1: return p2.data else: return p1.next.data else: return (p1.data, p1.next.data) l = [1,2,3,4,5,6] l = [1] head = None pre = None for i in l: cur = Node(i) if not head: head = cur pre = cur else: pre.next = cur pre = cur cur = head print 'LinkList:', while cur: print cur.data, cur = cur.next print ' meddle element:' , print_middle_element(head)
a74696e2da9b0d16c4630b3ca96f3bd8de69aea8
waitingliu/notes
/python/using_dict.py
288
3.53125
4
ab = { 'liu':'huantian', 'yang':'peng', 'wang':'binghua' } xing = raw_input('input a xing:') if xing in ab: print ab[xing] else: print 'not exists..' ab['li'] = 'bian' print 'add li:',ab del ab['wang'] print 'del wang:',ab for xing,ming in ab.items(): print '%s-%s' %(xing,ming)
de89c0be8b3461e0292f51aed71f898df9d3d9f1
spametki/web3py
/web3py/storage.py
920
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`, and setting obj.foo = None deletes item foo. >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o['a'] 2 >>> del o.a >>> print o.a None """ __slots__ = () __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ __getitem__ = dict.get __getattr__ = dict.get __repr__ = lambda self: '<Storage %s>' % dict.__repr__(self) # http://stackoverflow.com/questions/5247250/why-does-pickle-getstate-accept-as-a-return-value-the-very-instance-it-requi __getstate__ = lambda self: None __copy__ = lambda self: Storage(self) if __name__ == '__main__': import doctest doctest.testmod()
0b953fa66505720a02408992fd0785089aed4295
facu2279/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
258
3.53125
4
#!/usr/bin/python3 """ my_int""" class MyInt(int): """Class MyInt""" def __init__(self, xd): """iniciar""" self.xd = xd def __eq__(self, xd): return self.xd != xd def __ne__(self, xd): return self.xd == xd
052f2f2133ece64fe3a78041fc1731e65fbcba9b
gordonli08/Exercism-python
/perfect-numbers/perfect_numbers.py
411
3.578125
4
import math def classify(number): if number < 1: raise ValueError("Not a natural number") maxfactor = math.floor(math.sqrt(number)) aliquot = 0 for i in range(1,maxfactor + 1): if number % i == 0: if i * i == number: aliquot += i else: aliquot += i + (number/i) aliquot -= number if aliquot > number: return "abundant" if aliquot < number: return "deficient" return "perfect"
e30be62bc9c2b884bdaae8bd821e210d914a729c
bluerosinneo/Three-Fair-Dice
/threeFairDice.py
2,558
3.765625
4
# python 2.7 # This code explores the likelihood of repeated results when rolling three fair sixe-sidded dice four times rolls = {} for x in range(3,19): rolls[x]=0 for i in range(1,7): for j in range(1,7): for k in range(1,7): result = i+j+k rolls[result]=rolls[result]+1 print "Probabilities of rolling result of three d6:" for x in rolls: print "{}: {}/216".format(x,rolls[x]) print "" sumOfRolls = 0 for x in rolls: sumOfRolls = sumOfRolls + rolls[x] print "Sum of all the rolls is {}".format(sumOfRolls) print "" print "Now we calculate the different number of outcomes when three d6 are rolled four times." print "" #E keeps track of all the wasy we get repeated results E = 0 #number of ways all for rolls are the same A = 0 for i in rolls: result = rolls[i]*rolls[i]*rolls[i]*rolls[i] A = A + result print "A: All four results are the same" print "A: {}".format(A) print "" #number of ways three of the results are the same #i is repeated and j is the singleton B = 0 for i in rolls: for j in rolls: if(i!=j): # note that for any instance of i and j there are 4 ways it can happen result = rolls[i]*rolls[i]*rolls[i]*rolls[j]*4 B = B + result print "B: A result is repeated exaclty three times." print "B: {}".format(B) print "" #number of ways for two results are the same #i is the repeated and j/k are the singletons #note that for any instance of i/j/k there are 12 ways they can be arranged #but because how we are iterating j and k we will cut 12 in half to 6 C = 0 for i in rolls: for j in rolls: for k in rolls: if((i!=j)&(i!=k)&(j!=k)): result = rolls[i]*rolls[i]*rolls[j]*rolls[k]*6 C = C + result print "C: A result is repeated exaclty two times" print "C: {}".format(C) print "" #number of ways two repeated results #i and j are both repeatd result D = 0 for i in rolls: for j in rolls: if(i!=j): result = rolls[i]*rolls[i]*rolls[j]*rolls[j]*3 D = D + result print "D Two results are repeated once each" print "D: {}".format(D) print "" #number of was we do not get repeated results Fnot = 0 for i in rolls: for j in rolls: for k in rolls: for l in rolls: if((i!=j)&(i!=k)&(i!=l)&(j!=k)&(j!=l)&(k!=l)): result = rolls[i]*rolls[j]*rolls[k]*rolls[l] Fnot = Fnot +result F = A+B+C+D print "F: one or more results are repeated any number of times" print "F: {}".format(F) print "F': {}".format(Fnot) print "" print "Sample size is {}".format((6**3)**4) print "F + F' = {}".format(F+Fnot) print "" print "P(F) = {0:.5f}".format(float(F)/float((216**4)))
0e56874eb80d811e80cd528da495c265949d4250
toshi09/algorithms
/Determine_string_has_unique_characters.py
308
3.84375
4
def unique(input_string): sort_input = sorted(input_string) unique_found = True for idx in range(len(sort_input)-1): if sort_input[idx] == sort_input[idx + 1]: unique_found = False else: continue return(unique_found) unique('ashwani')
e384ed2670512ff1840e2ecd207dc26edb0dc253
RoyMcCrain/Mastering-Vim
/Chapter06/animal_farm.py
753
3.921875
4
#!/usr/bin/python3 """Our own little animal farm.""" import sys from animals import cat from animals import dog from animals import sheep import animal import farm def make_animal(kind): """Create an animal class.""" if kind == 'cat': return cat.Cat() if kind == 'dog': return dog.Dog() if kind == 'sheep': return sheep.Sheep() return animal.Animal(kind) def main(animals): animal_farm = farm.Farm() for animal_kind in animals: animal_farm.add_animal(make_animal(animal_kind)) animal_farm.print_contents() animal_farm.act('a farmer') if __name__ == '__main__': if len(sys.argv) == 1: print('Pass at least one animal type!') sys.exit(1) main(sys.argv[1:])
93da8269b535c894a7c685c65107551da3baa692
pytutorial/samples
/_summary/2.if/s21.py
215
3.515625
4
# Nhập vào 2 số, in ra số lớn hơn a = input('Số thứ nhất:') b = input('Số thứ hai:') a = float(a) b = float(b) if a > b: print('Số lớn hơn:', a) else: print('Số lớn hơn:', b)
a0176c0ca1e9626eb18cfccc5304198eb9a96dac
k-yama007/python3
/Myclass.py
1,133
4.1875
4
class Myclass: """A simple example class""" i = 12345 def f(self): return 'hello world' class Dog: kind = 'canine' #class variable shared by all instances #dell_k_yama007 tricks = [] def __init__(self,name): self.name = name #instance variable unique to each instance self.tricks = [] def add_trick(self,trick): self.tricks.append(trick) def __init__(self): self.data=[] x=Myclass() y=Myclass print("x=Myclass()") print("Myclass():",x) print("Myclass.f:",x.f) print("Myclass.f():",x.f()) print("Myclass.i:",x.i) print("y=Myclass:",y) #9.3.3. インスタンスオブジェクト x.counter =1 while x.counter <10: x.counter = x.counter +2 print("x.counter : ",x.counter) del x.counter #9.3.5. クラスとインスタンス変数 d= Dog('Fido') e= Dog('Buddy') d.add_trick('roll over') e.add_trick('play dead') print("kind of Dog:",d.kind) print("kind of Dog:",e.kind) print("name of Dog:",d.name) print("name of Dog:",e.name) print(d.tricks) #unexpectedly shared by all dogs if __name__ == "__main__" : import sys
2fd34cd90ae558c49d3c03b2da62e0757c00a08e
harvey345/B-S
/BS.py
206
3.9375
4
num1=float(input("請輸入數字 : ")) num2= float(input("請輸入數字 : ")) if num1>num2: print(num1,">",num2) if num1<num2: print(num1,"<",num2) if num1==num2: print(num1,"=",num2)
16c20c578c9a0f464bf687e7080857082c0e0fad
felixkiptoo9888/Cafe
/frontend/lesson3.py
633
4.34375
4
# dictionary stores data using key/ value approach # mostly used to store an object data in json format: ie car details person = {'name': 'Ken', 'age': 22, 'residence': 'nairobi', 'weight': 72.5, 'height': 1.5, 'email': 'ken@gmail.com', 'marks': 410} print(person) print(person['name']) print(person['email']) # append a new entry into a dictionary person['marks'] = 500 print(person) person['address'] = 'Haven Court, Waiyaki Way' print('adding address', person) del person ['weight'] print('delete weight', person) # CRUD # Delete the whole dictionary: del person del person
ba1175394d2562d42e4d73631debba07c4ab18b7
Beardocracy/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py
6,769
3.609375
4
#!/usr/bin/python3 ''' This module tests the rectangle class ''' import unittest import sys from models.rectangle import Rectangle from models.base import Base class TestRectangle(unittest.TestCase): ''' This is a unittest for class rectangle ''' def setUp(self): ''' Resets the class variable''' Base._Base__nb_objects = 0 def test_type(self): ''' Tests if type is correct ''' a = Rectangle(5, 5) self.assertEqual(type(a), Rectangle) self.assertTrue(isinstance(a, Base)) self.assertTrue(issubclass(Rectangle, Base)) def test_id_assignment(self): ''' Tests if id assignment works ''' r1 = Rectangle(10, 5) self.assertEqual(r1.id, 1) r2 = Rectangle(10, 5, 0, 0, 98) self.assertEqual(r2.id, 98) r3 = Rectangle(10, 5, 0, 0) self.assertEqual(r3.id, 2) def test_hwxy_assignment(self): ''' tests to see if variable assignment works ''' r1 = Rectangle(10, 5, 3, 4) self.assertEqual(r1.width, 10) self.assertEqual(r1.height, 5) self.assertEqual(r1.x, 3) self.assertEqual(r1.y, 4) r2 = Rectangle(1, 5) self.assertEqual(r2.width, 1) self.assertEqual(r2.height, 5) self.assertEqual(r2.x, 0) self.assertEqual(r2.y, 0) def test_input_validation(self): ''' tests for input validation exceptions and messages''' with self.assertRaisesRegex(TypeError, 'width must be an integer'): r1 = Rectangle('hi', 5) with self.assertRaisesRegex(TypeError, 'height must be an integer'): r2 = Rectangle(5, 'hi') with self.assertRaisesRegex(TypeError, 'x must be an integer'): r3 = Rectangle(5, 5, 'hi', 5) with self.assertRaisesRegex(TypeError, 'y must be an integer'): r4 = Rectangle(5, 5, 0, 'hi') with self.assertRaisesRegex(ValueError, 'width must be > 0'): r5 = Rectangle(-5, 5) with self.assertRaisesRegex(ValueError, 'height must be > 0'): r6 = Rectangle(5, -5) with self.assertRaisesRegex(ValueError, 'x must be >= 0'): r7 = Rectangle(5, 5, -1, 5) with self.assertRaisesRegex(ValueError, 'y must be >= 0'): r8 = Rectangle(5, 5, 5, -5) def test_area(self): ''' Tests for correct output of area method ''' r1 = Rectangle(10, 5) self.assertEqual(r1.area(), 50) r2 = Rectangle(5, 5, 1, 1) self.assertEqual(r2.area(), 25) def test_display(self): ''' Tests for correct output of display method ''' r1 = Rectangle(3, 2) r2 = Rectangle(2, 4) r3 = Rectangle(2, 3, 2, 2) r4 = Rectangle(3, 2, 1, 0) orig_stdout = sys.stdout with open('test_rectangle.txt', 'w') as f: sys.stdout = f r1.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '###\n###\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f r2.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '##\n##\n##\n##\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f r3.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '\n\n ##\n ##\n ##\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f r4.display() with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), ' ###\n ###\n') sys.stdout = orig_stdout def test_str(self): ''' Tests the __str__ method override ''' r1 = Rectangle(4, 6, 2, 1, 12) r2 = Rectangle(5, 5, 1) orig_stdout = sys.stdout with open('test_rectangle.txt', 'w') as f: sys.stdout = f print(r1) with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '[Rectangle] (12) 2/1 - 4/6\n') with open('test_rectangle.txt', 'w') as f: sys.stdout = f print(r2) with open('test_rectangle.txt', 'r') as f: self.assertEqual(f.read(), '[Rectangle] (1) 1/0 - 5/5\n') sys.stdout = orig_stdout def test_update(self): ''' Tests the update method ''' r1 = Rectangle(10, 10, 10, 10) self.assertEqual(r1.id, 1) self.assertEqual(r1.width, 10) self.assertEqual(r1.height, 10) self.assertEqual(r1.x, 10) self.assertEqual(r1.y, 10) r1.update(89) self.assertEqual(r1.id, 89) r1.update(89, 2, width=5) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) r1.update(89, 2, 3) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 3) r1.update(89, 2, 3, 4, id=98) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 3) self.assertEqual(r1.x, 4) r1.update(89, 2, 3, 4, 5) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 3) self.assertEqual(r1.x, 4) self.assertEqual(r1.y, 5) r1.update(height=1) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 1) self.assertEqual(r1.x, 4) self.assertEqual(r1.y, 5) r1.update(width=1, x=2) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 1) self.assertEqual(r1.height, 1) self.assertEqual(r1.x, 2) self.assertEqual(r1.y, 5) r1.update(y=1, width=2, x=3, id=89) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 2) self.assertEqual(r1.height, 1) self.assertEqual(r1.x, 3) self.assertEqual(r1.y, 1) r1.update(x=1, height=2, y=3, width=4) self.assertEqual(r1.id, 89) self.assertEqual(r1.width, 4) self.assertEqual(r1.height, 2) self.assertEqual(r1.x, 1) self.assertEqual(r1.y, 3) def test_dictionary(self): ''' Tests the dictionary method and using it with update method ''' r1 = Rectangle(10, 2, 1, 9) r1_dict = r1.to_dictionary() control_dict = {'x': 1, 'y': 9, 'id': 1, 'height': 2, 'width': 10} self.assertEqual(r1_dict, control_dict) self.assertEqual(type(r1_dict), dict) r2 = Rectangle(1, 1) r2_dict = r2.to_dictionary() self.assertEqual(str(r2), '[Rectangle] (2) 0/0 - 1/1') r2.update(**r1_dict) self.assertEqual(str(r2), '[Rectangle] (1) 1/9 - 10/2')
2516a933b33775fdc298d7ff208bd549331d650b
ChineseKawhi/Data-Structures-and-Algorithms
/LinkList/SkipList.py
4,563
4.09375
4
""" A skip list implementation. Skip list allows search, add, erase operation in O(log(n)) time with high probability (w.h.p.). """ import random class Node: """ Attributes: key: the node's key next: the next node prev: the previous node bottom: the bottom node in skip list (the node has same key in the level below) """ def __init__(self, key): """ Create a node. Args: key: the node's key Running Time: O(1) """ self.key = key self.next = None self.prev = None self.bottom = None def find(self, target): """ Find the node whose next node has bigger key than target. Args: target: the bigger key Return: The first node whose next node have the key that is bigger than target Running Time: O(n) """ if(self.next is not None and self.next.key <= target): return self.next.find(target) else: return self def append(self, target): """ Append a node with key of target to current node. Args: target: the key of new node Running Time: O(1) """ # define two side q = self.next p = Node(target) # connect left self.next = p p.prev = self # connect right p.next = q if(q is not None): q.prev = p def delete(self): """ Delete the node next. Running Time: O(1) """ # define two side p = self.prev q = self.next # connect # if(p is not None): p.next = q if(q is not None): q.prev = p del self class Skiplist: """ Attributes: startList: the head node list """ def __init__(self): """ Create a Skiplist. Running Time: O(1) """ self.startList = [Node(-1)] def search(self, target: int) -> bool: """ Query whether the node with target key exist. Args: target: the target key Return: Whether the node with target key exist Running Time: O(log(n)) w.h.p. """ p = self.startList[-1] while(p is not None and p.key < target): p = p.find(target) if(p.key == target): return True else: p = p.bottom return False def add(self, num: int) -> None: """ Add a node with key of num. Args: num: the key of the node Running Time: O(log(n)) w.h.p. """ p = self.startList[-1] s = [] while(p is not None and p.key < num): p = p.find(num) s.append(p) if(p.key == num): s.pop() while(p is not None): s.append(p) p = p.bottom break else: p = p.bottom b = None p = s.pop() p.append(num) p.next.bottom = b b = p.next while(random.choice([True, False])): if(len(s) > 0): p = s.pop() p.append(num) p.next.bottom = b b = p.next else: start = Node(-1) start.next = Node(num) start.bottom = self.startList[-1] start.next.bottom = b start.next.prev = start self.startList.append(start) b = start.next def erase(self, num: int) -> bool: """ Delete the node with key of num. Args: num: the key of the node Return: Whether delete success Running Time: O(log(n)) w.h.p. """ p = self.startList[-1] while(p is not None and p.key < num): p = p.find(num) if(p.key == num): while(p is not None): q = p p = p.bottom q.delete() return True else: p = p.bottom return False
db85f9a280842c3c641bd5d77e55b8b7a6f0469c
smithajanardan/janardan_python
/CalcSqrt.py
692
3.96875
4
# File: CalcSqrt.py # Description: Determining the square root of a poistive integer. # Student Name: Smitha Janardan # Student UT EID: ssj398 # Course Name: CS 303E # Unique Number: 52220 # Date Created: 09-29-10 # Date Last Modified: 09-29-10 def main(): n = input ("Enter a positive number: ") while n < 0: print "Error: input not in range" n = input ("Enter a positive number: ") oldGuess = 0 newGuess = n/2.0 while abs(oldGuess - newGuess) > .000001: oldGuess = newGuess newGuess = ((n / oldGuess) + oldGuess) / 2.0 diff = newGuess - ( n ** .5 ) print "Square root is: ", newGuess print "Difference is: ", diff main()
d301d8b7c002bf4a0e13825d9ef08f45594dd7a4
Frky/p-euler
/src/p61.py
4,130
3.9375
4
#-*- coding: utf-8 -*- from p import Problem from toolbox import is_triang, is_square, is_pent, is_hexa, is_hepta, is_octa class p61(Problem): """ Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae: Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... Square P4,n=n^2 1, 4, 9, 16, 25, ... Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ... The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties. 1. The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first). 2. Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and pentagonal (P5,44=2882), is represented by a different number in the set. 3. This is the only set of 4-digit numbers with this property. Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set. """ def satisfy(self, cand): to_check = [ (is_triang, list()), (is_square, list()), (is_pent, list()), (is_hexa, list()), (is_hepta, list()), (is_octa, list()), ] for n in cand: for test in to_check: if test[0](n): test[1].append(n) used = list() for octa in to_check[5][1]: used.append(octa) for hepta in to_check[4][1]: if hepta in used: continue used.append(hepta) for hexa in to_check[3][1]: if hexa in used: continue used.append(hexa) for pent in to_check[2][1]: if pent in used: continue used.append(pent) for squa in to_check[1][1]: if squa in used: continue used.append(squa) for triang in to_check[0][1]: if triang in used: continue return True used.remove(squa) used.remove(pent) used.remove(hexa) used.remove(hepta) used.remove(octa) return False def is_nothing(self, n): return not (is_triang(n) or is_square(n) or is_pent(n) or is_hexa(n) or is_hepta(n) or is_octa(n)) def candidates(self, n): c = [10] * n while c != [99] * n: yield c i = len(c) - 1 while i >= 0 and c[i] == 99: c[i] = 10 i -= 1 if i < 0: break c[i] += 1 while self.is_nothing(100 * c[i - 1] + c[i]) and c[i] < 99: c[i] += 1 def solve(self): candidates = list() for cand in self.candidates(6): candi = list() for i in xrange(len(cand) - 1): candi.append(cand[i] * 100 + cand[i + 1]) candi.append(cand[-1] * 100 + cand[0]) if self.satisfy(candi): print candi return sum(candi) return None
0fc5d9365d0c7af606aca1b95b9d8f9664dcb818
frclasso/FCGurus_python1_turma_novembro2019
/Cap09_estruturas_de_dados/9.4_tuplas/script1.py
2,397
3.5
4
# tuplas # tupla vazia tupla_vazia =() print(f'Tipo: {type(tupla_vazia)}') # tupla de um elemento tupla_de_um_elemento = (50, ) # <==== print(f'Tipo: {type(tupla_de_um_elemento)}') # ou tupla_de_um_elemento_sem_parenteses = 50, print(f'Tipo: {type(tupla_de_um_elemento_sem_parenteses)}') # Acessando valores cursos_1 = ('Matematica', 'Economia', 'Estatistica') print(f'Retorna o valor relacionado ao indice "0" na tupla cursos_1: {cursos_1[0]}') # indexar print(f"Retorna o indice 'Econonomia' na tupla cursos_1: {cursos_1.index('Economia')}") # concatenacao cursos_2 = ('Quimica', 'Fisica', 'Biologia') print(f"Concatenacao: {cursos_1+cursos_2}") all_cursos = cursos_1 + cursos_2 # repeticao '*' print(f"Repeticao: {cursos_2 * 3}") # Iverter os valores print(f"Invrtertido: {all_cursos[::-1]}") # Ordenacao print(f"Ordenando: {sorted(all_cursos,reverse=True)}") print(f"Ordenando: {tuple(sorted(all_cursos,reverse=True))}") # Op basicas (len, max, min, in , not in) print(f"len() de all_cursos: {len(all_cursos)}") nums = (100,30,4,25) print(f"Max de nums: {max(nums)}") print(f"Min de nums: {min(nums)}") # in /not in print(f"Verfica de Python esta em all_cursos: {'Python' in all_cursos}") print(f"Verfica de Python NAO esta em all_cursos: {'Python' not in all_cursos}") # LOOPS print('Usando laço for') for num, curso in enumerate(all_cursos, start=1): print(num, '==>',curso) print() # while print('Usando laço While') count = 0 while count < len(all_cursos): print(count + 1, "==>", all_cursos[count]) count += 1 print() # classe tuple() lista_de_cursos = list(all_cursos) print(type(lista_de_cursos)) print(lista_de_cursos) all_cursos_t = tuple(lista_de_cursos) print(type(all_cursos_t)) print() # string tec = 'Python' t1 = tuple(tec) print(t1) ## Imutabilidade # pop, append, insert, del , remove - NAO FUNCIONAM EM TUPLAS #all_cursos_t[0] = 'Python' # TypeError: 'tuple' object does not support item assignment #all_cursos_t.pop() # AttributeError: 'tuple' object has no attribute 'pop' #all_cursos_t.append('Django') #AttributeError: 'tuple' object has no attribute 'append' all_cursos_t_2 = all_cursos_t[:1] print(all_cursos_t_2) ## Util usuario = ('id', 'username', 'password') del usuario print(usuario) usuarios = [ ('Fabio',), ('Gabriel'), ('Norton') ] u = [ {'fabio':('Fabio','Classo')}, {'Gabriel':('demais dados',)} ]
02bc2eb8476f2dc28cf62865c08741b2087e8c94
oliverralbertini/euler
/003/solution.py
560
3.953125
4
"""Problem 3: Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?""" import sys import math as m sys.path.append('../modules') from isprime import is_prime from prime_factorization import prime_factorization """find out the largest prime factor of big_int""" big_int = 600851475143 #big_int = 13195 def main(): """in case big_int is prime""" if is_prime(big_int) == True: return big_int return prime_factorization(big_int) primes = main() print primes[-1]
39358e75284d42b875ef5809e50838561e18af96
AdrienGuille/EGC-Cup-2016
/ciprian/utils.py
878
3.53125
4
# coding: utf-8 __author__ = "Ciprian-Octavian Truică" __copyright__ = "Copyright 2015, University Politehnica of Bucharest" __license__ = "GNU GPL" __version__ = "0.1" __email__ = "ciprian.truica@cs.pub.ro" __status__ = "Production" import csv import codecs #author field parse def getAuthorName(text, ch = ','): return [(' '.join(name.split(' ')[:-1]), name.split(' ')[-1]) for name in text.split(ch)] #this part is for reading the file def determineDelimiter(character): if character == 't': return '\t' elif character == 'c': return ',' elif character == 's': return ';' # encoding='latin-1' # 'ISO-8859-1' def readCSV(filename, encoding='latin-1'): corpus = [] idx = 0 with codecs.open(filename, 'r', encoding=encoding) as csvfile: for line in csvfile: corpus.append(line.split('\t') + [idx]) idx += 1 return corpus
b4b00c410bacf2f1aaa7c969670245c13d241e7a
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_156/828.py
1,848
3.6875
4
f = open('input.txt', 'r') def function(pancakes, t): # a = 6 # if t == a: # print(pancakes) # # print('pancakes',pancakes) biggest = pancakes[-1] indexOfBiggest = pancakes.index(biggest) numberOfBiggestPancakes = len(pancakes)- indexOfBiggest time = 0 # print(numberOfBiggestPancakes) while pancakes[-1] > 0: while len(pancakes) != 0 and pancakes[0] == 0: pancakes = pancakes[1:] length = len(pancakes) if length == 0: break biggest = pancakes[-1] indexOfBiggest = pancakes.index(biggest) numberOfBiggestPancakes = length - indexOfBiggest if numberOfBiggestPancakes + (biggest+1)//2 < biggest: # pancakes[:] = [x - 1 for x in pancakes] # # elif (length == 1 and pancakes[0] > 2) or (pancakes[-1] > 3 and (pancakes[-1] - pancakes[0] > 1 or pancakes[-1] > 4)): if biggest == 9: pancakes1 = pancakes[:] pancakes2 = pancakes[:] pancakes1[-1] = 6 pancakes1.append(3) pancakes1 = sorted(pancakes1) pancakes2[-1] = 5 pancakes2.append(4) pancakes2 = sorted(pancakes2) time1 = function(pancakes1, t) time2 = function(pancakes2, t) # print(time, time1, time2) return min(time + 1 + time1, time + 1 + time2) else: half = pancakes[-1]//2 pancakes[-1] -= half pancakes.append(half) pancakes = sorted(pancakes) else: pancakes[:] = [x - 1 for x in pancakes] # if t == a: # print(pancakes) time += 1 return time T = int(f.readline()) for i in xrange(T): noOfDiners = int(f.readline()) pancakes = f.readline().split(' ') for j in range(noOfDiners): pancakes[j] = int(pancakes[j]) pancakes = sorted(pancakes) # if max(pancakes) == 9: # print(i+1, pancakes) print("Case #" + str(i+1) + ": " + str(function(pancakes, i+1))) # 3 4 4 4 4 4 3 4
6000a48c25d77b6e671d02904460008ae9384761
EB-coder/simple-game
/main.py
2,754
3.6875
4
from tkinter import * import random as rdm class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.startUI() def startUI(self): btn = Button(root, text="Rock", font=("Times New Roman", 15), command=lambda x=1: self.btn_click(x)) btn2 = Button(root, text="Scissors", font=("Times New Roman", 15), command=lambda x=2: self.btn_click(x)) btn3 = Button(root, text="Paper", font=("Times New Roman", 15), command=lambda x=3: self.btn_click(x)) btn4 = Button(root, text='help with choise', font=('Times New Roman', 11), foreground='green', command=lambda x=4: self.btn_click(x)) btn.place(x=10, y=100, width=120, height=50) btn2.place(x=155, y=100, width=120, height=50) btn3.place(x=300, y=100, width=120, height=50) btn4.place(x=400, y=35, width=120, height=50) self.lbl = Label(root, text="Srart the game!", bg="lightyellow2", font=("Times New Roman", 21, "bold")) self.lbl.place(x=150, y=25) self.win = self.drow = self.lose = 0 self.lbl2 = Label(root, justify="left", font=("Times New Roman", 13, "bold"), text=f"Wins: {self.win} \n Loses:" f" {self.lose} \n Drows: {self.drow}", bg="lightyellow2", fg='blue') self.lbl2.place(x=5, y=5) self.lbl4 = Label(root, text="random number!", bg="lightyellow2", font=("Times New Roman", 15, "bold"), fg='black') self.lbl4.place(x=400, y=5) def btn_click(self, choise): comp_choise = rdm.randint(1, 3) any_num = rdm.randint(1, 3) if choise == comp_choise: self.drow += 1 self.lbl.configure(text="Drow", fg='violet') elif choise == 4: self.lbl4.configure(text=str(any_num)) elif choise == 1 and comp_choise == 2 \ or choise == 2 and comp_choise == 3 \ or choise == 3 and comp_choise == 1: self.win += 1 self.lbl.configure(text="Win", fg='green') else: self.lose += 1 self.lbl.configure(text="Lose", fg='red') self.lbl2.configure(text=f"Wins: {self.win}\nLoses:" f" {self.lose}\nDrows: {self.drow}") del comp_choise if __name__ == '__main__': root = Tk() root.geometry("580x200+200+200") root.title("rock, scissors, paper") root.resizable(False, False) root["bg"] = "lightyellow2" app = Main(root) app.pack() root.mainloop()
1f2995c3a905f25a3a07afb533a298ed289d551d
sreerajch657/internship
/practise questions/split list.py
340
3.828125
4
#Take a list of 10 elements. Split it into middle and store the elements in two dfferent lists. n=int(input("enter the limit of the list : ")) lst=[] for i in range(0,n): x=int(input("enter the elements to list : ")) lst.append(x) middle=int(n/2) print("the array after spliting : ") print(lst[ :middle]) print(lst[middle : n+1])
815c9475d75a29e92c168a85bb01ebeaa345b987
jayhebe/w3resource_exercises
/Dictionary/ex11.py
130
3.609375
4
my_dict = {'data1': 100, 'data2': -54, 'data3': 247} result = 1 for value in my_dict.values(): result *= value print(result)
6c3df315649dd506d43ee913a8ee11775798d5a7
enderst3/challenges
/swap_cases.py
261
4.15625
4
""" Swap the cases of a a given string """ def swap_case(s): swapped = '' for char in s: if char.isupper(): swapped = swapped + char.lower() else: swapped = swapped + char.upper() return swapped
91e79442027d3f90c9dc7876a7b2e06946150428
JFaruk/Py_basics
/tuple.py
500
3.828125
4
#Tuples t1=(1,23,4) print(t1[2]) # can hold mix data type t2=(1,'faruk','ccc',4) print(t2[3]) # slicing print(t2[-3]) #tuples are immutable means cant assign or change index after assigning them to something # t2[0]='faruk' # print(t2) #this will through a error call 'tuple' object does not support item assignment # Sets x=set() x.add(2) x.add(3) x.add(9) x.add(8) x.add(0.1) x.add(6) x.add(8) x.add(10) print(x) converted=set([1,2,2,2,2,2,1,1,1,3,3,3,5,5,5,4,4]) print(converted)
1fb7248ef64295f0c01972afbad658ce87e8976a
myhelloos/concurrency-python
/app/thread/helloSemaphore.py
781
3.984375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: alfred_yuan # Created on 2019-01-28 """using a semaphore to synchronize threads""" import threading import time import random semaphore = threading.Semaphore(0) def consumer(): print("consumer is waiting") semaphore.acquire() print("Consumer notify : consumed item number %s " % item) def producer(): global item time.sleep(10) item = random.randint(0, 1000) print("producer notify: produced item number %s " % item) semaphore.release() if __name__ == '__main__': for i in range(0, 5): t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t2.start() t1.start() t1.join() t2.join() print("program terminated")
9d46754114c4c7f28062e6ff6f257c49f1bb7dab
Northwestern-CS348/assignment-3-part-2-uninformed-solvers-maxine1444
/student_code_game_masters.py
12,211
3.640625
4
from game_master import GameMaster from read import * from util import * class TowerOfHanoiGame(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ See overridden parent class method for more information. Returns: A Fact object that could be used to query the currently available moves """ return parse_input('fact: (movable ?disk ?init ?target)') def getGameState(self): """ Returns a representation of the game in the current state. The output should be a Tuple of three Tuples. Each inner tuple should represent a peg, and its content the disks on the peg. Disks should be represented by integers, with the smallest disk represented by 1, and the second smallest 2, etc. Within each inner Tuple, the integers should be sorted in ascending order, indicating the smallest disk stacked on top of the larger ones. For example, the output should adopt the following format: ((1,2,5),(),(3, 4)) Returns: A Tuple of Tuples that represent the game state """ ### student code goes here disk_dict = {'disk1': 1, 'disk2': 2, 'disk3': 3, 'disk4': 4, 'disk5': 5} #check if any of the pegs are empty ask1 = parse_input("fact: (empty peg1") answer1 = self.kb.kb_ask(ask1) if (answer1): #if peg1 is empty p1_tuple = () #empty tuple else: ask2 = parse_input("fact: (on ?x peg1") matches = self.kb.kb_ask(ask2) peg_num = [] for item in matches: #loop through each binding to find the disk value = item.bindings_dict['?x'] #get the disk number peg_num.append(disk_dict[value]) #look in disk dict to get the actual number peg_num.sort() p1_tuple = tuple(peg_num) #convert list to tuple ask3 = parse_input("fact: (empty peg2") answer2 = self.kb.kb_ask(ask3) if (answer2): #if peg1 is empty p2_tuple = () #empty tuple else: ask4 = parse_input("fact: (on ?x peg2") matches = self.kb.kb_ask(ask4) peg2_num = [] for item in matches: #loop through each binding to find the disk value = item.bindings_dict['?x'] #get the disk number peg2_num.append(disk_dict[value]) #look in disk dict to get the actual number peg2_num.sort() p2_tuple = tuple(peg2_num) #convert list to tuple ask5 = parse_input("fact: (empty peg3") answer3 = self.kb.kb_ask(ask5) if (answer3): #if peg1 is empty p3_tuple = () #empty tuple else: ask6 = parse_input("fact: (on ?x peg3") matches = self.kb.kb_ask(ask6) peg3_num = [] for item in matches: #loop through each binding to find the disk value = item.bindings_dict['?x'] #get the disk number peg3_num.append(disk_dict[value]) #look in disk dict to get the actual number peg3_num.sort() p3_tuple = tuple(peg3_num) #convert list to tuple result_tuple = (p1_tuple, p2_tuple, p3_tuple) return result_tuple def makeMove(self, movable_statement): """ Takes a MOVABLE statement and makes the corresponding move. This will result in a change of the game state, and therefore requires updating the KB in the Game Master. The statement should come directly from the result of the MOVABLE query issued to the KB, in the following format: (movable disk1 peg1 peg3) Args: movable_statement: A Statement object that contains one of the currently viable moves Returns: None """ #check if its a movable statement if (movable_statement.predicate == "movable"): if self.isMovableLegal(movable_statement): #check if the movable statement is legal disk = str(movable_statement.terms[0]) initial = str(movable_statement.terms[1]) target = str(movable_statement.terms[2]) game_state = self.getGameState() oldfact = "fact: (on " + disk + " " + initial + ")" self.kb.kb_retract(parse_input(oldfact)) #retract the old on fact in kb oldtop = "fact: (topstack " + disk + " " + initial + ")" self.kb.kb_retract(parse_input(oldtop)) #retract the old topstack fact in kb ask2 = parse_input("fact: (on ?x " + initial + ")") answer2 = self.kb.kb_ask(ask2) if (not answer2): #if there aren't any disks on the peg empty_fact = "fact: (empty " + initial + ")" self.kb.kb_assert(parse_input(empty_fact)) #assert the fact that the initial peg is empty now else: disk_below = "disk" + str(game_state[int(initial[-1])-1][1]) disk_below_fact = "fact: (topstack " + disk_below + " " + initial + ")" self.kb.kb_assert(parse_input(disk_below_fact)) #check if the target peg is empty or not ask1 = parse_input("fact: (empty " + target + ")") answer1 = self.kb.kb_ask(ask1) if (answer1): #if its empty/True self.kb.kb_retract(ask1) #retract the fact that its empty else: #if there are other larger disks on the target peg already, retract their topstack fact there = "disk" + str(game_state[int(target[-1])-1][0]) pasttopfact = "fact: (topstack " + there + " " + target + ")" self.kb.kb_retract(parse_input(pasttopfact)) #retract the previous topstack fact newfact = "fact: (on " + disk + " " + target + ")" self.kb.kb_assert(parse_input(newfact)) #add new position fact to kb newtop = "fact: (topstack " + disk + " " + target + ")" self.kb.kb_assert(parse_input(newtop)) #add new position fact to kb factslist = self.kb.facts for f in factslist: print(str(f)) ruleslist = self.kb.rules for r in ruleslist: print(str(r)) return def reverseMove(self, movable_statement): """ See overridden parent class method for more information. Args: movable_statement: A Statement object that contains one of the previously viable moves Returns: None """ pred = movable_statement.predicate sl = movable_statement.terms newList = [pred, sl[0], sl[2], sl[1]] self.makeMove(Statement(newList)) class Puzzle8Game(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ Create the Fact object that could be used to query the KB of the presently available moves. This function is called once per game. Returns: A Fact object that could be used to query the currently available moves """ return parse_input('fact: (movable ?piece ?initX ?initY ?targetX ?targetY)') def getGameState(self): """ Returns a representation of the the game board in the current state. The output should be a Tuple of Three Tuples. Each inner tuple should represent a row of tiles on the board. Each tile should be represented with an integer; the empty space should be represented with -1. For example, the output should adopt the following format: ((1, 2, 3), (4, 5, 6), (7, 8, -1)) Returns: A Tuple of Tuples that represent the game state """ ### Student code goes here tile_dict = {"tile1": 1, "tile2": 2, "tile3": 3, "tile4": 4, "tile5": 5, "tile6": 6, "tile7": 7, "tile8": 8, "empty": -1} xpos_dict = {"pos1": 0, "pos2": 1, "pos3": 2} ask1 = parse_input("fact: (on ?t ?x pos1)") matches = self.kb.kb_ask(ask1) row1 = [0,0,0] for item in matches: #loop through the tiles in the first row xpos = item.bindings_dict['?x'] #get the x position xpos1 = xpos_dict[xpos] #get the index number value = item.bindings_dict['?t'] #get the disk number row1[xpos1] = tile_dict[value] #look in disk dict to get the actual number r1_tuple = tuple(row1) #convert list to tuple ask2 = parse_input("fact: (on ?t ?x pos2)") #second row matches = self.kb.kb_ask(ask2) row2 = [0,0,0] for item in matches: #loop through the tiles in the 2nd row xpos2 = item.bindings_dict['?x'] #get the x position xpos22 = xpos_dict[xpos2] #get the index number value = item.bindings_dict['?t'] #get the disk number row2[xpos22] = tile_dict[value] #look in disk dict to get the actual number r2_tuple = tuple(row2) #convert list to tuple ask3 = parse_input("fact: (on ?t ?x pos3)") matches = self.kb.kb_ask(ask3) row3 = [0,0,0] for item in matches: #loop through the tiles in the first row xpos = item.bindings_dict['?x'] #get the x position xpos1 = xpos_dict[xpos] #get the index number value = item.bindings_dict['?t'] #get the disk number row3[xpos1] = tile_dict[value] #look in disk dict to get the actual number r3_tuple = tuple(row3) #convert list to tuple result_tuple = (r1_tuple, r2_tuple, r3_tuple) return result_tuple #pass def makeMove(self, movable_statement): """ Takes a MOVABLE statement and makes the corresponding move. This will result in a change of the game state, and therefore requires updating the KB in the Game Master. The statement should come directly from the result of the MOVABLE query issued to the KB, in the following format: (movable tile3 pos1 pos3 pos2 pos3) Args: movable_statement: A Statement object that contains one of the currently viable moves Returns: None """ ### Student code goes here if (movable_statement.predicate == "movable"): if self.isMovableLegal(movable_statement): #check if the movable statement is legal tile = str(movable_statement.terms[0]) x1 = str(movable_statement.terms[1]) y1 = str(movable_statement.terms[2]) x2 = str(movable_statement.terms[3]) y2 = str(movable_statement.terms[4]) #switch positions of empty and the tile oldtile = parse_input("fact: (on " + tile + " " + x1 + " " + y1 + ")") oldempty = parse_input("fact: (on empty " + x2 + " " + y2 + ")") #retract the old tile and empty position facts self.kb.kb_retract(oldtile) self.kb.kb_retract(oldempty) newtile = parse_input("fact: (on " + tile + " " + x2 + " " + y2 + ")") newempty = parse_input("fact: (on empty " + x1 + " " + y1 + ")") #assert the new tile and empty position facts self.kb.kb_assert(newempty) self.kb.kb_assert(newtile) def reverseMove(self, movable_statement): """ See overridden parent class method for more information. Args: movable_statement: A Statement object that contains one of the previously viable moves Returns: None """ pred = movable_statement.predicate sl = movable_statement.terms newList = [pred, sl[0], sl[3], sl[4], sl[1], sl[2]] self.makeMove(Statement(newList))
588f284b0c8cd0ee80f3210430ea7486f6fcebb9
SensorEducation/workshop_programs
/Loop.py
1,380
3.828125
4
#SensorEd Workshop V0.1 #Author - Jacob Ulasevich #Loop Introduction """ A loop in programming is a certain area of code that gets ran over and over again until something tells it to stop. Think of it like Newtons A loop in execution will stay in execution until another bit of code stops it. """ """ Just as we discussed with variables, there are different types of loops. Today we will be working with a WHILE loop which is the simplest form of a loop, only one condition must be met for it to run. """ """ What do you notice about the two loops? The condition inside of the parenthesis must be TRUE for the loop to run. As you saw, theres nothing that changes the True to be False so the first loop goes on forever. There are ways to manipulate the condition so make the loop run as many timea as you want! """ #Assign counter an integer digit counter = 1 #Assign runCount an integer digit greater than runCount runCount = 10 while(counter < runCount): print("number") runCount +=1 #Press F5 to save and run your program """ How many times did your star print? We used two variables to start the condition as true, then added 1 to one variable every time the loop ran to eventually make the condition false. There are numerous ways to change the variables inside the condition and inside the loop, try making your own below and run your program. """
1fb0a0e05dc6fd3fc714cdc56023954aedb99e40
jogusuvarna/jala_technologies
/read_file.py
225
3.8125
4
#Write a program to read text from .txt file using Input Stream #In the python we don’t have Input Stream instead of this we have ‘r’ mode to read the file f = open("c:\\information\\test.txt", 'r') f.read() f.close()
eeb4159a61fb206cef8ee5ada76a86d292ff2841
patrik-nilsson/Python
/2.3.py
1,162
4.3125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import random """ In the main function -sets variables for use in gameend -randomises a number -initiates the gamestart function """ def main(): c="Correct" w="Wrong" r=random.randrange(1,11) gamestart(r, c, w) return 0 """ In the gamestart function -asks the user for a number -grabs the input -checks if it's correct, higher or lower -gives you another try if you're wrong -initiates the gameend function """ def gamestart(n, c, w): print "Guess a number from 1 to 10. You get 2 attempts." g=input(">") for i in (1,2): if g == n: a=c break elif g < n: print "Wrong! "+str(g)+" is lower!" print "Guess a higher number!" a=w elif g > n: print "Wrong! "+str(g)+" is higher!" print "Guess a lower number!" a=w if i < 2: g=input(">") gameend(n, a, c, w) """ In the gameend function -checks if the answer was correct or wrong -when done, returns to main function """ def gameend(n, a, c, w): if a == c: print "Correct! "+str(n)+" was the correct number!" elif a == w: print "You couldn't guess the number.. It was "+str(n) if __name__=='__main__': main()
15fb8dbeb14662c4bd58f148a262934e7b16cca9
sidxlfc/practice
/google_question.py
1,066
3.671875
4
def find_neighbors(m, g, n, visited) : l = [] if g[0] < n and g[1] < n and g[0] > 0 and g[1] > 0 : if m[g[0]][g[1]] < m[g[0] + 1][g[1]] : l.append([g[0] + 1, g[1]]) if m[g[0]][g[1]] < m[g[0]][g[1] + 1] : l.append([g[0], g[1] + 1]) if m[g[0]][g[1]] < m[g[0] - 1][g[1]] : l.append([g[0] - 1, g[1]]) if m[g[0]][g[1]] < m[g[0]][g[1] - 1] : l.append([g[0], g[1] - 1]) elif : # so on.. return l def max_height(m, goals) : n = len(m[0]) - 1 for g in goals : l = [] visited = [] l = find_neighbors(m, g, n, visited) while l : pointer = max(l) visited.append(pointer) l.remove(pointer) #temp.append(l) temp = [] temp.append(max_height(m, find_neighbors(m, [pointer], n, visited))) return max(temp) m = [[1,2,3,4], [2,3,4,5], [4,4,4,1], [1,2G,4,6]] goals = [(2,1), (2,2)] '''goal_paths = [] goal_origins = [] for g in goals : # [x,y,value] path = [] # gets the path to origin with max length max_height(m,g,path) goal_paths.append(path) goal_origins.append(path[2])'''
cd9643d689811a2ed90b436068e229656e4054aa
elchuzade/gamerl
/games/Racing/core/core.py
9,112
3.8125
4
"""In this file we present all the classes that are used in Race game""" from common.constants import constants as common from games.Racing.constants import constants from common.core import core from games.Racing.helpers import helpers import pygame import numpy as np class MyCar: """Instance of this class becomes player's car on the game start""" def __init__(self, x, y): self.x = x self.y = y def move(self, roads_amount, direction): """Direction can be 0, 1, 2, where 0 means go-left, 1 means stay where you are, 2 means go-right""" if direction == 0 and self.x > common.MARGIN + constants.ROAD_WIDTH / 2: # Want to go-left and there is a road to the left of the player self.x -= constants.ROAD_WIDTH elif direction == 2 and self.x < roads_amount * constants.ROAD_WIDTH + common.MARGIN - constants.ROAD_WIDTH / 2: # Want to go-right and there is a road to the right of the player self.x += constants.ROAD_WIDTH class EnemyCar: """Instances of this class appear every other step""" def __init__(self, x, y): self.x = x self.y = y self.active = True def move(self): """Moves enemy car one car height down every step""" self.y += constants.CAR_HEIGHT def deactivate(self): """All cars that have active=False will be removed from game""" self.active = False class Racing(core.Game): """Creates an instance of Car Racing game""" def __init__(self, mode=common.GAME_MODE, speed=common.GAME_SPEED, roads=constants.ROADS_AMOUNT): super().__init__(mode, speed) print("Initializing a Race Environment...") self.__step_counter = 0 self.__roads_amount = roads self.__action_size = common.POSSIBLE_ACTIONS["racing"] self.__state_size = self.__roads_amount * constants.CAR_ROWS self.__enemy_cars = [] self.__my_car = MyCar(constants.MY_CAR_X, constants.MY_CAR_Y) self.__action_frequency = common.FPS / speed self.__new_car_frequency = self.__action_frequency * 2 self.__SCREEN_WIDTH = self.__roads_amount * constants.ROAD_WIDTH + common.MARGIN * 2 self.__SCREEN_HEIGHT = constants.CAR_HEIGHT * constants.CAR_ROWS + common.MARGIN * 2 + common.SCOREBOARD_HEIGHT self.__state = helpers.map_cars_to_state(self.__roads_amount, self.__enemy_cars, self.__my_car) self.model = core.Model("racing") def __test_model(self): # Building up a fake state based on amount of roads and checking the model to return proper action # TODO: Make better error raise messages with examples, steps to debug and links to videos and blog test_state = constants.TEST_STATES[:self.__roads_amount] # Check if model exists if not self.model: raise ValueError("Model does not exist!") # Check if model has predict function if not self.model.predict: raise ValueError("Model does not have a method predict!") action = self.model.predict(test_state) if action not in constants.ACTIONS: raise ValueError("Model does not predict a proper action") return print("Model has passed required tests!") def get_state(self): return self.__state def describe(self): print("State size: {}. Action size: {}".format(self.__state_size, self.__action_size)) return self.__state_size, self.__action_size def reset(self): self.__enemy_cars = [] self.__step_counter = 0 self.model = core.Model("racing") self.__my_car = MyCar(constants.MY_CAR_X, constants.MY_CAR_Y) self.__state = helpers.map_cars_to_state(self.__roads_amount, self.__enemy_cars, self.__my_car) return self.__state def __add_enemy_car(self): possible_indexes = helpers.make_possible_indexes(self.__roads_amount) coord_x, coord_y, possible_indexes = helpers.make_enemy_car_coordinates(possible_indexes) enemy_car = EnemyCar(coord_x, coord_y) self.__enemy_cars.append(enemy_car) def __add_multiple_enemy_cars(self): max_cars = 2 possible_indexes = helpers.make_possible_indexes(self.__roads_amount) while max_cars > 0: coord_x, coord_y, possible_indexes = helpers.make_enemy_car_coordinates(possible_indexes) enemy_car = EnemyCar(coord_x, coord_y) self.__enemy_cars.append(enemy_car) max_cars -= 1 def step(self, direction): self.__step_counter += 1 if self.__step_counter % 2 == 0: if self.__roads_amount > 3: self.__add_multiple_enemy_cars() else: self.__add_enemy_car() self.__state = helpers.map_cars_to_state(self.__roads_amount, self.__enemy_cars, self.__my_car) done = helpers.perform_action(self.__roads_amount, direction, self.__enemy_cars, self.__my_car) self.__state = helpers.map_cars_to_state(self.__roads_amount, self.__enemy_cars, self.__my_car) return self.__state, done def play(self): if self.__mode == "ai": self.__test_model() self.__initialize_game() def check_accuracy(self, trials): __error = helpers.check_accuracy_input(trials) if __error: raise ValueError(__error) if self.__mode == "ai": print("checking accuracy of ai model") __crash_counter = 0 __i = 0 while __i < trials: # Reshaping next state to save as neural network input reshaped_state = np.reshape(self.__state, [1, self.__state_size]) direction = self.model.predict(reshaped_state) _, done = self.step(direction) if done: __crash_counter += 1 __i += 1 # Since new cars appear every 2 actions, random accuracy means 1 mistake every roads_amount * 2 actions print("Your Accuracy: {}%, Random Accuracy: {}%".format(100 - (100 * __crash_counter) / trials, 100 - 100 / (2 * self.__roads_amount))) return 100 - __crash_counter * 100 / trials def __initialize_game(self): pygame.init() pygame.display.set_caption("Car Racing game by {}".format(self.__mode)) size = self.__SCREEN_WIDTH, self.__SCREEN_HEIGHT screen = pygame.display.set_mode(size) # Clock is set to keep track of frames clock = pygame.time.Clock() pygame.display.flip() frame = 1 action_taken = False # To restrict input actions with game step actions while True: clock.tick(common.FPS) pygame.event.pump() for event in pygame.event.get(): if self.__mode == "player" and not action_taken: # Look for any button press action if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: action_taken = True action = 0 # 0 means go left helpers.move_my_car(self.__roads_amount, action, self.__my_car) elif event.key == pygame.K_RIGHT: action_taken = True action = 2 # 2 means go right helpers.move_my_car(self.__roads_amount, action, self.__my_car) # Quit the game if the X symbol is clicked if event.type == pygame.QUIT: print("pressing escape") pygame.quit() raise SystemExit # Build up a black screen as a game background screen.fill(common.GAME_BACKGROUND) if frame % self.__action_frequency == 0: if self.__mode == "ai": self.__state = helpers.map_cars_to_state(self.__roads_amount, self.__enemy_cars, self.__my_car) # Reshaping next state to save as neural network input reshaped_state = np.reshape(self.__state, [1, self.__state_size]) action = self.model.predict(reshaped_state) done = helpers.perform_action(self.__roads_amount, action, self.__enemy_cars, self.__my_car) self.__state = helpers.map_cars_to_state(self.__roads_amount, self.__enemy_cars, self.__my_car) action_taken = False if done: print("Lost") if frame % (self.__action_frequency * 2) == 0: if self.__roads_amount > 3: self.__add_multiple_enemy_cars() else: self.__add_enemy_car() helpers.draw_state(screen, self.__enemy_cars, self.__my_car, self.__roads_amount) # update display pygame.display.flip() frame += 1
9002befb024258a18d693bcf477d404963b02594
DanielPramatarov/Python-Data-Structures-Implementation
/Stack/Stack.py
555
3.796875
4
class Stack: def __init__(self): self.stack = [] def is_empty(self): return self.stack == [] def push(self, data): self.stack.append(data) def pop(self): if self.size_stack() < 1: return None data = self.stack[-1] del self.stack[-1] return data def peek(self): return self.stack[-1] def size_stack(self): return len(self.stack) st = Stack() st.push(3212) st.push(32313) st.push(1342425654) st.push(78686) st.push(99878) print(st.pop())
a915a80bcbf624e40df7deb604c90ba2baee56ee
akshaytolwani123/gci-2019
/not-so-fast-gci/not-so-fast-gci.py
477
3.578125
4
#Not so fast task gci #By:- Akshay Tolwani #Username for gici:- akshayprogrammer #Loop to check if the input from user is valid while True: o = input('Please input n: ') if o: if o.isdigit(): n = int(o) break #Check if the number is more than 0 and less than or equal to 1024 if n > 0 and n <= 1024: answer = pow(2,n) print(answer) else: print("Please provide a number which is more than 0 and less than or equal to 1024") exit
2f3a7767919b8a83e6662ecf5a04174f3f4c3b7a
akshays-repo/learn.py
/files.py/Machine Learning/K MEAN/k means_1.py
1,734
3.984375
4
# importing required libraries import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans # read the train and test dataset train_data = pd.read_csv('/home/akshays/Desktop/learn.py/files.py/K MEAN/train-data.csv') print(train_data) test_data = pd.read_csv('/home/akshays/Desktop/learn.py/files.py/K MEAN/test-data.csv') print(test_data) # shape of the dataset print('Shape of training data :',train_data.shape) print('Shape of testing data :',test_data.shape) # Now, we need to divide the training data into differernt clusters # and predict in which cluster a particular data point belongs. model = KMeans() # fit the model with the training data model.fit(train_data) # Number of Clusters print('\nDefault number of Clusters : ',model.n_clusters) # predict the clusters on the train dataset predict_train = model.predict(train_data) print('\nCLusters on train data',predict_train) # predict the target on the test dataset predict_test = model.predict(test_data) print('Clusters on test data',predict_test) # Now, we will train a model with n_cluster = 3 model_n3 = KMeans(n_clusters=3) # fit the model with the training data model_n3.fit(train_data) # Number of Clusters print('\nNumber of Clusters : ',model_n3.n_clusters) # predict the clusters on the train dataset predict_train_3 = model_n3.predict(train_data) print('\nCLusters on train data',predict_train_3) # predict the target on the test dataset predict_test_3 = model_n3.predict(test_data) print('Clusters on test data',predict_test_3) m = pd.Series(predict_train_3) train_data['m'] = m tr0 = train_data[m == 0] tr1 = train_data[m == 1] tr2 = train_data[m == 2]
dc2f5c784de252f1f06d04effd6b7264c12cb124
shridharkapshikar/python_
/unique_list.py
387
4.1875
4
# **Write a Python function that takes a list and returns a new list with unique elements of the first list.** # # Sample List : [1,1,1,1,2,2,3,3,3,3,4,5] # Unique List : [1, 2, 3, 4, 5] def function_list(lst): unique_lst = [] for i in lst: if i not in unique_lst: unique_lst.append(i) print(unique_lst) function_list([1,1,1,1,2,2,3,3,3,3,4,5])
6e59bf3b6576bc8c9b697ce6bd9ee0860ddaeaa7
jsaraviab12/Exercism-Python
/isogram/isogram.py
236
4.09375
4
def is_isogram(string): string = string.lower() for letter in string: if letter == "-" or letter == " ": continue if (string.count(letter) > 1): return False return True
caeb4b7cc1f20905b7cd5d4506ebc9fb8ff61e43
yangzongwu/leetcode
/20200215Python-China/0394. Decode String.py
1,857
4.03125
4
''' Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. Examples: s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef". ''' class Solution: def decodeString(self, s: str) -> str: if not s: return "" s_stack=[] k=0 while k<len(s): if s[k] not in '[]': if s[k] in '1234567890': i=0 while i+k<len(s) and s[i+k] in '1234567890': i+=1 s_stack.append(s[k:k+i]) k+=i else: i=0 while i+k<len(s) and s[i+k] not in '1234567890[]': i+=1 if not s_stack or s_stack[-1].isdigit(): s_stack.append(s[k:k+i]) else: s_stack.append(s_stack.pop()+s[k:k+i]) k+=i elif s[k]==']': second=s_stack.pop() first=int(s_stack.pop()) cur=first*second if not s_stack or s_stack[-1].isdigit(): s_stack.append(cur) else: s_stack.append(s_stack.pop()+cur) k+=1 else: k+=1 return s_stack[-1]
e28269d4d872492ed3133fd2b8c9a7a96e34c62b
sabina2/DEMO3
/Hurray.py
138
3.953125
4
num1 = int(input("Enter your 1st number")) num2 = int(input("Enter your 2nd number")) if num1==num2 or num1+num2==7: print("Hurray")
afbd90d2f107bb7572ef03507b921fc3a8532a8f
N-Verma/Beginners-Python-Examples
/Percentage.py
753
3.90625
4
# Percantage Increase , Percentage Decrease def increasePercent(increase , origValue): iPercent = increase / origValue * 100 return(str(iPercent) + '%') def decreasePercent(decrease , origValue): dPercent = decrease / origValue * 100 return(str(dPercent) + '%') print('Hello\n') print('Press Enter To Exit ') incOrDec = str(input('Increase or Decrease : ')) if incOrDec == 'Increase': getInc = float(input('Increased Value : ')) orignal = float(input('Orignal Value : ')) print(increasePercent(getInc , orignal)) elif incOrDec == 'Decrease': getDec = float(input('Increased Value : ')) orignal = float(input('Orignal Value : ')) print(increasePercent(getDec , orignal)) else: quit()
1806cc48d7388d25aef3a2f7a5008dae4a6cbe9e
ayssel-uct/random_scripts
/search_pattern.py
924
3.609375
4
#this script searches for a specific input patterns (provided in Pattern_in.txt) in a fasta file, and outputs fasta sequences with matching patterns to the output fasta #!/usr/bin/env python import sys import os from collections import defaultdict import re _INPUT_FILE1 = 'Pattern_in.txt' _INPUT_FILE2 = 'Digitaria.transcripts.wgd.fasta' _OUTPUT_FILE = 'TEST_Digitaria.fasta' print (_INPUT_FILE2) def main(): p = open(_INPUT_FILE1, 'r') o = open(_OUTPUT_FILE, 'w+') for line_file1 in p: line_file1 = line_file1.replace("\n","") #strip newlines line_file1 = line_file1.replace("\r","") #strip carriage returns #print(f"1: #{line_file1}#") f = open(_INPUT_FILE2, 'r') for line_file2 in f: #print(f"#{line_file2}#") if line_file1 in line_file2: #print (f"found {line_file2}") o.write(line_file2) f.close() o.close() p.close() #f.close() print ("OK Done") if __name__ == '__main__': main()
4156231e0ebeed6a8378d1bf9d98960286375fd0
seongbeenkim/Algorithm-python
/Programmers/Level2/폰켓몬(poncketmon).py
303
3.6875
4
# https://programmers.co.kr/learn/courses/30/lessons/1845 def solution(nums): n = len(nums) // 2 nums = set(nums) if len(nums) >= n: return n else: return len(nums) print(solution([3, 1, 2, 3])) print(solution([3, 3, 3, 2, 2, 4])) print(solution([3, 3, 3, 2, 2, 2]))
591c8c0a1622fa897f18d347705d1ef709536266
WinterBlue16/Function-for-work
/Data Structure/time/02_get_month_last_day.py
276
3.703125
4
import calendar def get_month_last_day(year: int, month: int): month_last_day = calendar.monthrange(year, month)[-1] print("{}년 {}월의 마지막 날은 {}일입니다.".format(year, month, month_last_day)) return month_last_day get_month_last_day(2022, 6)
dfa58188b8063dded851616fcff5ada026607767
Reikonz/PythonLearning
/Basic Tutorial/dictionaries.py
553
4.28125
4
# python dictionaries - arrays indexed by objects (ex. strings, numbers, lists) # defining dictionaries phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 print(phonebook) phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } print(phonebook) # accessing dictionaries for name, number in phonebook.items(): print("Phone number of %s is %d" % (name, number)) del phonebook["John"] print(phonebook) phonebook.pop("Jack") print(phonebook)
90a29f9eeece05b94f0d30551d2e06a3015a21e8
mistryvatsal/Leetcode-Problems
/Remove_Nth_Node_From_Linkedlist/Solution.py
739
3.71875
4
# # Created on Fri Apr 18 2021 # # Title: Leetcode - Remove Nth node from end of linked list # # Author: Vatsal Mistry # Web: mistryvatsal.github.io # # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: first = second = head for i in range(n): if second.next is None: head = head.next return head second = second.next while second.next is not None: second = second.next first = first.next first.next = first.next.next return head
19e587f4258feabdd91bea5c338431ed404a22a6
agaitanis/deep_learning_with_python
/6_deep_learning_for_text_and_sequences/one_hot_encoding.py
2,214
4.0625
4
# -*- coding: utf-8 -*- """ Deep Learning with Python by Francois Chollet 6. Deep learning for text and sequences 6.1 Working with text data 6.1.1 One-hot encoding of words and characters """ # Word-level one-hot encoding (toy example) import numpy as np samples = ['The cat sat on the mat.', 'The dog ate my homework.'] token_index = {} for sample in samples: for word in sample.split(): if word not in token_index: token_index[word] = len(token_index) + 1 max_length = 10 results = np.zeros(shape=(len(samples), max_length, max(token_index.values()) + 1)) for i, sample in enumerate(samples): for j, word in list(enumerate(sample.split()))[:max_length]: index = token_index.get(word) results[i, j, index] = 1. # Character-level one-hot encoding (toy example) import string samples = ['The cat sat on the mat.', 'The dog ate my homework.'] characters = string.printable token_index = dict(zip(characters, range(1, len(characters) + 1))) max_length = 50 results = np.zeros(shape=(len(samples), max_length, max(token_index.values()) + 1)) for i, sample in enumerate(samples): for j, character in enumerate(sample): if j >= max_length: break index = token_index.get(character) results[i, j, index] = 1. # Using Keras for word-level one-hot encoding from keras.preprocessing.text import Tokenizer samples = ['The cat sat on the mat.', 'The dog ate my homework.'] tokenizer = Tokenizer(num_words=1000) tokenizer.fit_on_texts(samples) sequences = tokenizer.texts_to_sequences(samples) one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary') word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) # Word-level one-hot encoding with hashing trick (toy example) samples = ['The cat sat on the mat.', 'The dog ate my homework.'] dimensionality = 1000 max_length = 10 results = np.zeros((len(samples), max_length, dimensionality)) for i, sample in enumerate(samples): for j, word in list(enumerate(sample.split()))[:max_length]: index = abs(hash(word)) % dimensionality results[i, j, index] = 1.
7607700d6806d2fc27e5bb467ef0f3f5932552b8
lchoward/Practice-Python
/Graphs/LongestConseqSeq.py
1,283
3.734375
4
# # Given an unsorted array of integers, find the length of the longest consecutive elements sequence. # # Your algorithm should run in O(n) complexity. # Example: # Input: [100, 4, 200, 1, 3, 2] # Output: 4 # Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. # Therefore its length is 4. class Solution: # use dfs to search def dfs(self, num, visited, hashmap): if num in hashmap and visited[hashmap[num]] == False: visited[hashmap[num]] = True return 1 + self.dfs(num-1, visited, hashmap) + self.dfs(num+1, visited, hashmap) return 0 def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ if nums == []: return 0 visited = [False] * len(nums) hashmap = {value:key for key, value in enumerate(nums)} max_seq = 0 for num in nums: max_seq = max(max_seq, self.dfs(num, visited, hashmap)) return max_seq if __name__ == '__main__': soln = Solution() test1 = soln.longestConsecutive([]) #0 test2 = soln.longestConsecutive([100, 4, 200, 1, 3, 2]) #4 test3 = soln.longestConsecutive([1,3,5,2,4]) #5 assert test1 == 0 assert test2 == 4 assert test3 == 5
8f2eb6138629a1161090adf2363cad09c0593b66
Vivek-abstract/NCSIT-Journal-Tracking-System
/login.py
16,732
3.546875
4
import os from tkinter import * from tempfile import NamedTemporaryFile import tkinter.messagebox import datetime import shutil import csv def Login(): """This function creates the Login window and displays it""" def validate(): """Validates the user_name and password""" user_name = user_name_entry.get() password = password_entry.get() if user_name == "admin" and password == "root": login.destroy() Admin() elif user_name == "publisher" and password == "publisher": login.destroy() Publisher() else: label1 = Label(login, text="Invalid Credentials", fg="red") label1.place(relx=0.5, rely=0.7, anchor=CENTER) login = Tk() login.geometry("500x400") login.title("Login - NCSIT Journal Tracking System") login_label = Label(login, text="Login", fg="black") login_label.config(font=("Courier", 22)) user_name_label = Label(login, text="Username:", fg="black") password_label = Label(login, text="Password:", fg="black") user_name_entry = Entry(login) password_entry = Entry(login, show="*") submit_button = Button(login, text="Login", fg="blue", command=validate) exit_button = Button(login, text="Exit", command=login.destroy) login_label.place(relx=0.5, rely=0.3, anchor=CENTER) user_name_label.place(relx=0.4, rely=0.4, anchor=CENTER) user_name_entry.place(relx=0.6, rely=0.4, anchor=CENTER) password_label.place(relx=0.4, rely=0.5, anchor=CENTER) password_entry.place(relx=0.6, rely=0.5, anchor=CENTER) submit_button.place(relx=0.48, rely=0.6, anchor=CENTER) exit_button.place(relx=0.58, rely=0.6, anchor=CENTER) login.mainloop() def Admin(): """Admin Panel which displays all commands for admin""" def logout_admin(): """Destroys the window and opens the login screen""" admin_panel.destroy() Login() admin_panel = Tk() admin_panel.geometry("500x400") admin_panel.title("Admin Panel - NCSIT Journal Tracking System") welcome_label = Label(admin_panel, text="Welcome, Admin") welcome_label.config(font=("Courier", 18)) welcome_label.place(relx=0.5, rely=0.2, anchor=CENTER) review = Button(admin_panel, text="Review Missing Journals", command=calculate_missing_journals) review.place(relx=0.35, rely=0.4, anchor=CENTER) arrival_date_button = Button(admin_panel, text="Add arrival date", command=ArrivalDate) arrival_date_button.place(relx=0.65, rely=0.4, anchor=CENTER) book_journal_button = Button(admin_panel, text="Journal Reservation", command=BookJournal) book_journal_button.place(relx=0.35, rely=0.5, anchor=CENTER) renewal_button = Button(admin_panel, text="Renew Subscription", command=renew_subscription) renewal_button.place(relx=0.65, rely=0.5, anchor=CENTER) logout_button = Button(admin_panel, text="Logout", command=logout_admin) logout_button.place(relx=0.5, rely=0.6, anchor=CENTER) admin_panel.mainloop() def calculate_missing_journals(): """Calculate all the missing journals and call the display_missing_journals function""" missing_journals = [] file = open("booked_journals.csv", newline='') reader = csv.reader(file) header = next(reader) booked_journal = [row for row in reader] # Journal Name,Publish Date,Publisher Type,Date of Booking,Duration,Expiry Date journals_to_consider = [] for journal in booked_journal: date_of_booking = datetime.datetime.strptime(journal[3],"%d/%m/%Y") if journal[2] == "Indian" and (datetime.datetime.today() - date_of_booking).days > 15: journals_to_consider.append(journal) elif journal[2] == "International" and (datetime.datetime.today() - date_of_booking).days > 30: journals_to_consider.append(journal) file = open("arrived_journals.csv", newline='') reader = csv.reader(file) header = next(reader) arrived_journal_names = [row[0] for row in reader] missing_journals = [journal for journal in journals_to_consider if journal[0] not in arrived_journal_names] display_missing_journals(missing_journals) def display_missing_journals(missing_journals): """Displays all the missing journals in a new window""" missing = Tk() missing.geometry("500x400") missing.title("Missing Journals - NCSIT Journal Tracking System") missing_heading = Label(missing, text="The following Journals haven't arrived yet:") missing_heading.config(font=("Courier", 12)) missing_heading.place(relx=0.5, rely=0.1, anchor=CENTER) y = 0.2 count = 1 for each in missing_journals: # Journal Name,Publish Date,Publisher Type,Date of Booking,Duration,Expiry Date missing_journal_label = Label(missing, text=str(count) + ". " + each[0] + ", booked on: " + each[3]) missing_journal_label.place(relx=0.5, rely=y, anchor=CENTER) y+=0.1 count += 1 missing.mainloop() def ArrivalDate(): """Add arrival date window which lets user select journal and add an arrival date. It stores the result in arrived_journals.csv""" def on_closing(): """Closes the files and flushes the buffer""" file.close() file1.close() window.destroy() def add_arrival_date(): """Writes the journal name and arrival date in arrived_journals.csv""" journal_name = j_name.get() arrival_date = arrival_date_entry.get() writer.writerow([journal_name, arrival_date]) tkinter.messagebox.showinfo("Success", "The Arrival Date was successfully added") window = Tk() window.geometry("500x400") window.title("Add Arrival Date - NCSIT Journal Tracking System") if os.path.exists("arrived_journals.csv"): pass else: file = open("arrived_journals.csv", 'w', newline='') writer = csv.writer(file) writer.writerow(["Journal Name", "Arrival Date"]) file.close() file = open("arrived_journals.csv", 'a', newline='') writer = csv.writer(file) heading = Label(window, text="Add arrival date") heading.config(font=("Courier", 20)) heading.place(relx=0.5, rely=0.2, anchor=CENTER) select_label = Label(window, text="Select Journal:") select_label.place(relx=0.4, rely=0.4, anchor=CENTER) arrival_date_label = Label(window, text="Arrival Date:") arrival_date_label.place(relx=0.4,rely=0.5, anchor=CENTER) arrival_date_entry = Entry(window) arrival_date_entry.place(relx=0.62, rely=0.5, anchor=CENTER) file1 = open("booked_journals.csv", newline='') reader = csv.reader(file1) header = next(reader) booked_journal_names = [] # row = Journalname, Publishdate, PublisherType for row in reader: journal_name = row[0] booked_journal_names.append(journal_name) journal_options = booked_journal_names j_name = StringVar(window) j_name.set(journal_options[0]) # default value journal_options_select = OptionMenu(window, j_name, *journal_options) journal_options_select.place(relx=0.5, rely=0.4, anchor=W) submit_button = Button(window, text="Add", command=add_arrival_date) submit_button.place(relx=0.5,rely=0.6, anchor=CENTER) window.protocol("WM_DELETE_WINDOW", on_closing) window.mainloop() def BookJournal(): """Book journal window gives options to select journal and select the subscription type i.e Monthly, Bi-Monthly, Quarterly, Yearly""" book_window = Tk() book_window.geometry("500x400") book_window.title("Journal Reservation - NCSIT Journal Tracking System") booked_journals = [] if os.path.exists("booked_journals.csv"): pass else: file = open("booked_journals.csv", 'w', newline='') writer = csv.writer(file) writer.writerow(["Journal Name", "Publish Date", "Publisher Type", "Date of Booking", "Duration", "Expiry Date"]) file.close() file = open("booked_journals.csv", 'a', newline='') writer = csv.writer(file) def on_closing(): """Closes the files and flushes the buffer""" file.close() book_window.destroy() def book_journal(): """Writes the journal_name, date_of_booking, publish_date, publisher_type in booked_journals.csv""" global expiry_date journal_name = j_names.get() date_of_booking = datetime.datetime.today() duration = dur.get() file2 = open("published_journals.csv", newline='') reader = csv.reader(file2) data = [row for row in reader] # Jounralname, publish_date, publisher_type for row in data: if row[0] == journal_name: pub_date = row[1] pub_type = row[2] break if duration == "Monthly": expiry_date = datetime.datetime.today() + datetime.timedelta(30) elif duration == "Bi-Monthly": expiry_date = datetime.datetime.today() + datetime.timedelta(60) elif duration == "Quarterly": expiry_date = datetime.datetime.today() + datetime.timedelta(120) elif duration == "Half Yearly": expiry_date = datetime.datetime.today() + datetime.timedelta(182) formatted_date_of_booking = datetime.datetime.strftime(date_of_booking, "%d/%m/%Y") formatted_expiry_date = datetime.datetime.strftime(expiry_date, "%d/%m/%Y") writer.writerow([journal_name, pub_date, pub_type, formatted_date_of_booking, duration, formatted_expiry_date]) tkinter.messagebox.showinfo("Success", "The Journal was successfully booked") heading = Label(book_window, text="Journal Reservation") heading.config(font=("Courier", 20)) heading.place(relx=0.5, rely=0.2, anchor=CENTER) select_label = Label(book_window, text="Select Journal:") select_label.place(relx=0.5, rely=0.4, anchor=E) duration_label = Label(book_window, text="Select Duration:") duration_label.place(relx=0.5, rely=0.5, anchor=E) duration_options = ["Monthly", "Bi-Monthly", "Quarterly", "Half Yearly"] dur = StringVar(book_window) dur.set(duration_options[0]) # default value duration_options_select = OptionMenu(book_window, dur, *duration_options) duration_options_select.place(relx=0.52, rely=0.5, anchor=W) file1 = open("published_journals.csv", newline='') reader = csv.reader(file1) header = next(reader) published_journal_names = [] # row = Journalname, Publishdate, PublisherType for row in reader: journal_name = row[0] published_journal_names.append(journal_name) journal_options = published_journal_names j_names = StringVar(book_window) j_names.set(journal_options[0]) # default value journal_options_select = OptionMenu(book_window, j_names, *journal_options) journal_options_select.place(relx=0.52, rely=0.4, anchor=W) book_button = Button(book_window, text="Submit", command=book_journal) book_button.place(relx=0.5, rely=0.6, anchor=CENTER) book_window.protocol("WM_DELETE_WINDOW", on_closing) book_window.mainloop() def renew_subscription(): """Creates a temporary file to store the updated file and then renames it to original booked_journals.csv""" filename = 'booked_journals.csv' tempfile1 = "temp_booked_journals.csv" # # with open(filename, 'r', newline='') as csvFile, tempfile: csvFile = open(filename, newline='') tempfile = open(tempfile1, 'w', newline='') reader = csv.reader(csvFile) writer = csv.writer(tempfile) header = next(reader) writer.writerow(["Journal Name","Publish Date","Publisher Type","Date of Booking","Duration","Expiry Date"]) global exp_date updated_journals = [] for row in reader: # Journal Name,Publish Date,Publisher Type,Date of Booking,Duration,Expiry Date exp_date = datetime.datetime.strptime(row[5], "%d/%m/%Y") if (exp_date - datetime.datetime.today()).days <= 30: updated_journals.append(row[0]) if row[4] == "Monthly": exp_date = exp_date + datetime.timedelta(30) elif row[4] == "Bi-Monthly": exp_date = exp_date + datetime.timedelta(60) elif row[4] == "Quarterly": exp_date = exp_date + datetime.timedelta(120) elif row[4] == "Half Yearly": exp_date = exp_date + datetime.timedelta(182) formatted_exp_date = datetime.datetime.strftime(exp_date, "%d/%m/%Y") writer.writerow([row[0], row[1], row[2], row[3], row[4], formatted_exp_date]) csvFile.close() tempfile.close() shutil.move(tempfile1, filename) if(len(updated_journals) > 0): s = "" count = 1 for each in updated_journals: s += str(count) + ". " + each + "\n" tkinter.messagebox.showinfo("Success", "The Subscription of the following Journals was renewed:\n" + s) else: tkinter.messagebox.showinfo("Success", "All Subcriptions are already up-to-date.") def Publisher(): """Publisher window which contains publish journal, logout""" def logout_publisher(): """Destroys the window and opens the login screen""" publisher_panel.destroy() Login() publisher_panel = Tk() publisher_panel.geometry("500x400") publisher_panel.title("Publisher - NCSIT Journal Tracking System") welcome_label = Label(publisher_panel, text="Welcome, Publisher") welcome_label.config(font=("Courier", 18)) welcome_label.place(relx=0.5, rely=0.2, anchor=CENTER) publish_journal = Button(publisher_panel, text="Publish Journal", command=PublishJournal) publish_journal.place(relx=0.4, rely=0.4, anchor=CENTER) logout = Button(publisher_panel, text="Logout", command=logout_publisher) logout.place(relx=0.6, rely=0.4, anchor=CENTER) publisher_panel.mainloop() def PublishJournal(): """Publish Journal window which takes journal name, publish_date and publisher_type from user and stores them in published_journals""" if os.path.exists("published_journals.csv"): pass else: file = open("published_journals.csv", 'w', newline='') writer = csv.writer(file) writer.writerow(["Journal Name", "Publish Date", "Publisher Type"]) file.close() file = open("published_journals.csv", 'a', newline='') writer = csv.writer(file) def on_closing(): """Closes the files and flushes the buffer""" file.close() publish_window.destroy() def publish_journal(): """Publishes the journal and adds it in a csv file published_journals""" journal_name = journal_name_entry.get() publish_date = publish_date_entry.get() publisher_type = btn.get() writer.writerow([journal_name, publish_date, publisher_type]) tkinter.messagebox.showinfo("Success", "The Journal was successfully published") published_journals = [] # Tk doesn't work here so we use Tk() publish_window = Toplevel() publish_window.title("Publish Journal - NCSIT Journal Tracking System") btn = StringVar() btn.set("Indian") publish_window.geometry("500x400") welcome_label = Label(publish_window, text="Enter Journal Details") welcome_label.config(font=("Courier", 18)) welcome_label.place(relx=0.5, rely=0.2, anchor=CENTER) journal_name_label = Label(publish_window, text="Journal Name: ") publish_date_label = Label(publish_window, text="Publishing date: ") publisher_type_label = Label(publish_window, text="Publisher type: ") journal_name_entry = Entry(publish_window) publish_date_entry = Entry(publish_window) journal_name_label.place(relx = 0.35, rely=0.3, anchor=CENTER) journal_name_entry.place(relx = 0.6, rely=0.3, anchor=CENTER) publish_date_label.place(relx= 0.35, rely= 0.4, anchor=CENTER) publish_date_entry.place(relx = 0.6, rely=0.4, anchor=CENTER) publisher_type_label.place(relx=0.35, rely=0.5, anchor=CENTER) indian_radio_button = Radiobutton(publish_window, text="Indian", variable=btn, value="Indian") international_radio_button = Radiobutton(publish_window, text="International", variable=btn, value="International") indian_radio_button.place(relx=0.46, rely=0.5, anchor=W) international_radio_button.place(relx=0.46, rely=0.6, anchor=W) publish_button = Button(publish_window, text="Publish Journal", command=publish_journal) publish_button.place(relx=0.5, rely=0.7, anchor=CENTER) publish_window.protocol("WM_DELETE_WINDOW", on_closing) publish_window.mainloop() Login()
0d78ea7a584497039342b9c62e0290f84bbfd4db
BangAbe88/modul_python
/grade.py
803
3.640625
4
import math def grade1(nilai): if nilai<50: print("Nilai Anda E"+" __Maaf, anda tidak lulus mohon coba kembali") elif nilai>=50 and nilai<=59: print("Nilai Anda D"+" __Maaf, anda masih belum lulus mohon coba kembali") elif nilai>=60 and nilai<=74: print("Nilai Anda C"+" __Alhamdulillah, anda lulus dengan nilai cukup") elif nilai>=75 and nilai<=84: print("Nilai Anda B"+" __Alhamdulillah, anda lulus dengan nilai bagus") elif nilai>=85 and nilai<=100: print("Nilai Anda A"+" __Alhamdulillah, anda lulus dengan nilai Keren..!") else: print("Maaf Nilai anda tidak dapat kami eksekusi"+"\n__________________Karena Anda Melakukan banyak kesalahan.________ \nTerimaKasih")
cad1a97fe56016e1d9fe2523ed526eec0d44a28b
Dodilei/uncertainty_propagation
/calculator_sphere.py
265
3.671875
4
from math import pi i = True while i: print("\nDescribe your measures: \n") D = float(input("D: ")) _D = float(input("δD: ")) v = (1/6)*pi*(D**3) _v = (1/6)*pi*(3*(D**2)*_D) print(v, " +- ", _v) if input("Next? [y]/n\n") == "n": i = False
b998b5e7c529270d46c77e709552dfc0b349c67d
raghavbabbar/Learning-Python
/Basic/01_python.py
304
3.828125
4
num = 100 num2 = 100/3 print(num2) #it will print 33.33333333___ num3=100//3 print(num3) #but the num3 will be 33 num = 5*3 print(num) #it prints 15 num=5**3 print(num) #it prints 125 pth="C:Raghav\name\m" print(pth) #by inserting r no special character will b included pth=r"C:Raghav\name\m" print(pth)
f6ec843df6a4ad2fb5daca6b9ed95913a14352b7
emnsen/locale-direction-detect
/index.py
158
3.625
4
import json with open('data.json') as json_file: data = json.load(json_file) for locale in ['en', 'ar', 'fa', 'he', 'tr']: print(data[locale])
770a5baa4731aa0c5dd66312b9adb211bfce147b
y471n/algorithms-n-ds
/ds/stack-balanced-paranthesis.py
476
4.03125
4
from stack import Stack def paranthesis_check(symbols): balanced, s = True, Stack() for symbol in symbols: if symbol == "(": s.push(symbol) else: if s.is_empty(): balanced = False break s.pop() if not s.is_empty(): return False return balanced if __name__ == "__main__": symbols = input() is_balanced = paranthesis_check(symbols) print(is_balanced)
38784a0dc5809b3ddd73d5f0a706f2d58f781757
fucongcong/ssos
/php/AI/资料/Perceptron.py
1,425
3.53125
4
# -*- coding: UTF-8 -*- import numpy as np x = np.array([[2,1],[3,1],[1,1]])#创建数据集,共3个实例 y = np.array([1,1,-1]) #创建标签 history = [] #存储迭代学习过程中的w,b值,便于可视化绘图 #x.T是转置矩阵 gramMatrix = x.dot(x.T) #计算得到对称矩阵 alpha = np.zeros(len(x)) #初始化alpha为零向量 b = 0 #b为回归直线截距 learnRate = 1 #初始化为0;learnRate为学习率,设为1 k = 0; i = 0 #k用来计算迭代次数;i用来判定何时退出while循环 while 1: if y[i] * (np.sum(alpha * y * gramMatrix[i]) + b)<=0: #误分条件:若某一数据点被错误分类 alpha[i] = alpha[i] + learnRate #更新 alpha 值 b = b + learnRate * y[i] #更新 b 值 i = 0 #i 赋值为0,再遍历一次所有的数据集 k = k + 1 #k + 1 即迭代次数加1 continue else: #若某一数据点被正确分类 i = i + 1 if i >= x.shape[0]: #退出while循环条件,即 i >= 3,所有数据点都能正确分类 break #break 退出wile循环 w = (alpha*y).dot(x) #计算得到权值 w print "w = ", w print "b = ", b print "模拟次数:", k
6fdf07478e56de9f8880ddb6f4d8027f1303a8e1
volodinroman/py-flow-based-programming
/PyFBP/nodeGraph.py
6,189
3.578125
4
from port import Port from connection import Connection from node import Node from loop import NodeLoop, Loop class NodeGraph(object): """ NodeGraph controlls the way how connected nodes interract with each other """ def __init__(self): """[Constructor]""" self.nodesList = [] # list of nodes in our NodeGraph self.connectorsList = [] # list of all connection lines in our NodeGraph self.currentNode = None def setCurrentNode(self, node = None): self.currentNode = node def addNode(self, node = "Test", nodeName = None): #search for nodeName module # if exist - import data # exec(NodeType()) _node = Node(nodeName = nodeName) self.nodesList.append(_node) return _node # def connectNodes(self, sourcePort = None, targetPort = None): # con = Connection(source = sourcePort, target = targetPort) # sourcePort.setConnetionLine(line = con) # targetPort.setConnetionLine(line = con) # return con #---------------------- processing # def defence(self, node = None): # if not Node: # return # for i in node.getInputPorts(): # if not i.getValue(): # print "{} has no value".format(i.getName()) def calculatePort(self, port = None): # check pas if not port: return None _out = port.getValue() # get passed-in port value if _out != None: # if it has any value assigned (not None) return _out """#! REMOVE #get outPort -> port line | # line = port.getConnectionLine() # return L1 # #get line source # sourcePort = line.getSourcePort()""" # get the incoming connection source port (output of another node) sourcePort = port.getConnectedPort() if not sourcePort: return 0 #TODO return and do something with None result #check if the source port already has some value assigned sourcePort_value = sourcePort.getValue() if sourcePort_value: _out = sourcePort_value return _out # idea is: connected source port already has a calculated _out, but _out hasn't been sent to the target yet else: #calculate source node (get all input ports and calculate all outputs) sourcePortNode = sourcePort.getMasterNode() inputs = sourcePortNode.getInputPorts() #get all inputs for i in inputs: if not i.getValue(): #if any input has no value incoming_value = self.calculatePort(i) #get value from incoming node connected to this input if incoming_value: i.setValue(incoming_value) #Run source node (calculate outputs) sourcePortNode.run() for output in sourcePortNode.getOutputPorts(): # get the required output port from the source node if sourcePort == output: _out = output.getValue() #get the node of the current port masterNode = port.getMasterNode() #if LOOP if masterNode.getNodeType() == "Loop": loopData = masterNode.getLoopData() if masterNode.isNodeEnd(): #only if it's loop end node if loopData.isDone(): #increment +=1 | compare print ("Loop is done") loopData.zeroOutLoop() else: #_out = is our current loop output #but iteration has not been done yet #cleanup loop start loopStart = loopData.getStart() self.cleanupUpstream(node = loopStart, cleanLoop = False) #set loopStart input value = _out loopData.getStartInput().setValue(_out) _out = self.calculatePort(port = loopData.getEndInput()) #run nodes again until it gets to the end_loop loopData.getEndOutput().setValue(_out) return _out def start(self, node = None): """ @param node [class instance] the node which results we want to get """ #if no node has been specified - cancel if not node: return 0 #Make sure all required input ports have values assigned #It won't be possible to calculate this node if it's not provided with some values for i in node.getInputPorts(): #In case current input port does not have any value assigned # Retrieve value from incoming connection (if possible) if not i.getValue(): i.setValue(self.calculatePort(port = i)) #run node with calculated input values node.run() def cleanupUpstream(self, node = Node, cleanLoop = True): print ("cleaning node {}".format(node.getName())) #if we meet loop End first time - clean up steam, starting from loop Start if node.getNodeType() == "Loop" and node.isNodeEnd() and cleanLoop: print ("Here we get ", node.getName()) loopStart = node.getLoopData().getStart() self.cleanupUpstream(node = loopStart, cleanLoop = False) else: #if it's a default node or Loop Start node.cleanUpPorts() #clean all node ports' values #if node has any output connections - cleanup connected nodes for i in node.getOutputPorts(): line = i.getConnectionLine() if line: upstreamNode = line.getTargetPort().getMasterNode() #get the next upstream node self.cleanupUpstream(upstreamNode, cleanLoop = cleanLoop) #run cleanUp for this node """ Utilities """ def getNodeList(self): return self.nodesList def getCurrentNode(self): return self.currentNode
c1bc3f1eeca79cb89fc9be98951490fdc58b2b40
Lyasinkovska/BeetRootPython
/lesson_22/task_2.py
521
4.21875
4
""" Checks if input string is Palindrome is_palindrome('mom') True is_palindrome('sassas') True is_palindrome('o') True """ def is_palindrome(looking_str: str, index: int = 0) -> bool: if len(looking_str) < 2: return True if looking_str[0] != looking_str[-1]: return False return is_palindrome(looking_str[1:-1]) if __name__ == '__main__': print(is_palindrome('mom')) print(is_palindrome('sassas')) print(is_palindrome('o')) print(is_palindrome('llappyyppah'))
085f147fd7a754440c7fa2796902ef505867bc87
KIKUYA-Takumi/Python_basic
/small_large_equal.py
154
3.890625
4
InputNum = input().split() a = InputNum[0] b = InputNum[1] if a < b: print("a < b") elif a > b: print("a > b") elif a == b: print("a == b")
e75b23fbb630281d61509aed04b9e49e289fde3f
NateScheidler/ProjectEuler
/euler29.py
605
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 28 09:56:56 2014 @author: nscheidler """ # Calculates number of distinct factors of an integer # Does not count the integer itself and 1 as factors def countFactors(n): numFactors = 0 for i in range(2,n/2+1): if n%i == 0: numFactors += 1 return numFactors # Summing up all these distinct factors yields the number # of repeated spots in a grid of a^b vs b^a numRepeats = 0 for i in range(2,5): numRepeats += countFactors(i) print numRepeats print 16 - numRepeats # Never mind, this doesn't work # Putting a pin in it.
111fb653b1104c7c40dee8422845f6cf3838deac
Rsj-Python/project
/test/python.py
1,015
3.578125
4
#coding=utf-8 # 标识符 # 变量 a = 10 # 行和缩进 if True: print("正确") # 数据类型 # 1.浮点型 n = 3.14 #2.字符串 strl = 'This is Tom' # print(strl) # print(strl[8]) # print(strl[5:7]) # 格式化字符串 %s 格式化整数%d # x = 1.112 # y = 1.2210 # print(y-x) print(f'My name is 卢吊 and my age is {18}') # 3.列表 list1 = [1,'hello',True] # print(list1) # print(list1[1]) # print(list1[1:2]) # 修改 list1[0] = 2 # 添加 list1.append('卢吊') # 删除 del list1[2] # print(list1) # 元组Tuple有序,内部数据不能修改 tup1 = ('卢吊','任少杰',0,'王云蛋','徐浩然') tup2 = ('王润之','王岩','李鸿政') # print(tup1) # print(tup1[0]) # print(tup1[0:3]) tup = tup1 + tup2 print(tup) # 字典:无序 key #可以存储任意数据类型,键值对(key:value) # dic1 = dict(name='张三',gender='男',age=18) dic1 = {'name':'张三','sex':'男','age':18} print(dic1)
5f61b241f012ac728ef30fdda48380841bdda93e
entropyofchaos/QLearning
/originalPython/grid.py
2,100
3.6875
4
import qLearning class Grid: def __init__(self): self.world = [] self.cols = 0 #added by yuksel self.rows = 0 #added by yuksel self.walls = [] #added by yuksel self.weights = {} #added by yuksel def readFile(self, path): with open(path, "r") as ifs: for line in ifs: ls = [x for x in line.rstrip()] self.world.append(ls) self.rows = len(self.world) #added by yuksel self.cols = len(self.world[0]) #added by yuksel for y in range(self.rows): #added by yuksel for x in range(self.cols): #added by yuksel if(self.world[y][x] == "x"): #added by yuksel self.walls.append((x, y)) #added by yuksel def printWorld(self): for x in self.world: line = '' for y in x: line += str(y) + " " print(line) #added by yuksel def adjacent(self, loc): (x, y) = loc adj = [] if(x+1 < self.cols and (x+1, y) not in self.walls): adj.append((x+1, y)) if(x-1 >= 0 and (x-1, y) not in self.walls): adj.append((x-1, y)) if(y+1 < self.rows and (x, y+1) not in self.walls): adj.append((x, y+1)) if(y-1 >= 0 and (x, y-1) not in self.walls): adj.append((x, y-1)) return adj #added by yuksel def weight(self, target): return self.weights.get(target, 1) Grid.qLearning = qLearning.qLearning g = Grid() g.readFile("world.txt") g.printWorld() start = (0,0) goal = (4,4) #g.qLearning(start, goal) '''return_paths, gcost, hcost, fcost = g.aStar(start, goal) #added by yuksel #added by yuksel print("gcost") g.draw_grid(gcost, start, goal) print("hcost") g.draw_grid(hcost, start, goal) print("fcost") g.draw_grid(fcost, start, goal) print("path") g.reconstruct_path(return_paths, start, goal) print() '''