Skip to content

Commit 9674e1d

Browse files
author
cuichao
committed
Merge remote-tracking branch 'upstream/master'
2 parents 5299455 + 3bbb74a commit 9674e1d

9 files changed

+480
-22
lines changed

4 Digit Number Combinations.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,10 @@ def FourDigitCombinations():
33
numbers=[]
44
for code in range(10000):
55
code=str(code).zfill(4)
6-
print code,
6+
print(code)
77
numbers.append(code)
8+
9+
# Same as above but more pythonic
10+
def oneLineCombinations():
11+
numbers = list(map(lambda x: str(x).zfill(4), [i for i in range(1000)]))
12+
print(numbers)

TicTacToe.py

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
# Tic Tac Toe
2+
3+
import random
4+
5+
def drawBoard(board):
6+
# This function prints out the board that it was passed.
7+
8+
# "board" is a list of 10 strings representing the board (ignore index 0)
9+
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
10+
print('-----------')
11+
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
12+
print('-----------')
13+
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
14+
15+
def inputPlayerLetter():
16+
# Lets the player type which letter they want to be.
17+
# Returns a list with the player's letter as the first item, and the computer's letter as the second.
18+
letter = ''
19+
while not (letter == 'X' or letter == 'O'):
20+
print('Do you want to be X or O?')
21+
letter = input().upper()
22+
23+
# the first element in the tuple is the player's letter, the second is the computer's letter.
24+
if letter == 'X':
25+
return ['X', 'O']
26+
else:
27+
return ['O', 'X']
28+
29+
def whoGoesFirst():
30+
# Randomly choose the player who goes first.
31+
if random.randint(0, 1) == 0:
32+
return 'computer'
33+
else:
34+
return 'player'
35+
36+
def playAgain():
37+
# This function returns True if the player wants to play again, otherwise it returns False.
38+
print('Do you want to play again? (yes or no)')
39+
return input().lower().startswith('y')
40+
41+
def makeMove(board, letter, move):
42+
board[move] = letter
43+
44+
def isWinner(bo, le):
45+
# Given a board and a player's letter, this function returns True if that player has won.
46+
# We use bo instead of board and le instead of letter so we don't have to type as much.
47+
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
48+
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
49+
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
50+
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
51+
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
52+
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
53+
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
54+
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
55+
56+
def getBoardCopy(board):
57+
# Make a duplicate of the board list and return it the duplicate.
58+
dupeBoard = []
59+
60+
for i in board:
61+
dupeBoard.append(i)
62+
63+
return dupeBoard
64+
65+
def isSpaceFree(board, move):
66+
# Return true if the passed move is free on the passed board.
67+
return board[move] == ' '
68+
69+
def getPlayerMove(board):
70+
# Let the player type in his move.
71+
move = ' '
72+
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
73+
print('What is your next move? (1-9)')
74+
move = input()
75+
return int(move)
76+
77+
def chooseRandomMoveFromList(board, movesList):
78+
# Returns a valid move from the passed list on the passed board.
79+
# Returns None if there is no valid move.
80+
possibleMoves = []
81+
for i in movesList:
82+
if isSpaceFree(board, i):
83+
possibleMoves.append(i)
84+
85+
if len(possibleMoves) != 0:
86+
return random.choice(possibleMoves)
87+
else:
88+
return None
89+
90+
def getComputerMove(board, computerLetter):
91+
# Given a board and the computer's letter, determine where to move and return that move.
92+
if computerLetter == 'X':
93+
playerLetter = 'O'
94+
else:
95+
playerLetter = 'X'
96+
97+
# Here is our algorithm for our Tic Tac Toe AI:
98+
# First, check if we can win in the next move
99+
for i in range(1, 10):
100+
copy = getBoardCopy(board)
101+
if isSpaceFree(copy, i):
102+
makeMove(copy, computerLetter, i)
103+
if isWinner(copy, computerLetter):
104+
return i
105+
106+
# Check if the player could win on his next move, and block them.
107+
for i in range(1, 10):
108+
copy = getBoardCopy(board)
109+
if isSpaceFree(copy, i):
110+
makeMove(copy, playerLetter, i)
111+
if isWinner(copy, playerLetter):
112+
return i
113+
114+
# Try to take one of the corners, if they are free.
115+
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
116+
if move != None:
117+
return move
118+
119+
# Try to take the center, if it is free.
120+
if isSpaceFree(board, 5):
121+
return 5
122+
123+
# Move on one of the sides.
124+
return chooseRandomMoveFromList(board, [2, 4, 6, 8])
125+
126+
def isBoardFull(board):
127+
# Return True if every space on the board has been taken. Otherwise return False.
128+
for i in range(1, 10):
129+
if isSpaceFree(board, i):
130+
return False
131+
return True
132+
133+
134+
print('Welcome to Tic Tac Toe!')
135+
136+
while True:
137+
# Reset the board
138+
theBoard = [' '] * 10
139+
playerLetter, computerLetter = inputPlayerLetter()
140+
turn = whoGoesFirst()
141+
print('The ' + turn + ' will go first.')
142+
gameIsPlaying = True
143+
144+
while gameIsPlaying:
145+
if turn == 'player':
146+
# Player's turn.
147+
drawBoard(theBoard)
148+
move = getPlayerMove(theBoard)
149+
makeMove(theBoard, playerLetter, move)
150+
151+
if isWinner(theBoard, playerLetter):
152+
drawBoard(theBoard)
153+
print('Hooray! You have won the game!')
154+
gameIsPlaying = False
155+
else:
156+
if isBoardFull(theBoard):
157+
drawBoard(theBoard)
158+
print('The game is a tie!')
159+
break
160+
else:
161+
turn = 'computer'
162+
163+
else:
164+
# Computer's turn.
165+
move = getComputerMove(theBoard, computerLetter)
166+
makeMove(theBoard, computerLetter, move)
167+
168+
if isWinner(theBoard, computerLetter):
169+
drawBoard(theBoard)
170+
print('The computer has beaten you! You lose.')
171+
gameIsPlaying = False
172+
else:
173+
if isBoardFull(theBoard):
174+
drawBoard(theBoard)
175+
print('The game is a tie!')
176+
break
177+
else:
178+
turn = 'player'
179+
180+
if not playAgain():
181+
break
182+

