blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
788705189f46f7b324bd0b5136c5977b2436e306 | sharan-patil/programs | /Python Files/palindrome.py | 270 | 3.96875 | 4 | from sys import argv
def fail():
print "The given word is not a palindrome!"
exit (0)
name, word = argv
i = len(word)
x = 0
i = i - 1
while x < (i / 2):
if (word[x] != word[i]):
fail()
x = x + 1
i = i - 1
print "The given word is a palindrome!"
|
17108f287870c5a8eb012ae798fb030aa0f5842b | JacobSteinfeld/tic_tac_toe | /tictactoe.py | 3,095 | 4.0625 | 4 | #goal is to play tic tac toe
#first step is to create a board
#once board create X's and O's
#figure out where players want to go
#figure out who wins or draw
#
import numpy as np
board = np.chararray((3, 3))
rows, columns = board.shape
board[:] = "v"
print("Game Start:")
print(board)
#board[0,0] = "x"
#print(board)
gameover = False
turn = 0
#need to make all winning combos ie all horizontal,vertical,and both diagonals
winningcombos = [ [[0,0],[0,1],[0,2]], [[1,0],[1,1],[1,2]], [[2,0],[2,1],[2,2]], [[0,0],[1,0],[2,0]], [[0,1],[1,1],[2,1]], [[0,2],[1,2],[2,2]], [[0,0],[1,1],[2,2]], [[2,0],[1,1],[0,2]] ]
while not gameover:
#while game is active ask players what move they want
#and repeat until win or draw
#x will go on even turns and o will go on odd
# modulo determines even or odd. Player X goes on even turns
if turn % 2 == 0:
xrow = input("Player X Row: ")
xcol = input("Player X Col: ")
#line 26 changes x row and x col from strings to integers
#to index into board
if board[int(xrow), int(xcol)] == b"v":
board[int(xrow), int(xcol)] = "x"
print(board)
else:
print("Player O is in Square")
turn -= 1 # steiny's idea - good shit
else:
orow = input("Player O Row: ")
ocol = input("Player O Col: ")
print(board[int(orow), int(ocol)])
if board[int(orow), int(ocol)] == b"v":
board[int(orow), int(ocol)] = "o"
print(board)
else:
print("Player X is in Square")
turn -= 1
#check to see if x or o won
i = 0
while not gameover and i < len(winningcombos):
# get the positions for each tile in the winning postion
xposone = winningcombos[i][0][0]
yposone = winningcombos[i][0][1]
xpostwo = winningcombos[i][1][0]
ypostwo = winningcombos[i][1][1]
xposthree = winningcombos[i][2][0]
yposthree = winningcombos[i][2][1]
# check if all winning tiles are x's
if board[xposone][yposone] == b'x' and board[xpostwo][ypostwo] == b'x' and board[xposthree][yposthree] == b'x':
gameover = True
print("Player X wins")
# check if all winning tiles are o's
elif board[xposone][yposone] == b'o' and board[xpostwo][ypostwo] == b'o' and board[xposthree][yposthree] == b'o':
gameover = True
print("Player O wins")
i += 1
# scan through board and try to find a vacant tile
vacantfound = False
i = 0
j = 0
while not vacantfound and i < rows:
# if vacant tile found, end loop
if board[i][j] == b'v':
vacantfound = True
# else look in next column
else:
j += 1
# if last column, switch to next row
if j == columns:
i += 1
j = 0
# if all tiles have been played and the game is over, end the game and say draw
if not vacantfound and not gameover:
gameover = True
print("Draw Game")
# next turn
turn += 1
|
3e441eb65c66ccd940f4de674d0389467b3f31f7 | mayhem215/Python | /Количество элементов, равных максимуму.py | 136 | 3.5 | 4 | m = 0
n_m = 0
n = -1
while n != 0:
n = int(input())
if n > m:
m, n_m = n, 1
elif n == m:
n_m += 1
print(n_m) |
e5056e3822d0570192376446598716e8ca7a9d2b | ZhengC1/Practice | /CrackingTheCodingInterview/Chapter8/RobotTransversal.py | 1,921 | 3.578125 | 4 | from collections import deque
import random
from pprint import pprint
class RobotTransversal():
def __init__(self):
# map_size = input("map size: ")
# self.__create_map(map_size)
# print self.bfs()
# pprint(self.map)
self.run_sim()
def run_sim(self):
for i in range(100):
self.__create_map(10)
if self.bfs() == True:
pprint(self.map)
break
def __create_map(self, size):
self.visited = [[False for x in range(size)] for x in range(size)]
self.map = [[random.randint(0, 1) for x in range(size)] for x in range(size)]
self.map[0][0] = 7
self.map[len(self.map) -1][len(self.map) - 1] = 7
def bfs(self):
queue = deque()
queue.append((0, 0))
# starting at top left corner
self.visited[0][0] = True
finish = (len(self.map) - 1, len(self.map) -1)
print finish
while queue:
current = queue.popleft()
if current == finish:
print "Finished"
return True
for path_option in self.__get_path_options(current):
if path_option is None or self.visited[path_option[0]][path_option[1]]:
continue
queue.append(path_option)
self.visited[path_option[0]][path_option[1]] = True
self.map[path_option[0]][path_option[1]] = 7
print "solution was not found"
return False
def __get_path_options(self, current_position):
x = current_position[0]
y = current_position[1]
options = []
if (x + 1) < len(self.map) and (self.map[x + 1][y] != 1):
options.append((x + 1, y))
if (y + 1) < len(self.map) and (self.map[x][y + 1] != 1):
options.append((x, y + 1))
return options
m = RobotTransversal()
|
2b439cfe28a94164aa680e6e91b1e1b1483de591 | Elli-Savi/Dungeon-Game | /DungeonGame.py | 12,805 | 4 | 4 | #Dungeon Game
#flaws
#when waiting for raw_input, if enter is accidentally pressed the game will break
from sys import exit
from random import randint
#global variables
rooms = []
rooms = ['Start', '0', 'Lava', '1', 'Water', '2', 'Trophy', '3', 'Cthulu', '4', 'Nothing', '5', 'Hatter', '6', 'Key', '7', 'Escape', '8']
path = []
room_functions = []
def Start():
path.append(0)
print path
map(path)
print """
You are stuck in a dungeon. It will be very difficult to get out.
Are you excited? Well, you should be.
You can take door 1 or door 2.
Which do you choose?
"""
choice = raw_input("> ")
door = int(choice)
if door == 2:
Water()
else:
Lava()
def Lava():
path.append(1)
print path
map(path)
print """
You have entered the Lava room. Are you ready? Well good.
There are 2 doors on the other side.
Do you:
a) Attempt to surf across with a metal surf board
b) Swing across via a chain. Note: you can't swing or surf back.
c) Turn back
d) Make a silly face
"""
#choice = raw_input("> ")
while True:
choice = raw_input("> ")
if choice == "a" or choice == "A":
print """
You push the surf board into the lava.
It floats, so you step on.
You start to move. Then sink. Oh my the metal is melting!!!
K, so, one cannot surf on a metal surfboard. That was pretty dumb.
"""
dead()
elif choice == "b" or choice == "B":
print """
Do you want to grab onto the chain with your right hand which has a glove?
Or with your left hand which is stronger?
"""
hand = raw_input("> ")
if "left" in hand:
print """
You grab on and jump!
You swing and then the chain tightens, jerking you!
Lucky for you, you can climb down to the walkway.
So the 2 Doors to choose from!
5 on the left or 3 on the right?
"""
while True:
choice = raw_input("> ") #prevents and infinite loop however after going to the function we're still in the while loop
door = int(choice)
if door == 3:
Trophy()
elif door == 5:
Nothing()
else:
print "Ya, that's not a choice. So pick something."
choice = raw_input("> ")
elif "right" in hand:
print """
You swing, you jerk! Aaaaaaand your hand slips. That glove did NOT help.
You accidentally kick a level on the wall...and now lava is seeping..everywhere..
Gah but you're by door 5! jump! go thru! now!!!
"""
Nothing()
elif choice == "c" or choice == "C":
print "\t\tOkay fine, you can turn back."
location = path[-2]
choice = int(location)
print "Location: %d" % choice
pick_a_room(choice)
elif choice == "d" or choice == "D":
print "\t\tSo this is what the Gods think of your silly face:"
print "\t\tThey don't care. Pick another option."
else:
print "\t\tYa, that's not a choice. So pick something."
choice = raw_input("> ")
def Water():
path.append(2)
print path
map(path)
print """
You're in the Water Room!
You can see 2 doors on 2 different walls, across the water.
"""
print "Your previous room location was: %d" % path[-1]
limit = (len(path))-1
if len(path) > 2:
count = 0
for i in range(0, limit):
if path[i+1] == 0:
count = count + 1
else:
count = count
else:
count = 0
print "Count: %d" % count
if len(path)== 2 or (path[-2] == 0 and count == 1):
print """
Do you want to:
a) swim
b) dip your toe in (because you often get cold and it would be good to check)
c) climb the ladder next to you
"""
else:
print """
Do you want to:
a) swim
b) dip your toe in (because you often get cold and it would be good to check)
"""
choice = raw_input("> ")
water_choice(choice)
def water_choice(choice):
if choice == "a" or choice == "A":
print """
You catch some turbulence out of the corner of your eye.
A flaccid, pale, grey face emerges from the water.
Teeth...
Red sores...
...another face...then a swarm...
... the living dead...are coming.
"""
dead()
elif choice == "b" or choice == "B":
print """
Man that water is cold. A little turbulence in the corner of the room.
Do you take your foot out?
"""
answer = raw_input("> ")
if "yes" in answer or "Yes" in answer:
print "\t\tGooooood choice."
print "\t\tWould you like to turn back then?"
choice = raw_input("> ")
if choice == "yes" or choice == "Yes":
if path[-2] == "0" or len(path) == 2:
pick_a_room(0)
elif path[-2] == "3":
pick_a_room(3)
else:
print "\t\tSo the door behind you is locked...and the room is flooding..."
dead()
else:
water_choice("a")
else:
water_choice("a")
elif choice == "c" or choice == "C":
print """
You climb up the ladder next to you. Behold! A kayak. And oar.
Lucky you. You make the wise decision of using the kayak to cross the water.
A turbulence in the corner of the water.
A flaccid, pale, grey face emerges from the water.
Teeth...
Red sores...
...another face...then a swarm...
Luckily for you, you've got an oar! Whack whack Whack! They receed into the water.
Quickly now, the room is flooding! You won't be able to return!
Do you kayak over to room 4 or to room 3?
"""
room = raw_input("> ")
num = int(room)
if num == 3:
Trophy()
elif num == 4:
Cthulu()
else:
print "Listen, you were offered a chance to save yourself but...too slow."
dead()
else:
print "..."
def Trophy():
path.append(3)
print path
map(path)
print "\t\tYou're in the Trophy Room!"
print "\t\tDo you want to take the Trophy or go through the Door?"
choice = raw_input("> ")
if "Trophy" in choice or "trophy" in choice:
print "\t\tPrepare to warp!!!"
rand = randint(0,8) #create a random number from 0 to 8
print "random # %d" % rand
pick_a_room(rand)
elif "Door" in choice or "door" in choice:
print "\t\tWhich door? 2, 7, 6, or 1?"
direction = raw_input("> ")
num = int(direction)
pick_a_room(num)
def Cthulu():
path.append(4)
print path
map(path)
print "\t\tYou're meeting Cthulu!"
print "\t\tGuess what! You die instantly."
dead()
def Nothing():
path.append(5)
print path
map(path)
print "\t\tThere's Nothing interesting in this room!"
print "\t\tEither go through door 1 or through door 6."
while True:
num = raw_input("\t\tWhich one is it? > ")
choice = int(num)
if choice == 1 or choice == 6:
pick_a_room(choice)
else:
print "\t\tYou only have 2 options. Try again. 1 or 6?"
def Hatter():
path.append(6)
print path
map(path)
print "\t\tWelcome to the Mad Hatter and his compadres!"
print "\t\tSo, you can a) talk to the Mad Hatter, b) sit next to the door mouse, or c) talk to the Cheshire Cat."
while True:
choice = raw_input("> ")
if choice == "a" or choice == "A" or "hatter" in choice:
print "\t\tTea time, tip top! Pick a color (ROYGBIV)"
color = raw_input("> ")
rand = randint(1, 7)
print "\t\tTee hee hee, color doesn't matter!"
pick_a_room(rand)
elif choice == "b" or choice == "B" or "mouse" in choice:
print "\t\tTea time, tea time!"
print "\t\tSome advice, don't pick Red, Orange, or Green."
print "\t\tRiddle me this riddle me that try again: mad hatter, mouse, or cat?"
elif choice == "c" or choice == "C" or "cat" in choice:
print "\t\tHow many rooms have you visited, child?"
total = int(raw_input("> "))
count = 0
for i in range(0, len(path)):
for j in range(0, 9):
if path[i] == j:
count = count + 1
else:
count = count
if count == total:
print "\t\tCorrect!"
visit = 2*count - 4
if visit > count:
print "\t\tAnd guess what, you have to visit at least %d more rooms!" % (visit - count)
elif visit <= count:
Escape()
else:
print "\t\tFalse! I get to pick your color!"
Start()
else:
print "\t\tRiddle me this riddle me that try again: mad hatter, mouse, or cat?"
def Key():
path.append(7)
print path
map(path)
print "\t\tGuess what! There are Keys in this room."
print "\t\tA ruby key is hanging in the corner. You can use it on door 4 or the red chest. Which?"
while True:
choice = raw_input("> ")
if "door" in choice or choice == "4":
pick_a_room(4)
elif "chest" in choice:
print """
There's a saphire key in this chest!
It opens door 3 and the saphire chest. Which would you like to open?
"""
while True:
choice = raw_input("> ")
if "door" in choice or choice == "3":
pick_a_room(3)
elif "chest" in choice:
print """
There's an emerald key in this chest!
It opens door 8 and the emerald chest. Which would you like to open?
"""
while True:
choice = raw_input("> ")
if "door" in choice or choice == "8":
pick_a_room(8)
elif "chest" in choice:
print "\t\tThere's nothing actually in the chest...bummer. So what do you want to do?"
else:
print "\t\tSorry, you can't do that. What else would you like to do?"
else:
print "\t\tSorry, you can't do that. What else would you like to do?"
else:
print "\t\tSorry, you can't do that. What else would you like to do?"
def Escape():
path.append(8)
print path
map(path)
print """
Hot damm, you won! You've escaped! Go live your life!
...
...
...
..
......
No seriously,
why are you still here?
"""
exit()
def dead():
print """
Yeah, you died. So sad.
......
...
Yea, not really that sad.
But you're dead.
"""
exit()
def pick_a_room(num):
if num == 0:
Start()
elif num == 1:
Lava()
elif num == 2:
Water()
elif num == 3:
Trophy()
elif num == 4:
Cthulu()
elif num == 5:
Nothing()
elif num == 6:
Hatter()
elif num == 7:
Key()
elif num == 8:
Escape()
else:
print "Your code is totes broken."
def map(path):
print"\t\t ____________ ____________ ____________"
print"\t\t| | | | | |"
print"\t\t| | | | | |"
print"\t\t| |____| |____| |"
print"\t\t| Start ____ %s ____ %s |" % (room_check(2, path), room_check(4, path)) #(rooms[5], rooms[9])
print"\t\t| | | | | |"
print"\t\t| | | | | |"
print"\t\t|____ ____| |____ ____| |____ ____|"
print"\t\t | | | | | |"
print"\t\t ____| |____ ____| |____ ____| |____"
print"\t\t| | | | | |"
print"\t\t| | | | | |"
print"\t\t| |____| |____| |"
print"\t\t| %s ____ %s ____ %s |" % (room_check(1, path), room_check(3, path), room_check(7, path)) #(rooms[3], rooms[7], rooms[15])
print"\t\t| | | | | |"
print"\t\t| | | | | |"
print"\t\t|____ ____| |____ ____| |____ ____|"
print"\t\t | | | | | |"
print"\t\t ____| |____ ____| |____ ____| |____"
print"\t\t| | | | | |"
print"\t\t| | | | | |"
print"\t\t| |____| |____| |"
print"\t\t| %s ____ %s ____ %s |" % (room_check(5, path), room_check(6, path), room_check(8, path))#(rooms[11], rooms[13], rooms[17])
print"\t\t| | | | | |"
print"\t\t| | | | | |"
print"\t\t|____________| |____________| |____________|"
def room_check(choice, path):
check = choice
#print "check: %d " % check
#for i in path(1, 1, len(path)-1):
i = 0
#print "path length: %d" % len(path)
while i < len(path):
if path[i] == check:
room_number = check
#print "room # after if: %s " % room_number
return room_number
else:
room_number = ' '
#print "room # after else: %s " % room_number
i = i + 1
#print "i: %d" % i
return room_number
#room_functions = [Start(), Lava(), Water(), Cthulu(), Nothing(), Hatter(), Key(), Escape()]
Start()
|
fc9268174f952f17212cecf4ccb4441ebbde0bef | TanakitInt/Python-Year1-Archive | /In Class/Week 12/gui/botton.py | 824 | 3.953125 | 4 | # import tkinter
from tkinter import *
def init_window(master):
# initialize the window size
master.geometry('{}x{}'.format(400, 300))
# fixed size window
master.resizable(width=False, height=False)
# window title
master.title("Tkinter GUI: Button")
def init_button(master):
hello_button = Button(master, text='Click Me!', command = lambda: print_message(master))
hello_button.pack()
def print_message(master):
tmp = Label(master, text='Hi! This is the welcome message.').pack()
def main():
# initialize window
root = Tk()
# initialize window
init_window(root)
# initialize buttons
init_button(root)
# Tkinter event loop:
# The program will stay in the event loop until we close the window.
root.mainloop()
if __name__ == ('__main__'):
main()
|
85964f9b0a2acac3bfaf0cbd155954eead008266 | JeanMarieN/Amazon-Review-Analysis | /src/allpositive.py | 549 | 3.546875 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv('../data/raw/phase1_movie_reviews-train.csv')
df = pd.get_dummies(df['polarity'], drop_first=True)
train, test = train_test_split(df, test_size=0.2)
validation, test = train_test_split(test, test_size=0.5)
def predictallpos(dataframe):
return dataframe["positive"].sum()/len(dataframe)
print("Accuracies")
print("Training: "+str(predictallpos(train)))
print("Testing: "+str(predictallpos(test)))
print("Validation: " + str(predictallpos(validation))) |
2034573b685a301981ce49efd1da66553c1b4448 | starmaerker/Algorithmen-und-Datenstrukturen-in-Python | /Suche in Zeichenketten/sequential_search.py | 469 | 3.890625 | 4 | import random
def sequential_search(list_to_search, item):
position = 0
found = False
while position < len(list_to_search) and not found:
if list_to_search[position] == item:
found = True
else:
position += 1
return found, item, position
list_to_search = []
item = random.randint(0, 100)
for _ in range(100):
list_to_search.append(random.randint(0, 100))
print(sequential_search(list_to_search, item))
|
bced2d3c7b5412d844f3e6edef1b8dc0826e9f92 | krocriux/TICS311 | /semana_12_03/Extras/CL/SuperUserDo/SuperUserDo.py | 1,027 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 15:07:46 2018
Examples
0)
{1}
{10}
Returns: 10
Only libraries 1 to 10 must be installed, so the answer is 10.
1)
{1,101}
{10,110}
Returns: 20
2)
{1}
{1000}
Returns: 1000
3)
{1,2,3,4,5}
{6,7,8,9,10}
Returns: 10
In this test case the dependencies have non-empty intersections. One program needs libraries from 1 to 6, another program needs libraries from 2 to 7, and so on. In order to satisfy all dependencies, the package manager will install libraries numbered from 1 to 10, inclusive. Hence, the total number of installed libraries is 10.
4)
{1,1}
{1,1}
Returns: 1
@author: Cristian
"""
from Intervalos import intervalsMaker
A = [1,2,3,4,5]
B = [6,7,8,9,10]
def install(A, B) :
intervals_list = intervalsMaker(A, B)
num_total_libraries = 0
for interval in intervals_list :
num_total_libraries += ((interval[1] - interval[0]) + 1)
return num_total_libraries
|
a0b75637108bba4cba7a5be8280e9ed47b2d8a3f | tennisfar/courses | /MITx/6.00.1x Introduction to Computer Science and Programming/Material/Lecture 5 - Recursion/L5_Problem_6.py | 211 | 3.78125 | 4 | def lenIter(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
# Your code here
number = 0
for c in aStr:
number += 1
return number
print(lenIter('xxxcc'))
|
c6ff4877c4d095840443c5513227f580653175c0 | Tomdssdasd/try | /p4.py | 129 | 3.640625 | 4 | l=[]
for i in range(1,11):
import random
num=random.randint(1,11)
l.append(num)
l.sort()
l.reverse()
print(l) |
7ab6f3e6185d2d876c8d52161eb7a9a8b04715c9 | miaozaiye/PythonLearning | /miaozaiye/1207slideshow.py | 1,488 | 3.515625 | 4 | #从命令行读取2个或者更多图片文件名,然后用淡入淡出的方式来展示
'''
1. get list of filename from sys.argv[1:]
2. while not end, use fade(a,b) to show slide
3. fade(a,b), transfer a to b via n steps, and for i step, the pixel shows the value of average(a+b)
'''
import sys,pygame,PIL
from stdpackage import picture,stddraw
from stdpackage.picture import Picture
from stdpackage.color import Color
def blend(c1,c2,alpha):
r = (1-alpha)*c1.getRed()+alpha*c2.getRed()
g = (1-alpha)*c1.getGreen()+alpha*c2.getGreen()
b = (1-alpha)*c1.getBlue()+alpha*c2.getBlue()
return Color(int(r),int(g),int(b))
def fade(file1,file2):
print('can support extension:', pygame.image.get_extended())
source = Picture(file1)
target = Picture(file2)
n = 5
width =source.width()
height =source.height()
stddraw.setCanvasSize(width,height)
pic = Picture(width,height)
for t in range(n+1):
for col in range(width):
for row in range(height):
c0 = source.get(col,row)
cn = target.get(col,row)
alpha = 1.0*t/n
pic.set(col,row,blend(c0,cn,alpha))
stddraw.picture(pic)
stddraw.show(2)
stddraw.show()
fade('1.bmp','2.bmp')
# def main():
# filelist = sys.argv[1:]
#
# for i in range(len(filelist)):
# if i<len(filelist)-1:
# fade(fade(filelist[i],filelist[i+1]))
# else:
# pass
|
e9ca6aa9d3013fe1467cedcd7318bd91b2cd50c4 | omelkonian/ai-collection | /Sliding Blocks/slidingBlocksGenerator.py | 11,627 | 3.640625 | 4 |
"""
Generates a random grid with the given size and number of non-goal blocks
derived {steps} steps from a random goal state.
Size is given as a tuple (X,Y).
"""
from slidingBlocksUtilities import convertTupleToList, getSize,convertListToTuple,\
getValidActions, printState, getBlockSymbolsList,\
getLeftmosDownCornerPositionOfBlock, getBlockSize
import random
from math import ceil, floor
from slidingBlocks import SlidingBlock
def generateSlidingBlockGrid(size):
grid = None
grid = convertTupleToList(generateGrid(size, 0))
goalBlock = generateGoalBlock(size)
# grid = insertGoalBlockInEmptyGrid(goalBlock, grid)
grid = insertGoalBlockInStartPosition(goalBlock, grid) #{DIFFICULT}
i = 2
while getSpaceNumber(grid) > max(getSize(goalBlock)[0], getSize(goalBlock)[1]) + size[0]: #{DIFFICULT}
# while getSpaceNumber(grid) > (size[0]+size[1]):
newBlock = generateNonGoalBlock(size, i)
if getInsertPosition(newBlock, grid) != (-1, -1):
grid = insertNonGoalBlock(newBlock, grid, i)
else:
continue
i += 1
# grid = performNSteps(grid, steps)
if not checkIfGoalTileIsInUpperLeftHalfgrid(grid):
return generateSlidingBlockGrid(size)
else:
return grid
#_______________________RANDOM ACTIONS OPERATIONS____________________________________________
def performNSteps(grid, n):
temp = SlidingBlock(grid)
for _ in range(n):
validActions = getValidActions(grid)
tempBool = False
# Consider moving the red block first.
for action in validActions:
if action[0] == 1 and action[1] != 'down' and action[1] != 'left':
grid = temp.result(grid, action)
tempBool = True
break
# Consider moving a yellow block down or left.
if not tempBool:
for action in validActions:
if action[0] != 1 and (action[1] == 'down' or action[1] == 'left'):
grid = temp.result(grid, action)
tempBool = True
break
if validActions != [] and not tempBool:
action = random.choice(validActions)
grid = temp.result(grid, action)
return grid
def performNRandomSteps(grid, n):
temp = SlidingBlock(grid)
count = 0
while True:
count += 1
validActions = getValidActions(grid)
if validActions != []:
action = random.choice(validActions)
grid = temp.result(grid, action)
if checkIfGoalTileIsInUpperLeftHalfgrid(grid):
break
else:
if count > 1000:
for symbol in getBlockSymbolsList(grid):
if checkIfAnyTileIsInUpperLeftHalfgrid(grid, symbol):
grid = exchangeBlock(grid, 1, symbol)
continue
return grid
#______________________________GENERATION OPERATIONS__________________________________________________
def generateNonGoalBlock(sizeOfState, symbol):
offset = 1 + sizeOfState[0]/3
blockX = random.randint(1, sizeOfState[0] - offset)
blockY = random.randint(1, sizeOfState[1] - offset)
sizeOfBlock = (blockX, blockY)
return generateGrid(sizeOfBlock, symbol)
def generateGoalBlock(sizeOfState):
offset = 1 + sizeOfState[0]/3
blockX = random.randint(1, sizeOfState[0] - offset)
blockY = random.randint(1, sizeOfState[1] - offset)
sizeOfBlock = (blockX, blockY)
return generateGrid(sizeOfBlock, 1)
def generateGrid(size, symbol):
grid = ()
for _ in range(size[0]):
temp = ()
for _ in range(size[1]):
temp += (symbol, )
grid += (temp, )
return grid
#______________________________CHECKING OPERATIONS_____________________________________
# Checking always from top leftmost corner of block
def checkIfInsertionPossible(grid, block):
(gridX, gridY) = getSize(grid)
(blockX, blockY) = getSize(block)
if insertNonGoalBlock(block, grid, 15) == (-1, -1):
return False
for i in range(len(grid)):
for j in range(len(grid[i])):
if (grid[i][j] == 0):
tempBool = True
for k in range(blockX):
if i + k > gridX - 1:
tempBool = False
break
if grid[i + k][j] != 0:
tempBool = False
break
for l in range(blockY):
if j + l > gridY - 1:
tempBool = False
break
if grid[i][j + l] != 0:
tempBool = False
break
if tempBool:
return True
return False
def getInsertPosition(block, grid):
(gridX, gridY) = getSize(grid)
(blockX, blockY) = getSize(block)
validPositions = []
found = False
for i in range(len(grid)):
for j in range(len(grid[i])):
if (grid[i][j] == 0):
tempBool = True
for k in range(blockX):
for l in range(blockY):
if i + k > gridX - 1 or j + l > gridY - 1:
tempBool = False
break
if grid[i + k][j + l] != 0:
tempBool = False
break
if tempBool:
validPositions.append((i, j))
found = True
if found:
return random.choice(validPositions)
else:
return (-1 ,-1)
def getAverageBlockSize(grid):
totalSizeX = 0
totalSizeY = 0
totalNo = 0
for symbol in getBlockSymbolsList(grid):
totalNo += 1
(sizeX, sizeY) = (getBlockSize(symbol, grid))
totalSizeX += sizeX
totalSizeY += sizeY
return (totalSizeX/totalNo, totalSizeY/totalNo)
#________________________________INSERTION OPERATIONS___________________________
def insertNonGoalBlock(block, grid, symbol):
(blockX, blockY) = getSize(block)
# Get the position of the leftmost upper corner
insertPos = getInsertPosition(block, grid)
i = insertPos[0]
j = insertPos[1]
grid = convertTupleToList(grid)
grid[i][j] = symbol
# Fill it up
for k in range(blockX):
for l in range(blockY):
if grid[i + k][j + l] == 0:
grid[i + k][j + l] = symbol
return convertListToTuple(grid)
def insertGoalBlockInEmptyGrid(goalBlock, emptyGrid):
emptyGrid = convertTupleToList(emptyGrid)
for i in range(len(emptyGrid) - getSize(goalBlock)[0], len(emptyGrid)):
for j in range (0, getSize(goalBlock)[1]):
emptyGrid[i][j] = 1
return convertListToTuple(emptyGrid)
def insertGoalBlockInStartPosition(goalBlock, emptyGrid):
emptyGrid = convertTupleToList(emptyGrid)
goalSize = getSize(goalBlock)
for i in range(0, goalSize[0]):
for j in range (len(emptyGrid[i]) - goalSize[1], len(emptyGrid[i])):
emptyGrid[i][j] = 1
return convertListToTuple(emptyGrid)
def getSpaceNumber(grid):
total = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 0:
total += 1
return total
def checkIfGoalTileIsInUpperLeftHalfgrid(grid):
for i in range(0, int(floor(len(grid)/2))):
for j in range(int(floor(len(grid)/2)), len(grid)):
if grid[i][j] == 1:
return True
return False
def checkIfAnyTileIsInUpperLeftHalfgrid(grid, symbol):
for i in range(0, int(floor(len(grid)/2))):
for j in range(int(floor(len(grid)/2)), len(grid)):
if grid[i][j] == symbol:
return True
return False
#_______________________________EXTEND OPERATIONS (NOT USED GENERALLY)_____________________________________
def extendBottom(grid, (x,y), blockY, symbol):
grid = convertTupleToList(grid)
for j in range(y, y + blockY):
grid[x + 1][j] = symbol
return convertListToTuple(grid)
def extendLeft(grid, (x,y), blockX, symbol):
grid = convertTupleToList(grid)
for i in range(x - blockX + 1, x + 1):
grid[i][y - 1] = symbol
return convertListToTuple(grid)
def extendTop(grid, (x,y), blockX, blockY, symbol):
grid = convertTupleToList(grid)
for j in range(y, y + blockY):
grid[x - blockX][j] = symbol
return convertListToTuple(grid)
def extendRight(grid, (x,y), blockX, blockY, symbol):
grid = convertTupleToList(grid)
for i in range(x - blockX + 1, x + 1):
grid[i][y + blockY] = symbol
return convertListToTuple(grid)
def extendBlock(grid, symbol):
(x, y) = getLeftmosDownCornerPositionOfBlock(grid, symbol)
(blockX, blockY) = getBlockSize(symbol, grid)
# Check bottom side.
if x + 1 < len(grid):
tempBool = True
for j in range(y, y + blockY):
if grid[x + 1][j] != 0:
tempBool = False
break
if tempBool:
grid = extendBottom(grid, (x, y), blockY, symbol)
return grid
# Check left side.
if y - 1 >= 0:
tempBool = True
for i in range(x - blockX + 1, x + 1):
if grid[i][y - 1] != 0:
tempBool = False
break
if tempBool:
grid = extendLeft(grid, (x, y), blockX, symbol)
return grid
# Check top side.
if x - blockX >= 0:
tempBool = True
for j in range(y, y + blockY):
if grid[x - blockX][j] != 0:
tempBool = False
break
if tempBool:
grid = extendTop(grid, (x, y), blockX, blockY, symbol)
return grid
# Check right side.
if y + blockY < len(grid[0]):
tempBool = True
for i in range(x - blockX + 1, x + 1):
if grid[i][y + blockY] != 0:
tempBool = False
break
if tempBool:
grid = extendRight(grid, (x, y), blockX, blockY, symbol)
return grid
return grid
def extendBlocks(grid, extends):
symbols = getBlockSymbolsList(grid)
for _ in range(extends):
if symbols == []:
break
symbol = random.choice(symbols)
grid = extendBlock(grid, symbol)
symbols.remove(symbol)
return grid
def exchangeBlock(grid, symbol1, symbol2):
visitedPos = set()
grid = convertTupleToList(grid)
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == symbol1:
visitedPos.add((i, j))
grid[i][j] = symbol2
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == symbol2 and (i, j) not in visitedPos:
grid[i][j] = symbol1
return convertListToTuple(grid)
|
99a344d1d5a6b4a1238d4a5212e3a6b39a7de5cb | 1ambda/data-analysis | /intro-to-data-science/week5/memoization.py | 650 | 3.828125 | 4 | def fib(n):
assert type(n) == int and n >= 0
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def testFib(n):
assert type(n) == int and n >= 0
for i in range(n):
print ('fib of', i, '=', fib(i))
def fastFib(n, memo):
assert type(n) == int and n >= 0
if n == 0 or n == 1:
return 1
if n in memo:
return memo[n]
result = fastFib(n-1, memo) + fastFib(n-2, memo)
memo[n] = result
return result
def testFastFib(n):
assert type(n) == int and n >= 0
for i in range(n):
print ('fast fib of', i, '=', fastFib(i, {}))
testFastFib(40)
|
9fc480dcd206444261e10d4274042742f0be4128 | jennings1716/Datastructure | /doubly_linked_list.py | 4,822 | 3.96875 | 4 | #Double Linked List
#A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer,
#together with next pointer and data which are there in singly linked list.
import time
class Node:
def __init__(self,data):
self.data=data
self.prev=None
self.next= None
if __name__=='__main__':
print('Enter The Option \n')
option = input(' 1. Create root node \n 2. insert a node \n 3. traversing \n 4. Delete a node'+
'\n 5. Break \n')
option = int(option)
root = None
while(True):
if(option==1):
if(root==None):
data=input(" Enter the data for root node ")
root=Node(data)
root.prev=None
root.next=None
last=root
print(" Root Node Created ")
else:
print(" Root Node Already created ")
if(option==2):
flag=0
t=root
while t:
if t.next==None:
last=t
break
t=t.next
if(root!=None):
data=input(" Enter the data near to which you have to enter")
t=root
while t:
if t.data==data:
flag=1
break
t=t.next
if(flag==0):
print("Data is not found")
if(flag==1):
new_data = input(" Enter the data of new node")
pos = input(" Enter the position \n 1.before \n 2.After")
node = Node(new_data)
temp = root
while temp:
if temp.data == data:
if(pos=='1'):
if(temp.data==root.data):
temp.prev=node
node.next=root
root=node
break
else:
previous = temp.prev
previous.next=node
node.prev=previous
node.next=temp
previous=node
break
if(pos=='2'):
if(temp.data==last.data ):
node.prev=last
last.next=node
last=node
break
else:
node.next=temp.next
temp.next.prev=node
temp.next = node
node.prev= temp
break
temp=temp.next
else:
print("You have no root node please create a root")
if(option==3):
if(root!=None):
temp=root
print("\n The Nodes are")
while temp:
print(temp.data)
temp=temp.next
else:
print("You have no root node please create a root node")
if(option==4):
if(root!=None):
del_node = input(" Enter the data of node to be deleted")
temp=root
while temp:
previous=temp.prev
next_node=temp.next
if(temp.data==del_node):
if(next_node==None and previous==None):
root=None
print("Root node deleted")
elif(next_node==None):
previous.next=None
elif(previous==None):
next_node.prev=None
root=next_node
else:
previous.next=next_node
next_node.prev=previous
temp=temp.next
else:
print("You have no nodes to delete")
if(option==5):
print("Break")
break
time.sleep(0.4)
print('\n')
option = input(' 1. Create root node \n 2. insert a node \n 3. traversing \n 4. Delete a node'+
'\n 5. Break \n')
option = int(option)
|
53ca343c61173921febd4ed4bff501e2aad5bff2 | tjohnson1988/week1 | /birthday_checker.py | 894 | 4.5625 | 5 | #Take a users input and return their name + birthday. If today is there
# birthday output “Happy Birthday!”
# use .strftime to formats dates in a specific manner
# https://www.programiz.com/python-programming/datetime
# https://www.youtube.com/watch?v=hj6Tgc4hEU0&ab_channel=CleverProgrammer
from datetime import datetime
current_day = datetime.now().day
#print(current_day)
current_month = datetime.now().month
#print(current_month)
name = input("Enter your name:")
#print(name)
birth_month = int(input("Enter your birth month (01-12):"))
#print(birth_month)
birth_day = int(input("Enter your day of birth:"))
#print(birth_day)
birth_year = input("Enter your birth year:")
if (current_day == birth_day) and (current_month == birth_month):
print("Happy Birthday!")
else:
print("Hi", name + ". Your birthday is", str(birth_month) + "-" + str(birth_day) + "-" + birth_year + ".") |
c5aab13827a083030540c797cc1fb37c2be86aa9 | MihailMihaylov75/algorithms | /unique_characters_in_string.py | 481 | 3.78125 | 4 | __author__ = 'Mihail Mihaylov'
# Given string determine if it is compressed of unique characters
def find_unique_characters_in_str1(string):
""""Find unique characters in string vol 1"""
return len(set(string)) == len(string)
def find_unique_characters_in_str2(string):
""""Find unique characters in string vol 2"""
chars = set()
for letter in string:
if letter in chars:
return False
else:
chars.add(letter)
return True
|
9936d2b2366f831beaecf120189b635203f2d0bc | Vincentxjh/practice0723 | /009.py | 470 | 3.78125 | 4 | #第九个练习-模拟手机充值场景
money = int(input("欢迎使用XXX充值服务,请输入您要充值的金额:"))
t = int(input("您输入的充值金额为:" + str(money) +"元,确认充值请按1,取消充值请按2: "))
if t==1:
print("充值成功,您本次充值金额为" + str(money) + "元。")
elif t==2:
print("取消成功,您本次未充值。")
else:
print("对不起,您的输入有误,请重新输入。") |
f8c8fd6a5360a32fb648401a3de2b5358f3a86d7 | jikka/pythong | /comp.py | 152 | 3.65625 | 4 | n=input("\nEnter the n value")
k=input("\nEnter the k value")
a=list(str(n))
b=0
for i in n:
for j in k:
if i==j:
b=b+1
print(b)
|
8d0c495af3bf6f44d733bfede2d845c5d6f1d6e6 | olzhas23/thinkful | /parser.py | 193 | 3.640625 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display Square of any given argument", type=int)
args=parser.parse_args()
print args.square**2
|
6f6d8094f94fc005e3b1b0bd156ec85a943c0479 | javilamarque/ITEDES | /modulo1/segmento3/apunte3 "IF - ELSE IF (ELSE)"/ejercicio3/ejercicio3.py | 255 | 4 | 4 | caracter = int(input("Ingrese un caracter para saber si es una (vocal, consonante, numero): "))
if(caracter == "a" or "e" or "i" or "o" or "u"):
opcion = "vocal"
elif(caracter.isdigit()):
opcion = "numero"
else:
opcion = "consonante"
print(opcion)
|
fd0e80daae65fe7bf5695b60fd2a161bd1ff33eb | appleface2050/Coursera-ML | /johnwittenauer/src/multiple_linear_regression.py | 1,107 | 3.890625 | 4 | # coding=utf-8
"""
http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-2/
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from util.lib import computeCost, gradient_descent
if __name__ == '__main__':
path = os.getcwd() + "\data\ex1data2.txt"
data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
print (data2.head())
# add ones column
data2.insert(0, 'Ones', 1)
# set X (training data) and y (target variable)
cols = data2.shape[1]
X2 = data2.iloc[:,0:cols-1]
y2 = data2.iloc[:,cols-1:cols]
# convert to matrices and initialize theta
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
# theta2 = np.matrix(np.array([0,0,0]))
theta2 = np.matrix(np.zeros(X2.shape[1]))
theta2 = theta2.T
print(X2.shape, theta2.shape, y2.shape)
# perform linear regression on the data set
alpha = 0.001
iters = 30
g2, cost2, final_cost2 = gradient_descent(X2, y2, theta2, alpha, iters)
# get the cost (error) of the model
print (computeCost(X2, y2, g2)) |
65503ec44eaa52c4d65ca7f85b7c850d25af1324 | mpalliser/Programacion | /caminandoEnLaNiebla/Ejercicio12.py | 330 | 3.90625 | 4 | primer_numero = int (input("Introduce el primer numero "))
segundo_numero = int (input("Introduce el segundo numero "))
if primer_numero%2 ==0 and segundo_numero%2 ==0 and primer_numero <=50 and segundo_numero >99 and segundo_numero <=501 :
suma = primer_numero + segundo_numero
print (suma)
else:
print ("Error")
|
d8bd41c97e3607c2fef4f633a3171d9c248cd081 | sunatthegilddotcom/hyperAFM | /GUI/Practice/thenewboston/13.shapes_graphics.py | 568 | 4.21875 | 4 | '''
SHAPES AND GRAPHICS
'''
from tkinter import *
root = Tk()
#making a canvas to draw on
canvas = Canvas(root, width=200, height=100)
canvas.pack()
#all lines by default will be black
#set parameters for the line- first parameters will tell where to begin,
#the other two will tell how big it wil be
blackLine = canvas.create_line(0,0, 200, 50)
redLine = canvas.create_line(0,100, 200, 50, fill="red")
#create rectangle
greenBox = canvas.create_rectangle(25,25, 130, 60, fill = "green")
#if we want to delete a graphic
#canvas.delete(redLine)
root.mainloop()
|
af588e59157b133c81fc9b8cba5737d4cda03d13 | TheNew000/python101 | /dc_Code_Challenge.py | 3,472 | 4.53125 | 5 | # 1) Declare two variables, a string and an integer
# named "fullName" and "age". Set them equal to your name and age.
full_name = "Danny Arango"
age = 31
# 2) Declare an empty array called "myArray".
# Add the variables from #1 (fullName and age) to the empty array using the push method.
# Print to the console.
my_list = []
my_list.append(full_name)
my_list.append(age)
print my_list
# 3) Write a simple function that takes no parameters called "sayHello".
# Make it print "Hello!" to the console when called.
# Call the function.
def say_hello():
print "Hello!"
say_hello()
# 4) Declare a variable named splitName and set it equal to
# fullName split into two seperate objects in an array.
# (In other words, if the variable fullName is equal to "John Smith", then splitName should
# equal ["John", "Smith"].)
# Print splitName to the console.
# HINT: Remember to research the methods and concepts listed in the instructions PDF.
split_name = full_name.split()
print split_name
# 5) Write another simple function that takes no parameters called "sayName".
# When called, this function should print "Hello, ____!" to the console, where the blank is
# equal to the first value in the splitName array from #4.
# Call the function. (In our example, "Hello, John!" would be printed to the console.)
def say_name():
# print "Hello, " + split_name[0]
string = "Hello, my first name is {}. My last name is {}. My Age is {}"
print string.format(split_name[0], split_name[1], age)
say_name()
# 6) Write another function named myAge. This function should take one parameter: the year you
# were born, and it should print the implied age to the console.
# Call the function, passing the year you were born as the argument/parameter.
# HINT: http://www.w3schools.com/js/js_functions.asp
import datetime
def my_age(birth_year):
now = datetime.datetime.now()
print now.year - birth_year
my_age(1985)
# 7) Using the basic function given below, add code so that sum_odd_numbers will print to the console the sum of all the odd numbers from 1 to 5000. Don't forget to call the function!
# HINT: Consider using a 'for loop'.
# function sum_odd_numbers() {
# var sum = 0;
# // Write your code here
# console.log(sum);
# }
def sum_odd_numbers():
sum = 0
for i in range(1, 5000):
if i % 2 != 0:
sum += i
print sum
sum_odd_numbers()
# Make Squares
squares =[]
for i in range(1, 11):
# ** = squared
square = i**2
squares.append(square)
print squares
digits = [12, 3252354, 4235, 55, 534, 34545, 43534, 3455, 676556, 890, 123]
#Max and Min
print min(digits)
print max(digits)
print sum(digits)
squares = [i**2 for i in range(1, 11)]
print squares
# step = the incrementor
print range(1,11,2)
# slice in python is all about the :
dc_team = ['Max', 'Jake', 'Rob', 'Toby', 'Natalie']
team_part = dc_team[1:3]
print team_part
team_part = dc_team[1:-1]
print team_part
team_part = dc_team[:1]
print team_part
team_part = dc_team[2:]
print team_part
team_copy = dc_team
print team_copy
print dc_team
# Will keep a connection between the two lists so any change done to one list will affect both lists
team_copy = dc_team
team_copy.append('Luis')
print team_copy
print dc_team
# makes a new list independent of the old one
team_copy = list(dc_team)
team_copy.append('DeAnn')
print team_copy
print dc_team
team_copy = dc_team[:]
team_copy.append('DeAnn')
print team_copy
print dc_team
|
b6f1bf5c0a73d239c41c63553a10875b0bb50fe9 | mohammad-saber/CNN_classification_feature_extraction | /tools/visualization.py | 7,812 | 3.515625 | 4 |
# Visualization tools
import matplotlib.pyplot as plt
import numpy as np
import torch, torchvision
from torchvision import datasets
import itertools
from sklearn.metrics import confusion_matrix
import pandas as pd
def show_image_batch(data_loader, path, mean, std, class_names):
"""
Visualize training images, one batch. This function is called before training.
data_loader: usually train_loader is passed. Because transforms are all applied on train dataset.
"""
# Get a batch of training data , iteration through train dataset and get the next value
images, classes = next(iter(data_loader))
title=[class_names[x] for x in classes]
# Make a grid from batch. It concatenates all images into one Tensor.
# nrow : Number of images displayed in each row of the grid.
image = torchvision.utils.make_grid(images, nrow=8)
# Input is Image but it was converted into PyTorch tensor by data_transforms. We need to re-convert tensor into numpy array before image show.
# Convert PyTorch tensor into numpy array , put the 1st 2nd dimensions in the 0 and 1st dimentions.
# and put the 0 dimension into 3rd dimention. Because in PyTorch, Image Tensor is (C x H x W).
image = image.numpy().transpose((1, 2, 0))
image = std * image + mean # In data_transforms, we used transforms.Normalize. This code is de-normalization before image show.
image = np.clip(image, 0, 1) # Clip (limit) the values in an array. Otherwise, there might be warning.
fig = plt.figure()
plt.imshow(image)
plt.title(title)
#plt.pause(0.001) # pause a bit so that plots are updated
fig.savefig(path)
plt.close()
def show_image(data_folder, path, mean, std, image_num=6, row = 1, title = "Data Augmentation Result"):
"""
Visualize training images. This function is called before training.
data_folder: usually train_folders is passed. Because transforms are all applied on train dataset.
images_num: number of images you would like to show.
path: path to save figure
row: number of rowa in image grid
"""
class_names = data_folder.classes # name of classes
total_img = [] # List that keeps all images, every image is a Numpy array.
labels = []
for num in range(image_num):
image = np.array(data_folder.__getitem__(num)[0]).transpose((1, 2, 0)) # data_folder.__getitem__(num)[0] is the image
image = std * image + mean # In data_transforms, we used transforms.Normalize. This code is de-normalization before image show.
image = np.clip(image, 0, 1) # Clip (limit) the values in an array. Otherwise, there might be warning.
total_img.append(image)
labels.append(class_names[data_folder.__getitem__(num)[1]]) # data_folder.__getitem__(num)[1] is the index of class
fig = plt.figure()
plt.axis("off") # hide axis
plt.title(title, fontweight='bold')
for n, (image, label) in enumerate(zip(total_img, labels)):
ax = fig.add_subplot(row, np.ceil(image_num / float(row)), n + 1)
if image.ndim == 2:
plt.gray() # Set the colormap to "gray"
plt.axis("off")
plt.imshow(image)
ax.set_title(label)
fig.set_size_inches(fig.get_size_inches() * int(image_num/6))
plt.savefig(path)
plt.close()
def plot_graph(data_dict, title, x_label, y_label, path, y_scale_log=False):
'''
Plots the accuracy and loss vs epoch for train and test data (after training).
This function can plot accuracy or loss for several models.
data_dict: a dictionary containing accuracy or loss of the trained models.
Every model has a key in this dictionary. In fact, key is the model name.
path: path to save graph as an image file
'''
fig = plt.figure()
for model in data_dict.keys(): # loop over Keys. Key is the model name.
plt.plot(list(range(1, len(data_dict[model])+1)), data_dict[model], label=model)
plt.xlabel(x_label)
plt.ylabel(y_label)
if y_scale_log: plt.yscale("log")
plt.title(title)
plt.legend()
fig.savefig(path, dpi=200)
plt.close()
def plot_confusion_matrix(cm, class_names, save_path, normalize=True, title='Confusion Matrix', cmap=plt.cm.Blues):
if normalize:
# axis = 1: rows ; [:, np.newaxis] adds one more dimension to the 1D array
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig, ax = plt.subplots()
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(class_names))
plt.xticks(tick_marks, class_names, rotation=45)
plt.yticks(tick_marks, class_names)
ax.xaxis.tick_top() # send x-labels to the top of the plot
fmt = '.2f' if normalize else 'd' # format to display numbers
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] >= thresh else "black") # j is x direction, i is y direction
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.tight_layout()
plt.savefig(save_path)
plt.close()
def visualize_prediction(dataset_path, save_path, model, model_name, test_transforms,
mean, std, cuda, images_num=12, row=2, title = 'Model Prediction'):
'''
Display predictions for a few images, this function is called after training
dataset_path: usually test dataset path is passed.
images_num: number of images you would like to show.
save_path: path to save figure
row: number of rows in image grid
'''
dataset_folders = datasets.ImageFolder(dataset_path, test_transforms)
dataset_loader = torch.utils.data.DataLoader(dataset_folders, batch_size=images_num, shuffle=True)
class_names = dataset_folders.classes # name of classes
model.eval()
images, labels = next(iter(dataset_loader))
fig = plt.figure()
plt.axis("off") # hide axis
plt.title(title, fontweight='bold')
with torch.no_grad():
for i in range(images.shape[0]): # images.size()[0] is Batch Size
image_tensor = images[i,:,:,:] # shape : [channel_num, H, W]
image_tensor = image_tensor[None, :, :, :] # shape : [1, channel_num, H, W]
if cuda:
model = model.cuda()
image_tensor = image_tensor.cuda()
if model_name == 'vgg16':
output = model(image_tensor)[-1]
else:
output = model(image_tensor)
_, preds = torch.max(output, 1)
image = np.array(images[i,:,:,:]).transpose((1, 2, 0)) # [H, W, channel_num]
image = std * image + mean # In data_transforms, we used transforms.Normalize. This code is de-normalization before image show.
image = np.clip(image, 0, 1) # Clip (limit) the values in an array. Otherwise, there might be warning.
ax = fig.add_subplot(row, np.ceil(images_num / float(row)), i + 1)
if image.ndim == 2:
plt.gray() # Set the colormap to "gray"
plt.axis("off")
plt.imshow(image)
ax.set_title(class_names[preds])
plt.savefig(save_path)
plt.close()
model = model.cpu() # some functions require model on CPU.
def pretty_confusion_matrix(y_true, y_pred, class_names):
cm = confusion_matrix(y_true, y_pred)
pred_labels = ['Predicted '+ l for l in class_names]
df = pd.DataFrame(cm, index=class_names, columns=pred_labels)
return df
|
7aae923467dc9c64553c90ebfdd2425449dd943d | freddyfok/cs_with_python | /problems/leetcode/14_longest_common_prefix.py | 498 | 3.765625 | 4 | from typing import List
def longest_common_prefix(strs: List[str]) -> str:
if not strs:
return ""
if len(strs) == 1:
return strs[0]
prefix = strs[0]
prefix_len = len(prefix)
for s in strs[1:]:
while prefix != s[0:prefix_len]:
prefix = prefix[:-1]
prefix_len = len(prefix)
if prefix_len == 0:
return ""
return prefix
str[0] = flower
str[1] = flow
str[2] = flight
|
169938151efa7004a4ba1220d56cb1c091cd9b96 | kelian33/CryptoMoney | /cryptomoney.py | 849 | 3.546875 | 4 | #!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
import requests
liste_nom=requests.get('https://www.cryptocompare.com/api/data/coinlist/')
datas=liste_nom.json()
names_money = datas['Data']
fini = False
while fini != True :
money = input("Entrez le nom d'une cryptomoney sinon tapez 'liste' ou 'exit' : ")
if(money == "liste"):
for name_money in names_money :
print(name_money)
fini = False
elif(money == "exit"):
fini = True
else :
liste_prix = requests.get('https://min-api.cryptocompare.com/data/price?fsym='+money+'&tsyms=USD,EUR')
prix=liste_prix.json()
nom_money = datas['Data'][money]['FullName']
print("Voici le prix de : "+nom_money)
print("1",money,"=",prix['EUR'],"€")
print("1",money,"=",prix['USD'],"$")
fini = False
|
7424bbe296c60c382e35b013345c58af3ffa162d | nervylof/GloAcademy_python | /Урок 9/Задание 1.py | 197 | 3.984375 | 4 | while True:
num = int(input())
if num < 10:
continue
elif num > 100:
break
elif num > 10 or num < 101:
a = num
num = int(input())
print(a)
|
a86d4b218caba91487f183a9a2802738b007383c | naughtybabyfirst/algorithm | /Similarity_NLP/distance.py | 308 | 4.09375 | 4 | # -*- coding: utf-8 -*-
terms = ['Believe', 'believe', 'bargain']
def manhattan_distance(u, v, norm = False):
if u.shape != v.shape:
raise ValueError('length error..')
return abs(u - v).sum() if not norm else abs(u - v).mean()
for term in terms:
print(manhattan_distance()) |
93a35a3dc84a8a107baca4ddc39a1141367d718d | JulietaAtanasova/programming0 | /week1/conditional-statements/grader.py | 559 | 4.1875 | 4 | min_grade = 0
max_grade = 100
grade = int(input("Enter grade: "))
if min_grade <= grade <= (max_grade // 2):
print("Слаб 2")
elif (max_grade // 2 + 1) <= grade <= (max_grade // 2 + 10):
print("Среден 3")
elif (max_grade // 2 + 11) <= grade <= (max_grade // 2 + 20):
print("Добър 4")
elif (max_grade // 2 + 21) <= grade <= (max_grade // 2 + 30):
print("Много Добър 5")
elif (max_grade // 2 + 31) <= grade < max_grade:
print("Отличен 6")
elif grade == max_grade:
print("Много отличен 7") |
35679430edf848079e4a3c6dd339ee3c12e14c89 | jesee030/pythonProject | /Python开发技术—面向对象程序设计1/类和对象/src/step2/pointtest.py | 399 | 3.6875 | 4 | from point import Point
x1,y1 = input().split(',')
x2,y2 = input().split(',')
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
dx,dy = input().split(',')
dx = int(dx)
dy = int(dy)
p1 = Point(x1, y1)
p2 = Point(x2,y2)
print('p1点的坐标为:',p1)
print('p2点的坐标为:',p2)
p2.move_by(dx, dy)
print('移动后的坐标为:',p2)
print('p1与p2点的距离为:',p1.distance_to(p2)) |
fa93d4db389eb2aed9ee0094ad4502aaf8d9cebc | Quiver92/edX_Introduction-to-Python-Creating-Scalable-Robust-Interactive-Code | /Date_and_Time_Arithmetic/Task_2.py | 811 | 4.3125 | 4 | # [ ] Write a program to compute the date 3 weeks before your birthday
# to help you remember when to send the invitations
from datetime import datetime, timedelta
today = datetime.today()
my_birthday = datetime(today.year, 11, 17)
three_weeks_ago = timedelta(weeks = 3)
three_weeks_before_my_birhtday = my_birthday - three_weeks_ago
print(three_weeks_before_my_birhtday.strftime("%b/%d/%Y"))
# [ ] Write a program that computes the number of days from the current date till the 3 weeks reminder
# 1) Create a `timedelta` object (td1) for the period between the current date and your upcoming birthday
# 2) Create a `timedelta` object (td2) containing 3 weeks
# 3) Use the `timedelta` objects (td) from 1 and 2 to compute the required number of days
td0 = today - three_weeks_ago
print(td0.total_seconds())
|
e4fba18b052549633dde00c090ffcde1833c8631 | bailong0108/1807 | /07day/12-账号.py | 292 | 3.78125 | 4 | account = "123456"
passwd = "abc"
act = input("请输入你的账号:")
pwd = input("请输入你的密码:")
if act == account and pwd == passwd:
print("登录成功")
elif act != account:
print("账号不正确")
elif pwd != passwd:
print("密码不正确")
else:
print("重新输入")
|
3b2e91b72cb58c35cbfd4806427f39a36eaf9140 | delamorinierejh/Exercism | /python/word-count/word_count.py | 236 | 3.65625 | 4 | import re
def word_count(str):
str = str.decode('utf-8')
sentence = re.sub("[\W]|_", " ", str, re.UNICODE)
d = {}
for word in sentence.lower().split():
if word in d:
d[word] += 1
else:
d[word] = 1
return d |
97e626812bdd6c8683a3b56a1b7533372046c975 | tashakim/puzzles_python | /enqueue.py | 552 | 4.25 | 4 | # Simple python implementation of a queue
def enqueue(mylist, value) :
mylist.append(value)
return mylist
def dequeue(mylist) :
if mylist == [] :
print("list is empty")
return mylist
mylist.remove(mylist[0])
return mylist
if __name__ == "__main__":
mylist = [1,2,3]
print(enqueue(mylist, 4))
print(dequeue(mylist))
assert dequeue([]) == [], "Error!"
# Taking in user's input
print("what number do you want to enqueue? : ")
your_choice = input()
enqueue(mylist, int(your_choice))
# List with user's input enqueued.
print(mylist) |
903b95370d8c4008f59eaab498b5a404ef0458b8 | mohankumarp/Training | /Python_RF_Training/Python/LAB/variable_printing.py | 1,032 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: MohanKumarP
#
# Created: 22/12/2015
# Copyright: (c) MohanKumarP 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (
my_age, my_height, my_weight, my_age + my_height + my_weight)
if __name__ == '__main__':
main()
|
b780ec075d3caee0425f78e560a411842f82202e | huiyi999/leetcode_python | /Valid Parentheses.py | 2,387 | 3.921875 | 4 | '''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
'''
class Solution:
def isValid4(self, s: str) -> bool:
brackets = {
'(': ')',
'[': ']',
'{': '}'
}
open = []
for c in s:
if c in brackets:
open.append(c)
else:
if not open:
return False
elif c != brackets[open[-1]]:
return False
elif c == brackets[open[-1]]:
open.pop(-1)
return not open
def isValid3(self, s):
"""
:type s: str
:rtype: bool
"""
pars = [None]
parmap = {')': '(', '}': '{', ']': '['}
for c in s:
if c in parmap:
if parmap[c] != pars.pop():
return False
else:
pars.append(c)
return len(pars) == 1
def isValid2(self, s):
"""
:type s: str
:rtype: bool
"""
pars = [None]
parmap = {')': '(', '}': '{', ']': '['}
for c in s:
if c in parmap and parmap[c] == pars[len(pars) - 1]:
pars.pop()
else:
pars.append(c)
return len(pars) == 1
def isValid(self, s: str) -> bool:
stack = []
characters = {")": "(", "}": "{", "]": "["}
for ch in s:
if ch not in characters: # ch not in characters.keys 说明是左半部分
stack.append(ch)
else:
if not stack:
return False
elif characters[ch] != stack.pop():
return False
else:
stack.pop()
return len(stack) == 0
so = Solution()
print(so.isValid("()"))
print(so.isValid("()[]{}"))
print(so.isValid("(]"))
print(so.isValid("([)]"))
print(so.isValid("{[]}"))
'''
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
'''
|
a156b75c3f4d12088ac763d30edc9d82401b3ff4 | bhaumikmistry/mindDB | /software/aoc/2020/day8/run.py | 1,812 | 3.703125 | 4 | import copy
def open_file(file_path):
with open(file_path, 'r') as f:
entries = [entry.split('\n')[0] for entry in f.readlines()]
return entries
def program_2(data):
visited_list = program_1(data)
if len(visited_list) is 1:
return visited_list[0]
index = 0
old_data = copy.deepcopy(data)
while True:
if index >= len(data) or index < 0:
return -1
print(index)
c, n = data[index]
if c == "nop":
print("change ", data[index], ("jmp", n))
data = copy.deepcopy(old_data)
data[index] = ("jmp", n)
elif c == "jmp":
data = copy.deepcopy(old_data)
print("change ", data[index], ("nop", n))
data[index] = ("nop", n)
else:
index += 1
continue
return_value = program_1(data)
if len(return_value) is 1:
print(len(return_value))
return return_value
index += 1
def program_1(data):
index = 0
acc = 0
visited = []
while True:
if index in visited:
return visited
if index < 0 or index >= len(data):
print("Acc found at ", acc)
return [acc]
c, n = data[index]
if c == "nop":
visited.append(index)
index += 1
continue
elif c == "acc":
visited.append(index)
acc += int(n)
index += 1
continue
elif c == "jmp":
visited.append(index)
index += int(n)
continue
index += 1
def main():
data = open_file("input.txt")
data = [((d.split(" ")[0]),(d.split(" ")[1])) for d in data]
print(program_2(data))
if __name__ == '__main__':
main() |
410c98c0e2b60c4f26a95c6c59f2531681c816e4 | porrametict/learningSpace | /PythonWithChulalondkorn/list_demo1.py | 614 | 4.15625 | 4 | # basic operation list
# flower = ["calla","rose","lily"]
# print(flower)
# flower = flower+["for get me not","sunflowe"]
# print(flower)
# del flower[1]
# print(flower)
# flower.remove("calla")
# print(flower)
# sorted_flower = sorted(flower)
# print(flower)
# print(sorted_flower)
# flower.sort()
# print(flower)
# flower.append("carnation")
def demo():
flowers = ['calla', 'lily', 'jasmine', 'forget me not', 'sunflower', 'ivy', 'gypso']
# slice
print(flowers[1:4]) # [inclusive:exclusive]
print(flowers[-1])
print(flowers[-1:-4:-1])
print(flowers[:3])
print(flowers[2:])
demo() |
81900ff25816e47095edbcb59435c1f591800c1b | SophiaPankeyeva/python-laboratory | /laboratory1/task2.py | 905 | 3.921875 | 4 | print("Лабораторна робота №1 завдання2 \nПанкєєва Софія КМ-93 вар.№15")
while True :
print( 'введіть потрібний вам вік age= ')
r = True
while r:
try: age = int(input())
except:
print('введіть, будь ласка, числові значення ')
continue
else: r = False
if ( age>=0 ) and (age<6 ):
print('дошкільник');
elif ( 6<=age) and (age<23) :
print('учень');
elif (23<=age) and (age<60) :
print ('працівник')
elif(age>=60) and (age<=100):
print ('пенсіонер');
elif (age<0) :
print ('ви ще не народились, введіть інше значення');
elif (age >100 ) :
print('думаю, ви вже померли. введіть інше значення ') ; |
060d3c382971bb6ec6cf11af2021ad38af24a99d | FrancyPinedaB77/DJANGOTaller2 | /losdatos.py | 362 | 3.578125 | 4 | #!/usr/bin/env python
import json
print("un texto ")
n=1
p=3
print (n+p)
file = open("C:\\Users\\ASUS\\Desktop\\Downloads\\Taller1BigData-master\\Taller1BigData-master\\static\\js\\salida.txt","r")
d={}
for line in file:
x = line.split(",")
print(x[0],"nacio",x[2])
# print (x[0],'\n',x[1])
#print ({x[0],x[1]})
#print (x[0],'\t',x[1])
|
d1cc3e5e2f447c5e84c4fca6d67c208456c02db4 | Akazfu/Python-Rewind | /Algorithms and Data Structures/hotpotato.py | 401 | 3.5 | 4 | from datastructures import Queue
def hotpotate(namelist, num):
queue = Queue()
for name in namelist:
queue.enqueue(name)
while queue.size() > 1:
for i in range(num):
queue.enqueue(queue.dequeue())
queue.dequeue()
return queue.dequeue()
if __name__ == "__main__":
namelist = ['a', 'b', 'c', 'd', 'e', 'f']
print(hotpotate(namelist, 7))
|
9ed35b984f819b153be9b34bb5c679bf9c7aa4d5 | Poli96/python | /if13.py | 443 | 4.03125 | 4 | a=int(input("Введите первое число: "))
b=int(input("Введите второе число: "))
c=int(input("Введите третье число: "))
def main(a,b,c):
if a>b and a>c:
if b>c:
print(b)
else:
print(c)
if b>a and b>c:
if a>c:
print(a)
else:
print(c)
if c>a and c>b:
if a>b:
print(a)
else:
print(b)
main(a,b,c)
|
6ab28d84c9a13e34c8956e31d9dc93b8afeff6be | john2796/Python-Algos | /Data-Structure/Queue.py | 442 | 3.671875 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Queue:
def __init__(self):
self.size = 0
self.head = None
self.tail = None
def enqueue(self):
self
def dequeue(self):
self
def len(self):
self
def display(self, item):
elem = []
print(elem)
self
test = Queue()
print(test.display)
|
01fb9b351bf522811f96ed7906c52c32da5966f8 | ningmengpian/algorithm | /valid_bracket_pair.py | 1,534 | 4.28125 | 4 | """
判断有效括号对
question:
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
example:
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
"""
class Solution:
def is_valid(self, s: str) -> bool:
bracket_pair = {')': '(', '}': '{', ']': '['}
left_bracket = ['(', '{', '[']
right_bracket = [')', '}', ']']
bracket_queue = []
subscript = 0
for character in s:
if character in left_bracket:
bracket_queue.append(character)
subscript = subscript + 1
elif character in right_bracket:
if (subscript > 0) and (bracket_pair[character] ==
bracket_queue[subscript - 1]):
bracket_queue.pop()
subscript = subscript - 1
else:
return False
else:
return False
if subscript != 0:
return False
return True
if __name__ == '__main__':
s = '([)]'
s_2 = '()[]{}'
s_3 = ']'
bracket_pair = Solution()
result = bracket_pair.is_valid('')
print(result)
|
24b4bd3a596f9d529cb529b1ad4d903535ce994b | aki202/nlp100 | /chapter1/009.py | 427 | 3.546875 | 4 | import random
#string = 'The best way to predict the future is to invent it .'
string = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
words = string.split(' ')
for index, word in enumerate(words):
if len(word) <= 4: continue
chars = list(word[1:-1])
random.shuffle(chars)
words[index] = word[0] + ''.join(chars) + word[-1]
print(' '.join(words))
|
4e6ca67225bbabd629abef44cf44c966c34a852c | mirabl/j | /meilleurdev/2017-session2/roller/roller.py | 815 | 3.625 | 4 | #!/usr/local/bin/python3
#
# #*******
#* Read input from STDIN
#* Use echo or print to output your result, use the /n constant at the end of each result line.
#* Use:
#* local_print (variable );
#* to display simple variables in a dedicated area.
#* ***/
import sys
from collections import *
import heapq
import itertools
import copy
sys.setrecursionlimit(15000)
debug = True
def dprint(*args):
if debug:
print(args)
lines = []
for line in sys.stdin:
lines.append(line.rstrip('\n'))
heights = [int(x) for x in lines[1:]]
heights.sort()
n = len(heights)
small = heights[:n//2]
big = heights[n//2:]
i = 0
j = 0
r = []
while i < len(small) or j < len(big):
if i < len(small):
r.append(small[i])
i += 1
if j < len(big):
r.append(big[j])
j += 1
print(' '.join([str(x) for x in r]))
|
96fc57c7a7b78b13b0fe248a5905c448e5d057b8 | Aasthaengg/IBMdataset | /Python_codes/p03779/s325073396.py | 177 | 3.625 | 4 | import math
X = int(input())
x = max(0, int(math.sqrt(X)) - 10)
while True:
xx = x * (x + 1) // 2
if X <= xx:
print(x)
exit()
else:
x += 1 |
b4cacd659dd0301214ab1999c8478a1c775021b2 | nianien/algorithm | /src/main/python/leetcode/editor/cn/SwappingNodesInALinkedList.py | 1,611 | 3.9375 | 4 | # 1721.swapping-nodes-in-a-linked-list
# 给你链表的头节点 head 和一个整数 k 。
#
# 交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
#
#
#
# 示例 1:
#
#
# 输入:head = [1,2,3,4,5], k = 2
# 输出:[1,4,3,2,5]
#
#
# 示例 2:
#
#
# 输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5
# 输出:[7,9,6,6,8,7,3,0,9,5]
#
#
# 示例 3:
#
#
# 输入:head = [1], k = 1
# 输出:[1]
#
#
# 示例 4:
#
#
# 输入:head = [1,2], k = 1
# 输出:[2,1]
#
#
# 示例 5:
#
#
# 输入:head = [1,2,3], k = 2
# 输出:[1,2,3]
#
#
#
#
# 提示:
#
#
# 链表中节点的数目是 n
# 1 <= k <= n <= 105
# 0 <= Node.val <= 100
#
# Related Topics 链表
# 👍 20 👎 0
from leetcode.editor.cn.defined import *
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
p1 = head
p2 = head
for _ in range(k-1):
p2 = p2.next
k = p2
while p2.next:
p2 = p2.next
p1 = p1.next
val = k.val
k.val = p1.val
p1.val = val
return head
# leetcode submit region end(Prohibit modification and deletion)
# test from here
if __name__ == '__main__':
print(Solution().swapNodes(ListNode.build(1, 2, 3, 4, 5), 2))
|
266866adc1292b06a61277f31b2525c58c50e98a | gmidha/python-examples | /string_templates.py | 683 | 4.78125 | 5 | #!/usr/bin/env python3
# This program demonstrates the usage of template with strings.
from string import Template
def main():
str = "I am a {0}, I love coding {1}".format("coder", "python")
print(str)
print("--------------------------------")
temp = Template("I am a ${x}, I love coding ${y}")
str2=temp.substitute(x="coder", y="python")
print(str2)
print("--------------------------------")
#substituting template with values from dictionaries
data = { "x": "coder",
"y": "python"
}
str3=temp.substitute(data)
print(str3)
print("--------------------------------")
if __name__ == "__main__":
main()
|
9808a485e61be9c883ade8741787d66f601acb3b | spiritdan/pypypy_v2 | /lesson19/01.py | 1,080 | 3.921875 | 4 | start_floor = input('请输入起始楼层:')
end_floor = input('请输入终止楼层:')
input('接下来请依次输入起始层每个房间的户室尾号、南北朝向及面积,按任意键继续')
start_floor_rooms = {}
floor_last_number = []
for i in range(int(start_floor),int(end_floor)+1):
for i in range(3):
last_number = input('请输入起始楼层户室的尾号:(如01,02)')
floor_last_number.append(last_number)
#将尾号添加列表里,如floor_last_number = ['01','02']
room_number = int(start_floor + last_number)
#户室号为room_number,由楼层start_floor和尾号last_number组成,如301
direction = int(input('请输入 %d 的朝向(南北朝向输入1,东西朝向输入2):' % room_number ))
area = int(input('请输入 %d 的面积,单位 ㎡ :' % room_number))
start_floor_rooms[room_number] = [direction,area]
# 户室号为键,朝向和面积组成的列表为值,添加到字典里,如start_floor_rooms = {301:[1,70]}
print(start_floor_rooms) |
861e8cb6a125eab05ac4d6a66bbb5880a19aa70c | hussein343455/Code-wars | /kyu 7/Mumbling.py | 436 | 3.890625 | 4 | # This time no story, no theory. The examples below show you how to write function accum:
# Examples:
# accum("abcd") -> "A-Bb-Ccc-Dddd"
# accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
# accum("cwAt") -> "C-Ww-Aaa-Tttt"
# The parameter of accum is a string which includes only letters from a..z and A..Z.
def accum(s):
re=''.join([i.upper()+(i.lower()*ind)+'-' for ind,i in enumerate(s)])
return re[:-1] |
0847c2a167efc8e322d1fbe9c6ba9c596b00c594 | MarvelICY/LeetCode | /Solutions/scramble_string.py | 1,315 | 3.765625 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction:
Solution of [Scramble String] in LeetCode.
Created on: Nov 24, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# @return a boolean
# @ICY: dfs recurse
def isScramble(self, s1, s2):
#compare
if len(s1) != len(s2):
return False
if s1 == s2:
return True
# pruning
l1=list(s1)
l2=list(s2)
l1.sort()
l2.sort()
if l1!=l2:
return False
#check every division position and recurse
length = len(s1)
for index in range(1,length):
if self. isScramble(s1[:index], s2[:index]) and \
self.isScramble(s1[index:], s2[index:]):
return True
if self. isScramble(s1[:index], s2[length-index:]) and \
self.isScramble(s1[index:], s2[:length-index]):
return True
return False
#----------------------------SELF TEST----------------------------#
def main():
str1 = 'rgtae'
str2 = 'great'
str1 = 'abcdefghijklmn'
str2 = 'efghijklmncadb'
solution = Solution()
print solution.isScramble(str1, str2)
pass
if __name__ == '__main__':
main() |
1b70a6ad2c0d0aa95cd89b6f1f139db0b50e5889 | MariaBet/EstudosPython | /aulas/rato.py | 417 | 3.890625 | 4 | """
Exemplo de classe e objeto.
Criado para rapidinha #7: https://youtu.be/SQXmC6PbZWk
"""
"Molde para o rato."
class Personagem:
def __init__(self, nome, cor):
self.nome = nome
self.cor = cor
def __repr__(self):
return f'Personagem("{self.nome}", "{self.cor}")'
mickey = Personagem('Mickey', 'Preto')
pluto = Personagem('Pluto', 'Laranja')
pateta = Personagem('Pateta', 'Preto')
|
6585f53e2ff04bc7ecd99b83d9bbab69f67d379b | Conquerk/test | /python/day02/day02zuoye/zuoye3.py | 132 | 3.59375 | 4 | x=int(input("请输入一个年份:"))
if (x%4==0)and(x%100!=0)or(x%400==0):
print("润年")
else:
print("不是润年")
|
adee40607f6e65789891bece2cbaa32519ff0ca7 | ashish3x3/competitive-programming-python | /Hackerrank/Maths/Infimium Contest/pythagorean_triplets.py | 1,365 | 3.578125 | 4 | # https://www.hackerrank.com/contests/infinitum18/challenges/pythagorean-triple
#!/bin/python
# http://www.friesian.com/pythag.htm
#from __future__ import division
#import sys, math
def solveTriplets(a):
if a % 2 == 0:
print a**2/4 - 1, a, a**2/4 + 1
else:
print a, (a**2 - 1)/2, (a**2 + 1)/2
def factors(n):
results = set()
for i in xrange(1, int(math.sqrt(n)) + 1):
if n % i == 0:
results.add(i)
results.add(int(n/i))
return results
def getTriplet(a):
res = factors(int(a))
#print 'res ',res
if len(res) == 2:
m,n = max(list(res)[0],list(res)[1]), min(list(res)[0],list(res)[1])
else:
m,n = max(list(res)[0],list(res)[1]), min(list(res)[0],list(res)[1])
return [a, int(abs(m**2 - n**2)/2),int(abs(m**2 + n**2)/2)]
def pythagoreanTriple(n):
if n%2 ==0:
a = n
b = (long(((n/2)**2)-1)) # (a/2)2 - 1
c = b+2
return [a,b,c]
#return [n, (long(n**2/4)-1), (long(n**2/4)+1)]
else:
a = n
b = (long((n**2-1)/2)) #(a2 - 1) / 2
c = b+1
return [a,b,c]
#return [n, long(math.floor(n**2/2)), long(n**2/2)+1]
a = int(raw_input().strip())
solveTriplets(a)
#triple = pythagoreanTriple(a)
#triple = getTriplet(a)
#sorted(triple)
#print " ".join(map(str, triple))
|
bdcc895fbc7657fb18f62ead89b009b61b3d2541 | Matt-Robinson-byte/DigitalCrafts-classes | /python-algorithms-challenge/seven-counter.py | 77 | 3.859375 | 4 | number = int(input("Enter number with sevens to count: "))
print(len(number)) |
d498315385d8fc5f422223714a741bef7ece7310 | willzh0u/Python | /ex29.py | 1,822 | 4.125 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
# with dogs incremented by 5, people = dogs
if people >= dogs:
print "People are greater than or equal to dogs."
# with dogs incremented by 5, people = dogs
if people <= dogs:
print "People are less than or equal to dogs."
# with dogs incremented by 5, people = dogs
if people == dogs:
print "People are dogs."
# lines 29-32 added for Study Drill #4.
if people < cats:
print "Not so cool."
else:
print "Actually that's fine."
#1. if is conditional that can provide 1 of 2 (possibly more) answers. If this do that, if not, do this instead.
#1. - from ex30 - The if statement tells your script, "If this boolean expression is True, then run the code under it, otherwise skip it."
#2. You need to indent code, because it's a code block. This means that whitespace is significant, and must be consistent. If statements are a type of code block.
#2. - from ex 30 - A colon ":" at the end of a line is how you tell Python you are going to create a new "block" of code, and then indenting 4 spaces tells Python what lines of code are in that block.
#3. The code will return an Indentation Error: expected an indented block.
#3. - from ex 30 - If it isn't indented, you will most likely create a Python error.
#4. Added on lines 29-32
#5. Doesn't matter if you change the variables. Variables can be anything. It only matters if you change the numbers.
# what does += mean? The code x += 1 is the same as doing x = x + 1 but involves less typing.
# You can call this the "increment by" operator. Same goes for -= and many other expressions. |
a63cfa5a79b7ce36efd02dd129d54857b1fdf7b2 | Zheny-mc/Python3_19-ivt-2 | /lb5/main.py | 1,343 | 4.03125 | 4 | def punctuation_mark(ch):
'''Определяет является ли символ знаком препинания'''
if (ch >= '!' and ch <= '/'):
return True
elif (ch >= ':' and ch <= '@'):
return True
elif (ch >= '{' and ch <= '~'):
return True
elif (ch == ' '):
return True
else:
return False
Str = input("Input: ")
words = [] #слова текста
word = "" #слово
n = 1 #кол-во слов у которых первая и последняя буква совпадает
for i in range(0, len(Str)):
if not punctuation_mark(Str[i]):
word += Str[i]
print("find", word)
else:
if len(word) != 0:
print("add", word)
words.append(word)
print("words", words)
word = ""
print()
if len(word) != 0:
print("add", word)
words.append(word)
print("words ", words)
word = ""
print('\n', words)
#поиск слов с одинаковыми первыми и последними символами
i = 0
j = 1
while i < len(words)-1:
len_current = len(words[i]) - 1
len_next = len(words[j]) - 1
if ((words[i][0] == words[j][0]) and
(words[i][len_current] == words[j][len_next])):
n+=1
j+=1
else:
h = 0
|
7972207618450968596e32659261bc9410e62be9 | ProProgrammer/udacity-cs212-coursework | /writing_hand_rank.py | 9,208 | 4 | 4 | # You may assume the following behavior of each function:
#
# straight(ranks): returns True if the hand is a straight.
# flush(hand): returns True if the hand is a flush.
# kind(n, ranks): returns the first rank that the hand has
# exactly n of. For A hand with 4 sevens
# this function would return 7.
# two_pair(ranks): if there is a two pair, this function
# returns their corresponding ranks as a
# tuple. For example, a hand with 2 twos
# and 2 fours would cause this function
# to return (4, 2).
# card_ranks(hand) returns an ORDERED tuple of the ranks
# in a hand (where the order goes from
# highest to lowest rank).
#
# # # # # Poker Rules # # # # # #
# 0 Nothing - High Card
# 1 Pair
# 2 Two Pair
# 3 Three of a Kind
# 4 Straight
# 5 Flush
# 6 Full House
# 7 Four of a Kind
# 8 Straight Flush
# -------------------------------------------------
# Instructions for CS 212, hw1-2: Jokers Wild
#
# -----------------
# User Instructions
#
# Write a function best_wild_hand(hand) that takes as
# input a 7-card hand and returns the best 5 card hand.
# In this problem, it is possible for a hand to include
# jokers. Jokers will be treated as 'wild cards' which
# can take any rank or suit of the same color. The
# black joker, '?B', can be used as any spade or club
# and the red joker, '?R', can be used as any heart
# or diamond.
#
# The itertools library may be helpful. Feel free to
# define multiple functions if it helps you solve the
# problem.
#
# -----------------
# Grading Notes
#
# Multiple correct answers will be accepted in cases
# where the best hand is ambiguous (for example, if
# you have 4 kings and 3 queens, there are three best
# hands: 4 kings along with any of the three queens).
# -------------------------------------------------
import itertools
def _replace_wild_card(input_hand_str, wildcard, replacement_card):
"""
Args:
input_hand_str: input hand in string format
wildcard: Wildcard to replace
replacement_card: Card to replace wildcard with
Returns: hand in string format with that particular wild card replaced with the particular replacement_card
"""
if replacement_card not in input_hand_str:
return input_hand_str.replace(wildcard, replacement_card)
return None
def hands_without_joker(hand):
"""
Args:
hand: a list of cards such as ['6C', '7C', '8C', '9C', 'TC', '?R', '?B']
Returns: This function takes in a hand and if the hand has a wild card in the format ?B or ?R, it replaces the
wild cards with all possible values (Any S or C for ?B and any H or D for ?R) and returns the list of
hands with replaced wild cards
"""
hand_without_wildcard = []
rank = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]
b_wildcard_replacement_suit = ["C", "S"]
r_wildcard_replacement_suit = ["D", "H"]
replacement_cards_for_b_wildcard = ["".join(item) for item in itertools.product(rank, b_wildcard_replacement_suit)]
replacement_cards_for_r_wildcard = ["".join(item) for item in itertools.product(rank, r_wildcard_replacement_suit)]
black_wildcard = "?B"
red_wildcard = "?R"
hand_as_str = " ".join(hand)
if black_wildcard in hand_as_str and red_wildcard in hand_as_str:
for replacement_black_card in replacement_cards_for_b_wildcard:
hand_without_black_wildcard = _replace_wild_card(hand_as_str, black_wildcard, replacement_black_card)
if hand_without_black_wildcard:
for replacement_red_card in replacement_cards_for_r_wildcard:
interim_hand_without_wildcard = _replace_wild_card(hand_without_black_wildcard, red_wildcard,
replacement_red_card)
if interim_hand_without_wildcard:
hand_without_wildcard.append(interim_hand_without_wildcard)
elif black_wildcard in hand_as_str:
for replacement_black_card in replacement_cards_for_b_wildcard:
interim_hand_without_wildcard = _replace_wild_card(hand_as_str, black_wildcard, replacement_black_card)
if interim_hand_without_wildcard:
hand_without_wildcard.append(interim_hand_without_wildcard)
elif red_wildcard in hand_as_str:
for replacement_red_card in replacement_cards_for_r_wildcard:
interim_hand_without_wildcard = _replace_wild_card(hand_as_str, red_wildcard, replacement_red_card)
if interim_hand_without_wildcard:
hand_without_wildcard.append(interim_hand_without_wildcard)
else:
hand_without_wildcard.append(hand_as_str)
return hand_without_wildcard
def best_hand_from_list_of_hands(list_of_hands):
"""
Args:
list_of_hands: List of hands, each hand is a string. Eg: "6C 7C 8C 9C TC 5C 7H"
Returns: This function gets the 5 best cards out of list of 5 or more card hands and appends it to an output list
It then returns the max of all the cards from that output list
"""
five_card_best_hands = [max(itertools.combinations(hand.split(), 5), key=hand_rank) for hand in list_of_hands]
return max(five_card_best_hands, key=hand_rank)
def best_wild_hand(hand):
"""
Args:
hand:
Returns:
"""
return best_hand_from_list_of_hands(hands_without_joker(hand))
def test_best_wild_hand():
assert (sorted(best_wild_hand("6C 7C 8C 9C TC 5C ?B".split()))
== ['7C', '8C', '9C', 'JC', 'TC'])
assert (sorted(best_wild_hand("TD TC 5H 5C 7C ?R ?B".split()))
== ['7C', 'TC', 'TD', 'TH', 'TS'])
assert (sorted(best_wild_hand("JD TC TH 7C 7D 7S 7H".split()))
== ['7C', '7D', '7H', '7S', 'JD'])
return 'test_best_wild_hand passes'
def poker(hands):
"""
Args:
hands: List of hands such as "6C 7C 8C 9C TC 5C JS".split()
Returns: The best hand: poker([hand,...]) => hand
"""
return max(hands, key=hand_rank)
def hand_rank(hand):
"""
Args:
hand: Eg: "6C 7C 8C 9C TC 5C JS".split()
Returns: A value indicating the ranking of a hand.
"""
ranks = card_ranks(hand)
if straight(ranks) and flush(hand): # straight flush (8,11) "Jack High, Straight Flush"
return 8, max(ranks)
elif kind(4, ranks): # 4 of a kind (7, 14, 12) "Four aces, Queen Kicker"
return 7, kind(4, ranks), kind(1, ranks)
elif kind(3, ranks) and kind(2, ranks): # full house (6, 8, 13) "Full House, 8s over Kings"
return 6, kind(3, ranks), kind(2, ranks)
elif flush(hand): # flush (5, [10, 8, 7, 5, 3]) "Flush, 10-8"
return 5, ranks
elif straight(ranks): # straight (4, 11) "Straight, Jack high"
return 4, max(ranks)
elif kind(3, ranks): # 3 of a kind (3, 7, [7, 7, 7, 5, 2]) "Three 7s"
return 3, kind(3, ranks), ranks
elif two_pair(ranks): # 2 pair (2, 11, 3, [13, 11, 11, 3, 3]) "2 pairs Jacks and 3s"
return 2, two_pair(ranks), ranks
elif kind(2, ranks): # kind (1, 2, [13, 6, 3, 2, 2]) "Pairs of 2s, Jack high"
return 1, kind(2, ranks), ranks
else: # high card (0,7,5,4,3,2) "Nothing"
return 0, ranks
def test():
"""
Test cases for the functions in poker program
Returns: 'tests pass' if all assertions work, else AssertionError
"""
sf = "6C 7C 8C 9C TC".split() # Straight Flush
fk = "9D 9H 9S 9C 7D".split() # Four of a Kind
fh = "TD TC TH 7C 7D".split() # Full House
assert poker([sf, fk, fh]) == sf
assert poker([fk, fh]) == fk
assert poker([fh, fh]) == fh
assert poker([sf]) == sf
assert poker([sf] + 99 * [fh]) == sf
assert hand_rank(sf) == (8, 10)
assert hand_rank(fk) == (7, 9, 7)
assert hand_rank(fh) == (6, 10, 7)
return 'tests pass'
def card_ranks(hand):
"""
Args:
hand: Eg: "6C 7C 8C 9C TC 5C JS".split()
Returns: A list of the ranks, sorted with higher first.
"""
ranks = ['--23456789TJQKA'.index(r) for r, s in hand]
ranks.sort(reverse=True)
return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks
def flush(hand):
"""
Args:
hand: Eg: "6C 7C 8C 9C TC 5C JS".split()
Returns: True if all the cards have the same suit else False
"""
suits = [s for r, s in hand]
return len(set(suits)) == 1
def straight(ranks):
"""
Args:
ranks:
Returns: True if the ordered ranks form a 5-card straight.
"""
return (max(ranks) - min(ranks) == 4) and len(set(ranks)) == 5
def kind(n, ranks):
"""
Args:
n:
ranks:
Returns: The first rank that this hand has exactly n-of-a-kind of. Return None if there is no n-of-a-kind in the
hand.
"""
for r in ranks:
if ranks.count(r) == n:
return r
return None
def two_pair(ranks):
"""
Args:
ranks:
Returns: If there are two pair here, return the two ranks of the two pairs, else None.
"""
pair = kind(2, ranks)
print test_best_wild_hand()
|
f4a2f64e52ad75d07efd13cd16a9f82b2a39f5db | hassanbazari/python-practice-book | /anandology_chapter_2/2prb34_word.py | 390 | 4.21875 | 4 | # function to split data in a file into words and print in decresing order of occurences
def read_words(filename):
sorted_dict={}
import re
from collections import Counter
import operator
words = re.findall(r'\w+', open(filename, 'r').read().lower()) #list of words without punchuation
dictionary=Counter(words) #take count each word and arrange in descending order
|
6b73414d98b58649972f864e90c6f15fd77c3afe | Frijke1978/LinuxAcademy | /Python 3 Scripting for System Administrators/Adding Error Exit Status.py | 1,298 | 3.9375 | 4 | Adding Error Exit Status to reverse-file
When our reverse-file script receives a file that doesn’t exist, we show an error message, but we don’t set the exit status to 1 to be indicative of an error.
$ reverse-file -l 2 fake.txt
Error: [Errno 2] No such file or directory: 'fake.txt'
~ $ echo $?
0
Let’s use the sys.exit function to accomplish this:
~/bin/reverse-file
#!/usr/bin/env python3.6
import argparse
import sys
parser = argparse.ArgumentParser(description='Read a file in reverse')
parser.add_argument('filename', help='the file to read')
parser.add_argument('--limit', '-l', type=int, help='the number of lines to read')
parser.add_argument('--version', '-v', action='version', version='%(prog)s verison 1.0')
args = parser.parse_args()
try:
f = open(args.filename)
limit = args.limit
except FileNotFoundError as err:
print(f"Error: {err}")
sys.exit(1)
else:
with f:
lines = f.readlines()
lines.reverse()
if limit:
lines = lines[:limit]
for line in lines:
print(line.strip()[::-1])
Now, if we try our script with a missing file, we will exit with the proper code:
$ reverse-file -l 2 fake.txt
Error: [Errno 2] No such file or directory: 'fake.txt'
$ echo $?
1 |
146b63adcd447f0ae515995b031f3543f8e49b10 | shirishdhar/HW10 | /seventeen1.py | 1,115 | 3.921875 | 4 | import sys
def random_generator():
import random
ran=random.randint(1,3)
return ran
def seventeen():
marbles=17
while True:
try:
user_in=int(raw_input('Your turn: How many marbles will you remove (1-3)? '))
if (user_in not in range(1,4)) or (marbles-user_in<0): # 1/0 used to cause an exception if conditions are met.
1/0
except:
print 'Sorry, that is not a valid option. Try again! '
continue
else:
print 'You removed {this} marbles'.format(this=user_in)
marbles-=user_in
if marbles!=0:
print 'Number of marbles left in jar: {that}'.format(that=marbles)
else:
sys.exit('There are no marbles left. User wins')
print "Computer's turn..."
comp_in=random_generator()
print 'Computer removed {them} marbles.'.format(them=comp_in)
marbles-=comp_in
if marbles!=0:
print 'Number of marbles left in jar: {thats}'.format(thats=marbles)
else:
sys.exit('There are no marbles left. Computer wins!')
continue
def main():
print "Let's play the game of seventeen1"
print 'Number of marbles left in jar: 17'
seventeen()
main()
|
8a1285d448cf543a8bffdc9b834a88ed5dc3813d | utgwkk/brainfuck.py | /interpreter.py | 1,399 | 3.515625 | 4 | import sys
import re
def _generate_tree(program, ptr):
tree = []
while ptr < len(program):
if program[ptr] == '[':
leaf, nptr = _generate_tree(program, ptr + 1)
tree.append(leaf + [']'])
ptr = nptr
elif program[ptr] == ']':
return tree, ptr
else:
tree.append(program[ptr])
ptr += 1
return tree, 0
def parse(program):
program = re.sub(r'[^\.,\+\-><\[\]]', '', program)
return _generate_tree(program, 0)[0]
def _run(tree, memory, ptr):
output = ''
for ch in tree:
if isinstance(ch, list):
ptr, a = _run(ch, memory, ptr)
output += a
elif ch == '+':
memory[ptr] += 1
elif ch == '-':
memory[ptr] -= 1
elif ch == '>':
ptr += 1
if ptr >= len(memory):
memory.append(0)
elif ch == '<':
ptr -= 1
elif ch == '.':
output += chr(memory[ptr])
elif ch == ',':
try:
memory[ptr] = ord(sys.stdin.read(1))
except TypeError:
memory[ptr] = 0
elif ch == ']':
if memory[ptr] != 0:
return _run(tree, memory, ptr)
else:
return ptr, output
return 0, output
def run(tree):
return _run(tree, [0], 0)[1]
|
14d66cc839ac380257fb1f77437a6c502b16d263 | homepeople/PythonLearning | /src/像计算机科学家一样思考Python_Exercise3/Lesson005/Exercise5.5.py | 367 | 3.90625 | 4 | #coding=utf-8
#Exercise5.5
import turtle
Fred=turtle.Turtle()
#draw a branch
def draw(t,length,n):
if n==0:
return
angle=50
t.fd(length*n)
t.lt(angle)
draw(t,length,n-1)
t.rt(2*angle)
draw(t,length,n-1)
t.lt(angle)
t.bk(length*n)
if __name__ == '__main__':
draw(Fred,2,7)
turtle.mainloop()
|
1beb1ebc3addef82905d9fcc28f4ea83685034dc | MdAbuZehadAntu/Django3 | /PythonRefresherOOP/InnerClass.py | 690 | 3.71875 | 4 | class Human:
def __init__(self, name, gender, h_color, h_type):
self.name = name
self.gender = gender
self.hand = self.Hands(h_color, h_type,self)
def show(self):
print(self.name, self.gender)
self.hand.show()
class Hands:
fingers = 5
def __init__(self, color, type,other):
self.color = color
self.type = type
self.parent=other
def show(self):
print(self.parent.name+" : "+self.color, self.type,Human.Hands.fingers)
h1 = Human("Antu", "Male", "dark", "hard")
h2 = Human("Bush", "Female", "fair", "soft")
h1.show()
# h1.hand.show()
h2.show()
# h2.hand.show() |
242ccb6ad583cb09840d75281d4259e4de5db690 | juliamoraiss/python-CursoEmVideo | /Exercícios/ex050.py | 213 | 3.75 | 4 | soma = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {}º número: '.format(c)))
if n % 2 == 0:
cont += 1
soma += n
print('A soma dos {} valores pares é {}'.format(cont, soma))
|
37bbb68759df9d6256786600e7e73e84ac4b5e07 | r25ta/USP_python_1 | /semana4/primalidade.py | 302 | 4.09375 | 4 | def main():
print("Primalidade")
n = int(input("Digite um número inteiro:"))
if((n==2) or (n==3) or (n==5) or (n==7)):
print("primo")
elif((n%2==0) or (n%3==0) or (n%5==0) or (n%7==0)):
print("não primo")
else:
print("primo")
main() |
12971ba6f6a37ed9b6b94d8258366cbb48aada34 | nkchangliu/puzzles | /leetcode/longest_palindrome_subsequence.py | 484 | 3.6875 | 4 | def longest(s):
if len(s) == 0:
return 0
cache = [[1 for i in range(len(s))] for j in range(len(s))]
for i in range(len(s)-1, -1, -1):
for j in range(i+1, len(s)):
if j == i + 1 and s[i] == s[j]:
cache[i][j] = 2
elif s[i] == s[j]:
cache[i][j] = 2 + cache[i+1][j-1]
else:
cache[i][j] = max(cache[i+1][j], cache[i][j-1])
return cache[0][-1]
print(longest("bbbab"))
|
f04514832c2d0039d0a647782c426e73b9dd04ff | shoter/PythonTex-presentation | /python/indentation.py | 130 | 3.6875 | 4 | # And this is a comment.
from random import randint
number = randint(0, 9)
if number < 5:
print("0-4")
else:
print("5-9")
|
f191e8a13c3ba4110f19e30b64654343cea4f061 | vijaykumar7686/python | /vj12.py | 125 | 3.515625 | 4 | #a
n1=int(input())
temp=n1
r=0
while(n1>0):
s=n1%10
r=r*10+s
n1=n1//10
if(temp==r):
print("yes")
else:
print("no")
|
370a32028c8d40c0c42ceb32499d02694ced079b | jevinkeffers/DC-Repos-Week-1 | /KJ_Python_101_lessons/Large/GUESS_A_NUMBER.py | 4,647 | 4.625 | 5 | # # 3. Guess a Number
# # You will implement a guess-the-number game where the player has to try guessing a secret number until they gets it right. For now, you will "hard code" the secret number to 5 (just set it to five like secret_number = 5). You will prompt the player to enter a number again and again, each time comparing their input to the secret number. To to that, you will need to write a while loop. If they guess correctly, you will print "You win!", otherwise, you will prompt for a number again.
# #STEP 1
n = 5
print("I am thinking of a number between 1 and 10.")
i = int(input("What's the number? "))
if i == n:
print("Yes! You win!")
while i != n:
int(input("Nope, try again. "))
print("Yes! You win!")
break
# #SOLVED
#STEP 2: Give High-Low Hint
#Improve your game to provide the player with a high-or-low hint.
n = 5
print("I am thinking of a number between 1 and 10.")
guess = int(input("What's the number? "))
if guess == n:
print("Yes! You win!")
while guess != n:
if guess < n:
print("%d is too low" % guess)
guess = int(input("Guess again? "))
if guess > n:
print("%d is too high" % guess)
guess = int(input("Guess again? "))
if guess == n:
print("Yes! You win!")
break
# #SOLVED
# # Step 3: Randomly Generated Secret Number
# # Instead of hard-coding the secret number to 5 now, you will generate the secret number using a random number generator provided by Python, so that even you, the programmer, cannot know the secret number before hand.
# import random
# my_random_number = random.randint(1, 10)
print("I am thinking of a number between 1 and 10.")
guess = int(input("What's the number? "))
if guess == my_random_number:
print("Yes! You win!")
while guess != my_random_number:
if guess < my_random_number:
print("%d is too low" % guess)
guess = int(input("Guess again? "))
if guess > my_random_number:
print("%d is too high" % guess)
guess = int(input("Guess again? "))
if guess == my_random_number:
print("Yes! You win!")
break
# # #SOLVED
# # Step 4: Limit Number of Guesses
# # Limit the number of guesses the player has to 5. If he cannot guess the number within 5 guesses, he loses. Changing random number range to 1-20.
import random
my_random_number = random.randint(1, 20)
print("I am thinking of a number between 1 and 20.")
print("You have 5 guesses left.")
guess = int(input("What's the number? "))
number_of_guesses = 5
guesses_made = 0
while guess != my_random_number and (number_of_guesses -1) != guesses_made:
if guess < my_random_number:
print("%d is too low" % guess)
guesses_made += 1
guess = int(input("You have %d guesses remaining: Guess again? " % (number_of_guesses - guesses_made)))
elif guess > my_random_number:
print("%d is too high" % guess)
guesses_made += 1
guess = int(input("You have %d guesses remaining: Guess again? " % (number_of_guesses - guesses_made)))
if(number_of_guesses - 1) == guesses_made:
print("Sorry, you ran out of guesses.")
else:
print("Yes! You win!")
# # #SOLVED
# Bonus: Play Again
# At the conclusion of a game, give the player the option of playing again.
import random
def number_game():
my_random_number = random.randint(1, 20)
print("I am thinking of a number between 1 and 20.")
print("You have 5 guesses left.")
guess = int(input("What's the number? "))
number_of_guesses = 5
guesses_made = 0
while guess != my_random_number and (number_of_guesses -1) != guesses_made:
if guess < my_random_number:
print("%d is too low" % guess)
guesses_made += 1
guess = int(input("You have %d guesses remaining: Guess again? " % (number_of_guesses - guesses_made)))
elif guess > my_random_number:
print("%d is too high" % guess)
guesses_made += 1
guess = int(input("You have %d guesses remaining: Guess again? " % (number_of_guesses - guesses_made)))
if(number_of_guesses - 1) == guesses_made:
print("Sorry, you ran out of guesses.")
play_again = input("Would you like to play again? (Y or N) ").upper()
if play_again == 'N':
print("Bye.")
if play_again == 'Y':
number_game(my_random_number)
else:
print("Yes! You win!")
play_again = input("Would you like to play again? (Y or N) ").upper()
if play_again == 'N':
print("Bye.")
if play_again == 'Y':
number_game(my_random_number)
number_game(my_random_number)
|
a48918d6091e6c7ae1aabc36b4573103f367d9b1 | matthewkot/pythonhillel | /lessons/lesson9.2_f.py | 1,277 | 3.6875 | 4 | import random
def create_point(min_limit,max_limit):
point = {"x": random.randint(-10, 10),
"y": random.randint(-10, 10)}
return point
def create_triangle(points_name_str, min_limit, max_limit) :
return {key: create_point(-100,100) for key in points_name_str}
triangle_ABC = create_triangle("ABC", -100,100)
triangle_MNK = create_triangle("MNK", -100,100)
triangle_QWE = create_triangle("QWE",-100,100)
print(triangle_ABC)
print(triangle_MNK)
print(triangle_QWE)
# point_A = create_point()
# point_B = create_point()
# point_C = create_point()
# triangle_ABC = {"A": create_point(),
# "B": create_point(),
# "C": create_point()}
# triangle_ABC = {key: create_point() for key in "ABC"} ### Второй метод
# def create_triangle(): ### Третий (самый короткий) метод
# return {key: create_point() for key in "ABC"}
#
# triangle_ABC = create_triangle()
# def create_triangle(points_name_str):
# return {key: create_point() for key in points_name_str}
# triangle_ABC = create_triangle("ABC")
# triangle_MNK = create_triangle("MNK")
# triangle_QWE = create_triangle("QWE")
#
#
# print(triangle_ABC)
# print(triangle_MNK)
# print(triangle_QWE) |
c03234c4dab7eafcecd38e146d70679c0e8ddb42 | NeonMiami271/Work_JINR | /Python_Linux/Graphics for Selynin/split.py | 117 | 3.65625 | 4 | f = open ('test.txt')
for line in f:
buf = list()
buf = line.split('_')
print(str(buf))
print(str(float(buf[3])))
|
bd9c460388507790367f0ec702710529c1984c0f | y-nagamoto/python_basic | /2-10.dictionary_method.py | 631 | 3.625 | 4 | d = {'x': 10, 'y': 20}
# help(d)
print(d.keys())
print(d.values())
"""
dict_keys(['x', 'y'])
dict_values([10, 20])
"""
d2 = {'x': 1000, 'j': 500}
print(d)
print(d2)
d.update(d2)
print(d)
print(d['x'])
print(d.get('x'))
"""
{'x': 10, 'y': 20}
{'x': 1000, 'j': 500}
{'x': 1000, 'y': 20, 'j': 500}
1000
1000
"""
r = d.get('z')
print(r)
print(type(r))
"""
None
<class 'NoneType'>
"""
print(d)
print(d.pop('x'))
print(d)
"""
{'x': 1000, 'y': 20, 'j': 500}
1000
{'y': 20, 'j': 500}
"""
del d['y']
print(d)
"""
{'j': 500}
"""
d.clear()
print(d)
"""
{}
"""
d = {'a': 100, 'b': 200}
print('a' in d)
print('j' in d)
"""
True
False
""" |
c07a38f6ae1df0f19f03738000e4a8e46db6fd67 | an33shk4tl4/PythonLearn | /iterables.py | 302 | 3.796875 | 4 | # iterating over multiple lists using zip
import pprint as pp
import os
days = ['Monday', 'tuesday', 'wednesday']
fruits = ['banana', 'orange', 'peach']
desserts = zip(days, fruits)
pp.pprint(desserts)
# raw_input('Please hit a key to proceed further')
os.system('pause')
print('End of program')
|
8e27cc0eaee85bb3fc95ce5ad3003bae801c0dcd | Larry-Volz/python-data-structures | /fs_2_valid_parentheses/valid_parentheses.py | 745 | 3.875 | 4 | def valid_parentheses(parens):
"""Are the parentheses validly balanced?
>>> valid_parentheses("()")
True
>>> valid_parentheses("()()")
True
>>> valid_parentheses("(()())")
True
>>> valid_parentheses(")()")
False
>>> valid_parentheses("())")
False
>>> valid_parentheses("((())")
False
>>> valid_parentheses(")()(")
False
"""
if parens.index(")") !=0:
return parens.count("(") == parens.count(")")
return False
# fast fail: ) is first (index = 0)
# or unequal amount
#my solution is more elegant that teachers - she manually
# adds one for ( and subtracts one for ) and checks for = 0 |
c3aff15c94eac814f5784b4d559552aeab374310 | MatejKopcik1/pytonik | /EDU18.py | 151 | 3.921875 | 4 | a = input("a = ")
b = input("b = ")
c = input("c = ")
if a < b < c:
print(a, "<", b, "<", c)
elif a < c < b:
print(a, "<", c, "<", b)
|
17a5dfb5e7894676104942ce5a82d17d9edb564c | C109156214/pythontest | /4.py | 1,033 | 3.84375 | 4 | x=int(input("X軸座標:"))
y=int(input("Y軸座標:"))
a=0
if x == 0 :
if y == 0:
print("該點位於原點")
elif y > 0:
a=y**2
print("該點位於上半平面Y軸上,離原點距離為根號",a)
else:
a=y**2
print("該點位於下半平面Y軸上,離原點距離為根號",a)
elif x > 0:
if y == 0:
a=x**2
print("該點位於右半平面X軸上,離原點距離為根號",a)
elif y > 0:
a=x**2 + y**2
print("該點位於第一象限,離原點距離為根號",a)
else:
a=x**2 + y**2
print("該點位於第四象限,離原點距離為根號",a)
elif x < 0:
if y == 0:
a=x**2
print("該點位於左半平面X軸上,離原點距離為根號",a)
elif y > 0:
a=x**2 + y**2
print("該點位於第二象限,離原點距離為根號",a)
else:
a=x**2 + y**2
print("該點位於第三象限,離原點距離為根號",a) |
7fc3d735a01834f92f70bc3a29df6cb6f0496a30 | berazo29/network-fundamentals-py | /Server.py | 1,811 | 3.890625 | 4 | import argparse
from sys import argv
import socket
parser = argparse.ArgumentParser(description="""This is a very basic server program""")
parser.add_argument('-f', type=str, help='File to read the pairs words', default='Pairs.txt', action='store', dest='in_file')
parser.add_argument('port', type=int, help='This is the server port to listen', action='store')
args = parser.parse_args(argv[1:])
# load the text file as dictionary
index_pairs = {}
with open(args.in_file) as f:
for line in f:
(key, val) = line.strip().split(':')
index_pairs[key] = val
# Create a new socket
try:
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("[S]: Server socket created")
except socket.error as error:
print("Server socket error: {}".format(error))
exit()
server_addr = ('', args.port)
ss.bind(server_addr)
ss.listen(1)
# print server info
host = socket.gethostname()
print("[S]: Server hostname is {}".format(host))
localhost_ip = socket.gethostbyname(host)
print("[S]: Server IP address is {}".format(localhost_ip))
print("[S]: Server port number is {}".format(args.port))
# accept a client
csockid, addr = ss.accept()
print("[S]: Got a connection request from a client at {}".format(addr))
with csockid:
while True:
data = csockid.recv(512)
data = data.decode('utf-8')
try:
if index_pairs[data]:
print('[C]: {}'.format(data))
print('[S]: {}'.format(index_pairs[data]))
csockid.sendall(index_pairs[data].encode('utf-8'))
except:
if not data:
break
answer = 'NOT FOUND'
print('[C]: {}'.format(data))
print('[S]: {}'.format(answer))
csockid.sendall(answer.encode('utf-8'))
ss.close()
exit()
|
49b85b54ee44e259ad3e050e7893c57f01642ffc | denis-nuzhdin/dntest3 | /test/lesson4.1.py | 993 | 4.09375 | 4 | # анограмма, угадывание слов по буквам в перемешку, глава 4
import random
WORDS = ("home",
"python",
"apple",
"google",
"led zeppelin",
"lp")
word = random.choice(WORDS)
correct = word
jumble =""
while word:
position = random.randrange(len(word))
#print("position: ",position)
jumble += word[position]
word = word[:position] + word[(position+1):]
#print("word: ", word)
#print("jumble: ", jumble)
print("anogram",jumble)
guess = input("what? ")
helps = ("hepl1", "help1", "help3")
point = 5
while guess !=correct and guess!="":
#print("again!")
help = input("can i help you? ")
if help == "yes":
print(random.choice(helps))
guess = input("try with help: ")
point=1
elif help =="no":
guess = input("try: ")
point=2
else:
break
if guess==correct:
print("win! and point ",point)
|
95a28f2976beb68d5b66ef73be375b9a044a4007 | sakethraogandra/python1 | /1.py | 140 | 3.71875 | 4 | count=0
s=input("enter a strin :")
for i in s:
if(i =='a'or i =='e' i =='i' or i =='o' or i =='u'):
count=count+1
print(count)
|
aa19ff1b03d1acf71662ec0e3f5262cdea2e77c6 | TheGalacticCouncil/space-bridge | /HwReader/myIP.py | 416 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#https://www.w3resource.com/python-exercises/python-basic-exercise-55.php
import socket
def myIP():
ip = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127.")][:1], [[(s.connect(('1.1.1.1', 53)),
s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
return ip
|
9449f24ef04c98c98ecda49a2fed060c5b84affb | debrouwere/data-analysis-in-python | /utils.py | 1,388 | 3.9375 | 4 | # encoding: utf-8
"""
Utilities for normalizing column names, which is useful
when you're using data from different data sources,
all with their own naming conventions.
"""
import re
import math
import collections
def normalize_name(name, separator='-'):
name = re.sub(r'([a-z])([A-Z])', r'\1-\2', name)
return name \
.replace(' ', separator) \
.replace('_', separator) \
.replace('-', separator) \
.lower()
def normalize_columns(df, separator='-'):
names = [normalize_name(name, separator) for name in df.columns]
df.columns = names
return df
"""
JSON can be arbitrarily nested, but tables and data frames are
two-dimensional: there's columns and rows. This function can
"flatten" a dictionary until it's essentially a table.
"""
def flatten(d, parent_key='', connector='-'):
items = []
for k, v in d.items():
new_key = parent_key + connector + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, connector).items())
else:
items.append((new_key, v))
return dict(items)
"""
Data structures with primary keys are easier for Pandas to work with.
"""
# turn array into a keyed data structure
def index_by(list, index):
hash = {}
for el in list:
name = el[index]
hash[name] = el
return hash |
0dcc9789953e4194c7bc04d28332e3efd2ee61cb | rk012/Python-Algorithms-and-Datastructures | /graphs/dfs.py | 659 | 3.78125 | 4 | from graphs.graph import Graph
def dfs(start, end, adj_list):
visited = [start]
stack = [start]
while len(stack) != 0:
current_node = stack.pop()
for x in adj_list[current_node]:
if x not in visited:
visited.append(x)
stack.append(x)
if end in visited:
return True
return False
if __name__ == "__main__":
g = Graph(True)
for i in range(0, 6):
g.addNode()
g.addEdge(0, 3)
g.addEdge(1, 0)
g.addEdge(1, 2)
g.addEdge(3, 4)
g.addEdge(3, 5)
g.addEdge(4, 0)
g.addEdge(5, 2)
print(dfs(0, 1, g.getAdjacencyList()))
|
3bb60b56e212391bdeec18a4995c10af14c6df6e | codecakes/algorithms | /algorithms/practice/int_sqr_range.py | 2,770 | 4.15625 | 4 | """
Problem Statement
Watson gives two integers (A and B) to Sherlock and asks if he can count the number of square integers between A and B (both inclusive).
Note: A square integer is an integer which is the square of any integer. For example, 1, 4, 9, and 16 are some of the square integers as they are squares of 1, 2, 3, and 4, respectively.
Input Format
The first line contains T, the number of test cases. T test cases follow, each in a new line.
Each test case contains two space-separated integers denoting A and B.
Output Format
For each test case, print the required answer in a new line.
Constraints
1<=T<=100
1<=A<=B<=109
Sample Input
2
3 9
17 24
Sample output
2
0
Explanation
Test Case #00: In range [3,9], 4 and 9 are the two square numbers.
Test Case #01: In range [17,24], there are no square numbers.
"""
from math import floor
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n < x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
def perfect_sqrs_count(a,b):
count = 0
num = 0
if a==b:
num = pow(b,0.5)
a_sqr_root = floor(pow(a,0.5)) if len(str(a)) < 10 else floor(find_invpow(a, 2))
return 1 if a_sqr_root == num else 0
b_sqr_root = floor(pow(b,0.5)) if len(str(b)) < 10 else floor(find_invpow(b, 2))
a_sqr_root = floor(pow(a,0.5)) if len(str(a)) < 10 else floor(find_invpow(a, 2))
diff = b_sqr_root-a_sqr_root
if diff>0:
num = a_sqr_root
while num<=b_sqr_root:
res = num*num
if res == int(res) and a<=res<=b:
count += 1
num += 1
return count
if __name__ == "__main__":
import sys
# t = int(raw_input())
const = 10**9
fname = sys.argv[1]
ans = sys.argv[2]
with open(ans) as fans:
with open(fname) as f:
t = int(f.readline().strip().strip('\n'))
if 1<=t<=100:
for _ in xrange(t):
# a,b = map(int, raw_input().split())
a,b = map(int, f.readline().strip().strip('\n').split())
output = int(fans.readline().strip().strip('\n'))
if 1<=a<=b<=const:
try:
assert perfect_sqrs_count(a,b) == output
except AssertionError as e:
print "Range is %s - %s" %(a,b)
print perfect_sqrs_count(a,b), output |
5e9e79c2f95c707b8d9b83613b914f6d8696ef97 | sasa33k/PSCourse | /_02b_exceptions.py | 4,316 | 4.0625 | 4 | """
raise an exception to interrupt program flow
handle an exception to resume control
unhandled exception will terminate the program
exception objects contain info about the exception event
"""
def convert(s):
try:
x = int(s)
print(x)
except ValueError:
print("Cannot convert (str)")
x = -1
except TypeError:
print("Cannot convert (list)")
x = -1
return x
def convert2(s):
x = -1
try:
x = int(s)
print(x)
except (TypeError, ValueError):
print("Cannot convert") # need "pass" if removed, else have indentation error
return x
"""
Exceptions for programmer errors
IndentationError
SyntaxError
NameError
"""
import sys
def convert3(s):
try:
return int(s)
except (TypeError, ValueError) as e:
print("Conversion error: {}"\
.format(str(e)),
file=sys.stderr)
return -1
# Conversion error: invalid literal for int() with base 10: 'aa'
# -1
def convert3(s):
try:
return int(s)
except (TypeError, ValueError) as e:
print("Conversion error: {}"\
.format(str(e)),
file=sys.stderr)
raise # re-raise the error?
"""
Conversion error: invalid literal for int() with base 10: 'aa'
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 3, in convert3
ValueError: invalid literal for int() with base 10: 'aa'
"""
"""
exception, break the program and will not continue for the next line
ValueError:
1. (wasteful~)
except ZeroDivisionError:
raise ValueError()
2.
if x < 0:
raise ValueError("Cannot compute square root of negative number {}".format(x))
except ValueError as e:
print(e, file=sys.stderr)
"""
"""
Use common or existing exception types when possible
IndexError - integer index is out of range e.g. z[4] but z only hv 2 elements
KeyError - lookup in a mapping fails e.g. code = dict(a=1,b=2) ==> codes['d'] ==> KeyError
ValueError - object is of the right type, but inappropriate value e.g. int("aa")
TypeError ** avoid protecting against type errors --> aginst the grain in Python, limit reuse potential uneccessarily
...
"""
"""
Handling failure
1. Look Before You Leap - LBYL
e.g.
import os
p = '/path/to/file.dat'
if os.path.exists(p): # check only existance.. what if gabbage/directory?, race condition (delete by other process in between exist and process_file)
process_file(p)
else:
print('no such file')
2. *It's Easier to Ask Forgiveness than Permission - EAFP ** Exceptions handling
e.g.
import os
p = '/path/to/file.dat'
try
process_file(p)
except OSError as e:
print('Could not process file because()'\
.format(str(e)))
"""
"""
#clean up
import os
def make_at(path, dir_name):
original_path = os.getcwd()
os.chdir(path)
os.mkdir(dir_name) # if this fails, next line won't happen
os.chdir(original_path)
VS
import os
def make_at(path, dir_name):
original_path = os.getcwd()
try:
os.chdir(path)
os.mkdir(dir_name)
except OSError as e:
print(e, file=sys.stderr)
raise
finally:
os.chdir(original_path) # do this even above fails
"""
"""
Platform specific code
Windows
- try: import msvcrt
- msvcrt.getch() #wait for a keypress and return a single character string
OSX or Linux
- sys, tty, termios
"""
"""keypress - A module for detecting a single keypress."""
try:
import msvcrt
def getkey():
"""Wait for a keypress and return a single character string."""
return msvcrt.getch()
except ImportError: # because not windows
import sys
import tty
import termios
def getkey():
"""Wait for a keypress and return a single character string."""
fd = sys.stdin.fileno()
original_attributes = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)
return ch
# If either of the Unix-specific tty or termios are not found,
# we allow the ImportError to propagate from here
|
d144f1959b9187a07e8df36047b1cd1323686a86 | wellqin/USTC | /leetcode/editor/cn/[537]复数乘法.py | 945 | 3.53125 | 4 | # 给定两个表示复数的字符串。
#
# 返回表示它们乘积的字符串。注意,根据定义 i2 = -1 。
#
# 示例 1:
#
#
# 输入: "1+1i", "1+1i"
# 输出: "0+2i"
# 解释: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要将它转换为 0+2i 的形式。
#
#
# 示例 2:
#
#
# 输入: "1+-1i", "1+-1i"
# 输出: "0+-2i"
# 解释: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要将它转换为 0+-2i 的形式。
#
#
# 注意:
#
#
# 输入字符串不包含额外的空格。
# 输入字符串将以 a+bi 的形式给出,其中整数 a 和 b 的范围均在 [-100, 100] 之间。输出也应当符合这种形式。
#
# Related Topics 数学 字符串
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def complexNumberMultiply(self, a: str, b: str) -> str:
pass
# leetcode submit region end(Prohibit modification and deletion)
|
1095a84e5299bb1b4e951ea0a08590371c6ce426 | bi-nary-coder/CBSE-Class-11-Programs | /Ch 1- Data Handling/#5 Check if year is leap year.py | 355 | 4.4375 | 4 | #Question - Write a program to take year as input an check if it is a leap year or not.
# Solution=
year=int(input("Enter the year"))
if year%4 == 0:
if year%100==0:
if year%400==0:
print(f"{year} is leap year")
else:
print(f"{year} is not leap year")
else:
print(f"{year} is leap year")
else:
print (f"{year} is not a leap year")
|
814dfc1dbbedde2bd5d13df32e79b4b5c6a3bbd6 | Ebenezer-Rahul/ELO_RANKING_FOR-IPL-for-fun | /main.py | 3,848 | 3.8125 | 4 |
k = 40
baseRank = 100.0
import csv
class Team(object):
def __init__(self,name,rank):
#assert (type(name) == str and type(rank) == float)
self.name = name
self.rank = rank
def __str__(self):
return self.name
def __lt__(self,other):
return self.rank < other.rank
def getRank(self):
return self.rank
def getName(self):
return self.name
def setRank(self, new_rank):
self.rank = new_rank
def calcExpectation(teamA,teamB):
'''
Using Elo Rating System for calculation expectation values
inupts : teamA, teamB are of Team Class
output is a expectation of weather A wins over B
'''
#assert type(teamA) == Team and type(teamB) == Team
rankA = teamA.getRank()
rankB = teamB.getRank()
expectationA = 1/(1+10**((rankB-rankA)/400))
return expectationA
def updateRanks(result, teamA, teamB):
'''
The inputs : results is float
teamA and teamB are Team objects
expected format for results is
1 if A wins over B
0 if B wins over A
0.5 if the match is a draw
'''
#assert type(result) == float and type(teamA) == Team and type(teamB) == Team
oldRankA = teamA.getRank()
oldRankB = teamB.getRank()
expected = calcExpectation(teamA,teamB)
global k
new_rankA = oldRankA + k*(result-expected)
new_rankB = oldRankB + k*(result+expected-1)
teamA.setRank(new_rankA)
teamB.setRank(new_rankB)
return None
class Match(object):
def __init__(self, teamA, teamB,draw= False):
'''
The class assumes the teamA won or drawn over Team B
'''
# assert type(teamA)== Team and type(teamB) == Team and type(draw) == bool
self.teamA = teamA
self.teamB = teamB
self.draw = draw
def __str__(self):
if self.draw:
return f"Match between"
else :
return f"Match between {self.teamA} and {self.teamB}\n{self.teamA} won the game"
def getWinner(self):
if self.draw:
return None
else:
return self.teamA
def getResult(self):
if self.draw:
return 0.5
else :
return 1
def getTeams(self):
return (self.teamA,self.teamB)
rows = []
with open("./matches.csv",'r') as f:
csvreader = csv.reader(f)
header = next(csvreader)
for row in csvreader:
rows.append(row)
#print(header)
#print(rows)
teamsLookup = {}
allTeams = ['Sunrisers Hyderabad', 'Mumbai Indians', 'Gujarat Lions', 'Rising Pune Supergiant', 'Royal Challengers Bangalore', 'Kolkata Knight Riders', 'Delhi Daredevils', 'Kings XI Punjab', 'Chennai Super Kings', 'Rajasthan Royals', 'Deccan Chargers', 'Kochi Tuskers Kerala', 'Pune Warriors', 'Rising Pune Supergiants']
for team in allTeams:
teamsLookup[team] = Team(team,baseRank)
print(len(rows))
matches = []
for row in rows:
winner = row[10]
if winner != "":
if winner != row[4]:
loser = row[5]
else :
loser = row[4]
matches.append(Match(teamsLookup[winner],teamsLookup[loser]))
else :
matches.append(Match(teamsLookup[row[4]],teamsLookup[row[5]],draw=True))
from prettytable import PrettyTable
def Main():
print(f"No of Matches : {len(matches)}")
for match in matches:
teamA,teamB = match.getTeams()
updateRanks(match.getResult(),teamA,teamB)
teams = []
for team in teamsLookup.keys():
teams.append(teamsLookup[team])
teams.sort(reverse=True)
myTable = PrettyTable(['RANK','TEAM','RATEING'])
i = 0
for team in teams:
i+=1
myTable.add_row([i,team.name,"{:.2f}".format(team.rank)])
print(myTable)
Main() |
c4f4d8c4d432caff83d7a4394b56d3c83165105f | Dew2118/blackjack2 | /src/deck.py | 743 | 3.75 | 4 | from src.card import Card
import random
from src.custom_exception import DeckError
class Deck:
def __init__(self) -> None:
value = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
suit = ['S','H','D','C']
self.cards = [Card(v,s) for v in value for s in suit]
self.drawn = []
def deal(self, game):
"""return a Card. Raise Deckerror if there is no card left."""
if len(self.cards) - 1 < 0:
raise DeckError('Run out of deck, consider starting a new game')
result = self.cards.pop(0)
self.drawn.append(result)
return result
def shuffle(self):
"""Shuffle deck in place"""
random.shuffle(self.cards) |
bcec1ce34949131d16946eb1d1761f2271dd782d | r-arun/cse523 | /waiter/opt_sol.py | 15,111 | 3.625 | 4 | import sys
import itertools
import random
from copy import copy
GMIN = 2**32
GMAX = -GMIN
def generate_test(num):
arr = []
while len(arr) < num:
inp = random.random()
e = random.randint(0,10)
if(e > 5):
inp = inp * -1
arr.append(inp)
return arr
def median(points):
#Points is sorted
"""Given a sorted list of points, finds the median.
If length of the list is
even,
returns a pair of two middle elements.(middle -1 , middle +1)
odd, return a pair (middle,middle)"""
n = len(points)
p1 = n/2
if(n%2 == 0):
p2 = p1 -1
else:
p2 = p1
return points[p2],points[p1]
def perform_test(points):
"""Given a set of points, generates all permutations and places the points
according to the permutation and calculates the values of cg"""
#run tests on the permutation of points and print the result out
assert(len(points))
print points, sum(points)*1.0/len(points)
perm = itertools.permutations(points)
for arr in perm:
print arr,stat(arr,1)
def stat2(perm, detailed = 0):
"""Find the range and total movement of cg, placing two points simulataneoulsy at a time"""
i = 0
tot = 0
cnt = 0
cmin, cmax = GMIN, GMAX
old_cg = 0.0
movement = 0.0
while i < len(perm):
cnt += 1
tot += perm[i]
i += 1
if(i < len(perm)):
cnt += 1
tot += perm[i]
i += 1
cg = tot/ (cnt*1.0)
if(cmin > cg): cmin = cg
if(cmax < cg): cmax = cg
if(cnt > 2): movement += (abs (cg - old_cg))
old_cg = cg
if(detailed):
return (cmax, cmin, abs(cmax-cmin), movement)
return (abs(cmax-cmin),movement)
def stat(perm,detailed = 0):
"""Given a permutation, find the range and total movement of cg"""
cmin, cmax = GMIN, GMAX
movement = 0.0
total = 0.0
old_cg = 0.0
for ind in xrange(len(perm)):
total = total + perm[ind]
cg = total/(ind+1)
if(cmin > cg): cmin = cg
if(cmax < cg): cmax = cg
if(ind > 0):
#first cg does not imply movement
movement += abs(cg - old_cg)
old_cg = cg
if(detailed):
return (cmax, cmin, abs(cmax-cmin), movement)
return (abs(cmax-cmin),movement)
def average(i,j):
return (i+j)*1.0 /2.0
def getBalancingPair(points, cn , tot_p, cnt, delta = -1):
assert(len(points))
if(len(points) == 1):
return (points[0],)
min_pair = None
#ci = (tot_p + min_pair[0] + min_pair[1])*1.0/ (cnt+2.0)
min_cdiff = GMIN
if(delta >= 0):
for i_ind in xrange(len(points)):
for j_ind in xrange(len(points)):
if(i_ind == j_ind): continue
i = points[i_ind]
j = points[j_ind]
if(abs(i - j) > delta): continue
ci = (tot_p + i + j)*1.0/(cnt+2.0)
cdiff = abs(cn - ci)
if(min_cdiff > cdiff):
min_cdiff = cdiff
min_pair = (i,j)
if(min_pair):
return min_pair
for i_ind in xrange(len(points)):
for j_ind in xrange(len(points)):
if(i_ind == j_ind): continue
i = points[i_ind]
j = points[j_ind]
ci = (tot_p + i + j)*1.0/(cnt+2.0)
cdiff = abs(cn - ci)
if(min_cdiff > cdiff):
min_cdiff = cdiff
min_pair = (i,j)
return min_pair
def getClosestPair(points, cg):
"""From the given set of points, pick 2 points such that
new c_i is closest to cn"""
assert(len(points))
if(len(points) == 1):
return (points[0],)
min_pair = (points[0], points[1])
sel_average = average(points[0] , points[1])
min_diff = abs(sel_average - cg)
for i_ind in xrange(len(points)):
for j_ind in xrange(len(points)):
if(i_ind == j_ind): continue
i = points[i_ind]
j = points[j_ind]
cur_diff = abs(average(i, j) - cg)
if(min_diff > cur_diff):
min_pair = (i,j)
min_diff = cur_diff
return min_pair
def heuristic4(point, delta):
points = copy(point)
assert(len(points))
points.sort()
perm = []
cn = sum(points) * 1.0 / (len(points) * 1.0)
tot = 0
cnt = 0
while(len(points) > 0):
ret = getBalancingPair(points, cn, tot, cnt, delta)
if(len(ret) == 2):
perm.append(ret[0])
perm.append(ret[1])
tot += (ret[0] + ret[1])
cnt += 2
points.remove(ret[0])
points.remove(ret[1])
else:
perm.append(ret[0])
tot += (ret[0]) #unnecessary
cnt += 1
points.remove(ret[0])
return perm
def heuristic3(point):
"""Pick two points such that ci remains closest to cn.
"""
points = copy(point)
assert(len(points))
stat(points)
points.sort()
perm = []
cn = sum(points) * 1.0 / (len(points) * 1.0)
tot = 0
cnt = 0
while(len(points) > 0):
ret = getBalancingPair(points, cn, tot, cnt)
if(len(ret) == 2):
perm.append(ret[0])
perm.append(ret[1])
tot += (ret[0] + ret[1])
cnt += 2
points.remove(ret[0])
points.remove(ret[1])
else:
perm.append(ret[0])
tot += (ret[0]) #unnecessary
cnt += 1
points.remove(ret[0])
return perm
def heuristic2(point):
"""Select two points such that their average is closest to cn
This may be different from heuristic1 where ci always moves
closer to cn. Here the average is closest to cn but ci may not
move closer to cn. If there is only one point left, it is put in
place."""
points = copy(point)
assert(len(points))
stat(points)
points.sort()
perm = []
cn = sum(points)*1.0/(len(points)*1.0)
while(len(points) > 0):
ret = getClosestPair(points, cn)
if(len(ret) == 2):
perm.append(ret[0])
perm.append(ret[1])
points.remove(ret[0])
points.remove(ret[1])
else:
perm.append(ret[0])
points.remove(ret[0])
return perm
def heuristic6(point):
"""Select two points such that the new ci is closest to ci-1
This aims to greedily limit the distance ci moves apart from ci-1."""
points = copy(point)
assert(len(points))
stat(points)
points.sort()
perm = []
cprev = sum(points)*1.0/(len(points)*1.0)
while(len(points) > 0):
ret = getBalancingPair(points, cprev, sum(perm), len(perm))
if(len(ret) == 2):
perm.append(ret[0])
perm.append(ret[1])
points.remove(ret[0])
points.remove(ret[1])
else:
perm.append(ret[0])
points.remove(ret[0])
cprev = sum(perm)/len(perm)
return perm
def heuristic0(points, delta = -1):
"""Place the next point such that the new ci remains close to ci+1. A positive delta first forces the search within the (-delta, delta) interval"""
points = copy(points)
assert(len(points))
cn = sum(points)*1.0/len(points)
prev_ci = cn
#print "CN",cn
total = 0.0
count = 0
perm = []
while(len(points) > 0):
count += 1
best_ci = GMIN
best_ci_pos = -1
if(delta >= 0):
for i in xrange(len(points)):
pi = points[i]
if(not (cn - delta < pi < cn + delta)):
continue
ci = (total + pi) / count
if(abs(best_ci - prev_ci) > abs(ci -prev_ci)):
best_ci = ci
best_ci_pos = i
if(best_ci_pos < 0):
for i in xrange(len(points)):
pi = points[i]
ci = (total + pi) / count
if(abs(best_ci - prev_ci) > abs(ci -prev_ci)):
best_ci = ci
best_ci_pos = i
assert(best_ci_pos >= 0)
prev_ci = best_ci
perm.append(points[best_ci_pos])
total += points[best_ci_pos]
#print total
#print total/count
del points[best_ci_pos]
return perm
def heuristic1(points):
"""Place the next point such that the new ci remains close to cn"""
points = copy(points)
assert(len(points))
cn = sum(points)*1.0/len(points)
#print "CN",cn
total = 0.0
count = 0
perm = []
while(len(points) > 0):
count += 1
best_ci = (total + points[0]) / count
best_ci_pos = 0
for i in xrange(len(points)):
pi = points[i]
ci = (total + pi)/count
if(abs(best_ci - cn) > abs(ci -cn)):
best_ci = ci
best_ci_pos = i
perm.append(points[best_ci_pos])
total += points[best_ci_pos]
#print total
#print total/count
del points[best_ci_pos]
return perm
#garr = []
def find_opt(points, option = 0):
"""Returns all optimal permutations
option - 0 is to minimize the range
1 is to minimize the total sum- that is movement of cg"""
#heuristic 1 - minimize the range
#aim to test if median is part of all opt solutions
global perm_arr
opt_result = []
perm = itertools.permutations(points)
#an iterator of all permutations
best_range = GMIN
min_movement = GMIN
for arr in perm:
#garr.append(list(arr))
current_range, movement = stat(arr)
if(option == 0):
if(current_range < best_range):
best_range = current_range
opt_result = [arr]
elif(current_range == best_range):
opt_result.append(arr)
elif(option == 1):
if(movement < min_movement):
opt_result = [arr]
min_movement = movement
elif(min_movement == movement):
opt_result.append(arr)
#perm_arr = garr
return opt_result
def find_opt2(points, option = 0):
"""Returns all optimal permutations
option - 0 is to minimize the range
1 is to minimize the total sum- that is movement of cg"""
#heuristic 1 - minimize the range
#aim to test if median is part of all opt solutions
#global perm_arr
opt_result = []
perm = itertools.permutations(points)
#an iterator of all permutations
best_range = GMIN
min_movement = GMIN
for arr in perm:
#garr.append(list(arr))
current_range, movement = stat2(arr)
if(option == 0):
if(current_range < best_range):
best_range = current_range
opt_result = [arr]
elif(current_range == best_range):
opt_result.append(arr)
elif(option == 1):
if(movement < min_movement):
opt_result = [arr]
min_movement = movement
elif(min_movement == movement):
opt_result.append(arr)
#perm_arr = garr
return opt_result
if(__name__=='__main__'):
cnt = 0
perm_arr = []
val = int(sys.argv[1])
num_cases = int(sys.argv[2])
fd0 = open("result/result0.txt",'wb')
fd1 = open("result/result1.txt",'wb')
fd2 = open("result/result2.txt",'wb')
fd3 = open("result/result3.txt",'wb')
if(val < 4):
fd0.write("Ratio of Ranges of Center of mass\n")
fd0.write("H0, H1, H2, H3, H4, H5, H6\n")
if(val < 4):
fd1.write("Ratio of Distance moved by Center of mass\n")
fd1.write("H0, H1, H2, H3, H4, H5, H6\n")
if(val < 4):
fd2.write("Ratio of Ranges of Center of Mass: Single Pick vs Simultaneous Picks\n")
fd2.write("H2 Single, H2-2 picks, H3 Single, H3-2 picks,H4 Single,H4-2 picks, H6 Single, H6- picks\n")
if(val < 4):
fd3.write("Ratio of Distance Moved by Center of Mass: Single Pick vs Simultaneous Picks\n")
fd3.write("H2 Single, H2-2 picks, H3 Single, H3-2 picks,H4 Single,H4-2 picks, H6 Single, H6- picks\n")
else:
while cnt < 10:
test_case = generate_test(num_cases)
h0= heuristic0(test_case)
h1= heuristic1(test_case)
h2= heuristic2(test_case)
h3= heuristic3(test_case)
h6= heuristic6(test_case)
h0_stat = stat(h0,1)
h1_stat = stat(h1,1)
h2_stat = stat(h2,1)
h3_stat = stat(h3,1)
h4= heuristic4(test_case, min(h0_stat[2],h1_stat[1],h2_stat[2],h2_stat[2]))
h5= heuristic0(test_case, min(h0_stat[2],h1_stat[1],h2_stat[2],h2_stat[2]))
h4_stat = stat(h4,1)
h5_stat = stat(h5,1)
h6_stat = stat(h6,1)
h2_stat2 = stat2(h2,1)
h3_stat2 = stat2(h3,1)
h4_stat2 = stat2(h4,1)
h6_stat2 = stat2(h6,1)
range1 = min(h0_stat[2],h1_stat[2],\
h2_stat[2], h3_stat[2],\
h4_stat[2], h5_stat[2], h6_stat[2])
range2 = min(h2_stat2[2],h3_stat2[2],\
h4_stat2[2], h6_stat2[2])
dist1 = min(h0_stat[3],h1_stat[3],\
h2_stat[3], h3_stat[3],\
h4_stat[3], h5_stat[3], h6_stat[3])
dist2 = min(h2_stat2[3],h3_stat2[3],\
h4_stat2[3], h6_stat2[3])
#Range stat1
fd0.write("%f, %f, %f, %f, %f, %f, %f\n" %(h0_stat[2]/range1 , h1_stat[2]/range1 , h2_stat[2]/range1 , h3_stat[2]/range1 , h4_stat[2]/range1 , h5_stat[2]/range1 , h6_stat[2]/range1))
#Distance stat1
fd1.write("%f, %f, %f, %f, %f, %f, %f\n" %(h0_stat[3]/dist1, h1_stat[3]/dist1, h2_stat[3]/dist1, h3_stat[3]/dist1, h4_stat[3]/dist1, h5_stat[3]/dist1, h6_stat[3]/dist1))
#print "PICK 2 H6", h6_stat2
fd2.write("%f, %f, %f, %f, %f, %f, %f, %f\n" %(h2_stat[2]/range1,h2_stat2[2]/range2,\
h3_stat[2]/range1, h3_stat2[2]/range2,\
h4_stat[2]/range1,h4_stat2[2]/range2,\
h6_stat[2]/range1,h6_stat2[2]/range2))
#Distance stat2
fd3.write("%f, %f, %f, %f, %f, %f, %f, %f\n" %(h2_stat[3]/dist1,h2_stat2[3]/dist2,\
h3_stat[3]/dist1, h3_stat2[3]/dist2,\
h4_stat[3]/dist1,h4_stat2[3]/dist2,\
h6_stat[3]/dist1,h6_stat2[3]/dist2))
cnt += 1
while cnt < 10:
#test_case = generate_test(random.randint(1,10))
test_case = generate_test(num_cases)
#test_case = [440, 295, 466, 596, 836, -905, 981]
#print "Test Case:",test_case
#print "Optimal Solution:",
opt_range = find_opt(test_case)
opt_dist = find_opt(test_case, 1)
opt_range2 = find_opt2(test_case)
opt_dist2 = find_opt2(test_case,1)
#print "perm_arr", len(perm_arr)
#print "Average ",sum(test_case)*1.0/len(test_case)*1.0
#print "Optimal Statistics"
opt_stat_range = stat(list(opt_range[0]),1)
opt_stat_dist = stat(list(opt_dist[0]),1)
opt_stat_range2 = stat2(list(opt_range2[0]),1)
opt_stat_dist2 = stat2(list(opt_dist2[0]),1)
range1 = opt_stat_range[2]
range2 = opt_stat_range2[2]
dist1 = opt_stat_dist[3]
dist2 = opt_stat_dist2[3]
#print opt_stat_range
#print opt_stat_dist
#print "Heuristics"
h0= heuristic0(test_case)
h1= heuristic1(test_case)
h2= heuristic2(test_case)
h3= heuristic3(test_case)
h4= heuristic4(test_case, range1)
h5= heuristic0(test_case, range1)
h6= heuristic6(test_case)
#h0_stat2 = stat2(h0,1)
#h1_stat2 = stat2(h1,1)
h2_stat2 = stat2(h2,1)
h3_stat2 = stat2(h3,1)
h4_stat2 = stat2(h4,1)
#h5_stat2 = stat2(h5,1)
h6_stat2 = stat2(h6,1)
h0_stat = stat(h0,1)
h1_stat = stat(h1,1)
h2_stat = stat(h2,1)
h3_stat = stat(h3,1)
h4_stat = stat(h4,1)
h5_stat = stat(h5,1)
h6_stat = stat(h6,1)
#h5 is same as h0 with the change that there is a delta for it. h0 tries to keep c_i closest to c_{i-1}
"""
if(val == 5):
print h0, perm_arr.index(h0)
print h1, perm_arr.index(h1)
print h2, perm_arr.index(h2)
print h3, perm_arr.index(h3)
print h4, perm_arr.index(h4)
print h5, perm_arr.index(h5)
"""
#Range stat1
fd0.write( "%f, %f, %f, %f, %f, %f, %f\n" %(h0_stat[2]/range1 , h1_stat[2]/range1 , h2_stat[2]/range1 , h3_stat[2]/range1 , h4_stat[2]/range1 , h5_stat[2]/range1 , h6_stat[2]/range1))
#Distance stat1
fd1.write("%f, %f, %f, %f, %f, %f, %f\n" %(h0_stat[3]/dist1, h1_stat[3]/dist1, h2_stat[3]/dist1, h3_stat[3]/dist1, h4_stat[3]/dist1, h5_stat[3]/dist1, h6_stat[3]/dist1))
#Range Stat2
print "OPT RANGE2", opt_stat_range2
print "OPT DIST2", opt_stat_dist2
#print "PICK 2 H2", h2_stat2
#print "PICK 2 H3", h3_stat2
print "PICK H4", h4_stat
print "PICK 2 H4", h4_stat2
#print "PICK 2 H6", h6_stat2
fd2.write("%f, %f, %f, %f, %f, %f, %f, %f\n" %(h2_stat[2]/range1,h2_stat2[2]/range2,\
h3_stat[2]/range1, h3_stat2[2]/range2,\
h4_stat[2]/range1,h4_stat2[2]/range2,\
h6_stat[2]/range1,h6_stat2[2]/range2))
#Distance stat2
fd3.write("%f, %f, %f, %f, %f, %f, %f, %f\n" %(h2_stat[3]/dist1,h2_stat2[3]/dist2,\
h3_stat[3]/dist1, h3_stat2[3]/dist2,\
h4_stat[3]/dist1,h4_stat2[3]/dist2,\
h6_stat[3]/dist1,h6_stat2[3]/dist2))
if(val == 4):
print "CMAX, CMIN, INTERVAL, MOVEMENT"
print "H2", stat2(h2,1)
print "H3", stat2(h3,1)
print "H4", stat2(h4,1)
print "H6", stat2(h6,1)
cnt += 1
fd0.close()
fd1.close()
fd2.close()
fd3.close()
|
5205459cb550b7d0fdc94c9082362f6489ee9db8 | lo1cgsan/rok202021 | /2BP4/python_1/sort_wstaw.py | 830 | 3.546875 | 4 | import random
def losuj(lista, n, maks):
"""
Funkcja losuje n liczb z zakresu <0, n>
i dodaje je do listy.
"""
for i in range(n):
lista.append(random.randint(0, maks))
def sort_wstaw(lista, n):
"""
Funkcja sortuje listę liczb przy użyciu
algorytmu sortowania przez wstawianie.
"""
for i in range(1, n):
el = lista[i]
j = i - 1
while j >= 0 and el < lista[j]:
lista[j + 1] = lista[j]
j -= 1
lista[j + 1] = el
def main(args):
n = int(input('Ile liczb? '))
maks = 50
lista = [] # pusta lista
losuj(lista, n, maks)
print(lista) # lista nieposortowana
sort_wstaw(lista, n)
print(lista) # lista posortowana
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
df8a2c32664e756bdc357ba535de34d175c62a04 | xavierau/aind_soduku | /solution.py | 7,127 | 4.09375 | 4 | assignments = []
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
# Find all instances of naked twins
# Eliminate the naked twins as possibilities for their peers
total_chars_on_board_before = sum([len(values[box]) for box in boxes])
for unit in target_unit_list:
box_sets = dict([(box, values[box]) for box in unit if len(values[box]) == 2])
digits_container = set([value for value in box_sets.values() if list(box_sets.values()).count(value) == 2])
for digits in digits_container:
for digit in digits:
change_target_boxes = [box for box in unit if
values[box] not in digits_container and digit in values[box]]
for box in change_target_boxes:
values = assign_value(values, box, values[box].replace(digit, ""))
total_chars_on_board_after = sum([len(values[box]) for box in boxes])
return naked_twins(values) if total_chars_on_board_after < total_chars_on_board_before else values
def cross(A, B):
" Cross product of elements in A and elements in B."
return [s + t for s in A for t in B]
def grid_values(grid):
"""
Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid(string) - A grid in string form.
Returns:
A grid in dictionary form
Keys: The boxes, e.g., 'A1'
Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
"""
chars = []
digits = "123456789"
for char in grid:
chars.append(digits if char == '.' else char)
assert len(chars) == 81
return dict(zip(boxes, chars))
def display(values):
"""
Display the values as a 2-D grid.
Args:
values(dict): The sudoku in dictionary form
"""
width = 1 + max(len(values[s]) for s in values.keys())
line = '+'.join(['-' * (width * 3)] * 3)
for r in "ABCDEFGHI":
print(''.join(values[r + c].center(width) + ('|' if c in '36' else '')
for c in "123456789"))
if r in 'CF': print(line)
print("\n\n")
return
def eliminate(values):
single_digit_boxes = [box for box in values.keys() if len(values[box]) == 1]
for box in single_digit_boxes:
for peer_box in peer_list[box]:
if peer_box not in single_digit_boxes and len(values[peer_box]) > 1:
value = values[box]
values = assign_value(values, peer_box, values[peer_box].replace(value, ""))
return values
def only_choice(values):
target_list = target_unit_list
for unit in target_list:
for digit in "123456789":
dplaces = [box for box in unit if digit in values[box]]
if len(dplaces) == 1:
values = assign_value(values, dplaces[0], digit)
return values
def reduce_puzzle(values):
finished = False
while not finished:
previous = sum([len(values[box]) for box in values.keys()])
values = eliminate(values)
if all(len(values[box]) == 1 for box in boxes):
if is_completed(values):
return values
values = only_choice(values)
if all(len(values[box]) == 1 for box in boxes):
if is_completed(values):
return values
values = naked_twins(values)
if all(len(values[box]) == 1 for box in boxes):
if is_completed(values):
return values
after = sum([len(values[box]) for box in values.keys()])
finished = previous == after
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
values = reduce_puzzle(values)
if values is False:
return False
if is_completed(values):
return values
elif all(len(values[box]) == 1 for box in boxes):
return False
n, s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
for char in values[s]:
new_values = values.copy()
new_values[s] = char
attempt = search(new_values)
if attempt:
return attempt
def create_diagonal_units():
first_unit = []
second_unit = []
for i in range(len(rows)):
first_unit.append(rows[i] + cols[i])
second_unit.append(rows[len(rows) - i - 1] + cols[i])
return [first_unit, second_unit]
def peers(box):
_peers = []
for unit in target_unit_list:
if box in unit:
_peers += unit
_my_set = set(_peers)
_my_set.discard(box)
return list(_my_set)
def is_completed(values):
# target_list = unit_list
target_list = target_unit_list
# for each row only has 1 and only one
for unit in target_list:
temp_set = set()
for box in unit:
if len(values[box]) is not 1:
return False
if values[box] in temp_set:
return False
temp_set.add(values[box])
return values
def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution exists.
"""
sodoku_boxes = grid_values(grid)
solution = search(sodoku_boxes)
if solution:
return solution
else:
raise Exception('No Solution Found!')
rows = "ABCDEFGHI"
cols = "123456789"
# This are some constants
col_units = [cross(rows, col) for col in cols]
row_units = [cross(row, cols) for row in rows]
square_unit = [cross(row, col) for row in (["ABC", "DEF", "GHI"]) for col in (["123", "456", "789"])]
diagonal_units = create_diagonal_units()
boxes = cross(rows, cols)
standard_unit_list = col_units + row_units + square_unit
diagonal_unit_list = standard_unit_list + diagonal_units
# The target list is for toggle between diagonal or standard sudoku
target_unit_list = diagonal_unit_list
peer_list = dict([(box, peers(box)) for box in boxes])
if __name__ == '__main__':
diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
display(solve(diag_sudoku_grid))
try:
from visualize import visualize_assignments
visualize_assignments(assignments)
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
|
05f832de457f92cfe61b831a2b90b248725f3c14 | nanli-7/algorithms | /merge-sort.py | 1,888 | 4.1875 | 4 | """ Merge Sort
This is a very simple sorting algorithm. Because it's also very inefficient,
Bubble Sort is not practical for real-world use and is generally only discussed
in an academic context. The basic theory behind BubbleSort is that you take an
array of integers and iterate through it; for each element at some index whose
value is greater than the element at the index following it (i.e., index i+1 ),
you must swap the two values. The act of swapping these values causes the larger,
unsorted values to float to the back (like a bubble) of the data structure until
they land in the correct location.
Asymptotic Analysis
Worst Case: O(n^2)
Best Case: O(n)
Average: O(n^2)
"""
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
|
794e2f551081b111d5c4516007d5e87aa05be37e | brajesh-rit/hardcore-programmer | /Binary Search/BS_min_diff_sorted_arr.py | 637 | 3.6875 | 4 | #Given a sorted array, find the element in the array which has minimum difference with the given number.
class Solution:
def binary_search(self, arr, low, high, x):
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
if abs(arr[low] - x ) > abs(arr[high] - x ):
return high
else:
return low
# Your code here
arr = [1,2,8,10,11,12,19]
N = 7
x = 13
result = Solution()
print(result.binary_search(arr, 0, N -1 , x))
|
21c05e4f5d015d017b1065a892286c40451dba8e | lovejing0306/PythonInterview | /Chapter-005-generator/001_generators.py | 484 | 3.796875 | 4 | # coding=utf-8
## 生成器函数
def countdown(num):
print('Starting...')
while num>0:
yield num
num-=1
## 生成器表达式
# '()'表示一个生成器表达式,
# 不要混淆列表推导式‘[]’和生成器表达式‘()’
my_list = ['a', 'b', 'c', 'd']
gen_obj = (x for x in range(10))
if __name__ == '__main__':
val=countdown(5)
print(val)
print(val.next())
print(val.next())
print(gen_obj.next())
print(gen_obj.next()) |
57ad6a5942bff9c9555d366616f01fc44b4346b2 | sanjitsbatra/Sentiment_Mining_Twitter | /sortfile.py | 194 | 3.59375 | 4 | import sys
def sort(f):
l=open(f).read().split('\n')
g=open('bigram-sorted','w')
l=sorted(l)
for i in l:
g.write('%s\n' % i)
g.close()
def main(file):
sort(file)
main(sys.argv[1])
|
6316091608d8a8c0c745f4f391919df70072b126 | abhijeet-rawat/Hackerrank-Submissions | /submissions/Write a function.py | 578 | 4.09375 | 4 | '''-----------------------------------------------------------------------
Problem Title: Write a function
Problem Link: https://www.hackerrank.com/challenges/write-a-function
Author: abhijeet_rawat
Language : Python 3
-----------------------------------------------------------------------'''
def is_leap(year):
leap = False
if(year%4==0):
leap=True
if(year%100==0):
if(year%400==0):
leap=True
else:
leap=False
else:
leap=True
else:
leap=False
return leap
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.