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
a3deec695cf0473ccb80c3e77f6c0b57fd07699d
KKGar/password-retry
/password.py
251
4.09375
4
password = 'a123456' i = 3 # remaining times while i > 0: pwd = input('Please enter the password: ') if pwd == password: print('Log in success!') break #逃出迴圈 else: i = i - 1 print('Password is incorrect! Remaining', i,'times')
8e5bb430d0352a3e305918fce800455d78938e3f
LorenzoSacchi/Blackjack
/BlackJack.py
3,614
4.15625
4
import random import console #Class that creates a single card class Card: """ create one card methods: Onecard - return the card design OneValue - return the card actual value """ def __init__(self,card,value,sign): self.card = card self.value = value self.sign = sign def OneCard(self): if self.value == 11: thecard = ' ---\n|'+ self.sign +' |\n| ' + 'J' + ' |\n| '+ self.sign +'|\n ---' self.value = 10 elif self.value == 12: thecard = ' ---\n|'+ self.sign +' |\n| ' + 'Q' + ' |\n| '+ self.sign +'|\n ---' self.value = 10 elif self.value == 13: thecard = ' ---\n|'+ self.sign +' |\n| ' + 'K' + ' |\n| '+ self.sign +'|\n ---' self.value = 10 elif self.value == 1: thecard = ' ---\n|'+ self.sign +' |\n| ' + 'A' + ' |\n| '+ self.sign +'|\n ---' self.value = 11 else: thecard = ' ---\n|'+ self.sign +' |\n| ' + self.card + ' |\n| '+ self.sign +'|\n ---' return thecard def OneValue(self): thevalue = self.value return thevalue #Create the entire deck, each card is an object in the array class Deck: """ create a list of object, ecah one is a card methods: Shuffle - shuffle deck """ def __init__(self): self.CompleteDeck = [] decksigns = {'Hearts': 'h', 'Diamonds': 'd', 'Clubs': 'c', 'Spades': 's'} deckvocabulary = {'Ace': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Eleven': 11, 'Twelve': 12, 'Thirteen': 13} for signs in decksigns: for singlecard in deckvocabulary: self.CompleteDeck.append(Card(str(deckvocabulary[singlecard]),deckvocabulary[singlecard],decksigns[signs])) def __str__(self): return self.CompleteDeck def Shuffle(self): random.shuffle(self.CompleteDeck) class Game: """ handle the game and each turn request if pass or hit. exit handles the win-lose-continue """ def __init__(self,chips,bet): self.chips = chips self.bet = bet def Interface(self): return print(f'--- Blackjack ---\nChips: {self.chips}\nCurrent bet: {self.bet}') def Outcome(): self class Player: """ handle players turn and amount of money, and bet """ def __init__(self,chips=100, bet=0,hand=[]): self.chips = chips self.bet = bet self.hand = hand def Bet(self): self.chips -= self.bet player = [self.chips,self.bet] return player def Hand(self): pass def Hit(): pass def Pass(): class Starting: """ starts the game, restarts, exits, refreshes screen. import setting as save-restore game on ini file reset game handle interface """ def start(): pass class Hand: """ create each player's hand add his cards if hit #here starts the main #use main definition. improve interface #create deck and show card and value #deck = Deck() #print(f'{deck.CompleteDeck[0].OneCard()} {deck.CompleteDeck[0].OneValue()}') #deck.Shuffle() #print(f'{deck.CompleteDeck[0].OneCard()} {deck.CompleteDeck[0].OneValue()}') #start player and its basic amount, pass bet (more than one) #play = Player(102, 5) #play.Bet() #print(f'{play.chips} {play.bet}') #play = Player(play.chips,3) #play.Bet() #print(f'{play.chips} {play.bet}') #interface #game = Game(play.chips,play.bet) #game.Interface() #clear interface #console.clear() #create a hand by adding cards from the top of the deck #obj= [] #obj.append(deck.CompleteDeck.pop()) #obj.append(deck.CompleteDeck.pop()) #print(obj[0].OneCard()) #print(obj[1].OneCard()) #print(f'{obj[0].OneValue()}') #print(f'{obj[1].OneValue()}') #print(f'total = {int(obj[0].OneValue()) + int(obj[1].OneValue())}')
67306a05d7e23c8080d519e2dcb0c4a0537213ce
RicHz13/PythonExercices
/C38Decoradores.py
815
3.609375
4
#Un decorador es una función que recibe otra función y regresa una 3er función #Para reconocer un decorador, puedes ver que tiene un arroba sobre la declaración de una función #Útil para definir si una función debe ejecutarse o no. #Por ejemplo: #En servidores web, existen ciertas funciones que nada más deben ejecutarse si un usuario #se encuentra autenticado #NOTA: buscar más información de docoradores def protected(func): def wrapper(password): if password == 'platzi': return func() else: print('La contraseña es incorrecta') return wrapper @protected def protected_func(): print('Tu contraseña es correcta') if __name__ == '__main__': password = str(input('Ingresa tu contraseña: ')) protected_func(password)
e44ce833e21fb6c607eb82ea1d6bf7c977130803
sunzhqiiang888/KingSun
/kyo/python/1_function/a_decorator.py
790
3.546875
4
#!/usr/bin/env python3 def p(func): def inner(s): return '<p>' + func(s) + '</p>' return inner def tag(*args, name='p', **kwargs): def _tag(func): def inner(*args, **kwargs): return '<%s>%s</%s>' % (name, func(*args, **kwargs), name) return inner return _tag @tag(name='html') @tag(name='body') @tag(name='div') @tag() # @p def text(s): return '<span>%s</span>' % s @tag(name='p') def hello(s): return "hello %s" % s # @tag(name="div") # def text(): # 以上两行代码相当于: text = tag(name='div')(text) # @p # def text() # 以上两行代码相当于: text = p(text) if __name__ == "__main__": def main(): print(tag(name='div')(hello)('Decorator')) print(text("hello world")) main()
1e0eba1b1d893f30cf932c055ec6c045cdeabdc2
formation2020/slides
/python/examples/csv/read_monty.py
156
3.609375
4
import csv file = 'examples/csv/monty_python.csv' with open(file) as fh: rd = csv.DictReader(fh, delimiter=',') for row in rd: print(row)
f28ad6190f69c963252dc8e7aec243c712456be4
weychi/yzu_python
/lesson01/Hello.py
112
3.5625
4
import random y = 0 x = 0; while 1 : x = random.randint(1,9) print(x) if(x % 2 == 0): break;
5a7bceae3d0902d73892722b07ae62b2d70fe178
JuanCaychoPaucar/codigo-virtual-4-backend
/Semana1/dia2/02-transformar-tipos.py
131
3.515625
4
# Ingresar valores edad = input("Ingresa tu edad: ") print(edad) print(type(edad)) edadEntero = int(edad) print(type(edadEntero))
408327743480555c58f3e579f0dc0e3b8db75fdb
aboucaud/adventofcode2017
/day04/day04.py
1,448
3.90625
4
""" """ from typing import List from collections import Counter def valid_passphrase(phrase: str) -> bool: counter = Counter(phrase.split()) for val in counter.values(): if val > 1: return False return True assert valid_passphrase("aa bb cc dd ee") assert not valid_passphrase("aa bb cc dd aa") assert valid_passphrase("aa bb cc dd ee aaa") def count_valid(passphrases: List[str]) -> int: return sum(valid_passphrase(phrase) for phrase in passphrases) # Part 2 # ------ def valid_passphrase_anagram(phrase: str) -> bool: """ Trick for anagrams : sorted words are the same """ words = phrase.split() word_set = set(tuple(sorted(word)) for word in words) return len(words) == len(word_set) assert valid_passphrase_anagram("abcde fghij") assert not valid_passphrase_anagram("abcde xyz ecdab") assert valid_passphrase_anagram("a ab abc abd abf abj") assert valid_passphrase_anagram("iiii oiii ooii oooi oooo") assert not valid_passphrase_anagram("oiii ioii iioi iiio") def count_valid_stronger(passphrases: List[str]) -> int: return sum(valid_passphrase(phrase) & valid_passphrase_anagram(phrase) for phrase in passphrases) if __name__ == '__main__': with open('day04_input.txt', 'r') as f: PASSPHRASES = f.read().splitlines() print("Count:", count_valid(PASSPHRASES)) print("Count 2:", count_valid_stronger(PASSPHRASES))
c92135011c07f2a07c56126662f52b2cb48db010
aboucaud/adventofcode2017
/day24/day24.py
1,538
4
4
""" http://adventofcode.com/2017/day/24 """ from typing import List def parse_input(input: List[str]) -> List[List[int]]: return [list(map(int, line.split('/'))) for line in input] def build_bridges(parts, pin, bridge): available_parts = [part for part in parts if pin in part] # print(f'Available parts = {available_parts}') if not available_parts: return [bridge] # print(f"bridge = {bridge}") output = [] for part in available_parts: # print(f'Trying part {part}') parts_left = parts[:] parts_left.remove(part) pins = part[:] pins.remove(pin) # print(f'output = {output}') output += build_bridges(parts_left, pins[0], bridge + [part]) return output def strength(input, longest=False): parts = parse_input(input) bridges = build_bridges(parts, pin=0, bridge=[]) scores = [sum([sum(part) for part in b]) for b in bridges] if longest: bridge_length = [len(b) for b in bridges] return max([(length, score) for length, score in zip(bridge_length, scores)]) return max(scores) TEST = """0/2 2/2 2/3 3/4 3/5 0/1 10/1 9/10""".splitlines() assert strength(TEST[:]) == 31 assert strength(TEST[:], longest=True)[1] == 19 if __name__ == '__main__': with open('day24_input.txt', 'r') as f: INPUT = f.read().splitlines() print("Max strength :", strength(INPUT[:])) print("Max length, strength :", strength(INPUT[:], longest=True))
5ba21c48abe1d3dc5f53f901e36423a69cb8a59a
Connor24601/Othello
/othelloPlayers.py
4,944
4.0625
4
import othelloBoard from typing import Tuple, Optional '''You should modify the chooseMove code for the ComputerPlayer class. You should also modify the heuristic function, which should return a number indicating the value of that board position (the bigger the better). We will use your heuristic function when running the tournament between players. Feel free to add additional methods or functions.''' class HumanPlayer: '''Interactive player: prompts the user to make a move.''' def __init__(self,name,color): self.name = name self.color = color def chooseMove(self,board): while True: try: move = eval('(' + input(self.name + \ ': enter row, column (or type "0,0" if no legal move): ') \ + ')') if len(move)==2 and type(move[0])==int and \ type(move[1])==int and (move[0] in range(1,9) and \ move[1] in range(1,9) or move==(0,0)): break print('Illegal entry, try again.') except Exception: print('Illegal entry, try again.') if move==(0,0): return None else: return move def heuristic(board) -> int: '''the heuristic that's used''' return movesHeuristic(board) def basicHeuristic(board) -> int: '''This very silly heuristic just adds up all the 1s, -1s, and 0s stored on the othello board.''' sum = 0 for i in range(1,othelloBoard.size-1): for j in range(1,othelloBoard.size-1): sum += board.array[i][j] return sum def edgeHeuristic(board) -> int: '''values edges and corners more''' total = 0 for i in range(1,othelloBoard.size-1): for j in range(1,othelloBoard.size-1): factor = 1 if i == 1 or i == 8: factor += .3 if j==1 or j==8: factor += .3 total += board.array[i][j] * factor return total def movesHeuristic(board) -> int: '''this just works?''' return len(board._legalMoves(1))-len(board._legalMoves(-1)) class ComputerPlayer: '''Computer player: chooseMove is where the action is.''' def __init__(self,name,color,heuristic,plies) -> None: self.name = name self.color = color self.heuristic = heuristic self.plies = plies def minimax(self, board, depth, isMax): if not board._legalMoves(self.color) or not depth: return (None,self.heuristic(board)) best = (None,(-1)**isMax * 1E10) # get rekt dave for move in board._legalMoves(isMax * 2 - 1): possibleMove = self.minimax(board.makeMove(*move,isMax * 2 - 1),depth-1, not isMax) if isMax and possibleMove[1] > best[1]: best = (move,possibleMove[1]) elif (not isMax) and possibleMove[1] < best[1]: best = (move,possibleMove[1]) return best # chooseMove should return a tuple that looks like: # (row of move, column of move, number of times heuristic was called) # We will be using the third piece of information to assist with grading. def chooseMove(self,board) -> Optional[Tuple[int,int,int]]: '''This very silly player just returns the first legal move that it finds.''' return self.minimax(board,self.plies,(self.color+1) and True)[0] class ComputerPlayerPruning: def __init__(self,name,color,heuristic,plies) -> None: self.name = name self.color = color self.heuristic = heuristic self.plies = plies def minimax(self, board, depth, isMax,a,b): if not board._legalMoves(self.color) or not depth: return (None,self.heuristic(board)) best = (None,(-1)**isMax * 1E10) # get rekt dave for move in board._legalMoves(isMax * 2 - 1): possibleMove = self.minimax(board.makeMove(*move,isMax * 2 - 1),depth-1, not isMax,a,b) if isMax and possibleMove[1] > best[1]: best = (move,possibleMove[1]) a = max(best[1],a) elif (not isMax) and possibleMove[1] < best[1]: best = (move,possibleMove[1]) b = min(best[1],b) if isMax and b <= best[1]: return best if (not isMax) and a >= best[1]: return best return best # chooseMove should return a tuple that looks like: # (row of move, column of move, number of times heuristic was called) # We will be using the third piece of information to assist with grading. def chooseMove(self,board) -> Optional[Tuple[int,int,int]]: '''This very silly player just returns the first legal move that it finds.''' return self.minimax(board,self.plies,(self.color+1) and True, -1E10, 1E10)[0]
cc026974c3ce14ebbe67a6d488275473762a00b7
sasogeek/ContactManager
/add_delete_search_contacts.py
658
3.765625
4
from contacts import Contacts add_delete_search_contact_ = True phone_book = Contacts() while add_delete_search_contact_: check = input('Add/Delete/Search/Quit a contact? a/d/s/q ') if check == 'a': contact = phone_book.add_contact() add_delete_search_contact_ = True elif check == 'd': contact = input('Name of contact to delete: ') phone_book.delete_contact(contact) add_delete_search_contact_ = True elif check == 's': contact = input('Name of contact to search: ') phone_book.search_contact(contact) add_delete_search_contact_ = True elif check == 'q': break
dba0492edad611c00d9d0009778881147a7d42ef
Geeorgee23/Socios_cooperativa_MVC
/main.py
2,652
3.671875
4
from socios import Socios from controlador import Controlador from datetime import datetime controlador = Controlador() while True: print("Actualmente hay ",controlador.numSocios()," socios") print("1.- Añadir Socio") print("2.- Eliminar Socio") print("3.- Listar Socios") print("4.- Registrar Productos") print("5.- Actualizar Saldo") print("6.- Ficha de Socio") print("7.- Salir") while True: try: op=int(input("Introduce opción:")) if op>=1 and op<=7: break else: print("Introduce un numero del 1 al 7!") except ValueError: print("Introduce un numero!") if op==7: break if op==1: print() id_socio=input("Introduce el id del socio: ") dni=input("Introduce el dni del socio: ") nombre=input("Introduce el nombre del socio: ") apellidos=input("Introduce los apellidos del socio: ") fecha= datetime.now() hoy = str(fecha.strftime("%d-%m-%Y")) socio = Socios(id_socio,dni,nombre,apellidos,hoy) if controlador.addSocio(socio): print("Socio añadido correctamente!") else: print("Error al añadir el socio!") print() if op==2: print() id_socio=input("Introduce el id del socio a eliminar: ") if controlador.delSocio(id_socio): print("Socio eliminado correctamente!") else: print("Error al eliminar el socio!") print() if op ==3: print() print("Socios: ") for i in controlador.listarSocios(): print(i) print() if op ==4: print() print("Registrando productos...") id_socio=input("Introduce el id del socio: ") print("Productos:") print(controlador.getProductos()) producto=input("Introduce el nombre del producto: ") kilos=input("Introduce el numero de kilos: ") if controlador.addProducto(id_socio,producto,kilos): print("Producto añadido correctamente!") else: print("Error al añadir el producto!") print() if op ==5: print() id_socio=input("Introduce el id del socio: ") if controlador.actualizaSaldo(id_socio): print("Saldo actualizado correctamente!") else: print("Error al actualizar saldo!") print() if op==6: print() id_socio=input("Introduce el id del socio: ") print(controlador.fichaSocio(id_socio)) print()
9d4191a3fc0688dafe61bb3a4ee4c6e9e7ae11ba
jarvisteach/appJar
/docs/Lessons/topics/recursion/adjList.py
305
3.765625
4
# list of lists adjLists = [ [1,2], [2,3], [4], [4,5], [5], [] ] # testing print("Neighbors of vertex 0: ", adjLists[0]) print("Neighbors of vertex 3: ", adjLists[3]) print("\nPrint all adjacency lists with corresponding vertex") n = len(adjLists) for v in range(0,n): print(v, ":", adjLists[v])
56b0bc0cf840fe0849e3b7d287b4245feb49335d
jarvisteach/appJar
/docs/Lessons/topics/records/sample1.py
220
3.515625
4
bob = ('Bob', 30, 'male') print( 'Representation:', bob) jane = ('Jane', 29, 'female') print( '\nField by index:', jane[0]) print( '\nFields by index:') for p in [ bob, jane ]: print( '%s is a %d year old %s' % p)
6bf26142b6bc5d22a478e606a1371fcf2c44ccac
jarvisteach/appJar
/docs/Lessons/topics/records/sample2.py
413
3.5625
4
import collections # create the record, Person = collections.namedtuple ('Person', 'name age gender') print( 'Type of Person:', type(Person)) bob = Person(name='Bob', age=30, gender='male') print( '\nRepresentation:', bob) jane = Person(name='Jane', age=29, gender='female') print( '\nField by name:', jane.name) print( '\nFields by index:') for p in [ bob, jane ]: print( '%s is a %d year old %s' % p)
8d46136a978666dc1a21b64df14ca92edaa39c14
chaudharyachint08/Multiple-Sequence-Alignment
/Codes/LCS_Overlap.py
3,225
3.59375
4
# Dynamic Programming implementation of LCS problem import time import IP import DNA def lcs(X , Y): # find the length of the strings m = len(X) n = len(Y) # declaring the array for storing the dp values L = [[0 for x in range(n+1)] for x in range(m+1)] """Following steps build L[m+1][n+1] in bottom up fashion Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]""" for i in range(m+1): for j in range(n+1): if i == 0 or j == 0 : L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1]+1 else: L[i][j] = max(L[i-1][j] , L[i][j-1]) # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] return L[m][n] #end of function lcs1 def lcs2(X, Y, m, n): L = [[0 for x in range(n+1)] for x in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # Following code is used to print LCS index = L[m][n] # Create a character array to store the lcs string lcs = [""] * (index+1) lcs[index] = "\0" # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] i = m j = n while i > 0 and j > 0: # If current character in X[] and Y are same, then # current character is part of LCS if X[i-1] == Y[j-1]: lcs[index-1] = X[i-1] i-=1 j-=1 index-=1 # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i-=1 else: j-=1 #print ( 'LCS Found is',"".join(lcs) ) #end of function lcs2 # Driver program to test the above function print('Length\t|LCS|\t|CLCS| \t Fractional Overhead\t LCS%\t\t CLCS%') for L in range(3,14): X = IP.X[:2**L] Y = IP.Y[:2**L] #X = DNA.st #Y = X[::-1] #X='0123456789' #Y='5678901234' #X=''.join(chr(i) for i in range(ord('a'),ord('z')+1))+''.join(chr(i) for i in range(ord('A'),ord('Z')+1)) #Y=''.join(chr(i) for i in range(ord('A'),ord('Z')+1))+''.join(chr(i) for i in range(ord('a'),ord('z')+1)) #print('X=',X,'\nY=',Y) init = time.clock() #print( "Length of LCS is ", lcs(X, Y) ) r1 = lcs(X,Y) #print( 'Seconds Taken',time.clock() - init ) t1 = time.clock() - init if len(X)<len(Y): X=X*2 else: Y=Y*2 #print(len(X),len(Y)) init = time.clock() #print( "Length of Circular LCS is ", lcs(X, Y) ) r2 = lcs(X,Y) #print( 'Seconds Taken',time.clock() - init ) print('{0:4}\t{1:4} \t{2:4}\t\t{3:.4f}\t\t{4:.4f}%\t{5:.4f}%'.format(2**L,r1,r2,(time.clock() - init)/t1,(100*r1/(2**L)),(100*r2/(2**L))))
c1fe260237f4a694c49c6191271a3d5870241e6f
pawan9489/PythonTraining
/Chapter-3/3.Scopes_1.py
1,353
4.625
5
# Local and Global Scope # Global variable - Variables declared outside of Every Function # Local variable - Variables declared inside of a Function g = 0 # Global Variable def func(): i = 30 # Local Variable print("From Inside Func() - i = ", i) print("From Inside Func() - g = ", g) print('---- Global Variables ---') func() # print(i) # NameError: name 'i' is not defined print("From Outside Func() - g = ", g) print() # Modify Global Variables g = 0 def func1(): g = 10 print("From Inside Func1() - g = ", g) print('---- Modify Global Variables ---') func1() print("From Outside Func1() - g = ", g) print() g = 0 def func2(): global g g = 10 print("From Inside Func2() - g = ", g) print('---- Modify Global Variables ---') func2() print("From Outside Func2() - g = ", g) print() # g = 0 # def outer(): # o = 2 # def inner(): # i = 10 # print("Inner - g", g, id(g)) # print("Inner - i", i, id(i)) # print("Inner - o", o, id(o)) # # Below Code Creates new 'o' variable # # o = 20 # will loose the outer 'o' # # print("Inner - o", o, id(o)) # print("Outer - g", g, id(g)) # print("Outer - o", o, id(o)) # inner() # print("Outer - o", o, id(o)) # print(x) # # Comment x and see failure # x = 'Python' # outer() # # x = 'Python'
b9310befbc4a399a8c239f22a1bc06f7286fedee
pawan9489/PythonTraining
/Chapter-2/4.Sets.py
1,504
4.375
4
# Set is a collection which is unordered and unindexed. No duplicate members. fruits = {'apple', 'banana', 'apple', 'cherry'} print(type(fruits)) print(fruits) print() # Set Constructor # set() - empty set # set(iterable) - New set initialized with iterable items s = set([1,2,3,2,1]) print(s) print() # No Indexing - Since no ordering but we can Loop for fruit in fruits: print(fruit) print() # Membership print("'cherry' in fruits = {0}".format('cherry' in fruits)) print() # Only appending No Updating Items - Since no Indexing # Add items print("Before adding = {0}".format(fruits)) fruits.add('mango') print("fruits.add('mango') = {0}".format(fruits)) print() # Add Multiple items print("Before Multiple adding = {0}".format(fruits)) fruits.update(['orange', 'grapes']) print("fruits.update(['orange', 'grapes']) = {0}".format(fruits)) print() # Length of Set print("len(fruits) = {0}".format(len(fruits))) print() # Remove Item # remove(item) - will throw error if item dont exist # discard(item) - will not throw error if item dont exist print("Before removing = {0}".format(fruits)) fruits.remove('grapes') print("fruits.remove('grapes') = {0}".format(fruits)) print() # pop - remove some random element - Since no Indexing # only pop(), not pop(index) - Since no Indexing print("Before pop = {0}".format(fruits)) print("fruits.pop() = {0}".format(fruits.pop())) print() # clear() print("Before clear = {0}".format(fruits)) fruits.clear() print("fruits.clear() = {0}".format(fruits))
56e43c7c6023db7f49332b69086826f198938b34
pawan9489/PythonTraining
/Chapter-4/6.Magic_OR_Dunder_Methods.py
4,933
3.96875
4
# Magic or Dunder Methods - __Method__ # Meta Object Protocol # Enrich your classes by providing some implementation # Accomplishes a Contract => like Interfaces in C# or Java # Initialization of new objects (__init__) # Object representation (__repr__, __str__) # Enable iteration (__len__, __getitem__, __reversed__) # Operator overloading (comparison) (__eq__, __lt__) # Operator overloading (addition) (__add__) # Method invocation (__call__) # Context manager support (with statement) (__enter__, __exit__) # https://www.python-course.eu/python3_magic_methods.php # https://docs.python.org/3/reference/datamodel.html ''' AIM : Create a Rational Class with below Requirements Rational(18, 12) # 3 / 2 Rational(13, 1) => Rational(13) Should not be able to Create Rational(5, 0) Have a ToString() with Numerator/Denominator form Should be able to do Arithmetic Operators on Rationals r1 + r2 r1 - r2 r1 / r2 r1 * r2 Should be able to do Comparision Operators on Rationals r1 > r2 r1 < r2 r1 >= r2 r1 <= r2 r1 == r2 r2 != r2 Sort List of Rationals ''' class Rational: def __init__(self, p, q): p, q = self.__normalize(p, q) self.numerator = p self.denominator = q @property def numerator(self): return self._numer @numerator.setter def numerator(self, value): if type(value) is int or type(value) is float: self._numer = value else: raise TypeError("Expected only Numeric Values in the Numerator") @property def denominator(self): return self._denom @denominator.setter def denominator(self, value): if type(value) is int or type(value) is float: if value == 0: raise ValueError("Denominator Cannot be Zero.") else: self._denom = value else: raise TypeError("Expected only Numeric Values in the Denominator") # Some may dont want to create rational Numbers as 13 / 1 but just Rational(13) @classmethod # Static and Public def create(cls, numer): return cls(numer, 1) @classmethod # Static and Private def __gcd(cls, a, b): return a if (b == 0) else cls.__gcd(b, a % b) @classmethod # Static and Private def __normalize(cls, p, q): gcd = cls.__gcd(p, q) return (p / gcd, q / gcd) def __str__(self): # Used in Print == .toString(), Pretty Print an Object return "Rational({0})".format(self.numerator) if self.denominator == 1 else "Rational({0} / {1})".format(self.numerator, self.denominator) def __repr__(self): # String Representation of an Object ex: Rational(2 / 3) return "Rational({0})".format(self.numerator) if self.denominator == 1 else "Rational({0} / {1})".format(self.numerator, self.denominator) # r1 + r2 def __add__(self, r): if isinstance(r, Rational): return Rational(self.numerator * r.denominator + self.denominator * r.numerator, self.denominator * r.denominator) elif type(r) is int or type(r) is float: return Rational(self.numerator + self.denominator * r , self.denominator) else: raise TypeError("A Rational can only be added to a Number or other Rational") # r1 - r2 == __sub__ # r1 * r2 == __mul__ # r1 / r2 == __truediv__ # r1 // r2 == __floordiv__ # r1 == r2 def __eq__(self, r): if isinstance(r, Rational): return self.numerator == r.numerator and \ self.denominator == r.denominator elif type(r) is int or type(r) is float: return self.numerator == r and \ self.denominator == 1 else: raise TypeError("A Rational can only be Compared to a Number or other Rational") # r1 < r2 == __lt__ # Enables sort for List<Rational> def __lt__(self, r): if isinstance(r, Rational): return self.numerator * r.denominator < \ self.denominator * r.numerator elif type(r) is int or type(r) is float: return self.numerator < \ self.denominator * r else: raise TypeError("A Rational can only be Compared to a Number or other Rational") # r1 <= r2 == __le__ # r1 != r2 == __ne__ # r1 > r2 == __gt__ # r1 >= r2 == __ge__ r1 = Rational(7 , 9) print("r1", r1) print(Rational(13 , 1)) # r2 = Rational(12) r2 = Rational.create(12) print("r2", r2) # Python Interactive Shell # python -i file_name.py rationals = [Rational(3,4), Rational.create(2), Rational(1, 2)] print(sorted(rationals))
ea4f3b0a569bcc2fd312286f4d44383a2ef6729a
pawan9489/PythonTraining
/Chapter-4/1.Classes_Objects.py
1,641
4.21875
4
''' Class Like Structures in Functional Style: Tuple Dictionary Named Tuple Classes ''' d = dict( name = 'John', age = 29 ) print('- Normal Dictionary -') print(d) # Class Analogy def createPerson(_name, _age): return dict( name = _name, age = _age ) print() print('- Factory Function to Create Dictionaries -') print(createPerson('John', 19)) print(createPerson('Mary', 45)) # What is the Difference between Dictionary or Named Tuple and a Class? class Person: 'Person Class with Name and Age as Properties' def __init__(self, _name, _age): self.name = _name self.age = _age def __str__(self): return "Name - {0}, Age - {1}".format(self.name, self.age) # return ", ".join(map(lambda t: t[0].capitalize() + ' - ' + str(t[1]) # , self.__dict__.items())) print() print('- Using Classes -') p = Person('John', 30) print("p - {0}".format(p)) print(p.name, p.age) print(p.__dict__) # To Prove the Classes are Dictionaries print() print('After Adding a Key') p.job = 'Manager' print("p - {0}".format(p)) print(p.__dict__) del p.job print(p.__dict__) # Getters and Setters print() print(' Getters and Setters ') print(p.age) # Getter p.age = 99 # Setter print(p.age) print() # Generic Getters and Setters # getattr(object, property_name) # setattr(object, property_name, value) print(getattr(p, 'age')) setattr(p, 'age', 70) print(getattr(p, 'age')) # Get all avaliable functions on an Object print() print(dir(p)) print('----') for key in dir(p): print("{0:20} - {1}".format(key, getattr(p, key))) print('----')
df3792581d58282d7a157f748617891b69c94d9c
pawan9489/PythonTraining
/Chapter-2/7.TypeConversions.py
1,515
4
4
# Iterconversions between data structures l = [2, 3, 4, 5, 2] t = ('a', 2, True, -4.5, True) s = {False, 10, 34.5} d = {'a': 1, 'b': 2} print() # List Contructor with multiple Iterables print("list(list) = {0}".format(list(l))) print("list(tuple) = {0}".format(list(t))) print("list(set) = {0}".format(list(s))) print("list(dictionary) = {0}".format(list(d))) print() # Tuple Contructor with multiple Iterables print("tuple(list) = {0}".format(tuple(l))) print("tuple(tuple) = {0}".format(tuple(t))) print("tuple(set) = {0}".format(tuple(s))) print("tuple(dictionary) = {0}".format(tuple(d))) print() # Set Contructor with multiple Iterables print("set(list) = {0}".format(set(l))) print("set(tuple) = {0}".format(set(t))) print("set(set) = {0}".format(set(s))) print("set(dictionary) = {0}".format(set(d))) print() # Dictionary Contructor with multiple Iterables # print("dict(list) = {0}".format(dict(l))) # Error # print("dict(tuple) = {0}".format(dict(t))) # Error # print("dict(set) = {0}".format(dict(s))) # Error print("dict(dictionary) = {0}".format(dict(d))) print("dict(Iterable(tuple_with_2_elements)) = {0}".format(dict([(1,8), (4,9)]))) print() # Type Checking i = 2 f = 2.4 b = True if type(i) is int: print("i is int") if type(f) is float: print("f is float") if type(b) is bool: print("b is bool") if type(l) is list: print("l is list") if type(t) is tuple: print("t is tuple") if type(s) is set: print("s is set") if type(d) is dict: print("d is dictionary")
ca7b96d6389b50e8637507cce32274991e792144
SK7here/learning-challenge-season-2
/Kailash_Work/Other_Programs/Sets.py
1,360
4.25
4
#Sets remove duplicates Text = input("Enter a statement(with some redundant words of same case)") #Splitting the statement into individual words and removing redundant words Text = (set(Text.split())) print(Text) #Creating 2 sets print("\nCreating 2 sets") a = set(["Jake", "John", "Eric"]) print("Set 1 is {}" .format(a)) b = set(["John", "Jill"]) print("Set 2 is {}" .format(b)) #Adding elements print("\nAdding 'SK7' item to both sets") a.add("SK7") b.add("SK7") print("Set 1 after adding 'SK7' : ") print(a) print("Set 2 after adding 'SK7' : ") print(b) #Removing elements del_index = (input("\nEnter the element to be removed in set 1: ")) a.remove(del_index) print("After removing specified element") print(a) #Finding intersection print("\nIntersection between set 1 and set 2 gives : ") print(a.intersection(b)) #Finding items present in only one of the sets print("\nItems present in only one of the 2 sets : ") print(a.symmetric_difference(b)) print("\nItems present only in set a : ") print(a.difference(b)) print("\nItems present only in set b : ") print(b.difference(a)) #Finding union of 2 sets print("\nUnion of 2 sets : ") print(a.union(b)) #Clearing sets print("\nClearing sets 1 and 2") print("Set 1 is {}" .format(a.clear())) print("Set 2 is {}" .format(b.clear()))
fea886cfe9281350bc1efc3dccb996498cb055b8
SK7here/learning-challenge-season-2
/Kailash_Work/MySQL/MySQL_Insert.py
999
4.03125
4
#Package to use MySQL import mysql.connector #Creating a connection and opening the specified DB DB_Name = input("Enter the database name : ") mydb = mysql.connector.connect( host="localhost", user="# Your username #", passwd="# Your password #", database=DB_Name ) #Crating a cursor to execute SQL statements mycursor = mydb.cursor() #Getting inputs from user Table_Name = input("\n\nEnter table name in {} DB to insert values : " .format(DB_Name)) Name = input("Enter Student Name : ") Department = input("Enter Department : ") #SQL query to insert into table sql = "INSERT INTO {} VALUES (%s , %s)" .format(Table_Name) val = ("{}" .format(Name) , "{}" .format(Department)) mycursor.execute(sql, val) #To save changes mydb.commit() print("\n") print(mycursor.rowcount, "record inserted.") #Cross check whether record is inserted mycursor.execute("SELECT * FROM {}" .format(Table_Name)) myresult = mycursor.fetchall() for x in myresult: print(x)
0164661e3480ce4df1f2140c07034b3bb75a6c3b
SK7here/learning-challenge-season-2
/Kailash_Work/Arithmetic/Calculator.py
1,779
4.125
4
#This function adds two numbers def add(x , y): return x + y #This function subtracts two numbers def sub(x , y): return x - y #This function multiplies two numbers def mul(x , y): return x * y #This function divides two numbers def div(x , y): return x / y #Flag variable used for calculator termination purpose #Initially flag is set to 0 flag = 0 #Until the user chooses option 5(Stop), calculator keeps on working while(flag == 0): #Choices displayed print("\n\n\nSelect operation") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") print("5.Stop") #Take input from the user choice = input("\nEnter choice : ") if(choice == '5'): #If user wishes to stop calculator(choice 5), flag is set to 1 flag = 1 #If user has chosen choice 5(stop), control comes out of loop here, failing to satisfy the condition if(flag == 0): num1 = int(input("\nEnter first input : ")) num2 = int(input("Enter second input : ")) #Performing corresponding arithmetic operation if choice == '1': print("\nSum of {} and {} is {}" .format(num1 , num2 , add(num1,num2))) elif choice == '2': print("\nDifference between {} and {} is {}" .format(num1 , num2 , sub(num1,num2))) elif choice == '3': print("\nProduct of {} and {} is {}" .format(num1 , num2 , mul(num1,num2))) elif choice == '4': print("\nDivision of {} and {} is {}" .format(num1 , num2 , div(num1,num2))) else: print("Invalid operation") #Comes out of the loop, if user chooses choice 5(flag is set to '1') print("\nCalculator service terminated")
8a6026e238eba1caa1f9a6c2bdceb2d2784a468d
VantasHe/MLSOM_PD
/test.py
1,168
3.890625
4
import nltk # Import nltk. See www.nltk.org/install.html from nltk.corpus import wordnet as wn # Import WordNet def main(): # Define main function word1 = input('Word1:') # Get input from terminal word2 = input('Word2:') print(cal_similarity(word1, word2)) # Call 'noun_similarity' function and print result def cal_similarity(Word1, Word2): # Define 'noun_similarity', 'Word1' and 'Word2' are the arguments word1 = wn.synsets(Word1) # Get all of the word synsets, by using wn.synsets word2 = wn.synsets(Word2) # and get wordnet synsets List highest_score = 0 # Initialize highest_score highest_pair = [] # Initialize highest_pair list for i in word1: for j in word2: score = i.path_similarity(j) # Calculate the similarity between two synsets if score == None: # If similarity is None, skip to next round continue elif float(score) > highest_score: highest_score = score highest_pair = i, j print('Word1:{0} total {1} synset(s)'.format(Word1, len(word1))) print('Word2:{0} total {1} synset(s)'.format(Word2, len(word2))) return highest_pair, highest_score if __name__ == '__main__': main()
df585dc87cd99c226216f9ad8fec2d2410e5e037
kittytian/learningfishcpy3
/48example.py
796
3.671875
4
''' 一个容器如果是迭代器,那就必须实现__iter__()魔法方法,这个方法实际上就是返回迭代器本身。 接下来重点是要实现的是__next__()魔法方法,因为它决定了迭代的规则 斐波那契数列 需要两个因子 所以在init初始化里面定义一个a一个b ''' class Fibs: def __init__(self): self.a = 0 self.b = 1 #下一个值等于前两个和 def __iter__(self): return self #返回本身 本身是个迭代器 def __next__(self): self.a, self.b = self.b, self.a + self.b return self.a #得到下一个斐波那契数列的值 fibs = Fibs() for each in fibs: if each < 20: #加上判断条件 防止崩溃 一定要跳出循环 print(each) else: break
97862197e15c57c499a8abf7302908d86b38ecdf
kittytian/learningfishcpy3
/digui2.py
1,939
4.09375
4
#回文联 def is_palindrome(n, start, end): # 定义一个函数,三个形参。n为整个字符串内容,start为开始索引位置,end为末尾索引位置。 if start > end: # 如果 start的索引大于末尾索引位置的时,返回真值,表示已经判定过整个字符串了,一开始我也一脸懵逼,后来仔细想想明白了: # 假定字符串有五个长度[0,5],(最好在纸上写下0 1 2 3 4 五个数字) # 当开始索引[2]=末尾索引[2]的时候,双方都指在中间数2这个位置的时候,就已经检查完毕,那为什么要判定大于的情况呢? # 假定字符串有四个长度[0,4]呢?(0 1 2 3),怎么才能索引个遍呢? # 很明显,只有当开始索引[2]>末尾索引[1]的时候,开始指在2,末尾指在1的时候,才算索引个遍,这个大于判定就这么来的。 return 1 # 返回一个真值,(不为零即可,返回几百几千随便。) else: return is_palindrome(n, start + 1, end - 1) if n[start] == n[ end] else 0 # 这个语句判断的就是未完成检查的情况,从字符串0根末尾索引-1比较(不知道为何减一的同学面壁)。 # 依次开始第二位跟倒数第二位,开始第三位跟倒数第三位…… # 不相同的话就返回0,非真,假值。 string = input('请输入一串字符串:') length = len(string) - 1 # 不知道为何减1的同学面壁。 if is_palindrome(string, 0, length): # 这里传入三个实参,如果if为真值,也就是不为零,非真,假值的情况下(不为零的情况下就包含上面函数的判定:1、从头到位的检索,2、字符串的比较是否相等) print('"%s"是回文字符串!' % string) # 是真的情况下打印是回文联 else: print('"%s"不是回文字符串!' % string) # 否则打印不是回文联。
7337c033becfb2c6c22daa18f54df4141ff804ac
kittytian/learningfishcpy3
/33.3.py
1,904
4.5
4
''' 2. 尝试一个新的函数 int_input(),当用户输入整数的时候正常返回,否则提示出错并要求重新输入。% 程序实现如图: 请教1: int_input("请输入一个整数:") 这一句括号里的即是一个形参又是一个输入?为什么? 这一句的括号里不是形参,是实参,传递给了int_input函数 它并不是一个输入,能够作为输入是因为int_input函数中调用了input函数,才有了输入的功能 请教2: def int_input(prompt=''): 这里的我用(prompt)和(prompt='')的结果是一样的,他们有区别吗?如果是(prompt='')的话是什么意思? 第一种(prompt)并没有指定形参的默认值,这样在调用int_input函数时必须带参数,将该参数赋值给了prompt 第二种(prompt='')指定了形参的默认值为空'',这种情况下在调用int_input函数时可以不写参数,比如 a = int_input(), 设置默认参数可以避免调用函数时没有给指定参数传值而引发的错误。 你可以尝试把def int_input(prompt='')和def int_input(prompt)两种情况下调用: x=int_input() 如果没有设置默认参数,程序会报错。 def int_input(prompt=''): 这个就是定义一个函数,名字是int_input,调用这个函数的时候要传入一个参数,这个参数有个名字是prompt,而且规定了默认值为“空” int(input(prompt)) 里面的prompt就是刚才函数定义时传入的变量,然后对这个变量转换成int类型,如果是数字就直接跳出循环了,如果不是数字,会报一个ValueError,然后打印“出错,您输入的不是整数!” ''' def int_input(prompt = ''): while True: try: int(input(prompt)) break except ValueError: print('出错!您输入的不是整数') int_input('请输入一个整数:')
9a509d327d55321e718d06c9fc3ca63f788c96fc
kittytian/learningfishcpy3
/31天气查询.py
1,570
3.765625
4
#31课课堂演示 把原来的city这个字典变成pkl文件 然后加载进来 import urllib.request import json import pickle #建立城市字典 把pkl文件载入 pickle_file = open('city_data.pkl', 'rb') city = pickle.load(pickle_file) password=input('请输入城市:') name1=city[password] header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'} req = urllib.request.Request(url='http://m.weather.com.cn/data/'+name1+'.html',data=None,headers=header) # 接着把File那句改成 File1 = urllib.request.urlopen(req) weatherHTML= File1.read().decode('utf-8')#读入打开的url weatherJSON = json.JSONDecoder().decode(weatherHTML)#创建json weatherInfo = weatherJSON['weatherinfo'] #打印信息 print ( '城市:', weatherInfo['city']) print ('时间:', weatherInfo['date_y']) print ( '24小时天气:') print ('温度:', weatherInfo['temp1']) print ('天气:', weatherInfo['weather1']) print ('风速:', weatherInfo['wind1']) print ('紫外线:', weatherInfo['index_uv']) print ('穿衣指数:', weatherInfo['index_d']) print ('48小时天气:') print ('温度:', weatherInfo['temp2']) print ('天气:', weatherInfo['weather2']) print ('风速:', weatherInfo['wind2']) print ('紫外线:', weatherInfo['index48_uv']) print ('穿衣指数:', weatherInfo['index48_d']) print ('72小时天气:') print ('温度:', weatherInfo['temp3']) print ('天气:', weatherInfo['weather3']) print ('风速:', weatherInfo['wind3']) input ('按任意键退出:')
bb253f977f19bc69c71741e10e2d9f6be1191eea
kittytian/learningfishcpy3
/16.4.py
642
4.21875
4
''' 哎呀呀,现在的小屁孩太调皮了,邻居家的孩子淘气,把小甲鱼刚写好的代码画了个图案, 麻烦各位鱼油恢复下啊,另外这家伙画的是神马吗?怎么那么眼熟啊!?? 自己写的时候注意点 循环 还有判断!!一定要细心 会写 ''' name = input('请输入待查找的用户名:') score = [['米兔', 85], ['黑夜', 80], ['小布丁', 65], ['娃娃', 95], ['意境', 90]] flag = False for each in score:#遍历 if name in each: print(name + '的得分是:', each[1]) flag = True break if flag == False: print('查找的用户不存在')
3817b27e6c6fb3d83cf5b52927ec3566c075451b
kittytian/learningfishcpy3
/23.1.py
664
4.0625
4
''' 1. 写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放到列表中。 举例:get_digits(12345) ==> [1, 2, 3, 4, 5] 看了下答案解题思路:利用除以10取余数的方式,每次调用get_digits(n//10),并将余数存放到列表中即可。要注意的是结束条件设置正确。 自己写: def get_digits(n): list1 = [] if n: list1.append(n % 10) get_digits(n // 10) print(list1) get_digits(12345) 输出[] [1] [2] [3] [4] [5] ''' result = [] def get_digits(n): if n > 0: result.insert(0, n % 10) get_digits(n // 10) get_digits(12345) print(result)
33d0681848619697f3236def10951be9751c43ce
kittytian/learningfishcpy3
/17.0.py
498
4.53125
5
''' 编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值 递归(22课课后题0))和非递归法 def power(x, y): return x ** y print(power(2,3)) 看了答案发现 人家的意思是不用**幂函数 ''' ''' def power(x, y): result = 1 for i in range(y): result *= x return result print(power(2, 3)) ''' def power(x,y): if y: return x * power(x,y-1) else: return 1 print(power(2,3))
032358bb5bd38a079f8c5f0afff079648242fa08
kittytian/learningfishcpy3
/42.1.py
781
4.03125
4
''' 1. 移位操作符是应用于二进制操作数的,现在需要你定义一个新的类 Nstr,也支持移位操作符的运算: #>>> a = Nstr('I love FishC.com!') #>>> a << 3 'ove FishC.com!I l' #>>> a >> 3 'om!I love FishC.c' 字符串切片!! class Nstr(str): def __lshift__(self, other): return self[other:] + self[:other] def __rshift__(self, other): return self[-other:] + self[:-other] ''' class Nstr(str): def __lshift__(self, other): while other > 0: self = self[1:] + self[0] other -= 1 return self def __rshift__(self, other): while other > 0: self = self[-1] + self[:-1] other -= 1 return self a = Nstr('I love FishC.com!') print(a << 5)
ad7e9ef9966439a410c7ab821da2a5ce4c025015
kittytian/learningfishcpy3
/42.2.py
1,370
3.984375
4
''' 2. 定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的 ASCII 码之和进行计算: #>>> a = Nstr('FishC') #>>> b = Nstr('love') #>>> a + b 899 #>>> a - b 23 #>>> a * b 201918 #>>> a / b 1.052511415525114 #>>> a // b 1 和41课第2题一样 class Nstr(int): def __new__(cls, arg=0): if isinstance(arg,str):# 如果arg是字符串 total = 0 # 初始化变量total for each in arg:# 逐一拆分字符串 total += ord(each)# 每一个字符计算ASCII值后逐次相加 arg = total# 将结果total赋值给arg return int.__new__(cls, arg) # 返回父类int的__new__方法 a = Nstr('FishC') b = Nstr('love') print(a + b) ''' class Nstr: def __init__(self, arg=''): if isinstance(arg, str): self.total = 0 for each in arg: self.total += ord(each) else: print("参数错误!") def __add__(self, other): return self.total + other.total def __sub__(self, other): return self.total - other.total def __mul__(self, other): return self.total * other.total def __truediv__(self, other): return self.total / other.total def __floordiv__(self, other): return self.total // other.total
d424d0bf42f28ec2617309e4bcf68dbe66cabd20
kittytian/learningfishcpy3
/36.0.py
404
3.890625
4
''' 0. 按照以下提示尝试定义一个 Person 类并生成类实例对象。 属性:姓名(默认姓名为“小甲鱼”) 方法:打印姓名 提示:方法中对属性的引用形式需加上 self,如 self.name ''' class Person: #属性:姓名(默认姓名为“小甲鱼”) name = '小甲鱼' #方法:打印姓名 def print_name(self): print(self.name)
d4ce6c189534e9f21e702ea84f27cc47de1836fa
kittytian/learningfishcpy3
/factorial_1.py
516
4.09375
4
''' 写一个求阶乘的函数 ---正整数阶乘指从1乘以2乘以3乘以4一直乘到所要求的数。 ---例如所给的数是5,则阶乘式是1×2×3×4×5,得到的积是120,所以120就是4的阶乘 以下是非递归版本 ''' def factorial(n): result = n #注意初始值是n for i in range(1, n): #因为范围是1到n-1 result *= i return result number = int(input('请输入一个正整数:')) result = factorial(number) print("%d 的阶乘是:%d" % (number, result))
8eec822dd11b1f6f1f4453b9a2e2fe40dbfd5cbf
michalmaj/programowanie_aplikacji_w_jezyku_python
/wyk_1/wyk_1_tekst.py
846
3.90625
4
# tak pisząc jest probem, bo każdorazowa zmiana imienia i wieku musi nastąpić w każdym prinie print("był sobie mężczyzna i nazywał się Kłentin") print("miał 55 lat") print("bardzo lubił imie Kłentin") print("ale nie lubił, że ma 55 lat") # pierwsza wersja: utworzenie zmiennych i ich modyfikacja imie = "Kłentin" wiek = 55 print("był sobie mężczyzna i nazywał się " + imie) print("miał" + str(wiek) + " lat")# rzutownie int na str print("bardzo lubił imie " + imie) print("ale nie lubił, że ma " + str(wiek) + " lat")# rzutownie int na str # Więcej wyświetlania ze zmianą wielkości czcionki wyrazenie = "Wykład Python" print(wyrazenie.lower()) print(wyrazenie[0]) # indesk zaczyna się od 0 print(wyrazenie.index("n"))# poda na którym ideksie znajduje się litera print(wyrazenie.replace("Wykład", "Moduł"))
302ecbdb31271cbb404791fd4e69f94c8774a54a
michalmaj/programowanie_aplikacji_w_jezyku_python
/wyk_3/wyk_3_zip_unzip.py
1,056
4.09375
4
# "Odpakowywanie" (unzip): lista = [1, 2] a, b = lista # a = lista[0], b = lista[1] print(a, b) # splat (inaczej asterisk): x = [1, 2, 3] print(x) # drukuje listę (1 argument) print(*x) # drukuje "rozpakowaną" listę (3 argumenty) print(x[0], x[1], x[2]) # równoważny zapis x = "Python" print(x) print(*x) # zip/unzip działa na wszystkich sekwencjach print(*x, sep='\t') # unzip z tabulatorem jako separatorem pomiędzy literami # unzip i splat: a, *b = lista # a = lista[0], b = reszta print(a, b) lista = [1, 2, 3, 4, 5] a, *b, c = lista # a, b[0], b[1], b[2], c print(a, b, c) # "pakowanie" (zip) x = [1, 2, 3] y = ['a', 'b', 'c'] zipped = zip(x, y) # pary (x[i], y[i]) print(*zipped) x = [1, 2, 3, 4] y = ['a', 'b', 'c'] # długość nie ma znaczenia - ucina do listy o najmniejszej długości zipped = zip(x, y) # pary (x[i], y[i]) print(*zipped) # zip / unzip: x = [1, 2, 3] y = [4, 5, 6] x_copy, y_copy = zip(*zip(x, y)) print(x == list(x_copy) and y == list(y_copy)) print(list(zip(x,y))) print(*zip(x,y)) print(list(zip(*zip(x, y))))
18480bdc8d7713d23c6cce7e1e095b53f77cf4f1
Jaydenzk/DS-Unit-3-Sprint-2-SQL-and-Databases
/module2-sql-for-analysis/insert_titanic.py
1,640
3.921875
4
import pandas as pd import psycopg2 import sqlite3 #Reproduce demopostgres lecture #Extract data from csv df = pd.read_csv("titanic.csv") df['Name'] = df['Name'].str.replace("'", " ") # Make sqlite3 file and Connect to get cursor conn = sqlite3.connect('titanic.sqlite3') curs = conn.cursor() # data from df into sql file df.to_sql('titanic', conn, index=False, if_exists='replace') # check out the data table and see data types n_curs = conn.cursor() query = 'SELECT COUNT(*) FROM titanic;' n_curs.execute(query).fetchall() titanic = n_curs.execute('SELECT * FROM titanic;').fetchall() n_curs.execute('PRAGMA table_info(titanic);').fetchall() # connect psycopg2 dbname = 'vlfwvshe' user = 'vlfwvshe' password = '' # Don't commit this! host = 'salt.db.elephantsql.com' pg_conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host) pg_conn pg_curs = pg_conn.cursor() #Create table and execute create_titanic_table = """ CREATE TABLE titanic ( index SERIAL PRIMARY KEY, Survived INT, Pclass INT, Name TEXT, Sex TEXT, Age REAL, Siblings_Spouses_Aboard INT, Parents_Children_Aboard INT, Fare REAL ); """ pg_curs.execute(create_titanic_table) #Actual insert for t in titanic: insert_titanic = """ INSERT INTO titanic (Survived, PClass, Name, Sex, Age, Siblings_Spouses_Aboard, Parents_Children_Aboard, Fare) VALUES """ + str(titanic[0]) + ';' pg_curs.execute(insert_titanic) pg_curs.close() pg_conn.commit()
6963e68980e6a7b1c0ea2e50c6b62b5237cf5b42
Julie-H/GoogleChallenge
/GoogleChallenge_J.py
3,612
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 13 19:20:33 2016 @author: Damien """ # -*- coding: utf-8 -*- """ Created on Sat Aug 13 14:21:25 2016 @author: Julie """ import string def listOptimise(positions, termsList): while len(positions[termsList[0]])>1: #Remove the position of the 1st item of the list positions[termsList[0]] = positions[termsList[0]][1:] #Remove the 1st item from the list termsList = termsList[1:] #and again def answer(document, searchTerms): textList = string.split(document) start = -1 textLength = len(textList) #k will be the current position all along the document k = 0 positions = {term: [] for term in searchTerms} print positions termsNumber = len(searchTerms) termsList = [] #Find the 1st instance of a search term in the document while start == -1: for i in range(termsNumber): if textList[k] == searchTerms[i]: start = k #Start filling in the positions dictionnary and building the list of search terms: positions[textList[k]] = [k] termsList.append(textList[k]) k+=1 #Find the remaining search terms in the document to build an initial list #and record positions as they are encountered: while [] in positions.values(): for i in range(termsNumber): if textList[k] == searchTerms[i]: positions[textList[k]].append(k) termsList.append(textList[k]) k+=1 #Now optimise the initial list: listOptimise(positions, termsList) #We have an initial optimised list. Now record length and start position: length = k - positions[termsList[0]][0] start = positions[termsList[0]][0] while k < textLength: #Look for next appearance in the text of 1st item of the current optimised list. #Along the way, record the search terms appearing so we can optimise after: while (k < textLength and textList[k]<>termsList[0]): for i in range(termsNumber): if textList[k] == searchTerms[i]: positions[textList[k]].append(k) termsList.append(textList[k]) k+=1 #If not reached end of list, means that we found another instance of 1st item #so record position and add to list of occurences if k < textLength: positions[textList[k]].append(k) termsList.append(textList[k]) #Now we have found a candidate list with everything in. Time to optimise: listOptimise(positions, termsList) #Check if current optimised list is shorter than shortest so far. if (k - positions[termsList[1]][0]+1)<length: #If so, record start and length: length = k - positions[termsList[1]][0] + 1 start = positions[termsList[1]][0] #and again: k+=1 return string.join(textList[start:(start+length)]) text = "a b c d e f g h" terms = ["b", "e"] terms[1:] answer(text, terms) test1 = "many google employees can program" search1 = ["google", "program"] answer(test1, search1) test2 = "a b c d a" search2 = ["a", "c", "d"] test3 = "london here i am london here i am" search3 = ["london", "am", "am"] answer(test3, search3) dico = {'a':[1, 3], 'b':[0, 2, 5], 'c':[8]} mylist = ['b', 'a', 'b', 'a', 'b', 'c'] mytest = 'a b c d e a e d c f ' mysearch = ['a', 'd', 'b'] answer(mytest, mysearch) answer(mytest, mysearch) mylist[1:1+3] listOptimise(dico, mylist)
b1565d007d1eebd18b9eef56747f11b686efd19b
swissmurali/Python-
/myex/exc1.py
254
3.65625
4
print "I will now count my chickens:" print "Hens", 15 + 15 / 3 print "Roosters", 50 - 20 * 2 % 4 print "Now I will count the eggs:" print 5 + 5 + 1 - 2 + 3 / 1 * 2 print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 6 print "Is it greater?", 5 > 4
efd17d8216ea0b7848b07238bef557c189514b32
PavanGupta01/pythonTraining
/class/id_exp.py
397
3.578125
4
__author__ = 'pavang' __Date___ = '' import copy class Point: def __init( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print(class_name, "destroyed") pt1 = Point() pt2 = copy.copy(pt1) pt3 = pt1 print(id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts # del pt1 print(id(pt2)) del pt2 del pt3
035e5ba36bfcb82b444e78e55a80bc4c30a0b5a5
PavanGupta01/pythonTraining
/scope/scope_eclosing.py
543
3.578125
4
__author__ = 'pavang' __Date___ = '' X = 10 # Global scope name: not used def f1(): # global X # X = 20 # Enclosing def local def f2(): nonlocal X # global X X = 30 print('f2: ' + str(X)) # Reference made in # nested def f2() print('f1: ' + str(X)) if __name__ == '__main__': f1() # Prints 88: enclosing def local print('G : ' + str(X))
4d1455a28a83758176391f13a392f9590d2c10ab
ahmedzaabal/Python-Demos
/functions.py
796
3.984375
4
from datetime import datetime #this is a functions current date and time #custom messages # def print_time(task_name): # print(task_name) # print(datetime.now()) # print() # first_name = "Ahmed" # print_time("task is done") # for x in range(0, 10): # print(x) # print_time("Task is done") def get_initial(name, force_uppercase = True): if force_uppercase: initial = name[0:1].upper else: initial = name[0:1] return initial first_name = input("Enter your first name: ") first_name_initial = get_initial(force_uppercase = False, name = first_name) last_name = input("Enter your last name: ") last_name_initial = get_initial(name = last_name, force_uppercase = True) print('Your initials are: ' + first_name_initial + ' ' + last_name_initial)
0067a705e03144ed487716e4e6e38fa69be4a539
zain101/AI_Pracs
/programs/src/best_first_n_queens.py
2,578
3.890625
4
import heapq import random, copy from os import sys, path visited=[] class MYPriority_Q(object): """docstring for MYPriority_Q""" def __init__(self): self.heap = [] def add(self, m): if (m.values(), m) not in self.heap: heapq.heappush(self.heap, (m.values(), m)) def get(self): while(True): if (len(self.heap)): z = heapq.heappop(self.heap) #print z else: break #print "\n...", self.heap, "\n..." if z not in visited: break visited.append(z) return z ''' The program follow the algorithm and example from A.I. Modern Approach It assumes that there will be no two queens in same column It follow Hill_climbing with optimisation of random restart. For a single time the program stucks in a local minimum, But when repeated several times it comes closer to solution ''' def hill_chess(board): '''This will store the currrent succsessors state and heuristics value''' flag=1 pq = MYPriority_Q() pq.heap.append("10") while(pq is not None ): if flag == 1: flag = 0 pq.heap = [] for col in range(len(board)): best_move = board[col] for row in range(len(board)): if board[col] == row: """ Here we monitor already existing comdition of queen, Therefore not operation is performed """ continue moves = {} board_copy = list(board) #Move the queen to the new row board_copy[col] = row '''Generating Hurestics for child nodes''' moves[tuple(board_copy)] = get_heuristics_for_8_queen(board_copy) pq.add(moves) #print pq.heap #raw_input() smallest = pq.get() board = list(smallest[1].keys()[0]) #print smallest if not smallest[1].values()[0]: break return board if __name__ == "__main__" and __package__ is None: sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from lib.queens_heuristics import * a = [3, 2, 1, 4, 3, 2, 1, 2] #[0, 0, 1, 1, 2, 2, 3, 3]#[0, 1, 2, 3, 4, 5, 6, 7] #[7, 5, 3, 1, 6, 4, 2, 0] b = [] print "Initial Hurestics of start state ",get_heuristics_for_8_queen(a) a = hill_chess(a) print "Final goal state (%s) Hurestics is (%s) "%(a , get_heuristics_for_8_queen(a))
d37b0464e97f61aa1cb3637fdaf4f76f0ccd3009
eugengh/listainclasa
/inclasa.py
617
3.625
4
with open("lista.txt", "r")as f: x=list(eval(f.readline())) x.sort(reverse=True) y=sorted(x) with open("output.txt", "w") as f: f.write("Lista: "+ str(x) +"\n") f.write("Lista sortata "+str(y)+"\n") f.write("Lista sortata iners" +str(x)+"\n") f.write("Numarul de elemente din lista: " + str(len(x))+"\n") f.write("Elementul maxim din lista: " + str(max(x))+"\n") f.write("Elementul minim din lista: " + str(min(x))+"\n") f.write("Lista cu elementul 111 la sfarsit "+str(x+[111])+"\n") x.insert(1, 222) f.write("Lista cu elementul 222 pe pozitia a doua"+str(x))
36f624bddc0a623ecc9123049f1e1a14186217dd
githubfun/LPTHW
/CodingBat/front3.py
300
3.90625
4
def front3(str): if len(str) < 3: return str * 3 else: return str[0:3] * 3 print "'' gives ", front3('') print "'Java' gives ", front3('Java') print "'Chocolate' gives ", front3('Chocolate') print "'abc' gives ", front3('abc') print "'oz' gives ", front3('oz') print "'m' gives ", front3('m')
4e8b2c18ebf0d7793c7be7dc2830842f26535ab1
githubfun/LPTHW
/PythonTheHardWay/ex14-ec.py
1,061
4.25
4
# Modified for Exercise 14 Extra Credit: # - Change the 'prompt' to something else. # - Add another argument and use it. from sys import argv script, user_name, company_name = argv prompt = 'Please answer: ' print "Hi %s from %s! I'm the %s script." % (user_name, company_name, script) print "I'd like to ask you a few questions." print "Do you like me, %s from %s?" % (user_name, company_name) likes = raw_input(prompt) print "Where do you live, %s?" % user_name lives = raw_input(prompt) print "Where is %s located?" % company_name company_location = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) print "Did %s give you your %s computer?" % (company_name, computer) company_gave_computer = raw_input(prompt) print """ OK... so you said %r about liking me. You live in %s. Yes, I think I know the area. %s is in %s. You must have to fly to get there. That's a shame; there are closer companies, I'm sure. Your %s computer? Meh. I've seen better. """ % (likes, lives, company_name, company_location, computer)
517b3ded388be8ca065a4af822aeb74b991d6036
githubfun/LPTHW
/CodingBat/cat_dog_alt.py
226
3.640625
4
def cat_dog(str): return str.count("cat") == str.count("dog") print "cat_dog('catdog') is ", cat_dog('catdog') print "cat_dog('catcat') is ", cat_dog('catcat') print "cat_dog('1cat1cadodog') is ", cat_dog('1cat1cadodog')
cfd0643d9683222a28b2325859a7108f0bca2a74
githubfun/LPTHW
/PythonTheHardWay/ex03-ec05.py
2,017
3.84375
4
# This version uses floating-point calculations to insure accuracy to two places (sufficient for the formulas). # The first line of executable code prints a statment (the stuff contained between the quotes) to the screen. print "I will now count my chickens:" # Next we print the word "Hens" followed by a space, then the result of the formula, which is analyzed 25.00 + (30.00 / 6.00) print "Hens", 25.00 + 30.00 / 6.00 # Line 7 prints right below the above output the word "Roosters" then the result of the formula 100.00 - (( 25.00 * 3.00) % 4.00) print "Roosters", 100.00 - 25.00 * 3.00 % 4.00 # 10 prints the statement about counting the eggs. print "Now I will count the eggs:" # 12 puts the result of the formula on the next line below the statement about counting eggs. # This formula is calculated ( 3.00 + 2.00 + 1.00 - 5.00 ) + ( 4.00 % 2.00 ) - ( 1.00 / 4.00 ) + 6.00 # What tripped me up in the original version was ( 1 / 4 ) = 0, since that's integer math, not FP. print 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 + 6.00 # Exercise 3, Extra Credit 5 comment: Of course, this means we're now going to have something less than one egg... # 22 prints a whole statement, including the whole formula, since everything # is between the quotes. print "Is it true that 3.00 + 2.00 < 5.00 - 7.00?" # 25 prints the results of the formula, which is analyzed "Is ( 3.00 + 2.00 ) < ( 5.00 - 7.00 )"? print 3.00 + 2.00 < 5.00 - 7.00 # 28 and 26 analyze the "halves" of the above question and formula, printing the "halves" first, then the result of the calculation. print "What is 3.00 + 2.00?", 3.00 + 2.00 print "What is 5.00 - 7.00", 5.00 - 7.00 # 32 is an "Aha" from the above two analyses. print "Oh, that's why it's False." print "How about some more." # print the statement to the screen # The final three lines print a question, then the answer to a formula. print "Is it greater?", 5.00 > -2.00 print "Is it greater or equal?", 5.00 >= -2.00 print "Is it less or equal?", 5.00 <= -2.00
3b76da959defc159b101c26b32a8d256fb321ebc
githubfun/LPTHW
/CodingBat/make_out_word.py
350
3.859375
4
def make_out_word(out, word): front_out = out[:2] back_out = out[2:] return front_out + word + back_out print "make_out_word('<<>>', 'Yay') yields ", make_out_word('<<>>', 'Yay') print "make_out_word('<<>>', 'WooHoo') yields ", make_out_word('<<>>', 'WooHoo') print "make_out_word('[[]]', 'word') yields ", make_out_word('[[]]', 'word')
f59a0e720d2f4cfe8a03948c6eda34746f7865b2
githubfun/LPTHW
/CodingBat/refactoring/sum13_after.py
503
3.890625
4
def sum13(nums): total = 0 i = 0 r = len(nums) while i < r: if nums[i] == 13: i += 2 else: total += nums[i] i += 1 return total print "sum13([1, 2, 2, 1]) is ", sum13([1, 2, 2, 1]) print "sum13([1, 1]) is ", sum13([1, 1]) print "sum13([1, 2, 2, 1, 13]) is ", sum13([1, 2, 2, 1, 13]) print "sum13([1, 2, 13, 2, 1, 13]) is ", sum13([1, 2, 13, 2, 1, 13]) print "sum13([13, 1, 2, 13, 2, 1, 13]) is ", sum13([13, 1, 2, 13, 2, 1, 13])
b188bceeaf7d88b547fc90b891c0ef8edc1bc9ab
githubfun/LPTHW
/PythonTheHardWay/projects/lexicon_project/ex49ec/lexicon.py
1,242
3.828125
4
# Modified for Exercise 48, Extra Credit def scan(sentence_to_parse): directions = {'north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'} verbs = {'go', 'kill', 'eat', 'stop', 'shoot', 'take', 'get', 'talk'} stop_words = {'the', 'in', 'of', 'from', 'at', 'it', 'to', 'and'} nouns = {'bear', 'princess', 'door', 'cabinet', 'gun', 'ghost', 'prince', 'hunter'} new_sentence = [] words = sentence_to_parse.split() for word_to_test in words: try: isinstance(word_to_test, (float)) word_tuple = ('number', float(word_to_test)) new_sentence.append(word_tuple) except ValueError: if word_to_test.lower() in directions: word_tuple = ('direction', word_to_test.lower()) new_sentence.append(word_tuple) elif word_to_test.lower() in verbs: word_tuple = ('verb', word_to_test.lower()) new_sentence.append(word_tuple) elif word_to_test.lower() in stop_words: word_tuple = ('stop', word_to_test.lower()) new_sentence.append(word_tuple) elif word_to_test.lower() in nouns: word_tuple = ('noun', word_to_test.lower()) new_sentence.append(word_tuple) else: word_tuple = ('error', word_to_test.lower()) new_sentence.append(word_tuple) return new_sentence
03d710fb5e89ebd20523ccaf3b1530adc509c48d
githubfun/LPTHW
/CodingBat/has22_first.py
744
3.828125
4
def has22(nums): if nums.count(2) == 0: return False elif len(nums) < 2: return False elif len(nums) == 2: return nums[0] == 2 and nums[1] == 2 else: i = 1 while i <= (len(nums) - 1): if nums[i] == 2 and (nums[i+1] == 2 or nums[i-1] == 2): return True break else: return False break i += 1 print "has22([1, 2, 2]) is ", has22([1, 2, 2]) print "has22([1, 2, 1, 2]) is ", has22([1, 2, 1, 2]) print "has22([2, 1, 2]) is ", has22([2, 1, 2]) print "has22([]) is ", has22([]) print "has22([2]) is ", has22([2]) print "has22([2, 2]) is ", has22([2, 2]) print "has22([1, 2]) is ", has22([1, 2])
c8176ae9af68ecc082863620472e9fe440300668
githubfun/LPTHW
/PythonTheHardWay/ex03.py
1,688
4.1875
4
# The first line of executable code prints a statment (the stuff contained between the quotes) to the screen. print "I will now count my chickens:" # Next we print the word "Hens" followed by a space, then the result of the formula, which is analyzed 25 + (30 / 6) print "Hens", 25 + 30 / 6 # Line 7 prints right below the above output the word "Roosters" then the result of the formula 100 - (( 25 * 3) % 4) print "Roosters", 100 - 25 * 3 % 4 # 10 prints the statement about counting the eggs. print "Now I will count the eggs:" # 12 puts the result of the formula on the next line below the statement about counting eggs. # This formula is calculated ( 3 + 2 + 1 - 5 ) + ( 4 % 2 ) - ( 1 / 4 ) + 6 # What tripped me up was ( 1 / 4 ) = 0, since we're doing integer math, not FP. print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # 19 prints a whole statement, including the whole formula, since everything # is between the quotes. print "Is it true that 3 + 2 < 5 - 7?" # 22 prints the results of the formula, which is analyzed "Is ( 3 + 2 ) < ( 5 - 7 )"? print 3 + 2 < 5 - 7 # 25 and 26 analyze the "halves" of the above question and formula, printing the "halves" first, then the result of the calculation. print "What is 3 + 2?", 3 + 2 print "What is 5 - 7", 5 - 7 # vvv----I noticed a typo here while working on Extra Credit 5 # 29 is an "Aha" from the above two analyses. print "Oh, that's why it's False." print "How about some more." # print the statement to the screen # The final three lines print a question, then the answer to a formula. print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
c5841693cc3e722cfe041a7469a8b43c5ce48c8d
githubfun/LPTHW
/PythonTheHardWay/ex23-avg_age.py
484
3.703125
4
# Script from Bitbucket.org, and example from someone's "Intro to Python" course. # Copied and modified as part of LPTHW Exercise 23 # Copied/modified code begins below people = [ [ 'Herb', 74 ], [ 'Carole', 71 ], [ 'Jay R.', 48 ], [ 'Missi', 46 ], [ 'Teri', 43 ], [ 'Erica', 39 ], [ 'Geoff', 34] ] # My family members and their ages total_age = 0 for person in people: age = person[1] total_age += age avg_age = total_age / len(people) print "Average age:", avg_age
49a5b9d687ddd5616afcf589d61c79402c9a2ff3
githubfun/LPTHW
/CodingBat/without_end.py
339
4
4
def without_end(str): if len(str) == 2: return '' else: return str[1:(len(str)-1)] print "without_end('Hello') yields ", without_end('Hello') print "without_end('java') yields ", without_end('java') print "without_end('coding') yields ", without_end('coding') print "without_end('fb') yields ", without_end('fb')
c25a349f58f679513bedb2c66b06c3a393265abe
shamil-t/number_to_word_converter
/num_to_word.py
1,134
3.84375
4
below_20 = ["","one","two","three","four","five","six","seven","eight","nine", "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","ninteen"]; above_20 = ["","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"] thousands = {100:'hundred', 1000:'thousand', 100000:'million', 1000000000:'billion'} def num_to_word(num): if num == 0: return 'zero' if num<20: return below_20[num] if num<100: if num%10 ==0: return above_20[(int)(num/10) - 1] else: return above_20[(int)(num/10) - 1] +' '+ below_20[num%10] if num > 100: element = max([key for key in thousands.keys() if key <= num]) word= num_to_word((int)(num/element)) + ' ' + thousands[element]+ ('' if num%element==0 else ' ' + num_to_word(num%element)) return word print(num_to_word(0)+' dollars') print(num_to_word(250)+' dollars') print(num_to_word(8950)+' dollars') print(num_to_word(75603)+' dollars') print(num_to_word(1234567)+' dollars') print(num_to_word(123456789)+' dollars') print(num_to_word(1234567890)+' dollars') print(num_to_word(7654321)+' dollars')
0318f0eb8a34086650aafdf16d7077a2bcdc2741
IAmTurbanMan/CIS104
/Week 7/Exercise2.py
290
3.890625
4
numbers = [] divisibleNumbers = [] for i in range(1, 1001): numbers.append(i) for x in numbers: if (x%7 == 0): divisibleNumbers.append(x) print("The number of integers that are divisible by 7 within the range 1-1000 is: {}".format (len(divisibleNumbers)))
39352d5c8ea9da797337d05ef58c5a6f8f77a277
AdamLosinski/AdamLosinski
/ZadanieDziennik.py
1,497
3.921875
4
#!/usr/bin/python3 from numpy import mean class Student: def __init__(self, name, lastname): self.name = name self.lastname = lastname self.grade = 0.0 self.grades = [] self.grades_weight = [] self.average = 0.00 print("New student added: " + self.name + " " + self.lastname) def new_grade(self, grade, grade_weight): self.grade = grade self.grade_weight = grade_weight self.grades.append(grade) self.grades_weight.append(grade_weight) print("New grade added: " + str(self.grade) + "weight of: " + str(self.grade_weight) + " to student: " + self.name + " " + self.lastname) def student_data(self): self.average = mean(self.grades) i = 0 grades_sum = 0.00 grades_div = 0.00 temp = 0 for el in self.grades: temp = el*self.grades_weight[i] grades_div += self.grades_weight[i] i += 1 grades_sum += temp self.average = grades_sum / grades_div print("Student data: " + self.name + " " + self.lastname + " " + str(self.grades) + " Grades average is: " + str(round(self.average, 2))) def main(): s1 = Student("Jan", "Kowalski") s2 = Student("Pawel", "Nowak") s3 = Student("Aleksandra", "Kos") s1.new_grade(4, 3) s1.new_grade(1, 1) s1.new_grade(3, 3) s2.new_grade(5, 1) s2.new_grade(6, 2) s2.new_grade(5, 1) s2.new_grade(5, 1) s3.new_grade(3, 3) s1.student_data() s2.student_data() s3.student_data() if '__main__' == __name__: main()
ba2a6b867c35fb80b5010ad1875020c55bb15147
Feeling-well/word-to-Excel
/wordread.py
7,428
3.828125
4
#作者:苏向阳 #平台:pycharm ,python3 #日期:2018.12.1 #功能:提取word表格内容到excel内。运行前需要先创建一个空的Excel文档,然后直接点击运行选择需要转换的word文档和需要保存到的Excel文件就行。 import win32com from win32com.client import Dispatch, constants from docx import Document from tkinter.filedialog import askopenfilename import tkinter.filedialog def select_inv(con):#选择函数 use = con.find("█"or" "and"√") unused = con.find("□") try: if unused > use : con = con [use+1:unused] else: con = con[use+1:] except: con = "" return (con) def select_meet(con):#list1查找所有的会场,list2记录勾选的会场,list3记录勾选的会场在list1中的位置 list1 = [i for i in range (len (con)) if (con[i:i + 1] == "□") or (con[i:i + 1] == "█")or(con[i:i + 1] == " ")or(con[i:i + 1] == "√")] list2 = [i for i in range (len (con)) if (con[i:i + 1] == "█")or(con[i:i + 1] == " ")or(con[i:i + 1] == "√")] list3 = [list1.index (list2[i]) for i in range (len (list2))] try: if len(list3)>2:#参加了一场还是两场 con1 = con[list1[list3[0]] + 1:list1[list3[0] + 1]] if (list3[-1:][0] + 1) == len (list1): # 判断最后一条是否为勾选项 con2 = con[list1[list3[1]] + 1:] else: con2 = con[list1[list3[1]] + 1:list1[list3[1] + 1] - 1] con = con1 + con2 else: con = con[list1[list3[0]] + 1:list1[list3[0] + 1]] except: con = "" return (con) def select_type(con):#选择函数 use = con.find("█普"and' 'and"√",2) unused = con.find("□") try: if unused > use : con = con [use+1:unused-1] else: con = con[use+1:] except: con ="" return (con) #选择需要打开的word文档 root = tkinter.Tk() root.withdraw()#隐藏 path_word = askopenfilename(filetypes = (("docx", "*.docx*"),("all files", "*.*"))) root.destroy() #销毁 PATH=path_word file = Document(PATH) tables = file.tables table = tables[0] #通用信息 invoice_type2 = table.cell (2, 1).text + "" #发票类型全部 invoice_type = select_type(invoice_type2) #发票类型提取 company_name = table.cell (0, 3).text + "" invoice_title = table.cell (1, 5).text + "" #发票抬头 taxpayer_num = table.cell (2, 5).text + "" #纳税人识别号 address_and_num = table.cell (3, 5).text + "" #地址电话 bank = table.cell (4, 5).text + "" #开户行 invoice_con2 = table.cell (5, 5).text + "" #发票内容全部 invoice_con = select_inv(invoice_con2) #发票内容提取 post_address = table.cell (6, 3).text + "" #邮寄地址 title_speaker = table.cell (7, 3).text + "" #报告题目及报告人 meeting_house2 = table.cell (8, 3).text + "" #参加会场信息全部 meeting_house = select_meet(meeting_house2) #参加会场信息提取 #参会人员信息 name1 = table.cell (11, 0).text + "" gender1 = table.cell (11, 1).text + "" pro_title1 = table.cell (11, 3).text + "" tel_num1 = table.cell (11, 5).text + "" postbox1 = table.cell (11, 6).text + "" reg_data1 = table.cell (11, 8).text + "" names = locals() for i in range(5): if ((table.cell (12+i, 0).text + "")==""or (table.cell (12+i, 0).text + "")=='房 间 预 订'): break else: j=i+2 names['name%s' % j] =table.cell (12+i, 0).text + "" names['gender%s' % j] = table.cell (12+i, 1).text + "" names['pro_title%s' % j] = table.cell (12+i, 3).text + "" names['tel_num%s' % j] = table.cell (12+i, 5).text + "" names['postbox%s' % j] = table.cell (12+i, 6).text + "" names['reg_data%s' % j] = table.cell (12+i, 9).text + "" hotel1_prices1 = table.cell (12 + i + 3, 2).text + "" hotel1_room_num = table.cell (12 + i + 3, 7).text + "" hotel1_room_name = table.cell (12 + i + 3, 8).text + "" for x in range (8): for y in range(i+1): if (table.cell (12 + y + 4, 7).text + "") != "__间": names['hotel1_con%s' % (y + 1)] = hotel1_room_num = (table.cell (12 + y + 4, 2).text + "") + ( table.cell (12 + i + 3, 8).text + "") names['hotel1_con%s' % (y + 1)] = hotel1_room_num = (table.cell (12 + y + 4, 2).text + "") + ( table.cell (12 + i + 3, 8).text + "") #excel接口 w = win32com.client.Dispatch('Word.Application') excel = win32com.client.Dispatch('Excel.Application') #选择需要打开的excel文件 root = tkinter.Tk() root.withdraw()#隐藏 path_excel = askopenfilename(filetypes = (("xlsx", "*.xlsx*"),("all files", "*.*"))) root.destroy() #销毁 workbook=excel.Workbooks.open(path_excel) excel.Visible=False first_sheet=workbook.Worksheets(1) first_sheet.Cells(1,1).value="姓名" first_sheet.Cells(1,2).value="性别" first_sheet.Cells(1,3).value="单位" first_sheet.Cells(1,4).value="职称" first_sheet.Cells(1,5).value="电话" first_sheet.Cells(1,6).value="邮箱" first_sheet.Cells(1,7).value="报到日期" first_sheet.Cells(1,8).value="发票抬头" first_sheet.Cells(1,9).value="纳税人识别号" first_sheet.Cells(1,10).value="地址电话" first_sheet.Cells(1,11).value="开户行" first_sheet.Cells(1,12).value="邮寄地址" first_sheet.Cells(1,13).value="报告题目及报告人" #有些是涂黑有些是打勾,识别起来会出错,第一个是自己提取的信息(有可能出差错),第二个是该栏的全部信息。 first_sheet.Cells(1,14).value="发票类型" first_sheet.Cells(1,15).value="发票类型2" first_sheet.Cells(1,16).value="发票内容" first_sheet.Cells(1,17).value="发票内容2" first_sheet.Cells(1,18).value="参加的会场" first_sheet.Cells(1,19).value="参加的会场2" for n in range(1,10000): if first_sheet.Cells(n,1).value==None: break #添加信息 for h in range(i+1): first_sheet.Cells (h+n, 1).value = names['name%s' % (h+1)] first_sheet.Cells (h+n, 2).value = names['gender%s' % (h+1)] first_sheet.Cells (h+n, 3).value = company_name first_sheet.Cells (h+n, 4).value = names['pro_title%s' % (h+1)] first_sheet.Cells (h+n, 5).value = names['tel_num%s' % (h+1)] first_sheet.Cells (h+n, 6).value = names['postbox%s' % (h+1)] first_sheet.Cells (h+n, 7).value = names['reg_data%s' % (h+1)] first_sheet.Cells (h + n, 8).value = invoice_title first_sheet.Cells (h + n, 9).value = taxpayer_num first_sheet.Cells (h + n, 10).value = address_and_num first_sheet.Cells (h + n, 11).value = bank first_sheet.Cells (h + n, 12).value = post_address first_sheet.Cells (h + n, 13).value = title_speaker #可以选择是否输出这些信息 # first_sheet.Cells (h + n, 14).value = invoice_type # first_sheet.Cells (h + n, 15).value = invoice_type2 # first_sheet.Cells (h + n, 16).value = invoice_con # first_sheet.Cells (h + n, 17).value = invoice_con2 # first_sheet.Cells (h + n, 18).value = meeting_house # first_sheet.Cells (h + n, 19).value = meeting_house2 workbook.Save()#保存到Excel
cce990bf76facc021f3106a7f035c970273cb6a9
astlock/Outtalent
/Leetcode/246. Strobogrammatic Number/solution1.py
282
3.578125
4
class Solution: def isStrobogrammatic(self, num: str) -> bool: rotates = [0, 1, None, None, None, None, 9, None, 8, 6] for n1, n2 in zip(map(int, num), map(int, num[::-1])): if n1 != rotates[n2] or n2 != rotates[n1]: return False return True
33892bcfc08319b607d197a58ba3975b1e7276a5
modzozo/hack101
/week0/day0/sum_of_divisors.py
218
3.765625
4
import math def sum_of_divisors(n): sum = 0 for iterate in range(1,n+1): if n % iterate == 0: sum = sum + iterate return sum def main(): print (sum_of_divisors(100000)) if __name__== '__main__': main()
18cbc0427899c6e7ce432eb3973a261c19ee8594
modzozo/hack101
/week4/day0/manage_company.py
2,755
3.875
4
import sqlite3 class ManageCompany(): def __init__(self): self.connect = sqlite3.connect("company.db") self.connect.row_factory = sqlite3.Row self.cursor = self.connect.cursor() def list_employees(self): exe = self.cursor.execute('''SELECT id,name, position FROM employees''') for row in exe: print("{}. {} - {}".format(row["id"], row["name"], row["position"])) def monthly_spending(self): exe = self.cursor.execute('''SELECT SUM(monthly_salary) FROM employees''') print(list(exe.fetchone())) def yearly_spending(self): exe = self.cursor.execute('''SELECT SUM(yearly_spending) FROM employees''') print(list(exe.fetchone())) def add_employee(self): name = input("name> ") monthly_salary = input("monthly_salary> ") yearly_bonus = input("yearly_bonus> ") position = input("position> ") self.cursor.execute('''INSERT INTO employees(name, monthly_salary, yearly_bonus, position) VALUES(?, ?, ?, ?);''', (name, monthly_salary, yearly_bonus, position)) self.connect.commit() def update_employee(self, id): name = input("name> ") monthly_salary = input("monthly_salary> ") yearly_bonus = input("yearly_bonus> ") position = input("position> ") self.cursor.execute('''UPDATE employees SET name = ?, monthly_salary = ?, yearly_bonus = ?, position = ? WHERE id = ?;''', (name, monthly_salary, yearly_bonus, position, id)) self.connect.commit() def delete_employee(self,id): self.cursor.execute('''DELETE FROM employees WHERE id = ?''',(id)) self.connect.commit() def console(self): while True: reply = input("\nYour choice: ") if reply == 'exit': break else: reply = reply.split() # make list of arguments if reply[0] == "list_employees": self.list_employees() elif reply[0] == "monthly_spending": self.monthly_spending() elif reply[0] == "yearly_spending": self.yearly_spending() elif reply[0] == "add_employee": self.add_employee() elif reply[0] == "update_employee" and len(reply) == 2: self.update_employee(reply[1]) elif reply[0] == "delete_employee" and len(reply) == 2: self.delete_employee(reply[1]) else: print("Wrong command! Try again.") def main(): ManageCompany().console() if __name__ == '__main__': main()
e12728b653a685aba01bf66f0b89f2d31f8b0c6d
Flor91/Data-Science
/Code/3-numpy/np_vectorizacion.py
1,143
4.25
4
""" 1) Generemos un array de 1 dimension con 1000 elementos con distribución normal de media 5 y desvío 2, inicialicemos la semilla en el valor 4703. 2) Usando algunas de las funciones de Numpy listadas en Métodos matemáticos y estadísticos, calculemos la media y el desvío de los elementos del array que construimos en el punto 1. 3) Generemos otro array de dimensiones 100 filas, 20 columnas con distribución normal de media 5 y desvío 2. 4) Usando las mismas funciones que en 2) calculemos la media y el desvío de cada fila del resultado de 3. 5) Usando las mismas funciones que en 2) calculemos la media y el desvío de cada columna del resultado de 3. """ import numpy as np from random_distribuciones import random_binomial def print_stats(a, axis): print(f"Media: {a.mean(axis=axis)}") print(f"Desvio: {a.std(axis=axis)}") array_normal_1 = random_binomial(seed=4703, size=1000, n=5, p=2) print(array_normal_1[:5]) print_stats(array_normal_1, 0) array_normal_2 = random_binomial(seed=4703, size=(100, 20), n=5, p=2) print(array_normal_2[:5, :2]) print_stats(array_normal_2, 0) print_stats(array_normal_2, 1)
7f296b1df2cfc4c81fc0398de63e95725803a2b7
rafaelsantosxp/igti
/fundamentals/2/3-conditions_elif.py
416
4.09375
4
# Example_7 x = float(input('Type the first number')) y = float(input('Type the second number')) print('Type 1 to ADD') print('Type 2 to SUBTRACT') print('Type 3 to MULTIPLY') print('Type 4 to SPLIT') choice = int(input('Which one?')) if choice == 1: print(x + y) elif choice == 2: print(x - y) elif choice == 3: print(x * y) elif choice == 4: print(x / y) else: print('Your choice not exists')
d80e8ce7826655dba9e228b29abcd279c6413a8c
rafaelsantosxp/igti
/fundamentals/3/4-Range.py
140
3.609375
4
# Example_Range_1 # len verify length data = input("Type a string: ") for i in range(len(data)): print((data[i])) print("End of code")
add9ea117616b03698d26bf4c200815bf241dfb6
rafaelsantosxp/igti
/fundamentals/Task-1/codigo1.py
130
3.71875
4
idade = int(input("entre com sua idade : ")) nova_idade = idade % 1 print ("no proximo ano voce tera: {} anos".format(nova_idade))
f16de759b46a7fd02f9840669f5cbd3be77fa8d3
DevBash1/PyQaver-Demos
/Time/server.py
336
3.59375
4
from time import gmtime, strftime now = strftime("%H:%M", gmtime()) if("name" in _POST): #_POST is like $_POST in PHP name = _POST["name"] if(name.strip() == ""): print("Please Enter Your Name!") else: print("Hello {}, The Server Time is {}".format(name,now)) else: print("Please Enter Your Name!")
59b743c282501d6d5c6adaa7487a6b66ca34c24f
alf1983/gb
/1.py
481
4.03125
4
duration = input("Input duration: ") duration = int(duration) minutes = 0 hours = 0 days = 0 seconds = duration % 60 minutes = duration // 60 if minutes > 60: hours = minutes // 60 minutes = minutes % 60 if hours > 24: days = hours // 24 hours = hours % 24 if days > 0: print(days, "дней", end=" ") if hours > 0: print(hours, "часов", end=" ") if minutes > 0: print(minutes, "минут и", end=" ") print(seconds, "секунд")
1cf8de4490b02e2102d3b7337f54b707e12d3362
chase-g/euler
/euler20.py
255
3.671875
4
#Project Euler 20 #"Find the sum of the digits in the number 100!" def factorial(n): answer = 1 while(n > 0): answer = answer * n n = n - 1 return answer num = factorial(100) st = str(num) amount = 0 for i in st: amount += int(i) print(amount)
914517de052849732eda167d48859fb4ac4e5f50
xiaolinzi-xl/python_imooc
/twl/c8.py
702
3.5
4
import time def decorator(func): def wrapper(*args,**kw): print(time.time()) func(*args,**kw) return wrapper @decorator def f1(func_name): print('this is a function' + func_name) @decorator def f2(func_name1,func_name2): print('haha ' + func_name1 + ' ' + func_name2) @decorator def f3(func_name1,func_name2,**kw): print('haha ' + func_name1 + ' ' + func_name2) print(kw) # print(type(kw)) # f = decorator(f1) # f() # @ 设计模式中的动态代理 异曲同工之妙 AOP编程思想 # Python支持函数嵌套 # *args 可变参数 元组 tuple # **kw 关键字参数 字典 dict f1('xiaolinzi') f2('haha','shazi') f3('haha','xiaolinzi',a=1,b=2,c=3)
c40082b0cff483709b8858ddfe19406e38c38446
xiaolinzi-xl/python_imooc
/eleven/c2.py
472
4.0625
4
from enum import Enum class VIP(Enum): YELLOW = 1 GREEN = 2 BLACK = 3 RED = 4 class VIP1(Enum): YELLOW = 1 GREEN = 2 BLACK = 3 RED = 4 # print(type(VIP.BLACK)) # print(VIP.BLACK.name) # print(VIP.BLACK.value) # for x in VIP: # print(x) # result = VIP.BLACK > VIP.GREEN 枚举不支持大小比较,支持等值比较 # print(result) # result = VIP.GREEN == VIP1.GREEN # print(result) # print(type(VIP.BLACK)) a = 5 print(VIP(a))
f993801a82c941acf0c48eca30ab9ac52d8aa202
xiaolinzi-xl/python_imooc
/six/c1.py
292
3.9375
4
print('hello phython') # a = 2 ''' 流程控制语句 条件控制 循环控制 if else for while ''' mood = False if mood: print("go to left") else: print('go to right') print("back away") # 云服务 商业授权 a = 1 b = 2 if a > b: print('a > b') else: print('a <= b')
64bcfd97e6e23d48e5c03b0c2499c9a4c0cd92a1
britnicanale/06SoftDev
/08_lemme_flask_u_sumpn/app.py
1,354
3.6875
4
'''Britni Canale SoftDev1 pd6 K8 -- Fill Yer Flask 2018-09-19''' from flask import Flask app = Flask(__name__) @app.route("/") ##creating home page of web page def hello_world(): return "<!DOCTYPE html><html><head><title>BRITNI CANALE</title></head><body><h1> This is a website that contains some information</h1><p> Hello! This is a website. This website contains some InFORmaTioN. If you are interested in learning more about this information, click <a href =\"morestuff\"> here </a></p></body></html>" @app.route("/morestuff")##creating route def more_stuff(): return "<!DOCTYPE html><html><head><title>BRITNI CANALE</title></head><body><h1> This is a website that contains some more information ABOUT the information</h1><p> Hello! Welcome to the information about the information. This information is in regards to the more specific information. It's very important. It's very specific. It contains... information. If you'd like to see the REAL. SPECIFIC. <marquee> INFORMATION. </marquee> click <a href =\"morestuff/specificstuff\"> RIGHT. HERE.</a></p></body></html>" @app.route("/morestuff/specificstuff")##creating route within route def specific_stuff(): return "<!DOCTYPE><html><head><title>DOGE</title></head><body><h1><marquee>DOGE LOL</marquee></h1></body></html>" if __name__ == "__main__": ##runs code app.debug = True app.run()
88f1e468de82a9f3d0fcdfab65a657fe147a8e73
kurkol/python3_spider
/基本/正则表达式/非贪婪.py
222
3.578125
4
import re content = 'Hello 1234567 Word_This is a Regex Demo' result1 = re.match('^He.*(\d+).*Demo$', content) print(result1.group(1)) result2 = re.match('^He.*?(\d+).*Demo$', content) print(result2.group(1)) c=input()
8307da4c40f4cc3ebd2e8823e31b93ac683bac0d
abrosen/classroom
/itp/spring2018/countWordBeginnings.py
510
3.6875
4
counts = {} data = open("words.txt", 'r') for line in data: line = line.strip() line = line.lower() letter = line[0:2] if letter in counts: counts[letter] = counts[letter] + 1 else: counts[letter] = 1 mostCommonLetter = "" highestCount = 0 for letter in counts: if counts[letter] > highestCount: highestCount = counts[letter] mostCommonLetter = letter print(mostCommonLetter,highestCount)
b549c9db156fd82a945a101f713d0c66a14c64f8
abrosen/classroom
/itp/spring2020/roman.py
1,147
4.125
4
roman = input("Enter a Roman Numeral:\n") value = {"I" :1, "V":5, "X":10, "L":50,"C":100,"D":500,"M":1000} def validate(roman): count = {"I" :0, "V":0, "X":0, "L":0,"C":0,"D":0,"M":0} for letter in roman: if letter not in count: return False for letter in roman: count[letter] += 1 if count["I"] > 3 or count["X"] > 3 or count["C"] > 3 or count["M"] > 3: return False if count["V"] > 1 or count["L"] > 1 or count["D"] > 1: return False for i in range(len(roman) - 1): current = roman[i] nextNum = roman[i+1] if value[current] < value[nextNum]: if not (5*value[current] == value[nextNum] or 10*value[current] == value[nextNum]): return False return True def convert(roman): arabic = 0 for i in range(len(roman) - 1): current = roman[i] nextNum = roman[i+1] if value[current] >= value[nextNum]: arabic += value[current] else: arabic -= value[current] return arabic + value[roman[-1]] print(validate(roman.upper())) print(convert(roman.upper()))
539eaa2d0069cee0731b57fad4ca23614b840e20
abrosen/classroom
/itp/fall2019/createImage.py
256
3.546875
4
import image win = image.ImageWin(640, 480, "Image Processing") myPic = image.EmptyImage(100,100) for x in range(myPic.getWidth()): for y in range(myPic.getHeight()): myPic.setPixel(x,y, image.Pixel(200,255,0)) myPic.draw(win) win.exit_on_click()
3793d42c3709b43cdde99b2bbe3ece027b11da14
abrosen/classroom
/itp/spring2020/pigLatin.py
919
3.8125
4
# apple -> 0 # 01234567 # xyzabcde -> 3 def findFirstVowel(word): index = len(word) - 1 for char in word: if char in "aeiou": return word.index(char) """ for index, letter in enumerate(word): if letter in "aeiou": return index """ return index def convertToPigLatin(word): indexVowel = findFirstVowel(word) # if word starts with a vowel if indexVowel == 0: return word[1:] + word[0] + "way" elif indexVowel == len(word) -1: return word else: # first vowel exists somewhere in the middle return word[indexVowel:]+ word[:indexVowel]+ "ay" def main(): done = False while not done: word = input() word = word.lower() if word == "done": done = True else: pig = convertToPigLatin(word) print(pig) main()
7324063f73376ac7ea6b139f0d1e4c98e44b193e
abrosen/classroom
/itp/spring2021/shapes.py
741
3.890625
4
import math class Triangle: def __init__(self, side1, side2, side3): self.side1 = side1 self.side2 = side2 self.side3 = side3 def __str__(self): return "triangle with sides [" + str(self.side1) +", "+ str(self.side2) + ", " +str(self.side3) + "]" def get_perimeter(self): return self.side1 + self.side2 + self.side3 def get_area(self): semiperim = 0.5 * self.get_perimeter() return math.sqrt( semiperim * (semiperim-self.side1)*(semiperim-self.side2)*(semiperim-self.side3)) if __name__ == "__main__": my_triangle = Triangle(3,4,5) print(my_triangle) other = Triangle(3,3,3) print(my_triangle.get_area()) print(other.get_area())
baab7e3488a58f13cc94f0395264b6dfbaa5ad45
abrosen/classroom
/itp/spring2020/scamGame1.py
743
3.578125
4
""" Nine Card Hustle: add 2 more red cards (7 red, 2 Black), shuffle and place in a 3 x 3 array. The even money bet is that you can find three cards in a straight line that are red. (up, down and diagonals count). What are the real odds? RRR BRR RBR """ import random def createDeck(): cards = "RRRRRRRBB" cards = list(cards) random.shuffle(cards) row1 = cards[:3] row2 = cards[3:6] row3 = cards[6:] return [row1,row2,row3] def printGrid(deck): for row in deck: print(row) deck = createDeck() TRIALS = 100000 count = 0 for _ in range(TRIALS): deck = createDeck() choice = [deck[0][0], deck[1][1], deck[2][2]] if "B" not in choice: count+=1 print(count/TRIALS)
d50e9fb5f2154082d0f81f680db428b651a8c6c1
abrosen/classroom
/itp/fall2019/nestedTurtle2.py
381
3.953125
4
import turtle bob = turtle.Turtle() bob.shape("turtle") bob.shapesize(1.5,1.5) bob.penup() def triangle(bob): for line in range(5): for _ in range(10 - line* 2): bob.forward(50) bob.stamp() bob.back(50*(10 - line *2)) bob.right(90) bob.forward(50) bob.left(90) bob.write("Hello, world how are you?", move=True,font=("Fira Sans",30,"normal")) turtle.done()
fa5d43c77ef6b01fddd71b0de9e34366ec30603d
abrosen/classroom
/itp/spring2018/turtleTest.py
216
3.609375
4
import turtle bob = turtle.Turtle() screen = turtle.Screen() bob.shape("turtle") screen.colormode(255) for x in range(20): bob.forward(20 + 10*x) bob.lt(120) bob.pencolor(10*x +50, 10*x, 0) turtle.done()
58fde0a747e1877b46b67a0e72f4d026082bb404
abrosen/classroom
/itp/spring2021/monteCarlo.py
1,186
3.640625
4
import random """ def dealHand(): deck = (list(range(1,11)) + [10,10,10]) * 4 random.shuffle(deck) return deck[0:2] TRIALS = 100000 wins = 0 for _ in range(TRIALS): hand = dealHand() if 1 in hand and 10 in hand: wins += 1 print(wins/TRIALS) """ def roll(): die1 = ["eye","eye","eye","paw","paw","paw"] die2 = ["eye","eye","eye","paw","paw","paw"] die3 = ["eye","eye","eye","paw","paw","paw"] r1 = random.choice(die1) r2 = random.choice(die2) r3 = random.choice(die3) results = [r1,r2,r3] if "paw" not in results: return True if r1 == "paw": r1 = random.choice(die1) if r2 == "paw": r2 = random.choice(die2) if r3 == "paw": r3 = random.choice(die3) results = [r1,r2,r3] if "paw" not in results: return True if r1 == "paw": r1 = random.choice(die1) if r2 == "paw": r2 = random.choice(die2) if r3 == "paw": r3 = random.choice(die3) results = [r1,r2,r3] if "paw" not in results: return True return False TRIALS = 100000 wins = 0 for _ in range(TRIALS): if roll(): wins += 1 print(wins/TRIALS)
06879b5007d2755936133143a2cd01ace89b4481
abrosen/classroom
/itp/spring2020/forLoopsAndSequences.py
143
4.15625
4
word = 'hello' listOfNums = [1,2,3,4,5,"three"] for letter in word: print(letter) for thing in listOfNums: print(thing, type(thing))
393e44c5af61bab2155ecbad77c562da10964834
abrosen/classroom
/itp/spring2018/testRandom.py
248
3.625
4
import random num1 = 0 num2 = 0 num3 = 0 TRIALS = 3000000 for _ in range(TRIALS): num = random.randint(1,3) if num == 1: num1 += 1 elif num == 2: num2 += 1 elif num == 3: num3 += 1 print(num1,num2,num3)
6d7fb8508d9eafe5963a2f4acf4f90ada0b7aa0c
abrosen/classroom
/itp/spring2021/dateChecker.py
1,159
4.03125
4
def isLeapYear(year): # if not year % 4 == 0: return False elif year % 100 == 0: if year % 400 == 0: return True else: return False else: # divisible by 4, but not by 100 return True #def complexCalculation(x,y,z_prime,scary_greek_letter): # return -1 print("Enter a date:") date = input() # 01234567890 # MM/DD/YYYY month = date[0:2] month = int(month) day = int(date[3:5]) year = int(date[6:]) if month == 2: if 1 <= day <= 28: print("valid date") elif day == 29: #DOOOOOOOOOOOOOOOOOOOOOOOOM if isLeapYear(year): print("valid date") else: print("invalid; not a leap year") else: print("invalid day") elif month == 4 or month == 6 or month == 9 or month == 11: if 1 <= day <= 30: print("valid date") else: print("day invalid") elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: if 1 <= day <= 31: print("valid date") else: print("day invalid") else: print("Invalid date; month invalid.")
bf84516891d60a5bba8e7c37e84373931a3134bf
abrosen/classroom
/itp/spring2020/fileReadingExample.py
280
3.578125
4
data = open("shakespeare.txt","r") #print(data) countDracula = 0 countWords = 0 for line in data: words = line.split() countWords = countWords + len(words) print(words) """ if "dracula" in line.lower(): print(line) countDracula = countDracula +1 """ print(countWords)
388cac6c8c2fe26e2cb4d88584dac9dc39c45563
abrosen/classroom
/itp/spring2021/piglatin.py
758
3.953125
4
def findFirstVowel(word): vowels = 'aeiou' for index, letter in enumerate(word): if letter in vowels: return index return -1 def convertToPigLatin(word): vowelIndex = findFirstVowel(word) if vowelIndex == -1: return word elif vowelIndex == 0: # if the word starts with a vowel return word[1:] +word[0]+ "way" #restOfTheWord + vowel + "way" else: # the word doesn't start with a vowel return word[vowelIndex:] + word[0:vowelIndex] + "ay" def main(): finished = False while not finished: word = input("Enter a word: ") if word == "done": finished = True else: pig = convertToPigLatin(word) print(pig) main()
8987b85cf884dbaa3295df110539bb1c517d7f00
abrosen/classroom
/itp/fall2019/examp.py
79
3.875
4
print("Please enter your name:") name = input() print("Your name is " + name)
e2ba774131b26bcebcd74b9074e4b17b8a21b25b
abrosen/classroom
/itp/fall2019/multiColor.py
224
3.703125
4
import turtle bob = turtle.Turtle() bob.pensize(50) colors = ["red","green","cyan","blue","purple","black","#ff00ff","brown","red", "yellow"] for color in colors: print(color) bob.color(color) bob.forward(50)
6db17e91e654e5229ccad28166264478673839d9
abrosen/classroom
/itp/spring2020/booleanExpressions.py
427
4.1875
4
print(3 > 7) print(6 == 6) print(6 != 6) weather = "sunny" temperature = 91 haveBoots = False goingToTheBeach = True if weather == "raining": print("Bring an umbrella") print(weather == "raining" and temperature < 60) if weather == "raining" and temperature < 60: print("Bring a raincoat") if (weather == "raining" and temperature > 90 and not haveBoots) or goingToTheBeach: print("Looks like sandals for today")
c71bc97744c8a66d17ad908ee95c7314f84525ad
abrosen/classroom
/itp/spring2022/loops functions and sequences.py
960
3.984375
4
import turtle #text = "hello there, general kenobi!" #num = 13 #lowTemps = [2,4,-8,-7,-2,-7,-2,3,4,-2] #for char in text: # print(char) #total = 0 #for temp in lowTemps: # total = total + temp #print(total) #print(len(lowTemps)) #print(total/len(lowTemps)) #print(len(text)) def drawSquare(theTurtle,size): for _ in range(4): theTurtle.forward(size) theTurtle.right(90) bob = turtle.Turtle() bob.speed(10) bob.pensize(7) # 0 1 2 3 4 5 6 7 8 9 for i in range(10): bob.color(0+i*.1,0,1-i*.1) drawSquare(bob,50) bob.forward(60) colors = ["red","green","blue","pink"] #for _ in range(20): # for theColor in colors: # bob.color(theColor) # bob.forward(200) # bob.right(87) #def sayHi(): # print("Hi!") #def shoutIt(text): # SHOUTY_TEXT = text.upper() # print(SHOUTY_TEXT) #def add(a,b): # print(a,b,a+b) #sayHi() #shoutIt("hello how are you doing today?") #add(4,7)
d247b9ca4d9021d7af5fb1d5960c7d183f5f774f
abrosen/classroom
/itp/summer2018/forCounting.py
243
3.921875
4
for x in range(100,0,-3): print(str(x) + "\t"+ str(x**2)) LIMIT = 100 for x in range(0,LIMIT,6): print(x) print("changing steps") print("--------------") step = 1 for x in range(0,100,step): print(x, step) step = step + 1
2aa79e8f961bed16ce1d9ff435b00ca24fa42319
abrosen/classroom
/itp/fall2020/helloname.py
133
4.09375
4
name = input("What is your name: ") print("Hello, " + name) num = input("Please enter a number and I will double it: ") print(num*2)
2f6fe3623ba1c3bb8d82de2988f6ddd9c083ee04
abrosen/classroom
/itp/recusionExamples.py
2,877
3.65625
4
import random """ 7! = 7*(6*5*4*3*2*1) = 7 * 6! = 7 *720 = 4900 + 140 6! = 6*5*4*3*2*1 = 6 * 5! = 6 * 120 = 720 5! = 120 n! = n * (n-1)! = n * (n-1) * (n-2)! 1. Recursive case n! = n*(n-1)! 2. Base case(s) 1! = 1 , 0! = 1 3. Recursive cases move toward the base case """ def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) # 1 1 2 3 5 8 13 21 34 55 # f_n = f_(n-1) + f_(n-2) if n >2 # = 1 otherwise def fib(n): fib_lookup = {} return fib_recursive(n,fib_lookup) def fib_recursive(n,fib_lookup): if n <= 2: return 1 else: if n - 1 not in fib_lookup: fib_lookup[n-1] = fib_recursive(n-1,fib_lookup) if n - 2 not in fib_lookup: fib_lookup[n-2] = fib_recursive(n-2,fib_lookup) return fib_lookup[n-1] +fib_lookup[n-2] print(fib(60)) # board is the board # col is the current col we are trying to put a queen on def solve(board, col): if col >= 8: return True for row in range(0,8): if isValid(board,row,col): board[row][col] = 1 if solve(board, col + 1) == True: return True board[row][col] = 0 return False def isValid(board,row,col): return isRowValid(board,row,col) and isUpLeftValid(board,row,col) and isDownLeftValid(board,row,col) #####1### def isRowValid(board,row,col): for i in range(0, col): if board[row][i] == 1: return False return True # row - i >= 0 , i must stay below (row + 1) # col + i < 8, i must stay below 8 -(col + 1) # for(int i =0; row - i >= 0 && col + i < 8;i++) def isUpLeftValid(board,row,col): i = 0 while row - i >=0 and col-i >=0: if board[row-i][col-i] == 1: return False i = i+1 return True def isDownLeftValid(board,row,col): i = 0 while row + i < 8 and col-i >=0: if board[row+i][col-i] == 1: return False i = i+1 return True def solveSudoku(board,row,col): if col >= 9: row = row+1 col = 0 if row >= 9: return True if board[row][col]: return solveSudoku(board,row,col +1) for num in range(1,10): if isValidSudoku(board,row,col,num): board[row][col] = num if solveSudoku(board, row, col+1): return True board[row][col] = 0 return False board = [[0]*8,[0]*8,[0]*8,[0]*8,[0]*8,[0]*8,[0]*8,[0]*8] solve(board,0) for row in board: print(row) """ queens = random.sample(range(0,64),8) print(queens) for queen in queens: board[queen//8][queen%8] = 1 for row in board: print(row) print(64*63*62*61*60*59*58*57) 0 1 2 3 4 5 6 7 <- 0 8 9 10 11 12 13 14 15 <- 1 16 <- 2 """ #print(factorial(500))
ace85466e4ad045a772f66faecaaca972fca924e
zen-char/DBMS-Fault-Injection-Framework
/src/utils.py
3,594
3.703125
4
""" Author: Gerard Schroder Study: Computer Science at the University of Amsterdam Date: 08-06-2016 This file contains simple json helper functions. FILE: json_functions.py USAGE: python attach_strace.py """ import io import json import hashlib import datetime as dt """ Str to time & time utilities """ # Convert a string in format Hours:Mins:Secs e.g. 12:30:02 in a datetime.time() obj. def get_time_from_str(time_str, return_list=False): time_str_numbers = time_str.split(':') time_numbers = [int(float(number)) for number in time_str_numbers[:2]] if len(time_str_numbers[2].split('.')) == 2: secs, microsecs = [int(number) for number in (time_str_numbers[2]).split('.')] if return_list: return time_numbers + [secs, microsecs] return dt.time(time_numbers[0], time_numbers[1], secs, microsecs) else: if return_list: return time_numbers + [int(time_str_numbers[2])] return dt.time(time_numbers[0], time_numbers[1], int(time_str_numbers[2])) # Find the time between a and b return a time object def get_time_difference(time_a, time_b): datetime_a = dt.datetime(1, 1, 1, time_a.hour, time_a.minute, time_a.second, time_a.microsecond) datetime_b = dt.datetime(1, 1, 1, time_b.hour, time_b.minute, time_b.second, time_b.microsecond) try: time_delta = datetime_b - datetime_a return (dt.datetime.min + time_delta).time() except OverflowError: time_delta = datetime_a - datetime_b return (dt.datetime.min + time_delta).time() """ Print utilities """ # Add color codes to a string without adding another library. # Based on: http://stackoverflow.com/questions/287871 def color_str(str_to_color, color='y'): color_start_symbs = '\x1B[' c = '' if color == 'y': c = color_start_symbs + '0;33;80m' elif color == 'g': c = color_start_symbs + '0;92;80m' return c + str_to_color + color_start_symbs + '0m' """ Dictionary to str """ # Simple remapping of a dictionary to a non unicode str. # Based on: http://stackoverflow.com/questions/9590382 def ascii_encode_dict(data): def ascii_encode(x): return x.encode('ascii') if isinstance(x, unicode) else x return dict(map(ascii_encode, pair) for pair in data.items()) """ JSON utilities """ # Pretty print json data. def print_json(json_data): return json.dumps(json_data, sort_keys=True, indent=2, separators=(',', ': ')) def load_json_file(file_name): try: with io.open(file_name, 'r') as json_file: data = json.load(json_file) return data except ValueError: print 'Error while parsing the file: {}.'.format(file_name) except IOError: print 'File: {} does not exists. Exiting.'.format(file_name) return None """ Checksum utilities """ # Code referenced from: # http://stackoverflow.com/questions/3431825/ # Do not set the hasher in the header of the function. def gen_checksum_from_file(file_path, hasher=None, blocksize=65536, use_file=False): if hasher is None: hasher = hashlib.md5() opened_file = file_path if use_file else io.open(file_path, 'rb') buf = opened_file.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = opened_file.read(blocksize) if not use_file: opened_file.close() return hasher.digest().encode('hex') def gen_checksum_from_bytes(byte_string, hasher=None): if hasher is None: hasher = hashlib.md5() hasher.update(byte_string) return hasher.digest().encode('hex')
209d2dfd0dbb9979ad8b075d650a5f4b3f296c25
Ankita-neha/instabot
/instabot.py
6,806
3.578125
4
import requests # Here importing the requests library which is installed by using pip. APP_ACCESS_TOKEN = '1599633091.2fc0da1.63f5a1608a3e4414b4d96117bca38027' BASE_URL = 'https://api.instagram.com/v1/' def self_info(): # this is the function which fetches my instagram profile details by using api. request_url = (BASE_URL +'users/self/?access_token=%s') % (APP_ACCESS_TOKEN) print 'REQUESTING URL FOR DATA : ' + request_url my_info = requests.get(request_url).json() print 'MY INFO IS: \n' print 'My Bio: ' + my_info['data']['bio'] print 'My Website : ' + my_info['data']['website'] print 'My Full Name : ' + my_info['data']['full_name'] print 'My Username : ' + my_info['data']['username'] print 'I am followed by : ' + str(my_info['data']['counts']['followed_by']) + ' Users' print 'I follow : ' + str(my_info['data']['counts']['follows']) + ' Users' #self_info() #this function is used to fetch another user's details by entering instagram username and also it will return the userID def get_user_id_by_username(insta_username): request_url = (BASE_URL + 'users/search?q=%s&access_token=%s') % (insta_username, APP_ACCESS_TOKEN) print 'REQUESTING URL FOR DATA : ' + request_url search_results = requests.get(request_url).json() print search_results if search_results['meta']['code'] == 200: if len(search_results['data']) > 0: print 'User ID: ' + search_results['data'][0]['id'] return search_results['data'][0]['id'] else: print 'User does not found!' else: print 'Status code other than 200 was received' return None #get_user_id_by_username('shubham.is.here') def get_users_recent_posts(insta_username): #This function fetches the recent uploaded posts by the user. user_id = get_user_id_by_username(insta_username) request_url = (BASE_URL + 'users/%s/media/recent/?access_token=%s') % (user_id, APP_ACCESS_TOKEN) print 'REQUESTING URL FOR DATA : ' + request_url recent_posts = requests.get(request_url).json() if recent_posts['meta']['code'] == 200: if len(recent_posts['data']): return recent_posts['data'][1]['id'] else: print 'No recent post by this user!' else: print 'Status code other than 200' #print get_users_recent_posts('shubham.is.here') def like_users_post(insta_username): #Function to like the user post, it will like the post id that we fetched in the above funtion. post_id = get_users_recent_posts(insta_username) payload = {'access_token': APP_ACCESS_TOKEN} request_url = (BASE_URL + 'media/%s/likes') % (post_id) like_users_post = requests.post(request_url,payload).json() if like_users_post['meta']['code'] == 200: print "Like was successful" else: print "Like not successful" #like_users_post('shubham.is.here') def get_comment_id_for_a_post(insta_username): post_id = get_users_recent_posts(insta_username) request_url = (BASE_URL + 'media/%s/comments?access_token=%s') % (post_id, APP_ACCESS_TOKEN) print "REQUESTING COMMENTS FROM INSTAGRAM USING %s" % request_url comments = requests.get(request_url).json() print comments for comment in comments['data']: print "%s commented: %s" % (comment['from']['username'],comment['text']) #get_comment_id_for_a_post('shubham.is.here') def comment_on_users_post(insta_username): #comment on the post of that user whose post id is fetched by above function. post_id = get_users_recent_posts(insta_username) request_url = (BASE_URL + 'media/%s/comments') % (post_id) request_data = {'access_token':APP_ACCESS_TOKEN, 'text':'instabot commented here'} comment_request = requests.post(request_url, request_data).json() if comment_request['meta']['code'] == 200: print "Comment successful" else: print "Comment unsuccessful" #comment_on_users_post('shubham.is.here') def get_the_comment_id(insta_username): #here we search the comment by word and return its commentid. post_id = get_users_recent_posts(insta_username) request_url = (BASE_URL + 'media/%s/comments?access_token=%s') % (post_id, APP_ACCESS_TOKEN) comment_id = requests.get(request_url).json() word_in_comment = raw_input("Enter a word that you want to find in the comment:") if comment_id['meta']['code'] == 200: for i in len(comment_id['data']): if word_in_comment in comment_id['data'][i]['text']: print "Comment found" return comment_id['data'][i]['id'] else: print "Comment was not found" else: print "Status code other than 200 was received" #get_the_comment_id('shubham.is.here') def delete_comment_by_the_word(insta_username): #Here we delete the comment whose id we fetched in above function. post_id = get_users_recent_posts(insta_username) comment_id = get_the_comment_id(insta_username) request_url = (BASE_URL + 'media/%s/comments/%s?access_token=%s') % (post_id, comment_id, APP_ACCESS_TOKEN) delete_comment = requests.delete(request_url).json() if delete_comment['meta']['code']==200: print "Comment deleted successfully" else: print "Comment was not successfully deleted" #delete_comment_by_the_word('shubham.is.here') condition = 'i' #Here bot asks the user which action you want to perform insta_username = raw_input("Enter the instagram username on which you want to perform any action: ") if (condition=='i' ): print "The options of the actions that the bot can perform are given below:- \n\ 1. View the details of your instagram profile. \n\ 2. Fetch another user's instagram profile id. \n\ 3. Get user's recent uploaded post. \n\ 4. To like another user's post. \n\ 5. Comment on another user's post. \n\ 6. Search a word in your comments of the post and get the commentid. \n\ 7. Delete the searched comment. \n\ 8. Show the comments which are done on another user's post. \n" choose_the_option = int(raw_input("Enter your option: ")) if choose_the_option==1: self_info() elif choose_the_option==2: get_user_id_by_username(insta_username) elif choose_the_option==3: get_users_recent_posts(insta_username) elif choose_the_option==4: like_users_post(insta_username) elif choose_the_option==5: comment_on_users_post(insta_username) elif choose_the_option==6: get_the_comment_id(insta_username) elif choose_the_option==7: delete_comment_by_the_word(insta_username) elif choose_the_option==8: get_comment_id_for_a_post(insta_username) else: print "Invalid selection"
d673e94fa65fbb88d3af0bb0171cc9a8254e8305
djohnson67/sPython3rd
/math/io/write_sales.py
534
3.90625
4
#prompts for sales and writes to sales.txt def main(): #get number of days num_days = int(input('For how many days do you have sales? ')) #open sales file sales_file = open('sales.txt','w') for count in range(1, num_days +1): #get sales for day sales = float(input('Enter sales for day #' + str(count) + ': ')) #write sales to txt sales_file.write(str(sales)+ '\n') #close file sales_file.close() print('Data written to sales.txt') main()