WikipediaModule

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,10 @@ def fullPage(page):
4646
return soup
4747

4848
def randomWiki():
49-
'''
50-
This function gives you a list of n number of random articles
51-
Choose any article.
52-
'''
49+
'''
50+
This function gives you a list of n number of random articles
51+
Choose any article.
52+
'''
5353
number=input("No: of Random Pages : ")
5454
lst=wk.random(number)
5555
for i in enumerate(lst):

chaos.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# A simple program illustrating chaotic behaviour
2+
3+
def main():
4+
print ("This program illustrates a chaotic function")
5+
x = float((input("Enter a number between 0 and 1: ")))
6+
for i in range(10):
7+
x = 3.9 * x * (1-x)
8+
print (x)
9+
10+
main()
11+

cricket_live_score.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@
1313

1414

1515
score_box=soup_page.findAll("div",{"class":"cb-col cb-col-25 cb-mtch-blk"})
16-
print(len(score_box))
17-
for i in range(10):
16+
l = len(score_box)
17+
print(l)
18+
for i in range(l):
1819
print(score_box[i].a["title"])
1920
print(score_box[i].a.text)
20-
print()
21+
print()

powerdown_startup.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
# Script Name : powerdown_startup.py
2-
# Author : Craig Richards
3-
# Created : 05th January 2012
4-
# Last Modified :
5-
# Version : 1.0
2+
# Author : Craig Richards
3+
# Created : 05th January 2012
4+
# Last Modified : 21th September 2017
5+
# Version : 1.0
66

77
# Modifications :
88

9-
# Description : This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you.
9+
# Description : This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you.
1010

11-
import os # Load the Library Module
12-
import subprocess # Load the Library Module
11+
import os # Load the Library Module
12+
import subprocess # Load the Library Module
1313
from time import strftime # Load just the strftime Module from Time
1414

1515
def windows(): # This is the function to run if it detects the OS is windows.
16-
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
16+
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
1717
for server in open('startup_list.txt','r'): # Read the list of servers from the list
1818
ret = subprocess.call("ping -n 3 %s" % server, shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
1919
if ret == 0: # If you get a response.
20-
f.write ("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile
20+
f.write ("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile
2121
subprocess.Popen(('putty -load '+server)) # Load the putty session
2222
else:
23-
f.write ("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down
23+
f.write ("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down
2424

2525
def linux():
26-
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
26+
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
2727
for server in open('startup_list.txt'): # Read the list of servers from the list
2828
ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
2929
if ret == 0: # If you get a response.
@@ -36,7 +36,9 @@ def linux():
3636

3737
# Start of the Main Program
3838

39-
if os.name == "posix": # If the OS is linux...
40-
linux() # Call the linux function
39+
if os.name == "posix": # If the OS is linux...
40+
linux() # Call the linux function
4141
elif os.name in ("nt", "dos", "ce"): # If the OS is Windows...
42-
windows() # Call the windows function
42+
windows() # Call the windows function
43+
else:
44+
print("Not supported")

sierpinski_triangle.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'''Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95
2+
3+
Simple example of Fractal generation using recursive function.
4+
5+
What is Sierpinski Triangle?
6+
>>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve,
7+
is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller
8+
equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e.,
9+
it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after
10+
the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski.
11+
12+
Requirements(pip):
13+
- turtle
14+
15+
Python:
16+
- 2.6
17+
18+
Usage:
19+
- $python sierpinski_triangle.py <int:depth_for_fractal>
20+
21+
Credits: This code was written by editing the code from http://www.lpb-riannetrujillo.com/blog/python-fractal/
22+
23+
'''
24+
import turtle
25+
import sys
26+
PROGNAME = 'Sierpinski Triangle'
27+
if len(sys.argv) !=2:
28+
raise Exception('right format for using this script: $python fractals.py <int:depth_for_fractal>')
29+
30+
myPen = turtle.Turtle()
31+
myPen.ht()
32+
myPen.speed(5)
33+
myPen.pencolor('red')
34+
35+
points = [[-175,-125],[0,175],[175,-125]] #size of triangle
36+
37+
def getMid(p1,p2):
38+
return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) #find midpoint
39+
40+
def triangle(points,depth):
41+
42+
myPen.up()
43+
myPen.goto(points[0][0],points[0][1])
44+
myPen.down()
45+
myPen.goto(points[1][0],points[1][1])
46+
myPen.goto(points[2][0],points[2][1])
47+
myPen.goto(points[0][0],points[0][1])
48+
49+
if depth>0:
50+
triangle([points[0],
51+
getMid(points[0], points[1]),
52+
getMid(points[0], points[2])],
53+
depth-1)
54+
triangle([points[1],
55+
getMid(points[0], points[1]),
56+
getMid(points[1], points[2])],
57+
depth-1)
58+
triangle([points[2],
59+
getMid(points[2], points[1]),
60+
getMid(points[0], points[2])],
61+
depth-1)
62+
63+
64+
triangle(points,int(sys.argv[1]))

0 commit comments

Comments
 (0)