blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b825f1d76605fce12876d5a0bb1d57e82cb54a50
niyaspkd/python-unit-test-example
/sort.py
327
3.796875
4
class ElementTypeError(Exception):pass class TypeError(Exception):pass def sort(l): if type(l) != list: raise TypeError,"Input must be list" for i in l: if type(i) != int: raise ElementTypeError,"Invalid list element" for i in range(len(l)): for j in range(i,len(l)): if l[i]>l[j]: l[i],l[j]=l[j],l[i] return l
ee60c5f80a219159605ae413834ce60e2c4ab4a7
sumanth-hegde/Conversions
/speech-to-text-via-microphone.py
493
3.5
4
# Speech recognition using microphone # importing speech_recognition module import speech_recognition as sr r = sr.Recognizer() # Using microphone as source with sr.Microphone() as source: print("Talk now") audio_text = r.listen(source) print("Times up") try: print("Text: "+r.recognize_google(audio_text)) # adding an exception in case the audio is not recoognized except: print("sorry, audio not recognized") print("Be clear while pronouncing")
e371e74a4207ade3b0d5f5e152b71be78bb0ff3f
Ryuk17/LeetCode
/Python/394. Decode String.py
939
3.5
4
class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """ num_stack = [] char_stack = [] res = "" t = '' for c in s: if c == '[': char_stack.append(c) num_stack.append(int(t)) t = '' elif c == ']': tmp = "" while char_stack[-1] != '[': tmp = char_stack.pop() + tmp char_stack.pop() # pop '[' k = num_stack.pop() tmp *= k char_stack.append(tmp) elif (c < 'a' or c > 'z') and (c < 'A' or c > 'Z'): # number t = t + c elif 'a' <= c <= 'z' or 'A' <= c <= 'Z': # char char_stack.append(c) res = ''.join(str(t) for t in char_stack) return res
dca69aca43dac3f61cbab1b286ecd2e260b2b405
Ryuk17/LeetCode
/Python/448. Find All Numbers Disappeared in an Array.py
515
3.5625
4
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.insert(0, 0) res = [] for i in range(1, len(nums)): while nums[i] != i and nums[i] != nums[nums[i]]: tmp = nums[nums[i]] nums[nums[i]] = nums[i] nums[i] = tmp for i in range(1, len(nums)): if nums[i] != i: res.append(i) return res
4c6e1574243bee2e3bf997da8d728f52ee2973d2
Ryuk17/LeetCode
/Python/297. Serialize and Deserialize Binary Tree.py
1,318
3.515625
4
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return [] queue = [root] res = [] while len(queue) > 0: node = queue.pop(0) if node is None or node.val is None: res.append("null") else: res.append(str(node.val)) if node is not None: queue.append(node.left) queue.append(node.right) # cut i = len(res)-1 while i > 0: if res[-1] != "null": break try: if res[i] == "null" and res[i-1] == "null": res.pop() except: break i -= 1 return res def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if len(data) == 0: return return self.create(data, 0) def create(self, data, i): if i >= len(data): return root = TreeNode(data[i]) root.left = self.create(data, 2 * i + 1) root.right = self.create(data, 2 * i + 2) return root
07bb7a86ff930cb9f0d955b2c5569838836526dc
Ryuk17/LeetCode
/Python/141. Linked List Cycle.py
535
3.578125
4
class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head is None or head.next is None: return False p = head.next q = head.next.next while p.next is not None and q is not None: if q.next == p: return True else: try: p = p.next q = q.next.next except: break return False
b7ad81e0c65022aa16a1a817b0c520252f7cfefc
skmamillapalli/fluentpython-exercises
/Ch01/Frenchcard.py
1,129
4.0625
4
#!/usr/bin/env python import collections import random # card can have suit(Heart, Diamond, Spade, Club) and rank card = collections.namedtuple('Card', ['suit', 'rank']) class FrenchDeck: """Represents Deck of cards""" def __init__(self): self._cards = [card(rank, suit) for rank in ['Heart', 'Diamond', 'Spade', 'Club'] for suit in list(range(2,11))+list('JQKA')] def __len__(self): return len(self._cards) def __getitem__(self, i): # Slice object when slice notation is used, which is handled in int # 40 <class 'int'> # Card(suit='Club', rank=3) # slice(12, None, 13) <class 'slice'> print(i, type(i)) # Handling of actual work to another object, Composition - > A way of delegation return self._cards[i] cards = FrenchDeck() print(len(cards)) print(cards[-1]) # Leverage sequence type, again benefit of sticking to data model print(random.choice(cards)) # Print every 13th card, support for slicing by python framework print(cards[12::13]) # Support for interation, need either iter or getitem for card in cards: print(card)
e516ba068e730f8c2337acf71d762018c6822975
edvin328/EDIBO
/Python/dec2bin.py
536
3.9375
4
#!/bin/python3.8 n=int(input("Please enter decimal number: ")) given_dec=n #jauna massīva array izveidošana array=[] while (n!=0): a=int(n%2) # array.append komanda pievieno massīvam jaunu vērtību array.append(a) n=int(n/2) string="" # lai nolasītu massīvu array no gala izmanto [::-1] for j in array[::-1]: # string=string+str(j) mainīgais kurš pārraksta massīva vienības rindā string=string+str(j) #gala rezultāta izprintēšana uz ekrāna print("The binary number for %d is %s"%(given_dec, string))
bb4af43132c6d9246049362f3f5b554ad9a629cf
prashanthag/webDevelopment
/fullstack/projects/capstone/heroku_sample/starter/database/models.py
3,569
3.5
4
import os from sqlalchemy import Column, String, Integer from flask_sqlalchemy import SQLAlchemy import json from flask_migrate import Migrate db = SQLAlchemy() ''' setup_db(app) binds a flask application and a SQLAlchemy service ''' def setup_db(app): db.app = app db.init_app(app) migrate = Migrate(app, db) db_drop_and_create_all() # db.create_all() ''' db_drop_and_create_all() drops the database tables and starts fresh can be used to initialize a clean database !!NOTE you can change the database_filename variable to have multiple verisons of a database ''' def db_drop_and_create_all(): db.drop_all() db.create_all() ''' Movies a persistent Movies entity, extends the base SQLAlchemy Model ''' class Movies(db.Model): __tablename__ = 'Movies' # Autoincrementing, unique primary key id = db.Column(db.Integer, primary_key=True) # String Title title = Column(String(120), unique=True) release_date = Column(db.DateTime(), nullable=False) actor_id = db.Column(db.Integer, db.ForeignKey( 'Actors.id'), nullable=False) ''' insert() inserts a new model into a database the model must have a unique name the model must have a unique id or null id EXAMPLE movie = Movie(title=req_title, recipe=req_recipe) movie.insert() ''' def insert(self): db.session.add(self) db.session.commit() ''' delete() deletes a new model into a database the model must exist in the database EXAMPLE movie = Movie(title=req_title, recipe=req_recipe) movie.delete() ''' def delete(self): db.session.delete(self) db.session.commit() ''' update() updates a new model into a database the model must exist in the database EXAMPLE movie = Movie.query.filter(Movie.id == id).one_or_none() movie.title = 'Black Coffee' movie.update() ''' def update(self): db.session.commit() def __repr__(self): return json.dumps(self.short()) class Actors(db.Model): __tablename__ = 'Actors' # Autoincrementing, unique primary key id = db.Column(db.Integer, primary_key=True) # String Name name = Column(String(120), unique=True) age = Column(db.Integer) gender = Column(String(120), nullable=False) movies = db.relationship('Movies', backref='Actors', lazy=True) ''' insert() inserts a new model into a database the model must have a unique name the model must have a unique id or null id EXAMPLE movie = Movie(title=req_title, recipe=req_recipe) movie.insert() ''' def insert(self): db.session.add(self) db.session.commit() ''' delete() deletes a new model into a database the model must exist in the database EXAMPLE movie = Movie(title=req_title, recipe=req_recipe) movie.delete() ''' def delete(self): db.session.delete(self) db.session.commit() ''' update() updates a new model into a database the model must exist in the database EXAMPLE movie = Movie.query.filter(Movie.id == id).one_or_none() movie.title = 'Black Coffee' movie.update() ''' def update(self): db.session.commit() def __repr__(self): return json.dumps(self.short())
8be8e2bb46caf8a70c82b41172390c7403733085
RajatVermaz/pytho
/madlibs.py
293
3.578125
4
# Madlibs game based on string concatination adj1 = input('Adjective : ') adj2 = input('Adjective : ') verb1 = input('Verb : ') verb2 = input('Verb : ') print(f'Computer programming is so {adj1} it makes me {verb1}, and some day it will be {adj2} and \ computer will {verb2}.')
5d702c3b01d662249f704099ee85a8cc703d1c02
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/NumericalIntegration/python/program1.py
1,001
3.71875
4
# -*- coding: utf-8 -*- #Example of numerical integration with Gauss-Legendre quadrature #Translated to Python by Kyrre Ness Sjøbæk import sys import numpy from computationalLib import pylib #Read input if len(sys.argv) == 1: print "Number of integration points:" n = int(sys.stdin.readline()) print "Integration limits (a, b)" (a,b) = sys.stdin.readline().split(",") a = int(a) b = int(b) elif len(sys.argv) == 4: n = int(sys.argv[1]) a = int(sys.argv[2]) b = int(sys.argv[3]) else: print "Usage: python", sys.argv[0], "N a b" sys.exit(0) #Definitions m = pylib(inputcheck=False,cpp=False) def integrand(x): return 4./(1. + x*x) #Integrate with Gaus-legendre! (x,w) = m.gausLegendre(a,b,n) int_gaus = numpy.sum(w*integrand(x)) #Final output print "integration of f(x) 4/(1+x**2) from",a,"to",b,"with",n,"meshpoints:" print "Gaus-legendre:", int_gaus print "Trapezoidal: ", m.trapezoidal(a,b,n, integrand) print "Simpson: ", m.simpson(a,b,n,integrand)
1fbcf671cd4884007549a8e1c08685329c616e30
CompPhysics/ComputationalPhysics
/doc/Programs/PythonAnimations/animate2.py
876
3.5
4
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def data_gen(t=0): cnt = 0 while cnt < 1000: cnt += 1 t += 0.1 yield t, np.sin(2*np.pi*t) * np.exp(-t/10.) def init(): ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, 10) del xdata[:] del ydata[:] line.set_data(xdata, ydata) return line, fig, ax = plt.subplots() line, = ax.plot([], [], lw=2) ax.grid() xdata, ydata = [], [] def run(data): # update the data t, y = data xdata.append(t) ydata.append(y) xmin, xmax = ax.get_xlim() if t >= xmax: ax.set_xlim(xmin, 2*xmax) ax.figure.canvas.draw() line.set_data(xdata, ydata) return line, ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10, repeat=False, init_func=init) plt.show()
df00204272fad9115ea527d137cb7a06df1f16cd
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/PDE/python/2dwave/pythonmovie.py
2,018
3.5
4
#!/usr/bin/env python # This script reads in data from file with the solutions of the # 2dim wave function. The data are organized as # time # l, i, j, u(i,j) where k is the time index t_l, i refers to x_i and j to y_j # At the end it converts a series of png files to a movie # file movie.gif. You can run this movie file using the ImageMagick # software animate as - animate movie.gif et voila', Hollywood next # It creates a movie of the time evolution with the scitools.easyviz library. # To fetch this addition to python go to the link # http://code.google.com/p/scitools/wiki/Installation # This additional tool is the same as that used in INF1100 and should # be installed on most machines. from numpy import * from scitools.easyviz import * import sys, os try: inputfilename = sys.argv[1] except: print "Usage of this script", sys.argv[0], "inputfile"; sys.exit(1) # Read file with data ifile = open(inputfilename) lines = ifile.readlines() ifile.close() # Fixed Lengths used in other function to set up the grids. start = lines[0].split() stop = lines[-1].split() Lx = int(start[1]) + 1; nx = int(stop[1]) + 1 Ly = int(start[2]) + 1; ny = int(stop[2]) + 1 ntime = int(stop[0]) x, y = ndgrid(linspace(0, Lx, nx), linspace(0, Ly, ny), sparse=False) ifile = open(inputfilename) plotnr = 0 u = zeros([nx, ny]) # Loop over time steps for l_ind in xrange(1, ntime + 1): for i_ind in range(0, nx): for j_ind in range(0, ny): elements = [] while len(elements) < 4: elements = ifile.readline().split() l, i, j, value = elements if l_ind != int(l): raise IndexError, 'l_ind=%d, l=%d -> l_ind != l' %(l_ind, int(l)) u[int(i), int(j)] = float(value) plotnr += 1 mesh(x, y, u, hardcopy='frame%04d.png' %plotnr, show=False, axis=[0, 1, 0, 1,- 1, 1]) # Make movie movie('frame*.png', encoder='convert', output_file='movie.gif', fps=10) cmd = 'animate movie.gif' os.system(cmd)
54fa124eaace5d831d897f932615c57182404218
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/MCIntro/python/program1.py
628
3.90625
4
# coding=utf-8 #Example of brute force Monte Carlo integration #Translated to Python by Kyrre Ness Sjøbæk import math, numpy, sys def func(x): """Integrand""" return 4/(1.0+x*x) #Read in number of samples if len(sys.argv) == 2: N = int(sys.argv[1]) else: print "Usage:",sys.argv[0],"N" sys.exit(0) #Evaluate the integral using a crude MonteCarlo mc_sum = 0.0 mc_sum2 = 0.0 for i in xrange(N): fx=func(numpy.random.random()) mc_sum += fx mc_sum2 += fx*fx #Fix the statistics mc_sum /= float(N) mc_sum2 /= float(N) variance = mc_sum2 - mc_sum**2 print "Integral=",mc_sum,", variance=",variance
23b5fb07ddbe64e1434cb1bfcfdb35d883dc3a6f
raymag/forca
/mag-forca.py
6,486
4.34375
4
#Sendo o objetivo do programa simular um jogo da forca, #Primeiramente importamos a biblioteca Random, nativa do python #Assim podemos trabalhar com números e escolhas aleatórias import random #Aqui, declaramos algumas váriaveis fundamentais para o nosso código #Lista de palavras iniciais (Default) palavras = ['abacate','chocolate','paralelepipedo','goiaba'] #Nossos erros e acertos, ainda vazios letrasErradas = '' letrasCertas = '' #E aqui declaramos uma lista que porta os 'estados de forca' do programa FORCAIMG = [''' +---+ | |0 | | | | =========''',''' +---+ | | O | | | | =========''',''' +---+ | | O | | | | | =========''',''' +---+ | | O | /| | | | =========''',''' +---+ | | O | /|\ | | | =========''',''' +---+ | | O | /|\ | / | | =========''',''' +---+ | | O | /|\ | / \ | | ========='''] #Aqui definimos uma função que irá nos pedir palavras e adicionalas à nossa lista anterior. def Insert(): print(''' Insira palavras... Quando desejar parar, por favor, tecle enter sem digitar nenhum caractere.''') while True: q = input('Informe: ') #Caso o usuário não digite nenhum caractere e pressionar o enter, a função prosseguirá com o código if q == '': break palavras.append(q) q = 'Palavra adicionada com sucesso' #Aqui definimos a função principal do programa, ela é o cerne de nosso código def principal(): """ Função Princial do programa """ print('F O R C A') #Invocamos à nossa função insert aqui, e esta irá nos requisitar palavras Insert() #A variável palavraSecreta carregará a função sortearPalavra palavraSecreta = sortearPalavra() #Aqui definimos a variável palpite à qual nos será útil em breve palpite = '' #Invocamos a função desenhaJogo passando as nossas variáveis como parâmetros desenhaJogo(palavraSecreta,palpite) #Aqui criamos um loop que irá verificar se o usuário perdeu ou ganhou o jogo while True: # A variável palpite irá receber o resultado da função receberPalpite(), esta irá nos permitir tentar um palpite palpite = receberPalpite() # Aqui invocamos a função desenhaJogo, passando com parâmetros a palavraSecreta e o palpite, esta irá coordenar toda a parte gráfica do programa desenhaJogo(palavraSecreta,palpite) #Aqui verificamos se o jogador ganhou o perdeu o jogo, em ambos os casos, o nosso loop será quebrado if perdeuJogo(): print('Voce Perdeu!!!') break if ganhouJogo(palavraSecreta): print('Voce Ganhou!!!') break #Esta função irá informar se o jogador perdeu ou não o jogo; Usando valores booleanos no processo def perdeuJogo(): global FORCAIMG #Usando o comando global, ligamos a variável FORCAIMG local com as anteriores if len(letrasErradas) == len(FORCAIMG): #Verifica se o número de letras erradas é igual a quantidade de elementos da lista FORCAIMG, caso sim, retorna o valor booleano True return True else: #Caso a afirmação anterior seja falsa, o valor retornado também será Falso return False def ganhouJogo(palavraSecreta): #Esta função confere se o jogador ganhou o jogo global letrasCertas #Primeiramente ele liga a variável letrasCertas ganhou = True #Declara a variável ganhou com o valor True #Se cada letra na PalavraSecreta estiver dentro da lista letrasCertas, o ganhou continuará como Verdadeiro, caso contrário, tornará-se Falso for letra in palavraSecreta: if letra not in letrasCertas: ganhou = False return ganhou def receberPalpite(): #Esta função permite o jogador a fazer palpites das letras corretas palpite = input("Adivinhe uma letra: ") #primeiro o programa faz a requisição de uma informação ao usuário palpite = palpite.upper() #E este, torna todas as letras da informação maiúsculas if len(palpite) != 1: #Caso o jogador informe mais de um caractere por vez, o programa irá imprimir a seguinte frase print('Coloque um unica letra.') elif palpite in letrasCertas or palpite in letrasErradas: #E caso, o palpite esteja dentro de letrasCertas ou de letrasErradas, o programa #Informará que o jogador já disse esta letra print('Voce ja disse esta letra.') elif not "A" <= palpite <= "Z": #Caso o jogador informe algo além de letras, o programa irá requisitar apenas letras print('Por favor escolha apenas letras') else: #Caso, todas as afirmações e condições anteriores sejam falsas, a função irá retornar a variável palpite return palpite def desenhaJogo(palavraSecreta,palpite): #Como já informado, esta função coordena a parte gráfica do jogo #Inicialmente fazemos referências à variáveis já decladas global letrasCertas global letrasErradas global FORCAIMG print(FORCAIMG[len(letrasErradas)]) #E aqui imprimos o elemento de FORCAIMG que é equivalente ao número de letras erradas até o momento vazio = len(palavraSecreta)*'-' #Esta string terá o mesmo número de caracteres que a palavra secreta, sendo formada apenas por '_' if palpite in palavraSecreta: #Caso o palpite esteja dentro da palavraSecreta, isto irá adicionar o palpite dentro de letrasCertas letrasCertas += palpite else: #Caso contrário, irá adicionar o palpite às letrasErradas letrasErradas += palpite #Este bloco irá trocar os espaços vazios (__) pelas letras acertadas for letra in letrasCertas: for x in range(len(palavraSecreta)): if letra == palavraSecreta[x]: vazio = vazio[:x] + letra + vazio[x+1:] #Este bloco irá imprimir as letras acertadas e erradas para o jogador, como também a variável vazio print('Acertos: ',letrasCertas ) print('Erros: ',letrasErradas) print(vazio) def sortearPalavra(): #Esta é a função que escolhe uma palavra aleatória da lista de palavras e as torna maiúsculas global palavras return random.choice(palavras).upper() principal() #Aqui invocamos a nossa função principal, pode-se dizer que é o comando inicial de todo o nosso código
e9158dd3a5cd39959a07f8244e3268da819d253e
dustylee621/PythonBootCamp
/inheritance.py
523
3.78125
4
class Animal: def __init__(self, name, species): self.name = name self.species = species def __repr__(self): return f"{self.name} is a {self.genus}" def make_noise(self, sound): print(f"this animal says {sound}") class Snake(Animal): def __init__(self, name, genus, toy): super().__init__(name, species = "snake") self.genus = genus self.toy = toy def play(self): print(f"{self.name} eats the {self.toy}") chewy = Snake("chewy", "Ball Python", "rat") print(chewy) chewy.play()
58473b9b8f3bef88617060c78c084b85be492631
irfan-ansari-au28/Python-Pre
/Lectures/lecture9/dictinary.py
527
4.03125
4
""" dict = { "BJP":32, "Congress": 12, "AAP": 29 } print(dict) print (dict.items()) print(dict.keys()) print(dict.values()) """ parties = ["BJP", "AAP", "Congress", "BJP","AAP", "BJP", "BJP"] party_dict = {} for party in parties: if party in party_dict: party_dict[party] += 1 else: party_dict[party] = 1 print(party_dict) votes = 0 winner_party = "" for party, vote in party_dict.items(): if vote > votes: votes = vote winner_party =party print(winner_party)
5a6b0d985d1dcbaffc0702939d0fe91aeba778af
irfan-ansari-au28/Python-Pre
/Lectures/lecture8/tuples.py
179
3.859375
4
""" tuple is immutable that means it can't be change once create list can be typecast into tuple type >>> A = list() >>> B = tuple(A) to reverse an array >>> Array[::-1] """
5688123f5e2c4791f8f177a6642df1088138b35f
irfan-ansari-au28/Python-Pre
/Interview/RandomQuestions/binary_search.py
419
3.84375
4
# for binary search array must be sorted A = [1,7,23,44,53,63,67,72,87,91,99] def binary_search(A,target): low = 0 high = len(A) - 1 while low <= high: mid = (low + high) // 2 if target < A[mid]: high = mid - 1 elif target > A[mid]: low = mid + 1 else: return mid # print(low,high) return -1 print(binary_search(A,1))
594fee53a4e627a3897888522fb425d365b94d56
irfan-ansari-au28/Python-Pre
/hands_on_python/1.Intro/dictionary.py
773
4.0625
4
""" >>> sorted() -- Does not change the original ordering but gives a new copy """ vowel =['a', 'e', 'i','o' ,'u'] # word = input("provide a word to search for vowels:") word = "Missippi" found = [] for letter in word: if letter in vowel: if letter not in found: found.append(letter) for vowel in found: print(vowel) my_dict = {"name" : "john", "birth_year" : 1997, "age": 2037 - 1997} print(my_dict) for kv in my_dict: print(kv) for key in my_dict.keys(): print(key) for value in my_dict.values(): print(value) for kv in my_dict.items(): print(kv) for value in my_dict: print("value is :", my_dict[value]) for k, v in my_dict.items(): print("key",k , "value", v)
2b9c010fcbc0c77d42919128b13fe285a4fa94e2
irfan-ansari-au28/Python-Pre
/Interview/RandomQuestions/matrix_prob.py
1,105
3.796875
4
""" # A = [ # ['#', '#', '#'], # ['#', '', '#'], # ['#', '#', '#'], # ] for 3 X 3 gap = 1 idx =[ (1,)] for 4 X 4 gap = 2**2 idx = [(1,1),(1,2),(2,1),(2,2)] for 5 X 5 gap = 3**3 idx = [((1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3))] """ ip= int(input('Enter row or column of a square matrix greater than 3 : ')) A = [[0 for i in range(ip)] for j in range(ip)] # print(A) rows = len(A) cols = len(A[0]) list_of_non_border_ele = [] def findIdxOfGap(rows,cols): for row in range(1, rows-1): for col in range(1, cols-1): # print(row,col) list_of_non_border_ele.append((row,col)) findIdxOfGap(rows,cols) # print(list_of_non_border_ele) def printBorderElements(rows,cols): for row in range(rows): for col in range(cols): if (row,col) in list_of_non_border_ele: A[row][col] = ' ' print(A[row][col], end=' ') else: A[row][col] = '#' print(A[row][col], end=' ') print() printBorderElements(rows,cols) # print(A)
02b826027ec3d85ddc982ee11df3966527eb041f
irfan-ansari-au28/Python-Pre
/Doubt/week08_day01.py
311
3.84375
4
#Q-1) Next Greater Element #Answer:- def find_next_ele(A): for i in range(len(A)): next_ele = -1 for j in range(i+1,len(A)): if A[j]>A[i]: next_ele = A[j] break print(next_ele,end =" ") if __name__ == "__main__": A= [2,6,4,7,8,3,5,9] # 0 1 2 3 4 5 6 7 8 find_next_ele(A) # t(n) : O(n**2)
fb745ae55b2759660a882d00b345ae0db70e60d2
irfan-ansari-au28/Python-Pre
/Interview/DI _ALGO_CONCEPT/stack.py
542
4.28125
4
""" It's a list when it's follow stacks convention it becomes a stack. """ stack = list() #stack = bottom[8,5,6,3,9]top def isEmpty(): return len(stack) == 0 def peek(): if isEmpty(): return None return stack[-1] def push(x): return stack.append(x) def pop(): if isEmpty(): return None else: return stack.pop() if __name__ == '__main__': push(8) push(5) push(6) push(3) push(9) print(isEmpty()) print(peek()) x = pop() print(x,'pop') print(stack)
bcca7baa2d01e320b8a0c2257cbb1c9b2a0db405
irfan-ansari-au28/Python-Pre
/ClassPractice/W4D3/main.py
324
3.796875
4
from student import Student if __name__ == '__main__': name = input('Enter the name of the student') age = int(input('Enter the age of the student')) birth = int(input('Enter the birth date of the student')) pradeep = Student(name,age,birth) print(pradeep.name) print(pradeep.age) pradeep.read()
4cebce3d1fd394fb85db8ad4bee95f51b1e50dda
irfan-ansari-au28/Python-Pre
/Lectures/lecture4/nested_loop.py
96
3.546875
4
for i in range(3): for j in range(3): for k in range(3): print(i,j,k)
d74a82478b26a11505f547aefe6dcdea9efebce0
TSG405/Simple-Games
/main/Rock Paper Scissor/rock_paper_scissor_2_players.py
1,568
3.84375
4
s1=0 s2=0 # LOGICAL FUNCTION def winner(p1, p2): global s1 global s2 if (p1 == p2): s1+=1 s2+=1 return "It's a tie!" elif (p1 == 'r'): if (p2 == 's)': s1+=1 return "First Player wins!" else: s2+=1 return "Second Player wins!" elif (p1 == 's'): if (p2 == 'p'): s1+=1 return "First Player wins!" else: s2+=1 return"Second Player wins!" elif (p1 == 'p'): if (p2 == 'r'): s1+=1 return "First Player wins!" else: s2+=1 return "Second Player wins!" else: return "Invalid Input!" print(" --- ** --- !WELCOME TO THE R.P.S GAME! --- ** --- ") try: c=int(input("\nHow many rounds will you like to play? Enter that number:")) except: print("INVALID INPUT! Try again, next time!") exit() if c<=0: print("Negative number not allowed! Redirecting to 1 round only!") c=1 # DRIVER CODE... while(c>0): print("\nRounds left -->",c) player1 = input("\nFirst player: rock [enter 'r'], paper [enter 'p'] or scissors [enter 's']: ").lower() player2 = input("Second Player: rock [enter 'r'], paper [enter 'p'] or scissors [enter 's']: ").lower() print(winner(player1, player2)) c-=1 # RESULTS if s1>s2: print("\nUltimate Winner ---> First Player") elif s1<s2: print("\nUltimate Winner ---> Second Player") else: print("\nTie GAME!") @ CODED BY TSG405, 2020
c6d3d321cbe9cc790a109506c8b80f9d11397462
mattblk/Study
/Python/level1/level1_이상한문자만들기.py
397
3.578125
4
def solution(s): _list = s.split(" ") answer = '' def sub(string): k=0 sub_ans='' for i in string: if i==' ' : sub_ans+=' ' elif k%2 == 0 : sub_ans+=i.upper() else : sub_ans+=i.lower() k=k+1 return sub_ans for i in _list : answer+=sub(i)+" " return answer[:-1] #score 12
e6ae535a8661e08d94cbb21e812a1f2580f29f09
mattblk/Study
/Python/level2/level2_가장큰수.py
929
3.59375
4
# a=[1,3,4,56,4,2,23,12,89,9,888,999,331,1000] a=[3, 30, 34, 5, 9] def solution(arr): def str_arr(arr): str_arr="" for i in range(0, len(arr)): str_arr= str_arr + str(arr[i]) return str_arr def quick_sort(arr): if len(arr) <= 1: return arr pivot=arr[len(arr)//2] lesser_arr, equal_arr, greater_arr = [],[],[] for num in arr: if int(str(num)+str(pivot)) > int(str(pivot)+str(num)) : lesser_arr.append(num) elif int(str(num)+str(pivot)) < int(str(pivot)+str(num)) : greater_arr.append(num) else : equal_arr.append(num) return quick_sort(lesser_arr) + equal_arr + quick_sort(greater_arr) if str_arr(quick_sort(arr))[0] == 0 : return "0" else: return str_arr(quick_sort(arr)) print(solution(a))
785495eea588f1ac26f5bb49457648c072e3346b
mattblk/Study
/Python/level1/level1_두개뽑아서더하기.py
545
3.765625
4
numbers = [0,0] def solution(numbers): # 두개의 수 합 array arr_sum=[] # 두개의 수 합을 구하는 함수 추가 def add_sum(nums): # 배열 backward num_foward = nums[0] arr_backward=nums[1:len(nums)] for i in arr_backward : arr_sum.append(num_foward + i) if len(arr_backward) >= 2 : add_sum(arr_backward) add_sum(numbers) answer = list(set(arr_sum)) answer.sort() return answer print(solution(numbers))
672038829fa89be5aeb711cff4d9b26289028f5c
Vanderson10/Codigos-Python-UFCG
/mtp4/FuncionarioMes/funcionariomes.py
842
3.890625
4
#Receber a quantidade de chinelos produzidos por cada funcionario nos vários turnos dele. #Saida: descobrir quem vendeu mais chinelos. #obs:. não haberá empates #1)receber cada usuario e realizar a soma do quanto eles venderam #2)colocar cada soma numa lista #3)colocar o nome numas lista #4) analisar quem vendeu mais na lista nomes = [] soma = 0 somas = [] while True: nome = input() if nome=="fim":break else:nomes.append(nome) while True: n = input() if n=="-": break else: soma+=int(n) somas.append(soma) soma = 0 #analisar qual soma é maior i = 1 maior = somas[0] nom = nomes[0] while i<len(somas): if maior>=somas[i]: maior = maior nom = nom else: maior = somas[i] nom = nomes[i] i+=1 print(f'Funcionário do mês: {nom}')
88ea10bba74dc895a0cddb587de8f81f808e19ea
Vanderson10/Codigos-Python-UFCG
/4simulado/ar.py
155
3.671875
4
x = int(input()) y = int(input()) if x>y: print("---") exit() menos = y-x for i in range(0,menos+1): atu = x+i print(f'{atu} {atu*atu}')
8259b3a8301dac20fd5cf5d83f0a1dbb93aa0fda
Vanderson10/Codigos-Python-UFCG
/uni4/melhordesempenho/melhordesempenho.py
568
3.5625
4
#calcular qual aluno teve mais "." no miniteste #se tiver empate coloca o primeiro #se n acertar nenhuma questão é pra imprimir -1 quant = int(input()) #encontrar qual teve mais "." maior = 0 lista = [] for i in range(quant): exercicio = input() soma = 0 for t in range(0,len(exercicio)): if exercicio[t] == ".": soma +=1 lista.append(soma) if maior<soma: maior = soma if maior == 0: print(-1) exit() for v in range(0,len(lista)): if lista[v]==maior: print(v+1) break
7fedccbfa707a0a01b76ab3b65d91683abb1967e
Vanderson10/Codigos-Python-UFCG
/uni3/natalina/natalina.py
1,699
3.703125
4
#gratificação de natal #dados: 235 dias, G = (235 - número de dias que faltou) * valor-da-gratificação-por-dia-trabalhado #caso ele não tenha faltado nenhum dia tem a gratificação também #entrada: codigo do cargo, dias que faltou cod = int(input()) #caso1 if cod == 1: print('Deverá receber em dezembro R$ 25000.00.') elif cod ==2: print('Deverá receber em dezembro R$ 15000.00.') elif cod ==3: diasfaltou = int(input()) gratificacao = (235-diasfaltou)*2 if diasfaltou ==0: gt = 500 sala = 8000+gt print(f"Valor da gratificação R$ {gt:.2f}.") print(f"Deverá receber em dezembro R$ {sala:.2f}.") else: sala = 8000+gratificacao print(f"Valor da gratificação R$ {gratificacao:.2f}.") print(f"Deverá receber em dezembro R$ {sala:.2f}.") elif cod ==4: diasfaltou = int(input()) gratificacao = (235-diasfaltou)*1 if diasfaltou ==0: gt = 300 sala = 5000+gt print(f"Valor da gratificação R$ {gt:.2f}.") print(f"Deverá receber em dezembro R$ {sala:.2f}.") else: sala = 5000+gratificacao print(f"Valor da gratificação R$ {gratificacao:.2f}.") print(f"Deverá receber em dezembro R$ {sala:.2f}.") elif cod ==5: diasfaltou = int(input()) gratificacao = (235-diasfaltou)*0.7 if diasfaltou ==0: gt = 200 sala = 2800+gt print(f"Valor da gratificação R$ {gt:.2f}.") print(f"Deverá receber em dezembro R$ {sala:.2f}.") else: sala = 2800+gratificacao print(f"Valor da gratificação R$ {gratificacao:.2f}.") print(f"Deverá receber em dezembro R$ {sala:.2f}.")
511b43f80a63e424aa9403ac3a9d21529eca3082
Vanderson10/Codigos-Python-UFCG
/4simulado/tabelaquadrados/Chavesegura/chavesegura.py
1,009
4.125
4
#analisar se a chave é segura #se não tiver mais que cinco vogais na chave #não tem tre caracteres consecultivos iguais #quando detectar que a chave não é segura é para o programa parar e avisar ao usuario #criar um while e analisar se tem tres letras igual em sequencia #analisar se tem mais que cinco vogais, analisar com uma lista cada letra. #entrada chave = input() pri = chave[0] seg = chave[1] i = 2 soma = 0 vogais = ['A','E','I','O','U','a','e','i','o','u'] e = 0 while True: if pri == seg and pri == chave[i]: print("Chave insegura. 3 caracteres consecutivos iguais.") break else: pri = seg seg = chave[i] i=i+1 for v in vogais: if v==chave[e]: soma = soma+1 break e=e+1 if soma>5: print("Chave insegura. 6 vogais.") break if i==len(chave): print("Chave segura!") break if e>len(chave): print("Chave segura!")
c1f33cd31e1dd2237b7b4ad92268858864ed9f7f
Vanderson10/Codigos-Python-UFCG
/uni4/SOMAIMPARES/somai.py
798
3.734375
4
#recebe uma sequencia e calcula a soma dos ultimos impares até atingir o valor limite #obs. o valor limite não entra na soma #ex. 3,1,6,4,7 com limite 9, soma = 8 (1+7) obs. de tras pra frente #1-entrada: quantos itens, limite, nuns da sequencia quant = int(input()) limite = int(input()) #nuns dentro do for #colocar os elementos dentro de uma lista lista = [] for i in range(0,quant): n = int(input()) lista.append(n) #criar um for e colocar a lista de tras pra frente pra facilitar listai = [] for i in range(0,quant): listai.append(lista[(quant-1)-i]) #somar os elementos impares até chegar no valor limite (<=) soma = 0 for n in listai: if n%2!=0: soma=soma+n if soma>=limite: soma= soma-n break #imprimir a soma print(soma)
5e91680b3e38d6d2798d93a6c327cf64c5b8af8f
FloVnst/Python-Challenge-2020
/solutions/road_trip.py
2,499
3.796875
4
# Processing def road_trip(distance, speed, departure): durationMinutes = int((distance / speed) * 60) durationHours = durationMinutes // 60 durationMinutes -= durationHours * 60 # Generate the text for the departure time if departure[1] < 10: departureResult = "Départ à {}h0{}".format(departure[0], departure[1]) else: departureResult = "Départ à {}h{}".format(departure[0], departure[1]) # Generate the text for the duration of the travel durationResult = "Trajet de " if durationHours > 0: durationResult += "{} heure".format(durationHours) if durationHours > 1: durationResult += 's' durationResult += " et " durationResult += "{} minute".format(durationMinutes) if durationMinutes != 1: durationResult += 's' arrival = [0, 0] # [hours, minutes] arrival[1] = (departure[1] + durationMinutes) % 60 arrival[0] = (departure[0] + durationHours + (departure[1] + durationMinutes) // 60) % 24 # Generate the text for the arrival time if arrival[1] < 10: arrivalResult = "Arrivée prévue à {}h0{}".format(arrival[0], arrival[1]) else: arrivalResult = "Arrivée prévue à {}h{}".format(arrival[0], arrival[1]) return departureResult + '\n' + durationResult + '\n' + arrivalResult # Unit Tests API Input # print(road_trip(lines[0], lines[1], lines[2])) # Tests print(road_trip(45, 95, [7, 10])) # Must return "Départ à 7h10\nTrajet de 28 minutes\nArrivée prévue à 7h38" print(road_trip(600, 115, [23, 10])) # Must return "Départ à 23h10\nTrajet de 5 heures et 13 minutes\nArrivée prévue à 4h23" print(road_trip(200, 75, [23, 55])) # Must return "Départ à 23h55\nTrajet de 2 heures et 40 minutes\nArrivée prévue à 2h35" print(road_trip(15, 45, [15, 3])) # Must return "Départ à 15h03\nTrajet de 20 minutes\nArrivée prévue à 15h23" print(road_trip(0.1, 6, [15, 3])) # Must return "Départ à 15h03\nTrajet de 1 minute\nArrivée prévue à 15h04" print(road_trip(1, 0.97, [15, 3])) # Must return "Départ à 15h03\nTrajet de 1 heure et 1 minute\nArrivée prévue à 16h04" print(road_trip(1, 0.99, [15, 3])) # Must return "Départ à 15h03\nTrajet de 1 heure et 0 minutes\nArrivée prévue à 16h03" print(road_trip(143, 140, [18, 30])) # Must return "Départ à 18h30\nTrajet de 1 heure et 1 minute\nArrivée prévue à 19h31"
d43a0da77a1fa9164087b0a4dbc9b3be38c33d82
venkataniharbillakurthi/python-lab
/ex-2.py
263
4.0625
4
a=int(input('Enter the number:')) b=int(input('Enter the number:')) c=int(input('Enter the number:')) sum=a+b+c average=(a+b+c)/3 print('sum = ',sum,'\naverage = ',average) Enter the number:23 Enter the number:45 Enter the number:67 sum = 135 average = 45.0
b0f286afb0b68bc79aa25c4808abf5ad406cd582
KAPILSGNR/KapilSgnrMath
/KapilSgnrMath/MyRectangle.py
239
3.625
4
class Rectangle: def __init__(self,length, width): self.length=length self.width=width def getArea(self): area= self.length*self.width print("Area of the Rectangle is: ", area) return area
6a34496d114bc6e67187e4bc12c8ff874d575de0
BrightAdeGodson/submissions
/CS1101/bool.py
1,767
4.28125
4
#!/usr/bin/python3 ''' Simple compare script ''' def validate(number: str) -> bool: '''Validate entered number string is valid number''' if number == '': print('Error: number is empty') return False try: int(number) except ValueError as exp: print('Error: ', exp) return False return True def read_number(prefix: str) -> int: '''Read number from the prompt''' while True: prompt = 'Enter ' + prefix + ' > ' resp = input(prompt) if not validate(resp): continue number = int(resp) break return number def compare(a, b: int) -> (str, int): ''' Compare two numbers It returns 1 if a > b, returns 0 if a == b, returns -1 if a < b, returns 255 if unknown error ''' if a > b: return '>', 1 elif a == b: return '==', 0 elif a < b: return '<', -1 return 'Unknown error', 255 def introduction(): '''Display introduction with example''' _, example1 = compare(5, 2) _, example2 = compare(2, 5) _, example3 = compare(3, 3) print(''' Please input two numbers. They will be compared and return a number. Example: a > b is {} a < b is {} a == b is {} '''.format(example1, example2, example3)) def main(): '''Read numbers from user input, then compare them, and return result''' introduction() first = read_number('a') second = read_number('b') result_str, result_int = compare(first, second) if result_int == 255: print(result_str) return print('Result: {} {} {} is {}'.format(first, result_str, second, result_int)) if __name__ == "__main__": main()
0b3c1743acf1b4f3ad68757fe8699ee10fc8f67e
abhi-accubits/caffinated
/src/filegen.py
676
3.671875
4
import os """ File Generator Author Danwand NS github.com/DanBrown47 verify if the buffer file is present, if not generates one as temp storage of the file """ class FileGen: """ Checks if the file is present if not generate """ def __init__(self, path) -> None: self.path = path pass def generate(self) -> None: os.mkdir("godown") os.chdir("godown") f = open("buff.txt","x") def isFile(self) -> None: presence = os.path.isfile(self.path) if not presence: FileGen.generate(self) else: # Can Add banner here print("File Exists") pass
009b1d64116333f801b6b7947d336be76686f082
BowieSmith/project_euler
/python/p_001.py
133
4.0625
4
# Find the sum of all the multiples of 3 or 5 below 1000. ans = sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0) print(ans)
49b854f0322357dd2ff9f588fc8fb9c6f62fd360
BowieSmith/project_euler
/python/p_004.py
352
4.125
4
# Find the largest palindrome made from the product of two 3-digit numbers. def is_palindrome(n): s = str(n) for i in range(len(s) // 2): if s[i] != s[-i - 1]: return False return True if __name__ == "__main__": ans = max(a*b for a in range(100,1000) for b in range(100,1000) if is_palindrome(a*b)) print(ans)
81c2f882685c1222115f2700ae39aeb77da3749a
BowieSmith/project_euler
/python/p_019.py
1,550
4.03125
4
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? # Assume 1 Jan 1900 was a Monday def is_leap_year(n): if n % 4 != 0: # leap years on years divisible by 4 return False if n % 400 == 0: # also on years divisible by 400 return True if n % 100 == 0: # but not other centuries return False return True # 1 2 3 4 5 6 7 8 9 10 11 12 days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 0 1 2 3 4 5 6 weekdays = ["sun", "mon", "tues", "wed", "thurs", "fri", "sat"] def cal_gen(y, m, d, wkdy): year = y month = m day = d wkday = wkdy while True: yield (year, month, day, wkday) if ((day < 31 and month in (1, 3, 5, 7, 8, 10, 12)) or (day < 30 and month in (4, 6, 9, 11)) or (day < 28 and month == 2) or (day < 29 and month == 2 and is_leap_year(year))): day += 1 elif month < 12: month += 1 day = 1 else: year += 1 month = 1 day = 1 wkday = (wkday + 1) % 7 if __name__ == "__main__": first_of_month_sunday = 0 cal = cal_gen(1900, 1, 1, 1) date = next(cal) while date[0] < 2001: if (date[0] > 1900 and date[2] == 1 and date[3] == 0): first_of_month_sunday += 1 date = next(cal) print(first_of_month_sunday)
48d4eaad07fc9dcfa1f4c8b4a1f364bc02bbbd7f
Dron2200/My-first-steps-in-Python
/HW3_4.py
554
4.0625
4
print("This program is more interesting that previous", '\n', "So, using this program you can resolve following formula", '\n', "ax^2 + bx + c = 0 ") a = float(input("Please, write a :")) b = float(input("Please, write b :")) c = float(input("Please, write c :")) d = (b**2 - 4*a*c) x = -(b/2*a) x1 = None x2 = None if d < 0: print("you have no results D<0") elif d == 0: print("You have one result x =", x) elif d > 0: x1 = (-b + d ** 0.5) / 2 * a x2 = (-b - d ** 0.5) / 2 * a print("x1=", x1, "x2=", x2)
1def7f563fa6c611e1806b07e94c84e8af0cbb0d
Dron2200/My-first-steps-in-Python
/lesson2_3.py
362
4.03125
4
print("Homework-2 Task-3") print("This program is more interesting that previous", '\n', "So, using this program you can resolve following formula", '\n', "ax^2 + bx + c = 0 ") a = float(input("Please, write a :")) b = float(input("Please, write b :")) c = float(input("Please, write c :")) x = (-b + (b**2 - 4*a*c)**0.5) / (2*a) print(x)
ccb6c8bd7bd657668691cad6c3fa7c5bd699c766
tameravci/FeedForwardNNet
/AvciNeuralNet.py
7,606
4.09375
4
# coding: utf-8 # # Simple feedforward neural network with Stochastic Gradient Descent learning algorithm # # Tamer Avci, June 2016 # # Motivation: To get better insights into Neural nets by implementing them only using NumPy. # Task: To classify MNIST handwritten digits: http://yann.lecun.com/exdb/mnist/ # # Accuracy:~95% # # Deficiencies: # No optimization of the code # No cross-validation split. # # 1) Define a network class. Instance variables will be: # -num of layers e.g. [2,3,1] # -size of our network [2, 3, 1] = 3 # -bias vectors # -weight matrices # # 2) Write the instance methods: # -feedforward: used to pass the input forward once and evaluate # -train: take batches of the data and call SGD to minimize the cost function # -SGD: for every single input in the batch, call backprop to find the derivatives with respect to # weights and bias, and then update those in the descent direction # -backprop: find the derivatives using chain rule (watch the video for more help) # -evaluate: run feedforward after training and compare it against target value # -cost_derivative: as simple as (y(target) - x(input)) # -sigmoid: sigmoid function (1 / 1 - exp(-z)) # -sigmoid delta: derivative of the sigmoid function # In[ ]: #import dependencies import random import numpy as np # In[46]: class Network(object): def __init__(self, layer): # layer: input layer array # Example usage >>> net = Network([2,3,1]) # For instance [2,3,1] would imply 2 input neurons, 3 hidden neurons and 1 output neuron self.num_layers = len(layer) self.sizes = layer # Create random bias vectors for respective layers using uniform distribution self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]] # Create weight matrices for respective layers, note the swap x,y self.weights = [np.random.randn(y, x) for x, y in zip(self.sizes[:-1], self.sizes[1:])] def feedforward(self, a): """ For each layer take the bias and the weight, and apply sigmoid function Return the output of the network if "a" is input. Used after training when evaluating""" for b, w in zip(self.biases, self.weights): #One complete forward pass a = sigmoid(np.dot(w, a)+b) return a def train(self, training_data, epochs, mini_batch_size, eta, test_data=test_data): """ Train the neural network taking batches from the data hence stochastic SGD """ #provide training data, number of epochs to train, batch size, the learning rate and the test_data #learning rate: how fast do you want the SGD to proceed n_test = len(test_data) n = len(training_data) for j in xrange(epochs): random.shuffle(training_data) #shuffle the data mini_batches = [training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)] for mini_batch in mini_batches: self.SGD(mini_batch, eta) #uncomment this if you want intermediate results #print "Batch: {0} / {1}".format(self.evaluate(test_data), n_test) #otherwise epoch results: print "Epoch {0}: {1} / {2}".format(j, self.evaluate(test_data), n_test) def SGD(self, mini_batch, eta): """Update the network's weights and biases by applying gradient descent using backpropagation (derivatives) to a single mini batch.""" #provide the mini_batch and the learning rate #create empty derivative array of vectors for each layer nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: #call backprop for this particular input delta_nabla_b, delta_nabla_w = self.backprop(x, y) #update the derivative nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] #update the weight and biases in the negative descent direction aka negative derivative self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] def backprop(self, x, y): """For in-depth computation of the derivatives watch my video!""" delta_nabla_b = [np.zeros(b.shape) for b in self.biases] delta_nabla_w = [np.zeros(w.shape) for w in self.weights] # feedforward activation = x activations = [x] # list to store all the activations, layer by layer zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = sigmoid(z) activations.append(activation) # backward pass <<<--- output layer delta = self.cost_derivative(activations[-1], y) * sigmoid_prime(zs[-1]) #delta is simply cost_derivate times the sigmoid function of the last activation aka output which #is the derivative of the bias for output layer delta_nabla_b[-1] = delta #derivative of the weights: #delta * output of the previous layer which is the previous activation before the output delta_nabla_w[-1] = np.dot(delta, activations[-2].transpose()) #backward pass <<<--- hidden layers #using negative indices: starting from the first hidden layer and backwards for l in xrange(2, self.num_layers): z = zs[-l] sp = sigmoid_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp delta_nabla_b[-l] = delta delta_nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (delta_nabla_b, delta_nabla_w) def evaluate(self, test_data): """Return the number of test inputs for which the neural network outputs the correct result. Note that the neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation.""" test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data] return sum(int(x == y) for (x, y) in test_results) def cost_derivative(self, output_activations, y): return (output_activations-y) def sigmoid(z): """ Classic sigmoid function: lot smoother than step function that MLP uses because we want small changes in parameters lead to small changes in the output """ return 1.0/(1.0+np.exp(-z)) def sigmoid_prime(z): """Derivative of the sigmoid function.""" return sigmoid(z)*(1-sigmoid(z)) # Sources: # Neural networks and deep learning, Michael Nielsen (great book!) # http://neuralnetworksanddeeplearning.com/chap2.html # Neural network, backpropagation algorithm, Ryan Harris # https://www.youtube.com/watch?v=zpykfC4VnpM # MNIST database # # Code: # mnist_loader is completely Nielsen's work # Network code is also majorly inspired by him. I have made modifications to make it simpler.
b1ce06dcf2fffe8543d67751f712166d20000bf7
ysw900524/Python_Multicampus
/Day4_10_27/s606_인스턴스변수_인스턴스간공유안됨.py
556
3.5
4
# 인스턴스 변수 class Cat: def __init__(self, name): self.name = name self.tricks = [] # 인스턴스 변수 선언 def add_trick(self, trick): self.tricks.append(trick) #인스턴스 변수에 값 추가 cat1 =Cat('하늘이') cat2 = Cat('야옹이') cat1.add_trick('구르기') cat2.add_trick('두발로 서기') cat2.add_trick('죽은척 하기') print(cat1.name, ":", cat1.tricks) print(cat2.name, ':', cat2.tricks) # 하늘이 : ['구르기'] # 야옹이 : ['두발로 서기', '죽은척 하기']
daa15a806aa377a9261d0d4cb94a4d3676904b86
ysw900524/Python_Multicampus
/Day4_10_27/Day4_미션1_로또번호생성.py
1,121
4.03125
4
# 미션 1 # 로또 번호를 자동으로 생성해서 출력 # 주문한 개수만큼 N개의 로또 번호 출력 # Hint : 랜덤 숫자 생성 # import random # random.randint(num1, num2) # num1~num2까지의 정수 생성 # # Ex. dice.py # import random # # dice_num = random.randint(1, 6) # print('주사위:'. doce_num) import random # class Lotto: # nums = set() # # def select(self, num): # while len(num) <= 7: # num.add(random.randint(1,45)) # print(num) # # class Lotto: # nums = set() # # def __init__(self, num): # while len(num) <= 7: # self.nums.add(random.randint(1,45)) # # def select(self): # # # mylotto = Lotto() # my_lotto = mylotto.select() # print(my_lotto) class Lotto: final = list() def select(self, n): for i in range(n): nums = set() while len(nums) <= 6: num = random.randint(1, 45) nums.add(num) self.final.append(nums) return self.final try1 = Lotto() x = try1.select(4) print(x)
c8e8670b016510be47f75896a82fecaadef0aa77
ysw900524/Python_Multicampus
/Day2_10_25/Day2_과제_도형그리기.py
865
4
4
import turtle import math import time width = 100 height = 100 slide = math.sqrt(width**2 + height**2) input('엔터를 치면 거북이가 도형을 그립니다.') turtle.shape('turtle') turtle.pensize(5) turtle.color('blue') print('거북이 달리기 시작합니다.') #time.sleep(1) turtle.forward(width) #time.sleep(1) turtle.right(135) turtle.forward(slide) #time.sleep(1) turtle.left(135) turtle.forward(width) #time.sleep(1) turtle.left(135) turtle.forward(slide) #time.sleep(1) turtle.left(135) turtle.forward(height) #time.sleep(1) turtle.left(90) turtle.forward(width) #time.sleep(1) turtle.left(90) turtle.forward(width) #time.sleep(1) turtle.left(45) turtle.forward(slide/2) #time.sleep(1) turtle.left(90) turtle.forward(slide/2) turtle.done() # time.sleep(1) # turtle.right(90) # turtle.forward(width) # # time.sleep(1) # turtle.
a9e29aa8ec9548ea7928a9d83598ddcdec7e4ba7
ysw900524/Python_Multicampus
/Day1_10_24/s105_comment.py
626
3.65625
4
# 한줄 주석 : 샵기호(#)로 시작하는 줄 # 블럭 주석 : 큰따옴표 3개로 감사는 줄 # 이 줄은 라인 코멘트입니다. print("Hello World!") print("Hello World!") # 이것도 라인 코멘트입니다. print("Hello World!") # 이것도 라인 코멘트입니다. # First comment a = 15 # Second comment # a값을 출력해 보세요! print(a) b = '파이썬의 주석은 샾기호(#)로 시작합니다.' print(b) # 마지막 라인입니다. # 한줄 주석과 블럭 주석 """ 블럭주석, 즉 멀티라인의 주석문은 따옴표(''' ''') 3개 """ # 한줄 주석문은 샾기호(#)
00cf2f1c84d610e15e65b70d4a643caea0a01c4c
JordenHai/workSpace
/oldboyDaysDir/day1/passwd.py
360
3.625
4
# -*- coding:utf-8 -*- # Author: Jorden Hai #秘文输入 import getpass #新的包 _username = 'jh' _password = '123456' username = input("username:") password = input("password:") if username == _username and _password == password: print("Success Login!") print('''Wellcome user {_name} login...'''.format(_name = username)) else: print("Fail")
44c8ac49899f2174a56812c8e62d229ea7b0c3a3
JordenHai/workSpace
/oldboyDaysDir/day6/MulIheri.py
695
3.984375
4
# -*- coding:utf-8 -*- # Author: Jorden Hai class A(): def __init__(self): print("init in A") class B(A): def __init__(self): A.__init__(self) print("init in B") class C(A): def __init__(self): A.__init__(self) print("init in C") class D(B,A): #找到第一个就停下来 pass # # A # | \ # B C # D #继承策略 #继承方向 从D --> B --> C --> A 广度优先查找 # #从python3中经典类新式类按照广度优先 #从python2中经典类中深度优先来继承 新式类按照广度优先来继承 # #继承方向 从D --> B --> A --> C 深度优先查找 a = D()
5be234e49a9106b7bdef8a1cea9def37cc97a72b
JordenHai/workSpace
/oldboyDaysDir/day1/集合.py
1,073
3.859375
4
list_1 = [1,4,5,6,9,7,3,1,2] list_1 = set(list_1) print(list_1) list_2 = set([2,6,0,66,22,8,4]) print(list_2) #交集 list_3 = list_1.intersection(list_2) print(list_3) #并集 list_3 = list_1.union(list_2) print(list_3) #差集 list_3 = list_1.difference(list_2) print(list_3) list_3 = list_2.difference(list_1) print(list_3) #子集 #判断是不是子集 print(list_1.issubset(list_2)) print(list_1.issuperset(list_2)) list_3 = set([1,3,7]) print(list_3.issubset(list_1)) print(list_1.issuperset(list_3)) #反向的差集 #对称差集 list_3 = list_1.symmetric_difference(list_2) #去掉大家都有的 print(list_3) L = [] for value in list_3: L.append(value) print(L) #disjoint list_3 = [22,44,55] print(list_1.isdisjoint(list_3)) #用运算符来计算交并 print(list_1&list_2)#交集 print(list_1|list_2)#并集 print(list_1-list_2)#差集 print(list_1^list_2)#对称差集 #subset and upperset #没有专门符号 print(list_1) list_1.add(99) print(list_1) list_1.update([88,99,66,33]) print(list_1) list_1.remove(1) print(list_1)
a60a933c68c6210b3c407f3bdfcae0352cd575c6
MarkHershey/PythonWorkshop2020
/Session_01/py101/10_classes.py
418
3.984375
4
class People: def __init__(self, name, birthYear): self.name = name self.birthYear = birthYear self.age = 2020 - birthYear self.height = None self.pillar = None p1 = People("Maria", 1999) print(p1.name) print(p1.birthYear) print(p1.age) p1.pillar = "Architecture and Sustainable Design (ASD)" print(f"{p1.name} is {p1.age} years old, and she is majored in {p1.pillar}")
552b2a950f718a75b11dcba8ee93fbb41ad4438c
zhengshaobing/PythonSpider
/BK_全局锁机制_生产者与消费者模式.py
1,899
3.625
4
import threading, random, time Qmoney = 1000 # Value_data = 0 gLock = threading.Lock() gTotal_times = 10 gtimes = 0 # # # class CountThread(threading.Thread): # def run(self): # global Value_data # # 锁主要用于:修改全局变量的地方 # gLock.acquire() # for x in range(1000000): # Value_data += 1 # gLock.release() # print(Value_data) # # # def main(): # for x in range(2): # t = CountThread() # t.start() ''' 这种方法十分占用cpu资源, 不推荐使用 ''' # class Producer(threading.Thread): # def run(self): # global Qmoney # global gtimes # global gTotal_times # while 1: # money = random.randint(100, 1000) # gLock.acquire() # if gtimes >= gTotal_times: # gLock.release() # break # Qmoney += money # gtimes += 1 # gLock.release() # print('生产了%d元,剩余了%d元'%(money, Qmoney)) # time.sleep(0.5) # # # class Consumer(threading.Thread): # def run(self): # global Qmoney # global gTotal_times # global gtimes # while 1: # money = random.randint(100, 1000) # gLock.acquire() # if Qmoney >= money: # Qmoney -= money # gLock.release() # print('消费了%d元,剩余了%d元' % (money, Qmoney)) # else: # #if gtimes > gTotal_times: # gLock.release() # break # # time.sleep(0.5) # # # def main(): # # for x in range(1): # t = Producer(name='生产者%d'%x) # t.start() # for x in range(3): # t = Consumer(name='消费者%d'%x) # t.start() # # # if __name__ == '__main__': # main()
5822eb6433daf2b6421c7a0f318729b043eb84fb
avelikev/Exercises
/data_structures/dictionaries_and_arrays/2.Reverse_Array /Solutions/solution.py
196
4.0625
4
from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) reverse_array = array('i') for i in range(len(array_num)-1,-1,-1): reverse_array.append(array_num[i]) print(reverse_array)
ae5fd33d822cacc8617bf5db2f8b4633f9860f1a
avelikev/Exercises
/introduction_to_python/functions/1_return_hello/Solution/solution.py
128
3.671875
4
# Code your solution here def hello(name): data="Hello "+name return data name=input() result=hello(name) print(result)
73857ec7f281166378fecff5c1ab4f1ff3011d44
avelikev/Exercises
/data_structures/stacks_and_queues/1_create_queue/Solution/solution.py
369
3.703125
4
# Code your solution here def queue(): import queue queue_a = queue.Queue(maxsize=5) # Queue is created as an object 'queue_a' queue_a.put(9) queue_a.put(6) queue_a.put(7) # Data is inserted in 'queue_a' at the end using put() queue_a.put(4) queue_a.put(1) return queue_a data=queue() result=list(data.queue) print(result)
7cddd25f93030f10c2c9a4e6eb71bb1445f7fc9c
avelikev/Exercises
/introduction_to_python/functions/3_total/Solution/solution.py
160
3.5
4
# Code your solution here def summ(l): total = 0 for x in l: total=total+x return total l=[10,20,30,40,50,60] result=summ(l) print(result)
1bd7f0daf5019e00dc508429182bd7016956bf33
avelikev/Exercises
/data_structures/stacks_and_queues/2_stack_insert/Solution/solution.py
237
3.515625
4
# Code your solution here def insert(stack_planets): stack_planets.insert(2,'Earth') return stack_planets stack_planets=['Mercury','Venus','Mars','Jupiter','Saturn','Uranus','Neptune'] result=insert(stack_planets) print(result)
cbe50f30732a080bf558b0a77e29942ed2c04f7a
avelikev/Exercises
/data_structures/binary_trees/3_normal BST to Balanced BST/Solution/solution.py
1,810
3.953125
4
import sys import math # A binary tree node has data, pointer to left child # and a pointer to right child class Node: def __init__(self,data): self.data=data self.left=None self.right=None # This function traverse the skewed binary tree and # stores its nodes pointers in vector nodes[] def storeBSTNodes(root,nodes): # Base case if not root: return # Store nodes in Inorder (which is sorted # order for BST) storeBSTNodes(root.left,nodes) nodes.append(root) storeBSTNodes(root.right,nodes) # Recursive function to construct binary tree def buildTreeUtil(nodes,start,end): # base case if start>end: return None # Get the middle element and make it root mid=(start+end)//2 node=nodes[mid] # Using index in Inorder traversal, construct # left and right subtress node.left=buildTreeUtil(nodes,start,mid-1) node.right=buildTreeUtil(nodes,mid+1,end) return node # This functions converts an unbalanced BST to # a balanced BST def buildTree(root): # Store nodes of given BST in sorted order nodes=[] storeBSTNodes(root,nodes) # Constucts BST from nodes[] n=len(nodes) return buildTreeUtil(nodes,0,n-1) # Function to do preorder traversal of tree def preOrder(root): if not root: return return root.data preOrder(root.left) preOrder(root.right) if __name__=='__main__': root = Node(10) root.left = Node(8) root.left.left = Node(7) root.left.left.left = Node(6) root.left.left.left.left = Node(5) root = buildTree(root) # print("Preorder traversal of balanced BST is :") result=preOrder(root) print(result)
eed8d54cb38af8b0bb62927b9dadfdf0aa69d378
debargham14/bcse-lab
/Sem 4/Adv OOP/python_assignments_set1/sol10.py
444
4.125
4
import math def check_square (x) : "Function to check if the number is a odd square" y = int (math.sqrt(x)) return y * y == x # input the list of numbers print ("Enter list of numbers: ", end = " ") nums = list (map (int, input().split())) # filter out the odd numbers odd_nums = filter (lambda x: x%2 == 1, nums) # filter out the odd squares odd_squares = list (filter (check_square, odd_nums)) print ("Odd squares are: ", odd_squares)
6b2736e3ef5bd2b374367750d21d8af3e9ca2e0a
debargham14/bcse-lab
/Sem 4/Adv OOP/python_assignments_set1/sol11.py
434
4.28125
4
print ("Pythagorean Triplets with smaller side upto 10 -->") # form : (m^2 - n^2, 2*m*n, m^2 + n^2) # generate all (m, n) pairs such that m^2 - n^2 <= 10 # if we take (m > n), for m >= 6, m^2 - n^2 will always be greater than 10 # so m ranges from 1 to 5 and n ranges from 1 to m-1 pythTriplets = [(m*m - n*n, 2*m*n, m*m + n*n) for (m,n) in [(x, y) for x in range (1, 6) for y in range (1, x)] if m*m - n*n <= 10] print (pythTriplets)
2f266658a68658cc904391e4fea493d8581025c8
JasianJ/Python
/Fibonacci Sequence/Fibonacci.py
1,195
4.09375
4
from IPython.display import clear_output def findnum(n): out = [] a, b = 0, 1 for i in range(n): out.append(a) a, b = b, a+b return out def nth(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a on = True print 'Enther a number to generate Fibonacci sequence to that number.' while on == True: print 'Option 1 for display sequence\nOption 2 for display Nth number' op = int(raw_input('Press 1 or 2: ')) if op == 1: n = int(raw_input('Display Fibonacci sequence, starts from 0, upto ')) if n > 20: print 'Sorry your sequence is too long. Please use option 2.' else: print findnum(n) elif op == 2: n = int(raw_input('Display Nth number of Fibonacci sequence starts from 0. N = ')) print nth(n-1) again = str(raw_input('Again? Y/N: ')).upper() if again == 'Y': clear_output() pass elif again == 'N': clear_output() on = False break else: again = str(raw_input('Y or N only. Again? Y/N: ')).upper() clear_output()
2c0d624ee886d24c10a979e922c1e7fbab74d7ed
AlterFritz88/flask_practice
/task_3_14_6.py
758
3.546875
4
class PiggyBank: def __init__(self, dollars, cents): self.dollars = dollars self.cents = cents def add_money(self, deposit_dollars, deposit_cents): self.dollars += deposit_dollars self.cents += deposit_cents if self.cents > 99: self.dollars += self.cents // 100 self.cents = self.cents % 100 # if deposit_cents + self.cents > 99: # print('here') # print((deposit_cents + self.cents) % 100) # self.dollars += (deposit_cents + self.cents) // 100 # self.cents += (deposit_cents + self.cents) % 100 # else: # self.cents += deposit_cents pig = PiggyBank(10, 20) pig.add_money(0, 90) print(pig.dollars, pig.cents)
bbe6083817412b75edfb6985b3718f08a6740faa
ThallesVale/calculadoraAnuncios
/calculadora.py
849
3.765625
4
#CALCULADORA - ALCANCE DE ANÚNCIO ONLINE: investimento = input('Digite o valor a ser investido: ') investimento = float(investimento) #Visualizações atreladas ao valor investido: visualizacao = investimento*30 #Cliques gerados por volume de visualizações: cliques = int(visualizacao*.12) #Compartilhamentos por volume de cliques: compartilham = int(cliques*.15) #Manipulação de compartilhamentos considerando restrições: #Sequência de compartilhamentos controle_compart = compartilham//5 resto = compartilham%5 controle_compart *= 4 controle_compart += resto #Visualizações atreladas aos compartilhamentos: visualiz_extra = controle_compart * 40 #Total de visualizações: visualizacao += visualiz_extra visualizacao = int(visualizacao) print(f'O alcance do seu anúncio é de aproximadamente {visualizacao} visualizações. ')
84e3e7e273206db5ddb0576f42fbec467164f1c5
shaunmulligan/resin-neopixel
/app/leds.py
1,530
3.53125
4
from time import sleep from neopixel import Adafruit_NeoPixel, Color # LED strip configuration: LED_COUNT = 64 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 # DMA channel to use for generating signal (try 5) LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) ROW_WIDTH = 8 def setRowColor(strip, row_number, color): start = 0 + row_number*ROW_WIDTH end = start + ROW_WIDTH for i in range(start, end): strip.setPixelColor(i, color) strip.show() def fill_up_to(strip, row, color): for i in range(row + 1): setRowColor(strip,i,color) def empty_array(strip): for i in range(256): strip.setPixelColorRGB(i,0,0,0) strip.show() # Main program logic follows: if __name__ == '__main__': # Create NeoPixel object with appropriate configuration. led_array = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) # Intialize the library (must be called once before other functions). led_array.begin() while True: color = Color(0, 0, 60) # setRowColor(led_array,1,color) # fill_up_to(led_array,0,color) # sleep(0.1) fill_up_to(led_array,7,color) sleep(5) empty_array(led_array) sleep(3)
669f4bbca09f2d6062be01a30fdfd0f7a0367394
mckinleyfox/cmpt120fox
/pi.py
487
4.15625
4
#this program is used to approximate the value of pi import math def main(): print("n is the number of terms in the pi approximation.") n = int(input("Enter a value of n: ")) approx = 0.0 signchange = 1.0 for i in range(1, n+1, 2): approx = approx + signchange * 4.0/i # JA signchange = -signchange print("The aprroximate value of pi is: ", approx) print("The difference between the approximation and real pi is: ", math.pi - approx) main()
5c1a951d38aeeec9b7329a011b8d634cb9137f52
jorgeromeromg2/Python
/mundo2/ex92.py
580
3.703125
4
from datetime import datetime relacao = dict() relacao["Nome"] = str(input('Nome: ')).capitalize() idade = int(input('Ano de nascimento: ')) relacao["Idade"] = datetime.now().year - idade relacao["CTPS"] = int(input('Carteira de Trabalho (0 não tem): ')) if relacao["CTPS"] != 0: relacao["Contratação"] = int(input('Ano de Contratação: ')) relacao["Salário"] = float(input('Salário: ')) relacao["Aposentadora"] = relacao["Idade"] + ((relacao["Contratação"] + 35) - datetime.now().year) for k, v in relacao.items(): print(f'{"-":>5} {k} tem o valor {v}')
f6c98f4637a5dbf25fd4d76119aa0cb93c819e77
jorgeromeromg2/Python
/mundo2/ex85.py
670
3.84375
4
'''valores = [] par = [] impar = [] for v in range(1, 8): valores.append(int(input(f'Digite o {v}º valor: '))) if valores[0] % 2 == 0: par.append(valores[:]) elif valores[0] % 2 != 0: impar.append(valores[:]) valores.clear() print(sorted(par)) print(sorted(impar))''' numeros = [[], []] valor = 0 for v in range(1, 8): valor = int(input(f'Digite o {v}º valor: ')) if valor % 2 == 0: numeros[0].append(valor) else: numeros[1].append(valor) numeros[0].sort() numeros[1].sort() print('==='*30) print(f'Os números pares digitados são: {numeros[0]}') print(f'Os números ímpares digitados são: {numeros[1]}')
6d8ca4a28dfdc8a6a703c8dc8d8652981fe10238
jorgeromeromg2/Python
/mundo1/ex033.py
350
3.890625
4
reta1 = float(input('Digite a primeira reta: ')) reta2 = float(input('Digite a segunda reta: ')) reta3 = float(input('Digite a terceira reta: ')) if (reta1 + reta2 > reta3) and (reta2 + reta3 > reta1) and (reta1 + reta3 > reta2): print('Possui condição para ser um triângulo.') else: print('Não possui condição para ser um triângulo.')
4c538d0eccedfa427845be1ca803cdb6cc2ef867
jorgeromeromg2/Python
/mundo2/ex008_D41.py
787
4.25
4
#--------CATEGORIA NATAÇÃO--------# print(10 * '--=--') print('CADASTRO PARA CONFEDERAÇÃO NACIONAL DE NATAÇÃO') print(10 * '--=--') nome = str(input('Qual é o seu nome: ')).capitalize() idade = int(input('Qual é a sua idade: ')) if idade <= 9: print('{}, você tem {} anos e está cadastrado na categoria MIRIM.'.format(nome, idade)) elif idade <= 14: print('{}, você tem {} anos e está cadastrado na categoria INFANTIL.'.format(nome, idade)) elif idade <= 19: print('{}, você tem {} anos e está cadastrado na categoria JUNIOR.'.format(nome, idade)) elif idade <= 20: print('{}, você tem {} anos e está cadastrado na categoria SENIOR.'.format(nome, idade)) else: print('{}, você tem {} anos e está cadastrado na categoria MASTER.'.format(nome, idade))
fd614fdd36b34645dd4afc125153dc09493841c2
jorgeromeromg2/Python
/mundo1/ex005.py
648
4.15625
4
#--------SOMA ENTRE NÚMEROS------ #n1 = int(input('Digite o primeiro número: ')) #n2 = int(input('Digite o segundo número: ')) #soma = n1 + n2 #print('A soma entre {} e {} é igual a {}!'.format(n1, n2, soma)) #--------SUCESSOR E ANTECESSOR----- n = int(input('Digite um número e verifique o sucessor e antecessor:')) a = n-1 s = n+1 print('Analisando o valor {} podemos perceber que o antecessor é {} e o sucessor é {}.'.format(n, a, s)) #-----OU----- n = int(input('Digite um número e verifique o sucessor e antecessor:')) print('Analisando o valor {} podemos perceber que o antecessor é {} e o sucessor é {}.'.format(n, (n-1), (n+1)))
f26dc0e78afb7d4ca9e79764ee4914b8f523f9b8
jorgeromeromg2/Python
/mundo2/ex013_D51.py
437
4.0625
4
#-----PROGRESSÃO ARITMÉTICA------ '''num1 = int(input('Digite o primeiro termo da P.A: ')) num3 = int(input('Digite a razão da P.A: ')) for n in range(num1, 10*num3, num3): print('O termos da P.A são {} '.format(n))''' primeiro = int(input('Primerio termo: ')) razao = int(input('Razão: ')) decimo = primeiro + (10 - 1) * razao for c in range(primeiro, decimo + razao, razao): print('{}'.format(c), end=' » ') print('FIM')
457ee2cf1dbd934cab7bf67f8600c895ec9229a0
jorgeromeromg2/Python
/mundo2/ex88.py
458
3.6875
4
from random import randint from time import sleep jogo = [] jogo1 = [] jogadas = int(input('Quantos jogos você quer que eu sorteie? ')) print(3*'-=', f'SORTEANDO {jogadas} NÚMEROS', 3*'-=') for j in range(1, jogadas+1): jogo.clear() jogo1 = [randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60)] jogo.append(jogo1[:]) jogo1.clear() print(f'Jogo {j:^1}: {jogo}') sleep(1) print('Boa sorte')
c53134cddbc37e350cd80a9b8a334a0f1299382e
jorgeromeromg2/Python
/mundo2/ex013_D48.py
655
4.0625
4
#------NUMEROS IMPARES DIVISIVEIS POR 3-------- '''primeiro = int(input('Digite o primeiro número da sequência: ')) ultimo = int(input('Digite o último número da sequência: ')) for c in range(primeiro, ultimo): if c % 3 == 0 and c % 2 != 0: print(c) print('Na contagem de {} à {} os números em tela são impares múltiplos de 3'.format(primeiro, ultimo))''' soma = 0 cont = 0 for c in range(1, 501, 2): if c % 3 == 0: cont += 1 #QUANTIDAE DE VALORES SELECIONADOS soma += c #SOMATORIO DOS VALORES SELECIONADOS #print(c, end=' ') print('A soma de todos os {} valores solicitados é {}'.format(cont, soma))
d11deb0a802075340ada466cb8a9af86f764b71d
jorgeromeromg2/Python
/mundo2/ex014_D64.py
558
3.78125
4
cont = n = total = 0 while total < 999: total = int(input('Digite um número [999 para parar]: ')) if total != 999: n += total cont += 1 print('Você digitou {} números e a soma entre eles foi {}'.format(cont, n)) ''' n = cont = soma = 0 n = int(input('Digite um número [999 para parar]: )) while n != 999: soma += n cont += 1 n = int(input('Digite um número [999 para parar]: )) #O FLAG ESTANDO NA ULTIMA LINHA FAZ ELE SAIR DO WHILE print('Você digitou {} números e a soma entre eles foi {}.'.format(cont, soma))'''
225121d559a01c2380908f55d70d53357972b619
jorgeromeromg2/Python
/mundo2/ex014_D60.py
687
4.0625
4
#----FATORIAL----- '''from math import factorial fat = int(input('Digite o número e descubra seu fatorial: ')) num1 = factorial(fat) print('O fatorial de {} é {}'.format(fat, num1))''' '''n1 = int(input('Digite um número para calcular o fatorial: ')) f = 1 print('Calculando {}! = '.format(n1), end='') while n1 > 0: print('{}'.format(n1), end='') print(' x ' if n1 > 1 else ' = ', end='') f *= n1 n1 -= 1 print('{}'.format(f))''' fat = int(input('Digite um número: ')) c = 1 print('Calculando {}! = '.format(fat), end='') for n in range(fat, 0, -1): print('{}'.format(n), end='') print(' x ' if n > 1 else ' = ', end='') c *= n print(' {} '.format(c))
8bd089a620d46edb2e29106eeecbbcc94c4a46ab
jorgeromeromg2/Python
/mundo1/ex004a.py
204
3.765625
4
n1 = input('Digite algo: ') print('O que foi digitado é um número? ', n1.isalnum()) print('O que foi digitado é uma string? ', n1.isalpha()) print('O que foi digitado é alfanumérico? ', n1.isalnum())
c5eb72c84282a18019f9d280449ffcdbcf0948d1
Zoooka/Rock-Paper-Scissors-
/rock paper.py
1,228
4.03125
4
import sys import getpass # Creates two users, and for users to enter their names User1 = input("Player one, what is your name? ") User2 = input("Player two, What is your name? ") # Counts users wins User1_wincount = 0 User2_wincount = 0 # Prompts users to enter rock paper scissors etc... User1_answer = input("%s, do you want to choose rock, paper or scissors? " % User1) User2_answer = input("%s, do you want to choose rock, paper or scissors? " % User2) # Compares user ones and user twos inputs and calculates winner def compare(u1, u2): if u1 == u2: return("It's a tie!") elif u1 == 'rock': if u2 == 'scissors': return("Rock wins!") User1_wincount + 1 else: return('Paper wins!') elif u1 == 'scissors': if u2 == 'paper': return("Scissors wins!") else: return("Rock wins!") elif u1 == 'paper': if u2 == 'rock': return("Paper wins!") else: return("Scissors wins!") else: return("Invalid input. Don't try and get fancy.") sys.exit() # Prints who won to console print(compare(User1_answer, User2_answer)) # print(User1_wincount, User2_wincount)
ec7e9176ef54a88a6c1d25b89c599f8d9e419c89
irische/Intro-to-CS_Python
/HW_3/HW_3_part_1/hw3_part1_files/hw3_part1.py
3,744
3.921875
4
# Qianqian Che (cheq@rpi.edu) # Purpose: output the table about top 250 ranked female and male names on demand. # read and access the names and counts import read_names import sys # function to find if a value is in the list and the index and return required values def table(name,list_name,list_counts): position=list_name.index(name) count='%5d'%int(list_counts[position]) percent_top='%7.3f'%(100.*int(count)/list_counts[0]) percent_sum='%7.3f'%(100.*int(count)/sum(list_counts)) rank='%3d'%int(position+1) name=name.ljust(11) return '%s %s %s %s %s'%(rank,name,count,percent_top,percent_sum) # function to print out required table of rank, name, count, and percentage information def table_(name,list_name,list_counts): if name in list_name: position=list_name.index(name) if position==0: name_1=name name_2=list_name[position+1] name_3=list_name[position+2] print table(name_1,list_name,list_counts) print table(name_2,list_name,list_counts) print table(name_3,list_name,list_counts) elif position==1: name_1=name name_2=list_name[position+1] name_3=list_name[position+2] name_4=list_name[position-1] print table(name_4,list_names,list_counts) print table(name_1,list_names,list_counts) print table(name_2,list_names,list_counts) print table(name_3,list_names,list_counts) elif position==249: name_1=name name_2=list_name[position-1] name_3=list_name[position-2] print table(name_3,list_name,list_counts) print table(name_2,list_name,list_counts) print table(name_1,list_name,list_counts) elif position==248: name_1=name name_2=list_name[position+1] name_3=list_name[position-1] name_4=list_name[position-2] print table(name_4,list_name,list_counts) print table(name_3,list_name,list_counts) print table(name_1,list_name,list_counts) print table(name_2,list_name,list_counts) else: name_1=list_name[position-2] name_2=list_name[position-1] name_3=list_name[position] name_4=list_name[position+1] name_5=list_name[position+2] print table(name_1,list_name,list_counts) print table(name_2,list_name,list_counts) print table(name_3,list_name,list_counts) print table(name_4,list_name,list_counts) print table(name_5,list_name,list_counts) else: print '%s is not in top 250.'%name # read in year and names from the user and call the functions above to output the table required. read_names.read_from_file('top_names_1880_to_2014.txt') year=raw_input('Enter the year to check => ') print year if int(year)<1880 or int(year)>2014: print 'Year must be at least 1880 and at most 2014' sys.exit() print female_name=raw_input('Enter a female name => ') print female_name print 'Data about female names' (female_names,female_counts)=read_names.top_in_year(int(year), 'f') print 'Top ranked name %s'%female_names[0] print '250th ranked name %s'%female_names[249] list_250_female=female_names[0:250] female=table_(female_name,female_names,female_counts) print male_name=raw_input('Enter a male name => ') print male_name print 'Data about male names' (male_names,male_counts)=read_names.top_in_year(int(year), 'M') print 'Top ranked name %s'%male_names[0] print '250th ranked name %s'%male_names[249] list_250_male=male_names[0:250] male=table_(male_name,male_names,male_counts)
d4fd84f9634db9e9db97e347360b5da2bab01b09
irische/Intro-to-CS_Python
/HW_8/hw9_part1.py
1,898
3.84375
4
"""Author: <Boliang Yang and yangb5@rpi.edu> Purpose: This program reads a yelp file about the businesses, counts all categories that co-occur with the given category and prints those categories with counts greater than the given cutoff in sorted order. """ ## all imports import json ## main body of the program if __name__ == "__main__": category_name=raw_input('Enter a category ==> ') print category_name cutoff=int(raw_input('Cutoff for displaying categories => ')) print cutoff business_list=[] category_all=set() for line in open('businesses.json'): business = json.loads(line) business_list.append(business) for category in business['categories']: category_all.add(category) categories_dictionary={} for business_name in business_list: if category_name in business_name['categories']: for category in business_name['categories']: if category_name!=category: if category not in categories_dictionary.keys(): categories_dictionary[category]=0 categories_dictionary[category]+=1 output_list=[] for category in categories_dictionary.keys(): if categories_dictionary[category]>=cutoff: output_list.append((category,categories_dictionary[category])) if category_name not in category_all: print 'Searched category is not found' elif len(output_list)==0: print 'None above the cutoff' else: print 'Categories co-occurring with %s:' %category_name output_list.sort() for output in output_list: string='%s: %d' %(output[0],output[1]) space=' '*(30-len(output[0])) string=space+string print string
5bad1293e9456a4baf7c4b63c1edac3662d1f18d
irische/Intro-to-CS_Python
/HW_4/hw4_part3.py
1,473
3.640625
4
'''This program reads in the death statistics for areas of NYS from 2003 to 2013 and ouput the trend in a single line. ''' import hw4_util ## function definition to output the trend of death statistics. def read_deaths(county,data): data_=data[:] sum=0 for r in range(len(data_)): sum+=data_[r] average=sum/11 high=average*105/100 low=average*95/100 data__='' for d in range(len(data_)): if float(data_[d])>=high: data_[d]='+' data__+=data_[d] elif float(data_[d])<=low: data_[d]='-' data__+=data_[d] else: data_[d]='=' data__+=data_[d] print county.ljust(15)+data__ ## main body of program if __name__=="__main__": county_1=raw_input('First county => ') print county_1 data_1 = hw4_util.read_deaths(county_1) county_2=raw_input('Second county => ') print county_2 data_2= hw4_util.read_deaths(county_2) print ## conditional statements for different cases if data_1!=[] and data_2!=[]: print ' '*15+'2013'+' '*3+'2003' read_deaths(county_1,data_1) read_deaths(county_2,data_2) elif data_1!=[] and data_2==[]: print 'I could not find county %s'%county_2 elif data_1==[] and data_2!=[]: print 'I could not find county %s'%county_1 else: print 'I could not find county %s'%county_1 print 'I could not find county %s'%county_2
7354794ac710eeb677d5c2d163c2c74f60e78d22
nindanindra/meerkpy
/chapter2.py
1,715
4.0625
4
users={"Anna":{ "bbm":2.0, "doraemon":4.325}, "Joe":{"ff7":4.125, "doraemon":3.275}, "Smith":{"ff7":1.25, "bbm":2.450, }} def manhattan(rating1,rating2): distance=0 for key in rating1: if key in rating2: distance+=abs(rating1[key] - rating2[key]) return distance def minkowski(rating1, rating2, r): distance=0 commonRatings=False # calculate difference for key in rating1: if key in rating2: print 'in the loop' distance+=pow((abs(rating1[key] - rating2[key])),r) commonRatings= True if commonRatings: print 'true' return pow(distance, 1/r) else: print 'false' return 0 def computeNearestNeighbour(username,users): distances=[] for user in users: if user != username: distance = minkowski(users[user],users[username],2) distances.append((distance, user)) distances.sort() return distances def recommend(username, users): # get the name of the nearest neighbour nearestNeighbour = computeNearestNeighbour(username,users)[0][1] # computeNearestNeighbour return pair of tuple, we would like to pick the first # one which will return the pair of our username # if we pick [0], it will return the tuple # we want the name, which locate in the second index of our tuple [0] # therefore we increment the index into [1] recommendations = [] # get the list of their movies nearestNeighbourMov = users[nearestNeighbour] userMov = users[username] # get the recommendations for film in nearestNeighbourMov: if not film in userMov: recommendations.append((film, nearestNeighbourMov[film], nearestNeighbour)) return sorted(recommendations, key=lambda filmTuple: filmTuple[1], reverse = True)
3d93e7ba5742d17e856ec95538b1bfaaca906d79
Madhuparna-Das/Madhuparna_Das
/extension.py
330
3.890625
4
file_name=input("enter the file name").casefold() b=file_name.split('.') y=b[1] if(y=='py'): print("file extension is python") elif(y=='java'): print("file extension is java") elif(y=='c'): print("file extension is C") elif(y=='cpp'): print("file extension is c++") else: print("please enter valid file name")
d1efce2817a84b01f03ffd6510e19e70177387f9
elirud/kattis
/problems/sodasurpler.py
257
3.5625
4
i = dict(zip(['start', 'found', 'needed'], map(int, input().split()))) bottles = i['start'] + i['found'] sodas = 0 while bottles >= i['needed']: sodas += bottles // i['needed'] bottles = bottles // i['needed'] + bottles % i['needed'] print(sodas)
e8ba6c87fc0660ecec74f67dff3ab8a4b92316f8
jptafe/ictprg434_435_python_ex
/wk4/wk4_input.py
989
3.609375
4
#!/usr/bin/python # TAKE only 1 parameter from the CLI # calculate and print the CLI parameter + 5 # NOTE: Attempt this WITHOUT an if statement # use try: except: block instead import sys try: newnum = int(sys.argv[1]) + 4 if(newnum = 999): raise Exception('blah') except ValueError: print('err') sys.exit(1) except IndexError: newnum = 99 print(newnum) sys.exit(0) import sys try: newvar = int(sys.argv[1]) + 4 except: print('err: arg error') sys.exit(1) print(newvar) sys.exit(0) def GetInput(): return input('give me a number: ') def EvalAsNum(anum = 'a'): if anum.isdigit(): return True else: return False numb = str('abca') #while EvalAsNum(numb) == False: # numb = GetInput() try: if int(numb) > 5: print('larger than 5') else: print('smaller or equal to 5') except ValueError: print('I give up!!!')
6c3d96d82e199378ef5cb8b5060a52f4ad92da07
ArjunSubramonian/CrazyEights
/util/card.py
692
3.6875
4
from enum import Enum class Rank(Enum): JOKER = 14 KING = 13 QUEEN = 12 JACK = 11 TEN = 10 NINE = 9 EIGHT = 8 SEVEN = 7 SIX = 6 FIVE = 5 FOUR = 4 THREE = 3 DEUCE = 2 ACE = 1 class Suit(Enum): CLUBS = 1 DIAMONDS = 2 HEARTS = 3 SPADES = 4 class Color(Enum): BLACK = 1 RED = 2 class Card: def __init__(self, rank, suit, color, alt_value=None): self.rank = rank if alt_value: self.value = alt_value else: self.value = self.rank self.suit = suit self.color = color def __str__(self): return self.rank.name + ' OF ' + self.suit.name
0b1c100231c6dbe5d970655a92f4baed0cbe1221
firoj1705/git_Python
/V2-4.py
1,745
4.3125
4
''' 1. PRINT FUNCTION IN PYTHON: print('hello', 'welcome') print('to', 'python', 'class') #here by default it will take space between two values and new line between two print function print('hello', 'welcome', end=' ') print('to', 'python', 'class') # here we can change end as per our requirement, by addind end=' ' print('hello', 'welcome', end=' ') print('to', 'python', 'class', sep=',') # here you can change sep as per our requirement by writing it. By default sep as SPACE is present. 2. KEYWORDS IN PYTHON: RESERVED WORDS import keyword print(keyword.kwlist) #you will get list of keyword in Python print(len(keyword.kwlist)) print(dir(keyword.kwlist)) print(len(dir(keyword.kwlist))) 3. BASIC CONCEPTS IN PYTHON: A. INDEXING: +indexing: strats from 0 -indexing: starts from -1 0 1 2 3 4 5 s= 'P y t h o n' -6-5-4-3-2-1 B. HASHING: s='Pyhton' print(s[0]) print(s[-6]) print(s[4]) print(s[7]) C. SLICING: s='Python' print(s[0:4]) print(s[3:]) print(s[:]) print(s[:-3]) print(s[5:4]) D. STRIDING/STEPPING: s='Python' print(s[0:5:2]) print(s[0:7:3]) print(s[5:0:-2]) print(s[::-1]) #E. MEMBERSHIP: s='Python' print('o' in s) print('p' in s) #F. CONCATENATION: s1='Hi' s2='Hello' s3='303' print(s1+s2) print(s1+' '+s2) print(s1+s2+s3) print(s1+s2+100) # error will occur, As datatype should be same. #G. REPLICATION: s1='Firoj' print(s1*3) print(s1*s1) # multiplier should be integer #H. TYPECASTING: s='100' print(int(s)) n=200 s1=str(n) print(s1) s='Hello' print(list(s)) #I. CHARACTER TO ASCII NUMBER: print(ord('a')) print(ord('D')) #J. ASCII TO CHARACTER NUMBER: print(chr(97)) print(chr(22)) '''
bf66f636f476c0610625d54d5ebb6ec4c0111b05
firoj1705/git_Python
/V5.py
1,003
4.0625
4
''' 1. INPUTS IN PYTHON: s=input('Enter String: ') print(s) n=int(input("Enter Number: ")) print(n) f=float(input('Enter Floating point number: ')) print(f) 2. LOOPS IN PYTHON: A. if-elif-else ladder: Single if statement has multiple elif statements. n%5=Buzz n%3=Fizz n%3,5=FizzBuzz n=int(input("Enter Number: ")) if n%3==0 and n%5==0: print('FizzBuzz') elif n%3==0: print('Fizz') elif n%5==0: print('Buzz') else: print('Number is not divisible by 3,5') B. Range Function in Python: a. range(10): b. range(1,10): c. range(0,10,2): d. range(10,2,-1): for i in range(10): print(i) for i in range(20,0,-3): print(i) C. for loop in Pyhton: for i in range(1,101): if i%3==0 and i%5==0: print('FizzBuzz') elif i%3==0: print('Buzz') elif i%5==0: print('Fizz') else: print(i, 'is not divisible by 3,5') ''' for i in range(1,6): print(" "*(5-i)+'*'*i+"*"*(i-1))
b18609cde09810784b1c2ce40381ee7ab7ee6d43
samaro19/Random_Code
/decode_ceaser.py
717
3.859375
4
dict = { -2: '!', -1: '?', 0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', } message = input("input text to decode: ") three_back = [] decoded = [] if message != '': message = message.split(", ") print(message) for msg1 in message: three_back.append(int(msg1) - 3) print(three_back) for msg in three_back: print(dict[int(msg)]) decoded.append(dict[int(msg)]) print(" ") print(''.join(decoded))
54202c7d5234ff5bad17419c664f9d479615cef5
samaro19/Random_Code
/l_system_hilbert_curve.py
510
3.96875
4
import turtle turtle.penup() turtle.sety(00) turtle.pendown() turtle.hideturtle() turtle.tracer(20, 1) def str_rep(x): y = "" for xs in x: if xs == "A": y += "BF+AFA+FB-" elif xs == "B": y += "AF-BFB-FA+" else: y += xs return y def iterate(x, t): for i in range(t): x = str_rep(x) return x g = iterate("A",10) for gs in g: if gs == "F": turtle.forward(1) elif gs == "-": turtle.left(90) elif gs == "+": turtle.right(90) print(g) turtle.exitonclick()
38932f838745fff4b086d05c8b7b00802133bd22
samaro19/Random_Code
/polyalphabetic_cypher 1.0.py
818
3.78125
4
ALPHABET = { '!': -2, '?': -1, ' ': 0, 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26, } keyinp = input("Key word: ") leng = len(keyinp) key = [] for let in keyinp: lowerCasekey = let.lower() key.append(ALPHABET[lowerCasekey]) word = input("Word: ") enc = [] var = 0 if word != '': word.split() for msg in word: lowerCase = msg.lower() print(ALPHABET[lowerCase]) enc.append(int(ALPHABET[lowerCase]) + int(key[var])) var = var + 1 if var > leng: var = 0 enc = str(enc) print(" ") print(enc)
13ca3b030032cf5763a584614ee169d436145fb9
TroyeWlb/testProjects
/ifelse.py
1,207
3.8125
4
# price = float(input("价格")) # weight = float(input("重量")) # total = price * weight # print("合计 %.02f元 " % total) # name = input("name") # print("我的名字叫 %s,请多多关照" % name) # student_no = int(input("No.")) # print("我的学号是 %09d" % student_no) # scale = float(input("age")) # if scale >= 18: # print("welcome") # else: # print("go away") # print(1+2) # age = int(input("age")) # if age <= 18: # print("请叫家长") # if age == 17: # print("请明年再来") # elif age == 16: # print("请后年再来") # elif age <= 15: # print("回家去吧") # else: # hight = int(input("请输入身高 ")) # if hight > 160: # print("来吧") # else: # print("你太高了,有 %d 公分高" % hight) is_employee = True if not is_employee: print("go away") else: nummber = input("No. ") if len(nummber) == 4: if nummber[0] == "1": print("请去一楼") elif nummber[0] == "2": print("请去二楼") elif nummber[0] == "3": print("请去三楼") else: print("go away") else: print("go away !")
4c7fede5166a8852646ab41c41033e4d40be3c13
mohanbabu2706/testrepo
/2020/october/1/2-Oct/log2 and log10.py
255
3.609375
4
#importing "math" for mathematical operations import math #returnig log2 of 16 print("The value of log2 of 16 is:",end="") print(math.log2(16)) #returning the log10 of 10000 print("The value of log10 of 10000 is:",end="") print(math.log10(10000))
655468222209a0a6151c576027827d12c1082ad6
mohanbabu2706/testrepo
/2020/october/1/1-Oct/reverse string.py
194
4.09375
4
def string_reverse(str1): rstr = '' index = len(str1) while index>0: rstr1 += str1[index-1] index = index-1 return str1 print(string_reverse('1234abcd'))
9d72e56c01ac55832f7caa24afb7d32e39dde8b3
gc2321/Coursera_PC_1
/week2_2048_full.py
6,987
3.625
4
""" Clone of 2048 game. """ import poc_2048_gui, random # Directions, DO NOT MODIFY UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # Offsets for computing tile indices in each direction. # DO NOT MODIFY this dictionary. OFFSETS = {UP: (1, 0), DOWN: (-1, 0), LEFT: (0, 1), RIGHT: (0, -1)} def slide(line, val): """ Function that slide tiles to the front """ _original_list = line _new_list = [] # slide all non-zero value to the front if val == 1: for item in _original_list: if item!=0: _new_list.append(item) for item in _original_list: if item==0: _new_list.append(item) else: for item in _original_list: if item==0: _new_list.append(item) for item in _original_list: if item!=0: _new_list.append(item) # return new list return _new_list def combine(line, val): """ Function that combine adjust value if they are the same """ _original_list = line _new_list = _original_list # reverse list val !=1 if val!=1: _original_list= _original_list[::-1] # find paired tiles item = 0 while item <=(len(_original_list)-1): if item<=(len(_original_list)-2): if _original_list[item]==_original_list[item+1]: _new_list[item] = _original_list[item]*2 _new_list[item+1] = 0 item += 2 else: _new_list[item] = _original_list[item] item +=1 else: _new_list[item] = _original_list[item] item +=1 if val!=1: _new_list= _new_list[::-1] return _new_list def merge(line, val): """ Helper function that merges a single row or column in 2048 """ _original_list = line _new_list = [] _new_list = slide(_original_list, val) _new_list = combine(_new_list, val) _new_list = slide(_new_list, val) # return new list return _new_list class TwentyFortyEight: """ Class to run the game logic. """ def __init__(self, grid_height, grid_width): self._grid_height = grid_height self._grid_width = grid_width self._grid = [[row + col for col in range(self._grid_width)] for row in range(self._grid_height)] # make every cell = 0 for row in range(self._grid_height): for column in range(self._grid_width): self._grid[row][column] = 0 def reset(self): """ Reset the game so the grid is empty except for two initial tiles. """ for row in range(self._grid_height): for column in range(self._grid_width): self._grid[row][column] = 0 fill_cell = 0 while (fill_cell <2): self.new_tile() fill_cell +=1 def __str__(self): """ Return a string representation of the grid for debugging. """ #return str(self._grid) return str([x for x in self._grid]).replace("],", "]\n") def get_grid_height(self): """ Get the height of the board. """ return self._grid_height def get_grid_width(self): """ Get the width of the board. """ return self._grid_width def move(self, direction): """ Move all tiles in the given direction and add a new tile if any tiles moved. """ # copy grid before move _grid_before = [[row + col for col in range(self._grid_width)] for row in range(self._grid_height)] for row in range(self._grid_height): for col in range(self._grid_width): _grid_before[row][col] = 0 _grid_before[row][col] = self._grid[row][col] _direction = direction self._direction = OFFSETS[_direction] if (self._direction[1]==1 or self._direction[1]==-1): for row in range(self._grid_height): _old_list = [] for col in range(self._grid_width): _old_list.append(self._grid[row][col]) if (self._direction[1]==-1): _new_list = merge(_old_list, 2) else: _new_list = merge(_old_list, 1) for col in range(self._grid_width): self._grid[row][col] = _new_list[col] else: for col in range(self._grid_width): _old_list = [] for row in range(self._grid_height): _old_list.append(self._grid[row][col]) if (self._direction[0]==-1): _new_list = merge(_old_list, 2) else: _new_list = merge(_old_list, 1) for row in range(self._grid_height): self._grid[row][col] = _new_list[row] # compare grid before and after _move_happen = 0 for row in range(self._grid_height): for col in range(self._grid_width): if (_grid_before[row][col] != self._grid[row][col]): _move_happen +=1 print "Move happen"+str(_move_happen) # add new tile if there is a empty cell and move happened _empty = 0 for row in range(self._grid_height): for col in range(self._grid_width): if (self._grid[row][col]==0): _empty += 1 break if(_empty!=0 and _move_happen!=0): self.new_tile() def new_tile(self): """ Create a new tile in a randomly selected empty square. The tile should be 2 90% of the time and 4 10% of the time. """ fill_cell = 0 while (fill_cell <1): row = random.randrange(self._grid_height) col = random.randrange(self._grid_width) if (self._grid[row][col]==0): val = random.choice([2,2,2,2,2,2,2,2,2,4]) self._grid[row][col] = val fill_cell +=1 def set_tile(self, row, col, value): """ Set the tile at position row, col to have the given value. """ self._grid[row][col]=value def get_tile(self, row, col): """ Return the value of the tile at position row, col. """ return self._grid[row][col] poc_2048_gui.run_gui(TwentyFortyEight(4, 5))
3303ed1dceb6078ee7f6770b67dcf3fefd24a99b
saedmansour/University-Code
/Artificial Intelligence/final_competition/myGraph.py
6,492
3.734375
4
################################# ## ## ## Graph Search Algorithms ## ## ## ################################# # This file contains the basic definition of a graph node, and the basic # generic graph search on which all others are based. # The classes defined here are: # - Node # - GraphSearch # - Graph Search # - Breadth-First Graph Search # - Depth-First Graph Search # - Iterative Depening Search from algorithm import SearchAlgorithm from utils import * from utils import infinity import time ########################## ## Graph Definition ## ########################## # These are used for graphs in which we know there are no two routes to the # same node. class Node: ''' A node in a search tree used by the various graph search algorithms. Contains a pointer to the parent (the node that this is a successor of) and to the actual state for this node. Note that if a state is arrived at by two paths, then there are two nodes with the same state. Also includes the action that got us to this state, and the total path_cost (also known as g) to reach the node. Other functions may add an f and h value; see BestFirstGraphSearch and AStar for an explanation of how the f and h values are handled. ''' def __init__(self, state, parent=None, action=None, path_cost=0): ''' Create a search tree Node, derived from a parent by an action. ''' self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.depth = 0 if parent: self.depth = parent.depth + 1 def __cmp__(self, other): ''' The comparison method must be implemented to ensure deterministic results. @return: Negative if self < other, zero if self == other and strictly positive if self > other. ''' return cmp(self.getPathActions(), other.getPathActions()) def __hash__(self): ''' The hash method must be implemented for states to be inserted into sets and dictionaries. @return: The hash value of the state. ''' return hash(tuple(self.getPathActions())) def __str__(self): return "<Node state=%s cost=%s>" % (self.state, self.path_cost) def __repr__(self): return str(self) def getPath(self): ''' Returns a list of nodes from the root to this node. ''' node = self path = [] while node: path.append(node) node = node.parent path.reverse() return path def getPathActions(self): ''' Returns a list of actions ''' node_path = self.getPath() actions = [node.action for node in node_path] return actions[1:] # First node has no action. def expand(self): ''' Return a list of nodes reachable from this node. ''' def path_cost(action): return self.path_cost + action.cost successors = self.state.getSuccessors() return [Node(next, self, act, path_cost(act)) for (act, next) in successors.items()] ################################# ## Graph Search Algorithms ## ################################# # This is the base implementation of a generic graph search. class GraphSearch (SearchAlgorithm): ''' Implementation of a simple generic graph search algorithm for the Problem. It takes a generator for a container during construction, which controls the order in which open states are handled (see documentation in __init____). It may also take a maximum depth at which to stop, if needed. ''' def __init__(self, container_generator,time_limit=infinity, max_depth=infinity): ''' Constructs the graph search with a generator for the container to use for handling the open states (states that are in the open list). The generator may be a class type, or a function that is expected to create an empty container. This may be used to effect the order in which to address the states, such as a stack for DFS, a queue for BFS, or a priority queue for A*. Optionally, a maximum depth may be provided at which to stop looking for the goal state. ''' self.container_generator = container_generator self.max_depth = max_depth self.limit=time_limit #<new>SAED: timesToRun is for A* with limited steps.</new> def find(self, problem_state, heuristic=None, timesToRun=infinity): ''' Performs a full graph search, expanding the nodes on the fringe into the queue given at construction time, and then goes through those nodes at the order of the queue. If a maximal depth was provided at construction, the search will not pursue nodes that are more than that depth away in distance from the initial state. @param problem_state: The initial state to start the search from. @param heuristic: Ignored. ''' open_states = self.container_generator() closed_states = {} open_states.append(Node(problem_state)) #<new> safty_time=0.3 if(len(problem_state.robots)==5): safty_time = 0.7 if(len(problem_state.robots)>5): safty_time=2.5 i = 0 start=time.clock() #</new> while open_states and len(open_states) > 0: node = open_states.pop() if(self.limit -(time.clock()-start) <= safty_time ): return -1 #<new> if i >= timesToRun: return (0,node.getPathActions(),node.state) #current state to continue from i = i + 1 #</new> if node.depth > self.max_depth: continue if node.state.isGoal(): #print node.state return node.getPathActions() if (node.state not in closed_states) or (node.path_cost < closed_states[node.state]): closed_states[node.state] = node.path_cost open_states.extend(node.expand()) #print node.state return None
288f226242b46fc371d12df7f9dcfb7166f6d46b
whg/DfPaI
/week3/examples/exception-example.py
108
3.640625
4
text = input() try: number = int(text) print(number + 1) except: print("that's not a number!")
c7eebd9b9319084b280308ea931083fba6a4f222
chorton2227/dailyprogrammer
/challenge_86/intermediate/program.py
601
3.734375
4
import sys import math from datetime import date if len(sys.argv)==1: print 'Enter arguments' exit(0) days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] day = int(sys.argv[1]) month = int(sys.argv[2]) year = sys.argv[3] T = int(year[2:]) if T & 1: T += 11 T /= 2 if T & 1: T += 11 T = 7 - (T % 7) cent = int(year[:-2]) + 1 anchor = ((5 * cent + ((cent - 1) / 4)) % 7 + 4) % 7 doomsday = (anchor + T) % 7 year = int(year) search_date = date(year, month, day) doomsday_date = date(year, 4, 4) print days[(doomsday + (search_date - doomsday_date).days) % 7]