blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
14de2d3ce67d4e89c45a3ac4427743931c852fc5 | saipavans/pythonrepo | /lab3/3Task9.py | 342 | 3.515625 | 4 | words_file_path = "../resources/words.txt"
fin = open(words_file_path)
words_exceeding_twenty_characters = 0
character_threshold = 20
for line in fin:
word = line.strip()
if len(word) > character_threshold:
words_exceeding_twenty_characters = words_exceeding_twenty_characters + 1
print(word)
print(words_exceeding_twenty_characters)
|
ead7c18a738ee6fec1ea6f4cb69805da4799b4b9 | VineethChandha/Cylinder | /TicTacToe_Game.py | 2,607 | 4.09375 | 4 | #PY.01.15 Project 8: Tic Tac Toe Game
#Description: It is a 2 player game where X and O are two persons symbols used to fill the board
# If one of the person fills the board in such a way his/her symbol forms a straight line or a
# daigonal he will be the winner
board = [" " for i in range(1,10)] #Board with nine spaces
def printboard(): # arrangement of board
row1="|{}|{}|{}|".format(board[0],board[1],board[2])
row2="|{}|{}|{}|".format(board[3],board[4],board[5])
row3="|{}|{}|{}|".format(board[6],board[7],board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def player_move(symbol):
print("your turn player{}".format(symbol))
choice = int(input("Enter your choice from (1-9): ").strip()) # Input to give the position to enter the symbol
if board[choice-1] == " ":
board[choice-1] = symbol
else:
print()
print("already filled") # if space is already used
def win(symbol): # checks for the sides and diagonals for the win case
if(board[0] == symbol and board[1] == symbol and board[2] == symbol)or\
(board[3] == symbol and board[4] == symbol and board[5] == symbol)or\
(board[6] == symbol and board[7] == symbol and board[8] == symbol)or\
(board[0] == symbol and board[4] == symbol and board[8] == symbol)or\
(board[2] == symbol and board[4] == symbol and board[6] == symbol)or\
(board[0] == symbol and board[3] == symbol and board[6] == symbol)or\
(board[1] == symbol and board[4] == symbol and board[7] == symbol)or\
(board[2] == symbol and board[5] == symbol and board[8] == symbol):
print("{} wins !!!".format(symbol))
return True
else:
return False
def draw(): #if no space is remaining and the win not happens then it is a draw
if " " not in board:
return True
else:
return False
while True: # used to print the table frequently
printboard()
player_move("X") # Gives chance to X
printboard() # prints the board with X input position
if win("X"): # checks for win
break #If win happens the loop breaks
elif draw(): # else draw
print("Its a draw")
break
player_move("O") #same as above with O
if win("O"):
break
elif draw():
print("Its a draw")
break
|
cdfad3f2a3b8d22c82c203195a5c03ec456111e6 | VineethChandha/Cylinder | /loops.py | 987 | 4.125 | 4 | # PY.01.10 introduction to the loops
for a in range(1,11): # a will be valuated from 1 to 10
print("Hi")
print(a)
even_numbers = [x for x in range(1,100) if x%2 == 0]
print(even_numbers)
odd_numbers = [x for x in range(1,100) if x%2 != 0]
print(odd_numbers)
words = ["ram","krishna","sai"]
answer = [[w.upper(),w.lower(),len(w)] for w in words]
print(answer)
word = ["Happy","Birthday","To","You"]
word="-".join(word) #Join key word is used to join the list of the words with some specific sign or space as required
print(word)
Word2 = "Happy Birthday To You"
split_word = Word2.split() #.split() funtion is used to make the sentance to the list of words
print(split_word)
# This brings out the names of friends in which letter a is present
names={"male":["sandeep","rakesh","sudheer",],"female":["sravani","dolly"]}
for gender in names.keys():
for friend in names[gender]:
if "a" in friend:
print(friend)
|
773b4f9062212086ea7f4444a5d26983219cc8bd | omnimarkn/python_crud_with_graph | /Menu.py | 933 | 3.71875 | 4 | class Menu:
def __init__(self):
self.menus = [
'Add Student',
'Store Grade on Existing Student' ,
'View Grade of Students for each Assesment',
'View Students with below Average Grade for each Assesment',
'View Report of Students Total Grade for the Semester',
'View Report of Students with below Average Grade for the Semester',
'Exit',
'Discussion Forum Report Grade',
'Project Grade',
'Final Exam Grade',
'Go Back',
'Exit',
'Add another User'
]
def createMenu(self,list=[]):
#TODO Implement One liner here
x=0
selected_menus=[]
for each_menu in self.menus:
for each_list in list:
if each_list == x:
selected_menus.append(each_menu)
x += 1
return selected_menus
def formatMenu(self,list=[]):
x=0
formatted_menu=""
for each_list in list:
formatted_menu += ('[{0}] {1} \n'.format(x,each_list))
x += 1
return formatted_menu |
3c557554bffacdc1a07db0b6fce7ebad4495f210 | hectortv9/turtle-crossing-start | /car.py | 1,451 | 3.546875 | 4 | import random
from screen_box import ScreenBox
from turtle import Turtle
FILL_COLORS = ["cornflower blue", "lime green", "orchid", "bisque3", "DarkOliveGreen4", "turquoise3", "purple3"]
CAR_COLOR = "white"
CAR_SHAPE_NAME = "car"
CAR_SHAPE = ((3, -10), (3, -6), (10, -5), (10, 4), (3, 6), (3, 8), (1, 10), # trunk (top) - roof - hood
(-7, 10), (-7, 7), (-10, 6), (-10, 4), (-7, 3), # front bumper - front wheel
(-7, -3), (-10, -4), (-10, -6), (-7, -7), (-7, -10)) # chassis - rear wheel - trunk (bottom)
class Car(Turtle):
def __init__(self, x, y, car_width_ratio, car_length_ratio):
super().__init__(shape=CAR_SHAPE_NAME, visible=False)
self.speed(0)
self.setundobuffer(None)
self.setheading(180)
self.shapesize(stretch_wid=car_width_ratio, stretch_len=car_length_ratio)
self.penup()
self.color(CAR_COLOR)
self.fillcolor(random.choice(FILL_COLORS))
self.setposition(x, y)
self.showturtle()
@staticmethod
def register_car_shape():
ScreenBox().screen.register_shape(name=CAR_SHAPE_NAME, shape=CAR_SHAPE)
def park(self, x, y):
self.hideturtle()
self.goto(x, y)
def exit_parking_lot(self, x, y):
self.goto(x, y)
self.showturtle()
def change_car_size(self, car_width_ratio, car_length_ratio):
self.shapesize(stretch_wid=car_width_ratio, stretch_len=car_length_ratio)
|
c61f81309de7e41b2bda16893872031a23632b1a | ferreiradh/URI-Online-Judge-Problems-Contests | /Iniciante/1010.py | 264 | 3.6875 | 4 | cod1, n1, valor1 = input().split(" ")
cod1 = int(cod1)
n1 = int(n1)
valor1 = float(valor1)
cod2, n2, valor2 = input().split(" ")
cod2 = int(cod2)
n2 = int(n2)
valor2 = float(valor2)
total = (n1 * valor1) + (n2 * valor2)
print(f'VALOR A PAGAR: R$ {total:.2f}') |
ef850216d86059027091cc350436313781320bc0 | lila-yilmaz/alistirmalar_I | /soru13.py | 205 | 3.65625 | 4 | for sayı1 in range(10,100):
s1 = str(sayı1)
for sayı2 in range(10,100):
s2 = str(sayı2)
if int( s1+s2 ) == ( int(sayı1) + int(sayı2) ) * 11:
print("sayı1=",sayı1,"\nsayı2=",sayı2)
|
c105707683771cfcd237d7ebf82e3c80a4591863 | lila-yilmaz/alistirmalar_I | /soru17.py | 485 | 3.921875 | 4 | sayı = input("Lütfen 3 veya 4 basamaklı bir sayı giriniz:")
if len(sayı) == 3:
if int(str(sayı)[0]) == int(str(sayı)[-1]):
print("Bu sayı palindromiktir!")
else:
print("Bu sayı palindromik değildir.")
elif len(sayı) == 4:
if int(str(sayı)[0]) == int(str(sayı)[-2]) and int(str(sayı)[1]) == int(str(sayı)[-1]):
print("Bu sayı palindromiktir!")
else:
print("Bu sayı palindromik değildir.")
|
8b5aee4c6d58a3ec1fcc85ae5ca34b3cdc092178 | suvadipde/python | /databaseinsert.py | 732 | 3.734375 | 4 | import sqlite3
# establishing the connection
con = sqlite3.connect('TEST.db')
# preparing a cursor object
cursor = con.cursor()
# preparing sql statement
# rec = (456789, 'Frodo', 45, 'M', 100000.00)
records = [
(123456, 'John', 25, 'M', 50000.00),
(234651, 'Juli', 35, 'F', 75000.00),
(345121, 'Fred', 48, 'M', 125000.00),
(562412, 'Rosy', 28, 'F', 52000.00)
]
sql = '''
INSERT INTO EMPLOYEE VALUES ( ?, ?, ?, ?, ?)
'''
# executing sql statement using try ... except blocks
try:
# cursor.execute(sql, rec)
cursor.executemany(sql, records)
con.commit()
except Exception as e:
print("Error Message :", str(e))
con.rollback()
# closing the database connection
con.close()
|
d31ae6d84acd8352773045a2ab46b21421db9442 | rajkonkret/python-szkolenie | /pi2_pong.py | 2,048 | 3.8125 | 4 | import turtle
def paddle(x,y):
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape("square")
paddle.color("white")
paddle.shapesize(stretch_wid=5,stretch_len=1)
paddle.penup()
paddle.goto(x,y)
return paddle
def ball(x,y):
circle = turtle.Turtle()
circle.shape("circle")
circle.color("red")
circle.goto(x,y)
circle.penup()
return circle
def create_window():
window = turtle.Screen()
window.title('Pong')
window.bgcolor('black')
window.setup(width=800,height=600)
window.tracer(0)
return window
def left_paddle_change(distance):
y = paddle_l.ycor()
y+=distance
if y in range(-250,250):
paddle_l.sety(y)
def right_paddle_change(distance):
y = paddle_r.ycor()
y+=distance
if y in range(-250,250):
paddle_r.sety(y)
def paddle_l_up():
left_paddle_change(20)
def paddle_l_down():
left_paddle_change(-20)
def paddle_r_up():
right_paddle_change(20)
def paddle_r_down():
right_paddle_change(-20)
window = create_window()
window.listen()
ball_c = ball(0,0)
paddle_r = paddle(350,0)
paddle_l = paddle(-350,0)
ball_c.dx = 2
ball_c.dy = -2
window.onkeypress(paddle_l_up,"w")
window.onkeypress(paddle_l_down,"s")
window.onkeypress(paddle_r_up,"Up")
window.onkeypress(paddle_r_down,"Down")
while True:
window.update()
ball_c.setx(ball_c.xcor()+ball_c.dx)
ball_c.sety(ball_c.ycor()+ball_c.dy)
if ball_c.xcor() > 390 or ball_c.xcor() < -390:
ball_c.goto(0,0)
ball_c.dx = -ball_c.dx
print("gool!")
if ball_c.ycor() > 290 or ball_c.ycor() < -290:
#ball_c.goto(0,0)
ball_c.dy = -ball_c.dy
if ball_c.xcor() == paddle_l.xcor() and abs(paddle_l.ycor()-ball_c.ycor()) < 80:
print("gooola nie ma....")
print(paddle_l.ycor())
ball_c.dx = -ball_c.dx
if ball_c.xcor() == paddle_r.xcor() and abs(paddle_r.ycor()-ball_c.ycor()) < 80:
print("gooola nie ma....")
print(paddle_r.ycor())
ball_c.dx = -ball_c.dx
|
7f5e17b47ddd4152186df642968e61752178fab9 | rajkonkret/python-szkolenie | /prime.py | 116 | 3.53125 | 4 | number = int (input('Podaj liczbe\n'))
p_n=True
if number%2==0:
print('parzysta')
else:
print('niepRZYSTA')
|
bd7374bbb746fc41fe349d7446f11a3eb4c954e9 | rajkonkret/python-szkolenie | /wt_3_12.py | 216 | 3.75 | 4 | def is_it_quibc(number_1):
return(round(pow(number,1.0/3.0),8) % 1 == 0)
try:
number = int(input('Podaj liczbę: '))
print('Jest sześcianem ?:', is_it_quibc(number))
except:
print('Incorrect value!') |
fb9e938d9d4e5335f4c7c21836bdf364527b7bac | rajkonkret/python-szkolenie | /pi_pong_maja.py | 2,305 | 3.8125 | 4 | import turtle
def create_window():
window = turtle.Screen()#ekran
window.title('Pong Akademia Kodu')#tytul
window.bgcolor('black')#kolor ekranu
window.setup(width=800,height=600)
window.tracer(0)#szybkosc odswiezania
return window
def create_paddle(x,y):
paddle = turtle.Turtle()#tworzy jeden element do rysowania
paddle.speed(0)
paddle.shape("square")#tworzy prostokat
paddle.color('white')
paddle.shapesize(stretch_wid=5, stretch_len=1)#rozmiar
paddle.penup()#nie ma sladow zolwika
paddle.goto(x,y)
return paddle
def create_ball():
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.shapesize(stretch_wid=1,stretch_len=1)
ball.color("white")
ball.goto(0,0)
ball.penup()
return ball
window = create_window()
paddle_left = create_paddle(-350,0)
paddle_right = create_paddle(350,0)
ball = create_ball()
window.listen()
def paddle_left_change(distance):
y = paddle_left.ycor()
y +=distance
paddle_left.sety(y)
def paddle_left_up():
paddle_left_change(20)
def paddle_left_down():
paddle_left_change(-20)
window.onkeypress(paddle_left_up,"w")
window.onkeypress(paddle_left_down,"s")
def paddle_right_change(distance):
y = paddle_right.ycor()
y +=distance
paddle_right.sety(y)
def paddle_right_up():
paddle_right_change(20)
def paddle_right_down():
paddle_right_change(-20)
window.onkeypress(paddle_right_up,"Up")
window.onkeypress(paddle_right_down,"Down")
# Up , Down
#while True:
#window.update()
ball.dx = 2
ball.dy = -2
# Up , Down
while True:
window.update()
ball.setx(ball.xcor()+ball.dx)
ball.sety(ball.ycor()+ball.dy)
# zdobyccie bramki
if ball.xcor() >390 or ball.xcor()<-390:
ball.goto(0,0)
ball.dx = ball.dx*-1
# odbijanie się piłki od krawędzi gornej i dolnej
if ball.ycor()>290 or ball.ycor() <-290:
ball.dy = ball.dy*-1
if ((ball.xcor() >340 and ball.xcor() <350) and (ball.ycor() <
paddle_right.ycor()+40 and ball.ycor()
>paddle_right.ycor()-40)):
ball.setx(340)
ball.dx*=-1
if ((ball.xcor() <-340 and ball.xcor() >-350) and (ball.ycor()
<
paddle_left.ycor()+40 and ball.ycor()
>paddle_left.ycor()-40)):
ball.setx(-340)
ball.dx*=-1 |
8adb0db493d91f2877df01a696fd936141a25146 | rajkonkret/python-szkolenie | /pon_3_ex5.py | 811 | 3.75 | 4 |
def multiply(x,y):
return x*y
def pitagoras(a,b,c):
if a<0 or b<0 or c<0 :
return False
array = [a,b,c]
array.sort()
#if array[0] *array[0]+array[1]*array[1]==array[2]*array[2] :
# return True
#else:
# return False
return array[0]*array[0] +array[1]*array[1] == array[2]*array[2]
first_number = int(input('Podaj liczbę pierwszą'))
seond_number = int(input('Podaj liczbe drugą'))
print(multiply(x=first_number,y=seond_number))
print(multiply(y=first_number,x=seond_number))
try:
f_n = input('Podaj bok a\n')
if int(f_n):
f_n =int(f_n)
+except ValueError:
if not f_n:
print('Brak boku')
else:
print('not int')
s_n = int(input('Podaj bok b\n'))
th_n = int(input('Podaj bok c\n'))
print(pitagoras(f_n,s_n,th_n))
|
4ad9f27ff0639ad57543eecb1f22fb8353eb8cd4 | rajkonkret/python-szkolenie | /14.py | 230 | 3.796875 | 4 | word = input('Podaj wyraz \n')
if word == 'Akademia':
print('Podałeś poprawne hasło')
else:
print('nie')
try:
age = int(input('Podaj wiek\n'))
print('Twój wiek to: ', age)
except:
print('To nie jest wiek') |
96f4ff5df40c6d37b6cba08cc463fd1aeb27a0f1 | rajkonkret/python-szkolenie | /pon_3_ex11.py | 167 | 3.59375 | 4 | def number_of_divisors(n):
counter = 0
for i in range(1,n+1):
if n%i == 0:
counter+=1
return counter
print(number_of_divisors(9240))
|
d19fa849423670874a2b749adeb8b2dba700cd6d | rajkonkret/python-szkolenie | /pi_03_kaggle.py | 397 | 3.71875 | 4 | import pandas as pd
df = pd.read_csv('2019.csv')
print(df.head())
print(df.columns)
max_index = 0
min_index = 0
for index in df.index:
print(index)
if(df['Score'][index] > df['Score'][max_index]):
max_index = index
if(df['Score'][index] < df['Score'][min_index]):
min_index = index
print(df['Country or region'][max_index])
print(df['Country or region'][min_index])
|
edd61578d315cd37951ec334a4a6348d18f50f4e | IwanMitsak/Praktyka | /завдання5.2.py | 570 | 3.671875 | 4 | import math
import itertools
def f(x,k):
return pow(-1,k-1)*pow(x,k)
e=0.001
a=-0.9
b=1
k=0
i=0
print('X ','f(x)','f(x)набл','eps ','iteration')
for x in itertools.count(start=a,step=0.2):
if x>b:
print('break')
break
tmp=f(x,k)
result=tmp
if 1+x == 0:
ex='NULL'
else:
ex = 1/(1+x)
while(abs(tmp)>=e):
k+=1
i+=1
tmp=f(x,k)
result+=x
print(x,ex,result,e,k)
print('Загальна к-сть ітерацій:',k)
|
d1266c7789546ff1a2ee4a1239a9e20bf117dd50 | miseriae/python.practice | /codewars/unique_in_order.py | 387 | 4.0625 | 4 | '''
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without
any elements with the same value next to each other and preserving the original order of elements.
'''
def unique_in_order(iterable):
list = []
for i in iterable:
if len(list) < 1 or not i == list[len(list) - 1]:
list.append(i)
return list |
93621e9707c7d40cb107ff3636c3a19b02cbf9e9 | feitenglee/target_offer | /13_1_N皇后.py | 1,186 | 3.546875 | 4 | # 2019-08-28
# by lifieteng@live.com
# 二维矩阵上的回溯问题,leetcode-#51
# 题目描述:n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
# 输入输出:给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
# 示例:
# 输入: 4
# 输出: [
# [".Q..", // 解法 1
# "...Q",
# "Q...",
# "..Q."],
# ["..Q.", // 解法 2
# "Q...",
# "...Q",
# ".Q.."]
# ]
def NQueen(n):
"""
args: n
return res(list)
"""
if n <= 0:
return []
if n == 1:
return ["Q"]
Q = ["."*n for i in range(n)]
for row in range(n):
for col in range(n):
return back_track(n, row, col,Q)
def back_track(n, i, j,Q):
Q[i][j] = 'Q'
if len(lis) == n:
res.append(lis)
for x in range(n):
for y in range(n):
if check(i,j,x,y):
Q[x][y] = 'Q'
back_track(n, x, y, Q)
return res
def check(i,j,k,l):
if k != i or l != j or abs(k-i) != abs(l-j):
return True
return False
if "__name__" == "__main__":
print(NQueen(4))
print(NQueen(8)) |
5fa81f2a650b285b0328fd85049e61fb336325b2 | feitenglee/target_offer | /34_二叉树中和为某一值的路径.py | 2,020 | 3.578125 | 4 | #!/usr/bin/env python
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-08-31 17:05:53
@LastEditTime: 2019-09-01 16:50:24
@Description:
@State: PYTHON35 PASS
'''
import sys
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def find_path(root, val):
if not isinstance(root, TreeNode) or not isinstance(val, int):
print("inputs are not TreeNode or int type!")
sys.exit(1)
path = []
cur_val = 0
find_path2(root, val, path, cur_val)
def find_path2(node, val, path, cur_val):
'''
@discription:
@param {type}
@return: none
'''
cur_val += node.data
path.append(node)
# 叶子节点的条件 not node.left and not node.right
if cur_val == val and not node.left and not node.right:
for i in path:
print(i.data, end=' ')
print()
if node.left:
find_path2(node.left, val, path, cur_val)
if node.right:
find_path2(node.right, val, path, cur_val)
path.pop()
# 递归判断是否包含和为某一值的路径(从根节点到叶子节点)
# 判断左右子树是否包含val-root.data值的路径,递归下去
def has_path_sum(root, val):
# 这种递归终止条件包含单独根节点的路径,不符合题意
# if not root:
# return val == 0
if not root:
return False
if not root.left and not root.right:
return root.data == val
# 递归左右子树
if (has_path_sum(root.left, val - root.data)):
return True
if (has_path_sum(root.right, val - root.data)):
return True
return False
if __name__ == "__main__":
node1 = TreeNode(10)
node2 = TreeNode(5)
node3 = TreeNode(12)
node4 = TreeNode(4)
node5 = TreeNode(7)
node1.left,node1.right = node2,node3
node2.left,node2.right = node4,node5
find_path(node1,22)
print(has_path_sum(node1, 22)) |
673a0b7e371aee727579c98eb803b65a553fe47e | feitenglee/target_offer | /55_二叉树的深度.py | 1,839 | 3.6875 | 4 | #!/usr/bin/env python
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-09-05 20:56:57
@LastEditTime: 2019-09-06 09:32:44
@Description: 二叉树的深度, 判断是否是平衡二叉树
题目1:二叉树深度
思路1:深度是max(左子树,右子树)+1,递归解决
题目2:是否是平衡二叉树
思路:不太理解
@State: PYTHON35 PASS
'''
import sys
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
#题目1:二叉树深度
def depth_of_tree(root):
# if not isinstance(root, TreeNode):
# print("input is not TreeNode!")
# sys.exit(1)
if not root:# 叶节点不是空,叶节点的子节点为空
return 0
left_depth, right_depth = 0, 0
left_depth += depth_of_tree(root.left)
right_depth += depth_of_tree(root.right)
depth = max(left_depth, right_depth) + 1
return depth
#题目2:判断是否是平衡二叉树,不太理解
def is_balanced(root):
depth = 0
return is_balanced_core(root, depth)
def is_balanced_core(root, depth):
if not root:
depth = 0
return True
left, right = 0, 0
if is_balanced_core(root.left, left) and is_balanced_core(root.right, right):
diff = left - right
if abs(diff) <= 1:
depth = max(left, right) + 1
return True
return False
if __name__ == "__main__":
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node1.left,node1.right = node2,node3
node2.left,node2.right = node4,node5
node3.right = node6
node5.left = node7
print(depth_of_tree(node1))
print(is_balanced(node1)) |
7d7de0be772aaed08737ed0612307dedf6ee0ac8 | feitenglee/target_offer | /A_二叉树遍历.py | 5,088 | 3.859375 | 4 | #!/usr/bin/env python
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-08-29 22:04:54
@LastEditTime: 2019-09-23 13:10:46
@Description:
1、前序遍历
2、中序遍历
3、后序遍历
4、层序遍历
5、二叉树的右视图,层序遍历的变种
6、根据前序遍历和中序遍历重建二叉树
思路:队列中只存放下一层的所有节点,即pop出当前层的所有节点
@State: PYTHON35 PASS
'''
import sys
from queue import Queue#单向队列
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
# 前序遍历
# 1)递归实现
def pre_order(root):
if root:
print(root.data,end='->')
pre_order(root.left)
pre_order(root.right)
# return 不返回任何值,仅仅是遍历二叉树
#2) 非递归实现1
def pre_order_recursive1(root):
if not root:
return
stack = []
p = root
while p or stack:
while p != None:
print(p.data,end='->')
stack.append(p)
p = p.left
if stack:
p = stack.pop().right
#3) 非递归实现2
def pre_order_recursive2(root):
if not root:
return
stack =[root]
while stack:
root = stack.pop()
print(root.data,end='->')
if root.right:
# if root.right != None:
stack.append(root.right)
if root.left:
# if root.left != None:
stack.append(root.left)
# 中序遍历
# 1) 非递归
def in_order_recursive(root):
if not root:
return
stack = []
p = root
while p or stack:
if p:
stack.append(p)
# print(p.data, end='')
p = p.left
else:
tmp = stack.pop()
print(tmp.data, end='')
p = p.right
print()
# 层序遍历
def level_order(root):
if not isinstance(root, TreeNode):
print("input is not TreeNode type!")
sys.exit(2)
q = Queue()
q.put(root)
while not q.empty():
node = q.get()
print(node.data, end="->")
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
print()
# 二叉树的右视图,将队列的最后一个元素保存下来
def right_view(root):
if not isinstance(root, TreeNode):
print("input is not TreeNode type!")
sys.exit(1)
if not root:
return
res = []
q = [root]
while q:
res.append(q[-1].data)
for _ in range(len(q)):# 加个for循环,每次队列中存放的都是下一层的所有节点
node = q.pop(0) # pop出当前层的所有节点
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res
# 二叉树的左视图,与右视图相似,将队列的首个元素保存下来
def left_view(root):
if not isinstance(root, TreeNode):
print("input is not TreeNode type!")
sys.exit(1)
if not root:
return
res = []
q = [root]
while q:
res.append(q[0].data)
for _ in range(len(q)):
node = q.pop(0)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res
# 根据前序遍历和中序遍历重建二叉树
def construct_BT(lis1,lis2):
if not isinstance(lis1,list) or not isinstance(lis2,list):
print("input is not list type!")
sys.exit(2)
if not lis1 or not lis2:
return None
if set(lis1) != set(lis2): # 判断两个序列是否匹配,元素是否相同
return
root = TreeNode(lis1[0]) #根节点
i = lis2.index(root.data)
root.left = construct_BT(lis1[1:i+1],lis2[:i])
root.right = construct_BT(lis1[i+1:],lis2[i+1:])
return root
if __name__ == '__main__':
"""
8
/ \
6 10
/ \ / \
5 7 9 11
"""
node1 = TreeNode(8)
node2 = TreeNode(6)
node3 = TreeNode(10)
node4 = TreeNode(5)
node5 = TreeNode(7)
node6 = TreeNode(9)
node7 = TreeNode(11)
node1.left,node1.right = node2,node3
node2.left,node2.right = node4,node5
node3.left,node3.right = node6,node7
preorder = [1,2,4,7,3,5,6,8]
inorder = [4,7,2,1,5,3,8,6]
print("前序遍历:",end='')
pre_order(node1)
print("\n前序非递归遍历1:",end='')
pre_order_recursive1(node1)
print("\n前序非递归遍历2:",end='')
pre_order_recursive2(node1)
print("\n中序非递归遍历2:",end='')
in_order_recursive(node1)
print("\n层序遍历:",end='')
level_order(node1)
print("二叉树的右视图:",end='')
print(right_view(node1))
print("二叉树的左视图:",end='')
print(left_view(node1))
re_root = construct_BT(preorder,inorder)
print("重建二叉树的前序遍历:",end='')
pre_order(re_root) |
09be272a07d69c34fac2832d7e484bed71947dd3 | feitenglee/target_offer | /54_二叉搜索树的第k大节点.py | 1,471 | 3.890625 | 4 | #!/usr/bin/env python
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-09-05 20:41:15
@LastEditTime: 2019-09-05 20:54:16
@Description: 二叉树的中序遍历,是二叉树的升序
@State: PYTHON35 PASS
'''
import sys
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def kth_biggest_node(root, k):
if not isinstance(root, TreeNode) or not isinstance(k,int):
print("input is not TreeNode or int type!")
sys.exit(1)
if not root:
print("root is Node")
sys.exit(1)
# if
lis = []
mid_order(root,lis)
if k >= len(lis):
print("k is larger than the number of nodes")
sys.exit(1)
index = -1 * k
return lis[-1*k]
def mid_order(root, lis):
if not root:
return
if root:
mid_order(root.left,lis)
lis.append(root.data)
mid_order(root.right,lis)
if __name__ == "__main__":
node1 = TreeNode(5)
node2 = TreeNode(3)
node3 = TreeNode(7)
node4 = TreeNode(2)
node5 = TreeNode(4)
node6 = TreeNode(6)
node7 = TreeNode(8)
node1.left,node1.right = node2,node3
node2.left,node2.right = node4,node5
node3.left,node3.right = node6,node7
lis = []
mid_order(node1,lis)
print(lis)
print(kth_biggest_node(node1,5))
print(kth_biggest_node(node1,10))# k超出节点个数 |
790caf7e8da81001024549ecec550403d23c2ff1 | witoriamanuely/IA-2019.1 | /SearchingAlgorithms/BFS.py | 1,104 | 3.65625 | 4 | class BFS:
def __init__(self, grafo):
self.grafo = grafo
self.caminho = []
def imprimeCaminho(self):
print("Caminho achado utilizando BFS:")
for i in range(len(self.caminho)):
if i+1 == len(self.caminho):
print(self.caminho[i])
else:
print(self.caminho[i], "->", end=" ")
def BFS(self, origem, destino):
visitados = {}
for indice in self.grafo.nodes:
visitados[indice] = False
fila = []
fila.append(origem)
visitados[origem] = True
# Percorre o grafo e verifica se o lugar não foi visitado, adiciona na fila uma codição boleana na posição que
# ainda não foi visitada
while fila:
origem = fila.pop(0)
self.caminho.append(origem)
if origem == destino:
self.imprimeCaminho()
return
for i in self.grafo.neighbors(origem):
if visitados[i] == False:
fila.append(i)
visitados[i] = True
|
9fbc8187fe431f5322c4f1270562b810209cb77c | rustamovilyos/python_lessons | /py_lessons_for_github/my_game/game.py | 3,688 | 3.625 | 4 | import random #random ishlashi
b = 3 #joni
while True:
a = (random.randint (0,1)) #uyin sonlari random tanlash
print (a,'=') #ekranga chiqarish
x = int (input ('=')) #uynavotgan odami son kiritishi
if x == a: #tekshirib olish tengmi yoqmi
b = b - 1 #agar teng bolsa jondan 1ta olib tashiydi
if b == 0: #tugatishi tekshirish
break #tugatish
if x > 1: #boshqa sonlar ishtirok etishini tekshirish
break #tugatish
'''import random #random ishlashi
li = ['+','*','-'] #lislardan amallari
jon_sonni = 3 #uyin uchun jon
yutuq = 0 #yutuqlarni xisoblash
soat_hisobi = 0 #soat hisoblash uchun uzgaruvchi
while True:
birinchi_son = (random.randint(1,10)) # birinchi son random tanlash
ikkinchi_son = (random.randint(1,10)) #birinchi son random tanlash
amallar = (random.randint(1, len(li)-1)) #amali random tanlash
ifdagi_ammalar = li[amallar] #litdagi amalni bitta uzgaruvchiga tenglab olish
#if kampyuter uzi uchun xisob olvoti
if ifdagi_ammalar == '+': # amal qaysligini bilish
amal = birinchi_son + ikkinchi_son # qushuv amali bolsa ishlash
elif ifdagi_ammalar == '*': # amal qaysligini bilish
amal = birinchi_son * ikkinchi_son # kupaytruv amali bolsa ishlash
elif ifdagi_ammalar == '-': # amal qaysligini bilish
amal = birinchi_son - ikkinchi_son # ayiruv amali bolsa ishlash
print (birinchi_son , li[amallar] , ikkinchi_son ,'=') #ekranga chiqariash
javob = int (input('=')) #javobni qabul qilib olish
if amal == javob: #berilgan javob bilan berilgan savolni solishtrish
yutuq += 1 #agar tugri bulsa tugri javoblar sonini yana bittaga oshiradi
if amal != javob: #berilgan javob bilan berilgan savolni solishtrish
jon_sonni -= 1 #agar savol notugri bulsa uyindagi jodan bittasini olib tashiydi
print ('sizning joninggiz',jon_sonni,'ta qoldi') #qolgan jonlar sonini ekranga chiqaradi
if jon_sonni == 0: #joni sonini tekshirish
print ('\n\tuyin tugadi!') #uyin tugaganini habar berish
print ('siz',yutuq,'ta savolga tugri javob berdiz') #nechta savolga javob berganini kursatish
break ''' #uyini tugadish
# windows 7 sapyor uynash
# tekinter interfeyz un
# pygam |
d9eb3425a954f55795c7be817c10923987c3f191 | rustamovilyos/python_lessons | /py_lessons_for_github/dars_3/if-else.py | 1,451 | 3.90625 | 4 | # """ if ni yozilish strukturasi"""
# x = True
# x = False
# if x:
# print('x true!')
# print('if ichidagi komanda')
# print('if dan tashqari komanda')
# """ <, >, <=, >=, == """
# y = 2
# if y < 4:
# print('y 4 dan kichkina')
# """ Misol №1 """
# x = int(input(' 5 bilan taqqoslash uchun son kiriting: '))
# if x < 5:
# print('x 5 dan kichkina')
# # if x > 5:
# else:
# print('x 5 dan katta')
# """ Misol №2 """
# x = input('Matn kiriting: ')
# if x.count('1'):
# print('Matnda 1 raqami yo\'q!')
# else:
# print('Matnda 1 raqami bor!')
#
#
# """ elif """
# y = 3
# if y == 1:
# print('y 1 ga teng')
# elif y == 2:
# print('y 2 ga teng')
# elif y == 3:
# print('y 3 ga teng')
# else:
# print('y 3 dan katta')
# x = input('Ixtiyoriy 1ta harf kiriting: ')
# x = x.lower()
# if x == 'a':
# print('Siz kiritgan harf A')
# elif x == 'b':
# print('Siz kiritgan harf B')
# elif x == 'c':
# print('Siz kiritgan harf C')
# else:
# print('Siz alfabitda yo\'q harf kiritdingiz! :)')
# x = 5
# # if x == 4 or x == 5:
# if x > 4 and x < 6:
# print('1')
# else:
# print('0')
# x = int(input(' '))
# if x: #bu x teng emas 0 ga degani
# r = 2500/x
# print(r)
# else:
# print('Siz 0 sonini kiritdingiz!!')
# """ Misol №3 """
# x = int(input())
# if x:
# print('Kiritilgan raqam 0 ga teng emas')
# else:
# print('Kiritilgan raqam 0 ga teng!') |
9136b04d39610962d6316eb077735b5dfb7c7bf7 | rustamovilyos/python_lessons | /py_lessons_for_github/dars_10/vaqt.py | 742 | 3.96875 | 4 | # import time
# x = 0
# while True:
# print(x)
# x = x + 1
# time.sleep(2)
##############################################
# import time
# print(time.strftime("%H:%M:%S"))
# print(time.strftime("%Y-%m-%d"))
# print(time.strftime("%D"))
#########################################
# import time
# x = 0
# while x < 20:
# print('x ni qiymati = ', x)
# x = x + 1
# time.sleep(2)
##############################################
import time
x = 0
while x < 20:
print('x ni qiymati = ', x)
x = x + 1
time.sleep(2)
#########################################
# import time
# x = 0
# while x < 20:
# print('x ni qiymati = ', x, 'z ni qiymati = ', z)
# x = x + 1
# z = z + 3
# time.sleep(z) |
509e1fd051492bccb5ff9a2b9c92cbf39dc9e165 | rustamovilyos/python_lessons | /py_lessons_for_github/dars_3/Vazifa-6.py | 655 | 3.8125 | 4 | а = int(input('введите число для а: '))
б = int(input('введите число для б: '))
с = int(input('введите число для с: '))
д = int(input('введите число для д: '))
if (а+б)%4 == 0:
print("а + б")
else:
print("а + б:", False)
if (б+с)%4 == 0:
print("с + б")
else:
print("а + б:", False)
if (с+б+а)%4 == 0:
print("а + б + с")
else:
print("а + б + с:", False)
if (д+б+с)%4 == 0:
print("б + с + д")
else:
print("б + с + д:", False)
if (а+с+б+д)%4 == 0:
print("а + б + с + д")
else:
print("а + б + с + д:", False) |
d68124c47ce8939dc69bf08b6d38758b8c09dc3b | Teresa90/demo | /assisngment2.py | 805 | 4.09375 | 4 | import math
def introduction_message():
print("This program computers the roots")
print("of a second order equation:")
print()
print(" ax^2+bx+c=0 ")
print()
def input_and_solve():
a = eval(input ("please enter a: "))
b = eval(input ("please enter b: "))
c = eval(input ("please enter c: "))
delta = (b*b) - (4*a*c)
xl = -b + math.sqrt(delta)
x2 = -b - math.sqrt(delta)
print()
print("The roots are : ")
print("xl = ", xl)
print("x2 = ", x2)
def final_message():
print()
print(" Thank you for using this program")
print("=================================")
print("*** All rights reserved ***")
print("=================================")
print()
introduction_message()
input_and_solve()
final_message()
|
bb5ca3c05d0d46ab6ba63e7a75e3632bc91e1db7 | Artyom1803/course-2130 | /year_2021/python/hw2/legacy.py | 1,208 | 3.703125 | 4 | def t1(number):
"""
Поправьте код, чтобы возвращаемое значение было ближайшим сверху, кратным к 20
Пример: number=21 тогда нужно вернуть 40
Пример: -5 -> 0
"""
pass
def t2(string):
"""
На вход подается набор слов, разделенных пробелом, инвертируйте каждое слово.
Пример: `abc abc abc` -> `cba cba cba`
"""
pass
def t3(dictionary):
"""
На вход подается словарь. Преобразуйте его в строку по следующему шаблону 'key: value; key: value' и так далее
"""
pass
def t4(string, sub_string):
"""
проверить есть ли в строке инвертированная подстрока
"""
pass
def t5(strings):
"""
На вход подается список строк,
Отфильтруйте список строк, оставив только строки в формате: `x y z x*y*z`, где x,y,z - целые положительные числа
"""
pass |
f80085477c26ac983c627180dd14c432f64bc439 | cuchas/pythonlab | /my-first-script.py | 453 | 3.828125 | 4 | def welcome_message(name):
#Prints out a personalised welcome message
return "Welcome to this Python script, {}!".format(name)
def enjoy_yourself(name):
#prints how I'm happy to learn python
return "Long time you wanted to learn python, congratulations {}".format(name)
#Call the welcome message function with the input "Udacity Student"
#and print the output
print(welcome_message("Udacity Student"))
print(enjoy_yourself('eduardo')) |
4ca05ba21a3bcc47d07c19c414a48b9086754c3d | awanisazizan/awanis-kl-oct18 | /strToNum.py | 343 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 11:36:32 2018
@author: awanis.azizan
"""
deposit = input("How much would you like to deposit?")
freeToaster
if float(deposit) > 100:
freeToaster = True
else :
print("Enjoy your free mug!")
if freeToaster:
print("You get a free toaster!")
print("Have a nice day!") |
daf4203e12c8e480fe1b6b0b9f1f3e63b2f292fa | awanisazizan/awanis-kl-oct18 | /birthday.py | 439 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 10:41:07 2018
@author: awanis.azizan
"""
import datetime
#birthday = input("What is your birthday? (dd/mm/yyyy)" )
#birthdate = datetime.datetime.strptime(birthday,"%d/%m/%Y").date()
#print("Your birth month is " +birthdate.strftime('%B'))
nextBirthday = datetime.datetime.strptime('11/26/2018',"%m/%d/%Y").date()
currentDate = datetime.date.today()
print(nextBirthday - currentDate) |
30d48de72e6ebae96779f46a1eac87450af54187 | awanisazizan/awanis-kl-oct18 | /shipping.py | 302 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 11:20:04 2018
@author: awanis.azizan
"""
answer = input("Would you like express shipping?").lower()
if answer == "yes" :
print("That would add $10 to the fees")
print("Thank you!")
else :
print("Thank you for your purchase!") |
37475caf8afef1bfb9cf94754b6473c94bafbe39 | mogulseeker/sentiment-analysis | /20190922_Sentiment_analysis-assignment.py | 2,929 | 3.78125 | 4 |
#Import the relevant libraries
import pandas as pd
import matplotlib.pyplot as plt
#Import the baseline file and label the columns
df = pd.read_fwf('baseline.txt', delimiter=" ", names = ['Class', "Count"])
df
#remove the column header that we do not need
df = df.dropna()
df
# add a new column with the sentiment values
df = df.copy()
df['Values'] = range(-5,6)
df
#Find the total number of sentiment counts
df['Count'].sum()
# Multiply the count by value to get the score
df['Score'] = df['Count']*df['Values']
#Normalize the count value and score value to total counts
df['Normalized Count']=df['Count']/df['Count'].sum()
df['Normalized Score']=abs(df['Normalized Count']*df['Values'])
df
#Average sentiment value
df['Score'].sum()/df['Count'].sum()
#Make a bar plot of the baseline tweet sentiment scores
plt.bar(df['Values'],abs(df['Score']))
plt.xlabel('Sentiment Value')
plt.ylabel('Tweet Score')
plt.title('Baseline Tweet Sentiment Scores')
plt.show()
#Make a bar plot of the baseline tweet sentiment normalized scores
plt.bar(df['Values'],df['Normalized Score'])
plt.xlabel('Sentiment Value')
plt.ylabel('Normalized Tweet Score')
plt.title('Baseline Tweet Sentiment Normalized Score')
plt.show()
#Bar plot of the baseline tweet sentiment count
plt.bar(df['Values'],df['Count'])
plt.xlabel('Sentiment Value')
plt.ylabel('Tweet Count')
plt.title('Baseline Tweet Sentiment Count')
plt.show()
#Bar plot of the baseline tweet sentiment normalized count
plt.bar(df['Values'],df['Normalized Count'])
plt.xlabel('Sentiment Value')
plt.ylabel('Tweet Normalized Count')
plt.title('Baseline Tweet Sentiment Normalized Count')
plt.show()
# # # # # #
# Import the search specific tweets and make the same columns as we did for the baseline tweets.
#Import the baseline file and label the columns
df2 = pd.read_fwf('buff_py.txt', delimiter=" ", names = ['Class', "Count"])
df2
#remove the column header that we do not need
df2 = df2.dropna()
df2
# add a new column with the sentiment values
df2 = df.copy()
df2['Values'] = range(-5,6)
df2
# Find the 'total count' AND 'average sentiment value' of your specific tweets
df2['Count'].sum()
# Multiply the count by value to get the score
df2['Score'] = df2['Count']*df2['Values']
#Normalize the count value and score value to total counts
df2['Normalized Count']=df2['Count']/df['Count'].sum()
df2['Normalized Score']=abs(df2['Normalized Count']*df2['Values'])
df2
#Average sentiment value
df2['Score'].sum()/df2['Count'].sum()
# Make at least two graphs representing your specific tweet sentiment analysis. They can be similar to the plots above
# but they can be different too. Makre sure you add titles and have labeled axis.
# Try making at least one graph that shows the difference in baseline tweet counts or scores to your tweet specific counts or scores.
# Remember, Google (LMGTFY) is a great resource.
##### find the graph and the writeup in the word doc |
075aef3a38d29f02a62052d369e285788d0267f6 | LuizVinicius38/Semana-04---Aula-1---Parte-2 | /Atividade_Aula_4_2.2.py | 105 | 3.65625 | 4 | a = int(input(""))
b = int(input(""))
c = int(input(""))
resultado = (a + b + c)/3
print(resultado)
|
cc229e16ee78884dd3774fac7fd4bf64916e9960 | umpatel2618/Exercism | /isogram/isogram.py | 202 | 3.953125 | 4 | def is_isogram(string):
check=True
string=string.lower()
for i in string:
if i!=" " and i!="-" and string.count(i)>1:
check=False
break
return check
|
aaf7a5a0a5195ff1376ef2f0d6e6f84ffc273341 | XxdpavelxX/Python3 | /L3 Iteration in Python/decoder.py | 1,682 | 4.625 | 5 | """Create a Python3_Homework03 project and assign it to your Python3_Homework working set. In the
Python3_Homework03/src folder, create a file named decoder.py, which contains an iterator named alphabator.
When passed a list, simply return objects as-is unless they are integers between 1 and 26, in which case it
should convert that number to the corresponding letter. The integer-to-letter correspondence is 1=A, 2=B, 3=C, 4=D,
and so on.
You may use any technique you've learned in lesson 3 to execute this project.
Your alphabator iterator must pass the unittest below:
test_decoder.py
from string import ascii_uppercase
import unittest
from decoder import alphabator
class TestAlpha(unittest.TestCase):
def test_easy_26(self):
a = alphabator(range(1,27))
self.assertEqual(list(ascii_uppercase), list(a))
def test_upper_range(self):
a = alphabator(range(40,50))
self.assertEqual(list(range(40, 50)), list(a))
def test_various_objects(self):
l = ['python', object, ascii_uppercase, 10, alphabator]
a = list(alphabator(l))
self.assertNotEqual(l[3], a[3])
self.assertEqual("J", a[3])
self.assertTrue(isinstance(a[1], object))
if __name__ == "__main__":
unittest.main()
Submit decoder.py and test_decoder.py when they are working to your satisfaction.
"""
####################################################################################################################################################################
def alphabator(lst):
for num in lst:
if num in range(1,27):
yield chr(num+64)
else:
yield num
|
0a78c83f9ef57d9b72a23fe657ed93c9761f3e3e | XxdpavelxX/Python3 | /L4 Basic Regular Expressions/find_regex.py | 1,719 | 4.3125 | 4 | """Here are your instructions:
Create a Python3_Homework04 project and assign it to your Python3_Homework working set. In the Python3_Homework04/src
folder, create a program named find_regex.py that takes the following text and finds the start and end positions of the
phrase, "Regular Expressions".
Text to use in find_regex.py
In the 1950s, mathematician Stephen Cole Kleene described automata theory and formal language theoryin a set of models
using a notation called "regular sets" as a method to do pattern matching. Activeusage of this system, called Regular
Expressions, started in the 1960s and continued under such pioneers as David J. Farber, Ralph E. Griswold, Ivan P. Polonsky,
Ken Thompson, and Henry Spencer.
Your project should meet the following conditions:
•Your code must return 231 as the start and 250 as the end.
•You must include a separate test_find_regex.py program that confirms that your code functions as instructed.
Submit find_regex.py and test_find_regex.py when they are working to your satisfaction."""
##############################################################################################################################################################
import re
a = """In the 1950s, mathematician Stephen Cole Kleene described automata theory and formal language theory
in a set of models using a notation called "regular sets" as a method to do pattern matching. Activeusage of this system,
called Regular Expressions, started in the 1960s and continued under such pioneers as David J. Farber, Ralph E. Griswold,
Ivan P. Polonsky, Ken Thompson, and Henry Spencer."""
def searcher():
match = re.search("Regular Expressions", a)
beginning = match.start()
ending = match.end()
return (("Starts at:%d, Ends at:%d")%(beginning, ending))
print (searcher())
|
1eff10714e2827822e302261df860ce54ce51a8b | seryeongi/learn_algorithm | /Code06-03.py | 2,048 | 3.765625 | 4 | ## 함수
def isStackFull():
global SIZE, stack, top
if top >= SIZE -1 :
return True
else:
return False
def isStackEmpty():
global SIZE, stack, top
if top <= -1 :
return True
else:
return False
def pop() :
global SIZE, stack, top
if (isStackEmpty()) :
print('스택 텅!')
return
data = stack[top]
stack[top] = None
top -= 1
return data
def push(data):
global SIZE, stack, top
if (isStackFull()) :
print('스택 꽉!')
return
top += 1
stack[top] = data
def peek():
global SIZE, stack, top
if (isStackEmpty()) :
print('스택 텅!')
return None
return stack[top]
## 전역
SIZE = int(input('스택 크기 입력하세요-->'))
stack = [None for _ in range(SIZE)]
top = -1
## 결과 확인
# stack = ['커피','녹차','꿀물','콜라','환타']
# top = 4
# stack = ['커피','녹차','꿀물','콜라',None]
# top = 3
#
# print(stack)
# push('개토레이')
# print(stack)
# push('파워에이드')
# print(stack)
#
# stack = ['커피',None,None,None,None]
# top = 0
# retData = pop()
# print(retData)
# retData = pop()
# print(retData)
## 메인
if __name__ == '__main__' :
select = input('삽입(I)/추출(E)/확인(V)/종료(X) 중 하나 선택 -->')
while (select != 'X' and select != 'x') :
if (select == 'I' or select == 'i') :
data = input('입력할 데이터 -->')
push(data)
print('스택 상태 : ',stack)
elif (select == 'E' or select == 'e') :
data = pop()
print('추출된 데이터 -->',data)
print('스택 상태 : ',stack)
elif (select == 'V' or select == 'v') :
data = peek()
print('확인된 데이터 -->', data)
print('스택 상태 : ', stack)
else:
print('입력이 잘못됨!')
select = input('삽입(I)/추출(E)/확인(V)/종료(X) 중 하나 선택 -->')
print('프로그램 종료!')
|
ccc8620d0ec8f4dd1fdf13800ce16db8efa218ff | BiancaHofman/python_practice | /ex37_return_and_lambda.py | 744 | 4.3125 | 4 | #1. Normal function that returns the result 36
#And this result is printed
def name():
a = 6
return a * 6
print(name())
#2. Normal function that only prints the result 36
def name():
a = 6
print(a * 6)
name()
#3. Anonymous function that returns the result 36
#And this result is printed
x = lambda a: a * 6
print(x(6))
#4. Normal function that returns the result 30
#And this result is printed
def multiply():
a = 6
b = 5
return a * b
print(multiply())
#5. Normal function that only prints the result 30
def multiply():
a = 6
b = 5
print(a * b)
multiply()
#6.Anonymous function that returns result 30
#And this result is prints
multiply = lambda a, b: a * b
print(multiply (6,5)) |
fa489d07b01773a2018ed9c381198b045b4cb7d3 | gjreda/rosalind | /bioinformatics-stronghold/iprb.py | 1,864 | 3.921875 | 4 | """
Problem ID: IPRB
http://rosalind.info/problems/iprb/
Mendel's First Law
------------------
Given: Three positive integers k, m, and n, representing a population
containing k+m+n organisms: k individuals are homozygous dominant for
a factor, m are heterozygous, and n are homozygous recessive.
Return: The probability that two randomly selected mating organisms
will produce an individual possessing a dominant allele (and thus
displaying the dominant phenotype). Assume that any two organisms can mate.
"""
def calculate_dominant_phenotype_probability(k, m, n):
people = k + m + n
if people < 2:
raise ValueError
p = 0
# YY x (YY or Yy or yy) = 1.0
p += (k / people) * ((k - 1) / (people - 1)) * 1.0
p += (k / people) * (m / (people - 1)) * 1.0
p += (k / people) * (n / (people - 1)) * 1.0
# Yy x (YY or Yy or yy)
p += (m / people) * (k / (people - 1)) * 1.0
p += (m / people) * ((m - 1) / (people - 1)) * 0.75
p += (m / people) * (n / (people - 1)) * 0.5
# yy x (YY or Yy or yy)
p += (n / people) * (k / (people - 1)) * 1.0
p += (n / people) * (m / (people - 1)) * 0.5
p += (n / people) * ((n - 1) / (people - 1)) * 0
return p
# test it
assert(calculate_dominant_phenotype_probability(2, 0, 0) == 1.0)
assert(calculate_dominant_phenotype_probability(1, 1, 0) == 1.0)
assert(calculate_dominant_phenotype_probability(1, 0, 1) == 1.0)
assert(calculate_dominant_phenotype_probability(0, 2, 0) == 0.75)
assert(calculate_dominant_phenotype_probability(0, 1, 1) == 0.5)
assert(calculate_dominant_phenotype_probability(0, 0, 2) == 0.0)
assert(round(calculate_dominant_phenotype_probability(2, 2, 2), 5) == 0.78333)
with open('data/rosalind_iprb.txt', 'r') as f:
k, m, n = [int(s) for s in f.read().strip().split()]
print(calculate_dominant_phenotype_probability(k, m, n))
|
9dc01537d2a393584196037037261f946f31e8a6 | niranjana209/pro4.py | /30pro.py | 185 | 3.578125 | 4 | ani=(input())
cute=0
for i in range(0,len(ani)):
suro=(ani[:i]+ani[i+1:])
if(int(suro) % 8==0):
cute=1
break
if(cute==1):
print("yes")
else:
print("no")
|
d411b1259d7a7e4ea8d8f45a4bb0a213659aa275 | ermeydan-coder/jenkins-webhook-project | /hello-world.py | 141 | 3.8125 | 4 | fruits = ["christian", "joseph", "tyler", "kiwi", "azra"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist) |
2cf1813ba0c933c00afef4c26bec91ec7b1494ff | johnsbuck/MapGeneration | /Utilities/norm.py | 1,596 | 4.34375 | 4 | """N-Dimensional Norm
Defines the norm of 2 points in N dimensional space with different norms.
"""
import numpy as np
def norm(a, pow=2):
""" Lp Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,). Defines a point in 2-D space.
pow (float): The norm used for distance (Default: 2)
Returns:
(float) The distance between point a and point b with Lp Norm.
"""
return np.float_power(np.sum([np.float_power(np.abs(a[i]), pow) for i in range(len(a))]), 1./pow)
def manhattan(a):
"""Manhattan Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L1 norm.
"""
return norm(a, pow=1)
def euclidean(a):
"""Euclidean Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L2 norm.
"""
return norm(a, pow=2)
def minkowski(a):
"""Minkowski Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L3 norm.
"""
return norm(a, pow=3)
def chebyshev(a):
"""Chebyshev Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space.
Returns:
The distance between points a and b with L-Infinity norm.
"""
return np.max([np.abs(a[i]) for i in range(len(a))])
|
d6b657d761425a208e55bfc46ba19a29beb1f581 | zoleikha-mousavipak/zChallengeCodes | /Functionals/fib2.py | 180 | 3.890625 | 4 | def zfib(n):
if n <= 1:
return n
return zfib(n-1)+zfib(n-2)
if __name__ == "__main__":
inp = int(input("N: "))
for i in range(inp):
print(zfib(i)) |
f7f8c27059bf8b480fad7f7fdf1f1d9fde54f7b6 | zoleikha-mousavipak/zChallengeCodes | /Multiprocessing/multiprocessing_shareMemory.py | 670 | 3.765625 | 4 | import multiprocessing
def print_records(records):
for record in records:
print("Name: {0}\nScore: {1}\n".format(record[0], record[1]))
def insert_record(record, records):
records.append(record)
print("New Record Added!\n")
if __name__ == "__main__":
with multiprocessing.Manager() as manager:
records = manager.list([('Adam', 10), ('Bab', 20), ('Zoli', 100)])
new_record = ('Lusi', 50)
p1 = multiprocessing.Process(target=insert_record, args=(new_record, records))
p2 = multiprocessing.Process(target=print_records, args=(records,))
p1.start()
p1.join()
p2.start()
p2.join()
|
e9b6b4b2513c832213ef99b37cf7cd2109ff520b | ggjj321/leetcode-heap-practice | /K-Closest-Points-to-Origin-q973.py | 1,176 | 3.5 | 4 | import heapq
class Solution(object):
def kClosest(self, points, k):
"""
:type points: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def calcu(x,y):
return x ** 2 + y ** 2
heap = []
ans = []
for point in points[:k]:
distance = calcu(point[0], point[1])
heapq.heappush(heap,(distance, point[0],point[1]))
for point in points[k:]:
distance = calcu(point[0], point[1])
heapq.heappush(heap,(distance, point[0],point[1]))
#heap = heap[:k]
#print(heap)
for _ in range(k):
vector = heapq.heappop(heap)
ans.append([ vector[1], vector[2] ])
return ans
#49.06% 28.60%
class Solution(object):
def kClosest(self, points, k):
"""
:type points: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def calcu(point):
return point[0] ** 2 + point[1] ** 2
return sorted(points , key = calcu)[:k]
#built in sort 98.75% 93.56% |
1040a092ef92aa80822e0cada2d5df026a95b1e2 | snahor/chicharron | /cracking-the-code-interview/02.06.py | 860 | 4.15625 | 4 | from linked_list import Node
def reverse(head):
'''
>>> head = Node(1)
>>> reverse(head)
1
>>> head = Node(1, Node(2, Node(3)))
>>> reverse(head)
3 -> 2 -> 1
>>> reverse(reverse(head))
1 -> 2 -> 3
'''
new_head = None
curr = head
while curr:
new_head = Node(curr.value, new_head)
curr = curr.next
return new_head
def is_palindrome(head):
'''
>>> is_palindrome(Node(1))
True
>>> is_palindrome(Node(1, Node(2, Node(3))))
False
>>> is_palindrome(Node(1, Node(2, Node(3, Node(2, Node(1))))))
True
'''
new_head = reverse(head)
while head:
if head.value != new_head.value:
return False
head = head.next
new_head = new_head.next
return True
if __name__ == '__main__':
import doctest
doctest.testmod()
|
d8d8e2c4775e02977eb21ee60d28ec4fb123982e | Manmohit10/data-analysis-with-python-summer-2021 | /part01-e04_multiplication_table/src/multiplication_table.py | 200 | 3.765625 | 4 | #!/usr/bin/env python3
def main():
for n in range(10):
for m in range(10):
print('{:>4}'.format((n+1)*(m+1)),end="")
print("")
if __name__ == "__main__":
main()
|
81a1ab2f702bd56d5379540bee0e14044661a958 | Manmohit10/data-analysis-with-python-summer-2021 | /part01-e07_areas_of_shapes/src/areas_of_shapes.py | 864 | 4.21875 | 4 | #!/usr/bin/env python3
import math
def main():
while True:
shape=input("Choose a shape (triangle, rectangle, circle):")
shape=str(shape)
if shape=="":
break
elif shape=='triangle':
base=float(input('Give base of the triangle:'))
height=float(input('Give height of the triangle:'))
print(f"The area is {base*height*0.5}")
elif shape=='rectangle':
base=float(input('Give width of the rectangle:'))
height=float(input('Give height of the rectangle:'))
print(f"The area is {base*height}")
elif shape=='circle':
radius=float(input('Give radius of the circle:'))
print(f"The area is {math.pi*(radius**2)}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
|
37e2ca6c89b45416dda7e6c747d8b044bb03e961 | Manmohit10/data-analysis-with-python-summer-2021 | /part03-e11_to_grayscale/src/to_grayscale.py | 892 | 3.6875 | 4 | #!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
def to_grayscale(image):
"""avg=np.array([0.2126,0.7152,0.0722 ]).reshape(1,3)
new=image*avg
new=new.sum(axis=2)"""
avg=[0.2126,0.7152,0.0722]
new=np.sum(image*avg, axis=2)
return new
def to_red(image):
m=[1,0,0]
new=image*m
return new
def to_green(image):
m=[0,1,0]
new=image*m
return new
def to_blue(image):
m=[0,0,1]
new=image*m
return new
def main():
painting=plt.imread("src/painting.png")
plt.subplot(3,1,1)
red=to_red(painting)
plt.imshow(red)
plt.subplot(3,1,2)
green=to_green(painting)
plt.imshow(green)
plt.subplot(3,1,3)
red=to_blue(painting)
plt.imshow(red)
plt.show()
new = to_grayscale(painting)
plt.gray()
plt.imshow(new)
plt.show()
if __name__ == "__main__":
main()
|
6a96a1e2cd5b6a185ee7a6f53f3e5b52a14c1d9e | Manmohit10/data-analysis-with-python-summer-2021 | /part02-e01_integers_in_brackets/src/integers_in_brackets.py | 287 | 3.875 | 4 | #!/usr/bin/env python3
import re
def integers_in_brackets(s):
result=re.findall(r'\[\s*([+-]?\d*)\s*\]', s)
return list(map(int,result))
def main():
s1="afd [128+] [47 ] [a34] [ +-43 ]tt [+12]xxx"
print(integers_in_brackets(s1))
if __name__ == "__main__":
main()
|
0c810db86362129156458844b2b9a52bc4ad4ddf | Manmohit10/data-analysis-with-python-summer-2021 | /part02-e10_extract_numbers/src/extract_numbers.py | 415 | 3.875 | 4 | #!/usr/bin/env python3
def extract_numbers(s):
word = s.split()
List=[]
for l in word:
try:
List.append(int(l))
except ValueError:
try:
List.append(float(l))
except ValueError:
continue
return List
def main():
print(extract_numbers("abd 123 1.2 test 13.2 -1"))
if __name__ == "__main__":
main()
|
e1fab846ea96a6245113afd7a963f59ad3b6fc13 | Bigoz005/Python | /Fib.py | 225 | 3.78125 | 4 | def fib(n):
if n == 1:
return 0
if n == 2:
return 1
if n == 3:
return 1
else:
w = fib(n - 1) + fib(n - 2)
return w
print(fib(8))
# 0 1 1 2 3 5 8 13 21
|
6e820c26645987a220a3953b3d0a234b3a54b41c | nizhan26/leetcode_python | /17. Letter Combinations of a Phone Number.py | 911 | 4.03125 | 4 | '''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
'''
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
self.dict = {'1': "", "2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs","8":"tuv","9":"wxyz","10":" "}
if not digits:
return []
#at least one empty element in final
final = ['']
for digit in digits:
curr = self.dict[digits]
new = []
for i in final:
for j in curr:
new.append(i+j)
final = new
return final
|
36ceba8ac7c9a36f5c785bff1e783bddc048643d | nizhan26/leetcode_python | /24. Swap Nodes in Pairs.py | 1,004 | 4.03125 | 4 | '''
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
dummy = p = ListNode(0)
dummy.next = head
first = head
second = first.next
while first and second:
first.next = second.next
second.next = first
p.next = second
p = first
first = first.next
if not first:
break
second = first.next
return dummy.next
|
44ab850db10f462c00deaeded7766d8a75e5df73 | janagterhuis/Zaagcalculator | /dropdown.py | 439 | 3.65625 | 4 | from tkinter import *
root = Tk()
root.title('Zaagcalculator')
# Drop Down Boxes
def show():
myLabel=Label(root, text=clicked.get()).pack()
options = [
"Multiplex",
"MDF",
"Spaanplaat",
"Plexiglas"
]
clicked = StringVar()
clicked.set(options[0])
drop = OptionMenu(root, clicked, *options)
drop.pack()
myButton = Button(root, text="Show Selection", command=show).pack()
root.mainloop() |
09119efc6094cd992e23ad5c81b041806cf0dcca | rcarroll/DPW | /Rodriguez_Julian_Madlib/main.py | 2,061 | 3.90625 | 4 |
#First Prompt
print "Well hello hail and harty traveler, Who may I ask your name?"
NAME= raw_input(" Full Name?:")
print "Ahhh so your name is "+NAME+ " ....I see."
#Second Prompt
CLASS= raw_input(" What Class are you?: _")
print "Ohh so you are a mighty, "+CLASS+", Very interesting..."
#Third Prompt
HOME= raw_input("Where do you hail from?:")
print "I see so you come from the land of "+HOME+", I hear the weather is nice around this time of year."
#Stat Prompt's
print "Tell me more about yourself!"
STR= raw_input("What is your strength value?")
DEX= raw_input("What is your dexterity value?")
LUK= raw_input("How much of a wizard are you?(0-3!)")
#Stats Print, Character info plaved, and Beast array
print "I see, I see... So you have "+STR+" points of STR, "+DEX+" points of DEX and "+LUK+" points LUK."
CharacterInfo= {'Name':NAME, 'Class':CLASS, 'Home':HOME}
BEASTS= ["Dragon", "Ogre", "Litch", "Hell Hound"]
#Start The Quest
print "And so your adventure begins, your name is "+CharacterInfo['Name']+" the mighty "+CharacterInfo['Class']+" and you hail from the land of "+CharacterInfo['Home']+"."
#Loop to determine that luck stat is within a good value and to store it.
for i in range(0, int(LUK)):
if LUK > 4:
LUK == 4
else:
LUK == LUK
BEAST=BEASTS[i]
#This prints out what beast you will be facing
print "Your adventure begins wile you make your way to an old dungeon were you face a mighty "+BEAST+"!"
#Variable that will hold your "Skill"
SKILL= raw_input ("What Skill do you wish to use?")
#Function that will determine the power of your attack
def MonsterDefence(a, b, c):
DPS = (a / b) * c
print "You inflict "+str(DPS)+" points of damage!"
if DPS <= 9999:
print("The "+BEAST+" Has proven more of a challenge than expected, you decide to retreat and return another day.")
else:
print("Congratulations you have slain the "+BEAST+" and you return with a bounty of great spoils!")
#This places the values into the function.
MonsterDefence(int(STR), int(DEX), int(LUK))
|
758367a38be51f3900fe63887c0eaa03a5ae5fa9 | sayalighaisas/datastructures-algos | /palindrome.py | 234 | 4.09375 | 4 | def is_palindrome(string):
rev_string=string[::-1]
if string==rev_string:
return True
else:
return False
if __name__=="__main__":
str="radarrr"
if is_palindrome(str):
print("Is palindrome")
else:
print("Not palindrome")
|
4b37c423cd1c2c186689fb052204429a9452f9c1 | Davecupp/Pong | /Pong1.py | 5,377 | 3.671875 | 4 | # Made it to 17:10 in tutorial
# Link: https://youtu.be/XGf2GcyHPhc
import turtle
import tkinter as tk
import winsound
# Pulling splash page on main file, but then exiting. Can not get it to exit.
# Test turtle code. Turtle starts near center and goes as far as you put. 100 not far. Runs before pong game.
# turtle.speed(1) - Dictates speed.
# turtle.forward(500) - Dictates distance.
# for i in range(10): or loop range() dictates how long it lasts.
# turtle.speed(10-i) Goes fast then slow. i begins as 1. 1-10=9. Unless range is greater than 10. 0 is fastest.
# turtle.forward(50+20*i) This is the motion. (50+20*(i=1)=70. 90 degree turn. 50+20(i=2)=90. 90 degree turn.
# turtle.right(90)
def game():
wm.clear()
turtle.hideturtle()
turtle.clear()
em = turtle.Screen()
em.title("Pong with Dave")
em.bgcolor("lightblue")
em.setup(width=900, height=600)
em.tracer(0)
# Score
score_a = 0
score_b = 0
# Paddle A
paddle_a = turtle.Turtle()
# .speed() gives whatever is attached to it a speed. 0 being fastest, 10-fast - 1-slowest.
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("black")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("black")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("black")
# Keeps the ball from leaving a white trail. As in pen up, does not write on screen.
ball.penup()
ball.goto(0, 0)
ball.dx = .25
ball.dy = -.25
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color("black")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player_A: 0 Player_B: 0", align="center", font=("Courier", 24, "bold"))
# Function ~~~~~~~~~
# Paddle a
def paddle_a_up():
y = paddle_a.ycor()
y += 50
paddle_a.sety(y)
if paddle_a.ycor() > 250:
paddle_a.sety(250)
def paddle_a_down():
y = paddle_a.ycor()
y -= 50
paddle_a.sety(y)
if paddle_a.ycor() < -250:
paddle_a.sety(-250)
# Paddle b
def paddle_b_up():
y = paddle_b.ycor()
y += 50
paddle_b.sety(y)
if paddle_b.ycor() > 250:
paddle_b.sety(250)
def paddle_b_down():
y = paddle_b.ycor()
y -= 50
paddle_b.sety(y)
if paddle_b.ycor() < -250:
paddle_b.sety(-250)
# Keyboard binding
em.listen()
em.onkeypress(paddle_a_up, "w")
em.onkeypress(paddle_a_down, "s")
em.onkeypress(paddle_b_up, "Up")
em.onkeypress(paddle_b_down, "Down")
# Main game loop.
while True:
em.update()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border checking
# Ball boarder check
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.write("Player_A: {} Player_B: {}".format(score_a, score_b), align="center", font=("Courier", 24, "bold"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.write("Player_A: {} Player_B: {}".format(score_a, score_b), align="center", font=("Courier", 24, "bold"))
# Paddle Boarder Check
# Paddle and Ball Collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() -40):
ball.setx(340)
ball.dx *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() -40):
ball.setx(-340)
ball.dx *= -1
winsound.PlaySound("bounce.wav", winsound.SND_ASYNC)
wm = turtle.Screen()
wm.title("Pong with Dave")
wm.bgcolor("lightblue")
wm.setup(width=900, height=600)
wm.tracer(0)
turtle.ht()
turtle.penup()
turtle.goto(0, 100)
turtle.color("black")
turtle.write("Welcome to Pong with Dave!", move=False, align="center", font=("Times New Roman", 40, "bold"))
turtle.penup()
turtle.goto(0, -110)
turtle.color("black")
turtle.write("Instructions:", align="center", font=("Courier", 24, "bold"))
turtle.goto(0, -150)
turtle.color("black")
turtle.write("Player_A up = w, down = s", align="center", font=("Courier", 24, "normal"))
turtle.goto(0, -190)
turtle.color("black")
turtle.write("Player_B up = up, down = down", align="center", font=("Courier", 24, "normal"))
canvas = wm.getcanvas()
button = tk.Button(canvas.master, text="Click to begin!", command=game)
canvas.create_window(0, 0, window=button)
turtle.mainloop() |
a193a1b776334839238436d42a90dee05541e558 | flyxuxiaobai/AID2011 | /exercise02.py | 420 | 3.6875 | 4 | from threading import Thread, Lock
lock1 = Lock()
lock2 = Lock()
l = []
def value1():
for i in range(65, 91):
lock1.acquire()
print(chr(i))
lock2.release()
def value2():
for i in range(1, 53, 2):
lock2.acquire()
print(i)
print(i+1)
lock1.release()
t1 = Thread(target=value1)
t2 = Thread(target=value2)
lock1.acquire()
t1.start()
t2.start()
print(l)
|
42a2bdcd7c5f50a2889f7f12fc5e31377e19c036 | jakubczaplicki/projecteuler | /problem081.py | 1,413 | 3.625 | 4 | #!/usr/bin/env python
# pylint: disable=invalid-name
"""
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right,
by only moving to the right and down, is indicated in bold red and is equal to 2427.
131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."),
a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down.
"""
class Problem81():
"""
@class Solution for Problem 81
@brief
"""
def __init__(self):
self.result = None
def compute(self):
data = []
ins = open( "p081_matrix.txt", "r" )
for i,line in enumerate(ins):
data.append( [int(x) for x in line.split(',')] )
ins.close()
for i,d in enumerate(data):
for j in xrange(len(d)):
if i == 0 and j > 0:
data[i][j] = data[i][j] + data[i][j-1]
elif j == 0 and i > 0:
data[i][j] = data[i][j] + data[i-1][j]
elif i > 0 and j > 0:
data[i][j] = min(data[i][j] + data[i][j-1], data[i][j] + data[i-1][j])
self.result = data[-1][-1]
if __name__ == '__main__':
problem = Problem81()
problem.compute()
print problem.result
|
96cd3f07a60f4b8aae3ee63dcd25030f411b0bc1 | jakubczaplicki/projecteuler | /problem020.py | 698 | 3.546875 | 4 | #!/usr/bin/env python
# pylint: disable=invalid-name
"""
https://projecteuler.net/problem=20
"""
import math
from problembaseclass import ProblemBaseClass
class Problem20(ProblemBaseClass):
"""
@class Solution for Problem 20
@brief
"""
def __init__(self, n):
self.result = None
self.n = n
def compute(self):
str = "%s" % self.n
n = 0
for s in str:
n = n + int(float(s))
self.result = n
if __name__ == '__main__':
problem = Problem20( math.factorial(10) )
problem.compute()
print problem.result #27
problem = Problem20( math.factorial(100) )
problem.compute()
print problem.result #648
|
a83c79efaf48554e1ad4e863de45e38ed8ffdafa | jakubczaplicki/projecteuler | /problembaseclass.py | 1,938 | 3.53125 | 4 | #!/usr/bin/env python
"""Base class for the Project Euler problems in Python"""
##@file
#@ingroup
#
# @brief
# Base class for the Project Euler problems in Python
#
#
# @version $$
# @details
#
# @b Description
# This module implements a base class, that can be used
# for all project eurler solutions.
#
# @b Usage
# Usage:
# Extend this class to implement a test
import math
import time
import sys
class ProblemBaseClass(object):
"""
@class
@brief
"""
def __init__(self):
self.result = None
def label(self):
self.label = "No label"
def setup(self):
"""setup method for all solutions
Override to:
- process options, etc.
"""
def initiate(self, *_args, **_kwargs):
"""initiate method for all solutions
Override to:
- load data
- initiate connections to Spark
"""
def compute(self, *_args, **_kwargs):
"""@method compute the solution
Override to:
- implement a solution for the given problem.
Must be implemented
"""
return None
def teardown(self):
"""@method teardown method for all solutions
Override to:
- tidy up
Must be implemented
"""
def isPrime(self, number):
"""Returns True is number is prime, False otherwise"""
# This algorithm checks if the given number can be divided by integers of the form 6k +/- 1
# see: http://en.wikipedia.org/wiki/Primality_test#Naive_methods
if number <= 3:
return number > 1
if number % 2 == 0 or number % 3 == 0:
return False
for i in range(5, int(number ** 0.5) + 1, 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
if __name__ == '__main__':
problem = problem1()
problem.compute()
print problem.result
|
70b8698f195d78d197bd89b6ccf9eebf4f824f50 | yunchan312/data-structure | /LinkedStack.py | 504 | 3.625 | 4 | class Node:
def __init__(self, element):
self.link = None
self.data = element
class LinkedStack:
def __init__(self):
self.top = None
def isEmpty(self):
return self.top == None
def push(self, e):
newNode = Node(e)
newNode.link = self.top
self.top = newNode
def pop(self):
if self.isEmpty():
print("Stack is empty")
return
e = self.top.data
self.top = self.top.link
return e |
c9db9a68499d75cb7f8acef452a0c5e45fa764d8 | qinacme/qinacme-interview | /lintcode/Python/PNov9_1.py | 679 | 3.71875 | 4 | #[-2,2,-3,4,-1,2,1,-5,3]
#greedy
def maxSubArray(nums):
if nums == None or len(nums)==0:
return 0
maxSum = nums[0]
curSum = maxSum
for i in nums[1:]:
if curSum<0:
curSum = i
else:
curSum = curSum+i
maxSum = max(maxSum, curSum)
return maxSum
#prefix sum
def maxSubArray2(nums):
if nums == None or len(nums)==0:
return 0
maxSum, minSum, curSum = nums[0], nums[0], nums[0]
for i in nums[1:]:
curSum += i
maxSum = max(maxSum, curSum-minSum)
minSum = min(minSum, curSum)
return maxSum
if __name__ == '__main__':
print(maxSubArray([-2,2,-3,4,-1,2,1,-5,3]))
|
1773b435b09579cef80f7850a2f9fb33d04c1200 | vdakinshin/learn1 | /infro.py | 219 | 3.921875 | 4 | user_info = {}
user_first_name = input('What is your first name?: ')
user_info['first_name'] = user_first_name
user_last_name = input('What is your last name?: ')
user_info['last_name'] = user_last_name
print(user_info) |
eb7afe093052c09e4b96b47b9a8176d2988d1d72 | Claudio9701/bingtiles | /bingtiles/bingtiles.py | 8,015 | 3.5 | 4 | import math
class TileSystem(object):
EARTH_RADIUS = 6378137
MIN_LATITUDE = -85.05112878
MAX_LATITUDE = 85.05112878
MIN_LONGITUDE = -180
MAX_LONGITUDE = 180
def clip(self, n, min_value, max_value):
"""
Clips a number to the specified minimum and maximum values.
Parameters
----------
n : int
The number to clip.
minValue : int
Minimum allowable value.
maxValue : int
Maximum allowable value.
Returns
-------
The clipped value.
"""
return min(max(n, min_value), max_value)
def map_size(self, level_of_detail):
"""
Determines the map width and height (in pixels) at a specified level of detail.
Parameters
----------
level_of_detail: Level of detail, from 1 (lowest detail) to 23 (highest detail).
Returns
-------
The map width and height in pixels.
"""
return 256 << level_of_detail
def ground_resolution(self, latitude, level_of_detail):
"""
Determines the ground resolution (in meters per pixel) at a specified latitude and level of detail.
Parameters
----------
latitude : float
Latitude (in degrees) at which to measure the ground resolution.
level_of_detail : int
Level of detail, from 1 (lowest detail) to 23 (highest detail).
Returns
-------
The ground resolution, in meters per pixel.
"""
latitude = self.clip(latitude, self.MIN_LATITUDE, self.MAX_LATITUDE)
return math.cos(latitude * math.pi / 180) * 2 * math.pi * self.EARTH_RADIUS / self.map_size(level_of_detail)
def map_scale(self, latitude, level_of_detail, screen_dpi):
"""
Determines the map scale at a specified latitude, level of detail, and screen resolution.
Parameters
----------
latitude : float
Latitude (in degrees) at which to measure the map scale.
level_of_detail : int
Level of detail, from 1 (lowest detail) to 23 (highest detail).
screen_dpi : int
Resolution of the screen, in dots per inch.
Returns
-------
The map scale, expressed as the denominator N of the ratio 1 : N.
"""
return self.ground_resolution(latitude, level_of_detail) * screen_dpi / 0.0254
def latlong_to_pixel_xy(self, latitude, longitude, level_of_detail):
"""
Converts a point from latitude/longitude WGS-84 coordinates (in degrees) into pixel XY coordinates at a specified level of detail.
Parameters
----------
latitude : float
Latitude of the point, in degrees.
longitude : float
Longitude of the point, in degrees.
level_of_detail : int
Level of detail, from 1 (lowest detail) to 23 (highest detail).
Returns
-------
pixel_x : int
Output parameter receiving the X coordinate in pixels.
pixel_y : int
Output parameter receiving the Y coordinate in pixels.
"""
latitude = self.clip(latitude, self.MIN_LATITUDE, self.MAX_LATITUDE)
longitude = self.clip(longitude, self.MIN_LONGITUDE, self.MAX_LONGITUDE)
x = (longitude + 180) / 360
sinLatitude = math.sin(latitude * math.pi / 180)
y = 0.5 - math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * math.pi)
map_size = self.map_size(level_of_detail)
pixel_x = self.clip(x * map_size + 0.5, 0, map_size - 1)
pixel_y = self.clip(y * map_size + 0.5, 0, map_size - 1)
return pixel_x, pixel_y
def pixel_xy_to_latlong(self, pixel_x, pixel_y, level_of_detail):
"""
Converts a pixel from pixel XY coordinates at a specified level of detail into latitude/longitude WGS-84 coordinates (in degrees).
Parameters
----------
pixel_x : int
X coordinate of the point, in pixels.
pixel_y : int
Y coordinates of the point, in pixels.
level_of_detail : Level of detail, from 1 (lowest detail) to 23 (highest detail).
Returns
-------
latitude : float
Output parameter receiving the latitude in degrees.
longitude: float
Output parameter receiving the longitude in degrees.
"""
map_size = self.map_size(level_of_detail)
x = (self.clip(pixel_x, 0, map_size - 1) / map_size) - 0.5;
y = 0.5 - (self.clip(pixel_y, 0, map_size - 1) / map_size)
latitude = 90 - 360 * math.atan(math.exp(-y * 2 * math.pi)) / math.pi
longitude = 360 * x
return latitude, longitude
def pixel_xy_to_tile_xy(self, pixel_x, pixel_y):
"""
Converts pixel XY coordinates into tile XY coordinates of the tile containing the specified pixel.
Parameters
----------
pixel_x : int
Pixel X coordinate.
pixel_y : int
Pixel Y coordinate.
Returns
-------
tile_x : int
Output parameter receiving the tile X coordinate.
tile_y : int
Output parameter receiving the tile Y coordinate.
"""
tile_x = pixel_x / 256
tile_y = pixel_y / 256
return tile_x, tile_y
def tile_xy_to_pixel_xy(self, tile_x, tile_y):
"""
Converts tile XY coordinates into pixel XY coordinates of the upper-left pixel of the specified tile.
Parameters
----------
tile_x: int
Tile X coordinate.
tile_y: int
Tile Y coordinate.
Returns
-------
pixel_x : int
Output parameter receiving the pixel X coordinate.
pixel_y : int
Output parameter receiving the pixel Y coordinate.
"""
pixel_x = tile_x * 256
pixel_y = tile_y * 256
return pixel_x, pixel_y
def tile_xy_to_quadkey(self, tile_x, tile_y, level_of_detail):
"""
Converts tile XY coordinates into a QuadKey at a specified level of detail.
Parameters
----------
tile_x : int
Tile X coordinate.
tile_y : int
Tile Y coordinate.
level_of_detail : int
Level of detail, from 1 (lowest detail) to 23 (highest detail).
Returns
-------
A string containing the QuadKey.
"""
quadkey = ''
for i in range(level_of_detail, 0, -1):
digit = 0
mask = 1 << (i - 1)
if (tile_x & mask) != 0:
digit += 1
if (tile_y & mask) != 0:
digit += 2
quadkey += str(digit)
return quadkey
def quadkey_to_tile_xy(self, quadkey):
"""
Converts a QuadKey into tile XY coordinates.
Parameters
----------
quadKey : str
QuadKey of the tile.
Returns
-------
tile_x : int
Output parameter receiving the tile X coordinate.
tile_y : int
Output parameter receiving the tile Y coordinate.
level_of_detail : int
Output parameter receiving the level of detail.
"""
tile_x = tile_y = 0
level_of_detail = len(quadkey)
for i in range(level_of_detail, 0, -1):
mask = 1 << (i - 1)
if quadkey[level_of_detail - i] == '0':
pass
elif quadkey[level_of_detail - i] == '1':
tile_x |= mask
elif quadkey[level_of_detail - i] == '2':
tile_y |= mask
elif quadkey[level_of_detail - i] == '3':
tile_x |= mask
tile_y |= mask
else:
raise ValueError('Invalid QuadKey digit sequence.')
return tile_x, tile_y, level_of_detail
|
719484e3da2a99162a834431824ac42c356d7fad | SfietKonstantin/qfb | /tools/qfbtools.py | 830 | 3.546875 | 4 | def lowerCamelCase(name):
return name[0].lower() + name[1:]
def isPointer(name):
if name.strip()[-1:] == "*":
return True
else:
return False
def split(name):
return name.split("_")
def camelCase(splitted):
newSplitted = []
for splittedWord in splitted:
splittedWord = splittedWord.lower()
splittedWord = splittedWord[0].upper() + splittedWord[1:]
newSplitted.append(splittedWord)
camelCase = "".join(newSplitted)
camelCase = camelCase[0].lower() + camelCase[1:]
return camelCase
def staticKey(splitted, className):
newSplitted = []
newSplitted.append(className.upper())
for splittedWord in splitted:
newSplitted.append(splittedWord.upper())
newSplitted.append("KEY")
staticKey = "_".join(newSplitted)
return staticKey
|
87b47edb3ac4c944e7498021311d29a683de4873 | mashanivas/python | /scripts/fl.py | 208 | 4.28125 | 4 | #!/usr/bin/python
#Function for powering
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(2, 3))
|
5cfe897e64a23dea12802535001062a6e4e0575a | Apthox/MindPuzzle | /Graphics/Board.py | 2,396 | 3.8125 | 4 | from Graphics.Graphics import *
class Board:
__x_pixels = -1
__y_pixels = -1
__vertical_boxes = -1
__horizontal_boxes = -1
__matrix__ = None
__win__ = None
def __construct_board(self):
self.__win__ = GraphWin('board', self.__x_pixels, self.__y_pixels)
self.__win__.setCoords(0.0, 0.0,
self.__horizontal_boxes,
self.__vertical_boxes)
self.__win__.setBackground("yellow")
self.__matrix__ = [[Rectangle for col in range(self.__vertical_boxes)]
for row in range(self.__horizontal_boxes)]
print(self.__matrix__)
for x in range(self.__horizontal_boxes):
for y in range(self.__vertical_boxes):
self.__win__.plotPixel(x * (self.__x_pixels / self.__horizontal_boxes),
y * (self.__y_pixels / self.__vertical_boxes),
"purple")
for x in range(self.__horizontal_boxes + 1):
for y in range(self.__vertical_boxes + 1):
self.add_rectangle(x, y, "green")
self.__win__.update()
self.__matrix__[2][2].setFill("red")
self.__win__.update_idletasks()
def add_rectangle(self, x, y, color):
self.__win__.update()
square = Rectangle(Point(x - 1, y - 1), Point(x, y))
square.draw(self.__win__)
square.setFill(color)
self.__matrix__[x-1][y-1] = square
def update_board(self):
self.__win__.update()
def __init__(self, x_pixels, y_pixels, horizontal_boxes, vertical_boxes):
self.__x_pixels = x_pixels
self.__y_pixels = y_pixels
self.__horizontal_boxes = horizontal_boxes
self.__vertical_boxes = vertical_boxes
print("Pixels: x:" + str(x_pixels) + " y:" + str(y_pixels))
print("Boxes: x:" + str(horizontal_boxes) + " y:" + str(vertical_boxes))
if x_pixels < 10:
print("Must have at least 10 pixels!")
return
if y_pixels < 10:
print("Must have at least 10 pixels!")
return
if horizontal_boxes < 2:
print("Must have at least 2 boxes!")
return
if x_pixels < 2:
print("Must have at least 2 boxes!")
return
self.__construct_board()
|
620123a59f661877712972c9d9733b690d5ce3e4 | skphy/align | /align/_utils.py | 2,939 | 3.828125 | 4 | import numpy as np
from itertools import izip
def random_q():
"""
uniform random rotation in angle axis formulation
input: 3 uniformly distributed random numbers
uses the algorithm given in
K. Shoemake, Uniform random rotations, Graphics Gems III, pages 124-132. Academic, New York, 1992.
This first generates a random rotation in quaternion representation. We should substitute this by
a direct angle axis generation, but be careful: the angle of rotation in angle axis representation
is NOT uniformly distributed
"""
from numpy import sqrt, sin, cos, pi
u = np.random.uniform(0,1,[3])
q = np.zeros(4, np.float64)
q[0] = sqrt(1.-u[0]) * sin(2.*pi*u[1])
q[1] = sqrt(1.-u[0]) * cos(2.*pi*u[1])
q[2] = sqrt(u[0]) * sin(2.*pi*u[2])
q[3] = sqrt(u[0]) * cos(2.*pi*u[2])
return q
def q2mx( qin ):
"""quaternion to rotation matrix"""
Q = qin / np.linalg.norm(qin)
RMX = np.zeros([3,3], np.float64)
Q2Q3 = Q[1]*Q[2];
Q1Q4 = Q[0]*Q[3];
Q2Q4 = Q[1]*Q[3];
Q1Q3 = Q[0]*Q[2];
Q3Q4 = Q[2]*Q[3];
Q1Q2 = Q[0]*Q[1];
RMX[0,0] = 2.*(0.5 - Q[2]*Q[2] - Q[3]*Q[3]);
RMX[1,1] = 2.*(0.5 - Q[1]*Q[1] - Q[3]*Q[3]);
RMX[2,2] = 2.*(0.5 - Q[1]*Q[1] - Q[2]*Q[2]);
RMX[0,1] = 2.*(Q2Q3 - Q1Q4);
RMX[1,0] = 2.*(Q2Q3 + Q1Q4);
RMX[0,2] = 2.*(Q2Q4 + Q1Q3);
RMX[2,0] = 2.*(Q2Q4 - Q1Q3);
RMX[1,2] = 2.*(Q3Q4 - Q1Q2);
RMX[2,1] = 2.*(Q3Q4 + Q1Q2);
return RMX
def random_mx():
return q2mx(random_q())
def sum_internal_distances(x):
"""return the sqrt of the sum of the squared internal distances
this can be used to check that the relative positions of the atoms are unchanged
"""
s = ((x[:,np.newaxis] - x[np.newaxis,:])**2).sum()
return np.sqrt(s)
def random_configuration(n):
return np.random.uniform(-1, 1, n)
def random_translation():
return np.random.uniform(-1,1,3)
def random_rotation():
return q2mx(random_q())
def random_permutation(natoms):
perm = range(natoms)
np.random.shuffle(perm)
return perm
def random_permutation_permlist(permlist, natoms):
perm = np.zeros(natoms, np.integer)
for atomlist in permlist:
a = np.copy(atomlist)
np.random.shuffle(a)
for iold, inew in izip(atomlist, a):
perm[iold] = inew
# print perm
return perm
def translate(X, d):
Xtmp = X.reshape([-1,3])
Xtmp += d
def rotate(X, mx):
Xtmp = X.reshape([-1,3])
Xtmp = np.dot(mx, Xtmp.transpose()).transpose()
X[:] = Xtmp.reshape(X.shape)
def permute(X, perm):
a = X.reshape(-1,3)[perm].flatten()
# now modify the passed object, X
X[:] = a[:]
def invert(X):
X[:] = -X
def translate_randomly(X):
translate(X, random_translation())
def rotate_randomly(X):
rotate(X, random_rotation())
def permute_randomly(X, permlist, natoms):
permute(X, random_permutation_permlist(permlist, natoms))
|
f53e3d04b180ef7a9c362f00f5b1c8172fcacb38 | bazhenov23/GB_Home-Work | /Lesson3/Task 3.2.py | 619 | 3.921875 | 4 | def info():
name = input("Введите имя ")
surname = input("Введите фамилию ")
year = int(input("Введите год рождения "))
city = input("Введите город ")
email = input("Введите адрес электронной почты ")
telephone = input("Введите номер телефона ")
info_user = (
f"Пользователь {name} {surname} Год рождения {year} Город {city} Электорнный адрес {email} Телефон {telephone}")
return info_user
user = info()
print(user)
|
bfc5e5ed666b7f18d2a7d152b153c08e373e0b62 | bazhenov23/GB_Home-Work | /Lesson3/Task 3.3.py | 345 | 4 | 4 | def my_func():
x = int(input("Первое число "))
y = int(input("Второе число "))
z = int(input("Третье число "))
if x >= z and y >= z:
result = x + y
elif y < x < z:
result = x + z
else:
result = y + z
return result
user_result = my_func()
print(user_result)
|
05238eaab83d31d097428f7b9c85bc0f947d805a | bazhenov23/GB_Home-Work | /Lesson1/Task 3.py | 144 | 3.671875 | 4 | n = int(input("Введите число от 0 до 9 "))
sum_n: int = (n + int(str(n) + str(n)) + int(str(n) + str(n) + str(n)))
print(sum_n)
|
d1c843f440e1d929e2be5f859fc003db18b92c8b | bazhenov23/GB_Home-Work | /Lesson1/Task 5.py | 678 | 4 | 4 | profit = float(input("Введите выручку компании "))
cost = float(input("Введите издержки компании "))
if profit > cost:
print(f"Компания работает с прибылью. Рентабельность выручки составила {profit / cost:.1f}%")
workers = int(input("Введите количество сотрудников "))
print(f"Прибыль в расчете на одного сторудника сотавила {profit / workers:.1f}")
elif profit == cost:
print("Компания работает в ноль")
else:
print("Компания работает в минус")
|
cc6c58e549f132112a68038f4d71c8c582e63552 | moon-light-night/learn_python | /project.py | 577 | 4.3125 | 4 | #Дэбильный калькулятор
what = input ('Что делаем? (+, -, *, /)')
a = float(input ('Введи первое число: '))
b = float(input ('Введи второе число: '))
if what == '+':
c = a + b
print('Результат:' + str(c))
elif what == '-':
c = a - b
print('Результат:' + str(c))
elif what == '*':
c = a * b
print('Результат:' + str(c))
elif what == '/':
c = a / b
print('Результат:' + str(c))
else:
print('Выбрана неверная операция')
|
ea590d448e1961a26b862f5d0ec12bacb376d60d | Mingqianluo/A1805A | /A1807/05day/01-实例属性.py | 304 | 3.6875 | 4 | class Dog():
print('哈哈哈哈')
count = 10#类属性
def __init__(self,name):
self.name = name #实例属性
self.__age = 10
def getAge(self):
return self.__age
tom = Dog('Tom')
print(tom.name)
print(tom.getAge())
print(Dog.count)#通过类访问类方法
|
c11cfe2fdb52e858548532dd4a5b14474ab92d12 | Mingqianluo/A1805A | /A1807/02day/lx-gess.py | 404 | 3.640625 | 4 | import random
class Guess:
def guess(self):
a = random.randint(0,101)
while True:
u = int(input('请输入数字'))
if u > a:
print('猜大了')
elif u < a:
print('猜小了')
else:
print('猜对了')
break
g = Guess()
g.guess()
|
71f0a8c47e3a62c795d535570b6f3403d771667f | Mingqianluo/A1805A | /A1807/11day/04-..py | 129 | 4.03125 | 4 | list = [1,2,3,4,5,4,4]
list1 = []
for i in list:
if i not in list1:
list1.append(i)
print(list1)
#print(list(set()))
|
bf4e29367e523ef7306acc2620e1d253bc4c95b9 | kevinismantara/Stock-Predictor | /analyze_stocks.py | 5,150 | 3.515625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data = pd.read_csv('stock-data.csv', parse_dates=[0])
indexed = data.set_index(['Unnamed: 0'])
# Company Stocks
apple = pd.DataFrame(data=indexed['AAPL'])
amazon = pd.DataFrame(data=indexed['AMZN'])
google = pd.DataFrame(data=indexed['GOOGL'])
microsoft = pd.DataFrame(data=indexed['MSFT'])
# Forecast Data
forecast = 30 # 30 days ahead
apple['AAPL forecasted'] = apple['AAPL'].shift(-forecast)
amazon['AMZN forecasted'] = amazon['AMZN'].shift(-forecast)
google['GOOGL forecasted'] = indexed['GOOGL'].shift(-forecast)
microsoft['MSFT forecasted'] = microsoft['MSFT'].shift(-forecast)
# Train, Test, Predict Apple Stock Prices
X_apple = np.array(apple.drop(['AAPL forecasted'], 1))
X_apple = preprocessing.scale(X_apple)
X_apple_lately = X_apple[-forecast:]
X_apple = X_apple[:-forecast]
apple.dropna(inplace=True)
y_apple = np.array(apple['AAPL forecasted'])
X_train, X_test, y_train, y_test = train_test_split(X_apple, y_apple)
clf = LinearRegression()
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
print("Accuracy: ", accuracy)
forecastAppleStocks = clf.predict(X_apple_lately)
print("Forecast of apple's stocks: ", forecastAppleStocks)
# Train, Test, Predict Amazon Stock Prices
X_amazon = np.array(amazon.drop(['AMZN forecasted'], 1))
X_amazon = preprocessing.scale(X_amazon)
X_amazon_lately = X_amazon[-forecast:]
X_amazon = X_amazon[:-forecast]
amazon.dropna(inplace=True)
y_amazon = np.array(amazon['AMZN forecasted'])
X_train, X_test, y_train, y_test = train_test_split(X_amazon, y_amazon)
clf = LinearRegression()
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
print("Accuracy: ", accuracy)
forecastAmazonStocks = clf.predict(X_amazon_lately)
print("Forecast of amazon's stocks: ", forecastAmazonStocks)
# Train, Test, Predict Google Stock Prices
X_google = np.array(google.drop(['GOOGL forecasted'], 1))
X_google = preprocessing.scale(X_google)
X_google_lately = X_google[-forecast:]
X_google = X_google[:-forecast]
google.dropna(inplace=True)
y_google = np.array(google['GOOGL forecasted'])
X_train, X_test, y_train, y_test = train_test_split(X_google, y_google)
clf = LinearRegression()
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
print("Accuracy: ", accuracy)
forecastGoogleStocks = clf.predict(X_google_lately)
print("Forecast of google's stocks: ", forecastGoogleStocks)
# Train, Test, Predict Microsoft Stock Prices
X_microsoft = np.array(microsoft.drop(['MSFT forecasted'], 1))
X_microsoft = preprocessing.scale(X_microsoft)
X_microsoft_lately = X_microsoft[-forecast:]
X_microsoft = X_microsoft[:-forecast]
microsoft.dropna(inplace=True)
y_microsoft = np.array(microsoft['MSFT forecasted'])
X_train, X_test, y_train, y_test = train_test_split(X_microsoft, y_microsoft)
clf = LinearRegression()
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
print("Accuracy: ", accuracy)
forecastMicrosoftStocks = clf.predict(X_microsoft_lately)
print("Forecast of microsoft's stocks: ", forecastMicrosoftStocks)
# Create dates for forecasted stocks 30 days ahead
today = datetime.date.today()
tomorrow = (today + datetime.timedelta(days=1)).strftime('%Y-%m-%d')
dates = pd.date_range(tomorrow, periods=30, freq='D')
# Create dataframe for predicted apple stocks
applePredict = pd.DataFrame(data=forecastAppleStocks, index=dates)
applePredict.columns = ['AAPL Forecasted']
# Create dataframe for predicted amazon stocks
amazonPredict = pd.DataFrame(data=forecastAmazonStocks, index=dates)
amazonPredict.columns = ['AMZN Forecasted']
# Create dataframe for predicted google stocks
googlePredict = pd.DataFrame(data=forecastGoogleStocks, index=dates)
googlePredict.columns = ['GOOGL Forecasted']
# Create dataframe for predicted microsoft stocks
microsoftPredict = pd.DataFrame(data=forecastMicrosoftStocks, index=dates)
microsoftPredict.columns = ['MSFT Forecasted']
# Graph current and forecasted Apple stock
plt.plot(indexed.index, indexed['AAPL'], color="blue")
plt.plot(applePredict.index, applePredict['AAPL Forecasted'], color="red")
plt.xlabel('Date')
plt.ylabel('Closing Price ($)')
plt.legend()
# Graph current and forecasted Amazon stock
plt.plot(indexed.index, indexed['AMZN'], color="green")
plt.plot(amazonPredict.index, amazonPredict['AMZN Forecasted'], color="yellow")
plt.xlabel('Date')
plt.ylabel('Closing Price ($)')
plt.legend()
# Graph current and forecasted Google stock
plt.plot(indexed.index, indexed['GOOGL'], color="brown")
plt.plot(googlePredict.index, googlePredict['GOOGL Forecasted'], color="pink")
plt.xlabel('Date')
plt.ylabel('Closing Price ($)')
plt.legend()
# Graph current and forecasted Microsoft stock
plt.plot(indexed.index, indexed['MSFT'], color="orange")
plt.plot(microsoftPredict.index, microsoftPredict['MSFT Forecasted'], color="black")
plt.xlabel('Date')
plt.ylabel('Closing Price ($)')
plt.title('Stock Market Price')
plt.legend()
plt.savefig('stock-graph.png')
plt.show()
|
9de11c63bb0f64ac791be24c045d9ca4827d41f1 | Zorha/my-first-blog | /python_intro.py | 157 | 3.671875 | 4 | def hi (name):
if name == 'zoro':
print('hello my dear')
elif name == 'zola':
print('hello zola roronoa !! ')
else:
print('hi miss! ')
hi ("zola") |
3e3cf577d2b43618bbdbff52ca2ef06842964d64 | zjzjgxw/leetcode | /py/zigzagLevelOrder.py | 725 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
if not root:
return []
ans, level = [], [root]
curDepth = 1
while level:
if curDepth % 2 == 0:
ans.append([node.val for node in level[::-1]])
else:
ans.append([node.val for node in level])
temp = []
for node in level:
temp.extend([node.left, node.right])
level = [leaf for leaf in temp if leaf]
curDepth += 1
return ans
|
346eb96f30b1e2af8210564c1b40456c50268ff6 | zjzjgxw/leetcode | /py/largestValues.py | 977 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
ret, level = [], [root]
while level:
maxNum = level[0].val
for node in level:
if maxNum < node.val:
maxNum = node.val
ret.append(maxNum)
level = [kid for n in level for kid in (n.left, n.right) if kid]
return ret
#discuss看到的简化版
def findValueMostElement(self, root):
maxes = []
row = [root]
while any(row):
maxes.append(max(node.val for node in row))
row = [kid for node in row for kid in (node.left, node.right) if kid]
return maxes
|
835e1ffe42ba987d0b0ed32f1ce215a4e8462e61 | zjzjgxw/leetcode | /py/swapPairs.py | 761 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
newHead = head.next
pre = ListNode(None)
pre.next = head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return newHead
sol = Solution()
L1 = ListNode(1)
L2 = ListNode(2)
L3 = ListNode(3)
L1.next = L2
L2.next = L3
sol.swapPairs(L1)
print('he')
|
89788d2a5a6109a880a4a4983a631d9674f517c6 | hackrole/leetcode_go | /avltree/avltree2.py | 2,261 | 3.71875 | 4 | # -*- coding: utf-8 -*-
class Node(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 0
class AVLTree(object):
def __init__(self):
self.root = None
def height(self, node):
if node is None:
return -1
return node.height
def update_height(self, node):
node.height = max(self.height(node.left), self.height(node.right)) + 1
def unbalance(self, node):
return abs(self.height(node.left) - self.height(node.height)) is 2
def right_rotate(self, node):
node_right = node
node = node.left
node_right.left = node.right
node.right = node_right
self.update_height(node_right)
self.update_height(node)
return node
def left_rotate(self, node):
node_left = node
node = node.right
node_left.right = node.left
node.left = node_left
self.update_height(node_left)
self.update_height(node)
return node
def left_right_rotate(self, node):
node.left = self.left_rotate(node.left)
return self.right_rotate(node)
def right_left_rotate(self, node):
node.right = self.right_rotate(node.right)
return self.left_rotate(node)
def insert(self, key):
if self.root is None:
self.root = Node(key)
else:
self.root = self._insert(key, self.root)
def _insert(self, key, node):
if node is None:
node = node(key)
elif key < node.key:
node.left = self._insert(key, node.left)
if self.unbalance(node):
if key < node.left.key:
node = self.right_rotate(node)
else:
node = self.left_right_rotate(node)
elif key > node.key:
node.right = self._insert(key, node.right)
if self.unbalance(node):
if key < node.right.key:
if key < node.right.key:
node = self.right_left_rotate(node)
else:
node = self.left_rotate(node)
self.update_height(node)
return node
|
214e549b2c0032870788edb8532ff84d635909ae | sanjelarun/eip_python | /practice_programs/stacks/parenthesis_check_my_way.py | 569 | 3.6875 | 4 | def check_valid_parenthesis(exp):
s_cnt = m_cnt = l_cnt = 0
for each_brac in exp:
if s_cnt < 0 or m_cnt < 0 or l_cnt < 0:
return False
if each_brac == '(':
s_cnt += 1
elif each_brac == ")":
s_cnt -= 1
elif each_brac == "{":
m_cnt += 1
elif each_brac == "}":
m_cnt -= 1
elif each_brac == "[":
l_cnt += 1
else:
l_cnt -= 1
return True if s_cnt == m_cnt == l_cnt == 0 else False
print(check_valid_parenthesis("))(("))
|
9f52740f2da3b46278c7927b1f723b4064419472 | sanjelarun/eip_python | /practice_programs/stacks/RPN.py | 890 | 3.578125 | 4 | def RPN_evaluate(expression):
delimt = ","
operators = {'+': lambda x, y: x + y,
'-': lambda x, y: y - x,
'*': lambda x, y: x * y,
'/': lambda x, y: int(x / y)}
current_stack = []
cnt = 0
operator = ""
for token in expression.split(delimt):
if cnt == 2 and token in operators:
current_stack.append(operators[operator](int(current_stack.pop()), int(current_stack.pop())))
cnt = 1
operator = token
elif token in operators:
operator = token
else:
current_stack.append(token)
cnt += 1
print(current_stack)
# LAST CHECK
if cnt == 2:
current_stack.append(operators[operator](int(current_stack.pop()), int(current_stack.pop())))
return current_stack[0]
s = "/,3,1,*,7,+,12"
print(RPN_evaluate(s)) |
1508cfcdfc2e044d29c677e6587843d50bca6b34 | sanjelarun/eip_python | /practice_programs/arrays_1D/binary_add_cache_table.py | 1,284 | 3.609375 | 4 | ''' WAP which takee input two strings s and t of bits encoding binary numbers Bs and Bt, respectively
and returns a new string of bits represeting the number Bs + Bt '''
import time
def cache_table(a, b, c):
if a == '0' and b == '0' and c == '0':
return '0', '0'
elif a == '0' and b == '0' and c == '1':
return '1', '0'
elif a == '0' and b == '1' and c == '0':
return '1', '0'
elif a == '0' and b == '1' and c == '1':
return '0', '1'
elif a == '1' and b == '0' and c == '0':
return '1', '0'
elif a == '1' and b == '1' and c == '0':
return '0', '1'
elif a == '1' and b == '0' and c == '1':
return '0', '1'
else:
return '1', '1'
def binary_string_add(A, B):
# Making sure that both string have equal length
diff = abs(len(A) - len(B))
if len(A) < len(B):
for i in range(diff):
A = "0" + A
else:
for i in range(diff):
B = "0" + B
c = '0'
s = ""
i = len(A) - 1
while i >= 0:
tmp, c = cache_table(A[i], B[i], c)
s = tmp + s
i -= 1
if c == '1': s = '1' + s
return s
start_time = time.time()
print(binary_string_add('111', '11'))
print("--- %s seconds ---" % (time.time() - start_time)) |
aba50d2cd0d38f0b41aafe7f3998751f6a753e25 | sanjelarun/eip_python | /practice_programs/arrays_1D/multiply_two_arbitary_int.py | 1,522 | 4 | 4 | '''
WAP that takes two arrays_1D representing integers, and returns an integer representing their product
Example <1,2> and <2> returns <2,4>
'''
import time
# MY METHOD : Convert into single int and do multiplication
def multiply_two_list(A, B):
sign = -1 if A[0] < 0 or B[0] < 0 else 1
A[0], B[0] = abs(A[0]), abs(B[0])
num1 = 0
prod = 1
for i in reversed(A):
num1 += (i * prod)
prod *= 10
product = 1
result = 0
for i in reversed(B):
result += (i * num1 * product)
product *= 10
conver_list = [int(i) for i in str(result)]
return [conver_list[0] * sign] + conver_list[1:]
# BOOK METHOD
def multiply(A, B):
sign = -1 if A[0] < 0 or B[0] < 0 else 1
A[0], B[0] = abs(A[0]), abs(B[0])
result = [0] * (len(A) + len(B))
for i in reversed(range(len(A))):
for j in reversed(range(len(B))):
result[i + j + 1] += A[i] * B[j]
result[i + j] += result[i + j + 1] // 10
result[i + j + 1] %= 10
result = result[next((i for i, x in enumerate(result) if x != 0), len(result)):] or [0]
return [sign * result[0]] + result[1:]
start_time = time.time()
print(multiply_two_list([1, 9, 3, 7, 0, 7, 7, 2, 1,2,2,2,2,2,2], [-7, 6, 1, 8, 3, 8, 2, 5, 7, 2, 8, 7]))
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
print(multiply([1, 9, 3, 7, 0, 7, 7, 2, 1,2,2,2,2,2,2], [-7, 6, 1, 8, 3, 8, 2, 5, 7, 2, 8, 7]))
print("--- %s seconds ---" % (time.time() - start_time))
|
048e068032ebe293e664c6c7a1481a658dbf42e6 | victoriapovolotsky/practice | /codeWithTests/MaxArea.py | 700 | 3.703125 | 4 | class MaxArea:
def max_area(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
length = len(height)
for i in range(length):
for j in range(length):
if i != j:
area = MaxArea.find_area(i, j, height[i], height[j])
if area > max_area:
max_area = area
return max_area
def find_area(i, j, h1, h2):
height = 0
if h1 <= h2:
height = h1
else:
height = h2
width = abs(i-j)
return height * width
# ma = MaxArea()
# print(ma.max_area([1,8,6,2,5,4,8,3,7])) |
43dc57dfb14286a0a105fc36cc2ebda200341d26 | ureChanger/1day-1Algorithm | /2020.12.03 - 26/phoneBook.py | 480 | 3.609375 | 4 | def solution(phone_book):
#문제이해
#추상화: 뒤의 번호들과 비교
#계획하기: phone_book를 차례로 뒤에 위치한 원소들의 접두어들과 비교
answer = True
phone_book.sort()
for num in range(len(phone_book)):
phone_num = phone_book[num]
for nextNum in range(num+1, len(phone_book)):
if phone_num == phone_book[nextNum][:len(phone_num)]:
return False
return answer
|
e525f6530b818da101641d91a7efa2a01a91de62 | YangF0917/ML_Tutorials | /NumPy/Indexing.py | 1,383 | 4.0625 | 4 | import numpy as np
# Array Accessing
arr = np.array([1, 2, 3, 4, 5])
print(arr[0])
print(arr[4])
arr = np.array([[6, 3], [0, 2]])
# Subarray
print(repr(arr[0]))
# Accessing an element in an 1d array is identical to most other langs
# Sub-arrays
arr = np.array([1, 2, 3, 4, 5])
print(repr(arr[:]))
print(repr(arr[1:]))
print(repr(arr[2:4]))
# Cuts 1 element from the end
print(repr(arr[:-1]))
# Takes only the last 2 elements
print(repr(arr[-2:]))
# 2D array Splicing
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(repr(arr[:]))
print(repr(arr[1:]))
print(repr(arr[:, -1]))
print(repr(arr[:, 1:]))
print(repr(arr[0:1, 1:]))
print(repr(arr[0, 1:]))
# Note that the comma indicates how to splice each dimension respectively
# Argmin and Argmax
arr = np.array([[-2, -1, -3],
[4, 5, -6],
[-3, 9, 1]])
print(np.argmin(arr[0]))
print(np.argmax(arr[2]))
print(np.argmin(arr))
# Returns the index of the largest/smallest element in the array
# Using this operation on an multi-dimension array will return the index based on the flattened array
arr = np.array([[-2, -1, -3],
[4, 5, -6],
[-3, 9, 1]])
print(repr(np.argmin(arr, axis=0)))
# returns the max row for each column
print(repr(np.argmin(arr, axis=1)))
# retuns max column for each row
print(repr(np.argmax(arr, axis=-1)))
|
e5e0ec01bced5b08bb77559ca40c82e9486f1f1b | YangF0917/ML_Tutorials | /NumPy/Filtering.py | 2,575 | 3.734375 | 4 | import numpy as np
# Filtering Data
arr = np.array([[0, 2, 3],
[1, 3, -6],
[-3, -2, 1]])
print(repr(arr == 3))
print(repr(arr > 0))
print(repr(arr != 1))
# Negated from the previous step
print(repr(~(arr != 1)))
# Will return a boolean array of whether each element meets the filter requirements
arr = np.array([[0, 2, np.nan],
[1, np.nan, -6],
[np.nan, -2, 1]])
print(repr(np.isnan(arr)))
# np.isnan function returns trues for positions where it should be a placeholder
# Filtering out an array
print(repr(np.where([True, False, True])))
arr = np.array([0, 3, 5, 3, 1])
print(repr(np.where(arr == 3)))
arr = np.array([[0, 2, 3],
[1, 0, 0],
[-3, 0, 0]])
x_ind, y_ind = np.where(arr != 0) # Creates 2 arrays to store 2d indexes of non-sero elements
print(repr(x_ind)) # x indices of non-zero elements
print(repr(y_ind)) # y indices of non-zero elements
print(repr(arr[x_ind, y_ind]))
# End result is a flattened array of all non-zero elements
np_filter = np.array([[True, False], [False, True]])
positives = np.array([[1, 2], [3, 4]])
negatives = np.array([[-2, -5], [-1, -8]])
print(repr(np.where(np_filter, positives, negatives)))
# np.where takes in 3 params, first is the condition (can be a boolean array), second is if true and third for false
np_filter = positives > 2
print(repr(np.where(np_filter, positives, negatives)))
np_filter = negatives > 0
print(repr(np.where(np_filter, positives, negatives)))
# Notice since negatives is always negative, it will always use the value from negatives
np_filter = np.array([[True, False], [False, True]])
positives = np.array([[1, 2], [3, 4]])
print(repr(np.where(np_filter, positives, -1)))
# Notice the third param became a value, this substitutes the value if condition is false
# Axis-wide filtering
arr = np.array([[-2, -1, -3],
[4, 5, -6],
[3, 9, 1]])
print(repr(arr > 0))
print(np.any(arr > 0))
print(np.all(arr > 0))
# any and all returns a single boolean value
arr = np.array([[-2, -1, -3],
[4, 5, -6],
[3, 9, 1]])
print(repr(arr > 0))
print(repr(np.any(arr > 0, axis=0)))
print(repr(np.any(arr > 0, axis=1)))
print(repr(np.all(arr > 0, axis=1)))
# axis=0 means checks each row for each column (context 2d array)
arr = np.array([[-2, -1, -3],
[4, 5, -6],
[3, 9, 1]])
has_positive = np.any(arr > 0, axis=1)
print(has_positive)
print(repr(arr[np.where(has_positive)]))
# Removes the row with all non-positive values
|
affc33ba8100d8e4d2a42e6eb1c223fe018c4372 | semohy/Deu-programlama1 | /python-22022018.py | 1,479 | 3.609375 | 4 | def main():
state = input("ciro için 1 katma değer için 2 yaz : ")
state = int(state)
if(state == 1):
ciro()
elif(state ==2):
KatmaDegerciro()
def turnint(liste):
global createdDict
createdDict={}
for key, value in liste.items():
createdDict[key] = int(value)
def ciro():
miktar =input("Satış Miktarı Giriniz : ")
miktar = int(miktar)
birimfiyat = input("Birim satış fiyatı giriniz : ")
birimfiyat = int(birimfiyat)
result = miktar*birimfiyat
print("Cironuz :",result)
def KatmaDegerciro():
miktar =input("Satış Miktarı Giriniz : ")
hmm =input("ham madde maliyeti Giriniz : ")
bog =input("Bakım Onarım Gideri Giriniz : ")
sg =input("Sevkiyat gideri Giriniz : ")
sevg =input("Satın alınan hizmet giderleri Giriniz : ")
liste={'miktar':miktar,'hmm':hmm,'bog':bog,'sg':sg,'sevg':sevg}
turnint(liste)
result = createdDict["miktar"]-( createdDict["hmm"]+createdDict["bog"]+createdDict["sg"]+createdDict["sevg"] )
print("Katma değerli Cironuz :",result)
while (True):
try:
print("Ciro hesaplama programı")
main()
except KeyboardInterrupt:
interruptState = input("Çıkmak için e tuşla devam etmek için c : ")
if(interruptState == "e"):
exit()
elif (interruptState == "c" ):
pass
|
8570e157445bcbb0d2ff72b5d3c62921d5e084fd | prahaladbelavadi/codecademy | /python/5.making-a-request.py | 1,129 | 4.40625 | 4 | # Making a Request
# You saw a request in the first exercise. Now it's time for you to make your own! (Don't worry, we'll help.)
#
# On line 1, we've imported urlopen from the urllib2 module, which is the Python way of bringing in additional functionality we'll need to make our HTTP request. A module is just a collection of extra Python tools.
#
# On line 4, we'll use urlopen on placekitten.com in preparation for our GET request, which we make when we read from the site on line 5. (On line 6, we limit the response to specific character numbers to control the input we get back—this is what gives us our cat image.)
#
# We'll need your help to complete the request!
#
# Instructions
# On line 4, declare a variable, kittens, and set it equal to calling urlopen on http://placekitten.com. No need for the "www"!
#
# On line 8, print the body variable so we can see some of the data we got back.
from urllib2 import urlopen
# Open http://placekitten.com/ for reading on line 4!
kittens = urlopen('http://placekitten.com')
response = kittens.read()
body = response[559:1000]
# Add your 'print' statement here!
print body
|
821eef207a015d9ffa9b47e6d161f0cd566822c2 | prahaladbelavadi/codecademy | /python/17.requests.py | 645 | 3.84375 | 4 | # Requests
# All right! Let's see if you can make that request to http://placekitten.com/ all on your lonesome.
#
# Instructions
# You need to do two things:
#
# On line 4, create a variable called website and set it equal to calling the urlopen method on "http://placekitten.com/" (no need for the "www"!)
# On line 5, call the read method on website and save the result in a new variable called kittens.
# The last line will then take the full kittens response you saved and display part of it.
from urllib2 import urlopen
# Add your code here!
website = urlopen('http://placekitten.com')
kittens = website.read()
print kittens[559:1000]
|
901d7d94caefeb64b57c992199b377e0d4f29542 | INFO3401/problem-set-7-tala3849 | /parsers.py | 10,406 | 3.734375 | 4 | ################################################################################
# PART #1 #worked with Hannah and Marissa
################################################################################
import string
import csv
import os
from os import listdir
import json
def countWordsUnstructured(filename):
#wordcount = {}
#file = open(filename)
#for word in file.read().split():
#if word not in wordcount:
#wordcount[word] = 1
#else:
#wordcount[word] += 1
#print (word,wordcount)
#file.close();
#initialize a word count dictionare
wordCounts = {}
#step 1 - open the file & read it
datafile = open(filename).read()
#step 3 - split out into words
data = datafile.split()
#step 4 - count it
for word in data:
for mark in string.punctuation:
word = word.replace(mark, "")
if word in wordCounts:
wordCounts[word] = wordCounts[word] + 1
else:
wordCounts[word] = 1
#step 5 - return word count dictionary
return wordCounts
#return the word count dictionary
#return wordCounts
# This function should count the words in an unstructured text document
# Inputs: A file name (string)
# Outputs: A dictionary with the counts for each word
# +1 bonus point for removing punctuation from the wordcounts
# Test your part 1 code below.
bush1989 = countWordsUnstructured('./state-of-the-union-corpus-1989-2017/Bush_1989.txt')
print (bush1989)
################################################################################
# PART 2 #worked with Hannah and Marissa
################################################################################
#import CSV
#with open('taret_file.csv' , 'w') as csv_file:
#writer = csv.writer(csv_file)
#writer.writerow(('column 1, column 2, column 3'))
#for key, value in dictionary.items():
#writer.writerow([key, value[0],value[1]])
def generateSimpleCSV(targetfile,wordCounts):
#def generateSimpleCSV(targetfile, wordCounts):
# This function should transform a dictionary containing word counts to a
# CSV file. The first row of the CSV should be a header noting:
# Word, Count
# Inputs: A word count list and a name for the target file
# Outputs: A new CSV file named targetfile containing the wordcount data
#open the file
with open (targetfile, 'w') as csv_file:
#print the headers
writer = csv.writer(csv_file)
writer.writerow(['Word', 'Count'])
for key,value in wordCounts.items():
writer.writerow([key, value])
#iterate through the word counts
#add to our CSV file
#close the file
csv_file.close()
#return pointer to the file
return csv_file
# Test your part 2 code below
generateSimpleCSV('pleasepleasework', countWordsUnstructured('./state-of-the-union-corpus-1989-2017/Bush_1989.txt'))
################################################################################
# PART 3 #worked with Hannah and Marissa
################################################################################
#def countWordsMany(directory):
# This function should create a dictionary of word count dictionaries
# The dictionary should have one dictionary per file in the directory
# Each entry in the dictionary should be a word count dictionary
# Inputs: A directory containing a set of text files
# Outputs: A dictionary containing a word count dictionary for each
# text file in the directory
#open the directory pull a list of all file names
def countWordsMany(directory):
#open the directory and pulling list of name files
directory_list = listdir(directory)
wordCountDict = {}
#looping through the list of files, for each file you call the word counts function
for file in directory_list:
eachWordCount = countWordsUnstructured(directory + "/" + file )
wordCountDict[file] = eachWordCount
return wordCountDict
# Test your part 3 code below
big_dictionary = countWordsMany('./state-of-the-union-corpus-1989-2017')
print(big_dictionary)
################################################################################
# PART 4 #worked with Hannah and Marissa
################################################################################
#def generateDirectoryCSV(wordCounts, targetfile):
def generateDirectoryCSV(wordCounts, targetfile):
#open file as csv
with open(targetfile, 'w') as csv_file:
#create the csv
writer = csv.writer(csv_file)
#make the header row
writer.writerow(['Filename','Word','Count'])
#iterate the word counts and write them into csv
for key,value in wordCounts.items():
writer.writerow([key, value])
#close the csv
csv_file.close()
#return the file
return csv_file
# This function should create a CSV containing the word counts generated in
# part 3 with the header:
# Filename, Word, Count
# Inputs: A word count dictionary and a name for the target file
# Outputs: A CSV file named targetfile containing the word count data
# Test your part 4 code below
generateDirectoryCSV(countWordsMany('state-of-the-union-corpus-1989-2017'), 'part4CSV')
################################################################################
# PART 5 # worked with hannah and marissa and Steven
################################################################################
#def generateJSONFile(wordCounts, targetfile):
# This function should create an containing the word counts generated in
# part 3. Architect your JSON file such that the hierarchy will allow
# the user to quickly navigate and compare word counts between files.
# Inputs: A word count dictionary and a name for the target file
# Outputs: An JSON file named targetfile containing the word count data
def generateJSONFile(wordCounts, targetfile):
#opens the file
JSON_file = open(targetfile, "w")
#trasnform the word count directory to json
JSON_file.write(str(wordCounts).replace("\'","\""))
# close the file
JSON_file.close()
#return file
return JSON_file
# Test your part 5 code below
generateJSONFile(big_dictionary, "part5file")
################################################################################
# PART 6 #worked with Jacob, Hannah and Marissa
################################################################################
def searchCSV(csvfile, word):
# This function should search a CSV file from part 4 and find the filename
# with the largest count of a specified word
# Inputs: A CSV file to search and a word to search for
# Outputs: The filename containing the highest count of the target word
#set the variables to use
largest_count_file = ""
largest_count = 0
#open the csv file
with open(csvfile) as csv_file:
file = csv.reader(csv_file)
#make a for loop to find the filename with the largest count of a specified word
for line in file:
#finds which line has largest count
#if the 2nd value in the line is the word we are looking for an dlarger
if line[1] == word and int(line[2]) > int(largest_count):
largest_count = line[2]
largest_count_files = line[0]
#return the file
return largest_count_file
#close the file
csv_file.close()
def searchJSON(JSONfile, word):
# This function should search a JSON file from part 5 and find the filename
# with the largest count of a specified word
# Inputs: An JSON file to search and a word to search for
# Outputs: The filename containing the highest count of the target word
#set the variable
largest_count_file = ""
largest_count = 0
#open the json file
with open(JSONfile) as json_file:
data = json.load(json_file)
# make a loop for finding the file that has the highest count fot that word
for file in data:
if data[file][word] > largest_count:
largest_count = data[file][word]
largest_count_file = file
#return the file
return largest_count_file
#close the file
json_file.close()
print(searchCSV("part4CSV", "and"))
print(searchJSON("part5file","and"))
#make a search for words
#search the file by filename to find the largest value
#max_count = max(jsonFile['Count'])
#return the highest values filename
#close file
#jsonFile.close()
# Test your part 6 code to find which file has the highest count of a given word
# +1 bonus point for figuring out how many datapoints you had to process to
# compute this value
###############################################################################
#PART 7 #worked with Hannah and Marissa and Jacob
###############################################################################
#import sqlite3
#set up a connection to the database
#conn = sqlite3.connect('presidents_speech.db')
#c = conn.cursor()
#ask the connection to execute SQL statement
#c.execute('''CREATE TABLE word_counts ( filename, word, count)''')
#c.execute('''CREATE TABLE presidentInformation (index, number, start, end, president_name, prior occupation, party, VP)''')
#the table could be joined on president name or year of presidency
# Table 1 wordCounts
#text filename
#text word
# number(integer) count
# Table 2 - pres information
#integer index
#integer number
# text start
# text end
# text president_name
# text prior occupation
# text party
# text VP
#save (commit) the changes
#conn.commit()
#close the connection
#conn.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.