blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
93b4f43cfc3b0067a31ae69b2159a8b3a0224593 | blhwong/chess | /src/chess.py | 34,572 | 3.5 | 4 | '''
Created on Aug 11, 2016
Modified on Aug 15, 2016
@author: Brandon Wong
Description: Lists out all available chess moves given state of the board,
and player's turn (black or white). There is no accommodation for king in check,
en passant, or castling at the moment. The board is already set for initial
states for all pieces.
Important tips: 1. Do not modify the order of myChessBoard. You only have to
modify arguments of object chessSquare to change the state of
the board.
2. Moving a piece from a1 to a8 on the board is going "north",
and moving a piece from a1 to h1 on the board is going
"east". This will be helpful in understanding the output.
3. The white chess pieces can only start at rows a1 and a2, and
the white pawns can only move "north". The black pieces can
only start at rows a8 and a7, and the black pawns can only
move "south".
4. You only have to modify piece, and color parameters of
chessSquare. Do not modify the square parameter!
Piece argument is a string ('rook, 'knight', 'bishop',
'queen', 'king', 'pawn'), and color argument is a character
'w' for white or 'b' for black.
Example: a1 = chessSquare('queen', 'b', 'a1')
Function: listMoves(myChessBoard, color) located at the very bottom!
Input: myChessBoard array. Each element of array comprises of object
chessSquare as shown below.
a1 = chessSquare('piece', 'color', 'square')
.
.
.
myChessBoard=[[a8,b8,c8,d8,e8,f8,g8,h8],
[a7,b7,c7,d7,e7,f7,g7,h7],
[a6,b6,c6,d6,e6,f6,g6,h6],
[a5,b5,c5,d5,e5,f5,g5,h5],
[a4,b4,c4,d4,e4,f4,g4,h4],
[a3,b3,c3,d3,e3,f3,g3,h3],
[a2,b2,c2,d2,e2,f2,g2,h2],
[a1,b1,c1,d1,e1,f1,g1,h1]]
color is a one letter char either 'b' for black or 'w' for white.
color is the color of player's turn.
Output: The list of available moves for state of pieces on myChessBoard, and
the turn given by color parameter. Output will list out chess piece's
nth move, color of piece @ initial square, direction of movement, to
position of its final square.
Example:
3: w pawn@c2 move northwest to take b pawn@b3
1: w pawn@d2 move north to d3
'''
'''
PLEASE DO NOT MODIFY CODE BELOW
'''
class chessSquare:
def __init__(self, piece, color, square):
self.piece = piece
self.color = color
self.square = square
def listRookMoves(myChessBoard, color, i, j):
count = 1
for a in range(1,8):
if (i + a) > 7 or myChessBoard[i+a][j].color == color: #traversing south
break
if myChessBoard[i+a][j].piece != '0' and myChessBoard[i+a][j].color != color:
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move south to take ' + myChessBoard[i+a][j].color + ' ' + myChessBoard[i+a][j].piece + '@' + myChessBoard[i+a][j].square
count+=1
break
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move south to ' + myChessBoard[i+a][j].square
count+=1
for a in range(1,8):
if (i - a) < 0 or myChessBoard[i-a][j].color == color: #traversing north
break
if myChessBoard[i-a][j].piece != '0' and myChessBoard[i-a][j].color != color:
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move north to take ' + myChessBoard[i-a][j].color + ' ' + myChessBoard[i-a][j].piece + '@' + myChessBoard[i-a][j].square
count+=1
break
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move north to ' + myChessBoard[i-a][j].square
count+=1
for a in range(1,8):
if (j + a) > 7 or myChessBoard[i][j+a].color == color: #traversing east
break
if myChessBoard[i][j+a].piece != '0' and myChessBoard[i][j+a].color != color:
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move east to take ' + myChessBoard[i][j+a].color + ' ' + myChessBoard[i][j+a].piece + '@' + myChessBoard[i][j+a].square
count+=1
break
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move east to ' + myChessBoard[i][j+a].square
count+=1
for a in range (1,8):
if (j - a) < 0 or myChessBoard[i][j-a].color == color: #traversing west
break
if myChessBoard[i][j-a].piece != '0' and myChessBoard[i][j-a].color != color:
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move west to take ' + myChessBoard[i][j-a].color + ' ' + myChessBoard[i][j-a].piece + '@' + myChessBoard[i][j-a].square
count+=1
break
print str(count) + ': ' + color + ' rook@' + myChessBoard[i][j].square + ' move west to ' + myChessBoard[i][j-a].square
count+=1
return
def listKnightMoves(myChessBoard, color, i, j):
count = 1
if (i + 1) < 8 and (j + 2) < 8 and myChessBoard[i+1][j+2].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i+1][j+2].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i+1][j+2].color + ' ' + myChessBoard[i+1][j+2].piece + '@' + myChessBoard[i+1][j+2].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i+1][j+2].square
count+=1
if (i + 2) < 8 and (j + 1) < 8 and myChessBoard[i+2][j+1].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i+2][j+1].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i+2][j+1].color + ' ' + myChessBoard[i+2][j+1].piece + '@' + myChessBoard[i+2][j+1].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i+2][j+1].square
count+=1
if (i - 1) > -1 and (j + 2) < 8 and myChessBoard[i-1][j+2].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i-1][j+2].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i-1][j+2].color + ' ' + myChessBoard[i-1][j+2].piece + '@' + myChessBoard[i-1][j+2].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i-1][j+2].square
count+=1
if (i + 2) < 8 and (j - 1) > -1 and myChessBoard[i+2][j-1].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i+2][j-1].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i+2][j-1].color + ' ' + myChessBoard[i+2][j-1].piece + '@' + myChessBoard[i+2][j-1].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i+2][j-1].square
count+=1
if (i + 1) < 8 and (j - 2) > -1 and myChessBoard[i+1][j-2].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i+1][j-2].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i+1][j-2].color + ' ' + myChessBoard[i+1][j-2].piece + '@' + myChessBoard[i+1][j-2].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i+1][j-2].square
count+=1
if (i - 2) > -1 and (j + 1) < 8 and myChessBoard[i-2][j+1].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i-2][j+1].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i-2][j+1].color + ' ' + myChessBoard[i-2][j+1].piece + '@' + myChessBoard[i-2][j+1].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i-2][j+1].square
count+=1
if (i - 1) > -1 and (j - 2) > -1 and myChessBoard[i-1][j-2].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i-1][j-2].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i-1][j-2].color + ' ' + myChessBoard[i-1][j-2].piece + '@' + myChessBoard[i-1][j-2].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i-1][j-2].square
count+=1
if (i - 2) > -1 and (j - 1) > -1 and myChessBoard[i-2][j-1].color != color: #knight is in bounds and not blocked by own piece
if myChessBoard[i-2][j-1].piece != '0': #knight takes opposite piece
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' takes ' + myChessBoard[i-2][j-1].color + ' ' + myChessBoard[i-2][j-1].piece + '@' + myChessBoard[i-2][j-1].square
count+=1
else: #knight moves to empty space
print str(count) + ': ' + color + ' knight@' + myChessBoard[i][j].square + ' move to ' + myChessBoard[i-2][j-1].square
count+=1
return
def listBishopMoves(myChessBoard, color, i, j):
count = 1
for a in range(1,8):
if (i + a) > 7 or (j + a) > 7 or myChessBoard[i+a][j+a].color == color: #traversing southeast
break
if myChessBoard[i+a][j+a].piece != '0' and myChessBoard[i+a][j+a].color != color:
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move southeast to take ' + myChessBoard[i+a][j+a].color + ' ' + myChessBoard[i+a][j+a].piece + '@' + myChessBoard[i+a][j+a].square
count+=1
break
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move southeast to ' + myChessBoard[i+a][j+a].square
count+=1
for a in range(1,8):
if (i - a) < 0 or (j + a) > 7 or myChessBoard[i-a][j+a].color == color: #traversing northeast
break
if myChessBoard[i-a][j+a].piece != '0' and myChessBoard[i-a][j+a].color != color:
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move northeast to take ' + myChessBoard[i-a][j+a].color + ' ' + myChessBoard[i-a][j+a].piece + '@' + myChessBoard[i-a][j+a].square
count+=1
break
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move northeast to ' + myChessBoard[i-a][j+a].square
count+=1
for a in range(1,8):
if (i + a) > 7 or (j - a) < 0 or myChessBoard[i+a][j-a].color == color: #traversing southwest
break
if myChessBoard[i+a][j-a].piece != '0' and myChessBoard[i+a][j-a].color != color:
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move southwest to take ' + myChessBoard[i+a][j-a].color + ' ' + myChessBoard[i+a][j-a].piece + '@' + myChessBoard[i+a][j-a].square
count+=1
break
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move southwest to ' + myChessBoard[i+a][j-a].square
count+=1
for a in range (1,8):
if (i - a) < 0 or (j - a) < 0 or myChessBoard[i-a][j-a].color == color: #traversing northwest
break
if myChessBoard[i-a][j-a].piece != '0' and myChessBoard[i-a][j-a].color != color:
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move northwest to take ' + myChessBoard[i-a][j-a].color + ' ' + myChessBoard[i-a][j-a].piece + '@' + myChessBoard[i-a][j-a].square
count+=1
break
print str(count) + ': ' + color + ' bishop@' + myChessBoard[i][j].square + ' move northwest to ' + myChessBoard[i-a][j-a].square
count+=1
return
def listQueenMoves(myChessBoard, color, i, j):
count = 1
for a in range(1,8):
if (i + a) > 7 or myChessBoard[i+a][j].color == color: #traversing south
break
if myChessBoard[i+a][j].piece != '0' and myChessBoard[i+a][j].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move south to take ' + myChessBoard[i+a][j].color + ' ' + myChessBoard[i+a][j].piece + '@' + myChessBoard[i+a][j].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move south to ' + myChessBoard[i+a][j].square
count+=1
for a in range(1,8):
if (i - a) < 0 or myChessBoard[i-a][j].color == color: #traversing north
break
if myChessBoard[i-a][j].piece != '0' and myChessBoard[i-a][j].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move north to take ' + myChessBoard[i-a][j].color + ' ' + myChessBoard[i-a][j].piece + '@' + myChessBoard[i-a][j].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move north to ' + myChessBoard[i-a][j].square
count+=1
for a in range(1,8):
if (j + a) > 7 or myChessBoard[i][j+a].color == color: #traversing east
break
if myChessBoard[i][j+a].piece != '0' and myChessBoard[i][j+a].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move east to take ' + myChessBoard[i][j+a].color + ' ' + myChessBoard[i][j+a].piece + '@' + myChessBoard[i][j+a].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move east to ' + myChessBoard[i][j+a].square
count+=1
for a in range (1,8):
if (j - a) < 0 or myChessBoard[i][j-a].color == color: #traversing west
break
if myChessBoard[i][j-a].piece != '0' and myChessBoard[i][j-a].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move west to take ' + myChessBoard[i][j-a].color + ' ' + myChessBoard[i][j-a].piece + '@' + myChessBoard[i][j-a].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move west to ' + myChessBoard[i][j-a].square
count+=1
for a in range(1,8):
if (i + a) > 7 or (j + a) > 7 or myChessBoard[i+a][j+a].color == color: #traversing southeast
break
if myChessBoard[i+a][j+a].piece != '0' and myChessBoard[i+a][j+a].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move southeast to take ' + myChessBoard[i+a][j+a].color + ' ' + myChessBoard[i+a][j+a].piece + '@' + myChessBoard[i+a][j+a].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move southeast to ' + myChessBoard[i+a][j+a].square
count+=1
for a in range(1,8):
if (i - a) < 0 or (j + a) > 7 or myChessBoard[i-a][j+a].color == color: #traversing northeast
break
if myChessBoard[i-a][j+a].piece != '0' and myChessBoard[i-a][j+a].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move northeast to take ' + myChessBoard[i-a][j+a].color + ' ' + myChessBoard[i-a][j+a].piece + '@' + myChessBoard[i-a][j+a].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move northeast to ' + myChessBoard[i-a][j+a].square
count+=1
for a in range(1,8):
if (i + a) > 7 or (j - a) < 0 or myChessBoard[i+a][j-a].color == color: #traversing southwest
break
if myChessBoard[i+a][j-a].piece != '0' and myChessBoard[i+a][j-a].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move southwest to take ' + myChessBoard[i+a][j-a].color + ' ' + myChessBoard[i+a][j-a].piece + '@' + myChessBoard[i+a][j-a].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move southwest to ' + myChessBoard[i+a][j-a].square
count+=1
for a in range(1,8):
if (i - a) < 0 or (j - a) < 0 or myChessBoard[i-a][j-a].color == color: #traversing northwest
break
if myChessBoard[i-a][j-a].piece != '0' and myChessBoard[i-a][j-a].color != color:
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move northwest to take ' + myChessBoard[i-a][j-a].color + ' ' + myChessBoard[i-a][j-a].piece + '@' + myChessBoard[i-a][j-a].square
count+=1
break
print str(count) + ': ' + color + ' queen@' + myChessBoard[i][j].square + ' move northwest to ' + myChessBoard[i-a][j-a].square
count+=1
return
def listKingMoves(myChessBoard, color, i, j):
count = 1
if (i - 1) > -1 and myChessBoard[i-1][j].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i-1][j].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move north to take ' + myChessBoard[i-1][j].color + ' ' + myChessBoard[i-1][j].piece + '@' + myChessBoard[i-1][j].square
count+=1
else: #king moves to empty space north
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move north to ' + myChessBoard[i-1][j].square
count+=1
if (i - 1) > -1 and (j + 1) < 8 and myChessBoard[i-1][j+1].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i-1][j+1].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move northeast to take ' + myChessBoard[i-1][j+1].color + ' ' + myChessBoard[i-1][j+1].piece + '@' + myChessBoard[i-1][j+1].square
count+=1
else: #king moves to empty space northeast
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move northeast to ' + myChessBoard[i-1][j+1].square
count+=1
if (j + 1) < 8 and myChessBoard[i][j+1].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i][j+1].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move east to take ' + myChessBoard[i][j+1].color + ' ' + myChessBoard[i][j+1].piece + '@' + myChessBoard[i][j+1].square
count+=1
else: #king moves to empty space east
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move east to ' + myChessBoard[i][j+1].square
count+=1
if (i + 1) < 8 and (j + 1) < 8 and myChessBoard[i+1][j+1].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i+1][j+1].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move southeast to take ' + myChessBoard[i+1][j+1].color + ' ' + myChessBoard[i+1][j+1].piece + '@' + myChessBoard[i+1][j+1].square
count+=1
else: #king moves to empty space southeast
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move southeast to ' + myChessBoard[i+1][j+1].square
count+=1
if (i + 1) < 8 and myChessBoard[i+1][j].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i+1][j].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move south to take' + myChessBoard[i+1][j].color + ' ' + myChessBoard[i+1][j].piece + '@' + myChessBoard[i+1][j].square
count+=1
else: #king moves to empty space south
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move south to ' + myChessBoard[i+1][j].square
count+=1
if (i + 1) < 8 and (j - 1) > -1 and myChessBoard[i+1][j-1].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i+1][j-1].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move southwest to take ' + myChessBoard[i+1][j-1].color + ' ' + myChessBoard[i+1][j-1].piece + '@' + myChessBoard[i+1][j-1].square
count+=1
else: #king moves to empty space southwest
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move southwest to ' + myChessBoard[i+1][j-1].square
count+=1
if (j - 1) > -1 and myChessBoard[i][j-1].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i][j-1].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move west to take ' + myChessBoard[i][j-1].color + ' ' + myChessBoard[i][j-1].piece + '@' + myChessBoard[i][j-1].square
count+=1
else: #king moves to empty space west
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move west to ' + myChessBoard[i][j-1].square
count+=1
if (i - 1) > -1 and (j - 1) > -1 and myChessBoard[i-1][j-1].color != color: #king is in bounds and not blocked by own piece
if myChessBoard[i-1][j-1].piece != '0': #king takes opposite piece
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move northwest to take ' + myChessBoard[i-1][j-1].color + ' ' + myChessBoard[i-1][j-1].piece + '@' + myChessBoard[i-1][j-1].square
count+=1
else: #king moves to empty space northwest
print str(count) + ': ' + color + ' king@' + myChessBoard[i][j].square + ' move northwest to ' + myChessBoard[i-1][j-1].square
count+=1
return
def listPawnMoves(myChessBoard, color, i, j):
count = 1
if myChessBoard[i][j].color == 'w': #pawn is white. move north.
if (i - 1) > -1 and myChessBoard[i-1][j].piece == '0': #pawn is in bounds and not blocked by own piece
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move north to ' + myChessBoard[i-1][j].square
count+=1
if i == 6:
if myChessBoard[i-2][j].piece == '0':
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move north to ' + myChessBoard[i-2][j].square
count+=1
if (i - 1) > -1 and (j - 1) > -1 and myChessBoard[i-1][j-1].color != color and myChessBoard[i-1][j-1].piece != '0': #can take piece diagonal from pawn
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move northwest to take ' + myChessBoard[i-1][j-1].color + ' ' + myChessBoard[i-1][j-1].piece + '@' + myChessBoard[i-1][j-1].square
count+=1
if (i - 1) > -1 and (j + 1) < 8 and myChessBoard[i-1][j+1].color != color and myChessBoard[i-1][j+1].piece != '0':
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move northeast to take ' + myChessBoard[i-1][j+1].color + ' ' + myChessBoard[i-1][j+1].piece + '@' + myChessBoard[i-1][j+1].square
count+=1
else: #pawn is black. move south.
if (i + 1) < 8 and myChessBoard[i+1][j].piece == '0': #pawn is in bounds and not blocked by own piece
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move south to ' + myChessBoard[i+1][j].square
count+=1
if i == 1:
if myChessBoard[i+2][j].piece == '0':
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move south to ' + myChessBoard[i+2][j].square
count+=1
if (i + 1) < 8 and (j - 1) > -1 and myChessBoard[i+1][j-1].color != color and myChessBoard[i+1][j-1].piece != '0': #can take piece diagonal from pawn
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move southwest to take ' + myChessBoard[i+1][j-1].color + ' ' + myChessBoard[i+1][j-1].piece + '@' + myChessBoard[i+1][j-1].square
count+=1
if (i + 1) < 8 and (j + 1) < 8 and myChessBoard[i+1][j+1].color != color and myChessBoard[i+1][j+1].piece != '0':
print str(count) + ': ' + color + ' pawn@' + myChessBoard[i][j].square + ' move southeast to take ' + myChessBoard[i+1][j+1].color + ' ' + myChessBoard[i+1][j+1].piece + '@' + myChessBoard[i+1][j+1].square
count+=1
return
def listMoves(myChessBoard, color):
for i in range(0,8):
for j in range(0,8):
if myChessBoard[i][j].color != color:
continue
if myChessBoard[i][j].piece == 'rook':
listRookMoves(myChessBoard, color, i, j)
elif myChessBoard[i][j].piece == 'knight':
listKnightMoves(myChessBoard, color, i, j)
elif myChessBoard[i][j].piece == 'bishop':
listBishopMoves(myChessBoard, color, i, j)
elif myChessBoard[i][j].piece == 'queen':
listQueenMoves(myChessBoard, color, i, j)
elif myChessBoard[i][j].piece == 'king':
listKingMoves(myChessBoard, color, i, j)
else:
listPawnMoves(myChessBoard, color, i, j)
return
'''
PLEASE DO NOT MODIFY CODE ABOVE
'''
'''
The board is already set for initial states for all pieces.
MODIFY STATE OF CHESSBOARD BELOW
square = chessSquare('piece', 'color', 'square')
modify by changing piece, and color parameter only. Do not change square parameter.
Here is the order of the board for your reference:
[a8,b8,c8,d8,e8,f8,g8,h8],
[a7,b7,c7,d7,e7,f7,g7,h7],
[a6,b6,c6,d6,e6,f6,g6,h6],
[a5,b5,c5,d5,e5,f5,g5,h5],
[a4,b4,c4,d4,e4,f4,g4,h4],
[a3,b3,c3,d3,e3,f3,g3,h3],
[a2,b2,c2,d2,e2,f2,g2,h2],
[a1,b1,c1,d1,e1,f1,g1,h1]
'''
a1 = chessSquare('rook','w','a1')
b1 = chessSquare('knight','w','b1')
c1 = chessSquare('bishop','w','c1')
d1 = chessSquare('king','w','d1')
e1 = chessSquare('queen','w','e1')
f1 = chessSquare('bishop','w','f1')
g1 = chessSquare('knight','w','g1')
h1 = chessSquare('rook','w','h1')
a2 = chessSquare('pawn','w','a2')
b2 = chessSquare('pawn','w','b2')
c2 = chessSquare('pawn','w','c2')
d2 = chessSquare('pawn','w','d2')
e2 = chessSquare('pawn','w','e2')
f2 = chessSquare('pawn','w','f2')
g2 = chessSquare('pawn','w','g2')
h2 = chessSquare('pawn','w','h2')
a3 = chessSquare('0','0','a3')
b3 = chessSquare('0','0','b3')
c3 = chessSquare('0','0','c3')
d3 = chessSquare('0','0','d3')
e3 = chessSquare('0','0','e3')
f3 = chessSquare('0','0','f3')
g3 = chessSquare('0','0','g3')
h3 = chessSquare('0','0','h3')
a4 = chessSquare('0','0','a4')
b4 = chessSquare('0','0','b4')
c4 = chessSquare('0','0','c4')
d4 = chessSquare('0','0','d4')
e4 = chessSquare('0','0','e4')
f4 = chessSquare('0','0','f4')
g4 = chessSquare('0','0','g4')
h4 = chessSquare('0','0','h4')
a5 = chessSquare('0','0','a5')
b5 = chessSquare('0','0','b5')
c5 = chessSquare('0','0','c5')
d5 = chessSquare('0','0','d5')
e5 = chessSquare('0','0','e5')
f5 = chessSquare('0','0','f5')
g5 = chessSquare('0','0','g5')
h5 = chessSquare('0','0','h5')
a6 = chessSquare('0','0','a6')
b6 = chessSquare('0','0','b6')
c6 = chessSquare('0','0','c6')
d6 = chessSquare('0','0','d6')
e6 = chessSquare('0','0','e6')
f6 = chessSquare('0','0','f6')
g6 = chessSquare('0','0','g6')
h6 = chessSquare('0','0','h6')
a7 = chessSquare('pawn','b','a7')
b7 = chessSquare('pawn','b','b7')
c7 = chessSquare('pawn','b','c7')
d7 = chessSquare('pawn','b','d7')
e7 = chessSquare('pawn','b','e7')
f7 = chessSquare('pawn','b','f7')
g7 = chessSquare('pawn','b','g7')
h7 = chessSquare('pawn','b','h7')
a8 = chessSquare('rook','b','a8')
b8 = chessSquare('knight','b','b8')
c8 = chessSquare('bishop','b','c8')
d8 = chessSquare('king','b','d8')
e8 = chessSquare('queen','b','e8')
f8 = chessSquare('bishop','b','f8')
g8 = chessSquare('knight','b','g8')
h8 = chessSquare('rook','b','h8')
'''
The board is already set for initial states for all pieces.
MODIFY STATE OF CHESSBOARD ABOVE
square = chessSquare('piece', 'color', 'square')
modify by changing piece, and color parameter only. Do not change square parameter.
Here is the order of the board for your reference:
[a8,b8,c8,d8,e8,f8,g8,h8],
[a7,b7,c7,d7,e7,f7,g7,h7],
[a6,b6,c6,d6,e6,f6,g6,h6],
[a5,b5,c5,d5,e5,f5,g5,h5],
[a4,b4,c4,d4,e4,f4,g4,h4],
[a3,b3,c3,d3,e3,f3,g3,h3],
[a2,b2,c2,d2,e2,f2,g2,h2],
[a1,b1,c1,d1,e1,f1,g1,h1]
'''
myChessBoard=[[a8,b8,c8,d8,e8,f8,g8,h8], #PLEASE DO NOT MODIFY ORDER OF ELEMENTS IN myChessBoard
[a7,b7,c7,d7,e7,f7,g7,h7],
[a6,b6,c6,d6,e6,f6,g6,h6],
[a5,b5,c5,d5,e5,f5,g5,h5],
[a4,b4,c4,d4,e4,f4,g4,h4],
[a3,b3,c3,d3,e3,f3,g3,h3],
[a2,b2,c2,d2,e2,f2,g2,h2],
[a1,b1,c1,d1,e1,f1,g1,h1]]
'''
Function: listMoves(myChessBoard, color)
Inputs: myChessBoard- (do not have to change argument)
color - player's turn ('b' for black; 'w' for white)
More details in the comments at the very beginning!
'''
listMoves(myChessBoard,'w')
|
853aed70158b6c4f63141fe2fe05293f000cc8a2 | watsonpy/watson-validators | /watson/validators/numeric.py | 970 | 3.90625 | 4 | # -*- coding: utf-8 -*-
from watson.validators import abc
class Range(abc.Validator):
"""Validates the length of a string.
Example:
.. code-block:: python
validator = Length(1, 10)
validator('Test') # True
validator('Testing maximum') # raises ValueError
"""
def __init__(self, min=None, max=None,
message='"{value}" is not between {min} and {max}'):
self.message = message
if not max or not min:
raise ValueError('Min and max must be specified')
if min > max:
raise ValueError('Min cannot be greater than max')
self.min = min
self.max = max
def __call__(self, value, **kwargs):
if float(value) > self.max or float(value) < self.min:
raise ValueError(
self.message.format(
value=value,
min=self.min,
max=self.max))
return True
|
a499e78d9429cec4e7048d27c28dd2dd8eaca328 | RogerEC/CP-ICPC-Training | /Online-Judges/URI/Python/Iniciante/1064.py | 167 | 3.640625 | 4 | cont=0; soma=0.0
for i in range(6):
x=float(input())
if x>=0.0:
soma+=x
cont+=1
print("%d valores positivos" %cont)
print("%.1f" %(soma/cont))
|
0e9d463a1be1a09c63a62e1c4bbcfd01ffa21a02 | RogerEC/CP-ICPC-Training | /Online-Judges/URI/Python/Iniciante/1036.py | 246 | 3.6875 | 4 | a,b,c=input().split(' ')
a=float(a)
b=float(b)
c=float(c)
if a==0.0 or (b**2-4.0*a*c)<0:
print('Impossivel calcular')
else:
print("R1 = %.5f" %((-b+(b**2-4.0*a*c)**0.5)/(2.0*a)))
print("R2 = %.5f" %((-b-(b**2-4.0*a*c)**0.5)/(2.0*a)))
|
2e05f177f5f475c7f3ab4beb0357bb05546ad353 | RogerEC/CP-ICPC-Training | /Online-Judges/URI/Python/Iniciante/1011.py | 78 | 3.609375 | 4 | pi=3.14159
raio=float(input())
print("VOLUME = %.3f" %((4.0*pi*raio**3)/3.0))
|
fe8346b404dff136d32a77750c4564b7beef8397 | mohlinna/AoC2020 | /day8/aoc8.py | 613 | 3.703125 | 4 | def run_program(instructions):
acc = 0
line = 0
run_lines = set()
while line not in run_lines:
run_lines.add(line)
instruction = instructions[line].split()
op = instruction[0]
arg = int(instruction[1])
if op == 'jmp':
line += arg
elif op == 'acc':
acc += arg
line += 1
elif op == 'nop':
line += 1
return acc
if __name__ == '__main__':
file1 = open('input.txt', 'r')
lines = file1.readlines()
accumulator = run_program(lines)
print("The acc is at {}".format(accumulator))
|
e9fad52f1d346aa6712257675c1ca97983269e3a | mohlinna/AoC2020 | /day5/aoc5_2.py | 607 | 3.5 | 4 |
def get_seat_id(boarding_pass):
binary_rep = boarding_pass.replace('B', '1').replace('F', '0').replace('R', '1').replace('L', '0')
return int(binary_rep, 2)
def find_my_seat(boarding_passes):
seat_ids = sorted(map(get_seat_id, boarding_passes))
print(seat_ids)
seat_candidate = seat_ids[0]
for seat in seat_ids:
if seat != seat_candidate:
return seat_candidate
seat_candidate += 1
if __name__ == '__main__':
file1 = open('input.txt', 'r')
lines = file1.readlines()
mine = find_my_seat(lines)
print("My Seat Number: {}".format(mine))
|
a75dc944ca31f4050f35556a5c749f0f34c6dc9a | kcpedrosa/Python-exercises | /ex020.py | 263 | 3.59375 | 4 | import random
a = str(input('Digite o nome do primeiro aluno: '))
b = str(input('Digite o nome do segundo aluno: '))
c = str(input('Digite o nome do terceiro aluno: '))
lista = [a, b, c]
print('A ordem de apresentação será {}'.format(random.shuffle(lista)))
|
83ab827c9060e7f55072bd6119ab777a25ce56da | kcpedrosa/Python-exercises | /ex066.py | 301 | 3.671875 | 4 | ##066 - Vários números com flag, interrupção de WHILE com BREAK
num = 0
cont = soma = 0
while True:
num = int(input('Digite um numero [e 999 para parar]: '))
if num == 999:
break
cont += 1
soma += num
print('Voce digitou {} numero[s] e sua soma foi {}'.format(cont, soma))
|
93a70e8646da7edf7963932154f9525854eed061 | kcpedrosa/Python-exercises | /ex008.py | 260 | 3.890625 | 4 | e = float(input('Digite um valor em metros: '))
km = e/1000
hm = e/100
dam = e/10
dm = e * 10
cm = e * 100
mm = e * 1000
print('O valor indicado vale {} km {} hm {} dam'.format(km, hm, dam))
print('O valor indicado vale {} dm {} cm {} mm'.format (dm, cm, mm))
|
abe613199f6440cada8ff01c173d44c96e7362de | kcpedrosa/Python-exercises | /ex071.py | 691 | 3.609375 | 4 | print('=-' * 25)
print('{:^40}'.format('BANCO DEUTSCHES BANK'))
print('=-' * 25)
valor = int(input('Digite o valor a ser sacado: R$ '))
total = valor
totalced = 0
ced = 50
while True:
if total >= ced:
total -= ced
totalced += 1
else:
#if totalced > 0 de um tab no print abaixo, o programa nao vai printar nada se
#o numero de cedulas for zero, ex 0 cedulas de $ 20
print(f'Total de {totalced} cedulas de R$ {ced}')
if ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 1
totalced = 0
if total == 0:
break
print('=-' * 20)
print('SO LONG') |
7662cf949856c7e6ec3dbc8c07c2a07e018dab91 | kcpedrosa/Python-exercises | /ex047segundomodo.py | 159 | 3.953125 | 4 | #contagem de numero par com a metade das iterações
for numero in range (2, 51, 2):
print('.', end=' ')
print(numero, end=' ')
print('Begin the game') |
17feb48a9bbf87a6799b4377b66f5db73aff3cd4 | kcpedrosa/Python-exercises | /ex055usandoLST.py | 335 | 3.890625 | 4 | # Maior e menor da sequência
lst=[]
for pessoa in range(1, 4):
peso = float(input('Digite o peso da {}ª pessoa em kgs: '.format(pessoa)))
lst+=[peso]
print('O valor do peso da {}ª pessoa é {} kgs'.format(pessoa, peso))
print('O maior peso foi {} kgs'.format(max(lst)))
print('O menor peso foi {} kgs'.format(min(lst)))
|
013ba65877e79e4b2b826c3b466ed443931570fe | kcpedrosa/Python-exercises | /ex056.py | 924 | 3.765625 | 4 | somaidade = 0
media = 0
maioridhom = 0
nomevelho = ''
totmulher20 = 0
for pess in range(1,3):
print('--- {} ª pessoa ---'.format(pess))
nome = str(input('Digite o nome da pessoa: ')).strip()
idade = int(input('Digite a idade da pessoa: '))
sexo = str(input('Digite o sexo [M/F]: ')).strip()
somaidade = somaidade + idade
if sexo in 'Mm' and pess == 1:
maioridhom = idade
nomevelho = nome
if sexo in 'Mm' and idade > maioridhom:
maioridhom = idade
nomevelho = nome
if sexo in 'Ff' and idade < 20:
totmulher20 = totmulher20 + 1
#copiado e colado porem nao entendido...
media = somaidade/2
print('A media das idades analisadas é: {:.2f} '.format(media))
print('O homem mais velho tem {} anos '.format(maioridhom))
print('O homem mais velho se chama {}'.format(nomevelho))
print('Nesse grupo há {} mulher[es] com menos de 20 anos'.format(totmulher20)) |
7d3247fe1ed6b9f4f7e4eef50209cca956deadcc | kcpedrosa/Python-exercises | /ex003.py | 186 | 3.828125 | 4 | numero1 = float (input ('Digite um valor: '))
numero2 = float (input ('Digite outro valor: '))
soma = numero1 + numero2
print ('Soma: {} mais {} dá {}'.format(numero1, numero2, soma)) |
a06e203bb0e30a1874d4448be811595b555bb59d | kcpedrosa/Python-exercises | /ex013.py | 305 | 3.65625 | 4 | salario = float(input('Digite o montante do salário: R$ '))
aumento = float(input('Digite o valor percentual do aumento: '))
salarionovo = salario * (1 + (aumento/100))
print ('Um funcionário que ganhava R$ {:.2f} , \ncom aumento de {} %, passa a receber R${:.2f}'.format(salario, aumento, salarionovo)) |
0d0af0c4388871a673dde68dd141543047cd7f19 | kcpedrosa/Python-exercises | /ex078.py | 500 | 4.0625 | 4 | #digite 5 numeros e o programa vai dizer quem é o maior E sua posição
lista=[]
for c in range(0, 5):
lista.append(int(input('Digite um número: ')))
print(f'Você digitou {lista}')
print(f'O maior valor foi {max(lista)} ...', end='')
for pos, c in enumerate(lista):
if c == max(lista):
print(f'na posição {pos}', end=' ')
print(f'\nO menor valor foi {min(lista)} ...', end='')
for pos, c in enumerate(lista):
if c == min(lista):
print(f'na posição {pos}', end=' ')
|
ab167169d58ee255733db3229d95bb5f5df4786f | kcpedrosa/Python-exercises | /ex079.py | 305 | 3.875 | 4 | lista = []
while True:
num = int(input('Digite um número: '))
if num not in lista:
lista.append(num)
else:
print('Valor duplicado. ACESS DENIED')
perg = str(input('Quer continuar? [S/N] ')).lower()
if perg in 'n':
break
print(f'Você digitou {sorted(lista)}') |
5225e5adf912762cc349331c4276b978190c8bf9 | kcpedrosa/Python-exercises | /ex005.py | 222 | 4.1875 | 4 | #faça um programa que fale de sucessor e antecessor
numero = int (input('Digite um numero: '))
ant = numero - 1
suc = numero + 1
print('Urubusevando {}, seu antecessor é {} e seu sucessor é {}'.format(numero, ant, suc)) |
05b81c7d0cfee21343ec43e07e90a80844ec1b1f | kcpedrosa/Python-exercises | /ex091.py | 774 | 3.796875 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogos = {'jogador1': randint(1, 6), 'jogador2': randint(1, 6),
'jogador3': randint(1, 6), 'jogador4': randint(1, 6)
}
ranking = []
print(' JOGO DE DADO ')
print(jogos)
for k, v in jogos.items():
print(f'O {k} tirou {v} no dado')
sleep(1)
ranking = sorted(jogos.items(), key=itemgetter(1), reverse=True)
#se colocar o itemg no 0 vai aparecer jogador4 primeiro
print(ranking)
print('=-'*30)
for pos, c in enumerate(ranking):
print(f'{pos+1}º lugar : {c[0]} com {c[1]} pontos no dado')
sleep(1)
print(' FIM ')
#COMO FAZER ESSE PROGRAMA IDENTIF OS EMPATES?
#jogo=0
#for c in range(0,4):
#jogo = randint(1,6)
#jogos['Numero']=jogo
#print(jogos) |
034be106f76495593e2d2acaa5683960bd3be045 | kcpedrosa/Python-exercises | /ex075.py | 565 | 4.125 | 4 | #Análise de dados em uma Tupla
numeros = (int(input('Digite o 1º numero: ')), int(input('Digite o 2º numero: ')),
int(input('Digite o 3º numero: ')), int(input('Digite o 4º numero: ')))
print(f'Você digitou os valores {numeros}')
print(f'O valor 9 foi digitado {numeros.count(9)} vez(es)')
if 3 in numeros:
print(f'O primeiro numero 3 está na {numeros.index(3)+1}ª posição')
else:
print(f'O numero 3 não foi digitado')
print('Os numeros pares digitados foram', end=' ')
for n in numeros:
if n % 2 == 0:
print([n], end=' ')
|
6c01da59eaf3527be1aad68a889f7eabd24cbbf9 | kcpedrosa/Python-exercises | /ex029.py | 277 | 3.75 | 4 | velocidade = float(input('Qual a velocidade do carro? Digite aqui: '))
if velocidade > 80:
print('Atenção! Você foi multado')
print('Sua multa foi de R$ {}'.format((velocidade - 80) * 7))
else:
print('Parabéns, você está dirigindo dentro dos limites da lei.') |
5f46e672e9858af9f2e6b0372d87fa2df2022c82 | kcpedrosa/Python-exercises | /ex109reforc/mainprog.py | 870 | 3.828125 | 4 | from ex109reforc import moeda
#exerc refeito pra reforçar
preço = float(input('Digite o preço do produto: '))
taxa1 = int(input('Digite uma taxa de AUMENTO: '))
taxa2 = int(input('Digite uma taxa de DIMINUIÇÃO: '))
#o primeiro moeda é o nome do módulo e o segundo é o da função[abaixo]
#o preço abx está em dolar apenas pra testar o 2nd parâmetro
print(f'O valor do produto é {moeda.moeda(preço,"U$")}')
print(f'O valor do produto com taxa de aumento é {moeda.aumentar(preço,taxa1, True)}')
print(f'O valor do produto coom taxa de diminuição é {moeda.reduzir(preço,taxa2, False)}')
print(f'A metade do valor do produto é {moeda.metade(preço,)}')
print(f'O dobro do valor do produto é {moeda.dobro(preço, True)}')
#o prof usou taxas fixas, nao colocou input pra taxa ("aumentando em 10%...")
#colocou direto moeda.aumentar(preço,10) p ex |
adf4bb569e7585898d47ddf13f1aa3d862f2d430 | kcpedrosa/Python-exercises | /ex025optmzd.py | 590 | 3.84375 | 4 | cores = {'limpa': '\033[m',
'azul': '\033[34m',
'roxo': '\033[35m',
'fundociano': '\033[46m'}
n = str(input('Digite seu nome: ')).strip()
# O programa irá jogar tudo para minusculo.
n = n.lower()
n = str('silva' in n.split())
#Split will split a string into a list where each WORD is a list item:
#sendo assim ''Silvana Sá'' sera separada em silvana e sa
#e o programa nao vai dar falso positivo
if n == str('True'):
print(f'Seu nome tem {cores["azul"]}Silva{cores["limpa"]}')
else:
print(f'Seu nome não tem {cores["fundociano"]}Silva{cores["limpa"]}') |
b6916ffc42aa78e03f2a0a8c9acdf4994c834509 | NightHydra/HonChemCalc | /Chapter_6_Menu.py | 11,446 | 3.625 | 4 | from Thermochemistry import *
from Number_Validation import *
def Thermo_Menu(): # Main menu for chapter 6
print ("\nChapter 6 Menu:\n")
print ("Rules:\n")
print ("Please input all mass in grams")
print ("Please input all temperature in Celcius")
print ("Please input all specific heat values in cal/gC\n")
while True:
print ("Enter 0 to just calculate energy lost/gained")
print ("Enter 1 to solve equations without a calorimeter")
print ("Enter 2 to solve equations using a calorimeter")
print ("Enter 3 to return to the main menu")
option = input()
while option not in ['0', '1', '2', '3']:
option = input("You must enter either 0, 1 , or 2 ")
if option == '0':
Enthalpy_Menu()
if option == '1':
No_Calorimeter_Equation_Menu()
if option == '2':
Calorimeter_Equation_Menu()
if option == '3':
return ()
def Enthalpy_Menu(): # Finds heat lost or gained
variables = []
mass = get_others("What is the mass of the object? (enter u is this is your unknown) ")
heat = get_temp("What is the intital temperature of the object? (this cannot be an unknown) ", accepts_u = False)
sph = get_others("What is the specific heat value of the object? (enter u is this is your unknown) ")
cal = get_others("How many calories did the object lose/gain? (enter u is this is your unknown) ")
fin_H = get_temp("What is the final temperature of the object? (this cannot be an unknown) ", accepts_u = False)
variables = [mass, heat, sph, cal, fin_H]
while (variables.count("u")+variables.count("unknown")) != 1: #Input Validation
print ("You need to have exactly one unknown!")
mass = get_others("What is the mass of the object? (enter u is this is your unknown) ")
heat = get_temp("What is the intital temperature of the object? (this cannot be an unknown) ", accepts_u = False)
sph = get_others("What is the specific heat value of the object? (enter u is this is your unknown) ")
cal = get_others("How many calories did the object lose or gain? (enter u is this is your unknown) ")
fin_H = get_temp("What is the final temperature of the object? (this cannot be an unknown) ", accepts_u = False)
variables = [mass, heat, sph, cal, fin_H]
if "u" in variables:
variables.remove("u")
if "unknown" in variables:
variables.remove("unknown")
u = ["u", "unknown"]
#Gets the answer
if mass in u:
print ("The mass of the object is",Enthalpy.Get_Mass(*variables),"g")
elif sph in u:
print ("The SPH of the object is",Enthalpy.Get_SPH(*variables),"cal/gC")
elif cal in u:
print ("The object gained or lost",Enthalpy.Get_Total_Enthalpy(*variables), "cal")
def No_Calorimeter_Equation_Menu(): # Solves equations that do not use a calorimeter
# Very similar in code to the last one except more variables
mass_obj = get_others("What is the mass of the object? (enter u is this is your unknown) ")
heat_obj = get_temp("What is the intital temperature of the object? (enter u is this is your unknown) ")
sph_obj = get_others("What is the specific heat value of the object? (enter u is this is your unknown) ")
mass_l = get_others("What is the mass of the liquid? (enter u is this is your unknown) ")
heat_l = get_temp("What is the intital temperature of the liquid? (enter u is this is your unknown) ")
sph_l = get_others("What is the specific heat value of the liquid? (enter u is this is your unknown) ")
fin_H = get_temp("What is the final temperature of everything? (enter u is this is your unknown) ")
variables = [mass_obj, mass_l, heat_obj, heat_l, sph_obj, sph_l, fin_H]
gain_loss = False
if fin_H != "u" and heat_obj != "u" and heat_l != "u":
gain_loss = (fin_H < heat_obj == fin_H < heat_l)
while (variables.count("u")+variables.count("unknown")) != 1 or (gain_loss): # One unknown is required and one side must gain heat while the other side loses it
if gain_loss == True:
print ("One part must gain heat and the other must lose heat")
else:
print ("You must have exactly one unknown in your equation")
mass_obj = get_others("What is the mass of the object? (enter u is this is your unknown) ")
heat_obj = get_temp("What is the intital temperature of the object? (enter u is this is your unknown) ")
sph_obj = get_others("What is the specific heat value of the object? (enter u is this is your unknown) ")
mass_l = get_others("What is the mass of the liquid? (enter u is this is your unknown) ")
heat_l = get_temp("What is the intital temperature of the liquid? (enter u is this is your unknown) ")
sph_l = get_others("What is the specific heat value of the liquid? (enter u is this is your unknown) ")
fin_H = get_temp("What is the final temperature of everything? (enter u is this is your unknown) ")
variables = [mass_obj, mass_l, heat_obj, heat_l, sph_obj, sph_l, fin_H]
if fin_H != "u" and heat_obj != "u" and heat_l != "u":
gain_loss = (fin_H < heat_obj == fin_H < heat_l)
u = ["u", "unknown"]
unknown_type = ""
for i in variables[0:5:2]:
if i in u:
unknown_type = "object"
variables = [mass_l, mass_obj, heat_l, heat_obj, sph_l, sph_obj, fin_H] # Flips around variables if the unknown is about the object
if unknown_type == "":
for i in variables[1:2]:
if i in u:
unknown_type = "liquid"
if "u" in variables:
variables.remove("u")
if "unknown" in variables:
variables.remove("unknown")
if mass_obj in u or mass_l in u:
print ("The mass of the",unknown_type,"is",No_Calorimeter_Equations.get_mass(*variables), "g")
elif sph_obj in u or sph_l in u:
print ("The SPH of the", unknown_type, "is",No_Calorimeter_Equations.get_SPH(*variables), "cal/gC")
elif heat_obj in u or heat_l in u:
print ("The initial heat of the", unknown_type, "is",No_Calorimeter_Equations.get_init_heat(*variables), "C")
elif fin_H in u:
print ("The final heat of everything is",No_Calorimeter_Equations.get_final_heat(*variables), "C")
def Calorimeter_Equation_Menu(): # Finds Equations using a calorimeter
# Calorimeter - What the liquid and object are in. It absorbs heat as well.
mass_obj = get_others("What is the mass of the object? (enter u is this is your unknown) ")
heat_obj = get_temp("What is the intital temperature of the object? (enter u is this is your unknown) ")
sph_obj = get_others("What is the specific heat value of the object? (enter u is this is your unknown) ")
mass_l = get_others("What is the mass of the liquid? (enter u is this is your unknown) ")
heat_liqCal = get_temp("What is the intital temperature of the liquid and calorimeter? (enter u is this is your unknown) ") # Calorimeter and Liquid are same temp
sph_l = get_others("What is the specific heat value of the liquid? (enter u is this is your unknown) ")
mass_calor = get_others("What is the mass of the calorimeter (enter u is this is your unknown) ")
sph_calor = get_others("What is the SPH of the calorimeter (enter u is this is your unknown) ")
fin_H = get_temp("What is the final temperature of everything? (enter u is this is your unknown) ")
variables = [mass_obj, sph_obj, heat_obj, mass_l, sph_l, heat_liqCal, mass_calor, sph_calor, fin_H]
gain_loss = False
if fin_H != "u" and heat_obj != "u" and heat_liqCal != "u":
gain_loss = fin_H < heat_obj == fin_H < liqCal
while (variables.count("u")+variables.count("unknown")) != 1 or (gain_loss):
if gain_loss == True:
print ("One side of the equation must gain heat and the other must lose heat")
else:
print ("You must have exactly 1 unknown")
mass_obj = get_others("What is the mass of the object? (enter u is this is your unknown) ")
heat_obj = get_temp("What is the intital temperature of the object? (enter u is this is your unknown) ")
sph_obj = get_others("What is the specific heat value of the object? (enter u is this is your unknown) ")
mass_l = get_others("What is the mass of the liquid? (enter u is this is your unknown) ")
heat_liqCal = get_temp("What is the intital temperature of the liquid and calorimeter? (enter u is this is your unknown) ")
sph_l = get_others("What is the specific heat value of the liquid? (enter u is this is your unknown) ")
mass_calor = get_others("What is the mass of the calorimeter (enter u is this is your unknown) ")
sph_calor = get_others("What is the SPH of the calorimeter (enter u is this is your unknown) ")
fin_H = get_temp("What is the final temperature of everything? (enter u is this is your unknown) ")
variables = [mass_obj, sph_obj, heat_obj, mass_l, sph_l, heat_liqCal, mass_calor, sph_calor, fin_H]
if fin_H != "u" and heat_obj != "u" and heat_liqCal != "u":
gain_loss = fin_H < heat_obj == fin_H < liqCal
u = ["u", "unknown"]
unknown_type = ""
for i in variables[3:5]:
if i in u:
unknown_type == "liquid"
for i in variables[6:]:
if i in u:
unknown_type == "calorimeter"
if "u" in variables:
variables.remove("u")
if "unknown" in variables:
variables.remove("unknown")
if mass_obj in u:
print ("The mass of the object is",Calorimeter_Equations.get_Mass_Obj(*variables), "g")
elif sph_obj in u:
print ("The SPH of the object is",Calorimeter_Equations.get_SPH_Obj(*variables), "cal/gC")
elif heat_obj in u:
print ("The initial heat of the object is",Calorimeter_Equations.get_Heat_Obj(*variables), "C")
elif mass_l in u or mass_calor in u:
print ("The mass of the", unknown_type, "is",Calorimeter_Equations.get_Mass_Liquid(*variables),"g")
elif sph_l in u or sph_calor in u:
print ("The SPH of the", unknown_type, "is", Calorimeter_Equations.get_SPH_Liquid(*variables),"g")
elif heat_liqCal in i:
print ("The initial heat of the liquid and calorimeter is", Calorimeter_Equations.get_Heat_LiqCal(*variables))
elif fin_H in u:
print ("The final heat of everything is",Calorimeter_Equations.get_final_heat(*variables), "C")
def get_temp(message, accepts_u = True): # Function that gets the input for a temperature, will sometimes not accept u (Can be positive)
temp = input(message)
while valid_num(temp, domain = "(-inf, inf)") == False:
if accepts_u == True and temp in ["u", "unknown"]:
break
print ("You need to input a number")
temp = input(message)
if temp not in ["u", "unknown"]:
temp = float(temp)
return temp
def get_others(message): # Makes sure input is posivie
val = input(message)
while valid_num(val, domain = "(0, inf)") == False and val not in ["u", "unknown"]:
print ("You need to input a positive number")
val = input(message)
if val not in ["u", "unknown"]:
val = float(val)
return val
|
31029ba30520ba0f0f52246450554c8db3de6aac | nonlogic/BuildingTimeSeries | /linreg.py | 1,869 | 3.515625 | 4 | import numpy
from sklearn import linear_model
# Function to normalize data:
def normalize(X):
mean_r = []
std_r = []
X_norm = X
n_c = X.shape[1]
for i in range(n_c):
m = numpy.mean(X[:, i])
s = numpy.std(X[:, i])
mean_r.append(m)
std_r.append(s)
X_norm[:, i] = (X_norm[:, i] - m) / s
return X_norm
# Load data matrix from file:
data = numpy.loadtxt('matrix.dat')
# Randomize the examples in the matrix:
numpy.random.shuffle(data)
# First column (column 0) in matrix is Qcooling value, which is y.
# Second column (column 1) in matrix is Tsupply.
# The rest of the matrix (columns 2 - end) are the Tzone values for each zone.
# This is placed in X:
X = data[:, 2:]
# Subtract Tsupply from Tzone for each zone:
for i in range(1,X.shape[1]):
X[:, i] -= data[:, 1]
# Normalize the value of X:
X = normalize(X)
# Extend X to include all-ones feature:
beta = numpy.array([numpy.ones(X.shape[0])]).T
X = numpy.concatenate((beta, X), axis=1)
# Set y to Qcooling value:
y = numpy.array([data[:,0]]).T
# Create split between training and test data (currently 9:1):
split = int(X.shape[0] * 0.1)
X_train = X[:-split]
X_test = X[-split:]
y_train = y[:-split]
y_test = y[-split:]
# Train the linear regression model using Scikit's least-squares implementation:
regr = linear_model.LinearRegression()
regr.fit(X_train, y_train)
# Output the trained coefficients:
print('Coefficients: \n', regr.coef_)
# Output mean percentage error, square error, and variance score:
print('Mean percentage error: %.2f' % numpy.mean((numpy.abs(regr.predict(X_test) - y_test) / y_test) * 100))
print("Residual sum of squares: %.2f" % numpy.mean((regr.predict(X_test) - y_test) ** 2))
print('Variance score: %.2f' % regr.score(X_test, y_test)) |
b8749de2613cdc9ec48f3dd0ef26e07e8ef265c3 | fazejohk/Beginner-Projects | /Sentence-Gen/sentencegen.py | 453 | 3.53125 | 4 | import random
import time
first={
1:"What", 2:"Where", 3:"When", 4:"who"
}
second={
1:"did", 2:"you", 3:"were", 4:"do"
}
third={
1:"it", 2:"she", 3:"he", 4:"nibba"
}
fourth={
1:"do", 2:"eat", 3:"shit", 4:"steal"
}
random1=random.randint(1,4)
random2=random.randint(1,4)
print(first[random1])
time.sleep(1)
print(second[random2])
time.sleep(1)
print(third[random1])
time.sleep(1)
print(fourth[random2])
time.sleep(1)
print("""
""")
|
e8642c64ba0981f3719635db11e52a0823e89b68 | league-python/Level1-Module0 | /_02_strings/_a_intro_to_strings.py | 2,954 | 4.6875 | 5 | """
Below is a demo of how to use different string methods in Python
For a complete reference:
https://docs.python.org/3/library/string.html
"""
# No code needs to be written in this file. Use it as a reference for the
# following projects.
if __name__ == '__main__':
# Declaring and initializing a string variable
new_str = "Welcome to Python!"
# Getting the number of characters in a string
num_characters = len(new_str)
# Getting a character from a string by index--similar to lists
character = new_str[2] # 'l'
print(character)
# Check if a character is a letter or a number
print('Is ' + new_str[2] + ' a letter: ' + str(new_str[2].isalpha()))
print('Is ' + new_str[2] + ' a digit: ' + str(new_str[2].isdigit()))
# Removing leading and trailing whitespace from a string
whitespace_str = ' This string has whitespace '
print('original string .......: ' + whitespace_str + ' ' + str(len(whitespace_str)))
print('leading spaces removed : ' + whitespace_str.lstrip() + ' ' + str(len(whitespace_str.lstrip())))
print('trailing spaces removed: ' + whitespace_str.rstrip() + ' ' + str(len(whitespace_str.rstrip())))
print('leading and trailing spaces removed: ' + whitespace_str.strip() + ' ' + str(len(whitespace_str.strip())))
# Find the number of times a substring (or letter) appears in a string
num_character = new_str.count('o') # 3 occurrences
num_substring = new_str.count('to') # 1 occurrences
print('\'o\' occurs ' + str(num_character) + ' times')
print('\'to\' occurs ' + str(num_substring) + ' times')
# Making a copy of a string
str_copy = new_str[:]
# Convert string to all upper case or lower case
print(str_copy.upper())
print(str_copy.lower())
print(new_str)
# Getting a substring from a string [<stat>:<end>], <end> is NOT inclusive
new_substring1 = new_str[0:7] # 'Welcome'
new_substring2 = new_str[8:10] # 'to
new_substring3 = new_str[11:] # 'Python!'
print(new_substring1)
print(new_substring2)
print(new_substring3)
# Finding the index of the first matching character or substring
index = new_str.find('o')
print('\'o\' 1st appearance at index: ' + str(index))
index = new_str.find('o', index+1)
print('\'o\' 2nd appearance at index: ' + str(index))
# Converting a string to a list
new_str_list = list(new_str)
print(new_str_list)
# Converting a list to a string
back_to_string = ''.join(new_str_list)
print(back_to_string)
# Converting a list to a string with a separator (delimiter)
back_to_string = '_'.join(new_str_list)
print(back_to_string)
# Replacing characters from a string
back_to_string = back_to_string.replace('_', '')
print(back_to_string)
# Splitting a string into a list of strings separated by a space ' '
split_str_list = new_str.split(' ')
print(split_str_list)
|
163249718b991047cfb3c5245332ec871080a1e4 | kingwongf/basic_algos | /basic_algos3.py | 4,180 | 3.8125 | 4 |
def merge_sort(arr):
if len(arr)>1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
return arr
def recur_fib(n):
if n ==1:
return 1
elif n==2:
return 1
else:
return recur_fib(n-1) + recur_fib(n-2)
def prime_sieve(n):
primes = [True]*(n+1)
p=2
while p*p<=n:
if primes[p]:
for j in range(p*2,n+1,p):
primes[j] = False
p+=1
return [p for p in range(n+1) if primes[p]]
def non_recur_fib(n):
d=[1,1]
while len(d)< n:
d.append(d[-1]+d[-2])
return d
def merge_sort2(arr):
if len(arr)>1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort2(L)
merge_sort2(R)
i=j=k=0
while len(L) > i and len(R) > j:
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
while len(L) >i:
arr[k] = L[i]
i+=1
k+=1
while len(R) >j:
arr[k] = R[j]
j+=1
k+=1
return arr
def binary_search(arr, elem):
print(list(zip(arr, list(range(len(arr))))))
sorted_arr = merge_sort(arr)
lb = 0
ub = len(sorted_arr) -1
while lb <=ub:
mid = (lb +ub)//2
if sorted_arr[mid] > elem:
ub = mid -1
elif sorted_arr[mid] < elem:
lb = mid +1
elif sorted_arr[mid] == elem:
return mid
return 'not in list'
def bubble_sort(arr):
for i in range(len(arr)):
swapped=False
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped=True
if swapped is False:
return arr
def part(arr, low, high):
i = low-1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i+=1
arr[i],arr[j] = arr[j], arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return i+1
def quick_sort(arr, low, high):
if low < high:
pi = part(arr, low, high)
quick_sort(arr, low, pi-1)
quick_sort(arr, pi+1, high)
def beta(X,y):
import numpy as np
return np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
def nonrecur_factorial(n):
r=n
for i in range(1,n-1):
r*=(n-i)
return r
def combinations(n,k):
'''
nCr = n!/((n-k)!*(k!))
= (n*(n-1)*(n-2) *...*(n-k+1))/ (k(k-1)(k-2)*...*(1))
:param n:
:param k:
:return:
'''
r = 1
for i in range(k):
r*= (n-i)
r= r/(i+1)
return r
def permutation(n,k):
'''
nPr = n!/k!
= n(n-1)(n-2)*...*(n-k+1)
:param n:
:param k:
:return:
'''
r = 1
for i in range(k):
r*= (n-i)
return r
def part2(arr, low, high):
i = low-1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i+=1
arr[j], arr[i] = arr[i], arr[j]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i +1
def quicksort2(arr,low,high):
if low < high:
pi = part2(arr,low,high)
quicksort2(arr, low, pi-1)
quicksort2(arr, pi+1, high)
print('merge sort')
print(merge_sort([6,4,2,1,7,4,3]))
print("non recur fib")
print(non_recur_fib(10))
print("recur fib")
print(recur_fib(10))
print('merge sort 2')
print(merge_sort([6,4,2,1,7,4,3]))
print('bubble sort')
print(merge_sort([6,4,2,1,7,4,3]))
print('binary search')
print(binary_search([6,4,2,1,7,4,3], 3))
print([6,4,2,1,7,4,3].index(3))
print('quick sort')
li = [6,4,2,1,7,4,3]
low = 0
high = len(li)-1
quick_sort(li, low,high)
print(li)
|
d84ca3a229d7603d0eeb4781c770e4ec1853dee7 | LeviMorningstar/Anotacoes-de-aulas | /PandasAula 3(DrataFrame Seleção Condicional, set_index).py | 581 | 3.53125 | 4 | import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
df = pd.DataFrame(randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())
bol = df > 0
print(df[bol])
print()
df = df[df['W'] >0]
print(df)
# o 'and' nao consegue tratar Series entao o '&' entra no lugar dele.
# o 'or' nao consegue tratar Series enttao o '|' entra no lugar dele.
df.reset_index(inplace=True)
print(df)
print()
col ='RS RJ SP AM'.split()
df['Estado'] = col
df.set_index('Estado', inplace=True)
print(df)
input('Sair') |
8d4d6b1f7fcacf7d519c6bddb7038039754ba871 | maxrosssp/project-euler | /problems/p19.py | 1,136 | 4.03125 | 4 | def isLeapYear(year):
if year % 4 != 0:
return False
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return True
def thirty_day_month(year):
return 30
def thirty_one_day_month(year):
return 31
def february(year):
return 29 if isLeapYear(year) else 28
days_in_month = {
0: thirty_one_day_month,
1: february,
2: thirty_one_day_month,
3: thirty_day_month,
4: thirty_one_day_month,
5: thirty_day_month,
6: thirty_one_day_month,
7: thirty_one_day_month,
8: thirty_day_month,
9: thirty_one_day_month,
10: thirty_day_month,
11: thirty_one_day_month
}
days_of_week = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
def get_day_of_week(end_month, end_year):
day = 1
month = 0
year = 1900
sundays = 0
while year < end_year:
for i in range(12):
day = (day + days_in_month[month](year)) % 7
if day == 0:
sundays += 1
year += 1
for i in range(end_month):
day = (day + days_in_month[month](year)) % 7
if day == 0:
sundays += 1
return sundays
print(get_day_of_week(11, 2000) - get_day_of_week(11, 1901))
|
3d000553a48f8852f1ffb21bd4543b9fc217fc8b | maxrosssp/project-euler | /problems/p4.py | 728 | 3.640625 | 4 | def isPallindrome(n):
nStr = str(n)
nStrLen = len(nStr)
mid = nStrLen / 2
i = 0
while i < mid:
if nStr[i] != nStr[(nStrLen - 1) - i]:
return False
i += 1
return True
print('True: '),
print(isPallindrome(123321))
print('True: '),
print(isPallindrome(1235321))
print('False: '),
print(isPallindrome(123421))
print('False: '),
print(isPallindrome(124321))
def findLargestPallindrome():
x = 999
largestPallindrome = 0
while x > 0:
if largestPallindrome > (x * 999):
return largestPallindrome
y = x
while y <= 999:
prod = x * y
if isPallindrome(prod) and prod > largestPallindrome:
largestPallindrome = prod
y += 1
x -= 1
return largestPallindrome
print(findLargestPallindrome()) |
5e0dd91694bc5b7b0147492d6401183a51a45330 | mkrostm/Udacity-BikeShare-project | /bikeshare.py | 12,652 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Mohamed Kamel
"""
import time
import datetime
import pandas as pd
CITY_DATA = { 'chicago': 'Data/chicago.csv',
'new york city': 'Data/new_york_city.csv',
'washington': 'Data/washington.csv' }
months =['january','february','march','april','may','june']
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
months_abbreviation ={'jan':'january','feb':'february','mar':'march','apr':'april','may':'may','jun':'june'}
days_abbreviation ={'sun':'sunday','mon':'monday','tu':'tuesday','wed':'wednesday','thu':'thursday','fri':'friday','sat':'saturday'}
print('\n Hello! Let\'s explore some US bikeshare data!')
# ask user to choose city
selected_city = input('\n please select city to show \n \n Type letter a or b or c \n \n Letter (a) for Chicago \n Letter (b) for New York City \n Letter (c) for Washington \n\n').lower()
while selected_city not in ['a','b','c'] :
#Showing wrong choice message to the user and ask again type the correct letter
print('\n Wrong choice \n')
selected_city = input('\n please select city to show \n \n Type letter a or b or c \n \n Letter (a) for Chicago \n Letter (b) for New York City \n Letter (c) for Washington \n\n').lower()
#
if selected_city == 'a' :
city = 'chicago'
print('Your choice is {}'.format(city))
elif selected_city == 'b':
city = 'new york city'
print('Your choice is {}'.format(city))
elif selected_city == 'c':
city = 'washington'
print('Your choice is {}'.format(city))
#ask user to choose filter by month ,day , both day and month or no filter and put the result in time_frame var
time_frame = input('\n Would you like to filter {}\'s data by month, day, both, or not at all? type month or day or both or none: \n'.format(city.title())).lower()
# if user type wrong filter word, ask him again to type the filter
while time_frame not in ['month' , 'day' , 'both' , 'none'] :
print('\n Wrong choice \n')
time_frame = input('\n\n Would you like to filter {}\'s data by month, day, both, or not at all? \n type month or day or both or none: \n'.format(city.title())).lower()
# filter by all 6 months
if time_frame == 'none' :
month ='all'
day ='all'
print('Your choice is all 6 months.')
# filter by month
elif time_frame == 'month':
# ask user to choose month in put it in selected_month var
selected_month = input('Which month ? \n type jan,feb,mar,apr,may,jun \n').lower()
# while user type wrong word ask him again to type month
while selected_month not in months_abbreviation:
print('\n wrong choice \n')
selected_month = input('Which month ? \n type jan,feb,mar,apr,may,jun \n').lower()
# get the month name from months_abbreviation dict and set day to all
month = months_abbreviation.get(selected_month)
day ='all'
print('Your choice is {}'.format(month))
# filter by day
elif time_frame == 'day':
# ask user to choose day in put it in selected_day var
selected_day = input('\n Which day ? \n type sun,mon,tu,wed,thu,fri or sat \n').lower()
# while user type wrong word ask him again to type day
while selected_day not in days_abbreviation:
print('\n wrong choice \n')
selected_day = input('Which day ? \n type sun,mon,tu,wed,thu,fri or sat \n').lower()
# get the day name from days_abbreviation dict and set month to all
day = days_abbreviation.get(selected_day)
month= 'all'
print('Your choice is {}'.format(day))
# filter by month and day
elif time_frame == 'both':
# ask user to choose month in put it in selected_month var
selected_month = input('Which month ? \n type jan,feb,mar,apr,may,jun \n').lower()
# while user type wrong word ask him again to type month
while selected_month not in months_abbreviation:
print('\n wrong choice \n')
selected_month = input('Which month ? \n type jan,feb,mar,apr,may,jun \n').lower()
# get the month name from months_abbreviation dict and set day to all
month = months_abbreviation.get(selected_month)
# ask user to choose day in put it in selected_day var
selected_day = input('\n Which day ? \n type sun,mon,tu,wed,thu,fri or sat \n').lower()
# while user type wrong word ask him again to type day
while selected_day not in days_abbreviation:
print('\n wrong choice \n')
selected_day = input('Which day ? \n type sun,mon,tu,wed,thu,fri or sat \n').lower()
day = days_abbreviation.get(selected_day)
print('Your choice : month: {} , day: {} and city: {}'.format(month,day,city))
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA.get(city))
# convert start time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# add column month extract form start time column
df['month'] = df['Start Time'].dt.month
# add column day_of_week from start time column
df['day_of_week'] = df['Start Time'].dt.day_name()
# add hour column from start time column
df['hour'] = df['Start Time'].dt.hour
# add trip column from combination of start station and end statinon
df['Trip']= df['Start Station'] + ' - ' + df['End Station']
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""
Displays statistics on the most frequent times of travel.
"""
print('-'*60)
print('|' + ' '*58 + '|' )
print('| Calculating The Most Frequent Times of Travel. |')
print('|' + ' '*58 + '|' )
print('|'+'-'*59)
start_time = time.time()
# display the most common month
popular_month= df['month'].mode()[0]
popular_month= months[popular_month -1]
# display the most common day of week
popular_day = df['day_of_week'].mode()[0]
# display the most common start hour
popular_hour = df['hour'].mode()[0]
print('| Popular start hour is : {}'.format(popular_hour))
print('| Popular month is : {}'.format(popular_month))
print('| Popular day of the week is : {}'.format(popular_day))
print("| \n| This took %s seconds." % (time.time() - start_time))
print('-'*60)
def station_stats(df):
"""
Displays statistics on the most popular stations and trip.
"""
print('-'*60)
print('|' + ' '*58 + '|' )
print('| Calculating The Most Popular Stations and Trip.. |')
print('|' + ' '*58 + '|' )
print('-'*60)
start_time = time.time()
# display most commonly used start station
most_commonly_start_station = df['Start Station'].mode()[0]
print('most commonly used start station : {}'.format(most_commonly_start_station))
# display most commonly used end station
most_commonly_end_station = df['End Station'].mode()[0]
print('most commonly used End station : {}'.format(most_commonly_end_station))
# display most frequent combination of start station and end station trip
most_frequent_trip = df['Trip'].mode()[0]
print('Most common trip from start to end : {}'.format(most_frequent_trip))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*60)
def trip_duration_stats(df):
"""
Displays statistics on the total and average trip duration.
"""
print('-'*60)
print('|' + ' '*58 + '|' )
print('| Calculating Trip Duration... |')
print('|' + ' '*58 + '|' )
print('-'*60)
start_time = time.time()
# display total travel time
total__travel_time = df['Trip Duration'].sum()
print('total travel time in seconds : {}'.format(total__travel_time))
print('total travel time in Format Days, H:M:S > {}'.format(datetime.timedelta(seconds=float(total__travel_time))))
# display mean travel time
mean_travel_time = df['Trip Duration'].mean()
print('mean travel time in seconds : {}'.format(mean_travel_time))
print('mean travel time in in Format Days, H:M:S > {}'.format(datetime.timedelta(seconds=float(mean_travel_time))))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df,city):
"""
Displays statistics on bikeshare users.
"""
print('-'*60)
print('|' + ' '*58 + '|' )
print('| Calculating User Stats |')
print('|' + ' '*58 + '|' )
print('-'*60)
start_time = time.time()
# Display counts of user types
user_types =df['User Type'].value_counts()
print('counts of user types :\n{}'.format(user_types))
print(' '*25 + '-'*10 +' '*25)
# if selected city washington show message some state not available
if city == 'washington' :
print('Sorry, gender counts,earliest, most recent,\n and most common year of birth are not available for washington')
else:
# Display counts of gender
count_of_gender = df['Gender'].value_counts()
print('Gender count :\n{}'.format(count_of_gender))
print(' '*25 + '-'*10 +' '*25)
# Display earliest, most recent, and most common year of birth
earlist_year = df['Birth Year'].min()
Most_recent_year = df['Birth Year'].max()
most_common_year = df['Birth Year'].mode()[0]
print('Earliest year of birth: {}'.format(int(earlist_year)))
print('Most recent year of birth: {}'.format(int(Most_recent_year)))
print('Most common year of birth: {}'.format(int(most_common_year)))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*60)
def display_raw_data(city):
"""
prompt the user whether they would like to see the raw data. If the user answers 'yes'
print 5 rows of the data at a time, then ask the user if want to see 5 more rows of row data
Args:
(str) city - name of the city to show raw data
"""
display_raw =input('would you like to see raw data ? type yes or no : \n').lower()
try:
while display_raw == 'yes':
for chunk in pd.read_csv(CITY_DATA[city], chunksize = 5):
print(chunk)
display_raw = input('Would you like to view more 5 rows? Type "Yes" or "No": \n').lower()
if display_raw != 'yes':
print('Thank you')
break
except KeyboardInterrupt:
print('Thank you For your time')
def main():
while True:
city, month, day = get_filters()
load_data(city, month,day)
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df,city)
display_raw_data(city)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
cb304052a0a212b3e07ab2bf18b9b8b1b23f52e7 | tuxisma/python | /purepython/list_comprehension/list_comprehension.py | 93 | 3.8125 | 4 | words = "Hello I am Ismael Garcia".split()
r = [len(word) for word in words]
print(f'Result: {r}')
|
71ba32c406a48303f74e49a84f94f5acf01eaf8a | Pedro29152/binary-search-tree-python | /main.py | 1,046 | 3.734375 | 4 | import random, timeit, sys
from BinaryTree.BinarySearchTree import BinarySearchTree
if __name__ == '__main__':
size = 100
try:
size = int(sys.argv[1])
except:
pass
max_val = size*10
tree = BinarySearchTree()
arr = []
for i in range(size):
try:
val = random.randint(0, max_val)
tree.add_node(val)
arr.append(val)
except ValueError:
pass
print("Tree height/depth: ", tree.get_height())
print("Number of elements inserted: ", tree.get_size())
print("Tree max value: ", tree.get_max().id)
print("Tree min value: ", tree.get_min().id)
print("Tree as a sorted list: ", tree.get_list())
print("Tree as an inverted sorted list: ", tree.get_list(ascending=False))
try:
show = int(input('Show tree? (1 - Yes): '))
if show == 1:
print('TREE---------------------------------')
tree.print_tree()
print('-------------------------------------')
except:
pass |
dd0e18c7d844270de3e94041634fb5eae9949c47 | prajjwalkumar17/DSA_Problems- | /dp/Knapsack_Unbounded.py | 1,874 | 4.0625 | 4 | """
Unbounded Knapsack problem using dp (Unbounded means all the given weights are available in infinite quantity)
Given weights and their corresponding values,
We fill knapsack of capacity W to obtain maximum possible value(or profit). We can pick same weight more than once.
N: Number of (items)weight elements
W: Capacity of knapsack
Time Complexity: O(N*W) (Optimizing knapsack at capacities from 0 to W gradually using all N items)
Space Complexity: O(W) (knapsack array)
"""
def unbounded_knapsack(capacity, weights, values):
# 'items' variable represents number of weight elements
items = len(values)
# Initializing 1-d array knapsack values as 0
knapsack = [0 for x in range(capacity + 1)]
# Iterating to given capacity from 0
for current_capacity in range(capacity + 1):
# Iterating through all the items
for i in range(items):
# If the weight of item is less then current_capacity, it can be used in knapsack
if (weights[i] <= current_capacity):
knapsack[current_capacity] = max(
# Current item is not utilised
knapsack[current_capacity],
knapsack[current_capacity - weights[i]] + values[i])
# Current item is utilised, so knapsack value for current_capacity changes to
# value of current item + knapsack value when capacity is current_capacity-weight of utilised item
return knapsack[capacity]
if __name__ == '__main__':
print("Enter capacity:")
capacity = int(input())
print("Enter weights:")
weights = list(map(int, input().split()))
print("Enter values:")
values = list(map(int, input().split()))
print(unbounded_knapsack(capacity, weights, values))
"""
Sample Input:
capacity = 50
weights = 1 5 10
values = 10 50 100
Sample Output:
500
"""
|
c18d5b47c2598b24703a2a7d3ba5c9b471ea78bb | prajjwalkumar17/DSA_Problems- | /dp/Maximum_Profit.py | 2,223 | 3.921875 | 4 | '''
Purpose :
In a trading system a product is bought in the morning and sold out on the same day.
If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get.
Input formate :
Line1 : Number of test cases
Line2 : Length of the prices array
Line3 : prices array separated with a space
Output formate :
The maximum profit
Method :
Dynamic programming
Intuition :
Storing the maximum possible profit of every subarray in a table named profit
Finally returning the profit[n-1]
Argument: Array
return : int
'''
def maxProfit(price, n):
# Create profit array and initialize it as 0
profit = [0]*n
''' Get the maximum profit with only one transaction allowed.
After this loop,profit[i] contains maximum profit from price[i..n-1] using at most one trans.
max_price = price[n-1] '''
for i in range(n-2, 0, -1):
if price[i] > max_price:
max_price = price[i]
''' we can get profit[i] by taking maximum of:
a) previous maximum,i.e., profit[i+1]
b) profit by buying at price[i] and selling at max_price'''
profit[i] = max(profit[i+1], max_price - price[i])
'''Get the maximum profit with two transactions allowed
After this loop, profit[n-1] contains the result'''
min_price = price[0]
for i in range(1, n):
if price[i] < min_price:
min_price = price[i]
'''Maximum profit is maximum of:
a) previous maximum,i.e., profit[i-1]
b) (Buy, Sell) at (min_price, A[i]) and
profit of other trans.stored in profit[i]'''
profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price))
result = profit[n-1]
return result
# Driver function
def main():
for _ in range(int(input())):
price = []
length=int(input())
price=list(map(int,input().split()))
print ("Maximum profit is", maxProfit(price,length),"\n")
if __name__=="__main__":
main()
'''
Case : 1
Sample Input :
2
6
[90, 80, 70, 60, 50]
6
[10, 22, 5, 75, 65, 80]
Sample Output :
0
87
Reason :
1)No possible earn only loss if transactions takes place
2)Buy at 10, sell at 22, Buy at 5 and sell at 80. [12+75]
Time complexity : O(N)
Space Complexity : O(N)
'''
|
17684e47bb9c34e7088b9336118d73b2eac9dd3a | prajjwalkumar17/DSA_Problems- | /dp/Unique_BST.py | 1,730 | 3.90625 | 4 | """
Purpose: Total number of Unique BST's that can be
made using n keys/nodes.
Method: Dynamic Programming
Intution: Total number of Unique BST's with N nodes
= Catalan(N)
Here function Unique_BST() return the total number of
diffrent Binary Search Trees that can be made with N distinct nodes
Argument: N (number of distinct nodes)
return Type: int (Total number of binary tree)
Time Complexity: O(n)
Space Complexity: O(n)
Note: Since the number of possible binary search tree will be large
the answer is given in mod of 10^9+7
"""
# Catalan_Number (N) = ((2*N)!) / ((N+1)!*N!)
# Global Variables
MOD = 10**9+7
facto = [1] # Factorial Table
# To construct the factorial numbers using DP
def factorial(n):
global facto
for i in range(1, n+1):
facto += [(facto[-1]*i) % MOD]
# For Modular Inverse of num with respect to 10^9+7
def Mod_Inv(num):
return pow(num, MOD-2, MOD)
def Catalan_Number(num):
if num == 0 or num == 1:
return 1
# Constructing Factorial Table
factorial(2*num)
Numerator = facto[2*num]
Denominator = (facto[num+1]*facto[num]) % MOD
Catalan = (Numerator * Mod_Inv(Denominator)) % MOD
return Catalan
def Unique_BST(N):
# Nth Catalan Number
Cat = Catalan_Number(N)
return Cat
# ------------------------DRIVER CODE ------------------------
if __name__ == "__main__":
n = int(input("Enter the number of distinct nodes: "))
print("Total number of Binary Search Tree = ", Unique_BST(n))
"""
SAMPLE INPUT/OUTPUT
Enter the number of distinct nodes: 5
Total number of Binary Search Tree = 42
Enter the number of distinct nodes: 10
Total number of Binary Search Tree = 16796
"""
|
f17492efff4bbe8ce87a626abfece629c0297a83 | prajjwalkumar17/DSA_Problems- | /dp/length_common_decreasing_subsequence.py | 1,918 | 4.375 | 4 | """ Python program to find the Length of Longest Decreasing Subsequence
Given an array we have to find the length of the longest decreasing subsequence that array can make.
The problem can be solved using Dynamic Programming.
"""
def length_longest_decreasing_subsequence(arr, n):
max_len = 0
dp = []
# Initialize the dp array with the 1 as value, as the maximum length
# at each point is atleast 1, by including that value in the sequence
for i in range(n):
dp.append(1)
# Now Lets Fill the dp array in Bottom-Up manner
# Compare Each i'th element to its previous elements from 0 to i-1,
# If arr[i] < arr[j](where j = 0 to i-1), then it qualifies for decreasing subsequence and
# If dp[i] < dp[j] + 1, then that subsequence qualifies for being the longest one
for i in range(0, n):
for j in range(0, i):
if(arr[i] < arr[j] and dp[i] < dp[j] + 1):
dp[i] = dp[j] + 1
# Now Find the largest element in the dp array
max_len = max(dp)
return max_len
if __name__ == '__main__':
print("What is the length of the array? ", end="")
n = int(input())
if n <= 0:
print("No numbers present in the array!!!")
exit()
print("Enter the numbers: ", end="")
arr = [int(x) for x in input().split(' ')]
res = length_longest_decreasing_subsequence(arr, n)
print("The length of the longest decreasing subsequence of the given array is {}".format(res))
"""
Time Complexity - O(n^2), where 'n' is the size of the array
Space Complexity - O(n)
SAMPLE INPUT AND OUTPUT
SAMPLE I
What is the length of the array? 5
Enter the numbers: 5 4 3 2 1
The length of the longest decreasing subsequence of the given array is 5
SAMPLE II
What is the length of the array? 10
Enter the numbers: 15 248 31 66 84 644 54 84 5 88
The length of the longest decreasing subsequence of the given array is 4
"""
|
5851be9c774490d8643d8897c6aacb9a1340b569 | prajjwalkumar17/DSA_Problems- | /dp/Knapsack_01.py | 2,371 | 4 | 4 | """
Knapsack 0-1 problem using dp (0-1 means we either choose it or we don't, no fractions)
Given weights and their corresponding values,
We fill knapsack of capacity W to obtain maximum possible value in bottom-up manner.
N: Number of (items)weight elements
W: Capacity of knapsack
Time Complexity: O(N*W)(Looping through the matrix)
Space Complexity: O(N*W)(Space taken by matrix - knapsack_table)
"""
def knapsack(capacity, weights, values):
# 'items' variable represents number of weight elements
items = len(weights)
# Initializing knapsack_table values as 0
knapsack_table = [[0 for x in range(capacity + 1)]
for x in range(items + 1)]
# Updating knapsack_table[][] in bottom up manner
for i in range(items + 1):
# Note that list is 0-based, so to get i_th item we do i-1
for j in range(capacity + 1):
# i=0 means no items available to put
# j=0 means no capacity remains to be filled
if i == 0 or j == 0:
knapsack_table[i][j] = 0
# Weight of item is greater than current capacity, so we cannot use it
# So knapsack value here is the best we can do without this item ie. with the (i-1)th item
elif weights[i-1] > j:
knapsack_table[i][j] = knapsack_table[i-1][j]
# Weight of item is less than current capacity, so we can use it to optimize knapsack
else:
knapsack_table[i][j] = max(
# If i_th item is included,
# knapsack value is equal to it's value + best we can do(ie. value of knapsack_table):
# 1) without this item(with the previous one) and
# 2) capacity being current capacity(j) - weight of i_th item
values[i-1] + knapsack_table[i-1][j-weights[i-1]],
knapsack_table[i-1][j]) # i_th item is not included
return knapsack_table[items][capacity]
if __name__ == '__main__':
print("Enter Capacity:")
capacity = int(input())
print("Enter weights:")
weights = list(map(int, input().split()))
print("Enter values:")
values = list(map(int, input().split()))
print(knapsack(capacity, weights, values))
"""
Sample Input:
capacity = 50
weights = 1 5 10
values = 10 50 100
Sample Output:
160
"""
|
c437aca066dbd263bd28fba9b62953461eff4bb0 | Neix20/MiniProject | /Trash/Person_2.py | 2,413 | 3.59375 | 4 | import cv2
import numpy as np
def remove_background(img, threshold):
"""
This method removes background from your image
:param img: cv2 image
:type img: np.array
:param threshold: threshold value for cv2.threshold
:type threshold: float
:return: RGBA image
:rtype: np.ndarray
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, threshed = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
cnt = sorted(cnts, key=cv2.contourArea)[-1]
mask = cv2.drawContours(threshed, cnt, 0, (0, 255, 0), 0)
masked_data = cv2.bitwise_and(img, img, mask=mask)
x, y, w, h = cv2.boundingRect(cnt)
dst = masked_data[y: y + h, x: x + w]
dst_gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
_, alpha = cv2.threshold(dst_gray, 0, 255, cv2.THRESH_BINARY)
b, g, r = cv2.split(dst)
rgba = [r, g, b, alpha]
dst = cv2.merge(rgba, 4)
dst = cv2.cvtColor(dst, cv2.COLOR_BGRA2RGB)
return dst
## Image
img_path = "Dataset\\Apple\\0_100.jpg"
img = cv2.imread(img_path)
img = cv2.resize(img, (200, 200),interpolation = cv2.INTER_AREA)
img = remove_background(img, threshold = 225)
cv2.imshow("Orginal Image", img)
## Test Image
test_img_path = "Test_Images\\Apple\\apple1.jpg"
test_img = cv2.imread(test_img_path)
test_img = cv2.resize(test_img, (200, 200),interpolation = cv2.INTER_AREA)
test_img = remove_background(test_img, threshold = 225)
cv2.imshow("Test Image", test_img)
## Contrast Image
## Brighten Up Image
img = cv2.imread(img_path)
img = cv2.resize(img, (200, 200),interpolation = cv2.INTER_AREA)
img = remove_background(img, threshold = 225)
img = cv2.convertScaleAbs(img, alpha=1.5, beta=20)
cv2.imshow("Brightened Image", img)
## Color Enhancement
img = cv2.imread(img_path)
img = cv2.resize(img, (200, 200),interpolation = cv2.INTER_AREA)
img = remove_background(img, 225)
img = img / 255.0
r, g, b = cv2.split(img)
img_sum = r + g + b
CR, CG, CB = cv2.divide(r, img_sum), cv2.divide(g, img_sum), cv2.divide(b, img_sum)
img = cv2.merge((CR, CG, CB))
img = np.uint8(img * 255)
img = cv2.convertScaleAbs(img, alpha=1.5, beta=20)
cv2.imshow("Color Enhancement", img)
cv2.waitKey(0) |
f728d25f7ee2afeac14a37cad376f7a422b6544b | Eron9528/python-learning | /grammar/senior/iterable.py | 1,492 | 3.9375 | 4 | #
# 直接作用于for循环的数据类型有以下几种:
# 一类是集合数据类型,如list、tuple、dict、set、str等;
# 一类是generator,包括生成器和带yield的generator function。
# 这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
# 可以使用isinstance()判断一个对象是否是Iterable对象:
from collections.abc import Iterable
isinstance([], Iterable)
# 而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,
# 直到最后抛出StopIteration错误表示无法继续返回下一个值了。
# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
# 把list、dict、str等Iterable变成Iterator可以使用iter()函数:
# 因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用
# 并不断返回下一个数据,直到没有数据时抛出StopIteration错误。可以把这个数据流看做
# 是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算
# 下一个数据,所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。
# Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
|
280bc39bc28284d12595dd473f0699c332bb0968 | Eron9528/python-learning | /grammar/basic/if.py | 132 | 3.875 | 4 | age = 23
if age > 13:
print('ninde',' ', age)
else:
print('sss');
name = ['1','2','3']
for n in name:
print(n) |
d660544616126da5b9217b419db55c0aedfc1fc7 | fionnmcguire1/College-Programming | /Advanced-Security/RSA_SecurityAssignment/security_assignment.py | 1,349 | 3.734375 | 4 |
#Fionn Mcguire
#C13316356
#DT211/3
#Security assignment (RSA encryption)
import random
import math
"""340282366920938463463374607431768211456"""
def getting_public_keys() :
prime1 = random.randint(2, 340282366920938463463374607431768211456)
prime2 = random.randint(2, 340282366920938463463374607431768211456)
validation2 = 0
while validation2 != 50:
dividend = random.randint(2, prime1)
print("Dividend 1 is: {0}".format(dividend))
equation = dividend**(prime1-1) % prime1
print("Equation 1 is: {0}".format(equation))
if equation == 1:
validation2 += 1
else:
validation2 = 0
prime1 = random.randint(2, 340282366920938463463374607431768211456)
if validation2 == 50:
print("{0} Is Prime".format(prime1))
"""
validation2 = 0
while validation2 != 50:
dividend = random.randint(2, prime2)
print("Dividend 2 is: {0}".format(dividend))
if dividend**(prime2-1) % prime2 == 1:
print("Is Prime")
validation2 += 1
else:
print("Nevermind")
validation2 = 0
prime2 = random.randint(2, 340282366920938463463374607431768211456)"""
print("Number 1: {0}".format(prime1))
print(getting_public_keys())
|
c9bc59915700903ee3cb4df87acedfa883f4e6cd | fionnmcguire1/College-Programming | /Advanced-Security/DES_Encryption2.py | 4,307 | 3.515625 | 4 | #-*- coding: utf-8 -*-
'''
C13316356
Fionn Mcguire
Advanced Security
Lab 3
DES with ECB mode encryption & Decryption
'''
#importing the encrytption algorithm
from pyDes import *
import base64
#Q1
'''
Key : '12345678'
Plaintext : AAAABBBBAAAABBBB
Encrypted: '\x19\xffF7\xbb/\xe7|\x19\xffF7\xbb/\xe7|'
Ciphertext : 19FF4637BB2FE77C19FF4637BB2FE77C
Decrypted : '9\x07\xa6\xc1\xd7\xac\x13\xda-\xd0\x98\x8aC\x8d'j9\x07\xa6\xc1\xd7\xac\x13\xda-\xd0\x98\x8aC\x8d'j'
'''
#creating a function to handle the diffenernt modes of DES
def DES(msg,mode,e_or_d):
if mode == 'ECB':
#msg = msg.encode('utf8')
#msg=msg.decode('unicode_escape')
#Setting the DES algorithm
k = des("12345678", mode)
#Have to use getKey because the key was converted to binary in the algorithm
print ("Key : %s" % k.getKey())
print ("Message : %s" % msg)
#Encrypting the message
if e_or_d == 'encrypt':
e = k.encrypt(msg).encode('hex')
#e = e.decode('utf-8')
#e=e.decode('unicode_escape')
print ("Encrypted: %r" % e)
#d = k.decrypt(k.encrypt(msg))
#print ("Encrypted: %r" % d)
return e
if e_or_d == 'decrypt':
#Decrypting the encrypted ciphertext
msg = msg
d = k.decrypt(k.encrypt(msg))
print ("Decrypted: %r" % d.encode('hex'))
#print ("Decrypted: %r" % base64.b16encode(d))
if mode == 'CBC':
k=des("12345678", mode, b"\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
print ("Key : %s" % k.getKey())
print ("Message : %s" % msg)
if e_or_d == 'encrypt':
e = k.encrypt(msg)
#e = e.decode('utf-8')
#e=e.decode('unicode_escape')
print ("Encrypted: %r" % e.encode('hex'))
if e_or_d == 'decrypt':
#Decrypting the encrypted ciphertext
d = k.decrypt(msg)
print ("Decrypted: %r" % d)
plaintext = "AAAABBBBAAAABBBB"
#e = DES(msg,'ECB','encrypt')
'''print()
msg = '19FF4637BB2FE77C19FF4637BB2FE77C'
DES(msg,'ECB','decrypt')'''
print("DES: ECB Encrypting & Decryption")
k = des("12345678", 'ECB')
print ("Key : %s" % k.getKey())
print ("Message : %s" % plaintext)
encrypted = k.encrypt(plaintext)
print ("Encrypted: %r" % encrypted.encode('hex'))
decrypted = k.decrypt(encrypted)
print ("Decrypted: %r" % decrypted)
print
print("DES: CBC Encrypting & Decryption")
ciphertext = "AAAABBBBAAAABBBB"
#Note this only works when the ciphertext and plaintext are reversed
#In the lab the lecturer had this as the plaintext and aac823f6bbe58f9eaf1fe0eb9ca7eb08
#As the ciphertext
j = des("12345678", CBC,"00000000")
print ("Key : %s" % j.getKey())
print ("Message : %s" % ciphertext)
encrypted = j.encrypt(ciphertext)
print ("Encrypted: %r" % encrypted.encode('hex'))
decrypted = j.decrypt(encrypted)
print ("Decrypted: %r" % decrypted)
print
def addPadding(msg):
length = 8-(len(msg)%8)
i=0
while(i<length):
msg +="\x00"
i+=1
return msg
def removePadding(msg):
str1 = "\x00"
position = msg.find(str1,0)
msg = msg[:position]
return msg
plaintext = "AAAABBBBCCCC"
plaintext = addPadding(plaintext)
k = des("12345678", 'ECB')
print ("Key : %s" % k.getKey())
print ("Message : %s" % plaintext)
encrypted = k.encrypt(plaintext)
print ("Encrypted: %r" % encrypted.encode('hex'))
decrypted = k.decrypt(encrypted)
decrypted = removePadding(decrypted)
print ("Decrypted: %r" % decrypted)
print
'''
msg = 'AAAABBBBAAAABBBB'
k=des("12345678", CBC, "00000000")
e = k.encrypt(msg)
#DES(msg,'CBC','decrypt')
print
msg = 'AAC823F6BBE58F9EAF1FE0EB9CA7EB08'
#DES(msg,'CBC','encrypt')"""
'''
|
9512f7d0d18954002f22943e603216f222527471 | fionnmcguire1/College-Programming | /Advanced-Security/Caesar_and_Railfence.py | 1,030 | 3.984375 | 4 | #Name: Fionn Mcguire
#Course: DT211/4
#Student Number: C13316356
#Advanced Security Lab 1
#Date: 13/09/2016
def caesar(s,k,decrypt=False):
if decrypt: k= 26 - k
r=""
for i in s:
if (ord(i) >= 65 and ord(i) <= 90):
r += chr((ord(i) - 65 + k) % 26 + 65)
elif (ord(i) >= 97 and ord(i) <= 122):
r += chr((ord(i) - 97 + k) % 26 + 97)
else:
r +=i
return r
def encrypt(p,k):
return caesar(p,k)
def decrypt(c,k):
return caesar(c,k,True)
def fence(p,k):
fence = [[None] * len(p) for n in range(k)]
rails = range(k-1) and range(k - 1, 0, -1)
for n, x in enumerate(p):
fence[rails[n%len(rails)]][n] = x
return [c for rail in fence for c in rail if c is not None]
def encrypt1(p,k):
return ''.join(fence(p,k))
def decrypt1(c,k):
rng = range(len(c))
pos = fence(rng, k)
return ''.join(c[pos.index(k)] for k in rng)
|
df4cb5ed09c7922d28796c367e1d5e2775eb5217 | amirzhangirbayev/Final_Project_CSS253 | /DataCollection/split_csv.py | 1,207 | 3.703125 | 4 | # SPLIT THE CSV FILE
# import the necessary libraries
import csv
import pandas as pd
# a list for all the steam ids
steamids_list = []
# enter the name of the file with all the stema ids
steamids_csv = input('Enter the steamids file in the csv format: ')
# enter the per number
per_number = int(input('Enter the number of steam ids you want to have per one csv file: '))
# read the csv file
df = pd.read_csv(steamids_csv)
# append all steam ids to the list
for steamid in df['steamid']:
steamids_list.append(steamid)
# a function that splits a list into chunks
def chunks(lst, n):
# yield successive n-sized chunks from lst
for i in range(0, len(lst), n):
yield lst[i:i + n]
# a list of split (divided) steam ids
split_csv = list(chunks(steamids_list, per_number))
# naming files
file_i = 0
# take each chunk and add each steam id from that chunk to a csv file
for steamids in split_csv:
file_i += 1
filename = f'steamids_part_{file_i}.csv'
with open(filename, 'w', newline='') as f:
thewriter = csv.writer(f)
thewriter.writerow(['steamid'])
for steamid in steamids:
thewriter.writerow([steamid]) |
701b81e63adb89610499967e2c1c39e16c56a921 | PatrickDoolittle/PyMJ | /Main/pyMahjonMain.py | 2,754 | 3.5625 | 4 | import random
# Trying to create a game of Mahjong to test python skills
# Data structure for the tiles
# 1-9 in 3 suits, man, sou, and pinzu. Plus 3 dragons and 4 winds. 4 of each tile
class tile:
def __init__(self, suit, value, numid):
self.suit = suit
self.value = value
self.string = self.value + ' ' + self.suit + ' '
self.numid = numid
# Initialize a full tileset of 136 tiles
class deck:
# Generate a tileset with a tileID unique to each tile
def __init__(self):
self.tileSet = []
tileID = 0
for suit in ['man','sou','pinzu']:
for value in ['1','2','3','4','5','6','7','8','9']:
for i in range(4):
newTile = tile(suit, value, tileID)
tileID += 1
self.tileSet.append(newTile)
for dragon in ['red','green','white']:
for i in range(4):
newTile = tile(dragon, '', tileID)
tileID += 1
self.tileSet.append(newTile)
for wind in ['east','south','west','north']:
for i in range(4):
newTile = tile(wind,'', tileID)
tileID += 1
self.tileSet.append(newTile)
def remaining(self):
return (len(self.tileSet))
class player:
def __init__(self, seatWind, deck, name):
self.hand = []
self.discards = []
self.seatWind = seatWind
self.name = name
self.deck = deck
#Draw 13 tiles from the deck
for i in range(13):
tileDraw = random.choice(self.deck.tileSet)
self.hand.append(tileDraw)
self.deck.tileSet.remove(tileDraw)
self.sortHand()
def printhand(self):
handString = ""
for tile in self.hand:
handString += tile.string
return handString
# Function for the class Player that sorts the hand by numerical value and suit.
def sortHand(self):
newList = list(self.hand)
newHand = []
cache = []
for suitOrder in ['man','pinzu','sou','red','east','west','south','west','north','red','white','green']:
for tile in newList:
if tile.suit == suitOrder:
cache.append(tile)
for i in range(1, 10):
for tile in cache:
if tile.value == str(i):
newHand.append(tile)
cache.remove(tile)
elif tile.value == '':
newHand.append(tile)
cache.remove(tile)
self.hand = newHand
class table:
def __init__(self, num_players, deck, names = []):
self.seats = []
self.deck = deck
self.num_players = num_players
self.names = names
self.winds = ['East','South','West','North']
for i in range(num_players):
seatTaker = player(self.winds[i], self.deck, self.names[i] )
self.seats.append(seatTaker)
print("Hello, welcome to PyMJ.")
testDeck = deck()
testTable = table(4, testDeck, ['Patrick', 'David', 'Beth','Mimi'])
print(str(testDeck.remaining()) + " tiles remaining in the deck after initial draw.")
for player in testTable.seats:
print(player.name)
print(player.printhand())
|
99c8288d94702e548e03d757403e1b022582bea1 | san123i/CUNY | /Semester2/620-WebAnalytics/Week4/Assignment.py | 1,613 | 3.59375 | 4 | import requests
import nltk
import collections
import nltk, re, pprint
from nltk import word_tokenize
from nltk.corpus import stopwords
import urllib2
import operator
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
#from urllib2 import request
url = "https://raw.githubusercontent.com/san123i/CUNY/master/Semester2/620-WebAnalytics/Week4/data.txt"
#url="C:\\CUNY\\GIT\\CUNY\\Semester2\\620-WebAnalytics\\Week4\\data.txt"
response = urllib2.urlopen(url)
raw = response.read()
raw = unicode(raw, 'utf-8')
list_words = raw.split()
counter = Counter(list_words)
unique_words = sorted(counter)
#How many total unique words are in the corpus? (Please feel free to define unique words in any interesting, defensible way).
print(len(unique_words))
#Taking the most common words, how many unique words represent half of the total words in the corpus?
#Identify the 200 highest frequency words in this corpus.
common_200_words = counter.most_common(200)
common_200_words_dict = dict(common_200_words)
#Create a graph that shows the relative frequency of these 200 words
lists = sorted(common_200_words_dict.items(), key=operator.itemgetter(1), reverse=True)
print(common_200_words_dict)
keys, values = zip(*lists)
plt.plot(keys, values)
#Does the observed relative frequency of these words follow Zipf’s law? Explain
Yes, the observed relative frequency follows the Zipfs law.
Zips law states that the frequency of any word is inversely proportional to its rank in the frequency table. Looking at the chart,
its clearly visible that the frequency of the most common word is |
2c88ddfe992b4fcba6c1e2d4d06bdfa64c485b9b | ErikAckzell/cagd | /homework6/DeCasteljau.py | 2,997 | 3.890625 | 4 | import scipy
from matplotlib import pyplot
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def deCasteljau(n, controlnet, U):
"""
Uses the de Casteljau Algorithm for triangle patches to evaluate the point on the surface at U.
:param n: Degree
:param controlnet: List,
:param U: point
:return: Point on the surface
"""
if len(controlnet) > 1:
return deCasteljau(n-1, deCasteljauStep(n, controlnet, U), U)
else:
return controlnet[0]
def deCasteljauStep(n,controlnet, u):
"""
Evaluates the new points for the the given control net with the de Casteljau Algorithm for triangle patches.
:param n: degree
:param controlnet: list of points, ordered from the top of the triangle going left to right
:param u: point in 3D
:return: list with the new control net
"""
new_controlnet = []
i, j = 0, 1
# Iterating over each row in the triangle
for row in range(1,n+1):
# Evaluate every new point on that row
for k in range(row):
new_point = u[0]*controlnet[i] + u[1]*controlnet[j] + u[2]*controlnet[j+1]
new_controlnet.append(new_point)
j += 1
j += 1
return new_controlnet
def set_grid(m):
"""
Creates the grid of U=(u,v,w) where U is a barycentric combination.
:param m: int, number of points on each axis
:return: list of tuples (u,v,w)
"""
return [(i/m,j/m,1-(i+j)/m) for i in range(m,-1,-1) for j in range(m-i, -1, -1)]
def surface_vals(n, grid, controlnet):
"""
Evaluates the points on the surface. Returns the x, y and z values in separate lists
:param n: degree
:param grid: list of points U's
:param controlnet: list of control points
:return: x, y and z values in separate lists
"""
vals = [deCasteljau(n,controlnet, u) for u in grid]
return zip(*vals)
def plot_surface(n, controlnet, m, title):
"""
Plots the surface
:param n: degree
:param controlnet:
:param m: number of points to plot
:param title: Title of the plot
:return: figure
"""
grid = set_grid(m)
x,y,z = surface_vals(n,grid,controlnet)
fig = pyplot.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x,y,z, cmap=cm.jet, linewidth=0.2)
ax.set_title(title)
pyplot.show()
return fig
if __name__ == '__main__':
# The controlnet is starting from the top and going from left to right on each row
controlnetA = scipy.array([(0,6,0),(0,3,0),(3,3,6),(0,0,0),(3,0,0), (6,0,9)])
controlnetB = scipy.array([(0,6,0),(0,6,6),(3,3,6), (0,3,9),(6,3,15), (6,0,9)])
n=2
m=60
titleA = 'Triangle Patch with Control Net \n $(0,6,0)$, $(0,3,0)$, $(3,3,6)$, $(0,0,0)$, $(3,0,0)$, $(6,0,9)$'
titleB = 'Triangle Patch with Control Net \n $(0,6,0)$, $(0,6,6)$, $(3,3,6)$, $(0,3,9)$, $(6,3,15)$, $(6,0,9)$'
#figA = plot_surface(n,controlnetA,m,titleA)
figB = plot_surface(n,controlnetB,m,titleB) |
5e61c8288b73e25a29564389c893c216a7d111f0 | arthur-wfb/python-lessons | /model/Human.py | 346 | 3.703125 | 4 | class Human:
def __init__(self, name = "No name"):
self.name = name
self.happiness = 0
self.hungry = 0
def say(self, word):
print(self.name + " said: " + word)
def eat(self, food):
self.happiness += 5
self.hungry += food
def work(self, hours):
self.happiness -= hours |
be625b2c25c8014a5f6dee8805680e5d6b2942c7 | danielanatolie/Data-Science-Concepts | /conditionalProbability.py | 1,151 | 3.890625 | 4 | # Condtional Probability
# Data: People's purchases based on age
# 100,000 random individuals are produced and are randomly
# sorted to be in their 20s, 30s, 40s and so forth
random.seed(0)
#Total number of people in each age group
totals = (20:0, 30:0, 40:0, 50:0, 60:0, 70:0)
#Total number of things purchased in each age group
purchases = (20:0, 30:0, 40:0, 50:0, 60:0, 70:0)
totalPurchases = 0
for _ in range(100000):
ageDecade = random.choice([20,30,40,50,60,70])
purchaseProbability = float(ageDecade) / 100.0 #This makes age and purchase depend, you can make it constant to make both independent of each other
totals[ageDecade] += 1
if (random.random() < purchaseProbability):
totalPurchases += 1
purchases[ageDecade] +=1
print totals
print purchases
# Probability of purchasing given that you are in your 30s
PEF = float(purchases[30]) / float(totals[30])
print "P(purchase | 30s): ", PEF
# Probability of being 30:
PF = float(totals[30]) / 100000.0
print "P(30s): ", PF
# Probablity of buying someting:
PE float(totalPurchases) / 100000.0
print "P(Purchase):", PE
print "P(30's)P(Purchase)", PE * PF |
3cb797e9ad6e9f9a3bcd231f8e6bf87d383f2f39 | kennc05/Computing-GCSE | /Cousework A453/Task 1 - Currency Converter/currency v2.py | 1,466 | 3.546875 | 4 | file = open ('currency.txt', 'rt')
lines = file.readlines()
num=0
for line in lines:
splitline=line.split(' ')
num+=1
print('Option '+str(num)+': '+splitline[0])
option= int(input('What option would you like to choose: '))
amount= input('Enter the amount you want: ')
chosenline = lines[option]
currencies = chosenline.split(' ')
if option==1:
exchange1=float(amount)*float(currencies[1].strip())
print('$',exchange1)
if option==2:
exchange2=amount*float(currencies[1].strip())
print('€',exchange2)
if option==3:
exchange3=amount*float(currencies[1].strip())
print('¥',exchange3)
if option==4:
exchange4=amount*float(currencies[1].strip())
print('$',exchange4)
if option==5:
exchange5=amount*float(currencies[1].strip())
print('€',exchange5)
if option==6:
exchange6==amount*float(currencies[1].strip())
print('¥',exchange6)
if option==7:
exchange7=amount*float(currencies[1].strip())
print('£',exchange7)
if option==8:
exchange8=amount*float(currencies[1].strip())
print('$',exchange8)
if option==9:
exchange9=amount*float(currencies[1].strip())
print('¥',exchange9)
if option==10:
exchange10=amount*float(currencies[1].strip())
print('£',exchange10)
if option==11:
exchange11=amount*float(currencies[1].strip())
print('$',exchange11)
if option==12:
exchange12=amount*float(currencies[1].strip())
print('€',exchange12)
|
2acc09e82eec6baad0377d5045d1714affd0f23a | kennc05/Computing-GCSE | /Cousework A453/Task 2 - Address book/address book v3.py | 974 | 3.859375 | 4 | #Version 4 of the code - Goes with task requirements with only search for Surname + Date
# This code works when searching for surname but not year!!!
from csv import reader
file= reader(open('address.csv'))
results=[]
rowselect = input('Please select what row you want to search 1)Surname 2)Date Of birth')
search =input('Please enter what you are searching for ')
rowselectsurname=0
rowselectdob=6
if rowselect=='1':
rowselect=rowselectsurname
if rowselect=='2':
rowselect=rowselectdob
else:
for row in file:
date=row[6]
if row[rowselect]==search:
results.append(row)
if len(results)==0:
print('We found none :(')
else:
for i in results:
print('Lucky you! We found stuff...')
print('Results = '+str(len(results)))
print('Last Name: '+i[0]+'\n''First Name: '+i[1]+'\n''Address: '+i[2]+'\n''Area: '+i[3]+'\n''Postcode: '+i[4]+'\n''Date of brith: '+i[5]+'\n''Email '+i[6])
|
dae30b825ba3cfc285fdb037882922dead1d84bc | huanhuan18/test04 | /learn_python/字符串案例.py | 437 | 3.71875 | 4 | # user_email = 'nakelulu@itcast.cn'
# split 拆分 特别多
my_str = 'aa#b123#cc#dd#'
ret = my_str.split('#')
print(ret)
print(ret[0])
print(ret[3])
user_email = 'nakelulu@itcast.cn'
# 获得@字符串在user_email中出现的次数
char_count = user_email.count('@')
if char_count > 1:
print('你的邮箱不合法')
else:
result = user_email.split('@')
print('用户名:', result[0])
print('邮箱后缀:', result[1]) |
8c2ae6eaa09ff199ed5dcf711ef7ad9edad03d2a | huanhuan18/test04 | /learn_python/列表练习.py | 1,081 | 4.25 | 4 | # 一个学校,有3个办公室,现在有8个老师等待工位的分配,请编写程序完成随机的分配
import random
# 定义学校和办公室
school = [[], [], []]
def create_teachers():
"""创建老师列表"""
# 定义列表保存老师
teacher_list = []
index = 1
while index <= 8:
# 创建老师的名字
teacher_name = '老师' + str(index)
# 把老师装进列表里
teacher_list.append(teacher_name)
index += 1
return teacher_list
teachers_list = create_teachers()
# print(id(teachers_list))
# teachers_list2 = create_teachers()
# print(id(teachers_list2))
# 函数调用多次,每次返回一个新的对象
# 分配老师
for teacher in teachers_list:
# 产生一个办公室编号的随机数
office_number = random.randint(0, 2)
# 给老师随机分配办公室
school[office_number].append(teacher)
# 查看下各个办公室的老师
for office in school:
for person in office:
print(person, end=' ')
print() |
ff2525a07e6b548ad8decc3c4cce62223188e724 | huanhuan18/test04 | /learn_python/字典.py | 1,064 | 3.90625 | 4 | # 1.字典定义
# 字典注意点:
# 1.1字典的键不能重复,值是可以重复
# 1.2字典是非序列式容器,不支持索引,也不支持切片
def test01():
my_dict = {'name': 'Obama', 'age': 18, 'gender': '男', 101: 100}
print(my_dict['name'])
print(my_dict[101]) # key 关键字 value 值
my_dict['gender'] = '女'
print(my_dict)
def test02():
my_dict = {'name': 'Obama', 'age': 18, 'gender': '男', 101: 100}
# 使用中括号这种访问字典中元素的方式,如果键不存在则会报错,程序终止。
# print(my_dict['age1'])
# 使用 get 方法, 如果key 不存在默认返回None,也可以指定默认返回值
print(my_dict.get('age1', '我是默认值'))
def test03():
"""添加和修改元素"""
my_dict = {'name': 'Obama', 'age': 18, 'gender': '男', 101: 100}
my_dict['score' = 99] #添加新元素
print(my_dict)
# 如果key 不存在则是新增元素,存在的话就是修改元素
test01()
test02()
test03() |
5571891f4b5b8ebae7e873de6669cc7b9d7b5fea | lakshyajit165/DS_Coursera | /programs/Balanced_Parentheses/python/balanced_brackets_using_stack.py | 554 | 3.65625 | 4 | #python3
s = input()
stack = ['LK']
flag = 0
marker = 0
if(len(s) == 1 and s[0] in "()[]{}"):
print("1")
else:
for i in range(len(s)):
if(s[i] not in "({[]})"):
continue
elif(s[i] == '(' or s[i] == '{' or s[i] == '['):
stack.append(s[i])
print(i)
elif((s[i] == ')' and stack[-1] == '(') or (s[i] == ']' and stack[-1] == '[') or (s[i] == '}' and stack[-1] == '{')):
stack.pop()
print(i)
else:
print('No Match at ' + str(i))
break
|
9686cb889247f42481db72c01407a13fa8f03a49 | ElTioLevi/mi_primer_programa | /adivina_numero.py | 1,726 | 4.15625 | 4 | number_to_guess = int((((((((2*5)/3)*8)/2)*7)-(8*3))))
print("El objetivo del juego es adivinar un número entre 1 y 100, tienes 5 intentos")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print ("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has fallado, el número a adivinar es menor")
else:
print("Has fallado, el número a adivinar es mayor")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print("Has acertado!!!")
else:
print("Has perdido el juego")
|
4fc7f1196bf5e9df355d8ce2da9c269165bac519 | heysushil/python-practice-set-two-with-3.8 | /8.1.operatores.py | 2,381 | 4.0625 | 4 | # Operatores:
'''
Hame follwoing type ke Operatores milte hain:
1. Arithmatic Op (Math ke sare signs) + - /
2. Assigment Op (=)
3. Comparison Op (< > ! ==)
4. Logical Op (And Or Not)
5. Identity Op (is)
6. Membership Op (in)
7. Bitwise Op (True/False)
1. Arithmatic Op (Math ke sare signs):
+(add)
-(sub)
*(mul)
/(div)
%(modulus)
**(exponetiation)
//(floor div value)
2. Assigment Op (=):
Example:
a = 10
b = a + 10
b += 10 (b = b + 10)
3. Comparison Op (< > ! ==):
Example: a = 10 , b = 10
equal to: a == b like as print('Comapre a == b: ',a == b)
not equal: a != b
greater: a > b
greaten equal to: a >= b
lessten: a < b
less then equal to: a <= b
4. Logical Op (and or not):
Example: print(a < b and a <= b)
and: and ka matlab hai ki manlo ki a aur b do student hai class me aur condtion hai ki: jab a and b 2no class me present honge tabhi class chalegi other wise nahi chalegi.
Chalegi ka matlab: True
Nahi chalegi ka matlab: False
or: or ka matalab hai ki koi bhi ek condtion sahi ho gai to hame True mil jayega. Jaise ki and ki condtion me hi agar or ka use karle to hame True milega. Because example me a<b ye Flase hai but a<=b ye True hai aur ek condtion sahi hai so hamre True milega.
not: iska matlab hai ki koi bhi ek condtion hame escape karna chate hai to not ka use kiya jata hai, Jaise ki a<b ye condtion False hai aur hum isko escape karna chate hain.
not(a < b)
5. Identity Op (is, is not): is ke use se True ya False check kiya jata hai. aur iske liye compare hi kiya jata hai but yaha par 2 varibale ki vlaues ke alwa unke address ko bhi compare kiya jata hai.
Example:
a is b =>> print(a is b)
a is not b
6. Membership Op (in, not in):
Example:
listval = [3,4,5,6]
Print me check kar rahe hai ki kya 5 hamre list me exits karta hai ya nahi. Agar karta hai then True milega
print(5 in listval)
Manlo hum check kar rahe hai ki kya 2 rollnumber hamare listval ke andar hai ya nahi
print(2 not in listval)
7. Bitwise Op (True/False): ye bit form me values ka result deta hai aur ye logical op ki tarh hota hai.
& and
| or
! not
'''
'''
Programming Languge Types:
1. Low Level language:
1. assembly lanaguge
2. Hight Level Language
'''
|
8bc5a7f7a560110a4626405bddebbd1d3352b700 | heysushil/python-practice-set-two-with-3.8 | /9.list.py | 3,546 | 4.03125 | 4 | '''
Python Collections:
Ye 4 datatypes multiple values ko hold ya store karne ki capacity rakte hain. Is liye hi inhe collection bhi kha jata hai.
Example: Abhi tak humne int,float,comple aur set datatype use kiya but ye sabhi ek time pe ek value ko hi store kar sakte hain.
Isliye jab hame ek sath multiple values ko store karna ho single varibale me to hum yehai 4 datatypes ka use karte hain.
1. list => denote by []
2. tupe => ()
3. dict (dictonary) => {}
4. set => {}
Python List me following methods hain:
Note: Example ke liye mylist = [1,2,3,4], iske behalf par examples diye gaye hain:
1. append(): List me last se 1 nai value add karne ke liye append ka use kiya jata hai. Example: mylist.append(5)
2. clear(): clear method list ko empty karta hai. Empty karne par agar varibel ko print karoge to empty list milega. But error nahi milega. Example: mylist.clear()
3. copy(): Copy method ek list ko copy karke new variable me store kar dega. Example: newlist = mylist.copy()
4. extend(): Extend ka use karke ek se jada list ko aapsh me marge kiya jata hai. Exaple: mylist.extend(newlist)
5. index(): Index method kisi bhi value ka index position bata hai. Example: mylist.index(4)
6. insert(): Insert method list me existing index possition par new value ko update karta hai. Example: mylist.index(1, 11), yaha par(indexPossion, newValue)
7. pop(): Pop method thik append ka ulta hai. Ye by default list me last se ek value ko remove karta hai. Otherwise kisi specific index value ko remove karne ke liye is method me index postion dena hota hai. Example: mylist.pop() - Ye last se ek value remove kardega. mylist.pop(2) - Ye list ke 2nd index ki value ko remove kardega.
8. remove(): Remove ka use kiya jata hai jab aapko index postion ki jagh par value ka pata ho. To direct value ko remove karne ke liye remove method ka use karte hain. Example: mylist.remove(4) - Ye list me jaha bhi 4 hai useko remove karega.
9. reverse(): Reverse list ko ulta kardega. Means list by default assending order me hota hai. To ye list ko desending order me convert kar dega. Example: mylist.reverse()
10. sort(): Sort mehtod list ko assending order me sort kardega. Example: mylist.sort() yaha par sort(revers=Ture/False) Ture = Ye list ko desending order me sort karega. False = Ye assending order me sort karega.
11. count(): Count method list me present kisi bhi dublicate values ko count karne ke liye use hota hai. Example: mylist.count(4)
'''
# list:
btech = [1,2,3,4,5,6,7,8,9,10]
print('\nbtech type: ', type(btech))
print('\nBtech students: ', btech)
myclass = ['Nikhil', 'Debjit', 'Sushil']
mystring = '\nCheck 2: '
print(mystring, myclass[-1])
print('\nCheck 0 to 2 in myclass: ', myclass[0:2])
# append
myclass.append('Hariram')
# check index
rollnumber = myclass.index('Hariram')
print('\nHariram\'s rollnumber: ', rollnumber)
# use insert to replace existing value
myclass.insert(rollnumber, 'Hariram Prashad')
# Change Nikhil to Mr. Nikhil
myclass[0] = 'Mr. Nikhil'
# count:
myclass.append('Sushil')
checkDublicateStudent = myclass.count('Sushil')
print('\ncheckDublicateStudent: ', checkDublicateStudent)
# copy:
class1 = myclass.copy()
# clear()
myclass.clear()
# remove()
class1.remove('Sushil')
# pop()
removeStudentByRollNumber = class1.index('Hariram Prashad')
class1.pop(removeStudentByRollNumber)
# new students
newstudent = ['Radha','Geeta','Seeta']
# extend()
class1.extend(newstudent)
print('\nMyclass: ', myclass)
print('\nclass1: ', class1)
'''
Work:
1. positive aur negetive slicing activity list me karni hai.
''' |
a0d5767222865e698f097d2bf816c4751078275d | heysushil/python-practice-set-two-with-3.8 | /24.date_time.py | 712 | 3.890625 | 4 | # datetime
import datetime as d
mydate = d.date(2020, 11, 2)
print('\n mydate: ', mydate)
print('\nmydate.today(): ', mydate.today())
datedetail = '''
Todyas date: {}
Current Year: {}
Current Month: {}
'''.format(mydate.today(), mydate.today().year, mydate.today().month)
curetndatetime = d.datetime(2020, 11, 2)
print('\n Curent date and time: ', curetndatetime.now)
# month = mydate.
print(datedetail)
# curretn date and time
mydate = d.datetime.now()
print('\nMydate: ', mydate)
print('Todyas day: ', mydate.strftime('%a'))
print('Todyas day: ', mydate.strftime('%A'))
print('\nDate: ', mydate.strftime('%d %A %m %Y - %H:%M:%S %p'))
print('\nDate: ', mydate.strftime('%d\'th %B %Y - %H:%M:%S %p')) |
6d5b4c9c248fa3dc308e1f267e9033c855db95cf | Pogozhelskaya/pctm | /src/utils.py | 361 | 4.03125 | 4 | """ Useful utils module """
def is_prime(n: int) -> bool:
"""
Checks if a number n is prime
:param n: Integer number to test
:return: Boolean value - True if n is prime, else False
"""
if n < 2:
return False
i: int = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
|
f9a0d1cb85a5d77911206b7931094f97a8d2fe67 | JShanmukhRao/Blockchain | /Blockchain.py | 3,469 | 3.515625 | 4 | # Module 1 Create a Blockchain
import datetime
import json
import hashlib
from flask import Flask , jsonify
# Building Blockchain
class Blockchain:
def __init__(self):
self.chain=[]
self.create_block(proof=1,previous_hash='0')
def create_block(self,proof,previous_hash):
block={'index':len(self.chain)+1,
'timestamp':str(datetime.datetime.now()),
'proof':proof,
'previous_hash':previous_hash,
}
self.chain.append(block)
return block
def get_previous_block(self):
return self.chain[-1]
def proof_of_work(self,previous_proof):
new_proof=1
check_proof=False
while check_proof is False: #hexdigest() is used to convert output of sha256 in hexa
hash_operator=hashlib.sha256(str(new_proof**2-previous_proof**2).encode()).hexdigest() #encode() is used to encode the string in right format expected by sha256()
if hash_operator[:4]=='0000':
check_proof=True
else:
new_proof += 1
return new_proof
def hash(self,block):
encoded_blocl= json.dumps(block,sort_keys=True).encode()
return hashlib.sha256(encoded_blocl).hexdigest()
def is_chain_valid(self,chain):
previous_block=chain[0]
block_index=1
while block_index<len(chain):
block=chain[block_index]
if block['previous_hash']!=self.hash(previous_block):
return False
previous_proof=previous_block['proof']
proof=block['proof']
hash_operator=hashlib.sha256(str(proof**2-previous_proof**2).encode()).hexdigest() #encode() is used to encode the string in right format expected by sha256()
if hash_operator[:4]!='0000':
return False
previous_block=block
block_index += 1
return True
# Mining our Blockchain
#creating Web App
app=Flask(__name__)
#Creating Blockchain
blockchain=Blockchain()
#Mining new block
@app.route('/mine_block', methods=['GET'])
def mine_block():
previous_block = blockchain.get_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block=blockchain.create_block(proof, previous_hash)
self_hash=blockchain.hash(block)
response={'message':"SuccessFull",
'index':block['index'],
'timestamp':block['timestamp'],
'proof':block['proof'],
'previous_hash':block['previous_hash'],
'self_hash':self_hash
}
return jsonify(response),200
# getting full blockchain
@app.route('/get_chain', methods=['GET'])
def get_chain():
response={'chain': blockchain.chain,
'length':len(blockchain.chain)}
return jsonify(response),200
#Validation of chain
@app.route('/is_valid', methods=['GET'])
def is_valid():
chain=blockchain.chain
validation=blockchain.is_chain_valid(chain)
response={'Validation':validation}
return jsonify(response),200
app.run(host='0.0.0.0',port= 5000)
|
9de22a3e6b395267ffd011d8ebb1b74cfc4f8dca | TechNaturalist/MultiAgentEscape | /coalition.py | 4,067 | 3.625 | 4 | """A class to handle coalitions between the guards
Written by: Max Clark, Nathan Holst
"""
import random
from typing import Dict, List
from guard_agent import GuardAgent
colors = {
"WHITE": (255, 255, 255),
"BLACK": (0, 0, 0),
"GREEN": (0, 255, 0),
"DARKGREEN": (0, 155, 0),
"DARKGRAY": (40, 40, 40),
"GRAY": (100, 100, 100),
"PURPLE": (155, 0, 155),
"YELLOW": (255, 255, 0),
"BGCOLOR": (0, 0, 0),
"RED": (255, 0, 0),
"CORAL": (255, 77, 77),
}
class Coalition:
def __init__(self, member_count: int) -> None:
self.color = random.choice(list(colors.keys()))
self.member_count = member_count
@staticmethod
def form_coalition(guards: List[GuardAgent]) -> List[GuardAgent]:
print("Guards forming coalition")
a = guards[0]
b = guards[1]
c = guards[2]
v = {} # subset values
v['a'] = a.weapon
v['b'] = b.weapon
v['c'] = c.weapon
v['ab'] = a.attitude + b.attitude + v['a'] + v['b']
v['ac'] = a.attitude + c.attitude + v['a'] + v['c']
v['bc'] = c.attitude + b.attitude + v['c'] + v['b']
v['abc'] = ((v['ab'] + v['ac'] + v['bc']) / 2) ** 0.8
print(f"{{a}} = {v['a']}")
print(f"{{b}} = {v['b']}")
print(f"{{c}} = {v['c']}")
print(f"{{ab}} = {v['ab']}")
print(f"{{ac}} = {v['ac']}")
print(f"{{bc}} = {v['bc']}")
print(f"{{abc}} = {v['abc']:.4f}")
a_shap, b_shap, c_shap = Coalition.shapley_calc_3x(v)
if v['ab'] + v['c'] < v['abc'] and \
v['ac'] + v['b'] < v['abc'] and \
v['bc'] + v['a'] < v['abc']:
print("All guards joined coalition")
coalition = Coalition(3)
a.coalition = coalition
b.coalition = coalition
c.coalition = coalition
return [a, b, c]
if v['a'] + v['c'] < v['ac']:
print("AC coalition")
coalition = Coalition(2)
a.coalition = coalition
c.coalition = coalition
b.coalition = Coalition(1)
return [a, b, c]
if v['a'] + v['b'] < v['ab']:
print("AB coalition")
coalition = Coalition(2)
a.coalition = coalition
b.coalition = coalition
c.coalition = Coalition(1)
return [a, b, c]
if v['b'] + v['c'] < v['bc']:
print("BC coalition")
coalition = Coalition(2)
c.coalition = coalition
b.coalition = coalition
a.coalition = Coalition(1)
return [a, b, c]
print("No coalition formed")
return [a, b, c]
@staticmethod
def shapley_calc_3x(values: Dict[str, float]):
a_count = 0
b_count = 0
c_count = 0
# 123, 132, 213, 231, 312, 321
a_count += values['a'] # 123
a_count += values['a'] # 132
a_count += values['ab'] - values['b'] # 213
a_count += values['abc'] - values['bc'] # 231
a_count += values['ac'] - values['c'] # 312
a_count += values['abc'] - values['bc'] # 321
# 123, 132, 213, 231, 312, 321
b_count += values['b'] # 213
b_count += values['b'] # 231
b_count += values['ab'] - values['a'] # 123
b_count += values['abc'] - values['ac'] # 132
b_count += values['abc'] - values['ac'] # 312
b_count += values['bc'] - values['c'] # 321
# 123, 132, 213, 231, 312, 321
c_count += values['c'] # 312
c_count += values['c'] # 321
c_count += values['abc'] - values['ab'] # 213
c_count += values['bc'] - values['b'] # 231
c_count += values['abc'] - values['ab'] # 123
c_count += values['ac'] - values['a'] # 132
a_count /= 6
b_count /= 6
c_count /= 6
print(f"Shapley values: a = {a_count:.4f}, ", end="")
print(f"b = {b_count:.4f}, c = {c_count:.4f}")
return a_count, b_count, c_count
|
75e5c159bcb924c21ede7c886c98f9e90986f654 | Hans-Bananendans/CubeSat-Mission-Planner | /opstate.py | 1,371 | 3.640625 | 4 | """
opstate.py
"Specification of the OpState class."
@author: Johan Monster (https://github.com/Hans-Bananendans/)
"""
class OpState:
"""This class represents a separate operational state, and can be used
to calculate used power values and separate these by channel."""
def __init__(self, device_power_values, channels, device_channels, \
blips_on=1):
self.device_power_values = device_power_values
self.devices = list(device_power_values.keys())
self.channels = channels
self.device_channels = device_channels
self.blips_on = blips_on
def power_used_channel(self):
# Generate empty dictionary
channel_power = {chan: 0 for chan in self.channels}
# Calculate power for each channel
for device in self.devices:
# Find which power channel the device is connected to
chan = self.device_channels[device]
# Add power used by the device to total power used by channel
channel_power[chan] += self.device_power_values[device]
return channel_power
def power_used_device(self):
return self.device_power_values
def power_used(self):
return sum(self.device_power_values.values())
def blips(self):
return self.blips_on |
97174dfe60fdb0b7415ba87061573204d41490bc | rosa637033/OOAD_project_2 | /Animal.py | 597 | 4.15625 | 4 | from interface import move
class Animal:
#Constructor
def __init__(self, name, move:move):
self.name = name
self._move = move
# any move method that is in class move
def setMove(self, move) -> move:
self._move = move
# This is where strategy pattern is implemented.
def move(self):
self._move.run()
def wake(self):
print("I am awake")
def noise(self):
print("aw")
def eat(self):
print("I am eating")
def roam(self):
print("aw")
def sleep(self):
print("I am going to sleep")
|
b2a54172fb136c2298ff451de82d8038872597ca | DouglasKosvoski/URI | /1141 - 1150/1142.py | 116 | 3.5 | 4 | n = int(input())
a, b, c = 1, 2, 3
for i in range(n):
print(a, b, c, 'PUM')
a += 4
b += 4
c += 4
|
ee807dfee965cbc246a5296115068d88d6abecfb | DouglasKosvoski/URI | /1001 - 1020/1009.py | 153 | 3.5625 | 4 | name = str(input())
salary = float(input())
sales = float(input())
total_salary = salary + ((15/100) * sales)
print('TOTAL = R$ %.2f'%(total_salary))
|
2b90255fb4af8f07a09e61d595fcdc0addb5a9a9 | DouglasKosvoski/URI | /1131 - 1140/1133.py | 135 | 3.75 | 4 | x = int(input())
y = int(input())
for i in range(min(x,y)+1, max(x,y)):
if i % 5 == 2 or i % 5 == 3 and x != y:
print(i)
|
363d2410efc59f9dc5536bbd714290d87a1ad1fe | DouglasKosvoski/URI | /1001 - 1020/1008.py | 162 | 3.75 | 4 | NUMBER = int(input())
HOURS = int(input())
VALUE = float(input())
SALARY = HOURS * VALUE
print('NUMBER = %d'%(NUMBER))
print('SALARY = U$ %.2f'%(SALARY))
|
37ae37043038181bda2bb66f83342301611cd9ac | DouglasKosvoski/URI | /1171 - 1180/1175.py | 165 | 3.65625 | 4 | lista = []
for i in range(20):
n = int(input())
lista.append(n)
lista.reverse()
for i in range(len(lista)):
print('N[{0}] = {1}'.format(i, lista[i]))
|
785deab7e175755c7cbe84b41eda2b0f6b8dfe39 | accuLucca/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Semana 2/imprimedezenas.py | 148 | 4.0625 | 4 | num=int(input("Insira um numero inteiro: "))
unidade=num%10
unidade=(num-unidade)/10
dezena=unidade%10
print("O dígito das dezenas é",int(dezena)) |
c6ee66d4918ff2e20402ec9aa17b589ee8da6453 | accuLucca/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Semana 2/Contasegundos.py | 300 | 3.5 | 4 | segundos= input("Por favor insira o total de segundos para converter: ")
totalSegundos=int(segundos)
horas= totalSegundos // 3600
segRestantes = totalSegundos % 3600
minutos = segRestantes // 60
segRestantes2= segRestantes % 60
print(horas,"horas, ",minutos,"minutos e ",segRestantes2, "segundos. ") |
8aa4034d804f96ae79caa7ebd375f383ca4fee1e | jebbica/lilTurtGame | /bonusTurt.py | 5,981 | 3.890625 | 4 | import turtle
import random
import time
print('--------------------------------------------')
races = int(input("How many races u wanna see bruv? "))
print('--------------------------------------------')
win1 = 0
win2 = 0
colors = ['blue','green','pink','purple','brown','yellow','gold','turquoise']
def data(num, wins, total):
print(f"Turtle {num} has {wins} win(s)")
print(f"Turtle {num}'s win rate is {wins/total}")
for x in range(races):
turtle.bgcolor("grey")
one = turtle.Turtle()
two = turtle.Turtle()
ref = turtle.Turtle()
one.shape("turtle")
two.shape("turtle")
ref.shape("turtle")
one.speed(0)
two.speed(0)
ref.speed(0)
one.color("red")
two.color("blue")
ref.color("black")
x_val = -330
y_val = 340
ref.penup()
ref.goto(-330,340)
ref.pendown()
for a in range(22):
if a % 2 == 0:
for x in range(3):
if x % 2 == 0:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("black")
ref.end_fill()
x_val += 30
else:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("white")
ref.end_fill()
x_val += 30
else:
for x in range(3):
if x % 2 == 0:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("white")
ref.end_fill()
x_val += 30
else:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("black")
ref.end_fill()
x_val += 30
y_val -= 30
x_val = -330
x_val = 290
y_val = 340
ref.penup()
ref.goto(260,340)
ref.pendown()
for a in range(22):
if a % 2 == 0:
for x in range(3):
if x % 2 == 0:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("black")
ref.end_fill()
x_val += 30
else:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("white")
ref.end_fill()
x_val += 30
else:
for x in range(3):
if x % 2 == 0:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("white")
ref.end_fill()
x_val += 30
else:
ref.penup()
ref.goto(x_val,y_val)
ref.pendown()
ref.begin_fill()
for y in range(4):
ref.right(90)
ref.forward(30)
ref.color("black")
ref.end_fill()
x_val += 30
y_val -= 30
x_val = 290
one.penup()
one.goto(-275,200)
two.penup()
two.goto(-275, -200)
total_length = 525
distance = 0
distance1 = 0
#turtle.reset()
while distance < 525 and distance1 < 525:
move = random.randint(0,100)
move1 = random.randint(0,100)
one.forward(move)
one.color(random.choice(colors))
two.forward(move1)
two.color(random.choice(colors))
time.sleep(0.1)
distance1 += move1
distance += move
one.penup()
two.penup()
one.goto(-100,100)
two.goto(-100,50)
one.write("Distance traveled: " + str(distance), font=('Arial', 20 , 'italic'))
two.write("Distance traveled: " + str(distance1),font=('Arial', 20 , 'italic'))
time.sleep(2)
if distance>distance1:
one.right(90)
one.forward(20)
one.left(90)
one.write("winner winner chicken dinner", font=('Arial', 20 , 'italic'))
win1 += 1
else:
two.right(90)
two.forward(20)
two.left(90)
two.write("winner yeehaw",font=('Arial', 20 , 'italic'))
win2 += 1
turtle.clearscreen()
#turtle.bgpic("/lilTurt/winner.gif")
print('---------------------------')
data(1, win1, races)
print('---------------------------')
data(2, win2, races)
print('---------------------------')
# print("Turtle one: \n" + str(win) + " wins \n Turtle one win rate: " + str((win/races)*100))
# print("Turtle two: \n" + str(win2) + " wins \n Turtle two win rate: " + str((win2/races)*100))
turtle.mainloop() |
55571b0cbb00e6586886d0f907486ebcc50533f6 | junes7/pythonprac | /class_inheritance.py | 3,696 | 3.609375 | 4 | # 사람 클래스로 학생 클래스 만들기
class Person:
def greeting(self):
print('안녕하세요.')
class Student(Person):
def study(self):
print('공부하기')
james = Student()
james.greeting() # 안녕하세요.: 기반 클래스 Person의 메서드 호출
james.study() # 공부하기: 파생 클래스 Student에 추가한 study 메서드
# 포함 관계
class Person:
def greeting(self):
print('안녕하세요.')
class PersonList:
def __init__(self):
self.person_list = [] # 리스트 속성에 Person 인스턴스를 넣어서 관리
def append_person(self, person): # 리스트 속성에 Person 인스턴스를 추가하는 함수
self.person_list.append(person)
# 기반 클래스의 속성 사용하기
class Person:
def __init__(self):
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person):
def __init__(self):
print('Student __init__')
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello) # 기반 클래스의 속성을 출력하려고 하면 에러가 발생함
# super()로 기반 클래스 초기화하기
class Person:
def __init__(self):
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person):
def __init__(self):
print('Student __init__')
super().__init__() # super()로 기반 클래스의 __init__ 메서드 호출
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello)
# 메서드 오버라이딩 사용하기
class Person:
def greeting(self):
print('안녕하세요.')
class Student(Person):
def greeting(self):
print('안녕하세요. 저는 파이썬 코딩 도장 학생입니다.')
james = Student()
james.greeting()
# 다중 상속 사용하기
class Person:
def greeting(self):
print('안녕하세요.')
class University:
def manage_credit(self):
print('학점 관리')
class Undergraduate(Person, University):
def study(self):
print('공부하기')
james = Undergraduate()
james.greeting() # 안녕하세요.: 기반 클래스 Person의 메서드 호출
james.manage_credit() # 학점 관리: 기반 클래스 University의 메서드 호출
james.study() # 공부하기: 파생 클래스 Undergraduate에 추가한 study 메서드
# 다이아몬드 상속
class A:
def greeting(self):
print('안녕하세요. A입니다.')
class B(A):
def greeting(self):
print('안녕하세요. B입니다.')
class C(A):
def greeting(self):
print('안녕하세요. C입니다.')
class D(B, C):
pass
x = D()
x.greeting() # 안녕하세요. B입니다.
# 메서드 탐색 순서 확인하기
D.mro()
x = D()
x.greeting() # 안녕하세요. B입니다.
# 추상 클래스 사용하기
from abc import *
class StudentBase(metaclass=ABCMeta):
@abstractmethod
def study(self):
pass
@abstractmethod
def go_to_school(self):
pass
class Student(StudentBase):
def study(self):
print('공부하기')
def go_to_school(self):
print('학교가기')
james = Student()
james.study()
james.go_to_school()
# 추상 메서드를 빈 메서드로 만드는 이유
@abstractmethod
def study(self):
pass # 추상 메서드는 호출할 일이 없으므로 빈 메서드로 만듦
@abstractmethod
def go_to_school(self):
pass # 추상 메서드는 호출할 일이 없으므로 빈 메서드로 만듦
|
d5e73f709825cc160ac2688faafc2a57ce2875ca | junes7/pythonprac | /generator.py | 1,290 | 4.03125 | 4 | # 제너레이터 만들기
def number_generator(stop):
n = 0 # 숫자는 0부터 시작
while n < stop: # 현재 숫자가 반복을 끝낼 숫자보다 작을 때 반복
yield n # 현재 숫자를 바깥으로 전달
n += 1 # 현재 숫자를 증가시킴
for i in number_generator(3):
print(i)
# yield에서 함수 호출하기
def upper_generator(x):
for i in x:
yield i.upper() # 함수의 반환값을 바깥으로 전달
fruits = ['apple', 'pear', 'grape', 'pineapple', 'orange']
for i in upper_generator(fruits):
print(i)
# yield from 으로 값을 여러 번 바깥으로 전달하기
def number_generator():
x = [1, 2, 3]
for i in x:
yield i
for i in number_generator():
print(i)
def number_generator():
x = [1, 2, 3]
yield from x # 리스트에 들어있는 요소를 한 개씩 바깥으로 전달
for i in number_generator():
print(i)
g = number_generator()
next(g)
next(g)
next(g)
next(g)
# yield from에 제너레이터 객체 지정하기
def number_generator(stop):
n = 0
while n < stop:
yield n
n += 1
def three_generator():
yield from number_generator(3)
for i in three_generator():
print(i)
|
9f14f48a51cc8a7d8c9b6907e520abab02e39620 | junes7/pythonprac | /coroutine.py | 3,384 | 3.5625 | 4 | # 코루틴 사용하기
def add(a, b):
c = a + b # add 함수가 끝나면 변수와 계산식은 사라짐
print(c)
print('add 함수')
def calc():
add(1, 2) # add 함수가 끝나면 다시 calc 함수로 돌아옴
print('calc 함수')
calc()
# 코루틴에 값 보내기
def number_coroutine():
while True: # 코루틴을 계속 유지하기 위해 무한 루프 사용
x = (yield) # 코루틴 바깥에서 값을 받아옴, yield를 괄호로 묶어야 함
print(x)
co = number_coroutine()
next(co) # 코루틴 안의 yield까지 코드 실행(최초 실행)
co.send(1) # 코루틴에 숫자 1을 보냄
co.send(2) # 코루틴에 숫자 2을 보냄
co.send(3) # 코루틴에 숫자 3을 보냄
# 코루틴 바깥으로 값 전달하기
def sum_coroutine():
total = 0
while True:
x = (yield total) # 코루틴 바깥에서 값을 받아오면서 바깥으로 값을 전달
total += x
co = sum_coroutine()
print(next(co)) # 0: 코루틴 안의 yield까지 코드를 실행하고 코루틴에서 나온 값 출력
print(co.send(1)) # 1: 코루틴에 숫자 1을 보내고 코루틴에서 나온 값 출력
print(co.send(2)) # 3: 코루틴에 숫자 2를 보내고 코루틴에서 나온 값 출력
print(co.send(3)) # 6: 코루틴에 숫자 3을 보내고 코루틴에서 나온 값 출력
# 코루틴을 종료하기 예외 처리하기
def number_coroutine():
while True:
x = (yield)
print(x, end=' ')
co = number_coroutine()
next(co)
for i in range(20):
co.send(i)
# 코루틴 종료
co.close()
# GeneratorExit 예외 처리하기
def number_coroutine():
try:
while True:
x = (yield)
print(x, end=' ')
except GeneratorExit: # 코루틴이 종료 될 때 GeneratorExit 예외 발생
print()
print('코루틴 종료')
co = number_coroutine()
next(co)
for i in range(20):
co.send(i)
co.close()
# 코루틴 안에서 예외 발생시키기
def sum_coroutine():
try:
total = 0
while True:
x = (yield)
total += x
except RuntimeError as e:
print(e)
yield total # 코루틴 바깥으로 값 전달
co = sum_coroutine()
next(co)
for i in range(20):
co.send(i)
print(co.throw(RuntimeError, '예외로 코루틴 끝내기')) # 190
# 코루틴의 except에서 yield로 전달받은 값
# 하위 코루틴의 반환값 가져오기
def accumulate():
total = 0
while True:
x = (yield) # 코루틴 바깥에서 값을 받아옴
if x is None: # 받아온 값이 None이면
return total # 합계 total을 반환
total += x
def sum_coroutine():
while True:
total = yield from accumulate() # accumulate의 반환값을 가져옴
print(total)
co = sum_coroutine()
next(co)
for i in range(1, 11): # 1부터 10까지 반복
co.send(i) # 코루틴 accumulate에 숫자를 보냄
co.send(None) # 코루틴 accumulate에 None을 보내서 숫자 누적을 끝냄
for i in range(1, 101): # 1부터 100까지 반복
co.send(i) # 코루틴 accumulate에 숫자를 보냄
co.send(None) # 코루틴 accumulate에 None을 보내서 숫자 누적을 끝냄
|
1fbe4faa394a1d780010c2363e0395a7f5de2ea2 | ezekiel222/Matematica | /FuncCuadratica/func_cuadratica.py | 2,975 | 3.609375 | 4 | import os
from FuncCuadratica.calc_func_cuadratica import *
# Visual de la parte de Funcion Cuadratica.
def polinomio2():
while True:
try:
a = float(input("\nPrimer valor (a): "))
b = float(input("Segundo valor (b): "))
c = float(input("Tercer valor (c): "))
x1, x2, xv, yv = PolinomioCuadratico(a, b, c).calcular()
print("Las raices valen " + "{" + "{}. {}".format("%.2f" % x1, "%.2f" % x2) + "}")
print("El vertice es ({}, {})".format("%.2f" % xv, "%.2f" % yv))
PolinomioCuadratico(a, b, c).graficar()
input("\nEnter para volver.")
break
except:
print("Valor no valido, intentelo de nuevo")
continue
def factorizada2():
while True:
try:
a = float(input("\nPrimer valor (a): "))
x11 = float(input("Segundo valor (x1): "))
x22 = float(input("Tercer valor (x2): "))
b, c = cuadratica_factorizada(a, x11, x22)
x1, x2, xv, yv = PolinomioCuadratico(a, b, c).calcular()
print("Las raices valen " + "{" + "{}. {}".format("%.2f" % x1, "%.2f" % x2) + "}")
print("El vertice es ({}, {})".format("%.2f" % xv, "%.2f" % yv))
PolinomioCuadratico(a, b, c).graficar()
input("\nEnter para volver.")
break
except:
print("Valor no valido, intentelo de nuevo")
continue
def canonica1():
while True:
try:
a = float(input("\nPrimer valor (a): "))
xv1 = float(input("Segundo valor (xv): "))
yv2 = float(input("Tercer valor (yv): "))
b, c = cuadratica_canonica(a, xv1, yv2)
x1, x2, xv, yv = PolinomioCuadratico(a, b, c).calcular()
print("Las raices valen " + "{" + "{}. {}".format("%.2f" % x1, "%.2f" % x2) + "}")
print("El vertice es ({}, {})".format("%.2f" % xv, "%.2f" % yv))
PolinomioCuadratico(a, b, c).graficar()
input("\nEnter para volver.")
break
except:
print("Valor no valido, intentelo de nuevo")
continue
def menu():
os.system('clear')
print("Eliga una opcion:")
print("1-- Polinomio")
print("2-- Factorizada")
print("3-- Canonica")
print("4-- Salir")
option = input("Opción: ")
return option
def funcion_cuadratica():
while True:
option = menu()
if option == '1':
os.system('clear')
polinomio2()
continue
elif option == '2':
os.system('clear')
factorizada2()
continue
elif option == '3':
os.system('clear')
canonica1()
continue
elif option == '4':
break
else:
print("El valor no es valido, intentelo de nuevo")
continue
|
fb05fad10a27e03c50ef987443726e2acd11d49a | adamchainz/workshop-concurrency-and-parallelism | /ex4_big_o.py | 777 | 4.125 | 4 | from __future__ import annotations
def add_numbers(a: int, b: int) -> int:
return a + b
# TODO: time complexity is: O(_)
def add_lists(a: list[int], b: list[int]) -> list[int]:
return a + b
# TODO: time complexity is O(_)
# where n = total length of lists a and b
def unique_items(items: list[int]) -> list[int]:
unique: list[int] = []
for item in items:
if item not in unique:
unique.append(item)
return unique
# TODO: time complexity is O(_)
# where n = length of list items
def unique_items_with_set(items: list[int]) -> list[int]:
unique: set[int] = set()
for item in items:
unique.add(item)
return list(unique)
# TODO: time complexity is O(_)
# where n = length of list items
|
5207495ad7699318b8650d2f61272995fceecbc4 | aruncancode/wshsprojects | /002_AddingMachine/adding_machine.py | 3,062 | 4.03125 | 4 | from tkinter import *
def add():
# retrieves the value from the input box and assigns it to a variable
number1 = float(inpNumber1.get())
number2 = float(inpNumber2.get())
result = number1 + number2
# assigns the result variable to the text variable
lblResult.config(text=result)
def subtraction():
# retrieves the value from the input box and assigns it to a variable
number1 = float(inpNumber1.get())
number2 = float(inpNumber2.get())
result = number1 - number2
# assigns the result variable to the text variable
lblResult.config(text=result)
def multiplication():
number1 = float(inpNumber1.get())
number2 = float(inpNumber2.get())
result = number1 * number2
lblResult.config(text=result)
def division():
number1 = float(inpNumber1.get())
number2 = float(inpNumber2.get())
try:
result = number1/number2
lblResult.config(text=result)
except:
ZeroDivisionError
lblResult.config(text="ZeroDivisionError")
def clear():
inpNumber1.delete(0, END)
inpNumber2.delete(0, END)
lblResult.config(text='')
# Design the Graphical User Interface (GUI)
# Build the form
Form = Tk() # This creates a GUI and assigns it a name
Form.title("GUI Adding Machine")
Form.configure(bg="darkgrey")
# Sets the dimensions of the form, Length X Width, the X and Y coordinates
Form.geometry("350x500+1000+300")
# Create our form controls (the widgets/objects on the form, buttons, labels, inoutboxes, images, etc)
# input boxes
# set the name and style
inpNumber1 = Entry(Form, font=("default", 14))
inpNumber2 = Entry(Form, font=("default", 14))
# set its location and dimensions
inpNumber1.place(x=100, y=100, width=150, height=30)
inpNumber2.place(x=100, y=150, width=150, height=30)
# labels
lblResult = Label(Form, font=("default", 14), bg='cyan')
lblResult.place(x=100, y=200, width=150, height=30)
# buttons
# set name, style and assign a function to the command property
btnAdd = Button(Form, text="Add", fg="black", bg="white", command=add)
btnAddition = Button(Form, text="Addition", fg="black",
bg="white", command=add)
btnAddition.place(x=35, y=275, width=275, height=30)
# set its location and dimensions
btnSubtract = Button(Form, text="Subtract", fg="black",
bg="white", command=subtraction)
btnSubtract.place(x=35, y=300, width=275, height=25)
# set its location and dimensions
btnMultiplication = Button(Form, text="Multiplication",
fg="black", bg="white", command=multiplication)
btnMultiplication.place(x=35, y=325, width=275, height=25)
# set its location and dimensions
btnDivision = Button(Form, text="Division", fg="black",
bg="white", command=division)
btnDivision.place(x=35, y=350, width=275, height=25)
# set its location and dimensions
btnClear = Button(Form, text="Clear", fg="black", bg="white", command=clear)
btnClear.place(x=35, y=375, width=275, height=25)
# set its location and dimensions
# run the code
Form.mainloop()
|
c1f32f2060251d7e5b4349eafb98023bcaece3a0 | suryaaathhi/python | /vowel.py | 245 | 3.96875 | 4 | #enter the variable
variable=(input())
l=variable.isalpha()
if(l==True):
if( variable=="a" or variable=="e" or variable=="i" or variable=="o" or variable=="u"):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
b848f777182c2bce5c0a87a38b14608b39cc45fb | satishjasthi/CodeWar-Kata-s | /FindTheOddInt.py | 606 | 4.09375 | 4 | #Details:Given an array, find the int that appears an odd number of times.
#There will always be only one integer that appears an odd number of times.
#my first attempt code :)
def find_it(l):
return([number for number in l if (l.count(number)%2 != 0)][0])
#a = find_it([1,1,5,3,3,6,5,3,6,6,6]);print(a)
#other amazing solutions:
import operator
def find_it(xs):
return reduce(operator.xor, xs)
from collections import Counter
def find_it(l):
return [k for k, v in Counter(l).items() if v % 2 != 0][0]
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
|
eb667a28193f5c61ffc489d15285584d0a34ae13 | D10D3/Battleship | /battleship.py | 10,098 | 3.90625 | 4 | import os
import random
os.system('cls')
""" Single Player BattleShip Game Info:
Boards have 100 cells in 10 rows numbered A0 through J9
(chose to use 0-9 instead of traditional 1-10 to simplify code)
Cells will have 3 states:
"-" = empty or unknown
"O" = filled
"X" = bombed
"@" = known hit
players have 7 ships in their fleet:
Aircraft Carrier (5 cells)
Battleship (4 cells)
Cruiser (3 cells)
Submarine (3 cells)
Destroyer (2 cells)
"""
def initialize_board(board):
board = {}
for c in range(65,75):
for i in range(10):
board[chr(c) + str(i)] = '-'
return board
def error(): #if I screwed up
print "D10D3, your code sucks again"
quit()
def display_board(board): #displays selected board neatly
print " 0 1 2 3 4 5 6 7 8 9"
print " ____________________"
for c in range(65,75):
char = chr(c)
pstr = char + " |"
for i in range(10):
pstr += " " + board[char + str(i)]
pstr += "|"
print pstr
print " ----------------------"
def shipname(ship): #convert ships cell to ship name
shiplist = [
"Aircraft Carrier (5 cells)",
"BattleShip (4 cells)",
"Cruiser (3 cells)",
"Submarine (3 cells)",
"Destroyer (2 cells)"]
shipname = ""
shipname = shiplist[ship-1]
return shipname
def player_setup(board): #Player places his ships
for i in range (1,6):
while True:
os.system('cls')
intro_banner()
ships = [5,4,3,3,2] #cell size of each of the ships
ship_length = ships[i-1]
display_board(board)
print "-= PLAYER BOARD SETUP =-"
print ""
print " For each selection, first choose the top left ship position,"
print " then choose to fill to the right or down"
print " Where would you like to place %s" % shipname(i)
choice = choose_cell() #player chooses coordinate
while True:
direction = raw_input (' Fill in ship across or down? (A or D)> ')
direction.lower()
if direction == 'a':
break
elif direction == 'd':
break
else:
print " Please enter A or D"
selection = generate_selection(choice,ship_length,direction)
test = test_selection(selection,board)
if test:
board = write_ship(selection,board)
break
else:
print ""
print " That ship won't fit there, choose another spot"
raw_input (' <Press a Enter to select again>')
return board
def AI_setup(board): #AI places ships
for i in range (1,6):
while True:
ships = [5,4,3,3,2] #cell size of each of the ships
ship_length = ships[i-1]
choice = choose_cell_AI() #Computer chooses coordinate
dir_pos = ["a","d"] #possible orientations: Across or Down
direction = random.choice(dir_pos)
selection = generate_selection(choice,ship_length,direction)
test = test_selection(selection,board)
if test:
board = write_ship(selection,board)
print "Generating game boards..."
break
else:
print "Generating game boards..."
return board
def choose_cell(): #Asks player for cell choice, returns value
while True:
row = raw_input (' What Row? (A-J)> ')
row = row.upper()
letters = "ABCDEFGHIJ"
if row in letters:
break
else:
print " Please type a letter from A to J"
raw_input (' <Press a Enter to select again>')
while True:
column = raw_input(' What Column? (0-9)> ')
#column = int(column)
numbers = '0,1,2,3,4,5,6,7,8,9'
if column in numbers:
break
else:
print " Please type a number from 1 to 10"
raw_input (' <Press a Enter to select again>')
choice = ""
choice = choice + row + column
return choice
def choose_cell_AI(): #Generates random cell choice, returns value
letters = "ABCDEFGHIJ"
numbers = "0123456789"
row = random.choice(letters)
column = random.choice(numbers)
choice = ""
choice = choice + row + column
return choice
def generate_selection(choice,ship_length,direction): #Generates list of selected cells to place ship
selection = [choice]
if direction == 'a':
#across stuff
for i in range(1,ship_length):
addrow = choice[0]
addnum = choice[1]
addnum = int(addnum)
addnum += i
addnum = str(addnum)
addselect = ""
addselect = addselect + addrow + addnum
selection.append(addselect)
else:
#down stuff
for i in range(1,ship_length):
addrow = ord(choice[0]) #translates the letter into and ascii number
addrow += (i) #iterates it by 1
addrow = chr(addrow) #translates it back into a letter!
addnum = choice[1]
addselect = ""
addselect = addselect + addrow + addnum
selection.append(addselect)
return selection
def test_selection(selection,board): #checks if all cells for selected ship placement are allowed
test = False
badcell = False
for i in range(0,len(selection)): #creates loop based on length of selection
if selection[i] in board:
if board[selection[i]] == "-":
fnord = "fnord"
else:
badcell = True
else:
badcell = True
if badcell:
test = False
else:
test = True
return test
def test_shot(selection,board): #checks if shot is valid
test = False
badcell = False
for i in range(0,len(selection)): #creates loop based on length of selection
if selection[i] in board:
if board[selection[i]] == "-":
fnord = "fnord"
elif board[selection[i]] == "O":
fnord = "fnord"
elif board[selection[i]] == "X":
badcell = True
elif board[selection[i]] == "@":
badcell = True
else:
badcell = True
else:
badcell = True
if badcell:
test = False
else:
test = True
return test
def write_ship(selection,board): #writes the (now checked) ship selection to the board
# writecell = 0
for i in range(0,len(selection)): #creates loop based on length of selection
board[selection[i]] = "O"
return board
def intro_banner(): #fancy graphics
print"""
______ ___ _____ _____ _ _____ _____ _ _ ___________
| ___ \/ _ \_ _|_ _| | | ___/ ___| | | |_ _| ___ \\
| |_/ / /_\ \| | | | | | | |__ \ `--.| |_| | | | | |_/ /
| ___ \ _ || | | | | | | __| `--. \ _ | | | | __/
| |_/ / | | || | | | | |____| |___/\__/ / | | |_| |_| |
\____/\_| |_/\_/ \_/ \_____/\____/\____/\_| |_/\___/\_|
Ver 0.9 by D10D3
"""
def did_anyone_win(p_board,c_board):
#uses a letter loop and a number loop to check
#every cell of both boards for intact ship cells
#if none found on a board, the opponent is the winner
o_count_player = 0
o_count_computer = 0
for i in range(0,10):#letter loop
letter_index = "ABCDEFGHIJ"
letter = letter_index[i]
letter = str(letter)
for j in range(0,10):#number loop
number_index = range(0,10)
number = number_index[j]
number = str(number)
checkcell = letter + number
if p_board[checkcell] == "O":
o_count_player += 1
# else:
# fnord = "fnord"
if c_board[checkcell] == "O":
o_count_computer += 1
# else:
# fnord = "fnord"
if o_count_player == 0:
winner = "computer"
elif o_count_computer == 0:
winner = "player"
else:
winner = None
return winner
def win_lose(winner): #declare winner, ask if play again
print ""
if winner == "player":
print " You Win!"
else:
print " You Lose"
print ""
while True:
again = raw_input (' Play Again? Y or N> ')
again.lower
if again == "y" or again == "Y":
break
elif again == "n" or again == "N":
print "Thanks for playing!"
quit()
else:
print " Enter Y or N"
def man_or_ran(player_board): #choose manual or random player board setup
while True: #choose manual or random player ship placement
print ""
print ' Would you like to place your ships manually or randomly?'
setup = raw_input(' <M>anual or <R>andom? > ')
setup.lower()
if setup == 'm':
player_board = player_setup(player_board)
break
elif setup == 'r':
player_board = AI_setup(player_board)
break
else:
print " Please enter M or R"
return player_board
#***INITIALIZE AND SETUP***
os.system('cls')
intro_banner()
player_board = {}
computer_board = {}
hit_board = {}
player_board = initialize_board(player_board)
computer_board = initialize_board(computer_board)
hit_board = initialize_board(hit_board)
player_board = man_or_ran(player_board)
computer_board = AI_setup(computer_board)
#***BEGIN GAME LOOP***
while True:
while True: #did anyone win? if so play again?
winner = did_anyone_win(player_board,computer_board)
if winner:
win_lose(winner)
os.system('cls')
intro_banner()
player_board = {}
computer_board = {}
hit_board = {}
player_board = initialize_board(player_board)
computer_board = initialize_board(computer_board)
hit_board = initialize_board(hit_board)
player_board = man_or_ran(player_board)
computer_board = AI_setup(computer_board)
break
else:
fnord = "fnord"
break
os.system('cls')
intro_banner()
print " -= PLAYER SHIPS =-"
print ""
display_board(player_board)
print ""
print " -= Enemy =-"
display_board(hit_board) #Show the player where they have shot(and hit) so far
#display_board(computer_board) #cheat mode for debugging
print ""
#Player Attack
while True:
print " Choose A Cell to Attack!"
target = choose_cell() #player chooses coordinate
shooting = [target]
test = test_shot(shooting,computer_board)
print ""
if test:
if computer_board[target] == "-":
computer_board[target] = "X"
hit_board[target] = "X"
print " You didn't hit anything."
break
else:
computer_board[target] = "@"
print "You hit an enemy ship!"
hit_board[target] = "@"
break
else:
print ""
print " That is not a valid target!"
raw_input (' <Press a Enter to select again>')
#Computer Attack
while True:
target = choose_cell_AI() #AI chooses coordinate
shooting = [target]
test = test_shot(shooting,player_board)
if test:
if player_board[target] == "-":
player_board[target] = "X"
print " Computer attacks %s and misses" % target
raw_input (' <Press a Enter to continue>')
break
else:
player_board[target] = "@"
print " Computer attacks %s and hits!" % target
raw_input (' <Press a Enter to continue>')
break
else:
fnord = "fnord"
|
cc86f40a36fb6e74dae178fa6e1fd7324c17703e | Matt-Zimmer/week-3-lab-Matt-Zimmer | /week-03-lab-Matt-Zimmer.py | 2,807 | 3.875 | 4 | ######################################
# IT 2750 - Spring 2021 - Week 3 Lab #
# Password Cracking #
# Author: Matt Zimmer #
# Student: S00646766 #
######################################
############################################
#### SCROLL DOWN #########################
#### DON'T EDIT CODE IN THIS SECTION #####
############################################
# Import the zipfile module
import zipfile
# Open a zip file with a given password
def openZip(file, password=''):
# Create a new zip file object and open
# the zip file
zip = zipfile.ZipFile(file)
# Attempt to extract all contents of the zip file
# to the current directory. Return True if success
# and False if failure
try:
if password == '':
zip.extractall()
else:
zip.extractall(pwd=bytes(password, 'utf-8'))
return True
except Exception as e:
return False
############################################
#### START FROM HERE #####################
############################################
# Step 1: Create a list variable and initialize it with the
# first 10 of the top 25 most used passwords in 2019, per the following link:
# https://en.wikipedia.org/wiki/List_of_the_most_common_passwords
# USE THE FIRST TABLE, "According to SplashData"
passwords = ['123456', '123456789', 'qwerty', 'password', '1234567', '12345678', '12345', 'iloveyou', '111111', '123123']
# Step 2: Ask the user for the filename of the zip file that
# we will attempt to crack (just the filename, not the full
# path... make sure the actual zip file is in the same
# directory as the python script and that the current working
# directory in the command prompt is that same directory)
fileName = (input("What zip file do you want to use? "))
# Step 3: Create a loop that iterates through each password
# in the list. You can use a while loop or for loop
for passwordType in passwords:
print("Attempting Password... " + passwordType)
# Step 4: For each iteration of the loop, attempt to crack
# the zipfile password by calling the openZip function and
# passing the filename and the password to try. The openZip
# function returns True if it was successful and False if it
# was not. An example of calling the function is
# result = openZip(filename, password)
filename = True
result = openZip(filename, passwordType)
# Step 5: For each iteraton of the loop, let the user know
# what the result of the crack attempt was (True = success,
# False = failure) and what password was tried
for passwordType in passwords:
if passwordType != "":
print('...failed')
else:
print('...Success!!!')
|
eafef01f598c0b42b79646000b0e6355d56ded43 | keelymeyers/SI206-Project1 | /206project1.py | 5,635 | 3.96875 | 4 | import os
import csv
import filecmp
## Referenced code from SI 106 textbook 'Programs, Information, and People' by Paul Resnick to complete this project
def getData(file):
#Input: file name
#Ouput: return a list of dictionary objects where
#the keys will come from the first row in the data.
#Note: The column headings will not change from the
#test cases below, but the the data itself will
#change (contents and size) in the different test
#cases.
#Your code here:
data_file = open(file, "r")
new_file = csv.reader(data_file)
final = []
for row in new_file:
d = {}
d['First'] = row[0]
d['Last'] = row[1]
d['Email'] = row[2]
d['Class'] = row[3]
d['DOB'] = row[4]
final.append(d)
#print (final[1:])
return final[1:]
#Sort based on key/column
def mySort(data,col):
#Input: list of dictionaries
#Output: Return a string of the form firstName lastName
#Your code here:
x = sorted(data, key = lambda x: x[col])
return str(x[0]['First'])+ " " + str(x[0]['Last'])
#Create a histogram
def classSizes(data):
# Input: list of dictionaries
# Output: Return a list of tuples ordered by
# ClassName and Class size, e.g
# [('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)]
#Your code here:
#data = [{'first:keely, last: meyers, class: junior, dob: 5/18/97'}]
dd = dict()
for s in data:
if s['Class'] == 'Freshman':
if 'Freshman' not in dd:
dd['Freshman'] = 1
else:
dd['Freshman'] += 1
elif s['Class'] == 'Sophomore':
if 'Sophomore' not in dd:
dd['Sophomore'] = 1
else:
dd['Sophomore'] += 1
elif s['Class'] == 'Junior':
if 'Junior' not in dd:
dd['Junior'] = 1
else:
dd['Junior'] += 1
elif s['Class'] == 'Senior':
if 'Senior' not in dd:
dd['Senior'] = 1
else:
dd['Senior'] += 1
class_count = list(dd.items())
new_class_count = sorted(class_count, key = lambda x: x[1], reverse = True)
return new_class_count
# Find the most common day of the year to be born
def findDay(a):
# Input: list of dictionaries
# Output: Return the day of month (1-31) that is the
# most often seen in the DOB
#Your code here:
bday_dict = {}
for names in a:
n_bday = names['DOB'].strip()
new_bday = n_bday[:-5]
#print (new_bday)
if new_bday[1] == '/':
day = new_bday[2:]
elif new_bday[2] == '/':
day = new_bday[3:]
bday_dict[names['First']] = day
#print (bday_dict)
day_counts = {}
for birthday in bday_dict:
if bday_dict[birthday] in day_counts:
day_counts[bday_dict[birthday]] += 1
else:
day_counts[bday_dict[birthday]] = 1
#print(day_counts)
sorted_birthdays = sorted(day_counts.items(), key = lambda x: x[1], reverse = True)
return int(sorted_birthdays[0][0])
# Find the average age (rounded) of the Students
def findAge(a):
# Input: list of dictionaries
# Output: Return the day of month (1-31) that is the
# most often seen in the DOB
#Your code here:
ages = []
count = 0
for item in a:
year = item['DOB'][-4:]
age = (2017 - int(year))
ages.append(age)
count += 1
avg_age = round(sum(ages)/count)
#print (avg_age)
return avg_age
#Similar to mySort, but instead of returning single
#Student, all of the sorted data is saved to a csv file.
def mySortPrint(a,col,fileName):
#Input: list of dictionaries, key to sort by and output file name
#Output: None
#Your code here:
outfile = open(fileName, "w")
x = sorted(a, key = lambda x: x[col])
#print (x)
#note: x is sorted correctly.
for s in x:
outfile.write("{},{},{}\n".format(s['First'], s['Last'], s['Email']))
outfile.close()
################################################################
## DO NOT MODIFY ANY CODE BELOW THIS
################################################################
## We have provided simple test() function used in main() to print what each function returns vs. what it's supposed to return.
def test(got, expected, pts):
score = 0;
if got == expected:
score = pts
print(" OK ",end=" ")
else:
print (" XX ", end=" ")
print("Got: ",got, "Expected: ",expected)
return score
# Provided main() calls the above functions with interesting inputs, using test() to check if each result is correct or not.
def main():
total = 0
print("Read in Test data and store as a list of dictionaries")
data = getData('P1DataA.csv')
data2 = getData('P1DataB.csv')
total += test(type(data),type([]),40)
print()
print("First student sorted by First name:")
total += test(mySort(data,'First'),'Abbot Le',15)
total += test(mySort(data2,'First'),'Adam Rocha',15)
print("First student sorted by Last name:")
total += test(mySort(data,'Last'),'Elijah Adams',15)
total += test(mySort(data2,'Last'),'Elijah Adams',15)
print("First student sorted by Email:")
total += test(mySort(data,'Email'),'Hope Craft',15)
total += test(mySort(data2,'Email'),'Orli Humphrey',15)
print("\nEach grade ordered by size:")
total += test(classSizes(data),[('Junior', 28), ('Senior', 27), ('Freshman', 23), ('Sophomore', 22)],10)
total += test(classSizes(data2),[('Senior', 26), ('Junior', 25), ('Freshman', 21), ('Sophomore', 18)],10)
print("\nThe most common day of the year to be born is:")
total += test(findDay(data),13,10)
total += test(findDay(data2),26,10)
print("\nThe average age is:")
total += test(findAge(data),39,10)
total += test(findAge(data2),41,10)
print("\nSuccessful sort and print to file:")
mySortPrint(data,'Last','results.csv')
if os.path.exists('results.csv'):
total += test(filecmp.cmp('outfile.csv', 'results.csv'),True,10)
print("Your final score is: ",total)
# Standard boilerplate to call the main() function that tests all your code.
if __name__ == '__main__':
main()
|
2d69346d0d83057fd18eb28f51e9135b16f1a87f | juelianzhiren/python_demo | /alice.py | 236 | 3.640625 | 4 | filename="alice.txt";
try:
with open(filename) as f_obj:
contents = f_obj.read();
except FileNotFoundError:
msg = "Sorry, the file " + filename + " doesn't exist";
print(msg);
title = "Alice in Wonderland";
print(title.split());
|
9d2496045c0476bf19d4b3ce8f65894093f5083d | ynadji/scrape | /scrape-basic | 638 | 3.65625 | 4 | #!/usr/bin/env python
#
# Basic webscraper. Given a URL and anchor text, find
# print all HREF links to the found anchor tags.
#
# Usage: scrape-basic http://www.usenix.org/events/sec10/tech/ "Full paper"
#
# returns:
#
# http://www.usenix.org/events/sec10/tech/full_papers/Sehr.pdf
# ...
# http://www.usenix.org/events/sec10/tech/full_papers/Gupta.pdf
#
# Pipe into "wget -i -" to download the files one-by-one.
#
from scrape import *
import slib
import sys,os
if len(sys.argv) != 3:
print "usage: scrape-basic URL A-TEXT"
sys.exit(1)
main_region = s.go(sys.argv[1])
slib.basic(main_region, 'a', 'href', content=sys.argv[2])
|
e775866737d6da83a8311e5eaa45df7dcee199ea | vigneshrajmohan/CharterBot | /CharterBot.py | 3,356 | 3.765625 | 4 | # PyChat 2K17
import random
import time
def start():
pass
def end():
pass
def confirm(question):
while True:
answer = input(question + " (y/n)")
answer = answer.lower()
if answer in ["y" , "yes", "yup"]:
return True
elif answer in ["n", "no", "nope"]:
return False
def has_keyword(statement, keywords):
for word in keywords:
if word in statement:
return True
return False
def get_random_response():
responses = ["I understand",
"Mhm",
"Well... could you please elaborate?",
"I'm sorry, this is out of my field, please press 3 to be connected with another one of our representative."
]
return random.choice(responses)
def get_random_name():
responses = ["Vinny",
"Danny",
"Mark",
"Finn",
"Noah",
"Will",
"Desmond",
"Bill",
"Ajit"]
return random.choice(responses)
def get_response(statement):
statement = statement.lower()
service_words = ["phone", "internet", "vision"]
problem_words = [" not ", "broken", "hate", "isn't"]
competitor_words = ["at&t", "verizon", "comcast", "dish"]
if statement == "1":
response = "We provide the nation's fastest internet, highest quality phone service, and the best selection of channels. Press 3 to get connected to a representative"
elif statement == "2":
response = "We're sorry that you are having problems with our products. Please press '3' to be connected with one of our representatives"
elif statement == "3":
response = "Hello my name is " + get_random_name() + ". How may I be of service to you?"
elif has_keyword(statement, service_words):
response = "Our products are of optimum quality. Please visit out website charter.com or spectrum.com for more information."
elif has_keyword(statement, problem_words):
response = "So sorry to hear that, have you tried turning it off and back on?"
elif has_keyword(statement, competitor_words):
response = "Stay with us and we'll add $100 in credit to your account for loyalty."
else:
response = get_random_response()
return response
def play():
talking = True
print("""+-+-+-+-+-+-+-+
|C|H|A|R|T|E|R|
+-+-+-+-+-+-+-+""")
print("Hello! Welcome to Charter customer service. ")
print("We are always happy to help you with your Charter services or products.")
print("Please wait for some time while we get you connected")
time.sleep(1)
print("*elevator music*")
time.sleep(10)
print("Thank you for waiting")
print("Please press 1 for more information on our services.")
print("Please press 2 if you have a problem with one of our services.")
print("Please press 3 to be connected to a representative.")
while talking:
statement = input(">> ")
if statement == "Goodbye":
talking = False
else:
response = get_response(statement)
print(response)
print("Goodbye. It was nice talking to you.")
start()
playing = True
while playing:
play()
playing = confirm("Would you like to chat again?")
end()
|
4819a44f44262619c27320ce0fab50351f5039d6 | urmomlol980034/GCALC-V.2 | /square.py | 419 | 3.796875 | 4 | from os import system, name
from time import sleep
from math import sqrt
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def square():
sleep(1)
clear()
print('You have chosen: Square Root')
f = eval(input('What number do you want to be square rooted?\n> '))
equ = sqrt(f)
print('Your answer is:',equ)
input('|:PRESS ENTER WHEN DONE:|')
sleep(1)
clear() |
0d9f1324ec8c52ff6f2639439d705e11f65a35be | prah23/Stocker | /ML/scraping/losers/daily_top_losers.py | 943 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 23:52:33 2020
@author: pranjal27bhardwaj
"""
# This function will give the worst performing stocks of the day
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
def daily_losers():
dfs = pd.read_html('https://money.rediff.com/losers/bse/daily',header=0)
for df in dfs[:-1]:
print(df)
df1 = df[['Company', '% Change']]
print(df1)
df1.to_csv('daily_top_losers.csv', index=False)
daily_losers()
def plot_daily_losers():
plt.style.use('fivethirtyeight')
data_daily_losers = pd.read_csv('daily_top_losers.csv')
data_daily_losers_final = data_daily_losers[:16]
x4 = data_daily_losers_final.plot.bar(x = 'Company', y = '% Change', title = 'Daily Top Losers', color='Black')
plt.savefig('daily_top_losers.png', bbox_inches='tight')
plt.show(x4)
plot_daily_losers() |
d6aa861af8b2d53326a1dc779682273bb09ac52c | rlgustavo/DarkWord | /Dark-world/Dark_World_S1.py | 26,383 | 3.546875 | 4 | """
Grupo 4
Indice:
1. Definição de cores
2. Abertura do display, considerando altura e largura
3. Iniciado a função Clock
4. Carregando para a memória as músicas presentes./
definido a função para o som das teclas
5. Carregando imagens para memória/redimensionando B1,
referente a imagens, de setas e B3, referente a
imagem da tela inicial.
6. Definida a função para a esfera rodar como sprite
7. Contém os textos de todo o jogo, assim como as funções
que rodam esses textos.
8. Contem as chaves, em texto, que serão colocadas nas fases.
9. Lê valores das setas, Q e enter, retornando se estão ou não
pressionados.
10. Contém as fases do jogos de 0 a 10, essas utilizam-se de
outros elementos encontrados nos índices 7,8 e 14.4.
Contendo também, na fase 10, uma varíavel que altera 16.1
11. Teclas de fase compreende, exclusivamente, a fase 3.
12. Tela inicial encontra-se dentro do loop de game, e
aparece quando iniciar estiver em True. Também
encontra-se a opção de instruções aqui.
13. 'O jogo' desenha e passa os sprites da Orbita (6.), também
fornecendo qual fase deve ser rodada.
14. A lista de eventos é definida a cada passagem, sendo apagada
no começo desse setor. Duas listas são formados: Eventos e
Respostas.
15. Movimentação usa as informações de 9. Para definir a direção
e quanto a esfera se moverá.
16. Regras impede a esfera de passar da tela e muda o limite dos
sprites, fazendo a imagem mudar.
17. Utiliza-se da função relógio para reduzir a velocidade e
atualiza o display.
"""
import pygame
import random
pygame.init()
#________________1.Cores________________
branco = (255,255,255)
vermelho = (255,0,0)
preto = (0,0,0)
cinza_escuro = (50,50,50)
#________________2.Set de display________________
dimensao_tela = [720,480]
tela = pygame.display.set_mode(dimensao_tela)
pygame.display.set_caption("Dark dimension")
posição_x = dimensao_tela[0]/2
posição_y = dimensao_tela[1]/2
#________________3.Set Clock________________
relogio = pygame.time.Clock()
#________________4.Set Musicas________________
soundtrack = pygame.mixer.Sound('musicas/smash_hit_ost_zen_mode.mp3')
soundtrack.set_volume(0.1)
inicial = pygame.mixer.Sound('musicas/inicio.mp3')
inicial.set_volume(0.2)
teclas = pygame.mixer.Sound('musicas/Click.mp3')
teclas.set_volume(0.2)
def som_teclas():
soundtrack.stop()
teclas.play(1)
soundtrack.play(-1)
#________________5.Set imagens________________
#
esferas_1 = pygame.image.load('Esferas_180_1.png')
esferas_2 = pygame.image.load('Esferas_180_2.png')
esferas_3 = pygame.image.load('Esferas_180_3.png')
esferas_4 = pygame.image.load('Esferas_180_4.png')
esferas_5 = pygame.image.load('Esferas_180_5.png')
esferas_6 = pygame.image.load('Esferas_180_6.png')
esferas_7 = pygame.image.load('Esferas_180_7.png')
esferas_8 = pygame.image.load('Esferas_180_8.png')
esferas_9 = pygame.image.load('Esferas_180_9.png')
esferas_10 = pygame.image.load('Esferas_180_10.png')
esferas_11 = pygame.image.load('Esferas_180_11.png')
esferas_12 = pygame.image.load('Esferas_180_12.png')
esferas_13 = pygame.image.load('Esferas_180_13.png')
esferas_14 = pygame.image.load('Esferas_180_14.png')
esferas_15 = pygame.image.load('Esferas_180_15.png')
brilhar_0 = pygame.image.load('Transform/Esferas_Shine_0.png')
brilhar_1 = pygame.image.load('Transform/Esferas_Shine_1.png')
brilhar_2 = pygame.image.load('Transform/Esferas_Shine_2.png')
brilhar_3 = pygame.image.load('Transform/Esferas_Shine_3.png')
brilhar_4 = pygame.image.load('Transform/Esferas_Shine_4.png')
brilhar_5 = pygame.image.load('Transform/Esferas_Shine_5.png')
brilhar_6 = pygame.image.load('Transform/Esferas_Shine_6.png')
brilhar_7 = pygame.image.load('Transform/Esferas_Shine_7.png')
brilhar_8 = pygame.image.load('Transform/Esferas_Shine_8.png')
brilhar_9 = pygame.image.load('Transform/Esferas_Shine_9.png')
brilhar_10 = pygame.image.load('Transform/Esferas_Shine_10.png')
brilhar_11 = pygame.image.load('Transform/Esferas_Shine_11.png')
brilhar_12 = pygame.image.load('Transform/Esferas_Shine_12.png')
biblioteca_1 = pygame.image.load('Navigation_keys(1).png')
biblioteca_1 = pygame.transform.scale(biblioteca_1, [120, 100])
biblioteca_2 = pygame.image.load('Coruja(1).png')
biblioteca_3 = pygame.image.load('universe.jpg')
biblioteca_3 = pygame.transform.scale(biblioteca_3, [200, 200])
lista_esfera = [esferas_1,esferas_2,esferas_3,esferas_4,
esferas_5,esferas_6,esferas_7,esferas_8,
esferas_9,esferas_10,esferas_11,esferas_12,
esferas_13,esferas_14,esferas_15,
brilhar_0,brilhar_1,brilhar_2,brilhar_3,
brilhar_4,brilhar_5,brilhar_6,brilhar_7,
brilhar_8,brilhar_9,brilhar_10,brilhar_11,
brilhar_12]
quantidade_sprite = len(lista_esfera)
# 5.1-> Centro de imagens B1 e B3
centro1 = []
centro3 = []
for i in biblioteca_3.get_rect():
centro3.append(i)
for i in biblioteca_1.get_rect():
centro1.append(i)
#________________6.Formas________________
tamanho = 10
def orbitas():
global largura
global altura
largura = 259
altura = 259
tela.blit(lista_esfera[sprite],(posição_x-(largura/2),posição_y-(altura/2)))
#________________7.Textos________________
mensagem = ["Olá... tente... espaço","sinto que está perdido",
"Mas já sabe se mover...","Isso é bom...",
"se for mais fácil...","segure Q","Agora podemos seguir",
"Talvez...","eu consiga facilitar...","Melhor?",
"Acredito que sim...","Agora ouça...","Aqui... não é seguro",
"Não sei como veio parar aqui","Mas tem de achar a chave!",
"encontre a chave...","Fim da fase",
"Fase 2: Repita", "Muito bem...","a primeira porta foi aberta",
"está indo bem...","mas não deve parar","Outra chave está perdida",
"encontre-a","Fim da fase",
"Fase 3: Una","Cada passo é um passo...", "As vezes",
"o começo será arduo",
"mas veja...", "podia ser pior","imagine se tivesse mais de uma?",
"Opa, acho que falei demais hihi","Fim da fase",
"Fase 4: Tente","Nunca duvidei!","ta...quando apertou o primeiro",
"até duvidei",
"mas sabia que conseguiria!","...sei que estamos chegando",
"quase posso sentir","uma pitada do fim...",
"Mas... temos um problema","Eles sabem que estamos aqui",
"A chave... ela se move!","Boa sorte...", "Fim da fase",
"Fase 5: Escolha","Há muitas coisas curiosas aqui","Notou?",
"Veja... Não é apenas preto",
"Você é a luz desse lugar!","Que poético...","Ou pelo menos seria",
"Se não estivesse preso aqui","Por isso...","Sem chave dessa vez",
"Me responda de forma simples","Você quer sair daqui?","Sim ou Não",
"Ok... vamos recomeçar","Então vamos continuar!",
"Fase 6: Reconheça","O quê?","Ah, isso de chave e tudo mais",
"É... elas nunca foram necessárias","Sabe... eu tentei",
"Realmente tentei tornar isso mais fácil",
"Mas eu prevejo que continuará",
"Retomando ao começo","Sendo tão simples achar a saída",
"Apenas me diga","O que é isso?","Fim da fase",
"Fase 7: Ouça","A coruja... ela é uma base muito boa",
"para o que quero explicar",
"Uma ave observadora","tratada como a sabedoria",
"é sempre isso que buscamos","Mas não importe o quão corra atrás",
"nunca alcaçará...","Por isso, aceitamos nossos erros",
"E mesmo que não saiba responder a próxima","não se preocupe",
"Apenas tente novamente","veja... sequer notou os números",
"que passou por toda essa fase...","elas são sua saída",
"diga-me","Quais foram?","Viu... não foi tão ruim",
"Agora calma... leia tudo e responda",
"Some o primeio com o ultimo","eleve a",
"soma do segundo com o penultimo","E então me diga",
"Qual a chave da sabedoria?",
"Não era bem isso o que eu esperava...","Fim da fase",
"Fase 8: Perdoe","Okay... desculpa","Foi intensional a pergunta passada",
"Eu não quero que fique irritado","ou algo do tipo","Apenas...",
"Queria que ficasse um pouco mais","Estamos perto do fim",
"E... também não quero","que seu esforço seja em vão",
"Aquela conta que lhe pedi...","só... me diga o resultado",
"Fim da fase",
"Fase 9: Não esqueça","É isso...","Este é o fim",
"O ultimo dos desafios",
"Assim que terminar, poderá ir","Não quero que seja difícil",
"Só que... represente seu tempo aqui","Por isso...",
"Lembra das letras que pegou?","Faltou uma",
"Ela esteve em algum lugar","Mas não sei onde","Porém...",
"Não precisa voltar","Ela completa uma palavra",
"E só dela que preciso","Qual é... a palavra?", "Obrigado..."
"Seu tempo foi precioso","E mesmo assim","Insisto em perguntar",
"Você quer ficar?","Sim ou Não?","Eu gosto de você, vamos de novo",
"Okay... já não há limites... Ande, vá","Fim"]
tamanho_mensagem = len(mensagem)-1
mensagem1 = 0
def Informações_texto():
global cor
global tamanho_fonte
global posição_txt_y
cor = cinza_escuro
tamanho_fonte = 30
posição_txt_y = dimensao_tela[1] - 70
def txt():
font = pygame.font.SysFont('lucidacalligraphy',tamanho_fonte)
texto = font.render(mensagem[mensagem1],10,cor)
centro = []
for i in texto.get_rect():
centro.append(i)
posição_txt_x = (dimensao_tela[0]/2)-(centro[2]/2)
tela.blit(texto,[posição_txt_x,posição_txt_y])
# 7.1 -> Textos tela inicial
def outros_texto():
# -> Título
font = pygame.font.SysFont("CASTELLAR", 45)
nome_jogo = font.render("Dark World", 45, (75,0,130))
tela.blit(nome_jogo, [200, (dimensao_tela[1] / 2 - 20)])
# -> Texto "Começar" Centralizado
font = pygame.font.SysFont("lucidacalligraphy", 25)
começar = font.render("Começar", 45, cor1)
centro = []
for i in começar.get_rect():
centro.append(i)
posição_txt_x = (dimensao_tela[0]/2)-(centro[2]/2)
tela.blit(começar, [posição_txt_x, (dimensao_tela[1] / 2)+50])
# -> Texto "Instruções" centralizados
font = pygame.font.SysFont("lucidacalligraphy", 25)
começar = font.render("Instruções", 45, cor2)
centro = []
for i in começar.get_rect():
centro.append(i)
posição_txt_x = (dimensao_tela[0]/2)-(centro[2]/2)
tela.blit(começar, [posição_txt_x, (dimensao_tela[1] / 2)+90])
# 7.2 -> Textos de Instruções
def txt_instruções():
font = pygame.font.SysFont("lucidacalligraphy", 15)
esc_ins = font.render(" |Esc para voltar ao menu", 45, (255,255,255))
tela.blit(esc_ins, [dimensao_tela[0]-290, (dimensao_tela[1]-120)])
font = pygame.font.SysFont("lucidacalligraphy", 15)
nome_jogo = font.render(" |Segure q para melhor ver", 45, (255,255,255))
tela.blit(nome_jogo, [dimensao_tela[0]-290, (dimensao_tela[1] -80)])
font = pygame.font.SysFont("lucidacalligraphy", 15)
nome_jogo = font.render(" |Use letras e números para fases", 45, (255,255,255))
tela.blit(nome_jogo, [dimensao_tela[0]-290, (dimensao_tela[1]-40)])
#________________8.Chaves________________
chaves = ["Pressione: H","U","M","A","N","2","7","8","3","1","5"]
posição_chave_x = dimensao_tela[0] - 200
posição_chave_y = 50
tamanho_chave = 20
fase = 0
def keys():
font_chave = pygame.font.SysFont('lucidacalligraphy',tamanho_chave)
chave = font_chave.render(chaves[chave_fase],10,preto)
tela.blit(chave,[posição_chave_x,posição_chave_y])
#________________9.Comandos________________
def left_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
return True
return False
def right_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
return True
return False
def up_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
return True
return False
def down_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
return True
return False
def q_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_q]:
return True
return False
def enter_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_KP_ENTER]:
return True
return False
#________________10.Fases________________
def phase_1():
global mensagem1
global cor
global tamanho_fonte
global posição_txt_y
global fase
global chave_fase
if mensagem1 <= 8:
cor = preto
tamanho_fonte = 55
posição_txt_y = dimensao_tela[1]/2 - 170
if "espaço" in eventos:
if mensagem1 < 15:
mensagem1 += 1
if mensagem1 >= 17:
mensagem1 = 0
if mensagem1 == 15:
chave_fase = 0
keys()
if "h" in eventos:
mensagem1 = 16
fase = 1
txt()
def phase_2():
global mensagem1
global posição_chave_x
global posição_chave_y
global fase
global chave_fase
if "espaço" in eventos:
if mensagem1 < 23:
mensagem1 += 1
if mensagem1 == 23:
posição_chave_x = 50
posição_chave_y = dimensao_tela[1] -120
chave_fase = 1
keys()
if "u" in eventos:
mensagem1 = 24
fase = 2
txt()
def phase_3():
global mensagem1
global posição_chave_x
global posição_chave_y
global fase
global chave_fase
if "espaço" in eventos:
if mensagem1 < 32:
mensagem1 += 1
if mensagem1 == 32:
posição_chave_x = 15
posição_chave_y = dimensao_tela[1] -30
chave_fase = 2
keys()
posição_chave_x = dimensao_tela[0] -200
posição_chave_y = dimensao_tela[1]/2
chave_fase = 3
keys()
if "ma" in eventos:
mensagem1 = 33
fase = 3
txt()
def phase_4():
global mensagem1
global posição_chave_x
global posição_chave_y
global fase
global chave_fase
if "espaço" in eventos:
if mensagem1 < 45:
mensagem1 += 1
if mensagem1 == 45:
posição_chave_x = random.randint(30,dimensao_tela[0])-10
posição_chave_y = random.randint(30,dimensao_tela[1])-20
chave_fase = 4
keys()
if "n" in eventos:
mensagem1 = 46
fase = 4
txt()
def phase_5():
global mensagem1
global respostas
global fase
if len(respostas)>3:
respostas.clear()
if "espaço" in eventos:
if mensagem1 < 59:
mensagem1 += 1
if ["S","I","M"] == respostas:
mensagem1 = 61
fase = 5
respostas.clear()
if ["N","A","O"] == respostas:
mensagem1 = 60
fase = 0
respostas.clear()
print(respostas)
txt()
tempo_aparição = 0
def phase_6():
global mensagem1
global respostas
global fase
global tempo_aparição
if len(respostas)>6:
respostas.clear()
if "espaço" in eventos:
if mensagem1 < 72:
mensagem1 += 1
if mensagem1 == 72:
tempo_aparição += 1
if tempo_aparição < 10:
tela.blit(biblioteca_2,[dimensao_tela[0]-150,
dimensao_tela[1]-150])
elif tempo_aparição == 30:
tempo_aparição = 0
if ["C","O","R","U","J","A"] == respostas:
mensagem1 = 73
fase = 6
respostas.clear()
print (respostas)
txt()
primeira_parte = False
def phase_7():
global mensagem1
global posição_chave_x
global posição_chave_y
global respostas
global fase
global chave_fase
global primeira_parte
if "espaço" in eventos:
if mensagem1 < 90:
mensagem1 += 1
elif primeira_parte:
if mensagem1 < 97:
mensagem1 += 1
if mensagem1 == 75:
posição_chave_x = 50
posição_chave_y = dimensao_tela[1] -120
chave_fase = 5
keys()
elif mensagem1 == 79:
posição_chave_x = dimensao_tela[0] -100
posição_chave_y = 120
chave_fase = 6
keys()
elif mensagem1 == 82:
posição_chave_x = dimensao_tela[0] -300
posição_chave_y = dimensao_tela[1] -120
chave_fase = 7
keys()
elif mensagem1 == 85:
posição_chave_x = dimensao_tela[0]/2
posição_chave_y = -40
chave_fase = 8
keys()
elif mensagem1 == 87:
posição_chave_x = 50
posição_chave_y = dimensao_tela[1] -120
chave_fase = 9
keys()
elif mensagem1 == 90:
posição_chave_x = dimensao_tela[0]/2
posição_chave_y = dimensao_tela[1]/2
chave_fase = 10
keys()
if ["2","7","8","3","1","5"] == respostas:
primeira_parte = True
mensagem1 = 91
respostas.clear()
if ["C","O","R","U","J","A"] == respostas:
fase = 7
mensagem1 = 99
respostas.clear()
if len(respostas)>6:
fase = 0
mensagem1 = 98
respostas.clear()
print(respostas)
txt()
def phase_8():
global mensagem1
global respostas
global fase
if len(respostas)>7:
respostas.clear()
if "espaço" in eventos:
if mensagem1 < 111:
mensagem1 += 1
if ["5","7","6","4","8","0","1"] == respostas:
mensagem1 = 112
fase = 8
respostas.clear()
print (respostas)
txt()
def phase_9():
global mensagem1
global respostas
global fase
if len(respostas)>7:
respostas.clear()
if "espaço" in eventos:
if mensagem1 < 129:
mensagem1 += 1
if ["H","U","M","A","N","O"] == respostas:
mensagem1 = 130
fase = 9
respostas.clear()
print (respostas)
txt()
limite = True
def phase_10():
global mensagem1
global fase
global limite
global posição_txt_y
if "espaço" in eventos:
if mensagem1 < 134:
mensagem1 += 1
if ["S","I","M"] == respostas:
mensagem1 = 135
fase = 0
respostas.clear()
if ["N","A","O"] == respostas:
mensagem1 = 136
limite = False
respostas.clear()
if posição_x-(largura/2) >= dimensao_tela[0]+200:
posição_txt_y = dimensao_tela[1]/2
mensagem1 = 137
if posição_x-(largura/2) <= 0-200:
posição_txt_y = dimensao_tela[1]/2
mensagem1 = 137
if posição_y-(altura/2) <= 0-200:
posição_txt_y = dimensao_tela[1]/2
mensagem1 = 137
if posição_y-(altura/2) >= dimensao_tela[1]+200:
posição_txt_y = dimensao_tela[1]/2
mensagem1 = 137
print(respostas)
txt()
#________________11.Teclas de fases________________
"tecla fase 3"
def m_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_m]:
return True
return False
def a_is_down():
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
return True
return False
"__________________________________Game__________________________________"
# -> Pré informações de game
sair = True
sprite = 0
eventos = []
respostas = []
velocidade_de_mov = 15
vermelho_em = "começar"
iniciar = True
instruções = False
cor1 = vermelho
cor2 = branco
inicial.play(-1)
musica = 1
# -> Loop de Game
while sair:
tela.fill(preto)
#________________12.tela inicial game________________
if "esc" in eventos:
instruções = False
iniciar = True
if iniciar:
tela.blit(biblioteca_3,[(dimensao_tela[0]/2)-centro3[2]/2,20])
outros_texto()
if up_is_down():
vermelho_em = "começar"
cor1 = vermelho
cor2 = branco
if down_is_down():
vermelho_em = "instruções"
cor1 = branco
cor2 = vermelho
if vermelho_em == "começar" and "enter" in eventos:
iniciar = False
inicial.stop()
if vermelho_em == "instruções" and "enter" in eventos:
instruções = True
if instruções:
tela.blit(biblioteca_1,[(140)-centro1[2]/2,370])
txt_instruções()
#________________13.O jogo________________
else:
orbitas()
sprite += 1
soundtrack.play(-1)
Informações_texto()
if fase == 0:
phase_1()
elif fase == 1:
phase_2()
elif fase == 2:
phase_3()
elif fase == 3:
phase_4()
elif fase == 4:
phase_5()
elif fase == 5:
phase_6()
elif fase == 6:
phase_7()
elif fase == 7:
phase_8()
elif fase == 8:
phase_9()
elif fase == 9:
phase_10()
#________________14.Eventos________________
#14.1-> Sair
if "sair" in eventos:
sair = False
eventos.clear() #limpeza de eventos
for event in pygame.event.get():
if event.type == pygame.QUIT:
eventos.append("sair")
#14.2-> Teclas de alterar texto
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
eventos.append("espaço")
#14.3-> Teclas do início
if event.key == pygame.K_RETURN:
eventos.append("enter")
if event.key == pygame.K_ESCAPE:
eventos.append("esc")
#14.4-> Teclas Chaves
if event.key == pygame.K_h:
eventos.append("h")
som_teclas()
if event.key == pygame.K_u:
eventos.append("u")
som_teclas()
if m_is_down():
if event.key == pygame.K_a:
eventos.append("ma")
som_teclas()
if a_is_down():
if event.key == pygame.K_m:
eventos.append("ma")
som_teclas()
if event.key == pygame.K_n:
eventos.append("n")
som_teclas()
#14.4-> Teclas de Respostas
if event.key == pygame.K_s:
respostas.append("S")
som_teclas()
if event.key == pygame.K_i:
respostas.append("I")
som_teclas()
if event.key == pygame.K_m:
respostas.append("M")
som_teclas()
if event.key == pygame.K_n:
respostas.append("N")
som_teclas()
if event.key == pygame.K_a:
respostas.append("A")
som_teclas()
if event.key == pygame.K_o:
respostas.append("O")
som_teclas()
if event.key == pygame.K_c:
respostas.append("C")
som_teclas()
if event.key == pygame.K_r:
respostas.append("R")
som_teclas()
if event.key == pygame.K_u:
respostas.append("U")
som_teclas()
if event.key == pygame.K_j:
respostas.append("J")
som_teclas()
if event.key == pygame.K_0:
respostas.append("0")
som_teclas()
if event.key == pygame.K_1:
respostas.append("1")
som_teclas()
if event.key == pygame.K_2:
respostas.append("2")
som_teclas()
if event.key == pygame.K_3:
respostas.append("3")
som_teclas()
if event.key == pygame.K_4:
respostas.append("4")
som_teclas()
if event.key == pygame.K_5:
respostas.append("5")
som_teclas()
if event.key == pygame.K_6:
respostas.append("6")
som_teclas()
if event.key == pygame.K_7:
respostas.append("7")
som_teclas()
if event.key == pygame.K_8:
respostas.append("8")
som_teclas()
if event.key == pygame.K_9:
respostas.append("9")
som_teclas()
if event.key == pygame.K_h:
respostas.append("H")
som_teclas()
#________________15.Movimentação________________
if left_is_down():
posição_x += -velocidade_de_mov
if right_is_down():
posição_x += velocidade_de_mov
if up_is_down():
posição_y += -velocidade_de_mov
if down_is_down():
posição_y += velocidade_de_mov
#________________16.Regras________________
# 16.1-> Não ultrapasse o limite da tela
if limite:
if posição_x + tamanho >= dimensao_tela[0]:
posição_x += -velocidade_de_mov
if posição_x <= 0:
posição_x += velocidade_de_mov
if posição_y + tamanho >= dimensao_tela[1]:
posição_y += -velocidade_de_mov
if posição_y <= 0:
posição_y += velocidade_de_mov
# 16.2-> Se pressionar Q sua forma muda
if q_is_down():
if sprite == quantidade_sprite:
sprite = quantidade_sprite -4
else:
if sprite > quantidade_sprite - 13:
sprite +=-2
elif sprite == quantidade_sprite - 13:
sprite = 0
#________________17.Atual. Dysplay________________
relogio.tick(10)
pygame.display.update()
pygame.quit()
quit()
|
ef8e05fe07b951ec8d95b0c64491616b227eb0a2 | bmanandhar/python-playground | /b.py | 233 | 3.734375 | 4 | n = 100
for i in range(100):
i = i + 2
print(i)
arr = [1,2,3,4,5]
for i in range(len(arr)):
for j in range(5):
print('i is :-', i)
print('j is: ', j)
x = [7,2,4,1,5]
for i in range(len(x) - 1):
for |
e0241ab69dbb1a40c43e0db5fdcd2f0cc545100b | BOURGUITSamuel/NmapScanner_Project | /Scanner.py | 2,154 | 3.71875 | 4 | # coding: utf-8
import sys
import nmap
import re
import time
# Using the nmap port scanner.
scanner = nmap.PortScanner()
# Regular Expression Pattern to recognise IPv4 addresses.
ip_add_pattern = re.compile("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")
# Display the program banner.
print("-------------------")
print("Nmap python scanner")
print("-------------------")
# Ask user to input the ip address he want to scan.
while True:
ip_addr = input("Please enter the IP address you want to scan: ")
if ip_add_pattern.search(ip_addr):
print(f"{ip_addr} is a valid ip address")
type(ip_addr)
break
else:
print("Invalid IP address !")
continue
# Ask user which scan he want to do
while True:
resp = input("""\nPlease enter the type of scan you want to run:
1)SYN ACK Scan
2)UDP Scan
3)Comprehensive Scan \n""")
print(f"You have selected option {resp}")
if resp == '1':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr, '1-1024', '-v -sS')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print(scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
time.sleep(10)
break
elif resp == '2':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr, '1-1024', '-v -sU')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print(scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['udp'].keys())
time.sleep(10)
break
elif resp == '3':
print("Nmap Version: ", scanner.nmap_version())
scanner.scan(ip_addr, '1-1024', '-v -sS -sV -sC -A -O')
print(scanner.scaninfo())
print("Ip Status: ", scanner[ip_addr].state())
print(scanner[ip_addr].all_protocols())
print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
time.sleep(10)
break
elif resp >= '4':
print("Please enter a valid option. Enter 1-3")
continue
|
21791a22f0b353d69cf2f6ce03dff7a488cb2bbc | lazorfuzz/gameofde_rest | /ciphers/benchmark.py | 1,410 | 3.53125 | 4 | from Dictionaries import LanguageTrie, trie_search, dictionarylookup
import time
class Color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def test(sentence, lang, iterations):
'''Tests a dictionary lookup on a sentence using a trie search v.s. a line-by-line lookup.'''
print(Color.BLUE + 'Testing sentence: %r' % sentence + Color.END)
print('%sWord count:%s %d' % (Color.CYAN, Color.END, len(sentence.split())))
print('%sTesting trie_search: %s %d iterations' % (Color.YELLOW, Color.END, iterations))
start = time.time()
for i in range(iterations):
trie_search(sentence, lang)
stop = time.time()
print(Color.GREEN + ' Time elapsed:' + Color.END, stop - start, 'seconds')
print('%sTesting dictionarylookup: %s %d iterations' % (Color.YELLOW, Color.END, iterations))
start = time.time()
for i in range(iterations):
word_arr = sentence.split()
for w in word_arr:
dictionarylookup('en', w)
stop = time.time()
print(Color.GREEN + ' Time elapsed:' + Color.END, stop - start, 'seconds');
print ('-' * 50)
if __name__ == '__main__':
test('the quick brown fox jumps over the lazy red dog.', 'en', 100)
test('the quick brown fox jumps over the lazy red dog. ' * 5, 'en', 100) |
159d935411dd314c544af263dc1edf7e5d9f8238 | ztoolson/Intro-to-Algorithms-and-Data-Structures | /LinkedList.py | 4,457 | 4.3125 | 4 | class List:
"""
Implementation of a Singely Linked List.
"""
def __init__(self):
""" (List) -> NoneType
Initialize the head and tail of the list
"""
self.head = None
self.tail = None
def __str__(self):
""" (List) -> str
"""
result = ''
node_counter = 0
node = self.head
while node != None:
result = 'Node ' + str(node_counter) + ': ' + str(node.data) + '\n'
node = node.next
node_counter += 1
return result
def is_empty(self):
""" (List) -> bool
Checks to see if the head of the list is a reference to none.
"""
return self.head == None
def insert(self, node, data=None):
""" (List, ListNode, Object) -> NoneType
Creates and inserts a new node AFTER an existing node, updating the tail
when inserted at the end.
"""
new_node = ListNode(data, node.next)
node.next = new_node
if self.tail == node:
self.tail = new_node
def insert_end(self, data):
""" (List, Object) -> NoneType
Insert the node at the end of the List.
"""
# Check if the list is empty
if self.tail == None:
new_node = ListNode(data, None)
self.head = self.tail = new_node # The new node is both head and tail
else:
self.insert(self.tail, data)
def insert_beginning(self, data):
""" (List, Object) -> NoneType
Insert Node at the beginning of the List.
"""
new_node = ListNode(data, self.head)
self.head = new_node
def add(self, data):
""" (List, Object) -> NoneType
Simplier name than insert_beginning.
"""
self.insert_beginning(data)
def remove_after(self, node):
""" (List, ListNode) -> NoneType
Remove the node after the specified node.
"""
node.next = node.next.next
if node.next == None:
self.tail = node
def remove_beginning(self):
""" (List) -> NoneType
Remove the first node in the List.
"""
self.head = self.head.next
if self.head == None:
self.tail = None
def length(self):
""" (List) -> int
Return the number of items in the list.
"""
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def find_first(self, data):
""" (List, Object) -> ListNode
Finds the first occurance of the specified data in the list and returns the node.
If data is not in the list, will return None.
"""
find_first_func(lambda x: x == data)
def find_first_func(self, func):
""" (List, Function) -> Node
User supplies a predicate (function returning a boolean) and returns the first
node for which it returns True.
>>> node = list.find_first_func(lambda x: 2*x + 7 == 19)
"""
node = list.head
while node != None:
if func(node.data):
return node
node = node.next
class ListNode:
"""
The basic building block for a linked list data structure.
"""
def __init__(self, new_data, new_next = None):
""" (Node, Object, ListNode) -> NoneType
Initialize the Node with the data. Assumes the Node doesn't point to
any Node to start.
Nodes should only point to another ListNone, or to None if there isn't one.
"""
self.data = new_data
self.next = new_next
def get_data(self):
""" (ListNode) -> Object
Return the data in the Node.
"""
return self.data
def get_next(self):
""" (ListNode) -> ListNode
Return the Node which the current node points to. This is the next node in the list.
"""
return self.next
def set_data(self, new_data):
""" (ListNode, Object) -> NoneType
Set the data inside the Node
"""
self.data = new_data
def set_next(self, new_next):
""" (ListNode, Object) -> NoneType
Set a Node for which the current Node will now point to.
"""
self.next = new_next
|
17911c3e3c9f130caeeddf9dc571068a25d7bf4b | ArnaudParan/stage_scientifique | /gestion_doonees/operations_vect.py | 1,890 | 3.5625 | 4 | #!/usr/bin/python3.4
#-*-coding:utf-8-*
from donnees import *
import math as Math
##
# @brief crée la moyenne d'un tableau
# @param tab le tableau qu'on moyenne
# @return la moyenne
def moy (tab) :
taille_tab = len (tab)
moyenne = 0.
for elem in tab :
moyenne += float(elem) / float(taille_tab)
return moyenne
def moy_par_point(vals_point_simplex) :
for point in range(len (vals_point_simplex)) :
vals_point_simplex[point] = moy(vals_point_simplex[point])
##
# @brief multiplie un vecteur par un scalaire
# @param vect le vecteur
# @param scal le scalaire
# @return le produit
def mult (scal, vect) :
produit = []
for i in range (len (vect)) :
produit.append (vect[i] * scal)
return produit
def somme (vect1, vect2) :
somme = vect1
for cpt in range (len(somme)) :
somme[cpt] += vect2[cpt]
return somme
##
# @brief additionne trois vecteurs
# @param x1 le premier vecteur
# @param x2 le deuxième vecteur
# @param x3 le troisième vecteur
# @return la somme
#TODO retirer la désinformation
def add (vect1 ,vect2 ,vect3) :
somme = []
#envoie une evectception si les vecteurs n'ont pas la meme taille
if len (vect1) != len (vect2) or len (vect2) != len (vect3) or len (vect3) != len (vect1) :
raise "trois vecteurs de taille différente additionnés"
for i in range (len (vect1)) :
somme.append (vect1[i] + vect2[i] + vect3[i])
return somme
##
# @brief la norme infinie d'un vecteur
# @param x le vecteur
# @return la norme
def norminf (x) :
sup = max (x)
inf = min (x)
return max ([abs (sup), abs (inf)])
def sommeScalVect(l,x):
somme=[]
for i in range(len(x)):
somme.append(x[i]+l)
return somme
def variance(serieStat) :
moyenne = moy(serieStat)
distanceTot = 0.
for valExp in serieStat :
distanceTot += (valExp - moyenne)**2
variance = Math.sqrt(distanceTot/len(serieStat))
return variance
|
177f4d54814f1f899d2ea119454b0d692dfff382 | AphelionGroup/Examples | /SampleBots/WeatherBot/getWeather.py | 2,199 | 3.578125 | 4 | import argparse
from flask import Flask
from flask_restful import Resource, Api, reqparse
import json
import urllib2
class getWeather(Resource):
def forecast(self, city):
answer = None
# calls the weather API and loads the response
res = urllib2.urlopen(weather_today + city)
data = json.load(res)
# gets the temperature information
temp = data['main']['temp']
# converts the returned temperature in Celsius
c = temp - 273.15
# and converts the returned temperature in fahrenheit
f = 1.8 * (temp - 273) + 32
# compose the answer we want to return to the user
answer = str(
data['weather'][0]['description']).capitalize() + '. Current temperature is %.2fC' % c + '/%.2fF' % f
return answer
# This recieves requests that use the POST method.
def post(self):
# Uses the request parser to extract what we want from the JSON.
args = parser.parse_args()
variables = args['memoryVariables']
city = variables[0]['value']
# calls the getForecast function
response = self.forecast(city)
# Captures the first variable and it's currentValue.
return {"text": response}, 200
if __name__ == "__main__":
PARSER = argparse.ArgumentParser(description='Weather bot launcher')
PARSER.add_argument('apikey', help='openweathermap API key', type=str,
default='')
PARSER.add_argument('--port', help='port to serve on', type=int,
default=5000)
BUILD_ARGS = PARSER.parse_args()
# endpoint to a weather API
weather_today = 'http://api.openweathermap.org/data/2.5/weather?appid={}&q='.format(BUILD_ARGS.apikey)
app = Flask(__name__)
api = Api(app)
api.add_resource(getWeather, '/getWeather')
# Use RequestParser to pull out the intentName, memoryVariables and chatResult.
parser = reqparse.RequestParser()
parser.add_argument('intentName')
parser.add_argument('memoryVariables', type=dict, action='append')
parser.add_argument('chatResult', type=dict)
app.run(host='0.0.0.0', debug=True, port=BUILD_ARGS.port) |
b13aa117b4f2bd0f0a04ce3b04ff9950c239a7f6 | wenjie711/Leetcode | /python/021_merge_2_sorted_lists.py | 909 | 3.953125 | 4 | #!/usr/bin/env python
#coding: utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def mergeTwoLists(self, l1, l2):
l = ListNode(0)
p = l
while l1 and l2:
if(l1.val < l2.val):
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
if l2:
p.next = l2
return l.next
s = Solution()
l1 = ListNode(1)
l2 = ListNode(3)
l3 = ListNode(4)
l4 = ListNode(6)
m1 = ListNode(2)
m2 = ListNode(5)
m1.next = m2
l1.next = l2
l2.next = l3
l3.next = l4
p = s.mergeTwoLists(None,l1)
while(p != None):
print p.val
p = p.next
|
9cd76f9d4d60443cefc3cf495b67cade9ee06fba | wenjie711/Leetcode | /python/070_climbing_stairs.py | 538 | 3.9375 | 4 | #!/usr/bin/env python
#coding: utf-8
class Solution:
# @param {integer} n
# @return {integer}
def climbStairs(self, n):
c = n / 2
r = 0
for i in range(0, c + 1):
j = (n - i * 2) + i
r += self.C(i,j)
return r
def C(self, i, j):
return self.factorial(j) / self.factorial(i) / self.factorial(j - i)
def factorial(self, n):
if(n == 1 or n == 0):
return 1
return n * self.factorial(n - 1)
s = Solution()
print s.climbStairs(10)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.