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 |
|---|---|---|---|---|---|---|
2234fd813cf426e6d42c3ad7f61a8ab1a9a0ef45 | losskatsu/Programmers | /practice/sort/K번째수.py | 382 | 3.5 | 4 | # 100 점
def solution(array, commands):
answer = []
n = len(commands)
for i in commands:
tmp_array = []
init = i[0]-1
end = i[1]
n_ch = i[2]-1
for j in range(init, end):
tmp_array.append(array[j])
tmp_array.sort()
print(tmp_array)
answer.append(tmp_array[n_ch])
return answer
|
654910c7c7fd36f1a9db54f53a9a57a1ee6efc93 | alggalin/PythonChess | /chess/board.py | 3,753 | 3.859375 | 4 | import pygame
from .constants import BLACK, BROWN, ROWS, SQUARE_SIZE, TAN, ROWS, COLS, WHITE
from .piece import Piece
from chess import piece
class Board:
def __init__(self):
self.board = []
self.selected_piece = None
self.create_board()
def make_queen(self, piece):
if piece.color == WHITE:
piece.piece_type = "WQ"
else:
piece.piece_type = "BQ"
def get_piece(self, row, col):
if 0 <= col <= 7 and 0 <= row <= 7:
return self.board[row][col]
return None
def remove(self, row, col):
piece = self.board[row][col]
if piece.piece_type == "BK" or piece.piece_type == "WK":
print("CheckMate!")
self.board[row][col] = 0
def move(self, piece, row, col):
if piece.color == WHITE and row == 0 and piece.piece_type == "WP":
self.make_queen(piece)
elif piece.color == BLACK and row == 7 and piece.piece_type == "BP":
self.make_queen(piece)
temp = self.board[row][col]
self.board[row][col] = self.board[piece.row][piece.col]
self.board[piece.row][piece.col] = temp
self.board[row][col].move(row, col)
def draw_board(self, win):
win.fill(BROWN)
# loop used to draw the squares for the pieces
for row in range(ROWS):
for col in range(row % 2, ROWS, 2):
pygame.draw.rect(win, TAN, (row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def draw_pieces(self, win):
# need to go through the list and place each piece according to it's actual location
# have to look at the piece that's stored there and use position to know where to draw it
for col in range(COLS):
for row in range(ROWS):
board_position = self.board[col][row]
if board_position != 0: # there is a piece here that should be drawn
board_position.draw(win)
# function to fill up the board with appropriate pieces in their specific locations
def create_board(self):
for row in range(ROWS):
self.board.append([])
for col in range(COLS):
if row == 0 and (col == 0 or col == 7):
self.board[row].append(Piece(row, col, BLACK, "BR"))
elif row == 0 and (col == 1 or col == 6):
self.board[row].append(Piece(row, col, BLACK, "BN"))
elif row == 0 and (col == 2 or col == 5):
self.board[row].append(Piece(row, col, BLACK, "BB"))
elif row == 0 and col == 3:
self.board[row].append(Piece(row, col, BLACK, "BQ"))
elif row == 0 and col == 4:
self.board[row].append(Piece(row, col, BLACK, "BK"))
elif row == 1:
self.board[row].append(Piece(row, col, BLACK, "BP"))
elif row == 7 and (col == 0 or col == 7):
self.board[row].append(Piece(row, col, WHITE, "WR"))
elif row == 7 and (col == 1 or col == 6):
self.board[row].append(Piece(row, col, WHITE, "WN"))
elif row == 7 and (col == 2 or col == 5):
self.board[row].append(Piece(row, col, WHITE, "WB"))
elif row == 7 and col == 3:
self.board[row].append(Piece(row, col, WHITE, "WQ"))
elif row == 7 and col == 4:
self.board[row].append(Piece(row, col, WHITE, "WK"))
elif row == 6:
self.board[row].append(Piece(row, col, WHITE, "WP"))
else:
self.board[row].append(0) |
d1122b050c0cfc85ff9d7d4dcbc40c2c3096f1be | Moeozzy/Minesweeper | /Mine.py | 18,116 | 3.578125 | 4 | #Här kallar jag på olika moduler men även en python fil vilket inehåller en klass.
from tkinter import *
from tkinter import messagebox
import sys
import os
from operator import attrgetter
from Mine_Class import *
import time
import random
#Detta är fönstret som öppnas vid start av programet, I detta tkinter fönster
#Så kan man starta spelet, se highscore, ta upp instruktionerna och ställa in spelplanen.
#Fönstret består av knappar, två skalor och samt en input för användaren.
def mainmenu(main_screen):
Button(main_screen, bg = "BLACK", fg = "WHITE", text = "Instructions:", command = lambda: view_instructions()).pack()
Label(main_screen, bg = "BLACK", fg = "WHITE", text = "Name:").pack()
nameinput = Entry(main_screen)
nameinput.pack()
Label(main_screen, bg = "BLACK", fg = "WHITE", text = "Number of rows:").pack()
row = Scale(main_screen, bg = "BLACK", fg = "WHITE", from_= 6, to = 32, orient = HORIZONTAL)
row.pack()
Label(main_screen, bg = "BLACK", fg = "WHITE", text = "Number of columns:").pack()
col = Scale(main_screen, bg = "BLACK", fg = "WHITE", from_= 6, to = 32, orient = HORIZONTAL)
col.pack()
Label(main_screen, bg = "BLACK", fg = "WHITE", text = " Procentage of Mines:").pack()
mines = Scale(main_screen, bg = "BLACK", fg = "WHITE", from_= 15, to = 70, orient = HORIZONTAL)
mines.pack()
start_button = Button(main_screen, text = "Play", width = 25, fg = "GREEN", bg = "BLACK", command = lambda: Game_screen(row, col, mines, nameinput, main_screen))
start_button.pack()
Button(main_screen, text = "Exit", width = 25, fg = "RED", bg = "BLACK", command = main_screen.destroy).pack()
Button(main_screen, text = "Highscores", width = 25, fg = "GOLD", bg = "BLACK", command = lambda: ShowHighscores()).pack()
main_screen.config(bg = "BLACK")
#Denna funktion körs vid klick av "Instructions". Då öppnas en ny tkinter fönster
#Som användaren kan använda för att läsa om hur man spelar. Vid stänging av fönstret
#Så försvinner den och mainmenu kan användas
def view_instructions():
instructions = Toplevel()
instructions.title("Instructions")
message = Text(instructions)
message.insert(INSERT, """\t*********** INSTRUCTIONS ***********
\tHow to win:
- By revealing all squares without a mine or...
- "flagging" all squares with mines.
\tLeftclick:
- Opens selected square.
- * = Mine, you revealed a mine thus lost the game.
- 1-8 = Amount of mines that are adjacent to a square.
- Empty = No mines are adjacent to this square.
All adjacent squares without mines are automatically revealed.
\tRightclick:
- You can flag squares you suspect are mines.
- You can only win by flagging mines and only mines.
\tChoose dimensions:
- You can select the amount of rows and columns.
Remember the bigger the board the harder it is.
\tTip:
- Use the numbers to determine where you know a bomb is.
\t*********** GOOD LUCK ***********""")
message.config(bg = "BLACK", fg = "WHITE")
message.pack()
#Den här funktionen visar då topplistan vid click av knappen "Highscores".
#Det den gör också är att den läser in topplistan genom en for-lopp
#Detta är för att göra det lättare att ordna samt numrera topplistan.
#Här använder jag mig även av Typerror, vilket är en felhantering om ingen är med i topplistan.
#Då sskriver den bara ut texten "No highscores made yet."
def ShowHighscores():
Highscore_list = read_file()
highscore = Toplevel()
highscore.title("Highscores")
message = Text(highscore)
try:
for i in range (len(Highscore_list)):
message.insert(INSERT, str(i+1) + ". " + str(Highscore_list[i]) + "\n")
highscore.config(bg = "BLACK")
message.config(bg = "BLACK", fg = "WHITE")
message.pack()
except TypeError:
message.insert(INSERT, "No Highscores made yet.")
highscore.config(bg = "BLACK")
message.config(bg = "BLACK", fg = "WHITE")
message.pack()
#Den här funktionen används för att sortera listan via tre olika attribut (snabbast tid, störst plan och antalet minor)
#Det attregetter gör är att den frågar om attributen från operatorn och om det är mer än 1 så
#Kommer den att göra det till en tuple.
def sort_list(Highscore_list, attribute):
for key, reverse in reversed(attribute):
Highscore_list.sort(key = attrgetter(key), reverse = reverse)
return Highscore_list
#Den här funktionen läser av filen för topplistan
#Det den använder är av en try och except för felhantering.
#Funktionen börjar med att först kolla om fillen ligger i samma sökväg som programmet om inte så
#Kommer except köras och då skapas en ny fil. Om filen finns så läses den genom en for lopp.
#Samt så definereas "Keys" till sort_list
def read_file():
Highscore_list = []
try:
with open(os.path.join(sys.path[0], "Mine score.txt"), "r") as file:
text = file.readlines()
for row in text:
name, size, mines, time = row.split(" ")
Highscore_list.append(Win(name, size, mines, time))
sort_list(Highscore_list, (("size", True), ("mines", True), ("time", False)))
return Highscore_list
except IOError:
file = open(os.path.join(sys.path[0], "Mine score.txt"), "w")
#Här sparas filen och så öppnas den även genom os modulen. Så sparas även filen med attributen namn, storlek och tid.
#Här används även tidsfunktionen för att spara tiden.
def save_file(name, time_stop, time_start, row, col, mines):
with open(os.path.join(sys.path[0], "Mine score.txt"), "a") as file:
file.write(str(name) + " " + str(row*col) + " " + str(mines) + " " + str(round(time_stop-time_start, 2)) + "\n")
file.close()
#Här är felhanteringen för användarens input. Du får alltså bara använda dig av bokstäver (isalpha)
#Samt så får du bara ha ett namn med max 15 bokstäver och minst 1.
#Vid fel inmatning så körs en messagebox och då tas tillbacks till mainmenu.
def check_name(name, main_screen):
if len(name) >= 15:
messagebox.showerror("Error:", "Your name cant exceed 15 characters, try again.")
main_screen.destroy()
main()
if not name.isalpha():
messagebox.showerror("Error:", "Your name can only contain letters and atleast one, try again.")
main_screen.destroy()
main()
#Det här är funktionen för spel fönstret och är det tkinter fönstret som öppnas vid click av "Play"
#Den tar emot infromation såsom antal rader, kol och namn som användaren har uppgett.
#Lambda används för att köra en funktion i en annan funktion och commando är det som händer vid klick av knappen
#Jag gör spelplanen till en lista som sedan fylls med knappar via en for-loop
#Kallar även på funktionen "Squares" som är algorithemn för hur spelpölanen röjs.
#Buttons är de rutor man trycker på som sedan även kör vänster och högerclick.
#Field är en lista för vart innehållet av knapparna befinner sig. Fylls på med nya listor motsvarande antalet rader
#Den stänger även huvudmenyn fönstret innan den öppnar sig själv.
#Denna funktion inehåller även en timer som används för att sortera topplistan.
def Game_screen(row, col, mines, nameinput, main_screen):
row = row.get()
col = col.get()
name = nameinput.get()
mines = (mines.get()/100)
check_name(name, main_screen)
main_screen.destroy()
Game_screen = Tk()
Game_screen.title("Mine")
Game_screen.config(bg="BLACK")
Button(Game_screen, fg = "WHITE", bg = "BLACK", text="Mainmenu", width = 25, command=lambda:[Game_screen.destroy(),main()]).grid(row=row-1, column=col+1)
field = []
for x in range(row):
field.append([])
for y in range(col):
field[x].append(0)
Squares(x, y, row, col, mines, field)
buttons = []
for x in range(row):
buttons.append([])
for y in range(col):
button = Button(Game_screen, width = 2, height = 1, bg = "saddlebrown", disabledforeground = "BLACK")
button.grid(row=x, column=y, sticky=N+W+S+E)
button.bind("<Button-1>", lambda i, x=x, y=y: left_click(x, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start))
button.bind("<Button-3>", lambda j, x=x, y=y: right_click(x, y, col, row, mines, buttons, field, Game_screen, mines_flagged, flagged_squares, name, minutes, seconds, time_start))
buttons[x].append(button)
minutes = 0
seconds = 0
mines_flagged = []
flagged_squares = []
time_start = time.time()
check_win(Game_screen, row, col, mines, x, y, field, buttons, mines_flagged, flagged_squares, name, minutes, seconds, time_start)
#Verktyg för att se vart minorna befinner sig.
print(field)
#Denna funktion används för att nummrerar rutor som angränsar minor.
#Här bestäms även procentandelen minor
#Här finns även algoritmen som numrerar rutorna via antalet angränsande minor
def Squares(x, y, row, col, mines, field):
for i in range(int(mines*row*col)):
x = random.randint(0, row-1)
y = random.randint(0, col-1)
while field[x][y] == -1:
x = random.randint(0, row-1)
y = random.randint(0, col-1)
field[x][y] = -1
if x != 0 and y != 0 and field[x-1][y-1] != -1:
field[x-1][y-1] = int(field[x-1][y-1]) + 1
if x != 0 and field[x-1][y] != -1:
field[x-1][y] = int(field[x-1][y]) + 1
if x != 0 and y != col-1 and field[x-1][y+1] != -1:
field[x-1][y+1] = int(field[x-1][y+1]) + 1
if y != 0 and field[x][y-1] != -1:
field[x][y-1] = int(field[x][y-1]) + 1
if y != col-1 and field[x][y+1] != -1:
field[x][y+1] = int(field[x][y+1]) + 1
if y != 0 and x != row-1 and field[x+1][y-1] != -1:
field[x+1][y-1] = int(field[x+1][y-1]) + 1
if x != row-1 and field[x+1][y] != -1:
field[x+1][y] = int(field[x+1][y]) + 1
if x != row-1 and y != col-1 and field[x+1][y+1] != -1:
field[x+1][y+1] = int(field[x+1][y+1]) + 1
#left_click används för att köras när användaren vänsterklickar på en ruta.
#Den kollar även om rutan är flaggade, då kan inte användaren väsnterklicka utan att ta bort flaggan.
#Om rutan innehåller en siffra öppnas den och visar siffran.
#Om rutan innehåller en nolla så kommer funktionen autoclick köras för att öppna angränsade rutor fram tills en mina angränsar
#Om rutan innehåller en mina så öppnas alla rutor, visar vart minorna är och en messagebox körs för att säga att spelet är slut
#Samt även visar antalet minor du har flaggat av totala minorna.
#Funktionen ersätter även -1 med * för att indikera en mina.
#Vid förlust så tas användaren tillbaks till mainmenu
def left_click(x, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start):
if buttons[x][y]["text"] != "F":
if field[x][y] != 0:
buttons[x][y].config(bg = "#AF6500", text=field[x][y], state=DISABLED, relief=SUNKEN)
if field[x][y] == 0:
auto_click(x, y, col , row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
buttons[x][y].config(bg = "#AF6500", state=DISABLED, relief=SUNKEN)
check_win(Game_screen, row, col, mines, x, y, field, buttons, mines_flagged, flagged_squares, name, minutes, seconds, time_start)
if field[x][y] == -1:
for x in range(row):
for y in range(col ):
if field[x][y] != 0:
buttons[x][y].config(bg = "#AF6500", relief=SUNKEN, state=DISABLED, text=field[x][y])
elif field[x][y] == 0:
buttons[x][y].config(bg = "#AF6500", relief=SUNKEN, text=" ")
if field[x][y] == -1:
buttons[x][y].config(text="*", bg="red", relief=SUNKEN)
messagebox.showerror("Game over", "You sweept: " + str(len(mines_flagged)) + " bombs, out of " + str(int(mines*row*col)) + " total. Better luck next time.")
Game_screen.destroy()
main()
#Denna funktion används för att flagga rutorna genom användarens högerclick.
#Om rutan inte har en flagga så läggs en flagga till vid högerclick.
#Om rutan har redan en flagga tas den bort vid högerclick.
#Antalet flaggade minor av alla minor sparas även i variabler "mines_flagged" och "flagged_squares" för att jämföra och används som ett verktyg
#Detta görs genom en räknare som tar bort eller lägger till ett index
#Efter varje högerclick så körs även check_win för att kolla om villkoren är uppfyllda.
def right_click(x, y, col, row, mines, buttons, field, Game_screen, mines_flagged, flagged_squares, name, minutes, seconds, time_start):
if buttons[x][y]["text"] != "F" and buttons[x][y]["state"] != "disabled":
if field[x][y] == -1:
mines_flagged.append(1)
elif field[x][y] != -1:
flagged_squares.append(1)
buttons[x][y].config(text = "F", command = lambda x=x, y=y: left_click(x, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start))
elif buttons[x][y]["text"] == "F":
if field[x][y] == -1:
mines_flagged.remove(1)
elif field[x][y] != -1:
flagged_squares.remove(1)
buttons[x][y].config(text = " ", command = lambda x=x, y=y: left_click(x, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start))
check_win(Game_screen, row, col, mines, x, y, field, buttons, mines_flagged, flagged_squares, name, minutes, seconds, time_start)
#Verktyg för att visa antalet flaggade minor av alla.
#print("mines: " + str(len(mines_flagged)) + " None mine: " + str(len(flagged_squares)))
#Denna funktion körs när spelet behöver öppna angränsade minor automatiskt, när t.ex. man öppnar en tom ruta
#Detta görs genom rekursion för att kalla på sig själv tills minor angränsar.
def auto_click(x, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start):
if buttons[x][y]["state"] == "disabled":
return
else:
buttons[x][y].config(state=DISABLED, relief=SUNKEN)
if field[x][y] == 0:
if x != 0 and y != 0:
left_click(x-1, y-1, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if x != 0:
left_click(x-1, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if x != 0 and y != col-1:
left_click(x-1, y+1, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if y != 0:
left_click(x, y-1, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if y != col-1:
left_click(x, y+1, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if x != row-1 and y != 0:
left_click(x+1, y-1, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if x != row-1:
left_click(x+1, y, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
if x != row-1 and y != col-1:
left_click(x+1, y+1, col, row, mines, buttons, field, mines_flagged, flagged_squares, Game_screen, name, minutes, seconds, time_start)
#Check_win ansvarar för att kolla im användaren har uppfyllt villkoren för en vinst. Detta körs efter varje knappklickning.
#Börjar med att sätta vinst till sant och kollar om vilkoren är uppfyllda
#Om den inte är uppfylld genom att flagga eller öppna alla rutor utan minor. Så returnerar den false
#Men om det är ippfylld retunerar den true.
#Om true returneras så kommer timern att stoppas och så öppnas alla rutor för att visa vart minorna befinner sig.
#Siffrorna färgas även här-
#save_file körs för att spara vinsten.
#En messsagebox kommer sedan att öppnas för att visa vinsten med info såsom namn, storlek och tid.
#Fönstret stängs och användaren tas till mainmenu
def check_win(Game_screen, row, col, mines, x, y, field, buttons, mines_flagged, flagged_squares, name, minutes, seconds, time_start):
win = True
for x in range(row):
for y in range(col):
if field[x][y] != -1 and buttons[x][y]["relief"] != "sunken":
win = False
if int(len(mines_flagged)) == int(mines*row*col) and int(len(flagged_squares)) == 0:
win = True
if win:
time_stop = time.time()
#Verktyg för att se tiden i terminalen.
#print(time_stop-time_start)
for x in range(row):
for y in range(col):
if field[x][y] == 0:
buttons[x][y].config(state=DISABLED, relief=SUNKEN, text=" ")
elif field[x][y] == -1:
buttons[x][y].config(state=DISABLED, relief=SUNKEN, bg="GREEN", text="F")
else:
buttons[x][y].config(state=DISABLED, relief=SUNKEN, text=field[x][y])
save_file(name, time_stop, time_start, row, col, mines)
messagebox.showinfo("You Win! ", str(name) + " You sweept all mines in: " + str(round(time_stop-time_start, 2)) + " seconds.")
Game_screen.destroy()
main()
#Main funktionen startar mainmenu fönstret.
def main():
main_screen = Tk()
main_screen.title("Mine")
mainmenu(main_screen)
main_screen.mainloop()
main()
|
9290690787a3f69a48c29ff85d9c8b29a5f6caee | ehjalmar/AoC2019 | /day3part1.py | 1,779 | 3.84375 | 4 | class Coord:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
self.distance = abs(self.x) + abs(self.y)
def __hash__(self):
return hash((("x" + str(self.x)), ("y" + str(self.y)), self.distance))
def __eq__(self, other):
return self.x, self.y, self.distance == other.x, other.y, other.distance
def __ne__(self, other):
return not self.__eq__(other)
def GetCoordsFromPath(path):
coords = []
for instruction in path:
direction = instruction[:1]
distance = int(instruction[1:])
currentX = 0
currentY = 0
if len(coords) > 0:
currentCoord = coords[-1]
currentX = currentCoord.x
currentY = currentCoord.y
for foo in range(distance):
newPos = foo + 1
if direction == "R":
x = currentX + newPos
coords.append(Coord(x, currentY))
elif direction == "L":
x = currentX - newPos
coords.append(Coord(x, currentY))
elif direction == "U":
y = currentY + newPos
coords.append(Coord(currentX, y))
elif direction == "D":
y = currentY - newPos
coords.append(Coord(currentX, y))
return coords
file = open('day3.txt', 'r')
wireOnePath = file.readline().split(",")
wireTwoPath = file.readline().split(",")
file.close()
wireOneCoords = GetCoordsFromPath(wireOnePath)
wireTwoCoords = GetCoordsFromPath(wireTwoPath)
crossings = set(wireOneCoords).intersection(wireTwoCoords)
sortedCrossings = sorted(crossings, key=lambda x: x.distance, reverse=True)
for crossing in sortedCrossings:
print(crossing.distance) |
c55b86b1ab2607740a1995eac41953caebb746f6 | Sibgathulla/LearnPython | /Encryption/EncryptionSHA256.py | 1,139 | 3.5 | 4 | import hashlib
def GetChar(idx):
return chr(idx)
def StringToHash256(input):
result = hashlib.sha256(input.encode())
return result.hexdigest()
def GenerateData(len):
print('GenerateData of length.. '+str(len))
indx=1
while(indx<=len):
for i in range(97,97+26):
j=1
result=''
while(j<=indx):
result=result+GetChar(i)
j=j+1
print(result)
indx=indx+1
def GenerateDataRec(position):
result=GetChar(position)
print(result)
if(position<97+26-1):
return GenerateDataRec(position+1)
def main():
print('this is test application..')
# for i in range(97,97+5):
# input1=GetChar(i)
# for idx in range(97, 97 + 26):
# input=GetChar(idx)
# print(input1+input)
# output=StringToHash256(input)
# print(input + ' '+output)
# i=1
# while(i<=10):
# print(i)
# i=i+1
# i=1
# len=3
# while(i<=len):
# GenerateData(i)
# i=i+1
# GenerateData(3)
GenerateDataRec(97)
main() |
56a38332bec2e02606c3dceaa29ecade8bcdc7a0 | prakhar21/Learning-Data-Structures-from-Scratch | /stack/twostacks_onearray.py | 1,679 | 3.90625 | 4 | class Stack:
def __init__(self, size):
self.lst_stack = [None]*size
self.top1=-1
self.top2=size
def check_overflow(self, stack):
if stack==1:
if self.top1==self.top2-1:
return True
else: return False
else:
if self.top2==self.top1+1:
return True
else: return False
def push1(self, value):
overflow = self.check_overflow(1)
if not overflow:
self.top1=self.top1+1
self.lst_stack[self.top1]=value
else:
print ("Overflow for Stack 1")
exit()
def push2(self, value):
overflow = self.check_overflow(2)
if not overflow:
self.top2 = self.top2-1
self.lst_stack[self.top2]=value
else:
print ("Overflow for Stack 2")
exit()
def pop1(self):
if self.top1==-1:
print ("Underflow for Stack 1")
exit()
self.lst_stack[self.top1]=None
self.top1=self.top1-1
def pop2(self):
if self.top2==size-1:
print ("Underflow for Stack 2")
exit()
self.lst_stack[self.top2]=None
self.top2=self.top2+1
def printStack(self):
return self.lst_stack
if __name__=="__main__":
size=6
stack = Stack(size)
stack.push1(1)
stack.pop1()
stack.push2(5)
stack.push2(3)
stack.push2(2)
stack.pop2()
stack.push1(10)
stack.push1(14)
stack.push1(15)
stack.push1(17)
# stack.push1(12) // overflow
print (stack.printStack())
|
dcbc049a883fe018e38b7a55b4ac461da73668e3 | prakhar21/Learning-Data-Structures-from-Scratch | /deque/deque_using_linkedlist.py | 2,071 | 3.890625 | 4 | class Node:
def __init__(self, data=None, prev=None, next=None):
self.val = data
self.next = next
self.prev = prev
class Deque(Node):
def __init__(self):
self.head = None
self.size = 0
self.rear = None
def insertFront(self, val):
tmp = Node(data=val)
tmp.next = self.head
tmp.prev = None
if self.head is not None:
self.head.prev = tmp
self.head = tmp
else:
self.rear = tmp
self.head = tmp
self.size += 1
def getFront(self):
return self.head.val
def deleteFront(self):
tmp = self.head.val
self.head = self.head.next
self.head.prev = None
del tmp
def insertRear(self, val):
tmp = Node(data=val)
tmp.next = None
if self.rear is not None:
self.rear.next = tmp
tmp.prev = self.rear
self.rear = tmp
else:
tmp.prev = self.rear
self.rear = tmp
self.size += 1
def deleteRear(self):
tmp = self.rear.val
self.rear = self.rear.prev
self.rear.next = None
del tmp
def getRear(self):
return self.rear.val
def getSize(self):
return self.size
def traverse(self):
tmp = self.head
while tmp!=None:
print (tmp.val)
tmp = tmp.next
deque = Deque()
deque.insertFront(1)
deque.insertFront(2)
deque.insertFront(3)
deque.insertFront(4)
print (deque.traverse())
print ()
print ('Front - ' + str(deque.getFront()))
print ('Size - ' + str(deque.getSize()))
print ('Last - ' + str(deque.getRear()))
deque.insertRear(10)
print ()
print (deque.traverse())
print ()
print ('Last - ' + str(deque.getRear()))
print ('Front - ' + str(deque.getFront()))
print ()
deque.deleteRear()
deque.deleteFront()
print (deque.traverse())
print ()
print ('Last - ' + str(deque.getRear()))
print ('Front - ' + str(deque.getFront()))
|
4956212c52cce9d6b97d6ba588052161c03b239a | prakhar21/Learning-Data-Structures-from-Scratch | /tree/height_of_tree.py | 848 | 3.984375 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert(self, val):
if self.data:
if val < self.data:
if self.left is not None:
self.left.insert(val)
else:
self.left = Node(val)
else:
if self.right is not None:
self.right.insert(val)
else:
self.right = Node(val)
else:
self.data = data
def height(root):
if root!=None:
return max(height(root.left), height(root.right))+1
else: return 0
root = Node(10)
root.insert(8)
root.insert(9)
root.insert(4)
root.insert(3)
root.insert(11)
root.insert(12)
root.insert(13)
root.insert(14)
print (height(root))
|
1de568d0906cbb3b8de4541012425fc00839d391 | prakhar21/Learning-Data-Structures-from-Scratch | /tree/left_view_of_tree.py | 1,154 | 3.9375 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert(self, val):
if self.data:
if val < self.data:
if self.left is not None:
self.left.insert(val)
else:
self.left = Node(val)
else:
if self.right is not None:
self.right.insert(val)
else:
self.right = Node(val)
else:
self.data = data
traversedlevel = 0
def left_most(root, level=1):
global traversedlevel
if root == None: return
if traversedlevel < level:
print (root.data)
# print ("----"+str(maxlevel)+"----"+str(level)+"----")
traversedlevel = level
left_most(root.left, level+1)
left_most(root.right, level+1)
# 10
# / \
# 8 11
# / \ \
# 4 9 12
# \
# 13
root = Node(10)
root.insert(8)
root.insert(9)
root.insert(4)
root.insert(11)
root.insert(12)
root.insert(13)
print (left_most(root))
|
720cb12baf17510689f3818b15e21ad9745bd7ad | prakhar21/Learning-Data-Structures-from-Scratch | /misc/distince_element_in_allwindow_sizek.py | 657 | 3.515625 | 4 | def count_distinct(sub_list):
tmp_cnt = {}
for element in sub_list:
if element in tmp_cnt:
tmp_cnt.pop(element)
else:
tmp_cnt[element] = True
return len(tmp_cnt.keys())
def create_window(data, k):
windows = []
for idx in range(len(data)):
tmp = data[idx:idx+k]
if len(tmp)==k:
windows.append(tmp)
return windows
if __name__ == '__main__':
results = []
data = [1,2,1,3,4,2,3,2]
k = 3
windows = create_window(data, k)
for window in windows:
print ('Window: ' , window)
print ('Distinct: ', count_distinct(window))
|
2373663e0971d644f789b6c688616d3e5c2fff58 | sopoour/robotics | /LEGO Robot/sokoban.py | 2,029 | 3.953125 | 4 | from collections import deque
def main(graph, robotPos, canPos, canGoal):
path = planner(graph, canPos[0], canGoal[0])
robotGoTo = robotPathToCan(graph, path, robotPos[0])
robotPos[0] = path[len(path)-2]
print("Robot pos: ", robotPos)
finalPath = robotGoTo + path + robotPos
if path:
print("The path is: ", finalPath)
else:
print('no path found')
def planner(graph, start, goal):
if start == goal:
return [start]
visited = {start}
queue = deque([(start, [])])
while queue:
current, path = queue.popleft()
visited.add(current)
for neighbour in graph[current]:
print("neighbour: ",neighbour)
#if(checkIfValidMove(neighbour)):
if neighbour != canPos[0] and neighbour != canPos[1]:
if neighbour == goal:
canPos[0] = goal
return path + [current, neighbour]
if neighbour in visited:
continue
queue.append((neighbour, path + [current]))
visited.add(neighbour)
return None #No path found
def robotPathToCan(graph, path, robotPos):
if(path[0] - path[1]) == 4:
robotGoTo = planner(graph, robotPos, path[0] + 4)
elif(path[0] - path[1] == -4):
robotGoTo = planner(graph, robotPos, path[0] - 4)
elif(path[0] - path[1] == 1):
robotGoTo = planner(graph, robotPos, path[0] + 1)
elif(path[0] - path[1] == -1):
robotGoTo = planner(graph, robotPos, path[0] -1)
return robotGoTo
if __name__ == '__main__':
graph = {
0: [1, 4],
1: [0, 2, 5],
2: [1, 3, 6],
3: [2, 7],
4: [0, 5, 8],
5: [1, 4, 6, 9],
6: [2, 5, 7, 10],
7: [3, 6, 11],
8: [4, 9, 12],
9: [5, 8, 10, 13],
10: [6, 9, 11, 14],
11: [7, 10, 15],
12: [8, 13],
13: [9, 12, 14],
14: [10, 13, 15],
15: [11, 14],
}
robotPos = [13]
canPos = [10, 1]
canGoal = [6, 2]
main(graph, robotPos, canPos, canGoal)
|
8c66d4beff3d6bb8e4364559780ce307288960ca | maulxandr/maul-homework2 | /task_triangle_ya.py | 601 | 3.796875 | 4 | AX = int(input())
AY = int(input())
BX = int(input())
BY = int(input())
CX = int(input())
CY = int(input())
# Вычислим длины сторон треугольника
AB = ((AX - BX) ** 2 + (AY - BY) ** 2) ** 0.5
BC = ((BX - CX) ** 2 + (BY - CY) ** 2) ** 0.5
AC = ((AX - CX) ** 2 + (AY - CY) ** 2) ** 0.5
# Выполним проверку, является ли треугольник прямоугольным
if AB ** 2 == BC ** 2 + AC ** 2:
print('yes')
elif BC ** 2 == AB ** 2 + AC ** 2:
print('yes')
elif AC ** 2 == AB ** 2 + BC ** 2:
print('yes')
else:
print('no')
|
96e2e0d4ccfdb550673860199813c5467b83fe9f | rmedalla/5-2-18 | /Calculator.py | 429 | 4.1875 | 4 | first_number = int(input("Enter first number: "))
math_operation = input("Choose an operand +, -, *, /: ")
second_number = int(input("Enter second number: "))
if math_operation == "+":
print(first_number + second_number)
if math_operation == "-":
print(first_number - second_number)
if math_operation == "*":
print(first_number * second_number)
if math_operation == "/":
print(first_number / second_number)
|
e12b4feccf16912ed4f792fcb3b3d99c91897903 | ocastudios/glamour | /utils/__init__.py | 364 | 3.90625 | 4 | def reverse(original):
if original.__class__ in (int, float):
return original * -1
elif original.__class__ == str:
if original == "right":
return "left"
elif original == "left":
return "right"
elif original == "up":
return "down"
elif original == "down":
return "up"
|
7ba408f380547e2078dcc3163031f028cdf188a7 | achmat-samsodien/RealPython | /factors.py | 188 | 4.09375 | 4 |
pos_int = int(raw_input("Enter a positive integer:"))
for divisor in range(1, pos_int+1):
if pos_int % divisor == 0:
print "{} is a divisor of {}".format(divisor, pos_int)
|
327b3354f5924358273de9be284627d37520fbba | Nozzin/Age-to-100 | /Age 100.py | 386 | 4 | 4 | def main():
age = int(input('What is your age? '))
name = input('What is your name? ')
year = 2016
while age < 100:
age +=1
year +=1
howMany = int(input('How many times do you want the message? '))
for i in range(howMany):
print ('Hello',name,'you will be 100 in ',year,'.')
print('')
main()
|
5d7d2000c3d88ad79374e2e48c3b605cbaaee407 | Shivang1983/Application-Oriented-Programming-Using-Python | /Range.py | 108 | 3.5 | 4 | def func1():
for i in range(1000,2000):
if (i%7)==0 and (i%5)!=0 :
print(i)
func1() |
65887fd941b6b46332fed42aed93fa35f0f30eeb | Humaira-Shah/ECE499 | /asst2/AX12funcADJUSTED.py | 2,519 | 3.84375 | 4 | # FUNCTION getChecksum(buff)
# Takes packet as a list for its parameter.
# Packet must include at least 6 elements in order to have checksum calculated
# last element of packet must be the checksum set to zero, function will return
# packet with correct checksum value.
def getChecksum(buff):
n = len(buff)
if(n >= 6):
# check that first two elements are 255 as required in order to
# signify the start of an incoming packet
if((buff[0] != 255) or (buff[1] != 255)):
print "WARNING: FIRST TWO PARAMETERS OF PACKET MUST BE 255\n"
# calculate checksum
checksum = 0
# consider all elements of buff except checksum element buff[n-1]
# and except buff[0] and buff[1] for calculation of checksum
for i in range(n-3):
# add up all considered elements besides buff[0] and buff[1]
checksum = checksum + buff[i+2]
checksum = ~checksum
# get least significant byte after notting
checksum = checksum & 0xFF
buff[n-1] = checksum
else:
# does not contain at least minimum parameters
# Should have at least the following parameters
# buff[0] = 0xFF
# buff[1] = 0xFF
# buff[2] = ID
# buff[3] = LENGTH
# buff[4] = INSTRUCTION
# buff[n-1] = CHECKSUM
print "ERROR: YOU FOOL! A PACKET MUST BE AT LEAST OF LENGTH 6\n"
#print buff
return buff
def setVelocity(ID, vel):
# make sure ID is valid
if((ID > 254) or (ID < 0)):
print "WARNING: ID is out of acceptable range of values\n"
ID = ID & 0xFF
if(ID > 254):
ID = 254
# check to see if vel is within range of possible values
# must have magnitude less than or equal to 0x3FF which is
# 1023 in decimal
if((vel > 1023) or (vel < -1023)):
print "WARNING: User has entered vel outside acceptable range [-1023,1023]\n Behavior will not be as expected...\n"
# check to see if user specified positive (CW)
# or negative (CCW) velocity
velSign = 0x04 # by default, sign bit is raised, meaning CW
if(vel < 0):
# vel negative, therefore set sign bit for CCW
velSign = 0x00
# make vel positive to obtain magnitude
vel = (~vel) + 0x01
# get 2 least significant bytes of vel
vel = vel & 0xFFFF
# break vel into high byte and lowbyte
velH = vel & 0xFF00
velH = velH >> 8
velL = vel & 0x00FF
# limit high byte to 0x03 because maximum
# velocity is 0x03FF
velH = velH & 0x03
# put sign info in velH
velH |= velSign
# make command packet for goal position and moving speed
packet = [0xFF, 0xFF, ID, 0x04, 0x20, velL, velH, 0]
packet = getChecksum(packet)
#print packet
return packet
|
d16363c7abfa5cfa0435f4bb3a71e835d69b7fba | ryneches/Ophidian | /ACUBE/blob.py | 6,846 | 3.609375 | 4 | #!/usr/bin/env python
# vim: set ts=4 sw=4 et:
"""
Utility functions for building objects representing functions from
computed values.
"""
class SplineError(Exception) :
pass
class spline :
"""
This is a "natural" spline; the boundary conditions at the beginning
and end of the spline are such that the second derivative across
the boundary is zero.
"""
# data members
def __init__ (self) :
self.last_i = 0
self.R = []
self.Z = []
self.Z2 = []
# class methods
def get_R_for_Z (self, Z) :
"""
find the value R for a given Z
"""
if self.valid() == 0 :
raise SplineError, "Spline not initialized. Value: " + str(Z)
# avoid typing self.foo
R = self.R
Z = self.Z
Z2 = self.Z2
# find the right place in the table of R values
def get_Z_for_R (self, r) :
"""
find the value Z for a given r
"""
# make sure r is treated as a float
r = float(r)
if self.valid() == 0 :
raise SplineError, "Spline not initialized. Value: " + str(r)
if r < self.R[0] or r > self.R[len(self.R) - 1] :
raise SplineError, "Called value out of range. Value: " + str(r)
# avoid typing self.foo
R = self.R
Z = self.Z
Z2 = self.Z2
# check to see if most recent index is correct
if r >= R[self.last_i] and r < R[self.last_i + 1] :
i = self.last_i
else :
# find the right place in the table of R values
for i in range(len(R) - 1) :
if r >= R[i] and r < R[i + 1] :
self.last_i = i
break
h = R[i + 1] - R[i]
if h == 0.0 :
raise SplineError, "Bad spline! Value: ", str(r)
a = (R[i + 1] - r) / h
b = (r - R[i]) / h
return a * Z[i] + b * Z[i + 1] + \
((a**3 - a) * Z2[i] + (b**3 - b) * Z2[i + 1]) * (h**2) / 6.0
def get_dZ_for_R (self, r) :
"""
find the value Z for a given r
"""
# make sure r is treated as a float
r = float(r)
if self.valid() == 0 :
raise SplineError, "Spline not initialized. Value: " + str(r)
if r < self.R[0] or r > self.R[len(self.R) - 1] :
raise SplineError, "Called value out of range. Value: " + str(r)
# avoid typing self.foo
R = self.R
Z = self.Z
Z2 = self.Z2
# check to see if most recent index is correct
if r >= R[self.last_i] and r < R[self.last_i + 1] :
i = self.last_i
else :
# find the right place in the table of R values
for i in range(len(R) - 1) :
if r >= R[i] and r < R[i + 1] :
self.last_i = i
break
h = R[i + 1] - R[i]
if h == 0.0 :
raise SplineError, "Bad spline! Value: ", str(r)
a = (R[i + 1] - r) / h
b = (r - R[i]) / h
return - Z[i] / h + Z[i+1] / h + \
(h/6) * ( ( -3 * a**2 - 1 )*Z2[i] + ( 3 * b**2 - 1 )*Z2[i+1] )
def build (self, R_new, Z_new, natural = 'yes') :
"""
Takes list of points in a Cartesian plane and computes the spline
coefficeints. See Numerical Recipies in C, 2nd edition, section
3.3 for details.
Defaults to natural boundary conditions.
"""
if len(R_new) != len(Z_new) :
raise SplineError, "Dimension Mismatch: R: " + \
str(R_new) + " Z: " + str(Z_new)
self.R = R_new
self.Z = Z_new
# create some local names for class members. This is to avoid
# having to type self.foo all the time
R = self.R
Z = self.Z
Z2 = self.Z2
data = []
for i in range(len(R)) :
data.append([ float(R[i]), float(Z[i]) ])
data.sort()
for i in range(len(R)) :
R[i] = data[i][0]
Z[i] = data[i][1]
for i in range(len(R) - 1) :
if R[i] == R[i + 1] :
raise SplineError, "R values must be unique. Value: " + \
str(R[i])
# assorted variables
i = 1
k = 1
n = len(self.R) # number of elements
p = 0.0
qn = 0.0
sig = 0.0
un = 0.0
u = []
# first derivatives at the boundaries
Zp1 = 1e5
Zpn = -1e5
# initialize Z2 and u arrays to the correct size
# (values don't matter)
Z2 = range(n)
u = range(n)
if natural == 'yes' :
Z2[0] = u[0] = 0.0 # first real value here is also zero,
# because this is a natural spline
qn = un = Z2[n - 1] = u[n - 1] = 0.0 # "natural" upper boundary
else :
# set the lower boundary condition to match Zp1
Z2[0] = -0.5
u[0] = ( 3.0 / ( R[1] - R[0] ) ) * \
( (Z[1] - Z[0] ) / ( R[1] - R[0] ) - Zp1 )
qn = 0.5
un = ( 3.0 / ( R[n - 1] - R[n - 2] ) ) * \
( Zpn - ( Z[n - 1] - Z[n - 2] ) / ( R[n - 1] - R[n - 2] ) )
# tridiagonal decomposition (Z2 used as temporary storage)
# We loop from the second element to the second to last
# element
for i in range(1, n - 1) :
sig = ( R[i] - R[i - 1] ) / ( R[i + 1] - R[i - 1] )
p = sig * Z2[i - 1] + 2.0
Z2[i] = ( sig - 1.0 ) / p
u[i] = (6.0 * ((Z[i + 1] - Z[i]) / (R[i + 1] - R[i]) - \
(Z[i] - Z[i - 1]) / (R[i] - R[i - 1])) / ( R[i + 1] - \
R[i - 1]) - sig*u[i - 1]) / p
for k in range( n - 2, 0, -1) :
Z2[k] = Z2[k] * Z2[k + 1] + u[k]
self.Z2 = Z2
self.last_i = 0
def valid (self) :
"""
Returns true if the spline has been constructed (Z2 is fully
populated) and the boundary conditions match
"""
if len( self.Z2 ) == 0 :
return 0
#if self.Z2[0] != 0.0 or self.Z2[ len(self.Z2) - 1 ] != 0.0 :
# return 0
Rtest = self.R
for i in range( len(Rtest) - 1 ) :
if Rtest[i] == Rtest[i + 1] :
print "Independant variable cannot have repeated values!"
print "Shitting the bed."
return "alkdfjaldsfjadsf"
return 1
|
7dda5fbfaf023f50773d680aad4947ad2a61dad2 | g-m-b/Data-structures-and-algorithms | /selection_sort.py | 329 | 3.65625 | 4 | def select_sort(a):
for i in range(len(a)):
min_pos=i
for j in range(i,len(a)):
if a[j]<a[min_pos]:
min_pos=j
a[i],a[min_pos]=a[min_pos],a[i]
if __name__ == '__main__':
a=[10,6,5,4,3,2]
select_sort(a)
for i in range(len(a)):
print(a[i])
|
f5cc1786452e20b10771998ffa44cf0f130ef4be | evanpeck/ethical_engine | /python/student_code/main.py | 815 | 3.65625 | 4 |
from engine import decide
from scenario import Scenario
def runSimulation():
''' Temporarily putting a main function here to cycle through scenarios'''
print("===========================================")
print("THE ETHICAL ENGINE")
print("===========================================")
print()
keepRunning = True
while keepRunning:
scene = Scenario()
print(scene)
print()
result = decide(scene)
print()
input('Hit any key to see decision: ')
print('I choose to save the', result)
print()
# For breaking the loop
response = input("Hit 'q' to quit or 'enter' to continue: ")
if response == 'q':
keepRunning = False
print('Done')
if __name__ == '__main__':
runSimulation()
|
3ceee61fb8757295c4d165ccb1ccdbb53ce6afc4 | jringenbach/labyrinth | /labyrinth/labyrinth.py | 14,718 | 3.5625 | 4 | #Python libraries
import os
import platform
import time
import xlrd
#Project libraries
from labyrinth.element import Element
from labyrinth.node import Node
class Labyrinth:
def __init__(self, file_name=None, labyrinth=list()):
"""
file_name (str) : name of the file where the labyrinth is saved
labyrinth (list) : list of every line of the labyrinth
labyrinth_nodes (list) : list of each Node object on each line
list_empty_nodes (list) : list of Node objects containg empty spaces
list_wall_nodes (list) : list of Node objects containing walls
start_point (Node) : Node of the start point of the labyrinth
exit_point (Node) : Node of the exit of the labyrinth
agent_node (Node) : Node where the agent is in the labyrinth
labyrinth_statistics (dict) : dictionary containing statistics about the labyrinth
"""
self.file_name = file_name
self.list_empty_nodes = list()
self.list_wall_nodes = list()
self.labyrinth = labyrinth
self.labyrinth_nodes = list()
self.start_point = None
self.agent_node = None
self.end_point = None
self.labyrinth_statistics = self.set_empty_labyrinth_statistics()
#If a file_name is given to get the labyrinth, we get the labyrinth and set the list of nodes
if self.file_name is not None and len(labyrinth) == 0:
self.labyrinth = self.get_labyrinth_from_file_name(self.file_name)
self.initialization_labyrinth()
#If a labyrinth is given as its list form in parameter of __init__
elif len(labyrinth) > 0 and self.file_name is None:
self.initialization_labyrinth()
def breadth_first_search(self, start_point=None):
"""BFS algorithm indicating the shortest distance between start_point and each node
start_point (Node object) : Node where we start the algorithm"""
self.initialization_list_empty_nodes(self.labyrinth_statistics["number_of_nodes"])
#If start_point is None, we set it to the node where the agent is in the labyrinth
if start_point is None:
start_point = self.agent_node
#Initial situation of the algorithm
queue = [start_point]
start_point.status = 1
start_point.distance_from_start_point = 0
#While the queue is not empty, we analyze the nodes in it to empty it step by step
while(len(queue) > 0):
node_to_analyze = queue[0]
for node in node_to_analyze.connected_to:
if node.status == 0:
node.pere = node_to_analyze
node.distance_from_start_point = queue[0].distance_from_start_point + 1
node.status = 1
queue.append(node)
queue.pop(0)
node_to_analyze.status = 2
def equals_list_nodes(self, self_list_nodes, other_list_nodes):
"""Test if this labyrinth list of nodes is equal to an other list of nodes. Return True if the lists are the same, False else.
other_list_empty_nodes (list) : list of Node object"""
#If the two list of nodes have different lengths, they are automatically different
if len(self_list_nodes) != len(other_list_nodes):
return False
else:
#We sort both list of nodes
self_list_nodes = sorted(self_list_nodes, key=lambda x : x.num)
other_list_nodes = sorted(other_list_nodes, key=lambda x : x.num)
#For each node in both lists
for i, node in enumerate(self_list_nodes):
#We check if the length of the list of the nodes they are connected to are the same
if len(node.connected_to) != len(other_list_nodes[i].connected_to):
return False
else:
#We check if the connection between the nodes in both list is the same
node_connected_to = sorted(node.connected_to, key=lambda x : x.num)
other_node_connected_to = sorted(self_list_nodes[i].connected_to, key=lambda x : x.num)
for j, node_connec in enumerate(node_connected_to):
if node_connec.num != other_node_connected_to[j].num:
return False
return True
def find_node_to_move_on(self, node):
"""This method is looking for the node where the agent must move depending on the breadth first search done
just before"""
#We start from the node where the agent must go, and we climb up through each father of each node to reach
#the agent position which is set with distance_from_start_point = 0
while(node.pere is not None and node.pere.distance_from_start_point > 0):
node = node.pere
return node
def get_labyrinth_from_file_name(self, file_name):
"""Get every line of the labyrinth from a file with the name stocked in self.file_name"""
excel_file = xlrd.open_workbook(self.file_name)
labyrinth = list()
for sheet in excel_file.sheets():
for i in range(sheet.nrows):
row = list()
for j in range(sheet.ncols):
row.append(sheet.cell_value(i, j))
labyrinth.append(row)
return labyrinth
def initialization_labyrinth(self):
"""Initialize all the parameters of the labyrinth.
1. Create the list of nodes of the labyrinth.
2. Calculate the connections between the nodes
3. Set the labyrinth statistics"""
self.set_datas_from_labyrinth()
self.set_connection_between_nodes()
self.set_labyrinth_statistics_from_labyrinth()
def initialization_list_empty_nodes(self, n):
"""Initialize all the nodes in self.list_empty_nodes for the BFS algorithm
n : number of nodes, so it represents the maximum distance that cannot be reached with BFS algorithm"""
for node in self.list_empty_nodes:
node.status = 0
node.distance_from_start_point = n+1
node.pere = None
def is_equal_to(self, another_labyrinth):
"""Test if this labyrinth is the same as another_labyrinth. If it is, it returns True, else False"""
if self.equals_list_nodes(self.list_empty_nodes, another_labyrinth.list_empty_nodes) and \
self.equals_list_nodes(self.list_wall_nodes, another_labyrinth.list_wall_nodes) and \
self.start_point.position_is_equal_to(another_labyrinth.start_point) and \
self.exit_point.position_is_equal_to(another_labyrinth.exit_point):
return True
else:
return False
def move_to_exit(self, time_move=0.25):
"""Move the Agent through the labyrinth to reach the exit point
time_move (int) : time to wait between each move in the labyrinth"""
#While the agent is not on the exit, we keep going through the labyrinth
while self.agent_node.labyrinth_position != self.exit_point.labyrinth_position:
#We use breadth first search to create the tree with the distance of every node from the agent position
self.breadth_first_search()
node_to_move_on = self.find_node_to_move_on(self.exit_point)
self.update_statistics_after_move(node_to_move_on)
self.set_datas_after_move(node_to_move_on)
#We clear the terminal to print the labyrinth with the new position of the agent
clear = "cls" if platform.system() == "Windows" else "clear"
os.system(clear)
self.print_labyrinth()
time.sleep(time_move)
def print_labyrinth(self):
"""Print the labyrinth and its element in the terminal"""
for line in self.labyrinth_nodes:
for column in line:
#If there is only one element, we print its symbol
if len(column.elements) == 1:
print(column.elements[0].symbol, end="")
#Else, we are looking for the Agent element, and we print its symbol
else:
for element in column.elements:
if element.name == "Agent":
print(element.symbol, end="")
print()
def print_list_of_nodes(self):
"""Print details of every node with information collected after BFS algorithm"""
for node in self.list_empty_nodes:
print("--------------------------")
print("Node num : "+str(node.num))
print("Node distance from start point : "+str(node.distance_from_start_point))
if node.pere is None:
print("Pas de père")
else:
print("Num du père : "+str(node.pere.num))
def set_connection_between_nodes(self):
"""Set every attributes connected_to for every node in self.list_empty_nodes. It establishes the connection between nodes."""
for i, node in enumerate(self.list_empty_nodes):
line = node.labyrinth_position[0]
column = node.labyrinth_position[1]
for j in range(i+1, len(self.list_empty_nodes)):
line_j = self.list_empty_nodes[j].labyrinth_position[0]
column_j = self.list_empty_nodes[j].labyrinth_position[1]
if i != j and ((line == line_j and column == column_j - 1) \
or (line == line_j and column == column_j + 1) \
or (column == column_j and line == line_j - 1) \
or (column == column_j and line == line_j + 1)) \
and (not node in self.list_empty_nodes[j].connected_to) \
and (not self.list_empty_nodes[j] in node.connected_to):
node.connected_to.append(self.list_empty_nodes[j])
self.list_empty_nodes[j].connected_to.append(node)
def set_datas_after_move(self, node_to_move_on):
"""Change the attributes of the labyrinth depending on the node where the agent moved
node_to_move_on (Node) : node on which the agent must move"""
#We change the agent element from the node where it was to the node where it is
agent_element = self.agent_node.find_element_by_parameter(parameter="symbol", value="A")
self.agent_node.remove_element(agent_element)
node_to_move_on.elements.append(agent_element)
self.agent_node = node_to_move_on
def set_datas_from_labyrinth(self):
"""Create the list of nodes depending on the labyrinth read in a xls file and set self.start_point and self.exit_point
and self.agent_node"""
node_number = 1
for i, line in enumerate(self.labyrinth):
row = list()
for j, column in enumerate(line):
node = Node(node_number, (i,j))
#If it is an empty space
if column == "":
element = Element("Empty", " ", False)
node.elements = [element]
self.list_empty_nodes.append(node)
#If this is the start point
elif column == "S":
element = Element("Start", "S", False)
agent = Element("Agent", "A", False)
node.elements = [element, agent]
self.start_point = node
self.agent_node = node
self.list_empty_nodes.append(node)
#If this is the exit
elif column == "E":
element = Element("Exit", "E", False)
node.elements = [element]
self.exit_point = node
self.list_empty_nodes.append(node)
#If this is a wall
elif column == "X":
element = Element("Wall", "X", True)
node.elements = [element]
self.list_wall_nodes.append(node)
row.append(node)
node_number += 1
self.labyrinth_statistics["number_of_nodes"] += 1
self.labyrinth_nodes.append(row)
def set_empty_labyrinth_statistics(self):
"""Set the dictionary for the attributes labyrinth_statistics and returns it"""
labyrinth_statistics = {
"number_of_nodes" : 0,
"number_of_empty_nodes" : 0,
"number_of_walls" : 0,
"number_of_lines" : 0,
"number_of_columns" : 0,
"distance_between_start_and_end_point" : 0,
"distance_between_agent_and_end_point" : 0,
"number_of_moves_done_by_agent" : 0
}
return labyrinth_statistics
def set_labyrinth_statistics_from_labyrinth(self):
"""Set the dictionary of statistics about the labyrinth"""
self.labyrinth_statistics["number_of_walls"] = len(self.list_wall_nodes)
self.labyrinth_statistics["number_of_empty_nodes"] = len(self.list_empty_nodes)
self.labyrinth_statistics["number_of_lines"] = len(self.labyrinth_nodes)
self.labyrinth_statistics["number_of_columns"] = len(self.labyrinth_nodes[0])
self.labyrinth_statistics["number_of_moves_done_by_agent"] = 0
self.labyrinth_statistics["number_of_nodes"] = self.labyrinth_statistics["number_of_lines"]*self.labyrinth_statistics["number_of_columns"]
#We calculate the distance between the agent node and the exit node with breadth first search
self.breadth_first_search(self.agent_node)
self.labyrinth_statistics["distance_between_agent_and_end_point"] = self.exit_point.distance_from_start_point
#We calculate the distance between the start node and the exit node with breadth first search
self.breadth_first_search(self.start_point)
self.labyrinth_statistics["distance_between_start_and_end_point"] = self.exit_point.distance_from_start_point
def update_statistics_after_move(self, node_to_move_on):
"""Change the statistics that vary with the movement of the agent through the labyrinth"""
distance_exit = self.exit_point.distance_from_start_point
distance_node_to_move_on = node_to_move_on.distance_from_start_point
self.labyrinth_statistics["distance_between_agent_and_end_point"] = distance_exit - distance_node_to_move_on
self.labyrinth_statistics["number_of_moves_done_by_agent"] += 1 |
721e70fd5d2a3cb8c30895f8a9e8c8f6531c73d3 | aren945/pythonWay | /OOP/ObjectInfo.py | 905 | 3.671875 | 4 | # 使用type()
# 判断对象类型,使用type
type(12)
import OOP.ClassDemo as ClassDemo
a = ClassDemo.Man('zheng', 100)
print(type(123))
print(type(a))
import types
def fn():
pass
print(type(fn))
# 判断是否是函数
print(type(fn) == types.FunctionType)
print(type(x for x in range(10)) == types.GeneratorType)
# 判断继承关系
print (isinstance(a, ClassDemo.Man))
print (isinstance(a, object))
# 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法
print(dir('ABC'))
print(dir(ClassDemo))
# len方法实质上在len方法内部,他自动去调用该对象的__len__()方法,如果我们自己写的类也想用len()方法,就自己写一个__len__()方法
class MyDog(object):
def __len__(self):
return 100
dog = MyDog()
print(len(dog))
|
b6ef34d8c45e06da767d0dedd818ba215780fa27 | aren945/pythonWay | /切片.py | 318 | 3.59375 | 4 | l = ['a', 'b', 'c', 'd']
a = list(range(100))
# print(type(a))
print(a[1:3])
print(a)
# from collections import Iterable
# print(isinstance('adc', Iterable))
for i, val in enumerate(l):
print(i)
c = [1, 2, 3, 4, 5, 6]
print('min is %d' % min(c))
ll = [(1, 2), (4, 5), (7, 8)]
for x, y in ll:
print(x, y) |
01bd112fa9f40534dd7dc96f293768d2a90bd578 | aren945/pythonWay | /learnDecorator.py | 1,899 | 3.5625 | 4 | import functools
def d1(func):
@functools.wraps(func)
def wrapper():
print('1234')
print(func())
return wrapper
@d1
def foo():
print('this is function fun')
return 'asd'
print(foo.__name__)
foo()
# --------------------------函数带参------------------------------
def d2(func):
# @functools.wraps(func)
def wrapper(*args, **kw):
print('这是装饰器的打印')
func(*args, **kw)
return wrapper
@d2
def foo2(a, b):
print('a is {0}, b is {1}'.format(a, b))
print('foo2 name %s' % foo2.__name__)
foo2(1, 2)
# ___________________________带参装饰器——————————————————————
def d3(text):
def decorator(func):
print('decirator print %s' % text)
def wrapper(*args, **kw):
print('wrapper print')
return func(*args, **kw)
return wrapper
return decorator
@d3('test')
def foo3(a, b):
print('a is %s , b is %s' % (a, b))
foo3(3, 4)
# ---------------------类装饰器------------------------
class Foo(object):
def __init__(self, func):
self._func = func
def __call__(self):
print('class decorator runing')
self._func()
print('class decorator ending')
@Foo
def bar():
print('bar')
bar()
# ------------------------装饰器顺序-------------------
def d4(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('this is decorator4')
return func(*args, **kw)
return wrapper
def d5(text):
def decorator(func):
print('log is %s' % text)
def wrapper(*args, **kw):
print('asd')
return func(*args, **kw)
return wrapper
return decorator
@d4
@d5('多个装饰器')
def foo4(a, b):
print('a is %s, b is %s' % (a, b))
foo4(10, 20)
if (False, False):
print(123213) |
53cbd88eac06435fbf428d0141c666b489f18ffb | aren945/pythonWay | /advanced/map.py | 106 | 3.578125 | 4 | list_x = [1,2,3,4,5,6,7]
def square(x):
print(x)
return x * x
r = map(square, list_x)
print(list(r)) |
9d0a5ec66076a613f4b47e2bdb553a27e67cf028 | cherrycchu/AI-games | /sudoku.py | 4,895 | 3.78125 | 4 | #!/usr/bin/env python
#coding:utf-8
import queue as Q
import time
from statistics import mean, stdev
import sys
"""
Each sudoku board is represented as a dictionary with string keys and
int values.
e.g. my_board['A1'] = 8
"""
ROW = "ABCDEFGHI"
COL = "123456789"
def get_grids(row, col):
# get grids from row and column
return [ r + c for c in col for r in row]
def get_neighbors(grids, neighbors_list):
neighbors = {}
for g in grids:
neighbors[g] = set()
for n in neighbors_list:
if g in n:
neighbors[g] |= set(n)
return neighbors
GRIDS = get_grids(ROW, COL)
NEIGHBORS_LIST = ([get_grids(ROW, c) for c in COL] +
[get_grids(r, COL) for r in ROW] +
[get_grids(r, c) for c in ('123', '456', '789') for r in ('ABC', 'DEF', 'GHI')])
NEIGHBORS = get_neighbors(GRIDS, NEIGHBORS_LIST)
def print_board(board):
"""Helper function to print board in a square."""
print("-----------------")
for i in ROW:
row = ''
for j in COL:
row += (str(board[i + j]) + " ")
print(row)
def board_to_string(board):
"""Helper function to convert board dictionary to string for writing."""
ordered_vals = []
for r in ROW:
for c in COL:
ordered_vals.append(str(board[r + c]))
return ''.join(ordered_vals)
def mrv(csp):
# minimum remaining variable heuristic
# return a variable e.g. A1
return min(csp, key=csp.get)
def lcv(var, assignment, csp):
# least constraining value
# return list of value in lcv order
neighbors = NEIGHBORS[var]
unassigned_neighbors = neighbors.difference(set(assignment.keys()))
assigned_neighbors = neighbors.intersection(set(assignment.keys()))
constraints = [assignment[n] for n in assigned_neighbors]
## initialize list of domain value for a variable
domain = {}
for value in csp[var]:
if value not in constraints:
domain[value] = 0
## find the least contraining value by exmaining neighbor domains
for n in unassigned_neighbors:
for d in csp[n]:
if d in domain:
domain[d] += 1 # increment value count
## sort the lcv dict in ascending order
domain_in_lcv = [item[0] for item in sorted(domain.items(), key=lambda x:x[1])]
return domain_in_lcv, unassigned_neighbors
def backtrack(assignment, csp):
# check if assignment is complete
if len(assignment) == 81:
return assignment
if len(csp) == 0:
return "failure"
var = mrv(csp)
recover = {} # for csp backtracking
lcv_domain, unassigned_neighbors = lcv(var, assignment, csp)
for value in lcv_domain:
assignment[var] = value
recover[var] = csp[var]
del csp[var]
result = backtrack(assignment, csp)
if result != "failure":
return result
del assignment[var]
csp[var] = recover[var]
return "failure"
def backtracking(board):
"""Takes a board and returns solved board."""
# setup a assignment and domain dictionary
assignment = {}
csp = {}
for var in board:
if board[var] != 0:
assignment[var] = board[var]
else:
csp[var] = {1, 2, 3, 4, 5, 6, 7, 8, 9}
#for n in neighbors_of(var):
# csp[var].discard(board[n])
# restrict domains by propagating assignment
## commenting out the following solves hardest sudoku in 40 secs
for var in assignment.keys():
for n in NEIGHBORS[var]:
if n in csp:
csp[n].discard(assignment[var])
solved_board = backtrack(assignment, csp)
return solved_board
if __name__ == '__main__':
"""
# Read boards from source.
src_filename = 'sudokus_start.txt'
#src_filename = 'hardest_sudoku.txt'
try:
srcfile = open(src_filename, "r")
sudoku_list = srcfile.read()
except:
print("Error reading the sudoku file %s" % src_filename)
exit()
"""
# Setup output file
out_filename = 'output.txt'
outfile = open(out_filename, "w")
running_time = []
# Solve each board using backtracking
line = sys.argv[1]
# Parse boards to dict representation, scanning board L to R, Up to Down
board = { ROW[r] + COL[c]: int(line[9*r+c])
for r in range(9) for c in range(9)}
# Print starting board. TODO: Comment this out when timing runs.
print_board(board)
# Solve with backtracking
#start_time = time.time()
solved_board = backtracking(board)
#end_time = time.time()
# Print solved board. TODO: Comment this out when timing runs.
print_board(solved_board)
# Write board to file
outfile.write(board_to_string(solved_board))
outfile.write('\n')
#print("running_time: " + str(end_time-start_time))
|
b367f20e52abb94656d22cebda3cdf2fc533e2bb | havardMoe/euler | /problems/problem8.py | 501 | 3.890625 | 4 | """
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
"""
if __name__ == '__main__':
filename = "assets/p8_numbers.txt"
numbers = []
with open(filename, mode="r") as f:
for line in f:
for number in line.rstrip('\n'):
numbers.append(int(number))
print(numbers)
|
f8c1e91630c213360205d747e0dd573b3dbaed67 | Meemaw/Eulers-Project | /Problem_48.py | 400 | 3.796875 | 4 | __author__ = 'Meemaw'
print("Please insert upper bound:")
x = int(input())
print("Please insert last n numbers to be printed:")
last = int(input())
vsota = 0
for i in range(1,x+1):
vsota += i**i
if(last > vsota):
print("Sum doesnt have " +str(last) + " digits")
print("Sum: " + str(vsota))
else:
print("Last " + str(last) + " n digits of sum is:")
print(str(vsota)[-last:])
|
a31ad7eb37c00469902946e4149192bba1b94363 | Meemaw/Eulers-Project | /Problem_37.py | 888 | 3.71875 | 4 | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[i:]))) != 1:
return False
return True
def izDesne(stevilo):
for i in range(len(stevilo)):
if(isPrime(int(stevilo[0:len(stevilo)-i]))) != 1:
return False
return True
numOfPrimes = 0
vsota = 0
poglej = 11
while numOfPrimes != 11:
string = str(poglej)
if izDesne(string) and izLeve(string):
numOfPrimes+=1
vsota+=poglej
poglej+=1
print("Sum of the only eleven primes that are trunctable from left to right and right to left is:")
print(vsota) |
90c9d41f6128b5d5d324f00a66bc9847abfa886b | ColtonPhillips/wpdb | /src/wpdb/wpdb.py | 701 | 3.6875 | 4 | def csv_file_to_list(csv_file_path):
"""Converts a csv file_path to a list of strings
>>> csv_file_to_list("test/csv_file_to_list_test.csv")
['Pascal', 'Is', 'Lacsap']
"""
import csv
out_list = []
with open(csv_file_path, 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in csvreader:
out_list.append(', '.join(row))
return out_list
def _main():
import urllib
xml = urllib.urlopen("http://stats.grok.se/en/latest30/A_Dangerous_Path")
file = open ("out.txt", 'w')
#file.write(str(xml.read()))
if __name__ == "__main__":
import doctest
doctest.testmod()
_main()
|
863a17d68804499333542bc02eabbdb68080e66d | pratikbarjatya/Python-OOPS | /multilevel_inheritance.py | 512 | 3.609375 | 4 | class Father:
def father_property(self):
print('Father property used for home')
class Mother(Father):
def mother_property(self):
print('Mother property used for farming')
class Child(Mother):
def child_property(self):
print('child property used for playground')
def father_property(self):
print('Father property now used by child for cricket ground.')
obj1 = Child()
obj1.father_property()
obj1.mother_property()
obj1.child_property()
|
700af007f98f6ea5b0477b90804fc53499ac72c6 | jiangzhengfool/demo | /base.py | 10,125 | 3.84375 | 4 | # coding:utf-8
import re
# print ('江')
# flag = 'true'R
# if flag:
# print 'true'
# else:
# print 'false'
# n = 0
# count = 0
# while n <= 100:
# count += n
# n += 1
# print count
# print True
# def get_middle(s):
# #your code here
# str1 = s
# lens = len(s)
# if lens % 2 == 1:
# print str1[int(lens/2)]
# else:
# print str1[lens/2-1]+str1[lens/2]
#
# get_middle("abcdef")
# def find_short(s):
# # your code here
# arr = s.split(' ')
# l = len(s)
# for temp in arr:
# if l > len(temp):
# l = len(temp)
# return l # l: shortest word length
# print find_short('turns ot random test cases are easier than writing out basic ones')
# def is_isogram(string):
# # your code here
# count =[0]*26
# if not string:
# return True
# string =string.lower()
# lens =len(string)
# n = 0
# while n < lens:
# temp = string[n]
# n += 1
# temp = ord(temp) - 97
# count[temp] += 1
# if count[temp] >= 2:
# return False
# return True
# print is_isogram('ord')
# s = ''
# if not s:
# print 'null'
# else:
# print 'feikong'
#
# str = 'abc'
# print str.split(' ',3)
# a,b,c = 0 * 3
# print a,b,c
# a = {'name':{"jiang":'jian'}}
# a['name']['jiang'] = 'air'
# print a
# abc = 'abababbabab654'
# abc = re.sub ('[^1-9]','',abc)
#
# print abc
# def zeros(n):
# num = 0
# for i in range(1, n ):
# n = (n * i)
# while ((n % 10) == 0):
# n = n / 10;
# num += 1;
# n = n % 10;
#
# print(n,num)
# return num
# zeros(30)
# def pig_it(text):
# #your code here
# arr = text.split()
# for index,i in enumerate(arr):
# if len(i) > 1 | i.isupper() | i.islower():
# j = list(i)
# t = j.pop(0)
# j.append(t)
# j.append('ay')
# arr [index] = ''.join(j)
#
# text =' '.join(arr)
# print(text)
# return text
# pig_it('Pig latin is cool !')
# def score(dice):
# # your code here
# count = 0
# dice = sorted(dice)
# print(dice)
# if dice[0] == dice[2]:
# n = dice[2] * 100
# count += n * 10 if dice[2] == 1 else n
# if (dice[3] == 5) | (dice[3] ==1):
# count += dice[3] * 100 if dice[3] == 1 else dice[3] * 10
# if (dice[4] == 5) | (dice[4] == 1):
# count += dice[4] * 100 if dice[4] == 1 else dice[4] * 10
# elif dice[2] == dice[4]:
# n = dice[2] * 100
# count += n * 10 if dice[2] == 1 else n
# if (dice[0] == 5) | (dice[0] == 1):
# count += dice[0] * 100 if dice[0] == 1 else dice[0] * 10
# if (dice[1] == 5) | (dice[1] == 1):
# count += dice[1] * 100 if dice[1] == 1 else dice[1] * 10
# elif (dice[2] == dice[3])& (dice[2] == dice[1]):
# n = dice[2] * 100
#
# count += n * 10 if dice[2] == 1 else n
# if (dice[0] == 5) | (dice[0] == 1):
# count += dice[0] * 100 if dice[0] == 1 else dice[0] * 10
# if (dice[4] == 5) | (dice[4] == 1):
# count += dice[4] * 100 if dice[4] == 1 else dice[4] * 10
# # print(count)
# else:
#
# for i in dice:
# if i == 1:
# count += 100
# if i == 5:
# count += 50
# print(count)
# return count
# score([1,2,2,6,6])
# def dig_pow(n, p):
# # your code
# s = str(n)
# count =0
# s = reversed(s)
# for i in s:
#
# count += int(i)**p
# print(i)
# p += 1
# return count//n if (count % n==0) else -1
# print(dig_pow(89,1))
#
# def expanded_form(num):
# ls = []
# p = 1
# while num > 0:
# n = num % 10 * p
# if n :
# ls.append(str(n))
# num = num // 10
# p *= 10
#
# return ' + '.join(reversed(ls))
# print(expanded_form(70304))
# def move_zeros(array):
# t = [i for i in array if ((type(i) != int) & (type(i) != float) ) | (i!=0)]
# return t + [0]*(len(array)-len(t))
# #your code here
# seconds = 3600*24*365
# s = seconds % 60
# m = seconds // 60 % 60
# h = seconds // 3600 % 24
# d = seconds // 3600 // 24 % 365
# y = seconds // 3600 // 24 // 365
#
# print(s,m,h,d,y)
# def format_duration(seconds):
# # your code here
# num =['']*5
# s = [0]*5
# num[4] = se = str(seconds % 60)
# num[3] = m = str(seconds // 60 % 60)
# num[2] = h = str(seconds // 3600 % 24)
# num[1] = d = str(seconds // 3600 // 24 % 365)
# num[0] = y = str(seconds // 3600 // 24 // 365)
# print(y,d,h,m,se)
# s[0] = y + ' year' if y == '1' else y + ' years'
# s[1] = d + ' day' if d == '1' else d + ' days'
# s[2] = h + ' hour' if h == '1' else h + ' hours'
# s[3] = m + ' minute' if m == '1' else m + ' minutes'
# s[4] = se + ' second' if se == '1' else se + ' seconds'
# ret = [s[i] for i in range(5) if int(num[i]) > 0]
# print(s)
# l = len(ret) >= 2
# ret_str = ', '.join(ret)
# i = ret_str.rfind(',')
# ret_str = ret_str if not l else (ret_str[:i] + ' and ' + ret_str[i+2:])
# print(ret_str)
# return ret_str
#
#
# print(format_duration(62))
#
# print(1 == '1')
#
# b = "\n".join([
# ".W.",
# ".W.",
# "W.."
# ])
#
# # print(type(b))
# def path_finder(maze_s,x=0,y=0):
# maze = maze_s.split()
# l = len(maze)
# #print(x,y,l)
# #print((l -1) == x)
# if (x == y) and ((l -1) == x):
# print((x == y) and ((l -1) == x))
# return True
# if x+1 < l and maze[x+1][y]!='W':
# #print(maze[x+1][y])
# return path_finder(maze_s,x+1,y)
# if y + 1 < l and maze[x][y+1]!= 'W':
# return path_finder(maze_s, x , y+1)
# if x-1 < l and maze[x-1][y]!='W':
# #print(maze[x+1][y])
# return path_finder(maze_s,x-1,y)
# if y - 1 < l and maze[x][y-1]!= 'W':
# return path_finder(maze_s, x , y-1)
#
# return False
#
# a = "\n".join([
# '.W...',
# '.W...',
# '.W.W.',
# '...W.',
# '...W.'])
#
#
# print(path_finder(a))
# def next_smaller(n):
# s = list(reversed(str(n)))
# for index,i in enumerate(s):
# for j in range(index,len(s)):
# if s[index] < s[j]:
# t = s.pop(index)
# s.insert(j,t)
# return ''.join(reversed(s))
# return -1
# print(next_smaller(127))
# def narcissistic( value ):
# s = str(value)
# l = len(s)
# arr = [s,'is','narcissistic']
# count = 0
# for i in s:
# count += int(i)**l
# if count == value :
# arr.insert(2,'not')
# return ' '.join(arr)
# # Code away
# narcissistic(371)
# a = str(hex(148))
# print(hex(148))
# print(a[-2:])
# def rgb(r, g, b):
# # your code here :
# r = 0 if r < 0 else r
# g = 0 if g < 0 else g
# b = 0 if b < 0 else b
# r = 255 if r > 255 else r
# g = 255 if g > 255 else g
# b = 255 if b > 255 else b
# #print(r, g, b)
# r = hex(r)
# g = hex(g)
# b = hex(b)
# if len(r) == 3:
# r = r[0:2]+'0'+r[2:]
# if len(g) == 3:
# g = g[0:2]+'0'+g[2:]
# if len(b) == 3:
# b = b[0:2] + '0' + b[2:]
# print(r, g, b)
# return r[2:].upper() + g[2:].upper() + b[2:].upper()
#
# print(rgb(255,255,125))
#
# print(type(hex(55)))
# def domain_name(url='http://www.zombie-bites.com'):
# i0 = url.find('https')
# i1 = url.find('.')
# i2 = url.rfind('.')
# print(i0,i1)
# if i0 >= 0 :
# s =url[8:i1]
# print(0,s)
# else:
# s = url[7:i1]
# s = s if 'www' != s else url[i1+1:i2]
# return s
# domain_name()
# def domain_name(url='http://youtube.com'):
# i1 = url.find('.')
# i2 = url.rfind('.')
# i0 = url.find('https')
# if i1 != i2 :
# s = url[i1 + 1:i2]
# else:
# if i0 >= 0:
# s = url[8:i1]
# print(0, s)
# else:
# s = url[7:i1]
# print(s)
# return s
#
# domain_name()
'http://google.co.jp'
'icann.org'
'http://sjllixpmk0ew0bdgfbjam9my.tv/default.html'
# def domain_name(url='www.xakep.ru'):
# i0 = url.find(':')
# i1 = url.find('.')
# print(i0,i1)
# if i0 > 0:
# s = url[i0+3:i1]
# if s == 'www':
# s =url[i1+1:]
# i2 =s.find('.')
# s = s[:i2]
# else:
# s = url[:i1]
# if s == 'www':
# s =url[i1+1:]
# i2 =s.find('.')
# s = s[:i2]
# return s
# print(domain_name())
#
#
# def sum_of_intervals(intervals=[
# [1,4],
# [7, 10],
# [3, 5]
# ]):
#
#
# return sum([i[1]-i[0] for i in intervals])
#
# print(sum_of_intervals())
#
# 2、求中位数<br>用having子句进行自连接求中位数<br>
# 第一步-- 将集合里的元素按照大小分为上半部分、下班部分 两个子集,
# 求其交集(无论聚合数据的数目是 奇数 偶数)
# select t1.income
# from gradutes t1 , gradutes t2
# group by t1.income
# having sum(case when t2.income >=t1.income then 1 else 0 end) >= count(*)/2<
# and sum(case when t2.income <=t1.income then 1 else 0 end) >= count(*)/2;<br>
# 第二步 -- 将上下部分集合求得的交集,去重,然后求平均,得到中值<br>select avg(distinct income)<br>from ( select t1.income<br> from gradutes t1,gradutes t2<br> group by t1.income<br> having sum(case when t2.income >= t1.income then 1 else 0) >= count(*)/2<br> and sum (case when t2.incomme <= t1.income then 1 else 0 ) >= count(*)/2) as tmp
# def sum_triangular_numbers(n):
# # your code here
# for i in range(1,10):
# pass
# return sum((1 + i) * i / 2 for i in range(1,n))
# def countOnes(left=12, right=29):
#
# return sum([(str(bin(i))).count('1') for i in range(left,right+1)])
#
def countOnes(left=12, right=29):
count = 0
for i in range(left,right+1):
while i > 0:
if i % 2 ==1:
count +=1
i //=2
return count
print(countOnes())
|
a4ce3d32406e1a613a6b076854f96d39027b35ee | umasp11/PythonLearning | /Datatype/InputData.py | 203 | 3.953125 | 4 |
'''ex= int(input('enter first number'))
#num1= int(input('enter first number')) #Typecasting
num2= float(input('enter second number'))
print(int(ex) +num2)'''
a=int (10.6)
b= float(5)
print(a+b) |
0badd45d54c90de31ce273519219cc0869f7da57 | umasp11/PythonLearning | /arg.py | 684 | 3.78125 | 4 | '''def sum(*ab):
s=0
for i in ab:
s=s+i
print('sum is', s)
sum(20,35,55,90,140)
'''
'''def myarg(a,b,c,d,e):
print(a,b,e)
list=[10,15,30,50,77] #no of parameter should be same as no of arguments
myarg(*list)'''
#Keyword argument **
def myarg(a,b,c):
print(a,b,c)
li={'a':10, 'b':'hello', 'c':100}
myarg(**li)
#OR
def myarg(a=10,b=11,c=15):
print(a,b,c)
myarg()
#OR
def myarg(**keywords):
for i,j in keywords.items():
print(i,j)
myarg(name='Kohli', sport= "Cricket", age=30)
#Lambda Function
result= lambda a:a*10
print(result(5))
#OR
def myfun(n):
return lambda a: a*n
result= myfun(5)
print(result(10)) |
df9a22117bd98acc6880792e5c3c0273f270067d | umasp11/PythonLearning | /polymerphism.py | 1,482 | 4.3125 | 4 | #polymorphism is the condition of occurrence in different forms. it uses two method overRiding & overLoading
# Overriding means having two method with same name but doing different tasks, it means one method overrides the other
#Methd overriding is used when programmer want to modify the existing behavior of a method
#Overriding
class Add:
def result(self,x,y):
print('addition', x+y)
class mult(Add):
def result(self,x,y):
print('multiplication', x*y)
obj= mult()
obj.result(5,6)
#Using superclass method we can modify the parent class method and call it in child class
class Add:
def result(self,x,y):
print('addition', x+y)
class mult(Add):
def result(self,a,b):
super().result(10,11)
print('multiplication', a*b)
obj= mult()
obj.result(10,20)
#Overloading: we can define a method in such a way that it can be called in different ways
class intro():
def greeting(self,name=None):
if name is not None:
print('Hello ', name)
if name is None:
print('no input given')
else:
print('Hello Alien')
obj1= intro()
obj1.greeting('Umasankar')
obj1.greeting(None)
#Ex2
class calculator:
def number(self,a=None,b=None,c=None):
if a!=None and b!=None and c!=None:
s=a+b+c
elif a!=None and b!= None:
s=a+b
else:
s= 'enter atlest two number'
return s
ob=calculator()
print(ob.number(10,)) |
62c33ddc7ddc1daba876dd0422432686fcf361eb | umasp11/PythonLearning | /Threading.py | 890 | 4.125 | 4 | '''
Multitasking: Execute multiple task at the same time
Processed based multitasking: Executing multi task at same time where each task is a separate independent program(process)
Thread based multitasking: Executing multiple task at the same time where each task is a separate independent part of the same program(process). Each independent part is called thread.
Thread: is a separate flow of execution. Every thread has a task
Multithreading: Using multiple thread in a prhram
once a thread is created, it should be started by calling start method: t= Thread(target=fun, args=()) then t.start()
'''
from threading import Thread
def display(user):
print('hello', user)
th=Thread(target=display, args=('uma',))
th.start()
#Example: thread in loop
def show(a,b):
print('hello number', a,b)
for i in range(3):
t=Thread(target=show, args=(10,20))
print('hey')
t.start() |
fcdc70fdcb9d1125a2f01afc8d71123b29379733 | mc811mc/cracking-python-bootcamp | /the_python_virtual_atm_machine.py | 969 | 3.71875 | 4 | import time
from datetime import datetime
class ATM:
def __init__(self, name, pin):
pass
#else:
# raise ValueError("Invalid Account User")
def deposit(self):
print("{'transaction': ['" + datetime.now() "', " + amount +"]}")
return self.deposit
def withdrawal(self):
print(datetime.now())
return self.withdrawal
def check_balance(self):
print(datetime.now())
return self.check_balance
def get_transactions(self):
print(datetime.now())
return self.get_transactions
def get_withdrawals(self):
print(datetime.now())
return self.get_withdrawals
def get_name(self):
return self.get_name
def pin(self):
return self.pin
name = input("What's your name? ")
print("Accessing", name + "'s Virtual ATM...")
time.sleep(2)
print("Access Authorized")
michael = ATM("Michael", 0815)
michael.deposit(100) |
1dd9db0d99ccb4bb22d75d0dfcdc42f59c9b70ca | M-Sabrina/AdventOfCode2020 | /Tag-15/rambunctious_recitation2.py | 1,245 | 3.5625 | 4 | import numpy as np
def rambunctious_recitation2(contents):
start_numbers = contents.split(",")
numbers_array = np.array([int(number) for number in start_numbers])
turn_dict = {}
for ind, number in enumerate(numbers_array[:-2]):
turn_dict[number] = ind
turn = len(numbers_array) - 1
last = int(numbers_array[-2])
new = int(numbers_array[-1])
while turn < 30000000:
turn_dict[last] = turn - 1
if not (new in turn_dict) and (new != last):
last = new
new = 0
elif not (new in turn_dict) and (new == last):
last = new
new = 1
else:
last = new
new = turn - turn_dict[new]
turn += 1
return last
def test_tag15():
contents = """\
3,1,2"""
solution = rambunctious_recitation2(contents)
expected = 362
if solution != expected:
print("--------------FEHLER---------------------------------------")
print(f" Das Ergebnis des Tests ist {solution} und nicht {expected}")
test_tag15()
with open("Tag-15/input.txt", "rt") as myfile:
contents = myfile.read()
target = rambunctious_recitation2(contents)
print(f"Das Ergebnis von Tag 15 Part 2 ist: {target}")
|
f35e1fd8ae959c88cde48bf9f24ca460704407b3 | dapao1/python | /汉诺塔.py | 412 | 4 | 4 | def hanoi(n,x,y,z):#数量,原位置,缓冲区,目标位置
if n==1:
print(x,'--->',z)#将1从x移动到终点z
else:
hanoi(n-1, x, z, y)#将前n-1个盘子从x移动到y上
print(x,'-->',z)#将最底下的最后一个盘子从x移动到z上
hanoi(n-1,y,x,z)#将y上的n-1歌盘子移动到z上
n=int(input('请输入汉诺塔的层数:'))
hanoi(n,'X','Y','Z')
|
3c582e745d16072b8be72e653c2303770b4983d2 | arthurlambert27/Hangman | /pendu.py | 1,078 | 3.578125 | 4 | import random
def affichage_mot(mot, lettreTrouve):
final = ""
for i in mot:
final = final + "*"
for a in lettreTrouve:
if a == i:
final = final[:-1]
final = final + i
return(final)
rejouer = 1
liste_mot = ["arthur", "chien", "chat", "beau", "moche", "maison", "bouche"]
while rejouer == 1:
choix = random.randint(0, len(liste_mot))
motEnCours = ""
#print(liste_mot[choix])
lettreTrouve = ["1"]
while motEnCours != liste_mot[choix]:
#print(liste_mot[choix])
motEnCours = affichage_mot(str(liste_mot[choix]), lettreTrouve)
print(motEnCours)
section = str(input("Dites une lettre: "))
lettreTrouve.append(str(section))
motEnCours = affichage_mot(str(liste_mot[choix]), lettreTrouve)
print("bravo vous avez gagné! Encore un partie!")
rejouer = int(input("1 pour rejouer, 2 pour arreter le programme :"))
#for i in liste_mot[choix]:
# if slection == i:
|
a91cf716b618752bc6d8e39c3edd1df0935d109d | developerhat/project-folder | /hangman_4.py | 364 | 3.84375 | 4 | #Hangman game
import random
word = random.choice(['Subaru','Tesla','Honda','BMW'])
guessed_letters = []
attempt_number = 7
print(word)
while attempt_number <= 7:
user_input = str(input('Input a letter: '))
if user_input in word:
print("You got it!")
else:
attempt_number -= 1
print("Nope! Attempts left: ", attempt_number)
|
1c5db35bcaff5b9c024aec2976dd3e6c94e482a9 | developerhat/project-folder | /SimplePrograms2.py | 6,168 | 3.8125 | 4 | #Simple Programs 2 to run scripts on
def numbers_sum(lst):
nums_only = []
for i in lst:
if isinstance(i, bool):
continue
elif isinstance(i, int):
nums_only.append(i)
else:
continue
return sum(nums_only)
def unique_sort(lst):
no_dupes = []
for i in lst:
if i not in no_dupes:
no_dupes.append(i)
return sorted(no_dupes)
def count_vowels(txt):
vowels = 'aeiou'
vowel_count = 0
for i in txt:
if i in vowels:
vowel_count += 1
return vowel_count
def sum_two_smallest_nums(lst):
two_lowest_nums = []
positives = []
for i in lst:
if i < 0:
continue
elif i > 0:
positives.append(i)
positives = sorted(positives)
two_lowest_nums.append(positives[0])
two_lowest_nums.append(positives[1])
return sum(two_lowest_nums)
def unique_lst(lst):
unique_positives = []
for i in lst:
if i > 0:
unique_positives.append(i)
no_dupes = []
for i in unique_positives:
if i not in no_dupes:
no_dupes.append(i)
return no_dupes
def filter_list(lst):
ints_only = []
for i in lst:
if isinstance(i, bool):
continue
elif isinstance(i, int):
ints_only.append(i)
return ints_only
def index_of_caps(word):
index_pos = []
for i in word:
if i.isupper():
index_pos.append(word.index(i))
return index_pos
def setify(lst):
no_dupes = []
for i in lst:
if i not in no_dupes:
no_dupes.append(i)
return no_dupes
def cap_to_front(s):
cap_letters = ''
low_letters = ''
for i in s:
if i.isupper():
cap_letters += i
else:
low_letters += i
return cap_letters + low_letters
def sum_two_smallest_nums(lst):
two_smallest_nums = []
no_negs = []
for i in lst:
if i > 0:
no_negs.append(i)
no_negs = sorted(no_negs)
two_smallest_nums.append(no_negs[0])
two_smallest_nums.append(no_negs[1])
return sum(two_smallest_nums)
def replace_vowels(txt, ch):
vowels = 'aeiou'
for i in txt:
if i in vowels:
txt = txt.replace(i, ch)
return txt
#Weird & inefficent solution
def is_in_order(txt):
sorted_txt = []
nosorttxt = []
for i in txt:
sorted_txt.append(i)
nosorttxt.append(i)
if sorted(sorted_txt) == nosorttxt:
return True
else:
return False
def unique_sort(lst):
no_dupes = []
for i in lst:
if i not in no_dupes:
no_dupes.append(i)
return sorted(no_dupes)
def stutter(word):
new_word = ''
for i in word:
new_word += i
return new_word[:2] + '... ' + new_word[:2] + '... ' + new_word +'?'
def sum_two_smallest_nums(lst):
two_nums = []
no_negs = []
for i in lst:
if i > 0:
no_negs.append(i)
else:
continue
no_negs = sorted(no_negs)
two_nums.append(no_negs[0])
two_nums.append(no_negs[1])
return sum(two_nums)
def unique_sort(lst):
no_dupes = []
for i in lst:
if i not in no_dupes:
no_dupes.append(i)
return sorted(no_dupes)
#Come back & do this one!
def remove_enemies(names, enemies):
if len(enemies) < 1:
return names
else:
return names.remove(enemies)
def is_harshad(num):
harshad_num = []
if num == 0:
return False
else:
for i in str(num):
harshad_num.append(int(i))
harshad_num = sum(harshad_num)
if int(num) % harshad_num == 0:
return True
else:
return False
def society_name(friends):
secret_word = ''
word = []
for i in friends:
word.append(i[0])
word = sorted(word)
for i in word:
secret_word += i
return secret_word
def sum_two_smallest_nums(lst):
two_nums = []
pos_nums = []
for i in lst:
if i > 0:
pos_nums.append(i)
pos_nums = sorted(pos_nums)
two_nums.append(pos_nums[0])
two_nums.append(pos_nums[1])
return sum(two_nums)
def disemvowel(string):
vowels = 'aeiou'
for i in string:
if i.lower() in vowels:
string = string.replace(i, '')
return string
def xo(s):
x_count = 0
o_count = 0
for i in s:
if i.lower() == 'x':
x_count += 1
elif i.lower() == 'o':
o_count += 1
if x_count == o_count:
return True
else:
return False
def validate_pin(pin):
digits = []
if len(pin) == 4 or len(pin) == 6:
for
else:
return 'nope'
def secret_society(friends):
result = ''
initials = []
for i in friends:
initials.append(i[0])
initials = sorted(initials)
for i in initials:
result += i
return result
def array_plus_array(arr1, arr2):
lst_1 = sum(arr1)
lst_2 = sum(arr2)
return lst_1 + lst_2
def shortcut(s):
vowels = 'aeiou'
for i in s:
if i in vowels:
s = s.replace(i, '')
return s
def opposite(number):
if number < 0:
return abs(number)
elif number >= 1:
return -number
elif number == 0:
return 0
def feast(beast, dish):
if dish[0] == beast[0] and dish[-1] == beast[-1]:
return True
else:
return False
def max_redigit(num):
if num < 1 or num == 0 or len(str(num)) != 3:
return None
else:
lst_num = []
for i in str(num):
lst_num.append(int(i))
lst_num = sorted(lst_num)[::-1]
res = ''
for i in lst_num:
res += str(i)
return int(res)
def reverse(arg):
if isinstance(arg, bool):
if arg == True:
return False
else:
return True
else:
return 'boolean expected'
def largest_pair_sum(numbers):
two_pair = []
numbers = sorted(numbers)
two_pair.append(numbers[-1])
two_pair.append(numbers[-2])
return sum(two_pair)
|
8ec9acc3d100be489533d4a63ee4a42411c1ad94 | developerhat/project-folder | /SimplePrograms.py | 47,564 | 4.0625 | 4 | #Misc simple programs
#Counting vowels program (Incomplete)
def count_vowels(word):
vowels = 'aeiou'
count = 0
word = word.lower()
for vowel in vowels:
count = word.count(vowel)
print(count)
#Oh shoot it worked! Did this on my own. Had to look up reorganizing & adding FizzBuzz as first check tho
def fizz_buzz(num):
for i in range(num):
if i % 2 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 5 == 0:
print('Buzz')
elif i % 2 == 0:
print('Fizz')
else:
print(i)
def reverse_string(str):
return str[::-1]
#Got through this w minimal help
def is_palindrome(n):
n = str(n)
if n[::-1] == n[0::]:
return True
else:
return False
#Counts number of words in program, did this on my own!
def count_words(str):
for i in str:
return str.count(' ') +1
def add_char_string(str, char, num):
char = str(char)
num = int(num)
return str + (char*num)
def count_to_n(num):
while x != num:
return print(num)
x += 1
def potatoes(string):
return string.count('potato')
def count_true(list):
return list.count(True)
def is_safe_bridge(x):
if ' ' in x:
return False
else:
return True
def halfQUarterEigth(num):
list_results = [num/2, num/.25, num/.83]
return list_results
def space_me_out(str):
return " ".join(str)
def backwords(str):
return str[::-1]
def count_words(str):
return str.count(' ') +1
#Doesn't work!
#Add x chars to start & end of string Edabit
def string_add(string, char, length):
result = string.center(length, char)
return result
#What! Converts string equation to actual equation.
def equation(s):
return eval(s)
#wow this worked! Cheated tho, used stackoverflow
def count_syllables(str):
count = 0
str = str.lower()
vowels = 'aeiouy'
for i in range(0, len(str)):
if str[i] in vowels and str[i -1] not in vowels:
count +=1
if count == 0:
count+=1
return count #Trying to count syllables... hm..
#Doesn't work!
#Need for a way to say "If all chars in this string"
#OH SHIT! Got it to work!
#Switched all(i) to all(str)
def get_case(str):
for i in str:
if all(str) == str.isupper():
return 'upper'
elif all(str) == str.islower():
return 'lower'
else:
return 'mixed'
#My solution above, verbose
#Generator solution?
#return any(str.isupper() for i in str)
def has_key(dictionary, key):
if key in dictionary:
return True
else:
return False
#Works
#Fixed this!
def wumbo(words):
for i in words:
if i == 'M':
return words.replace('M', 'W')
#elif i == 'W':
# return words.replace('W', 'M')
#Not working as planned
def simplePigLatin(string):
return string[:0] #+ 'ay'
#Got it!
def has_same_bread(lst1,lst2):
if lst1[0] == lst2[0] and lst1[-1] == lst2[-1]:
return True
else:
return False
def yeahNope(b):
return "yeah" if b == True else "nope"
#Oh shit! Got this through w some help
def additive_inverse(lst):
for x in range(len(lst)):
lst[x] = -lst[x]
return lst
#Got through this w a lil help!
#It works but is rejected by Edabit
#Found out why rejected - added final_list
def even_odd_partition(lst):
even_list = []
odd_list = []
for i in lst:
if i % 2 == 0:
even_list.append(i)
else:
odd_list.append(i)
final_list = [even_list, odd_list]
return final_list
def long_burp(num):
return 'Bu' + num * 'r' + 'p'
def is_it_true(relation):
return eval(relation)
#Simple
def count_claps(txt):
return txt.count('C')
#Does not work
def can_nest(list1, list2):
if list1.min(list1) > list2.min(list2) and list1.max(list1) < list2.max(list2):
return True
else:
return False
#For every 6 cups, add 1
#not working
#FIGURE THIS OUT?!
def total_cups(n):
for x in range(n):
if x / 6 == 0:
return n + 1
#WTF? Why isn't this one working. Seems so simple
#NEver returns 1
def flipBool(b):
if b == True or 1:
return 0
elif b == False or 0:
return 1
def divide(a,b):
try:
return a/b
except:
print("Can't divide by Zero!")
def one_odd_one_even(n):
number = len(n)
#Need ot finish, book marked
def reverse_title(txt):
return txt.swapcase()
def googlify(n):
if n <= 1:
return 'invalid'
else:
return 'g' + ('o'*n) + 'gle'
#Having trouble incrementing
#NVM got this right! Solved it by creating new list, and appending new values to that list
#Instead of modifying list in place
def increment_items(lst):
new_list = []
for i in lst:
i +=1
new_list.append(i)
return new_list
def has_same_bread2(lst1,lst2):
if lst1[0] == lst2[0] and lst1[-1] and lst2[-1]:
return True
else:
return False
#Wow needevd help looked in October.py code
#My solution was to use count, but didn't work
#Instead iterate through
def capital_letters(txt):
cap_letters_counter = 0
for i in txt:
if i.isupper():
cap_letters_counter += 1
return cap_letters_counter
def reverse_capitalize(txt):
txt = txt[::-1]
return txt.upper()
def less_than_100(num1, num2):
if num1 + num2 < 100:
return True
else:
return False
def divides_evenly(a,b):
if a % b == 0:
return True
else:
return False
#Finish this!
def search(lst, item):
for item in lst:
return lst.index(item)
def prevent_distractions(txt):
for i in txt:
if 'anime' or 'meme' or 'vine' or 'roasts' or 'Danny DeVito' in txt:
return 'NO!'
else:
return "Safe watching!"
#Got it on my own! Wow! memorized, no help
def is_identical(s):
if s[::-1] == s[::]:
return True
else:
return False
def and(a,b):
if a and b == True:
return True
else:
return False
#Damn figured this out!
def rev(n):
n = str(abs(n))
return n[::-1]
#Wow, was using or True & or False here but no need!
def flip_bool(b):
if b == 1:
return 0
elif b == 0:
return 1
def F_to_C(f):
return (f - 32) * (5/9)
def C_to_F(c):
return (c * 9/5) + 32
def get_first_value(number_list):
return number_list[0]
#this one's a bit more complicated, solve it later hehe
#Requires 0 count first
def count_syllables(txt):
return txt.count()
#Damn gotta figure this out!
#Got it! Switched logic from is 13, to if not 13
def unlucky_13(nums):
new_list = []
for i in nums:
if i % 13 != 0:
new_list.append(i)
return new_list
#Couldn't figure this out!!
def hello_world(num):
if num % 5 and num % 3 == 0:
return 'Hello World'
elif num % 3 == 0:
return 'Hello'
elif num % 5 == 0:
return 'World'
def hello_world(num):
if num % 15 == 0:
return 'Hello World'
elif num % 3 == 0:
return 'Hello'
elif num % 5 == 0:
return 'World'
def get_multiplied_list(lst):
new_list = []
for i in lst:
i = i * 2
new_list.append(i)
return new_list
def remove_none(lst):
new_list = []
for i in lst:
if i != None:
new_list.append(i)
return new_list
def has_spaces(txt):
if ' ' in txt:
return True
else:
return False
#Doesn't work gotta return number of capital letters
def capital_letters(txt):
for i in txt:
if i.isupper():
return i.count(txt)
def k_to_k(n, k):
if k**k == n:
return True
else:
return False
#Got from hacker rank
def conditional(n):
if n % 2 == 1:
return 'Weird'
elif n % 2 == 0 and n in range(2,5):
return 'Not Weird'
elif n % 2 == 0 and n in range(6,20):
return 'Weird'
elif n % 2 == 0 and n > 20:
return 'Not Weird'
#Got it w minimal help!
#Was fucken up w/ max(lst), wrote it as lst.max()
def difference_max_min(lst):
for i in lst:
return max(lst) - min(lst)
def concat_list(lst1,lst2):
return lst1 + lst2
#DAMN! Pretty much solved this on my own
#Had trouble w/ format for count(), was using count(hashes) instead of hashes.count()
def hash_plus_count(txt):
hashes = []
pluses = []
for i in txt:
if i == '#':
hashes.append(i)
elif i == '+':
pluses.append(i)
return [hashes.count('#'), pluses.count('+')]
#Ouh this was a fun one!
#Solved on my own!! OH SHIT!
def remove_none(lst):
new_list = []
for i in lst:
if i != None:
new_list.append(i)
return new_list
def get_word(left, right):
return left.title() + right
#DOESNT WORK! FIGURE THIS ONE OUT
#GOT IT!
def is_palindrome(txt):
#rev_text = reverse(txt)
#Dont need rev_text, since the code below is already reversed
if txt[::-1] == txt:
return True
else:
return False
def first_last(lst):
new_list = []
new_list.append(lst[0])
new_list.append(lst[-1])
return new_list
#Returns the mean of number
def mean(nums):
result = sum(nums) / len(nums)
return round(result, 1)
#Swaps the cases
def reverse_case(txt):
return txt.swapcase()
def find_digit_amount(num):
num = str(num)
return len(num)
#Checks if all elementsi n list are same
#Not sure how count does this?
def jackpot(result):
if result.count(result[0]) == len(result):
return True
else:
return False
#DAMN! DID THIS ON MY OWN!
def count_vowels(txt):
vowels = 'aeiou'
vowel_count = 0
for i in txt:
if i in vowels:
vowel_count += 1
return vowel_count
#Got it down yee yee
#One of the first few problems I solved on Edabit
def no_odds(lst):
no_odds = []
for i in lst:
if i % 2 == 0:
no_odds.append(i)
return no_odds
#Not working?
def greet_people(names):
for i in names:
result = 'Hello '.join(i)
return result
#Doesn't work yet, want to sum numbers up to integer given
def add_up_to(n):
for i in range(0, n):
i += i
return i
#OH SHOOT! Got this right no help
def findLargestNums(lst):
new_list = []
for i in names:
new_list.append(i)
return new_list.join('Hello, ', new_list[0])
def get_fillings(sandwich):
new_list = []
for i in sandwich:
if i != 'bread':
new_list.append(i)
return new_list
def get_only_evens(nums):
new_list = []
for i in range(0, nums):
if i % 2 == 0:
new_list.append(i)
return new_list
#I GOT IT! BUT DOESNT do it in right format, why?
#Oh got it! Just add as an integer
def reverse_list(num):
new_list = []
for i in str(num):
new_list.append(int(i))
return new_list[::-1]
#?? Doesn't work
def measure_the_depth(lst):
return str(lst).count('[]')
def is_avg_whole(arr):
result = sum(arr) / len(arr)
if result.is_integer():
return True
else:
return False
#Got it!
def divisible(lst):
result = 1
for i in lst: #This for loop returns the product of all ele in list
result = result * i
if result % sum(lst) == 0:
return True
else:
return False
#EZ
#Tried doing it in 1 line initially: return(abs(sum(lst))), but didn't work
def get_abs_sum(lst):
new_list = []
for i in lst:
new_list.append(abs(i))
return sum(new_list)
#Thought for sure this would work for 2D matrix
#Only works w/ 1 array
def sum_of_evens(lst):
even_list = []
for i in lst:
if (i % 2 == 0):
even_list.append(i)
return sum(even_list)
#got this!
#Could also use count = 0, count=+1
def count_evens(nums):
even_nums = []
for num in nums:
if num % 2 == 0:
even_nums.append(num)
return len(even_nums)
#CodingBat
def big_diff(nums):
return max(nums) - min(nums)
#CodingBat
def make_ends(nums):
new_list = []
new_list.append(nums[0])
new_list.append(nums[-1])
return new_list
#CodingBat
def sum2(sums):
new_list = []
new_list.append(sums[0])
new_list.append(sums[1])
return sum(new_list)
#1st list nests inside 2nd
def can_nest(list1,list2):
if min(list1) > min(list2) and max(list1) < max(list2):
return True
else:
return False
#Want to count digits without using len()
#Got it! Was trying to use a list, but use count in this case
#Count() doesn't work here
def length(str):
count = 0
for i in str:
count += 1
return count
#Can't figure out the formatting here
#Getting closer! tried joining while the string is reversed
#Couldn't use join() method, used my own
def reverse_and_not(i):
result = str(i)
i = str(i)
return int(i[::-1] + result)
#Increment +1 for odd, -1 for even
#Got 'em! Getting better!!
def transform(lst):
final_list = []
for i in lst:
if i % 2 == 0:
i -= 1
final_list.append(i)
elif i % 2 != 0:
i += 1
final_list.append(i)
return final_list
#Couldn't get this, return later
def add_odd_to_n(n):
num_list = range(n)
for i in num_list:
if i % 2 != 0:
sum_result = sum(num_list)
return sum_result
#def add_odd_to_n(n):
#sum = int()
#for i in range(n):
#if i % 2 != 0:
#Incomplete return later
def max_total(nums):
sorted = sort(nums)
result = sum(sorted)
return result
#How do you inlcude integer? 1 should return 1,0
#Figured it out, must add +1 so that it counts itself
def countdown(start):
count = []
for i in range(start + 1):
count.append(i)
return count[::-1]
def calculate_scores(txt):
return [txt.count('A'), txt.count('B'), txt.count('C')]
#Logic practice
def should_serve_drinks(age, on_break):
if age >= 21 and on_break == False:
return True
elif age >= 21 and on_break == True:
return False
elif age <= 20 and on_break == False:
return False
elif age <= 20 and on_break == True:
return False
#Doesn't work..
def sum_first_n_nums(lst, n):
for n in range(lst):
return sum(n)
#Revised code, nice!!!
def sum_first_n_nums(lst, n):
first_n_num = lst[:n]
return sum(first_n_num)
#Doens't work?
def word_lengths(lst):
for i in lst:
return lst.count(len(i))
#My new solution! Look @ the progress
def word_lengths(lst):
word_lengths = []
for i in lst:
word_lengths.append(len(i))
return word_lengths
#Redid this for memory
def divisible(lst):
product = 1
for i in lst:
product = i * product
if product % sum(lst) == 0:
return True
else:
return False
def transform(lst):
new_list = []
for i in lst:
if i % 2 == 0:
i = i -1
new_list.append(i)
elif i % 2 != 0:
i = i + 1
new_list.append(i)
return new_list
#Redid this for memory
#Had to go back & check former answer
def sum_first_n_nums(lst, n):
first_n_num = lst[::n]
return sum(first_n_num)
#Logic here, redid for practice
def can_nest(list1, list2):
if min(list1) > min(list2) and max(list1) < max(list2):
return True
else:
return False
#Redid this for memory
def word_lengths(lst):
word_lengths = []
for i in lst:
word_lengths.append(len(i))
return word_lengths
#redid this one from memory too, nice!!
def reverse_list(num):
final_list = []
num = str(num)
for i in num:
final_list.append(int(i))
return final_list[::-1]
#Got this on my own!
#Figured out how to "APPEND" to strings
def detect_word(txt):
new_word = ''
for i in txt:
if i.islower():
new_word +=i
return new_word
#doesn't work, calculation is off by a small margin
#Probably related to the range
def sum_even_nums_in_range(start, stop):
even_nums = []
for i in range(start, stop):
if i % 2 == 0:
even_nums.append(i)
return sum(even_nums)
#Works, but trying to only extract unique elements
#WIP
def count_unique(s1, s2):
unique_chars = ''
for i in s1, s2:
if i not in unique_chars:
unique_chars += i
return len(unique_chars)
#Work in progress!
def filter_digit_length(lst, num):
filtered_list = []
for i in lst:
if len(str(i)) <= len(str(num)):
filtered_list.append(i)
return filtered_list
#Takes a string & adds all ecen-indexed & odd-indexed together
#Getting close, but missing the last character.. how
#Figured it out, using -1 only counts from the right most of the string (in reverse)
#So, key is to not specify this & use 0:: & 1::
def index_shuffle(txt):
even_words = txt[0::2]
odd_words = txt[1::2]
return even_words + odd_words
#The challenges was to do this without converting to INT, but couldn't figure it out, oh well! Works
def smaller_num(n1, n2):
n1, n2 = int(n1), int(n2)
lst = [n1, n2]
sorted_list = sorted(lst)
return str(min(sorted_list))
#Not complete, WIP, need to yse all()
def check_all_even(lst):
for i in lst:
if i % 2 == 0:
return True
else:
return False
#Work on this! To be continued
def add_nums(nums):
nums = nums.split(', ')
return sum(nums)
def add_nums(nums):
return sum(eval(nums))
def add_nums(nums):
nums = nums.split(', ')
return nums
#Work in progress, bookmarked
def mirror(lst):
new_list = []
for i in lst:
new_list.append(i)
new_list.append(lst[::-1])
return new_list
#Gotem
def mirror(lst):
return lst + lst[-2:]
#Got it on this one! took a lot of trial & error
def mirror(lst):
return lst + lst[-2::-1]
#Thought this would be more simple, got it down tho!
#Nice
def str_is_in_order(txt):
lst = []
for i in txt:
lst.append(i)
lst = sorted(lst)
sorted_word = ''.join(lst)
if txt == sorted_word:
return True
else:
return False
#Remove 1st last not complete
#Figure out list slicing notation
def remove_first_last(txt):
new_word = ''
for i in txt:
new_word.append(i[0])
new_word.append(i[-1])
return txt
#Remove 1st last not complete
#Figure out list slicing notation
def remove_first_last(txt):
new_word = []
for i in txt:
new_word.append(txt[1:-2])
return new_word
#Got it! Strengthening list comprehension!!!
def remove_first_last(txt):
if len(txt) <= 2:
return txt
else:
return txt[1:-1]
#Damn got it down! Noice
#Nice, got stuck on reverting negative to positive but got it down!!
def negate(lst):
negated_list = []
for i in lst:
if i < 0:
i = -i
negated_list.append(i)
elif i > 0:
i = -+i
negated_list.append(i)
return negated_list
#Works but returns True instead of False for last test in Edabit
def hurdle_jump(hurdles, jump_height):
if len(hurdles) <= 0:
return True
else:
for i in hurdles:
if len(hurdles) <= jump_height: #Hurdler can clear height if jump height is less than or equal to hurdle height
return True
else:
return False
#2nd attempt, doesn't work
def hurdle_jump(hurdles, jump_height):
if len(hurdles) < 0:
return True
else:
for i in range(hurdles):
if jump_height >= i:
return True
else:
return False
def exists_higher(lst, n):
if len(lst) < 0:
return False
else:
for i in lst:
if i >= n:
return True
else:
return False
def exists_higher(lst, n):
for i in lst:
if i >= n:
return True
else:
return False
#Wow, keep it simple!!
#Upper 2 code is complex, no need for the loop. The instructions tricky interpretation
def exists_higher(lst, n):
if len(lst) < 0:
return False
elif max(lst) >= n:
return True
else:
return False
#Simple problem
#not completed, adds instead of removing
def join_path(portion1, portion2):
if '/' not in portion1 and portion2:
return portion1 + '/' + portion2
elif '/' in portion1:
return portion1.strip('/') + '/' + portion2
elif '/' in portion2:
return portion2.strip('/') + '/' + portion2
#Returning only words that are 4 letters, WIP
def is_four_letters(lst):
four_letters = []
for i in lst:
if len(i) == 4:
four_letters.append(i)
return four_letters
#WIP, look @ bookmark
def amplify(num):
final_list = []
for i in range(num):
if i % 4 == 0:
i = i * 10
final_list.append(i)
else:
final_list.append(i)
return final_list
#Good problem to solve, keep wokrin
def index_of_caps(word):
cap_indexes = []
for i in range(word):
if i.isupper():
cap_indexes.append(i)
return cap_indexes
#Resolved out of memory (Sunday)
def reverse_list(num):
reversed_list = []
num = str(num)
for i in num:
reversed_list.append(int(i))
return reversed_list[::-1]
#Resolved out of memory (Sunday)
def reverse_title(txt):
titled_txt = txt.title()
return titled_txt.swapcase()
#Resolved out of memory (Sunday)
def increment_items(lst):
new_list = []
for i in lst:
i += 1
new_list.append(i)
return new_list
#Redid from memory
def has_same_bread(lst1, lst2):
if lst1[0] == lst2[0] and lst1[-1] == lst2[-1]:
return True
else:
return False
#Needed hints on this one
def sum_first_n_nums(lst, n):
first_n_num = lst[:n]
return sum(first_n_num)
#Redid from memory
def detect_word(txt):
new_word = ''
for i in txt:
if i.islower():
new_word += i
return new_word
#Memory
def increment_items(lst):
new_list = []
for i in lst:
i+=1
new_list.append(i)
return new_list
#Memory
def length(s):
str_len = 0
for i in s:
str_len += 1
return str_len
#Good string comprehension practice
def modify_last(txt, n):
last_char = txt[-1] * n
return txt[0:-1] + last_char
#Memory, nice!
def is_four_letters(lst):
four_list = []
for i in lst:
if len(i) == 4:
four_list.append(i)
return four_list
#Complete this
def spelling(txt):
word = []
for i in txt:
word.append(i)
return word
#Practiced using eval
def greater_than_one(frac):
if eval(frac) > 1:
return True
else:
return False
#Doesn't work (OLD CODE)
def owofied(sentence):
for x in sentence:
if x == 'i' or x == 'e':
if 'i' in x:
x.replace('wi')
elif 'e' in x:
x.replace('we')
return x, sentence
#New code, WIP
def owofied(sentence):
new_sentence = ''
for x in sentence:
if x == 'i':
x.replace(x, 'wi')
new_sentence += x
elif x == 'e':
x.replace(x, 'we')
new_sentence += x
return x, new_sentence
#endswith() practice
def check_ending(str1, str2):
if str1.endswith(str2):
return True
else:
return False
#WIP
#Trying to strip chars from sentence
def strip_sentence(txt, chars):
new_string = txt.replace(chars, '') #Only works with 1 letter
return new_string
#WIP
def both(n1, n2):
if n1 and n2 > 0 or n1 and n2 < 0 or n1 and n2 == 0:
return True
else:
return False
#Doesn't include number itself
def find_even_nums(num):
new_list = []
for i in range(num):
if i % 2 == 0:
new_list.append(i)
return new_list
#Redid from memory
def reverse_and_not(i):
str_integer = str(i)
return int(str_integer[::-1] + str_integer)
#Memory
def reverse_title(txt):
title_case = txt.title()
return title_case.swapcase()
def get_case(txt):
for i in txt:
if i.isupper():
return 'upper'
elif i.islower():
return 'lower'
elif i != i.lower() and i != i.upper():
return 'mixed'
def get_case(txt):
for i in txt:
if not i.isupper() and not i.islower():
return 'mixed'
elif i.islower():
return 'lower'
elif i.isupper():
return 'upper'
#3 attempts from memory, nice!
def get_case(txt):
mixed_case = not txt.isupper() and not txt.islower()
for i in txt:
if mixed_case == True:
return 'mixed'
elif i.islower():
return 'lower'
elif i.isupper():
return 'upper'
#Memory
def word_lengths(lst):
wordlen_list = []
for i in lst:
wordlen_list.append(len(i))
return wordlen_list
#Counting cap words, memory
def count_caps(word):
cap_letters = 0
for i in word:
if i.isupper():
cap_letters += 1
return cap_letters
#Memory
def modify_last(txt, n):7
last_letter = txt[-1]
return txt[0:-1] + (last_letter * n)
#memory
def long_burp(num):
num = num - 1
word = "Burp"
return word[0:2] + (word[2] * num) + word[2::]
#Memory :)
def is_it_true(relation):
if eval(relation) == True:
return True
else:
return False
#Memory
def minus_one(lst):
new_list = lst[0:-1]
return new_list
#Memory
def reverse_title(txt):
first_cap = txt.title()
return first_cap.swapcase()
#Failed attempt, revisit :(
def fizz_buzz(num):
for i in range(num):
if i % 3 == 0 and i % 5 == 0:
return 'FizzBuzz'
elif i % 3 == 0:
return 'Fizz'
elif i % 5 == 0:
return 'Buzz'
#Memory
def max_difference(num):
return max(num) - min(num)
#Memory
def rev(n):
n = abs(n)
n = str(n)
return n[::-1]
#Memory, nice!
def word_lengths(lst):
wordlen_list = []
for i in lst:
wordlen_list.append(len(i))
return wordlen_list
#Memory, nice 3
def get_multiplied_list(lst):
mult_list = []
for i in lst:
i = i*2
mult_list.append(i)
return mult_list
#memory
def reverse_list(num):
num = str(num)
num_list = []
for i in num:
num_list.append(int(i))
return num_list[::-1]
#Easy
def first_last(name):
return name[0] + name[-1]
#Easy
def repetition(txt, n):
return txt*n
#Easy
#Took awhile tho, needed hints
#Keep working!
def detect_word(txt):
low_word = ''
for i in txt:
if i.islower():
low_word += i
return low_word
#From w3resource
def csv_input(nums):
nums_list = []
for i in str(nums):
nums_list.append(int(i))
return nums_list
#INteresting one! Goal is to get 5+55+555
def w3_problem1(n):
n2 = str(n) + str(n)
n3 = str(n) + str(n) + str(n)
return n + int(n2) + int(n3)
#New problem, nice
def yen_to_usd(yen):
return round(yen / 107.5, 2)
#Doesn't work invalid syntax if 2=2? Solve
def is_it_true(relation):
if eval(relation) == True:
return True
else:
return False
#Memory! Nice!
def length(s):
count = 0
for i in s:
count +=1
return count
def first_last(name):
return name[0] + name[-1]
def potatoes(potato):
return potato.count('potato')
def highest_digit(num):
num = str(num)
num_list = []
for x in num:
num_list.append(int(x))
return max(num_list)
def is_odd(num):
if num % 2 == 1:
return True
else:
return False
def new_word(word):
return word[1::]
def football_points(wins, draws, losses):
wins = wins * 3
losses = 0
return wins + draws + losses
def give_me_something(a):
new_word = 'something ' + a
return new_word
def bomb(txt):
if 'bomb' in txt.lower():
return 'Duck!!!'
else:
return "There is no bomb, relax"
#trying to return last index item but not working
def last_ind(lst):
if not:
return None
else:
return lst[-1]
#Figure out eval syntax
def calculate(num1, num2, op):
op = str(op)
return eval(op, num1, num2)
def modify_last(txt, n):
last_char = txt[-1] * n
return txt[0:-1] + last_char
def highest_digit(num):
num_list = []
for i in str(num):
num_list.append(int(i))
return max(num_list)
def repetition(txt, n):
return txt * n
#Complicated this answer haha
def count_true(lst):
true_list = []
for i in lst:
if i == True:
true_list.append(i)
return true_list.count(True)
def get_fillings(sandwich):
fillings = sandwich[1:-1]
return fillings
def reverse_list(num):
lst = []
for i in str(num):
lst.append(int(i))
return lst[::-1]
def equation(s):
return eval(s)
def reverse_title(txt):
rev_text = txt.title()
return rev_text.swapcase()
def last_ind(lst):
if len(lst) < 1:
return None
else:
return lst[-1]
def second_largest(lst):
sorted_list = []
for i in lst:
sorted_list.append(i)
sorted_list.sort()
return sorted_list[-2]
def str_odd_or_even(word):
if len(word) % 2 == 0:
return True
else:
return False
def list_to_string(lst):
string = ''
for i in lst:
string += str(i)
return string
def list_less_than_100(lst):
if sum(lst) < 100:
return True
else:
return False
def make_pair(num1, num2):
return [num1, num2]
def count_vowels(txt):
vowels = 'a'
vowel_count = 0
for i in txt:
if vowels in txt:
vowel_count +=1
return vowel_count
#Look at old program.. damn good effort
#Failed this, couldn't figure out how to return # of parameters passsed
def number_args():
obj_list = []
for i in input:
obj_list.append(i)
return len(obj_list)
def min_max(nums):
return [min(nums),max(nums)]
#Damn! Got this!!!
def detect_word(txt):
word = ''
for i in txt:
if i.islower():
word += i
return word
#1 line
def get_fillings(sandwich):
return sandwich[1:-1]
def bomb(txt):
if 'bomb' in txt.lower():
return 'Duck!!!'
else:
return 'There is no bomb, relax.'
def less_than_100(lst):
if sum(lst) < 100:
return True
else:
return False
def say_hello_bye(name, num):
if num == 1:
return "Hello " + name.title()
elif num == 0:
return "Bye " + name.title()
def list_to_string(lst):
word = ''
for i in lst:
word += str(i)
return word
def num_to_dashes(num):
return num * '-'
def no_odds(lst):
even_vals = []
for i in lst:
if i % 2 == 0:
even_vals.append(i)
return even_vals
def unlucky_13(nums):
no_13_lst = []
for i in nums:
if i % 13 != 0:
no_13_lst.append(i)
return no_13_lst
def number_syllables(word):
return word.count('-') + 1
def is_avg_whole(arr):
avg_lst_num = sum(arr) / len(arr)
if avg_lst_num.is_integer():
return True
else:
return False
def highest_digit(num):
num_list = []
for i in str(num):
num_list.append(int(i))
return max(num_list)
def cap_me(lst):
capped_list = []
for i in lst:
capped_list.append(i.title())
return capped_list
def word_lengths(lst):
word_length = []
for i in lst:
word_length.append(len(i))
return word_length
#Needed help on this one, went back & looked at code
def check_num_inlist(lst, el):
if el in lst:
return True
else:
return False
def smaller_num(n1, n2):
n1 = int(n1)
n2 = int(n2)
min_num = min(n1, n2)
return str(min_num)
#Can't figure this one out!
def countdown(start):
pass
def reverse_capitalize(txt):
rev_text = txt[::-1]
return rev_text.swapcase()
def is_identical(s):
pass
#Solve this!!
def get_abs_sum(lst):
abs_list = []
for i in lst:
abs_list.append(abs(i))
return sum(abs_list)
def get_multiplied_list(lst):
mult_list = []
for i in lst:
mult_list.append(i*2)
return mult_list
def last_ind(lst):
if len(lst) > 0:
return lst[-1]
else:
return None
def hash_plus_count(txt):
hashes = txt.count('#')
pluses = txt.count('+')
if len(txt) > 0:
return [hashes, pluses]
else:
return [0,0]
#Do this one! Check if all lower case
#checked former answer on this one
#Couldn't get hthe syntax down
def get_case(txt):
if all(txt) == txt.isupper():
return 'upper'
elif all(txt) == txt.islower():
return 'lower'
else:
return 'mixed'
def difference_max_min(lst):
return max(lst) - min(lst)
def is_palindrome(txt):
if txt == txt[::-1]:
return True
else:
return False
def even_odd_partition(lst):
even_list = []
odd_list = []
for i in lst:
if i % 2 == 0:
even_list.append(i)
else:
odd_list.append(i)
return [even_list,odd_list]
def calculate_scores(txt):
a = txt.count('A')
b = txt.count('B')
c = txt.count('C')
return [a,b,c]
def min_max(nums):
min_max_lst = min(nums), max(nums)
return list(min_max_lst)
def reverse_and_not(i):
i = str(i)
reversed = i[::-1] + i
return int(reversed)
#Needed help on this one
def list_to_string(lst):
strng = ''
for i in lst:
strng += str(i) #Had to add str() here
return strng
def is_leap(year):
if year % 400 == 0:
return True
elif year % 4 == 0 and year % 100 != 0:
return True
else:
return False
def find_digit_amount(num):
result = len(str(num))
return result
def get_fillings(sandwich):
return sandwich[1:-1]
def double_char(txt):
word = ''
for i in txt:
word += (i*2)
return word
#Good shit!
def next_in_line(lst, num):
if len(lst) <= 0:
return 'No list has been selected'
else:
lst.append(num)
del lst[0]
return lst
def oddeven(lst):
odd_list = []
even_list = []
for i in lst:
if i % 2 == 0:
even_list.append(i)
else:
odd_list.append(i)
if len(odd_list) > len(even_list):
return True
else:
return False
def filter_list(l):
int_only = []
for i in l:
if isinstance(i, int):
int_only.append(i)
return int_only
def secret_society(friends):
friends.sort()
society_name = ''
for i in friends:
society_name += str(i[0])
return society_name.upper()
#was over complicating it, commented out!
#Good shit!
def cap_to_front(s):
low_digits = ''
hi_digits = ''
for i in s:
if i.islower():
low_digits += str(i)
else:
hi_digits += str(i)
result = sorted(hi_digits+low_digits)
#sorted_str = ''
#for x in result:
# sorted_str += str(x)
return hi_digits +low_digits
def is_valid_pin(pin):
if len(pin) == 4 or len(pin) == 6:
for i in pin:
if i.isdigit():
return True
else:
return False
else:
return False
#Almost.. only returns index position of 1st upper
def index_of_caps(word):
in_list = []
for x in word:
if x.isupper():
in_list.append(word.index(x))
return in_list
def filter_list(lst):
no_strings = []
for i in lst:
if i.isdigit():
no_strings.append(i)
return no_strings
#Only returns integers
def filter_list(lst):
no_strings = []
for i in lst:
if isinstance(i, int):
no_strings.append(i)
return no_strings
def return_only_integer(lst):
int_only = []
for i in lst:
if isinstance(i, int):
int_only.append(i)
return int_only
def mean(num):
sum_list = []
for i in str(num):
sum_list.append(int(i))
result = sum(sum_list)
final_result = result / len(str(num))
return final_result
def count_vowels(txt):
vowels = 'aeiou'
vowel_count = 0
for i in txt:
if i in vowels:
vowel_count += 1
return vowel_count
def oddeven(lst):
even_nums = []
odd_nums = []
for i in lst:
if i % 2 == 0:
even_nums.append(i)
else:
odd_nums.append(i)
if len(odd_nums) > len(even_nums):
return True
else:
return False
def to_list(num):
num_list = []
for i in str(num):
num_list.append(int(i))
return num_list
def to_number(lst):
num_result = ''
for i in lst:
num_result += str(i)
return int(num_result)
def alphabet_soup(txt):
sorted_txt = []
for i in txt:
sorted_txt.append(i)
result = sorted(sorted_txt)
str_result = ''
for i in result:
str_result += str(i)
return str_result
def is_symmerical(num):
rev_txt = str(num)
if rev_txt[::-1] == str(num):
return True
else:
return False
def count_vowels(txt):
vowels = 'aeiou'
vowel_count = 0
for i in txt:
if i in vowels:
vowel_count += 1
return vowel_count
def oddeven(lst):
even_nums = []
odd_nums = []
for i in lst:
if i % 2 == 0:
even_nums.append(i)
else:
odd_nums.append(i)
if len(odd_nums) > len(even_nums):
return True
else:
return False
def next_in_line(lst, num):
new_list = []
if len(lst) <= 0:
return 'No list has been selected'
else:
for i in lst:
new_list.append(i)
new_list.append(num)
return new_list[1::]
def double_char(txt):
new_char = ''
for i in txt:
new_char += (i*2)
return new_char
def split(txt):
vowels = 'aeiou'
vowel_letters = []
cons_letters = []
for i in txt:
if i in vowels:
vowel_letters.append(i)
else:
cons_letters.append(i)
#return vowel_letters, cons_letters
#vowel_str = ''
#cons_str = ''
#for x in vowel_letters, cons_letters:
# if x in vowels:
# vowel_str += x
# else:
# cons_str += x
#return vowel_str
#WOW! Simple solution! Look at what you tried doing while lit^^
def split(txt):
vowels = 'aeiou'
vowel_letters = ''
cons_letters = ''
for i in txt:
if i in vowels:
vowel_letters += i
else:
cons_letters += i
return vowel_letters + cons_letters
#return vowel_letters, cons_letters
#vowel_str = ''
#cons_str = ''
#for x in vowel_letters, cons_letters:
# if x in vowels:
# vowel_str += x
# else:
# cons_str += x
#return vowel_str
def sort_descending(num):
nums = []
for i in str(num):
nums.append(int(i))
sorted_nums = sorted(nums)
rev_sorted_nums = sorted_nums[::-1]
str_sorted = ''
for i in rev_sorted_nums:
str_sorted += str(i)
return int(str_sorted)
#Damn! Almost had this one
#Go back to this
#Negative numbers shouldn't be counted, bookmarked
def sum_two_smallest_nums(lst):
lowest_num = min(lst)
for i in lst:
if i == lowest_num:
lst.remove(i)
second_low = min(lst)
return lowest_num + second_low
#Damn! CANT figure this out! So close
#Using edge case [] empty string still returns 0,0
#Keep solving this
def sum_neg(lst):
positive_nums = 0
negative_nums = []
for i in lst:
if i > 0:
positive_nums += 1
elif i < 0:
negative_nums.append(i)
elif len(lst) < 1:
return lst
neg_sum = sum(negative_nums)
final_list = []
final_list.append(positive_nums)
final_list.append(neg_sum)
return final_list
def sum_neg(lst):
positive_nums = 0
negative_nums = []
for i in lst:
if len(lst) < 1:
return lst
elif i > 0:
positive_nums += 1
elif i < 0:
negative_nums.append(i)
neg_sum = sum(negative_nums)
final_list = []
if len(final_list) > 0:
return lst
else:
final_list.append(positive_nums)
final_list.append(neg_sum)
return final_list
def numbers_sum(lst):
integers = []
not_int = []
for i in lst:
if isinstance(i, int):
integers.append(i)
elif isinstance(i, bool):
not_int.append(i)
return sum(integers)
def numbers_sum(lst):
integers = []
not_int = []
for i in lst:
if isinstance(i, bool):
not_int.append(i)
elif isinstance(i, int):
integers.append(i)
return sum(integers)
def reverse(txt):
rev_text = ''
for i in txt:
rev_text += i
rev_text = rev_text[::-1]
return rev_text.swapcase()
def count_vowels(txt):
vowel_count = 0
vowels = 'aeiou'
for i in txt:
if i.lower() in vowels:
vowel_count += 1
return vowel_count
def return_only_integer(lst):
ints_only = []
bool_only = []
for i in lst:
if isinstance(i, bool):
bool_only.append(i)
elif isinstance(i, int):
ints_only.append(i)
return ints_only
def unique_sort(lst):
no_duplicates = []
for i in lst:
if i not in no_duplicates:
no_duplicates.append(i)
return sorted(no_duplicates)
def is_symmetrical(num):
if str(num) == str(num)[::-1]:
return True
else:
return False
def alphabet_soup(txt):
sorted_str = []
for i in txt:
sorted_str.append(i)
res_sorted = ''
sorted_str = sorted(sorted_str)
for i in sorted_str:
res_sorted+= i
return res_sorted
def next_in_line(lst, num):
if len(lst) < 1:
return 'No list has been selected'
else:
lst.append(num)
return lst[1::]
def reverse(txt):
return txt.swapcase()[::-1]
def letters_only(txt):
letters_only = ''
for i in txt:
if i.isalpha():
letters_only += i
return letters_only
def numbers_sum(lst):
numbers_only = []
for i in lst:
if isinstance(i, bool):
continue #Woah! Actually error handled here!
elif isinstance(i, int):
numbers_only.append(i)
return sum(numbers_only)
#? Getting lost here. REplaces some vowels but not all..
#GOt it! Simple, just had wrong indexes in places
#Didn't wrk tho was exclude vowels
def replace_vowels(txt, ch):
vowels = 'aeiou'
for i in txt:
if i.lower() in vowels:
result = txt.replace(i, ch)
return result
#Someone elses solutoin
def replace_vowels(txt, ch):
for char in txt:
if char in "aeiou":
txt = txt.replace(char,ch)
return txt
def sum2(a, b):
summed_ab = []
summed_ab.append(int(a))
summed_ab.append(int(b))
return str(sum(summed_ab))
#Couldn't figure this out
def square_digits(n):
squared_nums = 1
for i in str(n):
i = (i**2)
squared_nums += str(i)
return squared_nums
#Can't figure out join()
def greet_people(names):
guests = []
for i in names:
guests.append('Hello ',i)
return str(guests)
def greet_people(names):
for i in names:
result = 'Hello '.join(i)
return result
def steps_to_convert(txt):
step_count = 0
for i in txt:
if i.isupper():
step_count += 1
return step_count
#Ouh nice! got this w little help!
def index_of_caps(word):
index_pos = []
for i in word:
if i.isupper():
index_pos.append(word.index(i))
return index_pos
#Ouh nice! Figured this out on my own! list comprehension!
def last(a, n):
last_n_ele = []
if n > len(a):
return 'invalid'
elif n == 0:
return last_n_ele
else:
return a[-n:]
def letters_only(txt):
str_only = ''
for i in txt:
if i.isalpha():
str_only += i
return str_only
#Fuck! Get this right
#Not feeling today
def replace_vowels(txt, ch):
vowels = 'aeiou'
for i in txt:
if i in vowels:
txt.replace(i,ch)
return txt
#did it different here, actually removed
#Before would jsut call lst[1] not actually removing just passing test
def stand_in_line(lst, num):
if len(lst) < 1:
return 'No list has been selected'
else:
lst.append(num)
lst.remove(lst[0])
return lst
#did it differently again!
def remove_vowels(txt):
vowels = 'aeiou'
no_vows = ''
for i in txt:
if i.lower() not in vowels:
no_vows += i
return no_vows
def sum2(a, b):
ab_list = []
ab_list.append(int(a))
ab_list.append(int(b))
return str(sum(ab_list))
def split(txt):
vowels = 'aeiou'
vowel_str = ''
cons_str = ''
for i in txt:
if i.lower() in vowels:
vowel_str += i
else:
cons_str += i
return vowel_str + cons_str
#Easy problems from edabit
#Sort by length, not alphabetical
def sort_by_length(lst):
sorted_list = []
for i in lst:
sorted_list.append(i)
return sorted(sorted_list)
def remove_dups(lst):
no_dupes = []
for i in lst:
if i not in no_dupes:
no_dupes.append(i)
return no_dupes
#Almost there! Need to implement error check to handle negative ints
#Why is the -723 showing up in this case?
#AH! So tough. Ended up just making separate list then doing logic on that
#Remove method wasn't working as expected
def sum_two_smallest_nums(lst):
two_nums = []
no_neg = []
for i in lst:
if i < 0:
continue
else:
no_neg.append(i)
no_neg = sorted(no_neg)
two_nums.append(no_neg[0])
two_nums.append(no_neg[1])
return sum(two_nums)
def sum_neg(lst):
positive_count = 0
neg_nums = []
result = []
if len(lst) < 1:
return []
elif len(lst) > 1:
for i in lst:
if i < 0:
neg_nums.append(i)
else:
positive_count += 1
sum_neg_nums = sum(neg_nums)
result.append(positive_count)
result.append(sum_neg_nums)
return result
#an't figure this one out
def is_vowel_sandwich(s):
vowels = 'aeiou'
if len(s) == 3:
if s[0] and s[2] not in vowels and s[1] in vowels:
return True
elif s[1] not in vowels or s[0] and s[2] in vowels:
return False
else:
return False
def remove_enemies(names, enemies):
no_enemies = []
for i in names:
if i not in enemies:
no_enemies.append(i)
return no_enemies
def asc_des_none(lst, s):
if s == 'Asc':
return sorted(lst)
elif s == 'Des':
return sorted(lst)[::-1]
elif s == 'None':
return lst
def remove_special_characters(txt):
special_char = ".,`?!@#$%^&*\()+=[]{}<>~|':;"
no_chars = ''
for i in txt:
if i not in special_char:
no_chars += i
return no_chars
def remove_special_characters(txt):
special_char = ".!@#$%^&*\()"
no_chars = ''
for i in txt:
if i.isalnum():
no_chars += i
return no_chars
|
a6f7f06f6281317ea7ef81aeef1fc60e44fe51a7 | developerhat/project-folder | /Doing.py | 443 | 4.03125 | 4 | #This function is for addition
def add(x, y):
return x + y
#Function for subtraction
def subtract(x, y):
return x - y
#Function for multiplication
def multiply(x, y):
return x * y
#Function for division
def division(x, y):
return x / y
print("Welcome to Patrick's calculator! ")
print('\n' * 4)
print("Enter 1 for addition ")
print("Enter 2 for subtraction ")
print("Enter 3 for multiplication ")
print("Enter 4 for division ")
|
288dc860f25c3ddea6610726bb6547893f1e3a1c | developerhat/project-folder | /October.py | 14,755 | 3.96875 | 4 | #usr/bin/python
#This loop will print hello 5 times
spam = 0
#Will print hello until spam is equal to or greater than 5
while spam < 5:
print('Hello ')
spam = spam + 1
#Code below keeps asking for input until you type your name
#Programmer humor?
name = ' '
while name != 'your name':
name = str(input('Please type your name: '))
print('Thank you!')
#Edabit Level 2 Easy problem
#Sorta got it but edge cases like special chars doens't work
def is_valid_pin(pin):
if len(pin) == 4:
return True
elif len(pin) == 6:
return True
else:
return False
#checks for string value as symmetrical
#how can we do this for integer? store in list?
def is_symmetrical(num):
num = str(num)
if num[::-1] == num[::1]:
return True
else:
return False
#calculator from Edabit but no exception handling for 0
#Need to add for zero
def calculator(num1, operator, num2):
if operator == "+":
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return "Can't divide by 0!"
#This was easy but silly looking.
#Doesn't go through in Edabit though...
def is_truthy(val):
if val == False or None or 0 or [] or {} or "":
return 0
else:
return 1
#From coding bat, returns given string 3 times
def string_times(str, n):
return str*n
#From CodingBat, returns first 3 chars times 3
def front_times(str, n):
return str[:3] * n
#Returns number of times 9 appears in a list
#Getting better using the count function!
def array_count9(nums):
return nums.count(9)
#Returns True if first 4 values contains the integer 9
def array_front9(nums):
if 9 in nums[0:4]:
return True
else:
return False
#Returns False. We need it to return True.. why?
def array123(nums):
if [1,2,3] in nums [0:3]:
return True
else:
return False
#Supposed to return evens in a list
#Only returns the first even
#NEED TO SOLVE CODINGBAT LIST 2
def count_evens(nums):
for i in nums:
if i % 2 == 0:
return nums.count(i)
#Returns True if values are 6 or add up to 6, etc.
def love6(a,b):
if a or b == 6:
return True
elif a + b == 6:
return True
elif a - b or b - a == 6:
return True
else:
return False
#wow got this on my own!! Seemed so difficult but got it down!
def operation24(num1, num2):
if num1 + num2 == 24:
return 'added'
elif num1 - num2 == 24:
return 'subtracted'
elif num1 * num2 == 24:
return 'multiplied'
elif num1 / num2 == 24:
return 'divided'
else:
return None
#Working on very easy problem for Edabit, making progress! only does 1st one tho..
def add_ending(list4, ending):
for str in list4:
return str + ending
#Returns Edabit but with a the amount of times input is entered
#Pretty easy got it on my own!
def how_many_times(num):
return 'Ed' + 'a' * num + 'bit'
#Trying to return text n number of times: 'hhii'
def repeat(txt, n):
return txt*n
#Got this on StackOverflow. Big hack tho.. idk what it does really
def repeat(txt, n):
return ''.join([char*n for char in txt])
#Returns the index of first vowel encountered
#Doesn't work though, no substring?
#Returns None, why?
def first_vowel(txt):
for i in txt:
if 'aeiou' in txt:
return txt.index('aeiou')
#This removes 13, however it only removes the 1st 13 value it encounters. Why?
def unlucky_13(nums):
for i in nums:
if i % 13 == 0:
nums.remove(i)
return nums
#Wow did this on my own!! NO resources!!
#Sick! Returns index for value provided
def search(lst, item):
for i in lst:
if item in lst:
return lst.index(item)
else:
return -1
#Doens't work, see answer below. This was my attempt
def count_vowels(txt):
for i in txt:
return 'aeiou'.count(txt)
#Got this code from online
#Works tho!
def count_vowels(txt):
vowels = 0
for i in txt:
if (i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels += 1
return vowels
#Got this all on my own, easy
def tri_area(base, height):
return base * height / 2
#This is supposed to return a list of numbers counting down from numbers given to 0
#Can't get through it though. Edabit bookmarked problem
def countdown_to_zero(start):
for i in start:
while i != 0:
i = i - 1
return i
#Couldn't figure this out. Edabit bookmarked problem
def amplify4(num):
if num % 4 == 0:
for i in range(num):
return
#Wow got this w minimal help! Needed to add list()
def get_sequence(low, high):
return list(range(low, high+1))
def reverse(lst):
return lst[::-1]
#Got through this w minimal help, needed to use max()
def exists_higher(lst, n):
for i in lst:
if max(lst) >= n:
return True
else:
return False
#converts hours & minutes + adds for seconds
def convert(hours, minutes):
hours = hours * 3600
minutes = minutes * 60
return hours + minutes
#Wow! Returns index of given string in list
#Did this on my own no help
def find_index(lst, txt):
return lst.index(txt)
#Damn!! Got this on my own too! Used exception handling
#Instead of using if else, used exception handling
def search(lst, item):
try:
return lst.index(item)
except:
return -1
#Got through this w minimal help
#Needed to copy the list using [:]?
def no_odds(lst):
for i in lst[:]:
if i % 2 != 0:
lst.remove(i)
return lst
#Needed help on this one but got the fundamentals right on my own(using the for loop + range)
def sum_recursively(lst):
total = 0
for i in range(len(lst)):
total = total + lst[i]
return total
#Heyyyy got this right all on my own!!
#This works, but not entirely
#Entering 104 & 806 don't get removed even if they are divisible by 13. Weird
#Fixed this by copying the list nums[:]
def unlucky_13(nums):
for i in nums[:]:
if i % 13 == 0:
nums.remove(i)
return nums
#Did this on my own! Simple
def difference(nums):
for i in nums:
return max(nums) - min(nums)
#Figuring this out, how can you multiply list values w length of list?
#Got it! needed to create a new list & store the results in that list
#Needed some help but makes sense
def MultiplyByLength(arr):
result = []
for i in arr:
result.append(i * len(arr))
return result
#Got through this w a little help!
#Reverses a string
def rev(n):
n = abs(n)
return str(n)[::-1]
#This challenge is interesting. Not finished, bookmarked in Edabit
#What am I doing wrong here?
def transform(list):
for i in list:
if i % 2 == 0:
i = i-1
return list
else:
i = i+1
return list
#Works & did this on my own but pretty simple
def same_first_last(nums):
if nums[0] == nums[-1]:
return True
else:
return False
#This runs & works but doesn't return absolute value?
def get_abs_sum(lst):
total = 0
abs_value = [abs(i) for i in lst]
for i in range(len(lst)):
total = total + lst[i]
return total
#Did this on my own! Pretty simple but good nontheless
#Works but doesn't pass Edabit test
#Tried 2 strings: 1500 & 16 but returns 1500
#OH! Returns 1500 b/c it only compares 1st 2 digits?
def smaller_num(n1, n2):
return str(min(n1, n2))
#Trying to return number of arguments passed through
#Wow got through this! had an overcomplicated answer.
#Simplify it, key is simplify
def number_args(*argv):
return len(argv)
#Can't figure this out yet
#Need to return the difference between highest & lowest number in list
def list_difference(nums):
for i in nums:
result = nums.max(nums) - nums.min(nums)
return result
#Trying to check if all numbers in list are even
def check_all_even(lst):
if all(lst) % 2 == 0:
return True
else:
return False
#Checking if all items in list are even. Can't quite get it right
def check_all_even(lst):
for x in lst:
if x % 2 == 0:
return True
else:
return False
#Wow got this done on my own! Didn't think it worked but gave it a try
def programmers(one, two, three):
return max(one, two, three) - min(one, two, three)
#I get what it's asking for but havin trouble formatting..
#Hey got this on my own! Pretty simple
def animals(chickens, cows, pigs):
return (chickens*2) + (cows*4) + (pigs*4)
#Got this on my own pretty simple
def k_to_k(n, k):
if k**k == n:
return True
else:
return False
#Wow got this all on my own!!
#At first wasn't taking reverse(), so used built-in copy method
def reverse_capitalize(txt):
return txt.upper()[::-1]
#Wow pretty much did this on my own!
#Needed some pushing to use sum(), was thinking of using for loop
def mean(nums):
result = sum(nums)
mean_result = result / len(nums)
return round(mean_result, 1)
#Just messing round here!
def testing():
question = str(input('Hi! What is your name? '))
print('Hi, ' + question + '!')
age = int(input('How old are you? '))
print("Nice! You are " + str(age) + ' years old. You oldie!')
#Works but doesn't pass Edabit
#Checks last 2 chars of both strings? Why's it wrong?
def check_ending(str1, str2):
if str1[-2] == str2[-2]:
return True
else:
return False
#Wow got this on my own!
#Only issue is, Edabit is using a 2D list with more than 1 list passed
def count_ones(matrix):
for i in matrix:
result = matrix.count(1)
return result
#Found this answer on Stack overflow
#Same thing tho, weird?
def count_ones(matrix):
sum(i.count(1) for i in matrix)
#Need to add ending to strings provided
#Returns only once, need ot return for each item in list
def add_ending(lst, ending):
for x in lst:
return x + ending
#Got this answer from Stackoverflow, not exactly sure what it does though?
#Uses format()
def add_ending(lst, ending):
output = ["{}{}".format(i, ending) for i in lst]
return output
#No luck here..
#Need to use regular expressions?
def is_valid(zip_code):
zip_code = int(zip_code)
if zip_code.isinteger() == True:
return True
else:
return False
#Way too easy
#Calculates max edge for triangles
def next_edge(side1, side2):
return (side1 + side2) -1
#Trying to get this to sum cubes
#Getting closer but it only cubes the last item in list. Why?
def sum_of_cubes(nums):
for i in nums:
i = i**3
return i
#Got this online, not my code. Still not working though
def sum_of_cubes(nums):
return sum([2**x for x in nums])
#Can't figure this out, nested and statements
def is_leap(year):
if year % 400 and year % 4 == 0 and year % 100 != 0:
return True
else:
return False
#Got this down, but need to account for negative numbers
def score_calculator(easy, med, hard):
for i in easy,med,hard:
if i == -i:
return "Invalid"
else:
easy = easy * 5
med = med * 10
hard = hard * 20
return easy + med + hard
#Determines how many negative integers are in the list
#Did this all ony my own!
def is_negative(nums):
count = 0
for i in nums:
if i < 0:
count +=1
return count
#Got through this w minimal help
def is_empty(dictionary):
if not dictionary:
return True
else:
return False
#Need to use list comprehension or lamda, filter, map to remove all values in list
#Why does it only remove one value in list?
def remove_none(list):
for i in list:
if i == None:
list.remove(i)
return list
#Got through this w minimal help
def is_palindrome(n):
n = str(n)
if n[::-1] == n[0::]:
return True
else:
return False
#Return all list values, capitalized first letter
#Only returns the last value though?
def cap_me(lst):
for i in lst:
i = i.capitalize()
return i
#Seems like it should work but doesn't pass Edabit test
def divides_evenly(a, b):
if a/b % 2 == 0:
return True
else:
return False
#What is this supposed to do?.. All returns True
def both_zero(n1, n2):
if n1 and n2 == 0:
return True
elif n1 and n2 < 0:
return True
elif n1 and n2 > 0:
return True
else:
return False
#Got this on my own, pretty simple!
def less_than_100(a, b):
if a + b < 100:
return True
else:
return False
#Needed a bit of help w this one
def check_equality(a, b):
if type(a) == type(b):
return True
else:
return False
#Way too easy
def find_perimeter(height, width):
result = 2*height + 2*width
return result
#Supposed to multiply each item in list by 2
#Can't get it tho
def get_multiplied_list(lst):
for i in lst:
i = i * 2
return i
#Didn't know .endswith was a valid method
def is_last_char_n(word):
if word.endswith('n'):
return True
else:
return False
#Needed help w this one
def get_sum_of_elements(lst):
total = 0
ele = 0
while(ele < len(lst)):
total = total + lst[ele]
ele += 1
return total
def hello_world(num):
if num == 3:
return 'Hello'
elif num == 5:
return 'World'
elif num == 15:
return 'Hello World'
#Wow! Got through this on my own!! Good shit
def limit_number(num, range_low, range_high):
for i in range(range_low, range_high):
if num < range_low:
return range_low
elif num > range_high:
return range_high
elif num in range(range_low, range_high):
return num
#Got some help on this one, cheeseballs
def is_prime(num):
if num > 1:
for i in range(2, num//2):
if (num % i) == 0:
return False
break
else:
return True
#Need to solve this, return index position of uppercase chars
def capital_indexes(str):
index_count = []
for i in enumerate(str, 0):
if i.isupper():
index_count.append(i)
return index_count
#Wow!! Got ths done on my own
#My 1st idea was to use count(), but wasn't too intuitive
#Manually counted
def capital_letters(txt):
capital_counter = 0
for letter in txt:
if letter.isupper():
capital_counter +=1
return capital_counter
|
1f299c522d6430d5a7c4301e56a789d8e2192597 | developerhat/project-folder | /CreateFolder.py | 266 | 3.625 | 4 | #Creating folder using python
import os
path = "/Users/patrickgo/Desktop/Misc/NetDevEng"
os.mkdir(path)
print(os.getcwd())
print("\n")
print("All of the files & folders in this directory are: \n",os.listdir())
#Prints current working directory + sublists & files
|
24cda752498f51e747e869109f81da988089ca5a | developerhat/project-folder | /oop_practice.py | 608 | 4.125 | 4 | #OOP Practice 04/08/20
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@patgo.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('pat','go',300000)
emp_2 = Employee('xavier', 'braxis',15000)
#emp_1.first = "Pat"
#emp_1.last = "G"
#emp_1.email = 'pat.g@patrickgo.com'
#emp_1.pay = '300,000'
#emp_2.first = "Pet"
#emp_2.last = "f"
#emp_2.email = 'patooly'
#emp_2.pay = '20,000'
print(Employee.fullname(emp_2))
print(emp_2.fullname())
|
8b6dc2a503a73d243151605477c060e0db85fb70 | PeterLemon/N64 | /Compress/DCT/DCTBlockGFX/DCTEncode.py | 3,755 | 3.703125 | 4 | import math
# DCT Encoding: "https://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html"
# DCT Value At The Upper Left Corner Is Called The "DC" Value.
# This Is The Abbreviation For "Direct Current" & Refers To A Similar Phenomenon
# In The Theory Of Alternating Current Where An Alternating Current Can Have A Direct Component.
# In DCT The "DC" Value Determines The Average Brightness In The Block.
# All Other Values Describe The Variation Around This DC value.
# Therefore They Are Sometimes Referred To As "AC" Values (From "Alternating Current").
dct_input_1d = [ # Discrete Cosine Transform (DCT) 8x8 Input Matrix
## 87,87,87,87,87,87,87,87, # A Grey Colored Square.
## 87,87,87,87,87,87,87,87,
## 87,87,87,87,87,87,87,87,
## 87,87,87,87,87,87,87,87,
## 87,87,87,87,87,87,87,87,
## 87,87,87,87,87,87,87,87,
## 87,87,87,87,87,87,87,87,
## 87,87,87,87,87,87,87,87]
## 105,102,97,91,84,78,73,70, # A Curve Like A Half Cosine Line.
## 105,102,97,91,84,78,73,70,
## 105,102,97,91,84,78,73,70,
## 105,102,97,91,84,78,73,70,
## 105,102,97,91,84,78,73,70,
## 105,102,97,91,84,78,73,70,
## 105,102,97,91,84,78,73,70,
## 105,102,97,91,84,78,73,70]
## 104,94,81,71,71,81,94,104, # A Cosine Line, With A Full Period.
## 104,94,81,71,71,81,94,104,
## 104,94,81,71,71,81,94,104,
## 104,94,81,71,71,81,94,104,
## 104,94,81,71,71,81,94,104,
## 104,94,81,71,71,81,94,104,
## 104,94,81,71,71,81,94,104,
## 104,94,81,71,71,81,94,104]
## 121,109,91,75,68,71,80,86, # A Mix Of Both The 1st & 2nd Cosines.
## 121,109,91,75,68,71,80,86,
## 121,109,91,75,68,71,80,86,
## 121,109,91,75,68,71,80,86,
## 121,109,91,75,68,71,80,86,
## 121,109,91,75,68,71,80,86,
## 121,109,91,75,68,71,80,86,
## 121,109,91,75,68,71,80,86]
## 156,144,125,109,102,106,114,121, # Values That Vary In Y Direction
## 151,138,120,104,97,100,109,116,
## 141,129,110,94,87,91,99,106,
## 128,116,97,82,75,78,86,93,
## 114,102,84,68,61,64,73,80,
## 102,89,71,55,48,51,60,67,
## 92,80,61,45,38,42,50,57,
## 86,74,56,40,33,36,45,52]
124,105,139,95,143,98,132,114, # Highest Possible Frequency Of 8 Is Applied In Both X- & Y- Direction.
105,157,61,187,51,176,80,132, # Picture Shows A Checker-Like Appearance.
139,61,205,17,221,32,176,98,
95,187,17,239,0,221,51,143,
143,51,221,0,239,17,187,95,
98,176,32,221,17,205,61,139,
132,80,176,51,187,61,157,105,
114,132,98,143,95,139,105,124]
dct_result_1d = [0,0,0,0,0,0,0,0, # Discrete Cosine Transform (DCT) 8x8 Result Matrix
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0]
C = [(1/(2*math.sqrt(2))),0.5,0.5,0.5,0.5,0.5,0.5,0.5] # C Look Up Table (/2 Applied)
COS = [] # COS Look Up Table
for u in range(8):
for x in range(8):
COS.append(math.cos((2*x + 1) * u * math.pi / 16))
# DCT
for u in range(8):
for v in range(8):
for x in range(8):
for y in range(8):
dct_result_1d[v*8 + u] += (
dct_input_1d[y*8 + x]
* C[u]
* C[v]
* COS[u*8 + x] # math.cos((2*x + 1) * u * math.pi / 16)
* COS[v*8 + y] # math.cos((2*y + 1) * v * math.pi / 16)
)
print ("Discrete Cosine Transform (DCT) 8x8 Input Matrix:") # Print The DCT 8x8 Input Matrix
print ([x for x in dct_input_1d])
print ("Discrete Cosine Transform (DCT) 8x8 Result Matrix:") # Print The DCT 8x8 Result Matrix
print ([round(x) for x in dct_result_1d])
|
3dd6343d9218eec78dd061d58d6adf0292f74517 | aturfah/cmplxsys530-final | /ladder/random_ladder.py | 1,115 | 3.875 | 4 | """Ladder that randomly pairs two agents."""
from random import random
from ladder.base_ladder import BaseLadder
class RandomLadder(BaseLadder):
"""Ladder that matches players randomly."""
def __init__(self, game=None, K_in=32, selection_size=1):
"""
Initialize a ladder for a specific game.
Args:
game (battle_engine): Game to be played on this ladder.
K_in (int): K value to be used for calculating elo changes
on this ladder.
"""
super().__init__(game=game, K_in=K_in, selection_size=selection_size)
def match_func(self, player1, player2_pair):
"""
Return random value as a match weighting.
Since players will be sorted this random value, it is
equivalent to randomly choosing an opponent.
Args:
player1 (BaseAgent): The player who is being matched.
player2_pair (tuple): The candidate player & turns waiting pair for a match.
Returns:
The score for a match; in this case a random number.
"""
return random()
|
a68961fdb55a4ce92f150f10d4173ab89eec6aec | musthafashaik126/PythonFundamentals | /Day 7_B 28_python.py | 478 | 4.03125 | 4 | age = 22
if age >= 15:
print("you are eligible to vote")
else:
print("you are not eligible to vote next year")
year = 20
if year >= 55:
print("you are eligible to i cet exam ")
else:
print("you are not eligible to i cet exam")
age = 1
if age == 1:
print("baby will be able to crowl")
elif age == 2:
print("baby will be able to stand")
elif age == 3:
print("baby will be able to walk")
else:
print("baby will be able to run")
|
148b8cdd616b477d3824de4646ae3d4109256acf | dgoat416/Terminal_Blog | /Testing MongoDB.py | 2,028 | 3.734375 | 4 | __author__ = "DGOAT"
import pymongo
# exactly where on the mongoDB server we are connecting to
uri = "mongodb://127.0.0.1:27017"
# initialize the mongoDB client which has access to all databases in
# mongoDB instance
client = pymongo.MongoClient(uri)
database = client['fullstack']
collection = database['students']
# finds all data in the collection (table)
students = collection.find({})
student_list = []
# prints a pointer to the first element in our collection
# can be used to iterate over all elements
print(students)
print(2 * "\n")
# print all students
for student in students:
print(student)
# condensed and succinct form of above just get rid of 'grade'
print(3 * "\n")
students = [student['grade'] for student in collection.find({})]
print(students)
# creates a list consisting of digits 0 - 9
digits = [i for i in range(0, 10)]
print(digits)
#create a list of dictionaries with the same key
class1 = [{"name" : "Deron", "grade" : 100}, { "name" : "John", "grade" : 76},
{"name" : "Otis", "grade" : 59}, {"name" : "Uriah", "grade" : 100}]
class2 = [{"name" : "Jordan", "grade" : 100}, { "name" : "Octeye", "grade" : 76},
{"name" : "Dummy", "grade" : 59}, {"name" : "Justin", "grade" : 100}]
class3 = [{"name" : "Miles", "grade" : 100}, { "name" : "idioto", "grade" : 76},
{"name" : "stupid", "grade" : 59}, {"name" : "David", "grade" : 100}]
#collection.delete_many({"name" : "Otis", "grade" : 59})
collection.insert_many([student for student in class1])
students = collection.find({})
for i in students:
print(i)
# all_classes = [{class1}, {class2}, {class3}]
#
# # print each class individually
# all_classes_list = [a_class for a_class in all_classes]
# print(all_classes_list)
# print(2 * "\n")
#
# # print a list of all the names in the class
# names = [a_class["names"] for a_class in all_classes]
# print(names)
# print(2 * "\n")
#
# # print a list of all names with grade equal to 100
# names_100 = [smart for smart in all_classes if smart["grade"] = 100] |
88d72128cbb1a2073dcad72f2befc06105dd9ef2 | Nibinsha/python_practice_book_updated | /chp5/prbm1.py | 376 | 3.84375 | 4 | class reverse_iter:
def __init__(self,n):
self.i = 0
self.n = n
def next(self):
if self.i < self.n:
x = self.n
self.n -= 1
return x
else:
raise StopIteration()
a = reverse_iter(5)
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
|
2a7b37dbb0a6fac11b0e9ca2541c0f2e1cb7a1e1 | Nibinsha/python_practice_book_updated | /chp2/prbm14.py | 176 | 3.671875 | 4 | def unique(x):
l = []
for i in x:
s = i.lower()
if s not in l:
l.append(s)
return l
print unique(['Abc','A','ab','abc','a'])
|
18821aa2c606ee4838ea45fd91049589a352330b | Nibinsha/python_practice_book_updated | /chp2/prbm31.py | 134 | 3.546875 | 4 | def parse(x,y,z):
f = open(x).readlines()
print [[i.split(y)] for i in f if f[0] != z]
print parse('parse_csv.txt','!','#')
|
29eb770fffa63d9e89a1cac09de9184e1076abc2 | Nibinsha/python_practice_book_updated | /chp2/prbm2.py | 88 | 3.5 | 4 | def sum(x):
c = 0
for i in x:
c+=i
return c
print sum([1,2,3,4,5])
|
aae732bd6ddb3e12e17a472ca210a9df08803456 | Nibinsha/python_practice_book_updated | /chp2/prbm4.py | 101 | 3.671875 | 4 | def product(x):
mul = 1
for i in x:
mul*=i
return mul
print product([1,2,3,4])
|
140ebcf7e2d06b1743f6720946cc267728494dbd | johnny3young/codingame | /puzzles/python2/ascii_art.py | 382 | 3.796875 | 4 | width = int(raw_input())
height = int(raw_input())
text = raw_input().upper()
for i in range(height):
row = raw_input()
output = ""
for char in text:
position = ord(char) - ord("A")
if position < 0 or position > 25:
position = 26
start = position * width
end = start + width
output += row[start:end]
print(output)
|
81a7eedaa50f6053f34f436d2fba9d2481b8d568 | sungsoo-lim90/RL_HWs | /HW1/policy_iteration_multiclass.py | 6,736 | 4.0625 | 4 | """
MSIA 490 HW1
Policy iteration algorithm - multiclass
Sungsoo Lim - 10/19/20
Problem
- One state is assumed that represents the number of customers at the station at given time
- Two actions are assumed that either a bus is dispatched or it is not at given time and state
- Reward is assumed to be negative, as there are only costs involved
- Assume that a bus can be dispatched below its capacity
Multiclass
- Each class has its own initial and incoming customer numbers
- Assume that each class contributes equally to the bus
- Reward is calculated based on each c_h and c_f
- Each class capped at 100 members each - not yet incorporated into the algorithm written here
"""
import numpy as np
import matplotlib.pyplot as plt
NO_DISPATCH = 0 #State is no dispatched bus, and dispatches a bus
DISPATCH = 1 #State is dispatched bus, and dispatches a bus
def policy_iteration_multiclass(policy, theta, discount_factor):
nA = 2 #number of actions - dispatch a bus or not
K = 30 #capacity of a shuttle if dispatched
c_f = 100 #cost of dispatching a shuttle
c_h = [1, 1.5, 2, 2.5, 3] #cost of waiting per customer - 5 classes
P = {}
P = {a: [] for a in range(nA)}
s1 = np.random.randint(1,6) #initial number of customers for class 1
s2 = np.random.randint(1,6) #initial number of customers for class 2
s3 = np.random.randint(1,6) #initial number of customers for class 3
s4 = np.random.randint(1,6) #initial number of customers for class 4
s5 = np.random.randint(1,6) #initial number of customers for class 5
def expected_value(policy,P,V):
"""
Calculate the expected value function for all actions in the given policy
"""
v = 0
for a, action_prob in enumerate(policy):
for prob, reward in P[a]:
v += action_prob*prob*(reward + discount_factor * V)
return v
V = [0,0]
pol = [0]
custm =[[0,0,0,0,0]]
i = 1
while True:
#stopping condition
delta = 0
cust1 = np.random.randint(1,6) #uniform random increasing customers for class 1
cust2 = np.random.randint(1,6) #uniform random increasing customers for class 2
cust3 = np.random.randint(1,6) #uniform random increasing customers for class 3
cust4 = np.random.randint(1,6) #uniform random increasing customers for class 4
cust5 = np.random.randint(1,6) #uniform random increasing customers for class 5
#next state for dispatching a shuttle for each class
if K/5 > s1:
dispatch1 = cust1
else:
dispatch1 = (s1 - K/5 + cust1)
if K/5 > s2:
dispatch2 = cust2
else:
dispatch2 = (s2 - K/5 + cust2)
if K/5 > s3:
dispatch3 = cust3
else:
dispatch3 = (s3 - K/5 + cust3)
if K/5 > s4:
dispatch4 = cust4
else:
dispatch4 = (s4 - K/5 + cust4)
if K/5 > s5:
dispatch5 = cust5
else:
dispatch5 = (s5 - K/5 + cust5)
no_dispatch1 = s1 + cust1 #next state for not dispatching a shuttle - class 1
no_dispatch2 = s2 + cust2 #next state for not dispatching a shuttle - class 1
no_dispatch3 = s3 + cust3 #next state for not dispatching a shuttle - class 1
no_dispatch4 = s4 + cust4 #next state for not dispatching a shuttle - class 1
no_dispatch5 = s5 + cust5 #next state for not dispatching a shuttle - class 1
#total number of customers when not dispatching a shuttle
next_state_no_dispatch = no_dispatch1 + no_dispatch2 + no_dispatch3 + no_dispatch4 + no_dispatch5
next_state_dispatch = dispatch1 + dispatch2 + dispatch3 + dispatch4 + dispatch5
reward_no_dispatch = -(no_dispatch1*c_h[0] + no_dispatch2*c_h[1] + no_dispatch3*c_h[2] + no_dispatch4*c_h[3] + no_dispatch5*c_h[4]) #reward for not dispatching
reward_dispatch = -(dispatch1*c_h[0] + dispatch2*c_h[1] + dispatch3*c_h[2] + dispatch4*c_h[3] + dispatch5*c_h[4]) - c_f #reward for dispatching
#prob, reward for not/dispatching
P[NO_DISPATCH] = [(1.0, reward_no_dispatch)]
P[DISPATCH] = [(1.0, reward_dispatch)]
#the capacity capped at 500 customers
if next_state_no_dispatch >= 500: #always dispatch
P[NO_DISPATCH] = P[DISPATCH]
#First calculate the expected value function based on the next state
v = expected_value(policy,P,V[i-1])
delta = max(delta, np.abs(v - V[i]))
#random uniformly update the state (number of customers)
if next_state_no_dispatch >= 500: #always dispatch
s1 = dispatch1
s2 = dispatch2
s3 = dispatch3
s4 = dispatch4
s5 = dispatch5
best_action = 1
if np.random.uniform(0,1.0) <=0.50:
s1 = no_dispatch1
s2 = no_dispatch2
s3 = no_dispatch3
s4 = no_dispatch4
s5 = no_dispatch5
best_action = 0
else:
s1 = dispatch1
s2 = dispatch2
s3 = dispatch3
s4 = dispatch4
s5 = dispatch5
best_action = 1
i = i + 1
V.append(v)
pol.append(best_action)
custm.append([s1, s2, s3, s4, s5])
if delta < theta:
break
return custm,pol,V
def policy_improvement_multiclass(discount_factor, theta, policy_iteration_fn=policy_iteration_multiclass):
"""
Greedily improve the random policy
"""
def plus_one(nA,P,V):
"""
Calculate the value function for all action in a given state
"""
A = np.zeros(nA) #either dispatch or not dispatch
for a in range(nA):
for prob, reward in P[a]:
A[a] += prob*(reward + discount_factor * V)
return A
policy = [0.5, 0.5] #random policy
nA = 2 #two actions - dispatch or not dispatch a bus
P = {} #transition probability and reward tuple for each action
P = {a: [] for a in range(nA)}
c_f = 100 #cost of dispatching a shuttle
c_h = [1, 1.5, 2, 2.5, 3] #cost of waiting per customer - 5 classes
K = 30 #capacity
while True:
custm, pol, V = policy_iteration_fn(policy,theta,discount_factor)
del V[0]
policy_stable = True
for i in range(len(V)-1,-1,-1): #for each state
chosen_action = pol[i]
s1 = custm[i][0]
s2 = custm[i][1]
s3 = custm[i][2]
s4 = custm[i][3]
s5 = custm[i][4]
s = s1 + s2 + s3 + s4
reward_no_dispatch = -(s1*c_h[0] + s2*c_h[1] + s3*c_h[2] + s4*c_h[3] + s5*c_h[4]) #reward for not dispatching
reward_dispatch = -(s1*c_h[0] + s2*c_h[1] + s3*c_h[2] + s4*c_h[3] + s5*c_h[4]) - c_f #reward for dispatching
#prob, reward for not/dispatching
P[NO_DISPATCH] = [(1.0, reward_no_dispatch)]
P[DISPATCH] = [(1.0, reward_dispatch)]
A = plus_one(nA,P,V[i-1])
best_action = np.argmax(A)
if chosen_action != best_action:
policy_stable = False
policy = np.eye(nA)[best_action].tolist()
if policy_stable:
return custm, pol, V
custm, pol, V = policy_improvement_multiclass(0.95,0.01)
flat_list = np.zeros(len(custm))
for i in range(0,len(custm)-1):
flat_list[i] = np.sum(custm[i][:])
plt.scatter(flat_list,pol)
plt.title("Policy iteration - multiclass")
plt.xlabel('Number of people')
plt.ylabel('Optimal Policy')
plt.savefig("policy_multi.png",dpi=300) |
77e69bb4ca02c4add43f751ffc699d93f689d8bb | Mask-of-the-Fractal-Abyss/cryptodungeon4 | /playerCommands.py | 1,266 | 3.65625 | 4 | from tools import *
# Player searches for desired code
def search(codeToSearch):
if player.room is None:
if codeToSearch in codeClass.codes:
room = searchRoomsByCode(codeToSearch)
middle = int(room.size / 2)
room.contents[middle][middle] = player
player.coords = [middle, middle]
player.room = room
room.printRoom()
else:
print("You must leave your current room to search.")
# Moves the player in their room
def move(direction):
if player.room is not None:
if direction in "nesw":
player.move(direction)
player.room.printRoom()
else:
print("That's not a direction. Try: N, S, E, W...\n")
else:
print("You must be in a room to move...\n")
# Player attacks in their room
def attack(direction):
if player.room is not None:
if player.weapon is not None:
if direction in "nesw":
player.attack(direction, True)
else:
print("That's not a direction. Try: N, S, E, W")
else:
print("You must have a weapon to attack")
else:
print("You must be in a room to move")
|
69ea978428cde6f9a9023dc720b677564b1d1cec | wilhelmwen/password_retry | /pwretry.py | 263 | 3.90625 | 4 | x = 3
while x > 0:
x = x - 1
pw = input ('請輸入密碼: ')
if pw == 'a123456':
print('登入成功')
break
else:
print('密碼錯誤!')
if x > 0:
print('還有', x, '次機會')
else:
print('沒機會嘗試了! 要鎖帳號了啦!')
|
48b9d1c567012e7e766286f198f0c45903553bb4 | HTeker/Programmeeropdrachten | /12.py | 1,509 | 3.765625 | 4 | def printMatrix(cells):
for i in range(0, len(cells)):
row = ""
for x in range(0, len(cells[i])):
row += "["
if(cells[i][x] == 0):
row += " "
elif(cells[i][x] == 1):
row += "X"
else:
row += "O"
row += "]"
print(row)
def askUserInput(user):
selectedEmpty = False
while(selectedEmpty == False):
x = int(input("Speler " + str(user) + ": voer de X-waarde in voor je volgende zet: "))
y = int(input("Speler " + str(user) + ": voer de Y-waarde in voor je volgende zet: "))
if((1 <= x <= (len(cells[0]))) and (1 <= y <= (len(cells[0])))):
x -= 1
y -= 1
if (cells[x][y] == 0):
selectedEmpty = True
cells[x][y] = user
else:
print("U heeft geen lege veld geselecteerd.")
else:
print("U heeft een ongeldige invoer gegeven")
def checkGameNotOver():
for i in range(0, len(cells)):
for x in range(0, len(cells[i])):
if(cells[i][x] == 0):
return True
return False
cells = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
lastPlayer = 2
while(checkGameNotOver()):
printMatrix(cells)
if (lastPlayer == 1):
user = 2
else:
user = 1
lastPlayer = user
askUserInput(user)
print("Spel is voorbij.")
printMatrix(cells) |
a72050671b14bd9b9a245434503da04d1024ca3a | SamarthaSinghal/P---105 | /105.py | 497 | 3.75 | 4 | import math
import csv
with open ('data.csv',newline = '') as f :
reader = csv.reader(f)
data = list(reader)
data1 = data[0]
def mean (data1):
n = len (data1)
total = 0
for x in data1 :
total = total+int(x)
mean = total/n
return mean
list = []
for i in data1 :
a = int(i) - mean (data1)
a = a**2
list.append(a)
sum = 0
for j in list :
sum = sum + j
result = sum/(len(data1)-1)
standarddeviation = math.sqrt(result)
print (standarddeviation)
|
3b35bc7cc7235aba585d37bf014450b52767bafd | uppaltushar/hello-git | /assignment-2.py | 410 | 3.953125 | 4 | #1>
print("tushar Uppal")
#2>
str1 = "uppal"
str2 = "tushar"
print(str1+str2)
#3>
p = int(input("enter "))
q = int(input("enter "))
r = int(input("enter "))
print("p = ",p,"q = ",q,"r = ",r)
#4>
print("let's get started")
#5>
s = "Acadview"
course = "python"
fees = 5000
str1 = "{} {} course fee is {}".format(s,course,fees)
print(str1)
#6>
name="Tony Stark"
salary=1000000
print("%s,%d"%(name,salary))
|
d89b6e9450cb2bac5a603394f6da53e8381c500f | pavansaij/Algorithms_In_Python | /ThreadSafe_Dict/mutable_dict.py | 737 | 3.640625 | 4 | class MutableDict():
def __init__(self, *args, **kwargs):
self.__dict__.update(*args, **kwargs)
print(self.__dict__)
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
def __delitem__(self, key):
del self.__dict__[key]
def __iter__(self):
return iter(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return r'{}, MutableDict({})'.format(super(MutableDict, self).__repr__(),
self.__dict__)
d = MutableDict()
d[3] = 4
e = MutableDict({1:3, 2:4})
print(e) |
5a0ca6f1c602ce3a41a722d1d208daa131de6bb1 | renanpaduac/linguagem_programacao | /exercicio4.py | 244 | 3.671875 | 4 | for nr in range(2,100):
print(nr, end=' - >')
primo = True
x = 2
while x < nr and primo:
if nr %x == 0:
primo = False
x+=1
if primo:
print("VERDADEIRO")
else:
print ("FALSO")
|
2fc98fec393d40e8163c47aba7c5fd64ae076501 | mbeissinger/recurrent_gsn | /src/models/lstm.py | 809 | 3.546875 | 4 | """
LSTM with inputs, hiddens, outputs
"""
import torch
import torch.nn as nn
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size,
num_layers=2, bias=True, batch_first=False,
dropout=0, bidirectional=False, output_activation=nn.Sigmoid()):
super().__init__()
self.lstm = nn.LSTM(
input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bias=bias, batch_first=batch_first,
dropout=dropout, bidirectional=bidirectional
)
self.linear = nn.Linear(in_features=hidden_size, out_features=output_size, bias=bias)
self.out_act = output_activation
def forward(self, x):
output, _ = self.lstm(x)
return torch.stack([self.out_act(self.linear(out_t)) for out_t in output])
|
f80ce721837ae4b782981bba552681f886663ddb | girish75/PythonByGireeshP | /pycode/Question8listfunction.py | 2,252 | 4 | 4 | # Q8. Given a list, l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9], store 3 sub-lists such that those
# contains multiples of 2, 3 and 4 respectively. Print the lists.
# Repeat storing and printing the lists same as above as multiples of 2, 3 and 4 but take
# l1 as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
j = k = l = 1
sublist2 = []
sublist3 = []
sublist4 = []
sublist2multiples = []
sublist3multiples = []
sublist4multiples = []
#print (j, k, sublist2multiples, sublist3multiples, sublist4multiples )
listing =0
while listing <=2:
if listing == 0:
for i in l1:
# print("now entering 2nd if", i)
# print("now entering 2nd if ", j)
# print("now entering 2nd if ", k)
#create sublist
if i ==2 and j <= 3:
while j<=3:
sublist2.append(i*j)
j+=1
if i ==3 and k<=3:
while k<=3:
sublist3.append(i*k)
k+=1
if i ==4 and l<=3:
while l<=3:
sublist4.append(i*l)
l+=1
print("Sublist for 2 created from list l1 =", sublist2)
print("Sublist for 2 created from list l1 =", sublist3)
print("Sublist for 2 created from list l1 =", sublist4)
elif listing ==1:
print("listing =", listing, "entering into second for loop")
i = j = k = l = 1
for i in l2:
if i == 2 and j <= 3:
while j<=3:
sublist2multiples.append(i*j)
j+=1
if i ==3 and k<=3:
while k<=3:
sublist3multiples.append(i*k)
# print("i = ", i)
# print("k = ", j)
k+=1
if i ==4 and l<=3:
while l<=3:
sublist4multiples.append(i*l)
l+=1
print(sublist2multiples)
print(sublist3multiples)
print(sublist4multiples)
print("increment listing now =", listing)
listing += 1
|
116936cad73564abb9355199f5c8604d0b0bb8e7 | girish75/PythonByGireeshP | /pycode/Quesetion1assignment.py | 925 | 4.40625 | 4 | # 1. Accept user input of two complex numbers (total 4 inputs, 2 for real and 2 for imaginary part).
# Perform complex number operations (c1 + c2, c1 - c2, c1 * c2)
a = int(input("For first complex number, enter real number"))
b = int(input("For first complex number, enter imaginary number"))
a1 = int(input("For second complex number, enter real number"))
b1 = int(input("For second complex number, enter imaginary number"))
c1 = complex(a,b)
print(c1)
c2 = complex(a1,b1)
print(c2)
print("Addition of two complex number =", c1 + c2)
#Subtraction
print("Subtraction of two complex number =", c1 - c2)
#Multiplication
print("Multiplication of two complex number =", c1 * c2)
#Division
print("Division of two complex number =", c1 / c2)
c = (3 + 6j)
print('Complex Number: Real Part is = ', c. real)
print('Complex Number: Imaginary Part is = ', c. imag)
print('Complex Number: conjugate Part = ', c. conjugate())
|
ac235a932c259aac16a2a47fe0a45f9255e8a6f0 | girish75/PythonByGireeshP | /pythonproject/FirstProject/jsong.py | 1,813 | 4.3125 | 4 | import json
'''
The Json module provides an easy way to encode and decode data in JSON
Convert from Python to JSON:
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
convert Python objects of the following types, into JSON strings: dict, list
tuple, string, int
float, True, False
None
'''
data = {"Name": "Girish",
"Shares": 100,
"Price": 540}
# convert into JSON:
json_str = json.dumps(data)
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
# the result is a JSON string:
print(json_str)
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann", "Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
# Use the indent parameter to define the numbers of indents:
print(json.dumps(x, indent=4)) # Very useful.
# Use the separators parameter to change the default separator:
print(json.dumps(x, indent=4, separators=("|| ", " = ")))
# Order the Result
# Use the sort_keys parameter to specify if the result should be sorted or not:
print("New Dict = ", json.dumps(x, indent=4, sort_keys=True))
# ==============================================================
# Parse JSON - Convert from JSON to Python
# If you have a JSON string, you can parse it by using the json.loads() method.
# The result will be a Python dictionary.
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
|
f34b378c7bf7ee5a4f0c7263274312064a3ab596 | girish75/PythonByGireeshP | /pycode/newfunction.py | 696 | 4.09375 | 4 | def hello():
print("This is hello function")
# function to find factorial
def fact(n):
""" function to find factorial value"""
# print("Factorial function called" )
if n == 1:
return 1
else:
return (n * fact(n-1))
# Define `main()` function
def main():
hello()
print("This is a main function")
# Execute `main()` function
if __name__ == '__main__':
main()
#function to check positive or Negative
def check_num(a)->int:
""" function to check positive or negative number"""
if a > 0:
print(a, " is a positive number ")
elif a == 0:
print (a, "is a zero")
else:
print (a, " is a negative number")
|
8fec3c271497a7556c4c28ae307c8e686a2b1eb3 | girish75/PythonByGireeshP | /pycode/original1.ListComprehensions.py | 593 | 4.03125 | 4 | nums = [0, 1, 2, 3, 4]
print("Creating Empty list...")
print(nums)
squares = []
for x in nums:
print("Creating square list and appending square of = " + str(x))
squares.append(x ** 2)
print("Printing new list with squares .. ")
print(squares) # Prints [0, 1, 4, 9, 16]
print("list comprehensions..")
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares) # Prints [0, 1, 4, 9, 16]
print("list comprehensions can also contain conditions... ")
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares) # Prints "[0, 4, 16]"
|
30d6c602a49a9470a33a49b0d14762025e4743b3 | suberlak/quasars-sdss | /SF_plotting/FileIO.py | 4,905 | 4.03125 | 4 | import numpy
import os.path
def ReadColumns(FileName, ncols=None, delimiter='', comment_character='#', verbose=True):
""" Read a number of columns from a file into numpy arrays.
This routine tries to create arrays of floats--in this case 'nan' values
are preserved. Columns that can't be cast as floats are returned as
string arrays, with the caveat that all 'nan' datums in these string arrays
are turned into Nones.
ncols is the maximum number of columns to read
delimiter, by default, is any whitespace
if verbose is true, print out the number of lines read
Raises IOError (for unreadable files or files with no readable lines)
If you try to unpack too many columns, *you* will raise a ValueError
"""
try:
file = open(FileName)
except IOError, e:
if verbose:
print "I can't open", FileName, "\nAborting..."
raise IOError, "Can't open" + FileName + ": " + e
nrows = 0
rows = []
for line in file:
# if the line has no characters,
# or the first non-whitespace character is a comment:
if len(line.strip())==0 or line.strip()[0] == comment_character:
continue
line = line[:line.find(comment_character)] # return just the part before any '#'
# split the line into 'words'
if delimiter:
line = line.split(delimiter)
else:
line = line.split() # default is to split on any whitespace
# if we only want some of these columns...
if ncols:
line = line[:ncols]
line = [SafeFloat(x) for x in line] # carefully make a list of floats
rows.append( line ) # rows is a list of lists
nrows += 1
file.close()
if verbose:
print "Read", nrows, "lines from", FileName
if len(rows) == 0:
# oops, no readable lines
raise IOError, "No readable lines in file"
cols = zip( *rows ) # return a list of each column
# ( the * unpacks the 1st level of the list )
outlist = []
for col in cols:
arr = numpy.asarray( col )
type = arr.dtype
if str(type)[0:2] == '|S':
# it's a string array!
outlist.append( arr )
else:
outlist.append( numpy.asarray(arr, numpy.float32) ) # it's (hopefully) just numbers
return outlist # a list of numpy arrays, one for each column
def WriteColumns(FileName, cols, header='', clobber=False, NaNstring=None, verbose=True):
""" Write a file containing a column for each array passed.
Takes a filename, the arrays (which should be passed as a tuple),
an optional header, and options enabling overwriting files, dealing
with null values, and verbosity (defaults: protect files, use
literal 'nan's, and tell you stuff ).
If you don't want literal 'nan's to appear in your output file,
set NaNstring to the *string* you wish to see instead:
NaNstring='-99' <- note that '-99' is a string, not an integer
The header text is inserted verbatim (plus a final carriage return),
so be sure to include comment characters if necessary.
Raises IOError with a hopefully helpful error string
BUGS: unexpected results if you give it a single string array outside
of a tuple (try it!)
"""
# should we check if we're going to overwrite something?
if clobber == False and os.path.exists(FileName):
raise IOError, FileName + " already exists!"
try:
rows = len(cols[0])
except TypeError:
# there was only one column,
cols = (cols,) # so turn cols into the expected tuple
rows = len(cols[0])
try:
File = open(FileName, "w")
if header != '':
File.write( header+"\n" )
for i in range(rows):
for array in cols:
# if NaNstring is defined, replace NaNs
if NaNstring:
datum = array[i]
if numpy.isnan(datum)==True:
File.write( "\t" + NaNstring )
else:
File.write( "\t" + str(array[i]) )
else: # or don't
File.write( "\t" + str(array[i]) )
File.write( "\n" )
except IOError, e:
File.close()
if verbose:
print "Error writing to", FileName
raise IOError, "Error writing to " + FileName + ": " + e
if verbose:
print FileName, ":", rows, "rows written."
File.close()
def SafeFloat(value):
""" Try to convert values to floats, but recognize 'nan' and giving those
back as None. Strings that can't be converted to floats are simply returned
Used by ReadColumns()
"""
try:
return float(value)
except:
if value == 'nan':
return None
return value
|
6de8d2f46212c6c92213b5901a5e82ab2d692112 | manasviKnarula/LaterThan30Days | /RemoveFiles.py | 330 | 3.5625 | 4 | import time
import os
import shutil
path = input ("please enter the path for your folder: ")
days = 30
time.time(days)
if os.path.exists(path+"/"+ext):
os.walk(path)
os.path.join()
else:
print("path not found")
ctime=os.stat(path).st_ctime
return ctime
if ctime>days:
os.remove(path)
shutil.rmtree()
|
1bac046ce2443b8e1cd93566bf59b0e8800755be | PlasticTable/Python-Stuff | /Function Scoping Example.py | 204 | 3.6875 | 4 | lis1 = [1,2,3,4]
def random(lis1):
lis2 = []
for i in lis1:
lis2.append(i)
return lis2
print random(lis1)
print random([9,4,3,2])
# Very ugly and confusing code
# Was wondering why it worked
|
cee82ae95620940abc124cafe4ec4ffb6fab9da2 | aarthisandhiya/aarthisandhiya1 | /11hunter.py | 187 | 4.09375 | 4 | def reverse(sentence):
words=sentence.split(" ")
newWords=[i[::-1] for i in words]
newSentence=" ".join(newWords)
print(newSentence)
sentence=input()
reverse(sentence)
|
f710d6d6500b31254ea5c628a15733402bcfcd36 | himal8848/Data-Structures-and-Algorithms-in-Python | /linear_search.py | 307 | 4.09375 | 4 | #Linear Search In Python
#Time complexity is O(n)
def linear_search(list,target):
for i in range(len(list)):
if list[i] == target:
print("Found at Index ",i)
break
else:
print("Not Found")
list = [4,6,8,1,3,5]
target = 5
linear_search(list,target) |
2196af2ef6617fbba8292dda5aed2649e1aac0a3 | himal8848/Data-Structures-and-Algorithms-in-Python | /bubble_sort.py | 315 | 4.1875 | 4 | #Bubble Sort in Python
def bubble_sort(list):
for i in range(len(list)-1,0,-1):
for j in range(i):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
list = [23,12,8,9,25,13,6]
result = bubble_sort(list)
print(list) |
79ffca882d5bb5261533611b4d03e9dc2175d7ab | jonovik/cgptoolbox | /cgp/sigmoidmodels/doseresponse.py | 5,817 | 3.65625 | 4 | """Functions for modelling dose-response relationships in sigmoid models"""
from __future__ import division
import scipy
import numpy as np
def Hill(x, theta, p):
"""
The Hill function (Hill, 1910) gives a sigmoid increasing dose-response
function crossing 0.5 at the threshold theta with a steepness determined by
the Hill coefficient p.
:param theta: threshold parameter.
:param p: Hill coefficient.
:return: function value in the range [0,1].
.. plot::
:width: 400
:include-source:
import numpy as np
from matplotlib import pyplot as plt
from cgp.sigmoidmodels.doseresponse import Hill
x = np.arange(0, 10, 0.1)
y1 = [Hill(X,5,2) for X in x]
y2 = [Hill(X,5,10) for X in x]
plt.plot(x,y1,x,y2)
plt.xlabel('x')
plt.ylabel('Hill(x,5,p)')
plt.legend(('p=2','p=10'))
Example usage::
>>> Hill(5,5,1)
0.5
>>> Hill(10, 5, 5)
0.96969...
References:
* Hill AV (1910)
`The possible effects of the aggregation of the molecules of haemoglobin
on its dissociation curves
<http://jp.physoc.org/content/40/supplement/i.full.pdf+html>`_ J. Physiol.
40 (Suppl): iv-vii.
"""
if x <= 0:
return 0.0
elif theta == 0:
return 1
else:
return (x > 0) * (x ** p / (x ** p + theta ** p))
def nonmono(x, mu, sigma):
"""
Bell-shaped gene regulation function
Normal probability distribution scaled to have maximum 1. Used as the non-
monotonic gene regulation function in Gjuvsland et al. (2011).
Example usage:
>>> nonmono(5, 7, 1)
0.1353352832366127
Reference:
* Gjuvsland AB, Vik JO, Wooliams JA, Omholt SW (2011)
`Order-preserving principles underlying genotype-phenotype maps ensure
high additive proportions of genetic variance <http://onlinelibrary.wiley.
com/doi/10.1111/j.1420-9101.2011.02358.x/full>`_ Journal of Evolutionary
Biology 24(10):2269-2279.
"""
return(scipy.exp((-(x - mu) ** 2) / (2 * sigma ** 2)))
def R_logic(Z1, Z2, index, name=False):
"""
Output the continuous equivalent of 1 of 16 boolean functions of Z1 and Z2.
:param Z1: scalar in [0, 1]
:param Z2: scalar in [0, 1]
:param index: integer between 1 and 16 indicating Boolean function
(see table below)
:param names: Boolean whether to return function value (default) or
function name (names=True)
:return: function value in the range [0, 1].
Table of Boolean functions:
===== =================================== ====================================
index Boolean function Algebraic function
===== =================================== ====================================
1 AND(X1,X2) Z1Z2
2 AND(X1,NOT(X2)) Z1(1-Z2)
3 AND(NOT(X1),X2) (1-Z1)Z2
4 AND(NOT(X1),NOT(X2)) (1-Z1)(1-Z2)
5 X1 Z1
6 X2 Z2
7 NOT(X1) 1-Z1
8 NOT(X2) 1-Z2
9 OR(X1,X2) Z1+Z2-Z1Z2
10 OR(NOT(X1),NOT(X2)) 1-Z1Z2
11 OR(AND(X1,X2),AND(NOT(X1),NOT(X2))) 1-Z1-Z2+Z1Z2+Z1^2Z2+Z1Z2^2-Z1^2Z2^2
12 OR(AND(X1,NOT(X2)),AND(X1,NOT(X2))) Z1+Z2-3Z1Z2+Z1^2Z2+Z1Z2^2-Z1^2Z2^2
13 OR(X1,NOT(X2)) 1-Z2+Z1Z2
14 OR(NOT(X1),X2)) 1-Z1+Z1Z2
15 0 (always off) 0
16 1 (always on) 1
===== =================================== ====================================
Example - Create boolean truth tables for all 16 boolean functions::
>>> X1 = [0, 0, 1, 1]
>>> X2 = [0, 1, 0, 1]
>>> [(R_logic([], [], ind, name=True), [R_logic(x1, x2, ind)
... for x1, x2 in zip(X1, X2)]) for ind in range(1, 17)]
[('AND(X1,X2)', [0, 0, 0, 1]),
('AND(X1,NOT(X2))', [0, 0, 1, 0]),
('AND(NOT(X1),X2)', [0, 1, 0, 0]),
('AND(NOT(X1),NOT(X2))', [1, 0, 0, 0]),
('X1', [0, 0, 1, 1]),
('X2', [0, 1, 0, 1]),
('NOT(X1)', [1, 1, 0, 0]),
('NOT(X2)', [1, 0, 1, 0]),
('OR(X1,X2)', [0, 1, 1, 1]),
('OR(NOT(X1),NOT(X2))', [1, 1, 1, 0]),
('OR(AND(X1,X2),AND(NOT(X1),NOT(X2)))', [1, 0, 0, 1]),
('OR(AND(X1,NOT(X2)),AND(X1,NOT(X2)))', [0, 1, 1, 0]),
('OR(X1,NOT(X2))', [1, 0, 1, 1]),
('OR(NOT(X1),X2))', [1, 1, 0, 1]),
('0', [0, 0, 0, 0]),
('1', [1, 1, 1, 1])]
"""
if name:
func = dict({'1': 'AND(X1,X2)',
'2': 'AND(X1,NOT(X2))',
'3': 'AND(NOT(X1),X2)',
'4': 'AND(NOT(X1),NOT(X2))',
'5': 'X1',
'6': 'X2',
'7': 'NOT(X1)',
'8': 'NOT(X2)',
'9': 'OR(X1,X2)',
'10': 'OR(NOT(X1),NOT(X2))',
'11': 'OR(AND(X1,X2),AND(NOT(X1),NOT(X2)))',
'12': 'OR(AND(X1,NOT(X2)),AND(X1,NOT(X2)))',
'13': 'OR(X1,NOT(X2))',
'14': 'OR(NOT(X1),X2))',
'15': '0',
'16': '1'})
return func[str(np.int(index))]
else:
func = dict({'1': 'Z1*Z2',
'2': 'Z1*(1-Z2)',
'3': '(1-Z1)*Z2',
'4': '(1-Z1)*(1-Z2)',
'5': 'Z1',
'6': 'Z2',
'7': '1-Z1',
'8': '1-Z2',
'9': 'Z1+Z2-Z1*Z2',
'10': '1-Z1*Z2',
'11': '1-Z1-Z2+Z1*Z2+Z1**2*Z2+Z1*Z2**2-Z1**2*Z2**2',
'12': 'Z1+Z2-3*Z1*Z2+Z1**2*Z2+Z1*Z2**2-Z1**2*Z2**2',
'13': '1-Z2+Z1*Z2',
'14': '1-Z1+Z1*Z2',
'15': '0',
'16': '1'})
return eval(func[str(np.int(index))]) |
0c8d1f3f209e6509e22286834b9d45c063be5fd1 | jonovik/cgptoolbox | /cgp/examples/sigmoid.py | 4,618 | 3.734375 | 4 | """
Basic example of cGP study using sigmoid model of gene regulatory networks.
This example is taken from Gjuvsland et al. (2011), the gene regulatory model
is eq.(15) in that paper, and the example code reproduces figure 4a.
.. plot::
:width: 400
:include-source:
from cgp.examples.sigmoid import cgpstudy, plot_gpmap
gt, par, ph = cgpstudy()
plot_gpmap(gt, ph)
The gene regulatory model is a
:class:`~cgp.sigmoidmodels.sigmoid_cvode.Sigmoidmodel`. It is a diploid model,
in the sense that there is two differential equations per gene, one for each
allele. This calls for a genotype-to-parameter map where the two alleles are
mapped to two independent sets of parameter values. The function
:func:`~cgp.gt.gt2par.geno2par_diploid` offers such genotype-to-parameter
mapping with allele-specific parameters .
:class:`~cgp.sigmoidmodels.sigmoid_cvode.Sigmoidmodel` encodes a system with
three genes and the parameter *adjmatrix* is used to specify connetivity and
mode of regulation. The model in Gjuvsland et al. (2011) only has two genes, so
we focus only on gene 1 and 2, and make sure that gene 3 is not regulating any
of them.
For a given parameter set the resulting phenotype is the equilibrium expression
level of gene 2. In order to find the equilibrium we combine
:class:`~cgp.sigmoidmodels.sigmoid_cvode.Sigmoidmodel` with
:class:`~cgp.phenotyping.attractor.AttractorMixin`.
Reference:
* Gjuvsland AB, Vik JO, Wooliams JA, Omholt SW (2011)
`Order-preserving principles underlying genotype-phenotype maps ensure
high additive proportions of genetic variance <http://onlinelibrary.wiley.
com/doi/10.1111/j.1420-9101.2011.02358.x/full>`_ Journal of Evolutionary
Biology 24(10):2269-2279.
"""
# pylint: disable=W0621, W0212, W0612
import numpy as np
import matplotlib.pyplot as plt
from cgp.utils.placevalue import Placevalue
from cgp.gt.gt2par import geno2par_diploid
from cgp.sigmoidmodels.sigmoid_cvode import Sigmoidmodel
from cgp.phenotyping.attractor import AttractorMixin
from cgp.utils.rec2dict import dict2rec
########################################
### Model of gene regulatory network ###
########################################
class Model(Sigmoidmodel, AttractorMixin):
"""
Class that combines a sigmoid model with the ability to find equilibria.
.. inheritance-diagram:: Model cgp.sigmoidmodels.sigmoid_cvode.Sigmoidmodel cgp.phenotyping.attractor.AttractorMixin
:parts: 1
"""
pass
model = Model(adjmatrix=np.array([[0, 0, 0], [1, 0, 0], [0, 0, 0]]))
########################################
### Genotypes for two biallelic loci ###
########################################
names = ['Gene1', 'Gene2']
genotypes = Placevalue([3, 3], names=names, msd_first=False)
### Genotype-to-parameter map
gt2par = geno2par_diploid
#Allelic parameter values from legend of Figure 4a Gjuvsland et al. (2011)
#hetpar contains parameter values for a
hetpar = model.p
hetpar.alpha1 = [182.04, 159.72]
hetpar.alpha2 = [190.58, 135.08]
hetpar.theta21 = [32.06, 20.86]
hetpar.p21 = [8.84, 7.91]
#binary matrix indicating which parameter values are
#inherited together with what locus
loc2par = np.zeros((2, 18)) #two loci, 18 parameters in total
loc2par[0, 0:6] = 1
loc2par[1, 6:12] = 1
### Parameter-to-phenotype map
def par2ph(par):
"""
Phenotype: Equilibrium expression level of gene 2.
This maps a parameter value to a phenotype value.
"""
model._ReInit_if_required(y=np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]))
model.pr[:] = par
_t, y = model.eq(tmax=100, tol=1e-6)
return dict2rec(dict(Y2=y[2] + y[3]))
def cgpstudy():
"""
Connecting the building blocks of a cGP study.
This implements the simulation pipeline in Gjuvsland et al. (2011).
"""
from numpy import concatenate as cat
gt = np.array(genotypes)
par = cat([gt2par(list(g), hetpar, loc2par) for g in gt])
ph = cat([par2ph(p) for p in par])
return gt, par, ph
def plot_gpmap(gt, ph):
"""Lineplot of genotypes and corresponding phenotypes."""
plt.plot(gt['Gene1'][gt['Gene2'] == 0], ph[gt['Gene2'] == 0], 'ro-')
plt.plot(gt['Gene1'][gt['Gene2'] == 1], ph[gt['Gene2'] == 1], 'go-')
plt.plot(gt['Gene1'][gt['Gene2'] == 2], ph[gt['Gene2'] == 2], 'bo-')
plt.xlabel('Genotype gene 1')
plt.xticks(range(3), ('11', '12', '22'))
plt.ylabel('Expression level gene 2')
plt.legend(('11', '12', '22'), title="Genotype gene 2")
plt.grid(b='on', axis='y')
plt.show()
if __name__ == "__main__":
gt, par, ph = cgpstudy()
plot_gpmap(gt, ph)
|
5da1487437a7556fac90072c2d7dddbb01a965a6 | jonovik/cgptoolbox | /cgp/utils/extrema.py | 2,060 | 3.8125 | 4 | """Find local maxima and minima of a 1-d array"""
import numpy as np
from numpy import sign, diff
__all__ = ["extrema"]
# pylint:disable=W0622
def extrema(x, max=True, min=True, withend=True): #@ReservedAssignment
"""
Return indexes, values, and sign of curvature of local extrema of 1-d array.
The boolean arguments max, min, withend determine whether to
include maxima and minima, and include the endpoints.
Basic usage.
>>> x = [2, 1, 0, 1, 2]
>>> extrema(x) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
rec.array([(0, 2, -1), (2, 0, 1), (4, 2, -1)],
dtype=[('index', '<i...'), ('value', '<i...'), ('curv', '<i...')])
Options to include only certain types of extrema.
>>> extrema(x, withend=False)
rec.array([(2, 0, 1)],...
>>> extrema(x, max=False)
rec.array([(2, 0, 1)],...
>>> extrema(x, min=False)
rec.array([(0, 2, -1), (4, 2, -1)],...
>>> extrema(x, max=False, min=False)
rec.array([],...
The beginning and end of flat segments both count as extrema,
except the first and last data point.
>>> extrema([0, 0, 1, 1, 2, 2])
rec.array([(1, 0, 1), (2, 1, -1), (3, 1, 1), (4, 2, -1)],...
>>> extrema([0, 0, 0])
rec.array([],...)
>>> extrema([0, 0, 1, 1], withend=False)
rec.array([(1, 0, 1), (2, 1, -1)],...
@todo: Add options on how to handle flat segments.
"""
x = np.squeeze(x) # ensure 1-d numpy array
xpad = np.r_[x[1], x, x[-2]] # pad x so endpoints become minima or maxima
curv = sign(diff(sign(diff(xpad)))) # +1 at minima, -1 at maxima
i = curv.nonzero()[0] # nonzero() wraps the indices in a 1-tuple
ext = np.rec.fromarrays([i, x[i], curv[i]],
names=["index", "value", "curv"])
if not withend:
ext = ext[(i > 0) & (i < len(x) - 1)]
if not max:
ext = ext[ext.curv >= 0]
if not min:
ext = ext[ext.curv <= 0]
return ext
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS)
|
9247bc433012c2af963293105933a1e422af281e | bariskucukerciyes/280201035 | /lab9/harmonic.py | 146 | 3.5 | 4 | def harmonic(x):
h_sum = 0
if x == 1:
return 1
h_sum = (1 / x) + harmonic(x - 1)
return h_sum
print(harmonic(5)) |
f5ad9e7ceadf975f9c3af3917bd4c3557ef39972 | bariskucukerciyes/280201035 | /lab5/evens.py | 169 | 4.03125 | 4 | N = int(input("How many number?"))
evens = 0
for i in range(N):
number = int(input("Enter integer:"))
if number % 2 == 0:
evens += 1
print(evens/N * 100, "%")
|
ba5de5ac9904058a9c7a5d48e881b9bd564b2824 | bariskucukerciyes/280201035 | /lab1/fahrenheit.py | 162 | 4.0625 | 4 | Celcius = int(input("Enter celcius value:"))
Fahrenheit = int(Celcius*1.8 + 32)
print(Celcius, "Celcius degree is equals to", Fahrenheit, "Fahrenheits degree" ) |
6acb845b6105cc4253fbc3421ef3b3354a23be3d | bozkus7/Python_File | /neural.py | 985 | 3.84375 | 4 | import numpy
import matplotlib.pyplot
data_file = open('mnist_train_100.csv.txt', 'r')
data_list = data_file.readlines()
data_file.close()
#The numpy.asfarray() is a numpy function to convert the text strings into real numbers and to create an array of those numbers
all_values = data_list[0].split(',')
image_array = numpy.asfarray(all_values[1:]).reshape((28,28))
print(matplotlib.pyplot.imshow(image_array, cmap = 'Greys', interpolation = 'None'))
"""
Dividing the raw inputs which are in the range 0255
by 255 will bring them into the range 01.
We then need to multiply by 0.99 to bring them into the range 0.0 0.99.
We then add 0.01 to
shift them up to the desired range 0.01 to 1.00. The following Python code shows this in action
"""
scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
print(scaled_input)
#output node is 10 (ex)
onodes = 10
targets = numpy.zeros(onodes) + 0.01
targets[int(all_values[0])] = 0.99
|
38e59e24c8a8d4a11c1bc6d8bb9fe4a9071ef492 | amansharma2910/DataStructuresAlgorithms | /02_PythonAlgorithms/Sorting/singly_linked_list.py | 3,113 | 4.34375 | 4 | class Node:
# Node class constructor
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
# LinkedList constructor
def __init__(self):
self.head = None
def print_list(self):
"""Method to print all the elements in a singly linked list.
"""
node = self.head
while node is not None:
print(node.data, end=" ")
node = node.next
def append(self, data):
"""Method to add node to the end of the linked list."""
node = Node(data)
# check the base case where the singly linked list is empty, i.e., head is None
if self.head is None:
self.head = node
return
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def prepend(self, data):
"""Method to add node to the beginning of the linked list."""
node = Node(data)
node.next = self.head
self.head = node
def add_at_idx(self, data, idx):
"""Method to add node in a linked list at a given position.
"""
if idx == 0:
node = Node(data)
node.next = self.head
self.head = node
return
count = 0
curr_node = self.head
while curr_node != None and count != idx-1:
curr_node = curr_node.next
count += 1
if count == idx-1:
node = Node(data)
node.next = curr_node.next
curr_node.next = node
else:
print(f"{idx} is not present in the linked list.")
def delete_head(self):
"""Method to delete the head node in a linked list.
"""
temp = self.head
self.head = self.head.next
del(temp) # in python, dereferencing an object sends it to garbage collection, so this step is optional
def delete_tail(self):
"""Method to delete the last node of a linked list.
"""
curr_node = self.head
while curr_node.next.next != None:
curr_node = curr_node.next
curr_node.next = None
def delete_at_idx(self, idx):
"""Method to delete the node at a given index value.
"""
if idx == 0:
self.head = None
return
curr_node = self.head
count = 0
while curr_node != None and count != idx-1:
curr_node = curr_node.next
count += 1
if count == idx-1:
curr_node.next = curr_node.next.next
else:
print(f"{idx} does not exist for the given linked list.")
if __name__ == "__main__":
llist = SinglyLinkedList()
llist.append(3) # head -> 3
llist.prepend(5) # head -> 5 -> 3
llist.prepend(6) # head -> 6 -> 5 -> 3
llist.prepend(4) # head -> 4 -> 6 -> 5 -> 3
llist.add_at_idx(11, 2) # head -> 4 -> 6 -> 11 -> 5 -> 3
llist.delete_head() # head -> 6 -> 11 -> 5 -> 3
llist.delete_at_idx(1) # head -> 6 -> 5 -> 3
llist.print_list()
|
df369f3cd5db77a5ed5fa071a3a8badfcf404905 | ea3/Exceptions-Python | /exception.py | 887 | 4.03125 | 4 | def add(a1,a2):
print(a1 + a2)
add(10,20)
number1 = 10
number2 = input("Please provide a number ") # This gives back a string.
print("This will never run because of the type error")
try:
#You you want to attempt to try.
result= 10 + 10
except:
print("It looks like you are not adding correctly")
else:
print("NO ERRORS!")
print(result)
try:
f = open('testfile', 'w')
f.write('Write a test line')
except TypeError:
print('There was a type error')
except :
print('Hey, you have an OS Error')
finally:
print('I always run')
def ask_for_int():
while True:
try:
result = int(input("Pleae provide a number: "))
except:
print("Whoops!That is not a number")
continue
else:
print("Yes, thank you for the number")
break
finally:
print("End of try/except/finally")
print("I will always run at the end")
ask_for_int()
|
8f76584b2645bb0ef6d525cd456ab11b7b2933c7 | stanton101/Ansible-Training | /core_python_ep6.py | 462 | 3.90625 | 4 | # Tuples
# t = ("Norway", 4.953, 3)
# print(t * 3)
# print(t[0])
# print(t[2])
# print(len(t))
# for item in t:
# print(item)
# t + (338186)
# a = ((220, 284), (1184, 1210), (2620,2924), (5020, 5564), (6232, 6368))
# print(a[2][1])
# def minmax(self):
# return min(self), max(self)
# num = minmax([83, 33, 84, 32, 85, 31, 86])
# print(num)
# print("Hello world")
make = "500"
sum = 5 + int(make)
print(str(sum) + " rand in my pocket")
# print(500) |
e613ee5e149ff0ed9af83a11e1571421c9c8551c | charlesrwinston/nlp | /lab0/winston_Lab0.py | 1,326 | 3.5625 | 4 | # Winston_Lab0.py
# Charles Winston
# September 7 2017
from nltk.corpus import gutenberg
def flip2flop():
flip = open("flip.txt", "r")
flop = open("flop.txt", "w")
flip_text = flip.read()
flop.write(reverse_chars(flip_text) + "\n")
flop.write(reverse_words(flip_text) + "\n")
emma = gutenberg.words('austen-emma.txt')
flop.write(str(len(emma)) + "\n")
flop.write("Word.\n")
flop.write("It's lit.\n")
def reverse_chars(sentence):
length = len(sentence)
new_sentence = ""
for i in range(length):
new_sentence += sentence[length - 1 - i]
return new_sentence
def reverse_words(sentence):
words = get_words(sentence)
len_words = len(words)
new_sentence = ""
for i in range(len_words):
new_sentence += words[len_words - 1 - i]
if (i != (len_words - 1)):
new_sentence += " "
return new_sentence
def get_words(sentence):
length = len(sentence)
words = []
temp_word = ""
for i in range(length):
if sentence[i].isspace():
words.append(temp_word)
temp_word = ""
elif (i == (length - 1)):
temp_word += sentence[i]
words.append(temp_word)
else:
temp_word += sentence[i]
return words
if __name__ == '__main__':
flip2flop()
|
4074f1ca36b2ad151d2b918274f661c8e0ae4b80 | htars/leetcode | /algorithms/1_two_sum.py | 733 | 3.546875 | 4 | from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)-1):
n1 = nums[i]
for j in range(i+1, len(nums)):
n2 = nums[j]
if (n1+n2) == target:
return [i, j]
if __name__ == '__main__':
s = Solution()
inputs = [
[2, 7, 11, 15],
[3, 2, 4],
[3, 3],
]
targets = [
9,
6,
6,
]
outputs = [
[0, 1],
[1, 2],
[0, 1]
]
for nums, target, output in zip(inputs, targets, outputs):
result = s.twoSum(nums, target)
print(result)
assert result == output
|
742952425469528b62320860c834a73d8f52e444 | americanchauhan/problem-solving | /Find the maximum element and its index in an array/Find the maximum element and its index in an array.py | 428 | 4.0625 | 4 | def FindMax(arr):
#initialze first value as largest
max = arr[0]
for i in range(1, len(arr)):
#if there is any other value greater than max, max is updated to that element
if arr[i] > max:
max = arr[i]
ind = arr.index(max)
#Print the maximum value
print(max)
#return index of the maximum value
return ind
arr = list(map(int, input().split()))
print(FindMax(arr)) |
68e668797ce78e861ba24a295f05a4e7aaf07086 | rupalisinha23/problem-solving | /rotating_series.py | 517 | 3.9375 | 4 | """
given two arrays/lists A and B, return true if A is a rotation of B otherwise return false
"""
def is_rotation(A,B):
if len(A) != len(B): return False
key=A[0]
indexB = -1
for i in range(len(B)):
if B[i] == key:
indexB = i
break
if indexB == -1: return False
for i in range(len(A)):
j = (indexB + i)%len(A)
if A[i] != B[j]:
return False
return True
if __name__=='__main__':
print(is_rotation([1,2,3,4],[3,4,1,2]))
|
3da789960183c8f13bb5b22307c60fe57adf316b | rupalisinha23/problem-solving | /pallindrome_linked_list.py | 493 | 3.734375 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Pallindrome:
def isPallindrome(self, head:ListNode) -> bool:
if not head or not head.next:
return True
stack = []
while head:
stack.append(head.val)
head = head.next
length = len(stack)
for i in range(length/2):
if stack[i] != stack[len(stack)-i-1]:
return False
return True
|
75260678d000751037a56f69e517b253e7d82ad9 | aasmith33/GPA-Calculator | /GPAsmith.py | 647 | 4.1875 | 4 | # This program allows a user to input their name, credit hours, and quality points. Then it calculates their GPA and outputs their name and GPA.
import time
name = str(input('What is your name? ')) # asks user for their name
hours = int(input('How many credit hours have you earned? ')) # asks user for credit hours earned
points = int(input('How many quality points do you have? ')) # asks user for amount of quality points
gpa = points / hours # calculates GPA
gpa = round(gpa, 2) #rounds gpa 2 decimal places
print ('Hi ' + str(name) + '. ' + 'Your grade point average is ' + str(gpa) + '.') # displays users name and GPA
time.sleep(5)
|
89899700c49efdc29c14accb87082a865da2b896 | darpanhub/python1 | /task4.py | 2,041 | 3.984375 | 4 | # Python Program to find the area of triangle
a = 5
b = 6
c = 7
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
# python program finding square root
print('enter your number')
n = int(input())
import math
print(math.sqrt(n))
# Python program to swap two variables
x = 5
y = 10
swap = x
x = y
y = swap
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
# Program to generate a random number
import random
print(random.randint(1,10))
# to convert kilometers to miles
1 KILOMETER = O.621371 MILES
kilometers = float(input("Enter value in kilometers: "))
conv_factor = 0.621371
miles = kilometers * conv_factor
print('{} kilometers is equal to {} miles'.format(kilometers, miles))
# python programme to check leap years
print(' please enter year')
year = int(input())
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
else:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
# proramme to print table
print('Enter your number')
n= int(input())
for i in range (1, 11):
print('{} * {} = {}'.format(n, i, n*i))
# find sum of natural numbers
n = int(input())
s = n*(n+1)/2
print(s)
# calculator
import math
def addition(a,b):
print ('sum is:', a+b)
def subtraction(a , b):
print ('subtractio is:', a-b)
def multiplication (a,b):
print ('multiplication is: ', a*b)
def division (a,b):
print ('division is:', int(a/b))
def reminder(a,b):
print('reminder :', a % b)
print('Welcome to Calulator : ')
print('Enter first number:')
n1 = int(input())
print('Enter second number:')
n2 = int(input())
addition(n1, n2)
subtraction(n1,n2)
multiplication(n1,n2)
division(n1,n2)
reminder(n1,n2)
math.sqrt(n1)
|
99a99291c1dc2b399b282914db4e5f57da7f46d8 | darpanhub/python1 | /list.py | 1,242 | 3.796875 | 4 | # student_list=[1,45,6,6,7]
# print(student_list)
# print('Welcome User')
# admin_list = ['manish' , 'darpan' , 'sandeep', 'mohammed']
# print('hey user, Please enter your name for verification')
# name = input()
# if name in admin_list:
# print('hey ' + name + ', happy to see you Welcome back')
# else:
# print('Hey ' + name + ',You are Not a member please register to continue')
# import random
# print('enter number')
# num = input()
# print('Your OTP is :')
# for i in range(6):
# otp = random.choice(num)
# print(otp, end='')
# user register
# user_database = ['darpan','manish','mohammed','sandeep']
# usernames_list = ['darpan','manish','mohammed','sandeep']
# print('Enter First Name')
# first_name = input().strip().lower()
# print('Enter last Name')
# last_name = input().strip().lower()
# print('Enter User Name')
# user_name = input().strip().lower()
# print('Enter your password')
# password = input().strip().lower()
# password2 = input().strip().lower()
# if password == password2:
# user_database['usernames_list'].insert(user_name)
# user_database[user_name +'_password']= password
# print('hey {} Your Account is Created'.format(user_name)) |
cf43e8c07ad2deeeb928439291b3fd97ddcde57c | ronaldoussoren/pyobjc | /pyobjc-core/Examples/Scripts/subclassing-objective-c.py | 1,656 | 4.09375 | 4 | #!/usr/bin/env python
# This is a doctest
"""
=========================================
Subclassing Objective-C classes in Python
=========================================
It is possible to subclass any existing Objective-C class in python.
We start by importing the interface to the Objective-C runtime, although
you'd normally use wrappers for the various frameworks, and then locate
the class we'd like to subclass::
>>> import objc
>>> NSEnumerator = objc.lookUpClass('NSEnumerator')
>>> NSEnumerator
<objective-c class NSEnumerator at 0xa0a039a8>
You can then define a subclass of this class using the usual syntax::
>>> class MyEnumerator (NSEnumerator):
... __slots__ = ('cnt',)
... #
... # Start of the method definitions:
... def init(self):
... self.cnt = 10
... return self
... #
... def nextObject(self):
... if self.cnt == 0:
... return None
... self.cnt -= 1
... return self.cnt
... #
... def __del__(self):
... global DEALLOC_COUNT
... DEALLOC_COUNT = DEALLOC_COUNT + 1
To check that our instances our deallocated we maintain a ``DEALLOC_COUNT``::
>>> DEALLOC_COUNT=0
As always, the creation of instances of Objective-C classes looks a bit odd
for Python programs:
>>> obj = MyEnumerator.alloc().init()
>>> obj.allObjects()
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
Destroy our reference to the object, to check if it will be deallocated::
>>> del obj
>>> DEALLOC_COUNT
1
"""
import doctest
import __main__
doctest.testmod(__main__, verbose=1)
|
eaa7fec6da4273925a0cb7b68c910a729bf26f3c | Yaguit/lab-code-simplicity-efficiency | /your-code/challenge-2.py | 822 | 4.15625 | 4 | """
The code below generates a given number of random strings that consists of numbers and
lower case English letters. You can also define the range of the variable lengths of
the strings being generated.
The code is functional but has a lot of room for improvement. Use what you have learned
about simple and efficient code, refactor the code.
"""
import random
import string
def StringGenerator():
a = int(input('Minimum length: '))
b = int(input('Maximum length: '))
n = int(input('How many strings do you want? '))
list_of_strings = []
for i in range(0,n):
length = random.randrange(a,b)
char = string.ascii_lowercase + string.digits
list_of_strings.append(''.join(random.choice (char) for i in range(length)))
print(list_of_strings)
StringGenerator() |
3b9eb781f9ae784e62b9e4324f34120772209576 | inniyah/MusicDocs | /HiddenMarkovModel.py | 11,115 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See: https://github.com/adeveloperdiary/HiddenMarkovModel
# See: http://www.adeveloperdiary.com/data-science/machine-learning/introduction-to-hidden-markov-model/
import numpy as np
# Hidden Markov Model (θ) has with following parameters :
#
# S = Set of M Hidden States
# A = Transaction Probability Matrix (aij)
# V = Sequence of T observations (vt)
# B = Emission Probability Matrix (Also known as Observation Likelihood) (bjk)
# π = Initial Probability Distribution
# Evaluation Problem: Given the model (θ), we want to determine the probability that
# a particular sequence of visible states/symbol (V) that was generated from the model (θ).
def forward(V, a, b, initial_distribution):
# αj(0) = πj·bjk
alpha = np.zeros((V.shape[0], a.shape[0]))
alpha[0, :] = initial_distribution * b[:, V[0]]
# αj(t+1) = bjkv(t+1)·∑i=1..M, aij·αi(t)
for t in range(1, V.shape[0]):
for j in range(a.shape[0]):
# Matrix Computation Steps
# ((1x2) . (1x2)) * (1)
# (1) * (1)
alpha[t, j] = alpha[t - 1].dot(a[:, j]) * b[j, V[t]]
return alpha
# Backward Algorithm is the time-reversed version of the Forward Algorithm. In Backward Algorithm
# we need to find the probability that the machine will be in hidden state si at time step t
# and will generate the remaining part of the sequence of the visible symbol V.
def backward(V, a, b):
beta = np.zeros((V.shape[0], a.shape[0]))
# setting beta(T) = 1
beta[V.shape[0] - 1] = np.ones((a.shape[0]))
# βi(t) = ∑j=0..M, βj(t+1)·bjkv(t+1)·aij
# Loop in backward way from T-1 to
# Due to python indexing the actual loop will be T-2 to 0
for t in range(V.shape[0] - 2, -1, -1):
for j in range(a.shape[0]):
beta[t, j] = (beta[t + 1] * b[:, V[t + 1]]).dot(a[j, :])
return beta
# Learning Problem: Once the high-level structure (Number of Hidden & Visible States) of
# the model is defined, we want to estimate the Transition (a) & Emission (b) Probabilities
# using the training sequences.
def baum_welch(V, a, b, initial_distribution, n_iter=100):
M = a.shape[0]
T = len(V)
for n in range(n_iter):
alpha = forward(V, a, b, initial_distribution)
beta = backward(V, a, b)
xi = np.zeros((M, M, T - 1))
for t in range(T - 1):
denominator = np.dot(np.dot(alpha[t, :].T, a) * b[:, V[t + 1]].T, beta[t + 1, :])
for i in range(M):
numerator = alpha[t, i] * a[i, :] * b[:, V[t + 1]].T * beta[t + 1, :].T
xi[i, :, t] = numerator / denominator
gamma = np.sum(xi, axis=1)
a = np.sum(xi, 2) / np.sum(gamma, axis=1).reshape((-1, 1))
# Add additional T'th element in gamma
gamma = np.hstack((gamma, np.sum(xi[:, :, T - 2], axis=0).reshape((-1, 1))))
K = b.shape[1]
denominator = np.sum(gamma, axis=1)
for l in range(K):
b[:, l] = np.sum(gamma[:, V == l], axis=1)
b = np.divide(b, denominator.reshape((-1, 1)))
return (a, b)
# Decoding Problem: Once we have the estimates for Transition (a) & Emission (b) Probabilities,
# we can then use the model (θ) to predict the Hidden States W which generated the Visible Sequence V
def viterbi(V, a, b, initial_distribution):
T = V.shape[0]
M = a.shape[0]
omega = np.zeros((T, M))
omega[0, :] = np.log(initial_distribution * b[:, V[0]])
prev = np.zeros((T - 1, M))
# ωi(t+1) = max(i, ωi(t)·aij·bjkv(t+1))
# One implementation trick is to use the log scale so that we dont get the underflow error.
for t in range(1, T):
for j in range(M):
# Same as Forward Probability
probability = omega[t - 1] + np.log(a[:, j]) + np.log(b[j, V[t]])
# This is our most probable state given previous state at time t (1)
prev[t - 1, j] = np.argmax(probability)
# This is the probability of the most probable state (2)
omega[t, j] = np.max(probability)
# Path Array
S = np.zeros(T)
# Find the most probable last hidden state
last_state = np.argmax(omega[T - 1, :])
S[0] = last_state
backtrack_index = 1
for i in range(T - 2, -1, -1):
S[backtrack_index] = prev[i, int(last_state)]
last_state = prev[i, int(last_state)]
backtrack_index += 1
# Flip the path array since we were backtracking
S = np.flip(S, axis=0)
return S
def test_forward(V):
# Transition Probabilities
a = np.array(((0.54, 0.46), (0.49, 0.51)))
# Emission Probabilities
b = np.array(((0.16, 0.26, 0.58), (0.25, 0.28, 0.47)))
# Equal Probabilities for the initial distribution
initial_distribution = np.array((0.5, 0.5))
alpha = forward(V, a, b, initial_distribution)
print(alpha)
def test_backward(V):
# Transition Probabilities
a = np.array(((0.54, 0.46), (0.49, 0.51)))
# Emission Probabilities
b = np.array(((0.16, 0.26, 0.58), (0.25, 0.28, 0.47)))
beta = backward(V, a, b)
print(beta)
def test_baum_welch(V):
# Transition Probabilities
a = np.ones((2, 2))
a = a / np.sum(a, axis=1)
# Emission Probabilities
b = np.array(((1, 3, 5), (2, 4, 6)))
b = b / np.sum(b, axis=1).reshape((-1, 1))
# Equal Probabilities for the initial distribution
initial_distribution = np.array((0.5, 0.5))
print(baum_welch(V, a, b, initial_distribution, n_iter=100))
def test_viterbi(V):
# Transition Probabilities
a = np.ones((2, 2))
a = a / np.sum(a, axis=1)
# Emission Probabilities
b = np.array(((1, 3, 5), (2, 4, 6)))
b = b / np.sum(b, axis=1).reshape((-1, 1))
# Equal Probabilities for the initial distribution
initial_distribution = np.array((0.5, 0.5))
a, b = baum_welch(V, a, b, initial_distribution, n_iter=100)
print([['A', 'B'][int(s)] for s in viterbi(V, a, b, initial_distribution)])
def main():
W = np.array(['B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B',
'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A',
'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B',
'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'A'])
V = np.array([0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 1, 0, 2, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 2,
0, 2, 2, 0, 2, 2, 2, 0, 0, 1, 0, 1, 2, 2, 2, 2, 0, 2, 2, 2, 1, 2, 0, 1, 0, 0, 2, 1, 2, 1, 1, 1, 0, 2, 0, 0, 1,
1, 2, 0, 1, 2, 0, 1, 0, 2, 1, 0, 0, 2, 0, 1, 0, 2, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 1, 2,
2, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 1, 0, 1, 0, 1, 0, 1, 2, 0, 2, 2, 1, 0, 0, 1, 1, 2, 2, 0, 2, 0,
0, 0, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 1, 2, 1, 1, 1, 2, 2,
2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 0, 2, 0, 1, 2, 0, 1, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
0, 0, 1, 2, 1, 0, 2, 2, 1, 2, 2, 2, 1, 0, 1, 2, 2, 2, 1, 0, 1, 0, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 0, 2, 0, 1,
1, 2, 0, 0, 2, 2, 2, 1, 1, 0, 0, 1, 2, 1, 2, 1, 0, 2, 0, 2, 2, 0, 0, 0, 1, 0, 1, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0,
1, 1, 2, 2, 0, 1, 2, 2, 2, 2, 2, 2, 0, 1, 2, 2, 0, 2, 0, 2, 2, 2, 1, 2, 2, 2, 1, 1, 1, 1, 2, 0, 0, 0, 2, 2, 1,
1, 2, 1, 0, 2, 1, 1, 1, 0, 1, 2, 1, 2, 1, 2, 2, 2, 0, 2, 0, 0, 2, 2, 2, 2, 2, 2, 1, 0, 1, 1, 1, 2, 1, 2, 2, 2,
2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 0, 1, 2, 0, 1, 2, 1, 2, 0, 2, 1, 0, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2, 2, 1,
2, 0, 2, 1, 2, 2, 2, 1, 2, 2, 2, 0, 0, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 1, 2, 2, 2, 2, 1, 2, 0,
2, 1, 2, 2, 0, 1, 0, 1, 2, 1, 0, 2, 2, 2, 1, 0, 1, 0, 2, 1, 2, 2, 2, 0, 2, 1, 2, 2, 0, 1, 2, 0, 0, 1, 0, 1, 1,
1, 2, 1, 0, 1, 2, 1, 2, 2, 0, 0, 0, 2, 1, 1, 2, 2, 1, 2])
print("\nTest: Forward:")
test_forward(V)
print("\nTest: Backward:")
test_backward(V)
print("\nTest: Baum Welch:")
test_baum_welch(V)
print("\nTest: Viterbi:")
test_viterbi(V)
if __name__ == '__main__':
main()
|
2e36c061760bd5fc34c226ecbe4b57ef3965c52c | tchen01/tupper | /tupper.py | 368 | 3.515625 | 4 | from PIL import Image
im = Image.open("bd.jpg")
width = im.size[0]
height = im.size[1]
k = ''
def color( c ):
sum = c[0] + c[1] + c[2]
if ( sum < 383 ):
return 1
else:
return 0
for x in range(0, width):
for y in reversed(range(0, height)):
k += str( color( im.getpixel( (x,y) ) ))
k = int(k, base = 2) * height
print("k=",k, "height=", height)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.