blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
97b74119ddcbc077e44755d38b27a7e3361edfa5 | matthewdoles/python-practice | /zelle-python/chapter08/syracuse.py | 536 | 4.1875 | 4 |
# exercise 4 - calculate the Syracuse sequence when given a user input
# sequence stops when the number 1 is reached
def syracuse(x, sequence):
if x % 2 == 0:
x = int(x / 2)
sequence.append(x)
elif x % 2 == 1:
x = int(3 * x + 1)
sequence.append(x)
return x
def main():
n = eval(input("What is the starting value you would like to see for the Syracuse sequence? "))
sequence = [int(n)]
while n != 1:
n = syracuse(n, sequence)
print(sequence)
main()
|
472dd25b7227f053b3034da924a657c8aff238c4 | himanshushukla254/OPENCV_Python_Codes | /threshold.py | 315 | 3.5 | 4 | # import opencv
import cv2
# Read image
src = cv2.imread("threshold.png", cv2.IMREAD_GRAYSCALE)
# Set threshold and maxValue
thresh = 0
maxValue = 255
# Basic threshold example
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY);
cv2.imshow('image',dst)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
|
8d5a6e22cc13f3a0e869d296e1722005d63aba1d | szhou12/MachineLearning4PublicPolicy | /pa2/Preprocess.py | 4,949 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 13 15:32:38 2018
@author: JoshuaZhou
"""
import scipy.stats
import numpy as np
import pandas as pd
def fill_missing(df, cols, mean=True):
'''
Fill in missing values using mean if mean==True or 0 if mean==False.
Inputs:
df: the original dataframe
cols (list): a list of col names that have missing values
mean (bool): use mean to fill in missing values or not
'''
if mean:
for c in cols:
mean = df[c].mean()
df[c].fillna(mean, inplace=True)
else:
for c in cols:
df[c].fillna(0, inplace=True)
return df
def get_stats(col):
'''
Get mean and standard deviation from the given variable
'''
return col.mean(), col.std()
def log_transform(df, colname):
'''
Log Transformation: Apply log(x+1) to the given variable.
'''
log_trans = df[colname].apply(np.log1p)
return log_trans
def normalized(df, colname, use_log):
'''
Normalization-based discretization: discretize using normalization
4 categories:
within 1 std: if the standardized value is <=1 std away from mean
within 2 std: if the standardized value is >1 and <=2 std away from mean
within 3 std: if the standardized value is >2 and <=3 std away from mean
out 3 std: if the standardized value is > 3 std away from the mean
Inputs:
df: dataframe
colname: the variable to normalize
use_log (bool): True if log transformation is needed
Outputs:
df: dataframe
use_norm (bool): True if use normalization in the end
'''
use_norm = True
if use_log:
log_trans = log_transform(df, colname)
mean, std = get_stats(log_trans)
norm_col = log_trans.apply(lambda x: abs((x-mean)/std))
else:
mean, std = get_stats(df[colname])
norm_col = df[colname].apply(lambda x: abs((x-mean)/std))
norm_bins = [0.0, 1, 2, 3, float('inf')]
norm_labels = ['within 1 std', 'within 2 std', 'within 3 std', \
'out 3 std']
discretize_colname = "d_"+colname
df[discretize_colname] = pd.cut(norm_col, norm_bins, \
labels=norm_labels, right=False)
return df, use_norm
def quartilized(df, colname, use_log):
'''
Quantile-based discretization: discretize by quantiles
4 categories:
Q1: bottom 25% in the rank
Q2: (25%, 50%) in the rank
Q3: (50%, 75%) in the rank
Q4: top 25% in the rank
Inputs:
df: dataframe
colname: the variable to normalize
use_log (bool): True if log transformation is needed
Outputs:
df: dataframe
use_norm (bool): False if use quatile in the end; True if switch to normalization
'''
use_norm = False
qlabels = ['Q1','Q2','Q3','Q4']
discretize_colname = "d_"+colname
try:
if use_log:
log_trans = log_transform(df, colname)
df[discretize_colname] = pd.qcut(log_trans, 4, labels=qlabels)
else:
df[discretize_colname] = pd.qcut(df[colname], 4, labels=qlabels)
except:
df, use_norm = normalized(df, colname, use_log)
return df, use_norm
def discretize(df, colname, is_norm=True):
'''
Discretize a continuous variable w/ normalization-based or quantile-based.
Apply log transformation at first if the distribution of the variable is highly skewed.
Inputs:
df: dataframe that filled in missing values
colname (str): the variable to discretize
is_norm (bool): True if discretize by normalization; False if by quartile.
Outputs:
df_disc: dataframe that adds a categorical variable column
use_norm (bool): True if use normalization; False if use quartile.
'''
if round(scipy.stats.skew(df[colname])) != 0:
use_log = True
else:
use_log = False
if is_norm:
df_disc, use_norm = normalized(df, colname, use_log)
else:
df_disc, use_norm = quartilized(df, colname, use_log)
return df_disc, use_norm
def create_dummy(df_disc, colname, is_norm=True):
'''
The function that takes a categorical variable specified in discretize()
and creates binary/dummy variables from it.
Inputs:
df_disc: dataframe from discretize()
colname (str): the variable to create dummy
is_norm (bool): True if discretize by normalization; False if by quartile.
Outputs:
df_disc: dataframe that adds a dummy variable column
'''
if is_norm:
df_disc['95% CI'] = df_disc["d_"+colname].apply(lambda x: \
'3 std' not in x)
else:
df_disc['upper 50%'] = df_disc["d_"+colname].apply(lambda x: \
x in ['Q3','Q4'])
return df_disc
|
e941cbaf4e482d7da49061c63be957553d268cf1 | bssrdf/pyleet | /F/FloodFill.py | 3,739 | 4.03125 | 4 | '''
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
'''
from queue import Queue
class Solution(object):
# def isvalid(self, i, j, board, processed, target):
# if i>=0 and i<len(board) and j>=0 and j<len(board[0]):
# print 'isvalid: ', i, j, board[i][j], processed[i][j]
# return i>=0 and i<len(board) and j>=0 and j<len(board[0]) and board[i][j] == target and (not processed[i][j])
row = [ -1, -1, -1, 0, 0, 1, 1, 1]
col = [ -1, 0, 1, -1, 1, -1, 0, 1]
def BFS(self, board, x, y, replacement):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
process = [False for l in board[0]]
processed = [process[:] for l in board]
q = Queue(len(board)*len(board[0]))
target = board[x][y]
q.enqueue((x,y))
print('target = ', target)
processed[x][y] = True
while(not q.isEmpty()):
(x1, y1) = q.dequeue()
board[x1][y1] = replacement
for r,c in zip(self.row, self.col):
#print r,c,len(q)
#if isvalid(self, x1+r,y1+c, board, processed, target):
i=x1+r
j=y1+c
if i>=0 and i<len(board) and j>=0 and j<len(board[0]) and board[i][j] == target and (not processed[i][j]):
q.enqueue((i,j))
# print r,c, i, j, board[i][j], processed[i][j], len(q)
processed[i][j] = True
return
def DFS(self, board, x, y, target, replacement):
board[x][y] = replacement
for r,c in zip(self.row, self.col):
i=x+r
j=y+c
if i>=0 and i<len(board) and j>=0 and j<len(board[0]) and board[i][j] == target:
self.DFS(board, i, j, target, replacement)
return
def DFSIter(self, board, x, y, target, replacement):
stack = []
#board[x][y] = replacement
stack.append((x,y))
while stack:
(x1, y1)=stack.pop()
board[x1][y1] = replacement
for r,c in zip(self.row, self.col):
i=x1+r
j=y1+c
if i>=0 and i<len(board) and j>=0 and j<len(board[0]) and board[i][j] == target:
stack.append((i,j))
return
if __name__ == "__main__":
board = [
[ 'Y', 'Y', 'Y', 'G', 'G', 'G', 'G', 'G', 'G', 'G' ],
[ 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'G', 'X', 'X', 'X' ],
[ 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'X', 'X', 'X' ],
[ 'W', 'W', 'W', 'W', 'W', 'G', 'G', 'G', 'G', 'X' ],
[ 'W', 'R', 'R', 'R', 'R', 'R', 'G', 'X', 'X', 'X' ],
[ 'W', 'W', 'W', 'R', 'R', 'G', 'G', 'X', 'X', 'X' ],
[ 'W', 'B', 'W', 'R', 'R', 'R', 'R', 'R', 'R', 'X' ],
[ 'W', 'B', 'B', 'B', 'B', 'R', 'R', 'X', 'X', 'X' ],
[ 'W', 'B', 'B', 'X', 'B', 'B', 'B', 'B', 'X', 'X' ],
[ 'W', 'B', 'B', 'X', 'X', 'X', 'X', 'X', 'X', 'X' ]
]
for l in board:
print l
#Solution().BFS(board, 3, 9, 'C')
#Solution().DFS(board, 3, 9, 'X', 'C')
Solution().DFSIter(board, 3, 9, 'X', 'C')
print('=============================')
for l in board:
print(l)
#assert board == expected_board
|
91349c2d8c90d86fcbc5d2e1ce155a53c94d8910 | aanndalia/andrew-dalia | /anagram_diff.py | 2,063 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import fileinput
def anagramDiff2(word):
word = word.rstrip('\n')
if not word:
return -1
if len(word) % 2 == 1:
return -1
mid = len(word) / 2
word1 = word[:mid]
word2 = word[mid:]
word1list = list(word1)
word2list = list(word2)
word1list.sort()
word2list.sort()
i1 = 0
i2 = 0
td = 0
#ld = 0
while i1 < mid and i2 < mid:
if word1list[i1] == word2list[i2]:
i1 += 1
i2 += 1
elif word1list[i1] < word2list[i2]:
td += 1
i1 += 1
else:
#td += 1
i2 += 1
while i1 < mid:
td += 1
i1 += 1
while i2 < mid:
#td += 1
i2 += 1
return td
def anagramDiff(word):
word = word.rstrip('\n')
if not word:
return -1
if len(word) % 2 == 1:
return -1
mid = len(word) / 2
word1 = word[:mid]
word2 = word[mid:]
charToFreq = {}
charToFreq2 = {}
for c in word1:
if c in charToFreq:
charToFreq[c] += 1
else:
charToFreq[c] = 1
for c in word2:
if c in charToFreq2:
charToFreq2[c] += 1
else:
charToFreq2[c] = 1
print charToFreq
print charToFreq2
totalDiff = 0
loners = 0
for char, freq in charToFreq.iteritems():
if char in charToFreq2:
totalDiff += abs(charToFreq2[char] - freq)
else:
totalDiff += freq
#for char, freq in charToFreq2.iteritems():
#if char not in charToFreq:
#totalDiff += freq
#print charToFreq
#totalDiff = 0
#for char, freq in charToFreq.iteritems():
# totalDiff += abs(freq)
return totalDiff
lines = []
for line in fileinput.input():
lines.append(line)
N = lines[0]
for word in lines[1:]:
print anagramDiff2(word) |
fd00c250778b1014b678c856fbc011b039c5a452 | ankursheth/python_practice | /fibonacci.py | 594 | 4 | 4 | def fibonacci1(number):
if number == 0:
return 0
elif number == 1:
return 1
else:
return fibonacci1(number-1)+fibonacci1(number-2)
def fibonacci2(number):
x, y = 1, 1
for i in range(number-1):
x, y = y, x+y
return x
def fibonacci3():
x, y = 1, 1
while True:
yield x
x, y = y, x+y
for i in range(1, 10):
print(fibonacci1(i), end=" ")
print()
for i in range(1, 300):
print(fibonacci2(i), end=" ")
print()
n = 0
for i in fibonacci3():
if n >= 15:
break
print(i, end=" ")
n = n + 1
|
3e7e48ec1739d1fb417805ba372dfbf06fe91777 | ccc013/DataStructe-Algorithms_Study | /Python/Leetcodes/binary_tree/jianzhi_offer_68_2_lowestCommonAncestor.py | 938 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/12/14 7:45 上午
@Author : luocai
@file : jianzhi_offer_68_2_lowestCommonAncestor.py
@concat : 429546420@qq.com
@site :
@software: PyCharm Community Edition
@desc :
https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
剑指 offer68 题 II,二叉树的最近公共祖先
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or p == root or q == root:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not right:
return left
if not left:
return right
return root
|
50a008dc38801d47d37e975fba037bbcddb06b93 | chenxu0602/LeetCode | /1114.print-in-order.py | 2,735 | 4.0625 | 4 | #
# @lc app=leetcode id=1114 lang=python3
#
# [1114] Print in Order
#
# https://leetcode.com/problems/print-in-order/description/
#
# concurrency
# Easy (65.64%)
# Likes: 576
# Dislikes: 103
# Total Accepted: 60.6K
# Total Submissions: 91.4K
# Testcase Example: '[1,2,3]'
#
# Suppose we have a class:
#
#
# public class Foo {
# public void first() { print("first"); }
# public void second() { print("second"); }
# public void third() { print("third"); }
# }
#
#
# The same instance of Foo will be passed to three different threads. Thread A
# will call first(), thread B will call second(), and thread C will call
# third(). Design a mechanism and modify the program to ensure that second() is
# executed after first(), and third() is executed after second().
#
#
#
# Example 1:
#
#
# Input: [1,2,3]
# Output: "firstsecondthird"
# Explanation: There are three threads being fired asynchronously. The input
# [1,2,3] means thread A calls first(), thread B calls second(), and thread C
# calls third(). "firstsecondthird" is the correct output.
#
#
# Example 2:
#
#
# Input: [1,3,2]
# Output: "firstsecondthird"
# Explanation: The input [1,3,2] means thread A calls first(), thread B calls
# third(), and thread C calls second(). "firstsecondthird" is the correct
# output.
#
#
#
# Note:
#
# We do not know how the threads will be scheduled in the operating system,
# even though the numbers in the input seems to imply the ordering. The input
# format you see is mainly to ensure our tests' comprehensiveness.
#
#
# @lc code=start
from threading import Lock, Semaphore
class Foo:
def __init__(self):
# self.firstJobDone = Lock()
# self.secondJobDone = Lock()
# self.firstJobDone.acquire()
# self.secondJobDone.acquire()
self.two = Semaphore(0)
self.three = Semaphore(0)
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
# printFirst()
# self.firstJobDone.release()
printFirst()
self.two.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
# printSecond() outputs "second". Do not change or remove this line.
# with self.firstJobDone:
# printSecond()
# self.secondJobDone.release()
with self.two:
printSecond()
self.three.release()
def third(self, printThird: 'Callable[[], None]') -> None:
# printThird() outputs "third". Do not change or remove this line.
# with self.secondJobDone:
# printThird()
with self.three:
printThird()
# @lc code=end
|
29adb2d797cdd1d43a3928a9fe835736f6c3e85d | kelvin002a/kes-sqlite3 | /script.py | 570 | 4.1875 | 4 | import sqlite3
connection = sqlite3.connect("test.db")
Cursor = connection.cursor()
table1 = """CREATE TABLE IF NOT EXISTS
Movies(movie_name TEXT,Actor_name Text ,actress_name TEXT ,Director_Name TEXT ,Year_of_release INTEGER) """
Cursor.execute(table1)
Cursor.execute("INSERT INTO Movies VALUES ('PIE','Arun','Bony','Cathy',2001)")
Cursor.execute("INSERT INTO Movies VALUES ('PEL','Anto','Benson','Catherin',2001)")
Cursor.execute("SELECT * FROM Movies")
Cursor.execute("SELECT * FROM Movies WHERE actor_name='Anto' ")
result = Cursor.fetchall()
print(result) |
1a2a51b714e82ae71922c9dfb5d3b002923d53b3 | Crow07/python-learning | /python learning/循环/for.py | 390 | 3.984375 | 4 | for i in range(3):
print('loop',i)
for i in range(0,6,2):
print("loop",i)
age_of_crow = 22
count= 0
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age_of_crow:
print("yes,all right")
break
elif guess_age > age_of_crow:
print("smaller")
else:
print("bigger")
else:
print("you have tried too many times") |
85d6b0e97d344c9a3252c575fb404bb8cca40d4d | cory-evans/calculus | /complex_numbers.py | 1,508 | 3.671875 | 4 | from math import *
def to_polar(c: complex):
r = sqrt(c.real ** 2 + c.imag ** 2)
theta = tanh(abs(c.imag) / abs(c.real))
if c.real < 0 and c.imag >= 0:
theta_real = pi - theta
print('c.real < 0 and c.imag >= 0')
elif c.real < 0 and c.imag < 0:
theta_real = pi + theta
print('c.real < 0 and c.imag < 0')
elif c.real >= 0 and c.imag < 0:
theta_real = 2 * pi - theta
print('c.real >= 0 and c.imag < 0')
else:
theta_real = theta
return r, theta_real
class ComplexPolar:
def __init__(self, r, theta):
self._r = r
self._theta = theta
@property
def r(self):
return self._r
@property
def theta(self):
theta = self._theta % (2 * pi)
if self._theta < 0:
return -theta
return theta
@property
def rect(self):
return complex(self.r * cos(self.theta), self.r * sin(self.theta))
def to_string(self, n_digits: int = 16):
return '{} cis {}'.format(round(self.r, n_digits), round(self.theta, n_digits))
def __repr__(self):
return self.to_string(3)
def __mul__(self, other):
return ComplexPolar(self.r * other.r, self.theta + other.theat)
def __truediv__(self, other):
return ComplexPolar(self.r / other.r, self.theta - other.theta)
def __pow__(self, other: int):
return ComplexPolar(self.r ** other, self.theta * other)
|
4484d59b49850f2dd950561f9afe0b44ba1e6718 | ycliu912/python-basic | /pyhelloworld/src/class03.py | 844 | 3.921875 | 4 | #-*-coding:utf-8 -*-
'''
Created on 2016年5月10日
@author: liu
'''
class Parent: #定义父类
parentAttr = 100
def __init__(self):
print "调用父类构造函数"
def parentMethod(self):
print "调用父类方法"
def setAttr(self,attr):
Parent.parentAttr = attr
def getAttr(self):
print "父类属性 :",Parent.parentAttr
class Child(Parent): #定义子类
def __init__(self):
print "调用子类构造方法"
def childMethod(self):
print "调用子类方法 child method"
c = Child() #实例化子类
c.childMethod() #调用子类方法
c.parentMethod() #调用父类方法
c.setAttr(200) #调用父类方法
c.getAttr() #再次调用父类方法
|
93216b996bbb01741f86b67d237ee18df2e0e961 | Fitzy1098/AI-Search-Assignment | /AI Search 17-10-18.py | 2,131 | 3.65625 | 4 | def readFile(filename):
#filename = "AISearchtestcase.txt" #"NEWAISearchfile012.txt" #
file = open(filename, 'r')
data=file.readlines()
stringdata="".join(data)
return(stringdata)
def getName(stringdata):
stringdata=stringdata.split("=")
name=stringdata[1].lstrip(" ")
name=name.split(",")[0]
return(name)
def getSize(stringdata):
stringdata=stringdata.split("=")
size=""
size=stringdata[2][1:2]
i=3
while stringdata[2][1:i].isdigit():
size=stringdata[2][1:i]
i+=1
stringdata=stringdata[2][i:]
return int(size)
def generateMatrix(size):
size=int(size)
matrix = [[0]*size for i in range(size)]
return matrix
def populateMatrix(stringdata, size, matrix):
stringdata=stringdata.split("=")
size=""
size=stringdata[2][1:2]
i=3
while stringdata[2][1:i].isdigit():
size=stringdata[2][1:i]
i+=1
stringdata=stringdata[2][i:]
stringdata=stringdata.split(",")
size=int(size)
length=size-1
rowNum=1
while length!=0:
row=stringdata[:length]
stringdata=stringdata[length:]
colNum=size
for cell in row:
num=""
i=0
foundInt=0
while foundInt!=2:
if cell[i].isdigit():
num+=cell[i]
foundInt=1
else:
if foundInt == 1:
foundInt=2
if cell[i]==cell[-1]:
foundInt=2
i+=1
num=int(num)
matrix[rowNum-1][size-colNum+rowNum]=num
matrix[size-colNum+rowNum][rowNum-1]=num
colNum-=1
length-=1
rowNum+=1
return(matrix)
def printMatrix(size, matrix):
for i in range(size):
print(matrix[i])
def work(x):
s=readFile(x)
n=getName(s)
si=getSize(s)
m=generateMatrix(si)
n=populateMatrix(s,si,m)
printMatrix(si,n)
|
e260b5a547f126bfe66252298cfe23cb352d8032 | nushrathumaira/Udacity_DataStructureAlgo | /P2/problem_4.py | 1,192 | 4.21875 | 4 | def swap(input_list, i, j):
temp = input_list[i]
input_list[i] = input_list[j]
input_list[j] = temp
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
start = 0
mid = 0
pivot = 1
end = len(input_list)-1
while mid <= end :
if input_list[mid] < pivot: # current element less than 1
swap(input_list, start,mid)
start += 1
mid += 1
elif input_list[mid] > pivot: #current element is 2
swap(input_list,mid, end)
end -= 1
else:
mid += 1
return input_list
def test_function(test_case):
sorted_array = sort_012(test_case)
#print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
test_function([])
test_function([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) |
69517becf55b367b141181fbcc44e32ac154b8a8 | codewithgauri/HacktoberFest | /python/two_sum.py | 537 | 3.609375 | 4 | /*
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
*/
class Solution(object):
def twoSum(self, nums, target):
hash_table = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement not in hash_table:
hash_table[nums[i]] = i
else:
return [hash_table[complement], i]
|
e24a55e306bee7063d56f2bb5a893ee6dc628653 | cristianjs19/codefights-solutions-Python | /The Core/02 - largestNumber/largestNumber.py | 105 | 3.625 | 4 | def largestNumber(n):
res = ""
for i in range(n):
res = res + "9"
return int(res) |
c1e8ec2d2df231c63b1d1327abacd954d5edba7d | zjxpirate/Daily-Upload-Python | /hash_tables/find_anagrams.py | 519 | 4.3125 | 4 |
import functools, collections
# 2. find anagrams
def find_anagrams(dictionary):
sorted_string_to_anagrams = collections.defaultdict(list)
for s in dictionary:
# sorts the string, uses it as a key, and then appends the original
# string as another value into hash table.
sorted_string_to_anagrams[''.join(sorted(s))].append(s)
return [group for group in sorted_string_to_anagrams.values() if len(group) >= 2]
print(find_anagrams(["string1", "string2", "1string", "2string"]))
|
2eba91d9a3642847e949eeebd52d6043a895b644 | ARASKES/Python-practice-2 | /Practice2 tasks/Lesson_9/Task_9_1.py | 364 | 3.8125 | 4 | M = int(input())
N = int(input())
library_books = []
book_list = []
for i in range(M):
library_books.append(input())
for i in range(N):
book_list.append(input())
for book in book_list:
is_found = False
for lb in library_books:
if lb == book:
is_found = True
if is_found:
print("YES")
else:
print("NO")
|
c112b762be793050ac1f290f63a652427060979a | ihaeeun/Algorithms | /Python/SWExpertAcademy/level3/5601.py | 92 | 3.6875 | 4 | for t in range(int(input())):
n=input()
s='1/'+n+' '
print(f'#{t+1} {s*int(n)}') |
9156f384f1ed2557a2bb5fac10082d966d1a7f69 | jiaxiaoyu7777/ai-game | /chess game.py | 9,041 | 3.734375 | 4 | # 棋盘
#define game
row = 4
maxdepth = 3
playuse = 1
#0: minmax 1: 减枝算法
class Board(object):
def __init__(self):
#self._board = '-'*9 # 坑!!
self._board = ['-' for _ in range(row*row)]
self._history = [] # 棋谱
# 按指定动作,放入棋子
def _move(self, action, take):
if self._board[action] == '-':
self._board[action] = take
self._history.append((action, take)) # 加入棋谱
# 撤销动作,拿走棋子
def _unmove(self, action):
self._board[action] = '-'
self._history.pop()
# 棋盘快照
def get_board_snapshot(self):
return self._board[:]
# 取棋盘上的合法走法
def get_legal_actions(self):
actions = []
for i in range(row*row):
if self._board[i] == '-':
actions.append(i)
return actions
# 判断走法是否合法
def is_legal_action(self, action):
return self._board[action] == '-'
# 终止检测
def teminate(self):
board = self._board
line1 = [board[i*row:i*row+row] for i in range(row) ]
line2 = [board[i::row] for i in range(row)]
line3 = [board[0::row + 1]]
line4 = [board[row - 1:row * row - row + 1:row - 1]]
lines = line1+line2+line3+line4
print(self.eval1())
if ['X']*3 in lines or ['O']*3 in lines or '-' not in board:
return True
else:
return False
#评估函数
def eval1(self):
board = self._board
line1 = [board[i * row:i * row + row] for i in range(row)]
line2 = [board[i::row] for i in range(row)]
line3 = [board[0::row + 1]]
line4 = [board[row - 1:row * row - row + 1:row - 1]]
lines = line1 + line2 + line3 + line4
value = 0
for s in lines:
value+=s.count('X')^2
for s in lines:
value-=s.count('O')^2
return value
# 胜负检查
def get_winner(self):
board = self._board
line1 = [board[i * row:i * row + row] for i in range(row)]
line2 = [board[i::row] for i in range(row)]
line3 = [board[0::row + 1]]
line4 = [board[row - 1:row * row - row + 1:row - 1]]
lines = line1 + line2 + line3 + line4
if ['X']*3 in lines:
return 0
elif ['O']*3 in lines:
return 1
else:
return 2
# 打印棋盘
def print_b(self):
board = self._board
for i in range(len(board)):
print(board[i], end='')
if (i+1)%row == 0:
print()
# 打印棋谱
def print_history(self):
print(self._history)
# 玩家
class Player(object):
'''
玩家只做两件事:思考、落子
1. 思考 --> 得到走法
2. 落子 --> 执行走法,改变棋盘
'''
def __init__(self, take='X'): # 默认执的棋子为 take = 'X'
self.take=take
def think(self, board):
pass
def move(self, board, action):
board._move(action, self.take)
# 人类玩家
class HumanPlayer(Player):
def __init__(self, take):
super().__init__(take)
def think(self, board):
while True:
say = "Please input a num in 0-%d" % (row*row-1)
action = input(say)
ra = [i for i in range(row*row-1)]
if int(action) in ra and board.is_legal_action(int(action)):
return int(action)
# min-max
class AIPlayer(Player):
def __init__(self, take):
super().__init__(take)
def think(self, board):
print('AI is thinking ...')
take = ['X','O'][self.take=='X']
player = AIPlayer(take) # 假想敌!!!
_, action = self.minimax(board, player)
print('OK')
return action
# 极大极小法搜索,α-β剪枝
def minimax(self, board, player, depth=0) :
# '''参考:https://stackoverflow.com/questions/44089757/minimax-algorithm-for-tic-tac-toe-python'''
if self.take == "O":
bestVal = -10
else:
bestVal = 10
if board.teminate() :
#print(depth)
if board.get_winner() == 0 :
return -10 + depth, None
elif board.get_winner() == 1 :
return 10 - depth, None
elif board.get_winner() == 2 :
return 0, None
if depth > maxdepth :
return 0, None
for action in board.get_legal_actions() : # 遍历合法走法
board._move(action, self.take)
val, _ = player.minimax(board, self, depth+1) # 切换到 假想敌!!!
board._unmove(action) # 撤销走法,回溯
if self.take == "O" :
if val > bestVal:
bestVal, bestAction = val, action
else :
if val < bestVal:
bestVal, bestAction = val, action
#print(depth)
return bestVal, bestAction
# cut
class AIPlayer2(Player):
def __init__(self, take):
super().__init__(take)
def think(self, board):
print('AI is thinking ...')
take = ['X','O'][self.take=='X']
player = AIPlayer2(take) # 假想敌!!!
_, action = self.minimaxcut(board, player)
print('OK')
return action
# 极大极小法搜索,α-β剪枝
def minimaxcut(self, board, player, depth=0, fatherbeta = 0, fatheralpha = 0) :
# '''参考:https://stackoverflow.com/questions/44089757/minimax-algorithm-for-tic-tac-toe-python'''
#print(depth)
beta = 100000
alpha = -100000
bestAction = None
if self.take == "O":
bestVal = -10
else:
bestVal = 10
if board.teminate() :
#print(depth)
if board.get_winner() == 0 :
return -10 + depth, None
elif board.get_winner() == 1 :
return 10 - depth, None
elif board.get_winner() == 2 :
return 0, None
if depth > maxdepth :
if self.take == "O":
return -board.eval1(), None
else:
return +board.eval1(), None
for action in board.get_legal_actions() : # 遍历合法走法
if self.take == "O" :
if fatheralpha > beta :
return
else :
if fatherbeta < alpha :
return
board._move(action, self.take)
val, _ = player.minimaxcut(board, self, depth+1,beta,alpha) # 切换到 假想敌!!!
board._unmove(action) # 撤销走法,回溯
if self.take == "O" :
if val > bestVal:
bestVal, bestAction = val, action
if val >alpha :
alpha = val
else :
if val < bestVal:
bestVal, bestAction = val, action
if val < beta :
beta = val
#print(depth)
return bestVal, bestAction
# 游戏
class Game(object):
def __init__(self):
self.board = Board()
self.current_player = None
# 生成玩家
def mk_player(self, p, take='X'): # p in [0,1]
if p==0:
return HumanPlayer(take)
else:
if playuse == 0:
return AIPlayer(take)
if playuse == 1:
return AIPlayer2(take)
# 切换玩家
def switch_player(self, player1, player2):
if self.current_player is None:
return player1
else:
return [player1, player2][self.current_player == player1]
# 打印赢家
def print_winner(self, winner): # winner in [0,1,2]
print(['Winner is player1','Winner is player2','Draw'][winner])
# 运行游戏
def run(self):
ps = input("Please select two player's type:\n\t0.Human\n\t1.AI\nSuch as:0 0\n")
p1, p2 = [int(p) for p in ps.split(' ')]
player1, player2 = self.mk_player(p1, 'X'), self.mk_player(p2, 'O') # 先手执X,后手执O
print('\nGame start!\n')
self.board.print_b() # 显示棋盘
while True:
self.current_player = self.switch_player(player1, player2) # 切换当前玩家
action = self.current_player.think(self.board) # 当前玩家对棋盘进行思考后,得到招法
self.current_player.move(self.board, action) # 当前玩家执行招法,改变棋盘
self.board.print_b() # 显示当前棋盘
if self.board.teminate(): # 根据当前棋盘,判断棋局是否终止
winner = self.board.get_winner() # 得到赢家 0,1,2
break
self.print_winner(winner)
print('Game over!')
self.board.print_history()
if __name__ == '__main__':
Game().run() |
aa540a6c38f81bb77831df7599c4f389743ec6f6 | BBorisov95/python_fund_homeworks | /03-Problem.py | 762 | 3.8125 | 4 | emails = {}
command = input()
while not command == 'Statistics':
command = command.split('->')
if command[0] == 'Add':
if command[1] in emails:
print(f'{command[1]} is already registered')
else:
emails[command[1]] = []
elif command[0] == 'Send':
emails[command[1]].append(command[2])
elif command[0] == 'Delete':
if command[1] in emails:
del emails[command[1]]
else:
print(f'{command[1]} not found!')
command = input()
print(f"Users count: {len(emails)}")
ordered_emails = dict(sorted(emails.items(), key=lambda x: (-len(x[1]), x[0])))
for user, value in ordered_emails.items():
print(user)
for email in value:
print(f' - {email}') |
6a743f698af4aa2fd4e36e1c7c2f5f5b17e98e02 | Enoch715/Python--guss-number | /gussnumber.py | 447 | 3.75 | 4 | import random
start = int(input('請決定隨機數字開始值: '))
end = int(input('請決定隨機數字結束值: '))
num = random.randint(start, end) #產生隨機數字
count = 0
while True:
user = int(input('請猜數字: '))
count += 1
if user == num:
print ('恭喜猜對了!!!!共猜測', count, '次')
break
elif user > num:
print('比答案大')
elif user < num:
print('比答案小')
print('已猜測第', count, '次')
|
f06b7841ea0aaf0a2df3d725bbdf80592acbeed7 | WallysonGalvao/Python | /CursoEmVideo/3 - TwentyOneToThirty/Challenge024.py | 260 | 4.125 | 4 | """Checking The First Letters Of A Text"""
print("Challenge 024")
print("Create a program that read the name of a city and tell if it begin or not with the name 'SANTO'")
city = str(input('What city do you born ?')).strip()
print(city[:5].upper() == 'SANTO')
|
236f0a571e35e0fdf22ef3b25fac867b200a2e73 | rajesh-zero/PracticePrograms | /Python/shortPyPrograms/4.py | 251 | 4.0625 | 4 | #String datatype
#slicing
mystr="hellO how are you bro kaisa chal raha hai zindagi main"
print(mystr[1])#it takes second letter
print(mystr[::-1])
print(len(mystr))#length of mystr
print(mystr[1:5:])
print(mystr.split('l'))
print(mystr.swapcase())
|
0a54a4f3e2d1cfca75e6b8a2b2c3b675e9a773ff | zeerakt/Python-Chatbot | /server.py | 1,672 | 3.65625 | 4 | """
A python Chatbot using Tkiner for the GUI
The program uses TCP sockets, with AF_INTET and SOCK_STREAM flags.
"""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
# Global variables
clients = {}
addresses = {}
HOST = 'localhost'
PORT = 12346
BUFSIZE = 1024
ADDRESS = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDRESS)
def listen():
""" Wait for incoming connections """
print("Waiting for connection...")
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Welcome to the Chatbot!" +
"Please enter your name", "utf8"))
addresses[client] = client_address
Thread(target = listenToClient, args = (client)).start()
def listenToClient(client):
""" Get client username """
name = client.recv(BUFSIZE).decode("utf8")
message = "Welcome to the Chatbot %s To exit please type {QUIT}" % name
client.send(bytes(message, "utf8"))
msg = "%s joined the catroom" % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZE)
if msg != bytes("{QUIT}", "utf8"):
sendMessage(msg, name+": ")
else:
client.send(bytes("{QUIT}", "utf8"))
client.close()
del clients[client]
sendMessage(bytes("%s left the chat room!" %name, "utf8"))
break
def sendMessage(msg, name=""):
""" send message to all users present in
the chat room"""
for client in clients:
client.send(bytes(name, "utf8") + msg)
if __name__ == "__main__":
SERVER.listen(5) #Five connection maximum
ACCEPT_THREAD = Thread(target=listen)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
|
d6c5a2e742f788ac11fda04bd27908d43747f0be | Jhordancito/Python | /ejercicio1ifelse.py | 303 | 4.03125 | 4 | print("Programa tendra una función llamada DEVUELVEMAX")
num1 = int(input("Introducir el primer Numero:" ))
num2 = int(input("Introducir el segundo Numero:" ))
def DevuelveMax(num1,num2):
if num1>num2:
print(f"El {num1} es mayor")
else:
print(f"El {num2} es mayor")
DevuelveMax(num1,num2) |
c6c811c24068fd92d82c190e42aa1d47fb2c3851 | anlzou/python-test | /python-course/P90_10_19/P90_6.py | 505 | 3.796875 | 4 | import math
#<0
def fun_1():
print("函数无解")
#=0
def fun_2(a,b):
x1 = -b/2*a
print("有一个解:",x1)
#>0
def fun_3(a,b,c):
x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
print("有两个解:%d,%d"%(x1,x2))
def fun(a,b,c):
p = b**2-4*a*c
if p < 0:
fun_1()
elif p == 0:
fun_2(a,b)
elif p > 0:
fun_3(a,b,c)
#主程序
a = float(input("a="))
b = float(input("b="))
c = float(input("c="))
fun(a,b,c)
|
b5d9fec765a1705e92aa13f1431f911f851313f5 | Yakima-Teng/Salute_Python | /python_basic_02/arithmetic_operator_06/arithmetic_operator.py | 10,094 | 4 | 4 | #!/usz/bin/env python
# -*- coding:utf-8 -*-
"""
@file : arithmetic_operator.py
@author : zgf
@brief : python算数运算符
@attention : life is short,I need python
"""
# ========================================= 算术运算符 =========================================
# 和数学中的运算符的优先级一致,在 Python 中进行数学计算时,同样也是:
# 先乘除后加减
# 同级运算符是 从左至右 计算
# 可以使用 () 调整计算的优先级
# 加减乘除取模幂
# 整数与浮点数运算结果是浮点数
# 除法运算的结果是浮点数
# flag = True
flag = False
if flag:
a = 10
b = 20
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b) # 取模 % 取余数 返回除法的余数 9 % 2 = 1
print(a ** b) # 幂 又称次方、乘方,2 ** 3 = 8
print(a // b) # 取整除 返回除法的整数部分(商) 9 // 2 输出结果 4
print(13 // 5) # 整数商 x/y 向下取整数
x = 1
print(-x) # 取反
# 在 Python 中 * 运算符还可以用于字符串,计算结果就是字符串重复指定次数的结果
print("-" * 50)
print(1 + 1.5, type(1 + 1.5)) # 2.5 <class 'float'>
print(2 / 5, type(2 / 5)) # 0.4 <class 'float'>
print(8 / 4, type(8 / 4)) # 2.0 <class 'float'>
# ========================================= 比较运算符 =========================================
#
# flag = True
flag = False
if flag:
a = 10
b = 20
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
# 非空
ls = [1]
if ls: # 数据结构不为空、变量不为0、None、False 则条件成立
print("非空")
else:
print("空的")
# ========================================= 逻辑运算 =========================================
# 与运算,True和False进行与运算结果应该为False
# 或运算,True和False进行或运算结果应该为True
# 非运算,将结果置非,即True变False,False变True
# 复合逻辑运算的优先级 非 > 与 > 或
# 优先级 ()> not >and>or
# 0对应的bool值为False,非0都为True
# x or y if x is True,return x
# 求and与or相反
# flag = True
flag = False
if flag:
a = 10
b = 8
c = 12
print((a > b) and (b > c)) # 与
print((a > b) or (b > c)) # 或
print(not (a > b)) # 非
print(a == b) # 相等
print(True and False)
print(True or False)
print(not (True and False))
# bool :用于将给定参数转换为布尔类型,如果没有参数,返回False。 ***
print(bool(1 < 2 and 3 > 4 or 5 < 6 and 9 > 2 or 3 > 1))
print(bool("fdsjkfl"))
"""逻辑运算作为指示条件"""
n = 2800
while True:
m = eval(input("请输入一个正整数:"))
if m == n:
print("你猜对啦")
break
elif m > n:
print("太大了")
else:
print("太小了")
"""逻辑运算作为掩码"""
import numpy as np
x = np.array([[1, 3, 2, 5, 7]]) # 定义 numpy数组
print(x > 3) # [[False False False True True]]
print(x[x > 3]) # [5 7]
"""数字逻辑运算"""
# x or y if x is True,return x
# x and y if x is True,return y
print(1 or 2) # 1
print(1 and 2) # 2
print(5 or 2) # 5
print(5 and 2) # 2
print(0 or 3 and 5 or 4) # 5
# ========================================= 赋值运算 =========================================
# 使用 = 可以给变量赋值
# flag = True
flag = False
if flag:
a = 10
b = 20
a += b
print(a)
a -= b
print(a)
a *= b
print(a)
a /= b
print(a)
# ========================================= 赋值运算 - 面试题 =========================================
# 面试题 += 列表
# 列表变量使用 + 不会做相加再赋值的操作 ! 本质上是在调用列表的 extend 方法
# flag = True
flag = False
if flag:
def demo(num, num_list):
print("函数开始")
# num = num + num
num += num
# 列表变量使用 + 不会做相加再赋值的操作 !
# num_list = num_list + num_list
# 本质上是在调用列表的 extend 方法
num_list += num_list
# num_list.extend(num_list)
print(num)
print(num_list)
print("函数完成")
gl_num = 9
gl_list = [1, 2, 3]
demo(gl_num, gl_list)
print(gl_num)
print(gl_list)
# ========================================= 身份运算 =========================================
# is比较id,判断的是两个变量的id值是否相同。是判断两个标识符是不是引用同一个对象
# is not 是判断两个标识符是不是引用不同对象
# ==比较值
# 在内存中id都是唯一的,如果两个变量指向的值的id相同,就证明他们在内存中是同一个。
# 与None值比较 判断某个变量是否为None时,请使用is 而不是==
# 如果is是True, == 一定是True。
# flag = True
flag = False
if flag:
a = "sdasdsadasdasdasdasdasdddddddddddddddddddddddddddfsafdafaag.62952a9fadggagag"
b = "sdasdsadasdasdasdasdasdddddddddddddddddddddddddddfsafdafaag.62952a9fadggagag"
print(a is b) # 用于判断 两个变量 引用对象是否为同一个
print(a is None)
print(a == b) # 用于判断引用变量的值 是否相等
print(a is not b)
# ========================================= 存在运算 =========================================
# 元素 in 列表/字符串
# flag = True
flag = False
if flag:
cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print("BMW" in cars)
print("BENZ" in cars)
print("BMW" not in cars)
print("BENZ" not in cars)
# ========================================= 数学运算操作函数 - abs() =========================================
# 求绝对值 abs()
# flag = True
flag = False
if flag:
print(abs(-5)) # 5
print(abs(3 + 4j)) # 5.0 # 对复数a+bj 执行的是求模运算(a^2+b^2)^0.5
# ========================================= 数学运算操作函数 - pow(x,n) =========================================
# 幂次方 pow(x,n)
# pow:求x**y次幂。(三个参数为x**y的结果对z取余) **
# flag = True
flag = False
if flag:
print(pow(2, 5)) # 32 # pow(x,n) x的n次方 等价于x**n
print(pow(2, 5, 3)) # 2 # 2^5 % 3 更快速
# ========================================= 数学运算操作函数 - round(x,n) =========================================
# 四舍五入 round(x,n) 保留浮点数的小数位数,默认保留整数,四舍五入。
# flag = True
flag = False
if flag:
a = 1.618
print(round(a)) # 2 默认四舍五入为整数
print(round(a, 2)) # 1.62 参数2表示四舍五入后保留2位小数
print(round(a, 5)) # 1.618 位数不足,无需补齐
# ========================================= 数学运算操作函数 - divmod(x,y) =========================================
# 整数商和模运算 divmod(x,y)
# 等价于返回二元元组(x//y,x % y)
# flag = True
flag = False
if flag:
# divmod:计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)。
print(divmod(13, 5)) # (2, 3) 较(x//y,x % y)更快,只执行了一次x/y
# 分页。
# 103 条数据,你每页显示12 条数据,你最终显示多少页。
print(divmod(103, 12))
# ========================================= 数学运算操作函数 - max( ) min( ) =========================================
# 序列最大/最小值 max( ) min( )
# flag = True
flag = False
if flag:
# max:返回可迭代对象的最大值(可加key,key为函数名,通过函数的规则,返回最大值)。
a = [3, -2, 3, 6, 9, 4, 5]
print("max:", max(a)) # max:9
# min:返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)。
print("min:", min(a)) # min:-2
print("min:", min(a, key=abs)) # min:-2
# 求出年龄最小的那个元组
ls = [("alex", 1000), ("太白", 18), ("wusir", 500)]
min1 = min([i[1] for i in ls])
for i in ls:
if i[1] == min1:
print(i)
def func(x):
return x[1] # 1000 18 500
print(min([("alex", 1000), ("太白", 18), ("wusir", 500)], key=func))
# 1,他会将iterable的每一个元素当做函数的参数传进去。
# 2,他会按照返回值去比较大小。
# 3,返回的是 遍历的元素 x.
# [('alex',1000),('太白',18),('wusir',500)]
# ========================================= 数学运算操作函数 - sum(x) =========================================
# 求和sum(x)
# sum:对可迭代对象进行求和计算(可设置初始值)
# flag = True
flag = False
if flag:
print(sum((1, 2, 3, 4, 5))) # 15
print(sum([1, 2, 3, 4, 100, 101]))
# sum(iterable,start_num)
# iterable – 可迭代对象,如:列表(list)、元组(tuple)、集合(set)、字典(dictionary)。
# start – 指定相加的参数,如果没有设置这个值,默认为0。
# 也就是说sum() 最后求得的值 = 可迭代对象里面的数加起来的总和(字典:key值相加) + start的值(如果没写start的值,则默认为0)
print(sum([1, 2, 3, 4, 100, 101], 100))
print(sum({1: 5, 2: 6, 3: 7})) # 6 in dictionary key
print(sum([int(i) for i in [1, "2", 3, "4", "100", 101]]))
# ========================================= 数学运算操作函数 - 借助科学计算库 math\scipy\numpy =========================================
# 借助科学计算库 math\scipy\numpy
# flag = True
flag = False
if flag:
import math # 导入库
import numpy as np
print(math.exp(1)) # 2.718281828459045 指数运算 e^x
print(math.log2(2)) # 1.0 对数运算
print(math.sqrt(4)) # 2.0 开平方运算 等价于4^0.5
a = [1, 2, 3, 4, 5]
print(np.mean(a)) # 3.0 求均值
print(np.median(a)) # 3.0 求中位数
print(np.std(a)) # 1.4142135623730951 求标准差
|
6b972f353091c2a416ae1151bf54ae187a082f82 | Shalin-Shekhar/python-challenge | /PyBank/main.py | 2,193 | 4.125 | 4 | # First we'll import the os and csv module
# This will allow us to create file paths across operating systems
import os
import csv
# Write a function that returns the arithmetic average for a list of numbers
def average(numbers):
length = len(numbers)
total = 0.0
for number in numbers:
total += number
return round(total / length,2)
# Create a CSV file handler
csvpath = os.path.join(".", "Resources", "budget_data.csv")
# Lists to store data
date = []
pnl = []
revenue = 0
total_mnths = 0
total_amt = 0
max_profit = 0
profit_year = ""
max_loss = 0
loss_year = ""
avg_amt = 0
# Open file to read
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# Identify the header
header = next(csvreader)
for row in csvreader:
# Add Date
date.append(row[0])
# Add price
pnl.append(float(row[1]))
total_amt += int(row[1])
revenue = int(row[1])
if revenue > max_profit:
max_profit = revenue
profit_year = row[0]
if revenue < max_loss:
max_loss = revenue
loss_year = row[0]
# do all the work on data
total_mnths = len(date)
avg_amt = average(pnl)
print(F'Financial Analysis')
print(F'----------------------------')
print(F'Total Months: {total_mnths}')
print(F'Total: ${total_amt}')
print(F'Average Change: ${avg_amt}')
print(F'Greatest Increase in Profits: {profit_year} (${max_profit})')
print(F'Greatest Decrease in Profits: {loss_year} (${max_loss})')
# Set variable for output file
output_file = open("Financial Analysis.txt","a")
# write to the file
print(F'Financial Analysis',file = output_file)
print(F'----------------------------',file = output_file)
print(F'Total Months: {total_mnths}',file = output_file)
print(F'Total: ${total_amt}',file = output_file)
print(F'Average Change: ${avg_amt}',file = output_file)
print(F'Greatest Increase in Profits: {profit_year} (${max_profit})',file = output_file)
print(F'Greatest Decrease in Profits: {loss_year} (${max_loss})',file = output_file)
# Closing a file "output_file.txt"
output_file.close() |
28274d71e2c20ba52f965a3179a3d62169bc6823 | Novellino89/Testing-program | /Poker di dadi.py | 7,965 | 3.5 | 4 | import random as r
import os
#from Definizione_funzioni import tira,calcola_risultato,Visualizza_Ottenuto
#creazione funzione tira
def tira():
r.seed()
a=r.randint(1,6)
return a
#creazione funzione calcolo risultato
def calcola_risultato(tiro):
coppia=0
tris=0
somma=0
vincente=0
checkcoppia=0
checktris=0
due=0
tre=0
for i in range(1,7):
if (tiro.count(i) == 5):
numero=i
somma=numero*5
vincente=8
return vincente,somma
break
if(tiro.count(i) == 4):
numero=i
somma=numero*4
vincente=7
return vincente,somma
break
if(tiro.count(i) == 3):
numero=i
tre=1
tris=i
if(tiro.count(i) == 2):
numero=i
due+=1
coppia=i
if tre==1 and checktris==0:
checktris=1
vincente=3
somma=i*3
if tre==1 and due==1 and checktris==1:
somma=(tris*3)+(coppia*2)
vincente=6
return vincente,somma
break
if due==1 and checkcoppia==0:
checkcoppia=1
numero=i
somma=numero*2
vincente=1
if due==2 and checkcoppia==1:
somma=somma+(i*2)
vincente=2
return vincente,somma
break
if (tiro[0]==1 and tiro[1]==2 and tiro[2]==3 and tiro[3]==4 and tiro[4]==5):
vincente=4
return vincente,somma
break
elif (tiro[0]==2 and tiro[1]==3 and tiro[2]==4 and tiro[3]==5 and tiro[4]==6):
vincente=5
return vincente,somma
break
return vincente,somma
def Visualizza_Ottenuto(vincente,avversario):
if vincente==0 and avversario==0:
print('purtroppo il tuo lancio non vale nulla \n')
elif vincente==1 and avversario==0:
print('Hai ottenuto una coppia\n')
elif vincente==2 and avversario==0:
print('Hai ottenuto una doppia coppia\n')
elif vincente==3 and avversario==0:
print('Hai ottenuto un tris\n')
elif vincente==4 and avversario==0:
print('Hai ottenuto una scala di 5\n')
elif vincente==5 and avversario==0:
print('Hai ottenuto una scala di 6\n')
elif vincente==6 and avversario==0:
print('Hai ottenuto un full\n')
elif vincente==7 and avversario==0:
print('Hai ottenuto 4 dadi uguali\n')
elif vincente==8 and avversario==0:
print('Hai ottenuto 5 dadi uguali, è strabiliante\n')
elif vincentea==0 and avversario==1:
print('Il tuo avversario non ha ottenuto nulla\n')
elif vincentea==1 and avversario==1:
print('Il tuo avversario ha una coppia\n')
elif vincentea==2 and avversario==1 :
print('Il tuo avversario ha una doppia coppia\n')
elif vincentea==3 and avversario==1:
print('Il tuo avversario ha un tris\n')
elif vincentea==4 and avversario==1:
print('Il tuo avversario ha una scala di 5\n')
elif vincentea==5 and avversario==1:
print('Il tuo avversario ha una scala di 6\n')
elif vincentea==6 and avversario==1:
print('Il tuo avversario ha un full\n')
elif vincentea==7 and avversario==1:
print('Il tuo avversario ha 4 dadi uguali\n')
elif vincentea==8 and avversario==1:
print('Il tuo avversario ha 5 dadi uguali, spera nella tua buona stella\n')
checkfine=1
piatto=0
#Inizio programma
while True:
if checkfine==1:
denaro=r.randint(150,400)
denaroa=r.randint(250,600)
print('Attualmente hai nel portafoglio' , denaro,'Euro')
print('Il tuo avversario ha nel portafoglio',denaroa,'Euro')
else:
print('Attualmente hai nel portafoglio' , denaro,'Euro')
print('Il tuo avversario ha nel portafoglio',denaroa,'Euro')
ripetizione=0
tiroa=[]
tiro=[]
valore=[]
try:
scelta=input('Vuoi giocare a poker di dadi? S/N ')
except:
print('Inserisci o S per giocare ancora o N per uscire \n')
if scelta=='s' or scelta=='S':
os.system('cls')
if denaro<=0:
print('Non hai più soldi da scommettere e non possiamo più farti giocare. Ci spiace ma deve abbandonare l"edificio.')
break
if denaroa<=0:
print('Hai mandato sul lastrico il tuo avversario! Ma si sta avvicinando un"altra persona al tavolo.')
denaroa=r.randint(150,600)
continue
puntata=input('\n Inserisci quanto vuoi scommettere per questa puntata ')
puntata=int(puntata)
if puntata>denaro:
print('Non hai abbastanza soldi')
continue
denaro-=puntata
if denaroa<puntata:
print('Il tuo avversario accetta ma ha meno soldi della tua posta, mette tutto quello che ha.')
piatto=puntata+denaroa
denaroa=0
else:
print("l'avversario accetta la posta \n")
denaroa-=puntata
piatto=puntata*2
#lancio dei dadi e ordinamento
for i in range(5):
tiro.append(tira())
tiro.sort()
print(tiro,"\n")
vincente,somma=calcola_risultato(tiro)
Visualizza_Ottenuto(vincente,0)
try:
scelta1=input('Vuoi Ritirare qualche dado? ')
except:
print('Inserisci o S per ritirare o N per per continuare.')
if scelta1=='s' or scelta1=='S' or scelta1=='Si' or scelta1=='S ' or scelta1=='s ':
# taking multiple inputs at a time
try:
sostituisci = [int(x) for x in input("Che dadi vuoi ritirare?: ").split()]
print("I dadi che vuoi ritirare sono: ", sostituisci,"\n")
except:
print('Inserisci per favore almeno un valore numerico.')
for item in range(0,len(sostituisci)):
if sostituisci[item] in tiro:
tiro[tiro.index(sostituisci[item])]=tira()
print('Il tuo nuovo tiro è \n ' )
tiro.sort()
print(tiro,"\n")
if scelta1=='n' or scelta1=='N' or scelta1=='NO' or scelta1=='no' or scelta1=='n 'or scelta1=='N ':
ripetizione=1
#conteggio valori
vincente,somma=calcola_risultato(tiro)
if ripetizione!=1:
Visualizza_Ottenuto(vincente,0)
for i in range(5):
tiroa.append(tira())
tiroa.sort()
print('Questo è il tiro del tuo avversario\n')
print(tiroa,"\n")
#conteggio valori avversario
vincentea,sommaa=calcola_risultato(tiroa)
Visualizza_Ottenuto(vincente,1)
if vincente>vincentea:
print('Congratulazioni, hai vinto!\n')
denaro+=piatto
checkfine=0
elif vincente<vincentea:
print('Peccato, hai perso!\n')
denaroa+=piatto
checkfine=0
else:
if somma>sommaa:
print('Congratulazioni, hai vinto!\n')
denaro+=piatto
checkfine=0
elif somma<sommaa:
print('Peccato, hai perso!\n')
denaroa+=piatto
checkfine=0
else:
print('Il punteggio è finito in parità, è molto raro ma può capitare. Giocate ancora per spareggiare.\n')
if casuale==1:
denaro+=piatto
denaroa+=piatto
checkfine=0
elif casuale==2:
denaro+=piatto
denaroa+=(piatto+piattosuperiore)
checkfine=0
#aggiungo commento per la sincronizzazione di Github.
elif scelta=='n' or scelta=='N':
print('grazie per aver giocato al poker di dadi')
break
else:
print('Inserisci S per giocare ancora o N per uscire')
continue
|
f1438c2a955e4f0952b79d5da31b4ef6cbcc1508 | lopeztaelisa/CS2302 | /hashtbl.py | 3,360 | 3.8125 | 4 | #Author: Elisabet Lopez
#CS 2302 10:30AM
#Instructor: Diego Aguirre
#T.A.: Manoj Pravaka Saha
#Lab Assignment 4 Option A
#Last modified: November 11, 2018
#Purpose: This program creates a hash table to store words and their vector description (embedding).
#The hash table solves collisions by chaining. This program includes multiple hash functions. This
#program also computes the load factor of a hash table.
#class to create hash table node
class HTNode:
def __init__(self, word, embedding, next):
self.word = word
self.embedding = embedding
self.next = next
#class to create hash table; includes hash functions
class HashTable:
def __init__(self, table_size):
self.table = [None] * table_size
def hash1(self, k):
word_int = 0
for char in k:
word_int += ord(char) #adds up ASCII values of each character
return word_int % len(self.table)
def hash2(self, k):
word_base_26 = 0
for i in range(len(k)-1, -1, -1):
char_base_26 = ord(k[i].lower())-97 #converts character base 26 to base 10
char_base_26 = abs(char_base_26) #handles special characters that end up as negative numbers
word_base_26 += char_base_26 * (26 ** len(k)-1-i) #converts entire word base 26 to base 10
if word_base_26 >= len(self.table):
word_base_26 = 0
return word_base_26
#better hash function
def hash3(self, k):
word_base_26 = 0
for i in range(len(k)-1, -1, -1):
char_base_26 = ord(k[i].lower())-97 #converts character base 26 to base 10
char_base_26 = abs(char_base_26) #handles special characters that end up as negative numbers
word_base_26 += char_base_26 * (26 ** len(k)-1-i) #converts entire word base 26 to base 10
return word_base_26 % len(self.table)
#creates and populates hash table
def create_HT(filename):
with open(filename) as file:
f = file.readlines()
file.close()
size = (400000//10)+1
H = HashTable(size) #initializes hash table
for line in f:
if line[0].isalpha() == False: #if word does not start with alphabetic character
continue #ignore
line = line.strip().split() #remove whitespace and separate each word
word = line.pop(0) #word is first item in each line
embedding = line #list of numbers
insert(H, word, embedding) #insert word in hash table
return H
#inserts a word into hash table
def insert(H, word, embedding):
loc = H.hash3(word) #get corresponding bucket
H.table[loc] = HTNode(word, embedding, H.table[loc]) #create node and insert in table
#computes load factor (average list size) of a hash table
def load_factor(h):
elem = 0
#traverses buckets
for i in range(len(h.table)):
temp = h.table[i]
while temp != None: #traverses linked list in bucket
elem += 1
temp = temp.next
return elem/len(h.table)
#prints all buckets and their contents from hash table
def print_HT(H):
for bucket in range(len(H.table)):
print(str(bucket) + ": ", end=" ")
temp = H.table[bucket]
while temp != None:
print(temp.word, end=" ")
temp = temp.next
print('\n')
#counts how many empty buckets there are in hash table
def empty_buckets(H):
empty = 0
for i in range(len(H.table)):
if H.table[i] == None:
empty += 1
return empty
H = create_HT("glove.6B.50d.txt") #creates hash table
print_HT(H) #prints hash table contents
print(empty_buckets(H)) #prints number of empty buckets
print(load_factor(H)) #prints load factor of hash table
|
c0963368d33ad9ea54375931c52fa9038b7451a1 | stoicio/whiteboard | /python/sorting/faster_sorts.py | 637 | 4.4375 | 4 | from data_structures import heap_pq
def heap_sort(list_to_sort, sorting_function):
""" Given a list and a sorting function, uses heap sort to sort the list
Args:
list_to_sort (list) : List containing any abstract data type
sorting_function (function): A function which takes in two args and returns True if
* first is smaller than second - Ascending order sort
* first is greater than second - Descending order sort
Return:
sorted_list (list)
"""
q = heap_pq.HeapPriorityQueue(sorting_function, list_to_sort)
sorted_list = [q.pop() for i in range(len(q))]
return sorted_list
|
404a1437aaf3c148054ee7c2cf8648cc05e52156 | yxpku/anand-python | /chapter2/pro8-min_max.py | 421 | 3.96875 | 4 | #Python has built-in functions min and max to compute minimum and maximum of a given list. Provide an implementation for these functions. What happens when you call your min and max functions with a list of strings?
def min(list):
list.sort()
return list[0]
def max(list):
list.sort()
return list[-1]
print min([1,2,4,6])
print min(['hai','shihas','ashna'])
print max([1,2,4,6])
print max(['hai','shihas','ashna'])
|
3bde04eec167ff1473858c0b929b902dbe023489 | mkp-in/codefights-py | /intro/level2/adjacent_elements_product.py | 358 | 3.703125 | 4 | #
# https://app.codesignal.com/arcade/intro/level-2/xzKiBHjhoinnpdh6m
#
def adjacentElementsProduct(inputArray):
product = -32768
for i in range(0, len(inputArray)-1):
if inputArray[i] * inputArray[i+1] > product:
product = inputArray[i] * inputArray[i+1]
return product
print(adjacentElementsProduct([3, 6, -2, -5, 7, 3])) |
56aefcec8169a9a3853ffa03a585b3aaa4f46423 | samuelyusunwang/PythonStudy | /Think Python/Exercise/Ex_8_5.py | 237 | 4.125 | 4 | # count
def count(word, letter):
'''
count the number of letter in word
'''
count = 0
for x in word:
if x == letter:
count = count + 1
return count
# test code
print(count('abcdabcda', 'a')) |
fe06b9af5e1cee069cc4dbb6b490914cda87884b | Sandy4321/Effective-Quadratures | /effective_quadratures/computestats.py | 3,384 | 4.21875 | 4 | #!/usr/bin/env python
"""Computing Statistics from Polynomial Expansions"""
import numpy as np
from utils import error_function
class Statistics(object):
"""
This class defines a Statistics object
:param numpy matrix coefficients: polynomial coefficients (can be from any of the methods)
:param IndexSet index_set: The index set corresponding to the polynomial basis that was used to compute the coefficients
"""
# constructor
def __init__(self, coefficients, index_set):
self.coefficients = coefficients
self.index_set = index_set
def getMean(self):
"""
Computes the mean of a polynomial expansion using its coefficients.
:param Statistics self: An instance of the Statistics class
:return: mean
:rtype: double
**Notes**
The mean is simply the first coefficient of the expansion.
"""
coefficients = self.coefficients
mean = coefficients[0,0]
return mean
def getVariance(self):
"""
Computes the variance of a polynomial expansion using its coefficients.
:param Statistics self: An instance of the Statistics class
:return: variance
:rtype: double
**Notes**
The variance is the sum of the squares of all the coefficients except the first coefficient.
"""
coefficients = self.coefficients
m, n = coefficients.shape
if m > n:
coefficients = coefficients.T
variance = np.sum(coefficients[0][1:m]**2)
return variance
# Function that computes first order Sobol' indices
def getFirstOrderSobol(self):
"""
Computes the first order Sobol indices.
:param Statistics self: An instance of the Statistics class
:return: first_order_sobol_indices
:rtype: numpy ndarray
"""
coefficients = self.coefficients
m, n = coefficients.shape
if m > n:
coefficients = coefficients.T
index_set = self.index_set
# Allocate memory!
index_set = index_set.getIndexSet()
index_set = np.mat(index_set)
m, dimensions = index_set.shape
variance = self.getVariance()
if dimensions == 1:
utils.error_function('ERROR: Sobol indices can only be computed for parameter studies with more than one parameter')
else:
index_set_entries = m
local_variance = np.zeros((index_set_entries, dimensions))
first_order_sobol_indices = np.zeros((dimensions))
# Loop for computing marginal variances!
for j in range(0, dimensions):
for i in range(0, index_set_entries): # no. of rows
# If the index_set[0,j] is not zero but the remaining are...
remaining_indices = np.arange(0, dimensions)
remaining_indices = np.delete(remaining_indices, j)
if(index_set[i,j] != 0 and np.sum(index_set[i, remaining_indices] ) == 0):
local_variance[i, j] = coefficients[0][i]
# Now take the sum of the squares of all the columns
for j in range(0, dimensions):
first_order_sobol_indices[j] = (np.sum(local_variance[:,j]**2))/(variance)
return first_order_sobol_indices
|
2cf353986b37e9d0f18a8bda9b38ecda1c9660fe | sunandinis/Rosalind-Problems | /Hamming Distance.py | 394 | 3.59375 | 4 | def hamming_distance():
file=open('/Users/dhruvarora/Downloads/rosalind_hamm (1).txt', 'r')
fastafile = [line.rstrip('\n') for line in file.readlines()]
s = fastafile[0]
t = fastafile[1]
hamming_count = 0
for nucleotide in range(0,len(s)):
if s[nucleotide] != t[nucleotide]:
hamming_count = hamming_count + 1
print(hamming_count)
hamming_distance()
|
a31f963abe87e2be1dd1004975f2fb29a750c374 | Sarayaar/python01 | /Assignments/sr.assignment3.1.py | 192 | 3.609375 | 4 | hrs = float(raw_input("Enter Hours: "))
rte = float(raw_input("Rate: "))
if hrs > 40:
extra_hrs = hrs - 40
tnh = rte * 1.5
total = (rte * 40) + (extra_hrs * tnh)
else:
total = hrs * rte |
3cb3949fa1cbba0c129190d909a0b62eaedcb6f4 | gmroughton/advent-of-code | /2020/dec_8.py | 2,725 | 3.9375 | 4 | import copy
from pprint import pprint
def program_to_list(filename):
"""
Convert a file into a list representing commands in an assembly-like language
:param filename: File containing instruction set
:return: The program loaded into memory as a list of instructions
"""
output = []
with open(filename) as f:
for line in f:
vals = line.split()
output.append([vals[0], int(vals[1].strip('+'))])
return output
TEST_PROGRAM = program_to_list("files/test_infinite_program.txt")
FULL_PROGRAM = program_to_list("files/infinite_program.txt")
def run_program(program):
"""
Run a program and return the current acc value and a boolean representing
whether or not it fully completed or ran into an infinit loop
:param program: List of instructions
:return: Sum, True if runs to end of instruction set, False otherwise
"""
global_sum = 0
line_ptr = 0
repeat_lines = []
while True:
if line_ptr in repeat_lines:
return global_sum, False
elif line_ptr > len(program) - 1:
return global_sum, True
instruction, value = program[line_ptr]
repeat_lines.append(line_ptr)
if instruction == "acc":
global_sum += value
line_ptr += 1
elif instruction == "nop":
line_ptr += 1
elif instruction == "jmp":
line_ptr += value
def problem_fifteen():
"""
Run the program as is and return the acc when the first loop is encountered
:return: Value of accumulator on program termination
"""
return run_program(FULL_PROGRAM)[0]
def problem_sixteen():
"""
Run the program, but change one nop / jmp at a time to see if it results in
a new instruction set that allows the program to complete normally.
:return: Value of accumulator for instruction set that successfully runs
"""
program = FULL_PROGRAM
line_ptr = 0
while True:
instruction, value = program[line_ptr]
if instruction == "acc":
line_ptr += 1
elif instruction == "nop":
new_program = copy.deepcopy(program)
new_program[line_ptr][0] = "jmp"
final_sum, completed = run_program(new_program)
if completed:
return final_sum
line_ptr += 1
elif instruction == "jmp":
new_program = copy.deepcopy(program)
new_program[line_ptr][0] = "nop"
final_sum, completed = run_program(new_program)
if completed:
return final_sum
line_ptr += value
print(f"FIFTEEN: {problem_fifteen()}")
print(f"SIXTEEN: {problem_sixteen()}") |
e68b722216be4abb5ab7de9f93e69387a2564ac0 | weichuntsai0217/work-note | /programming-interviews/epi-in-python/ch11/12_7_FINDTHE_MIN_AND_MAX_SIMULTANEOUSLY.py | 1,518 | 4.03125 | 4 |
def find_min_max(x):
"""
The time complexity is O(n)
"""
if not x: return None
if len(x) == 1:
return x[0], x[0] # the first is min and the second is max
min_val = x[0]
max_val = x[0]
for i in xrange(1, len(x)):
if x[i] < min_val:
min_val = x[i]
elif x[i] > max_val:
max_val = x[i]
def min_max(a, b):
if a < b:
return a, b
return b, a
def find_min_max_fast(x):
"""
The time complexity is O(n)
Note that even though find_min_max_fast and find_min_max have the same order of time complexity,
If you count the comparison operations carefully, you would find that
find_min_max_fast takes O(3n/2 - 2) comparisons and
find_min_max takes O(2n - 2) comparisons
"""
import math
if not x: return None
if len(x) == 1:
return x[0], x[0] # the first is min and the second is max
min_val, max_val = min_max(x[0], x[1])
for i in xrange(2, (len(x) - 1), 2):
smaller, larger = min_max(x[i], x[i+1])
min_val = min(smaller, min_val)
max_val = max(larger, max_val)
if len(x) & 1:
# the length of x is odd.
min_val = min(x[-1], min_val)
max_val = max(x[-1], max_val)
return min_val, max_val
def get_input(case=0):
x = [3,2,5,1,2,4]
ans_min = 1
ans_max = 5
if case == 0:
pass
return x, ans_min, ans_max
if __name__ == '__main__':
for case in xrange(1):
x, ans_min, ans_max = get_input(case)
res_min, res_max = find_min_max_fast(x)
print(res_min == ans_min)
print(res_max == res_max)
|
ce89d666264232f9ba2012360cfdf595d036d530 | rubakhan9430/PythonTraining | /Week4/practice3.py | 139 | 4.03125 | 4 | value = float(input('Enter a number:'))
while (value > 10 and value < 100):
value = float(input('Enter a number again:'))
print(value)
|
5b92f2ee24280cdcb9e78ce2b0f7703905528941 | Nithanaroy/PythonSnippets | /Uber2.py | 574 | 3.84375 | 4 | """
Given two arrays a and b,
for each i in b:
find the number of numbers in a greater than a[i]
"""
def countGreaterNumbers(a, b):
c = sorted(a)
res = []
for i in b:
res.append(findGreater2(c, a[i - 1]))
return res
def findGreater(a, n):
count = 0
for i in a:
if i > n:
count += 1
return count
def findGreater2(a, n):
import bisect
# index = bisect.bisect_left(a, n)
index = bisect.bisect_right(a, n)
return len(a) - index
print countGreaterNumbers([3, 4, 1, 2, 4, 6], [1, 2, 3, 4, 5, 6])
|
7cebc529be2c188720591880ce65d001d63870a5 | zhtsh/Learning-Algorithms | /python/Sort.py | 3,074 | 3.859375 | 4 | #! /usr/bin/python
# coding=utf8
import sys
import time
import random
def select_sort(data_list):
print("starting select sorting........")
begin_time = time.time()
n = len(data_list)
for i in range(n):
k = i
is_sorted = True
for j in range(i+1, n):
if data_list[j] < data_list[k]:
k = j
if data_list[j] < data_list[j-1]:
is_sorted = False
if is_sorted:
break
if k != i:
data_list[i], data_list[k] = data_list[k], data_list[i]
print("elasped time: {} seconds".format(time.time()-begin_time))
print("select sort result: ")
print(data_list)
def bubble_sort(data_list):
print("starting bubble sorting........")
begin_time = time.time()
n = len(data_list)
for i in range(n-1, -1, -1):
is_swaped = False
for j in range(0, i):
if data_list[j] > data_list[j+1]:
data_list[j], data_list[j+1] = data_list[j+1], data_list[j]
is_swaped = True
if not is_swaped:
break
print("elasped time: {} seconds".format(time.time()-begin_time))
print("bubble sort result: ")
print(data_list)
def insert_sort(data_list):
print("starting insert sorting........")
begin_time = time.time()
n = len(data_list)
for i in range(1, n):
i_value = data_list[i]
k = i
for j in range(i-1, -1, -1):
if data_list[j] > i_value:
data_list[j+1] = data_list[j]
k = j
else:
break
if k != i:
data_list[k] = i_value
print("elasped time: {} seconds".format(time.time()-begin_time))
print("insert sort result: ")
print(data_list)
def quick_sort(data_list, left, right):
if left < right:
p = partition(data_list, left, right)
quick_sort(data_list, left, p)
quick_sort(data_list, p+1, right)
def partition(data_list, left, right):
pivot = data_list[(left + right) / 2]
i = left
j = right
while True:
while data_list[i] < pivot:
i += 1
while data_list[j] > pivot:
j -= 1
if i >= j:
return j
data_list[i], data_list[j] = data_list[j], data_list[i]
if __name__ == '__main__':
n = int(sys.argv[1])
data_list = [random.randint(1, 10000) for i in range(n)]
# data_list.sort(reverse=True)
print("source data list: ")
print(data_list)
select_data_list = list(data_list)
select_sort(select_data_list)
print("")
bubble_data_list = list(data_list)
bubble_sort(bubble_data_list)
print("")
insert_data_list = list(data_list)
insert_sort(insert_data_list)
print("")
quick_data_list = list(data_list)
print("starting quick sorting........")
begin_time = time.time()
quick_sort(quick_data_list, 0, n-1)
print("elasped time: {} seconds".format(time.time()-begin_time))
print("quick sort result: ")
print(quick_data_list)
print("") |
3b310c770336c7cd210af8b13e6aa2bf504f4ed6 | tdsymonds/codeeval | /python/easy/(92) penultimate-word.py | 507 | 3.515625 | 4 | import sys
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
if line:
line = line.strip()
# find the last space and trim
last_space = line[::-1].find(' ')
line = line[:-last_space-1]
# find the next last space and trim
# if needed.
last_space = line[::-1].find(' ')
if last_space == -1:
print line
else:
print line[-last_space:] |
6f33db467efb2c903866e39352da668b55b65260 | SteveVallay/coding-bat-py | /coding_bat/w2/string_match.py | 321 | 3.640625 | 4 | def string_match(a,b):
la = len(a)
lb = len(b)
l = min(la,lb)
s = 0
for i in range(0,l-1):
print 'ai+2', a[i:i+2]
if a[i:i+2] == b[i:i+2]:
s+=1
return s
def min(a,b):
if a > b:
return b
else:
return a
print string_match('abcdef','abdcef')
|
978d6ddfe90450d3845c26fb084b9a944e4ff593 | Yosh23/python-scraper | /scrape.py | 315 | 3.546875 | 4 | from bs4 import BeautifulSoup as bs
import lxml
with open('test.html', 'r') as html_file:
content = html_file.read()
soup = bs(content, 'lxml')
titles = soup.find_all('title')
h1s = soup.find_all('h1')
for title in titles:
print(title.text)
for h1 in h1s:
print(h1.text) |
fdead48fb02d6c959e513343e39d6ee2d062f7db | yaposebastien/ProgContact | /contact.py | 420 | 3.671875 | 4 | #!/usr/bin/env python3.6
"""
Ce Script est une reecriture du programme d'un carnet d'addresse en Python.
L'objectif est de sauvegarder les contacts permanemment d'un fichier texte et
le gerer par un menu.
"""
print("Nom du contact ou Saisir Q pour stopper :", end=' ')
nom = input()
print("Telephone du contact :", end=' ')
telephone = input()
print(f"Votre contact est : {nom} : {telephone}")
|
61398be9729f27558ef6d5d537deab55e5e99df4 | willgrota/CEDERJ_EXERCICIOS | /FP_AD2/questao-4-AD2.py | 1,618 | 3.515625 | 4 |
import struct
TAM = 8
# Subprogramas
def ler(arq):
inteiro = struct.unpack("=i", arq.read(4))[0]
flutuante = struct.unpack("=f", arq.read(4))[0]
return inteiro, flutuante
# Programa Principal
intTest = int(input())
flutTest = float(input())
with open("valores.bin", "r+b") as arq:
arq.seek(0)
qtdReg = struct.unpack("=i", arq.read(4))[0]
chave = 0
print("ANTES") #teste de funcionamento - string para titulo
while chave < qtdReg:
arq.seek(4+(chave * TAM))
inteiro, flutuante= ler(arq)
# teste de funcionamento lê os valores antes da comparação e de modificação
print("inteiro:", inteiro, "flutuante:", flutuante)
if inteiro < intTest and flutuante > flutTest:
arq.seek(4 + (chave * TAM))
arq.write(struct.pack("=i", -1))
arq.write(struct.pack("=f", 9999.0))
elif inteiro < intTest:
arq.seek(4 + (chave * TAM))
arq.write(struct.pack("=i", -1))
arq.write(struct.pack("=f", flutuante))
else:
if flutuante > flutTest:
arq.seek(4 + (chave * TAM))
arq.write(struct.pack("=i", inteiro))
arq.write(struct.pack("=f", 9999.0))
chave += 1
#teste de funcionamento # lê valores após comparação e modificação
chaveteste = 0
print("\nAPÓS")
while chaveteste < qtdReg:
arq.seek(4 + (chaveteste * TAM))
inteiro, flutuante = ler(arq)
print("inteiro:", inteiro, "flutuante:", flutuante)
chaveteste += 1 |
1bf68719b0a145721afdab97fdd3e16ea8fa3850 | abhishekzambre/Python_Programs | /DSA/Stacks.py | 1,496 | 3.828125 | 4 | class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""
def __init__(self):
"""Create an empty stack."""
self._data = [] # nonpublic list instance
def len (self):
"""Return the number of elements in the stack."""
return len(self. _data)
def is_empty(self):
"""Return True if the stack is empty."""
return len(self._data) == 0
def push(self, e):
"""Add element e to the top of the stack."""
self._data.append(e) # new item stored at end of list
def top(self):
"""Return (but do not remove) the element at the top of the stack.
Raise Empty exception if the stack is empty.
"""
if self.is_empty( ):
raise Empty('Stack is empty')
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop()
def reverse_file(filename):
"""Overwrite given file with its contents line-by-line reversed."""
S = ArrayStack()
original = open(filename)
for line in original:
S.push(line.rstrip('\n')) # we will re-insert newlines when writing
original.close()
# now we overwrite with contents in LIFO order
output = open(filename, 'w') # reopening file overwrites original
while not S.is_empty():
output.write(S.pop() + '\n') # re-insert newline characters
output.close()
reverse_file('test.txt')
|
cfca0089d8ca04371ddf649840fab1a9fb9b9345 | RusKursusGruppen/GRIS | /lib/expinterpreter.py | 1,458 | 3.625 | 4 | class ExpinterpreterException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return "Not a valid expression: " + repr(self.value)
def lexer(string):
result = ['']
for char in string:
if char.isdigit():
if result[-1].isdigit():
result[-1] += char
else:
result.append(char)
elif char in "+-*/()l|":
result += char
else:
result.append("")
return [r for r in result[1:] if r != ""]
def rpn(tokens):
stack = []
for t in tokens:
if t.isdigit():
stack.append(int(t))
elif t in "+-*/":
if len(stack) < 2:
raise ExpinterpreterException()
y = stack.pop()
x = stack.pop()
if t == '+':
r = x + y
elif t == '-':
r = x - y
elif t == '*':
r = x * y
elif t == '/':
r = x / y
stack.append(r)
elif t in "l|":
if len(stack) == 0:
stack.append(1)
else:
stack.append(stack.pop()+1)
if len(stack) == 0:
return 0
if len(stack) != 1:
raise ExpinterpreterException(stack)
return stack[0]
def interpret(string):
return rpn(lexer(string))
def interpret_amount(string):
return interpret(string)*100
|
553ff635122902861aae01a73c71b4302d63155c | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_168.py | 604 | 4.09375 | 4 | def main():
degree = input("Please enter the temperature: ")
scale = input("Please enter 'C' for Celcius, or 'K' for Kelvin: ")
if degree > ("99") and scale == "C":
print("At this temperature, water is a gas.")
if degree >= ("373.15") and scale == "K":
print("At this temperature, water is a gas.")
if degree <= ("0") and scale == "C":
print("At this temperature, water is a solid.")
if degree <= ("273.15") and scale == "K":
print("At this temperature, water is a solid.")
else:
print("At this temperature, water is a liquid.")
main()
|
eb59c674748a3a747462cfde8d2f5a0fcbe5a657 | gateway17/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 531 | 4.25 | 4 | #!/usr/bin/python3
# Write a function that removes all characters c and C from a string.
# Prototype: def no_c(my_string):
# The function should return the new string
# You are not allowed to import any module
# You are not allowed to use str.replace()
def no_c(my_string):
ctr = 0
new_string = ""
while ctr < len(my_string):
if my_string[ctr] == 'C' or my_string[ctr] == 'c':
ctr += 1
else:
new_string += my_string[ctr]
ctr += 1
return new_string
|
7a6dce314eeb28162deeb60475405c04f2bff698 | LiuTianyong/myml | /第一章/coding.py | 1,709 | 3.53125 | 4 | #导入需要用到的库
import numpy as np
import matplotlib.pyplot as plt
#定义储存输入数据(x) 和 目标数据(y) 的数组
x,y = [], []
#遍历数据集,变量sample对应的正是一个个的样本
for sample in open('.//data/prices.txt','r'):
_x, _y = sample.split(',')
#将字符串数据转化为浮点数
x.append(float(_x))
y.append(float(_y))
#读取完数据后,将他们转化为numpy 数组以方便进一步的处理
x, y = np.array(x) , np.array(y)
#标准化
x = (x - x.mean()) / x.std()
#将原始数据以散点图的形式画出
plt.figure()
plt.scatter(x, y,c = "g",s = 6)
plt.show()
#在(-2,4)在这个区间上取100个点作画图的基础
x0 = np.linspace(-2, 4, 100)
#利用Numpy 的函数定义训练并返回多项式回归模型的函数
#deg参数代表着模型参数中的n,亦即模型中多项式的次数
#返回的模型能够根据数据的x(默认x0),返回相对应的预测的y
def get_model(deg):
return lambda input_x = x0: np.polyval(np.polyfit( x, y, deg), input_x)
#根据参数n,输入的 x,y返回相应的损失
def get_cost(deg, input_x, input_y):
return 0.5 * ((get_model(deg)(input_x) - input_y) ** 2).sum()
#定义测试参数集并根据它进行各种实验
test_set = (1, 2, 3 , 4, 10)
for d in test_set:
#输出相应的损失
print(get_cost(d, x, y))
#画出相应的图像
plt.scatter(x, y, c="g", s=20)
for d in test_set:
plt.plot(x0, get_model(d)(), label = "degree = {}".format(d))
#将横轴,纵轴的范围分别限制在(-2,4),(10^5,8*10^5)
plt.xlim(-2, 4)
plt.ylim(1e5, 8e5)
#调用legend方法使曲线对应的label正确显示
plt.legend()
plt.show() |
0386f330e92e65f75188310530de8ecced176aae | wbroach/python_work | /ch_4_range_loops.py | 532 | 3.890625 | 4 | #for value in range(1,1000001):
#print(value)
#millions = list(range(1,1000001))
#print(min(millions))
#print(max(millions))
#print(sum(millions))
#odds = list(range(1,21,2))
#for odd in odds:
#print(odd)
#multiples = list(range(3,31,3))
#for multiple in multiples:
#print(multiple)
#cubes = list(range(1,11))
#for cube in cubes:
#print(cube**3)
#cubes2 = []
#for value in range(1,11):
#cube_int = value**3
#cubes2.append(cube_int)
#print(cubes2)
cubes = [value**3 for value in range(1,11)]
print(cubes)
|
1379e620591bd5bc57c6df3c13550e03c6b09747 | ongsuwannoo/Pre-Pro-Onsite | /Pancake Shop EP.5.py | 358 | 3.640625 | 4 | """ Pancake Shop EP.5 """
def main():
""" input """
num = float(input())
print("|--------|")
print("|%-8.2f|" %num)
print("|--------|")
print("")
print("|--------|")
print("|%8.2f|" %num)
print("|--------|")
print("")
print("|--------|")
print("|%08.2f|" %num)
print("|--------|")
main()
|
a75e00640e83c0e74a2568712286a116ebae7b09 | taurusyuan/python | /04_高级数据类型/hm_13_字符串定义和遍历.py | 119 | 3.921875 | 4 | str1 = "hello python"
str2 = '他的外号是"大西瓜"'
print(str2)
print(str1[6])
for char in str2:
print(char) |
db1fa395cc8e1b98de1658a0cb86d5a66d8c6dbe | naushadzaman/DecipherDataOrg | /projects/twitter-search-stream-api/twitterstream.py | 3,281 | 3.96875 | 4 | # this program outputs twitter streams with language code, user name, tweet, creation time in a tab seperated output
# usage: python twitterstream.py
# initial skelaton taken from: https://class.coursera.org/datasci-001
#The steps below will help you set up your twitter account to be able to access the live 1% stream.
#
#● Create a twitter account if you do not already have one.
#● Go to https://dev.twitter.com/apps and log in with your twitter credentials.
#● Click "create an application"
#● Fill out the form and agree to the terms. Put in a dummy website if you don't have one you want to use.
#● On the next page, scroll down and click "Create my access token"
#● Copy your "Consumer key" and your "Consumer secret" into twitterstream.py
#● Click "Create my access token." You can Read more about Oauth authorization.
#● Open twitterstream.py and set the variables corresponding to the consumer key, consumer secret, access token, and access secret.
#
#access_token_key = "<Enter your access token key here>"
#access_token_secret = "<Enter your access token secret here>"
#
#consumer_key = "<Enter consumer key>"
#consumer_secret = "<Enter consumer secret>"
#
import json
import oauth2 as oauth
import urllib2 as urllib
access_token_key = "ENTER YOURS"
access_token_secret = "ENTER YOURS"
consumer_key = "ENTER YOURS"
consumer_secret = "ENTER YOURS"
_debug = 0
oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
http_method = "GET"
http_handler = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)
'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''
def twitterreq(url, method, parameters):
req = oauth.Request.from_consumer_and_token(oauth_consumer,
token=oauth_token,
http_method=http_method,
http_url=url,
parameters=parameters)
req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)
headers = req.to_header()
if http_method == "POST":
encoded_post_data = req.to_postdata()
else:
encoded_post_data = None
url = req.to_url()
opener = urllib.OpenerDirector()
opener.add_handler(http_handler)
opener.add_handler(https_handler)
response = opener.open(url, encoded_post_data)
return response
def extract_tweet_from_stream(line):
try:
response = json.loads(line)
#print response.keys()
encoded_string = response["text"].encode('utf-8')
return response["lang"] + '\t' + response["user"]["screen_name"] + '\t' + encoded_string + '\t' + response["created_at"]
except:
return ''
def fetchsamples():
url = "https://stream.twitter.com/1/statuses/sample.json"
parameters = []
response = twitterreq(url, "GET", parameters)
for line in response:
#print line.strip()
result = extract_tweet_from_stream(line.strip())
if result != '':
print result
if __name__ == '__main__':
fetchsamples()
|
f2683732791ca2fb143c1937127e8b7ce87ddb8c | Muhammed-Moinuddin/30daysofcode | /codeday1.py | 1,148 | 4.0625 | 4 | print("hello,world!")
name = "mark"
name = "ace"
print(name)
thanx = "thanks for your input!"
print(thanx)
weight = 150
sum = weight + 150
print(sum)
print(13*4)
print(12/5)
print(12%5)
print(10%3)
print(3%10)
print(3/10)
age = 50
age += 18
print(age)
age *= 2
print(age)
greeting = "Hello"
address = "World"
separators = ", "
punc = "!"
whole_greeting = greeting + separators + address + punc
print(whole_greeting) #concatenation
whole_greeting2 = "Hello" + separators + "World!"
print(whole_greeting2)
print("Hello" + separators + "World!")
print("The sum of 2 + 2 is",2+2)
print("The sum of 3 + 3 is " + "6")
species = "cat"
if species == "cat":
print("Yep,Its a cat")
if 2+2 == 4:
print("Everything makes sense")
if species == "cat":
print("So far so good")
print("Congratulations")
print("All done")
sentence = "is my name and my age is"
full_name = "Mark is my name and my age is 20"
if full_name == "Mark " + sentence + " 20" :
print("You've done a right thing")
labour_cost = 120
material_cost = 180
total_cost = 300
if total_cost == labour_cost + 180:
print("You've done right calculations")
|
b8751596c06a2be2d40692d39c7bc2292e78e00a | torresv1/mit_intro_programming | /l4_p5_lo_hi_function.py | 558 | 3.9375 | 4 | # Name: Write a Python function, clip(lo, x, hi) that returns lo if x is less than lo; hi if x
# is greater than hi; and x otherwise. For this problem, you can assume that lo < hi.
# Purpose: Learn to use functions
# Date: 12/14/2013 12:18 PM
# Author: Vladimir Torres-Rivas
def clip( lo, x, hi ):
'''
Takes in three numbers and returns a value based on the value of x.
Returns:
- lo, when x < lo
- hi, when x > hi
- x, otherwise
'''
# Your code here
return min( max( x, lo ), hi )
|
257bfab4cd7ce9edb6e93f5a271bf3a99217f043 | jeremiah-hodges/learning.py | /basics/exp.py | 271 | 3.859375 | 4 |
def exp(base, power):
num = 1
for index in range(power):
num = num * base
return num
print(exp(5,3))
def exp3(base, power):
result = 1
while power > 0:
result = base * result
power -= 1
return result
print(exp3(5,3)) |
a10dbd8bdb19c7b557105ec8de31ed4fb53d7b7e | hongta/practice-python | /search/binary_search.py | 1,070 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def binary_search(a, needle):
def _binary_search(lo, hi):
print lo, hi
mid = lo + (hi - lo) //2
if lo > hi:
return False
elif a[mid] < needle:
return _binary_search(mid + 1, hi)
elif a[mid] > needle:
return _binary_search(lo, mid - 1)
else:
return mid
return _binary_search(0, len(a)-1)
def binary_search2(a, needle):
lo = 0
hi = len(a) - 1
while lo <=hi:
mid = lo + (hi - lo) // 2
if a[mid] < needle:
lo = mid + 1
elif a[mid] > needle:
hi = mid - 1
else:
return mid
return False
from bisect import bisect_left
def binary_search3(a, needle):
p = bisect_left(a, needle)
if p < len(a) and a[p] == needle:
return p
return False
if __name__ == '__main__':
d = sorted([2,3,6, 21, 23,5, 10,30,24, 15])
print d
print binary_search(d, 10)
print binary_search2(d, 12)
print binary_search3(d, 31)
|
abb9c66974e8d4fb360ed8ce1a3b104e29368397 | matejtarca/MasarykBOT | /tests/mocks/helpers.py | 877 | 3.890625 | 4 |
class MockReturnFunc(object):
"""
This object mocks the returns of a function
It takes a generator and on each call returns
the next value
example:
def true_once():
yield True
yield False
class MockTrueFunc(object):
def __init__(self):
self.gen = true_once()
def __call__(self):
return self.gen.next()
true_func = MockTrueFunc()
true_func() # True
true_func() # False
true_func() # None
true_func() # None
"""
def __init__(self, gen):
self.gen = gen()
self.stopped = False
def __call__(self, *args, **kwargs):
if self.stopped:
return None
try:
return next(self.gen)
except StopIteration:
self.stopped = True
|
2685e666b9cc393588fd6184461d6f1ab496e51a | SylarK/Python_ | /Road/Dictionaries/main_intro.py | 410 | 4.21875 | 4 | # Dictionaries
# Are indexed by keys, which can be any immutable type.
# All keys are unique in the dictionaries.
# list(d) - dictionary return a list of all the keys used in the dictionary
data = {'John':455620, 'Julia':998653}
data['Joshua'] = 999999
#print(list(data))
#print(sorted(data))
print('John' in data)
print({x: x**2 for x in (5,10,20,30)})
print(dict(car='e350', cilinder='55x80')) |
439c4a01f042bd0e882469e0f0886bf187f9bfc5 | JulyKikuAkita/PythonPrac | /cs15211/InsertintoaBinarySearchTree.py | 3,940 | 4.09375 | 4 | __source__ = 'https://leetcode.com/problems/insert-into-a-binary-search-tree/'
# Time: O(h) h: height of the tree
# Space: O(h)
#
# Description: Leetcode # 701. Insert into a Binary Search Tree
#
# Given the root node of a binary search tree (BST) and a value to be inserted into the tree,
# insert the value into the BST. Return the root node of the BST after the insertion.
# It is guaranteed that the new value does not exist in the original BST.
#
# Note that there may exist multiple valid ways for the insertion,
# as long as the tree remains a BST after insertion.
# You can return any of them.
#
# For example,
#
# Given the tree:
# 4
# / \
# 2 7
# / \
# 1 3
# And the value to insert: 5
# You can return this binary search tree:
#
# 4
# / \
# 2 7
# / \ /
# 1 3 5
# This tree is also valid:
#
# 5
# / \
# 2 7
# / \
# 1 3
# \
# 4
#
import unittest
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#108ms 55.06%
class Solution(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
if not root:
root = TreeNode(val)
return root
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
else:
root.left = self.insertIntoBST(root.left, val)
return root
#100ms 98.14%
class Solution2(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
return Solution2.BST_insert(root, val)
@staticmethod
def BST_insert(root, val):
if root == None:
root = TreeNode(val)
elif root.val < val:
root.right = Solution.BST_insert(root.right, val)
else:
root.left = Solution.BST_insert(root.left, val)
return root
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
time complexity of the insertion operation is the same with search operation which is O(h).
Or O(N) in the worst case and O(logN) ideally if the tree is well organized.
The space complexity of the recursion soultion is O(h) as well.
In other word, O(N) in the worst case and O(logN) ideally.
If you implement the algorithm iteratively, the space complexity can be O(1).
# Recursion
# 1ms 100%
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
Ex: [7,3,9,2,5], insert 4,
the new BST will be : [7,3,9,2,5,null,null,null,null,4]. no need to balance
# Iteration
# 1ms 100%
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode cur = root;
while(true) {
if(cur.val <= val) {
if(cur.right != null) cur = cur.right;
else {
cur.right = new TreeNode(val);
break;
}
} else {
if(cur.left != null) cur = cur.left;
else {
cur.left = new TreeNode(val);
break;
}
}
}
return root;
}
}
''' |
7b83e1f07336a3df88cf14b3bed36463e386147d | ChangxingJiang/LeetCode | /未完成题目/0701-0750/0702/0702_Python_1.py | 515 | 3.5 | 4 | # """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
if __name__ == "__main__":
print(Solution().search(reader=[-1, 0, 3, 5, 9, 12], target=9)) # 4
print(Solution().search(reader=[-1, 0, 3, 5, 9, 12], target=2)) # -1
|
67ef86169e16782f1f3b22091a2eaa81b9d51687 | sotirisnik/projecteuler | /prob20.py | 262 | 3.5625 | 4 | memo = {}
def f( x ):
if x == 0:
return 1
if x in memo:
return ( memo[x] )
memo[x] = x*f(x-1)
return ( memo[x] )
tmp = f(100)
ans = 0
while tmp > 0:
ans += ( tmp % 10 )
tmp /= 10
print "%d" % ( ans ) |
54332b7b956b591c6436d94281882076aa41a901 | sumitjain34/flickr-store | /app/utils.py | 502 | 3.59375 | 4 | def solve_pagination(total_pages,page_no):
print "solving pagination"
if page_no > 5 and page_no != total_pages:
start_page = page_no - 4
end_page = start_page + 9
elif page_no <= 5:
start_page = 1
end_page = start_page + 9
else:
end_page = total_pages
start_page = total_pages - 9
if end_page > total_pages and end_page != total_pages:
end_page = total_pages
start_page = total_pages - 9
if start_page < 0:
start_page = 1
end_page = total_pages
return [start_page,end_page]
|
636852550833715c9b0bbaa18fe7ff6a49371235 | AnimaShadows/advent2020 | /solutions/day_4/day_4_p_2.py | 5,165 | 3.640625 | 4 | #!/usr/bin/python3
from array import *
import re
def populate():
puzzle_input = []
f = open("puzzle_input.txt", "r")
#f = open("puzzle_input_test.txt", "r")
for line in f.read().split("\n\n"):
puzzle_input.append(line)
f.close()
#print (puzzle_input)
return puzzle_input
def validateBirthYear(birthYear):
isValid = True
#Check length of birthYear
if (len(birthYear) != 4):
isValid = False
if (int(birthYear) >= 1920 and int(birthYear) <= 2002):
isValid = True
else:
isValid = False
return isValid
def validateIssueYear(issueYear):
isValid = True
#Check length of issueYear
if (len(issueYear) != 4):
isValid = False
if (int(issueYear) >= 2010 and int(issueYear) <= 2020):
isValid = True
else:
isValid = False
return isValid
def validateExpirationYear(expYear):
isValid = True
#Check length of issueYear
if (len(expYear) != 4):
isValid = False
if (int(expYear) >= 2020 and int(expYear) <= 2030):
isValid = True
else:
isValid = False
return isValid
def validateHeight(height):
isValid = True
if "cm" in height:
measurement = int(height.replace("cm", " "))
if (measurement >= 150 and measurement <= 193):
isValid = True
else:
isValid = False
elif "in" in height:
measurement = int(height.replace("in", " "))
if (measurement >= 59 and measurement <= 76):
isValid = True
else:
isValid = False
else:
isValid = False
return isValid
def validateHairColour(hairColour):
if re.match('^#[0-9a-z]{6}$', hairColour) != None:
return True
else:
return False
def validateEyeColour(eyeColour):
isValid = True
if (eyeColour == "amb" or
eyeColour == "blu" or
eyeColour == "brn" or
eyeColour == "gry" or
eyeColour == "grn" or
eyeColour == "hzl" or
eyeColour == "oth"):
isValid = True
else:
isValid = False
return isValid
def validatePID(pid):
if re.match('^[0-9]{9}$', pid) != None:
return True
else:
return False
def countValidPassports(puzzle_input):
count = 0
for x in range(0, len(puzzle_input)):
if ("byr:" in puzzle_input[x] and
"iyr:" in puzzle_input[x] and
"eyr:" in puzzle_input[x] and
"hgt:" in puzzle_input[x] and
"hcl:" in puzzle_input[x] and
"ecl:" in puzzle_input[x] and
"pid:" in puzzle_input[x]):
passport = puzzle_input[x].replace("\n", " ")
#print (passport)
passportAttributes = passport.split(" ")
#print (passportAttributes)
#loop through passportAttributes, validating each
validBirthYear = False
validIssueYear = False
validExpirationYear = False
validHeight = False
validHairColour = False
validEyeColour = False
validPassportID = False
for i in range(0, len(passportAttributes)):
keyValuePair = passportAttributes[i].split(":")
#if valid key-value pair, do further processing
if (len(keyValuePair) == 2):
if (keyValuePair[0] == "byr"):
validBirthYear = validateBirthYear(keyValuePair[1])
if (keyValuePair[0] == "iyr"):
validIssueYear = validateIssueYear(keyValuePair[1])
if (keyValuePair[0] == "eyr"):
validExpirationYear = validateExpirationYear(keyValuePair[1])
if (keyValuePair[0] == "hgt"):
validHeight = validateHeight(keyValuePair[1])
if (keyValuePair[0] == "hcl"):
validHairColour = validateHairColour(keyValuePair[1])
if (keyValuePair[0] == "ecl"):
validEyeColour = validateEyeColour(keyValuePair[1])
if (keyValuePair[0] == "pid"):
validPassportID = validatePID(keyValuePair[1])
#print("Valid Birth Year: " + str(validBirthYear))
#print("Valid Issue Year: " + str(validIssueYear))
#print("Valid Expiration Year: " + str(validExpirationYear))
#print("Valid Height: " + str(validHeight))
#print("Valid Hair Colour: " + str(validHairColour))
#print("Valid Eye Colour : " + str(validEyeColour))
#print("Valid PID: " + str(validPassportID))
#print("----------------------------")
#Now check if all valid
if (validBirthYear == True and
validIssueYear == True and
validExpirationYear == True and
validHeight == True and
validHairColour == True and
validEyeColour == True and
validPassportID == True):
count += 1
return count
def main():
puzzle_input = populate()
validPassports = countValidPassports(puzzle_input)
print ("Valid passports: " + str(validPassports))
if __name__ == "__main__":
main()
|
bf514f745c7054e3023abaaa3c67b7f20d1eb594 | drewripa/python3linuxacademy | /task_1_0.py | 264 | 4.03125 | 4 | def _printer(message, count):
for iteration in range(count):
print(message)
message = input("Please enter message to echo: ")
count = input("Please enter repeat count: ")
if count:
count = int(count)
else:
count = 1
_printer(message,count)
|
ca2406112c66c5d36c85e01bf0ba1bf91c2dda84 | xiatian0918/auto_scripts | /学习脚本/云计算python学习/Python语言基础学习/面向对象与装饰器.py | 699 | 3.953125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author: xiatian
# 面向对象
class Student:
def __init__(self,name,grade):
self.name = name
self.grade = grade
def introduce(self):
print("hi! I'm %s" %self.name)
print("my grade is: %s" %self.grade)
def improve(self,amount):
self.grade = self.grade + amount
jim = Student("jim",86)
jim.introduce()
jim.improve(10)
jim.introduce()
# 装饰器
def add_candles(cake_func):
def insert_candles():
return cake_func() + " and candles "
return insert_candles()
@add_candles
def make_cake():
return "cake"
# gift_func = add_candles(make_cake)
print(make_cake)
# print(gift_func) |
53aabafd2dc454d5c3ec0880bcfa176d7f31f759 | Emmalinda/querylabs | /datatypes.py | 479 | 3.90625 | 4 | def data_type(n):
if isinstance(n,str):
#print("entered string, the length is:")
return len(n)
elif isinstance(n,bool):
#print("this is boolean")
return n
elif isinstance(n, int):
num=100
if n<num:
return "less than 100"
elif n>num:
return "more than 100"
#print("this is integer")
elif isinstance(n, list):
if len(n)>2:
return n[2]
else:
return None
elif n is None:
return "no value" |
fe7e9df50d891f461c4a8b88500260dff0261d1b | harris-ippp/hw-6-LauraBer | /e2.py | 1,359 | 3.6875 | 4 |
import requests
address="http://historical.elections.virginia.gov/elections/download/{}/precincts_include:0/"
for line in open("ELECTION_ID"): # run a loop over ELECTION_ID file
# newvar=line.split() # create new variable and split each line where there are white spaces
# print(newvar) # prints these lists
newvar=line.split() # generate a new variable for "ELECTION_ID" that creates a list for each row of that file and splits the cells into elements of that list
print(newvar[1]) # print the position 1 of each list (which is the year)
year=newvar[1] # we call this position 'year'
address_list=address.format(newvar[0]) # create new variable address_list, plug the position 0 of list 'newvar' into address. This generates an address for each of the election id's
print(address_list) # print this address_list (to see how it looks like)
response = requests.get(address_list) # create a variable called response, and call on address_list to read in that file
file_name = year + ".csv" # create a new variable called file_name, its consists of the 'year' and the extension '.cvs' which makes sure that we save it as a .cvs file
with open(file_name, "w") as out: # we take our file_name and call it "out" (temporarilly)
out.write(response.text) # we save a file with the response content for each file_name
|
1527eada1fe9ff9fa7a4d81a21fd90cb5ced293b | lfr4704/ilyanovak-class1 | /testhelper.py | 411 | 3.515625 | 4 | import pandas as pd
import helper
print ("HELLO!")
df = pd.DataFrame({'A':[1,2,3], 'B':['05-08-2020', '07-04-1776', '08-30-1945']})
print('SplitDate\n---Before---\n', df)
df2 = helper.SplitDate(df, 'B')
print('---After---\n', df2, '\n')
a_list = ['8','4','H']
print('ListToSeries\n---Before---\n', df2)
print('The List:', a_list, '\n')
df3 = helper.ListToSeries(df2, a_list)
print('---After---\n', df3, '\n') |
8941ddd6e10555500519a783690d6a6a63dd7058 | HannaKulba/AdaptiveTraining_English | /tasks/part_1/login_and_password.py | 295 | 3.546875 | 4 | lp = [int(i) for i in input().split()]
login = 100500
password = 424242
if login == lp[0] and password == lp[1]:
print("Login success")
elif login == lp[0] and password != lp[1]:
print("Wrong password")
elif login != lp[0]:
print("No user with login " + str(lp[0]) + " found")
|
5852b07b8ba95d578edd34d4c4982966cdd6ea8d | andrew-bydlon/Courses | /Python/ProjectSolutions/DiceRoller.py | 1,600 | 4.03125 | 4 | from random import randint
def DiceRoller(Quantity,Dice,Modifier):
Roll = 0
for i in range(Quantity):
Roll += randint(1,Dice)
return Roll+Modifier
def Main():
ReRoll = 'n'
while True:
if ReRoll == 'n':
Quant = input("How many dice would you like to roll? ")
if Quant == "":
Quant = 1
elif Quant.isnumeric():
Quant = int(Quant)
else:
print("Needs to be integral!")
continue
Dice = input("What die size would you like? ")
if Dice == "":
Dice = 20
elif Dice.isnumeric():
Dice = int(Dice)
else:
print("Needs to be integral!")
continue
Mod = input("Is there any modifier? ")
if Mod == "":
Mod = 0
elif Mod.isnumeric():
Mod = int(Mod)
else:
print("Needs to be integral!")
continue
elif ReRoll!='':
print("Please input either y or n.")
ReRoll = input("Would you like to reroll? ([y]es/[n]o, change parameters/[q]uit]").lower()
continue
if Mod<0:
print(Quant, "d", Dice, Mod, " = ", DiceRoller(Quant, Dice, Mod), sep="")
else:
print(Quant, "d", Dice, "+", Mod, " = ", DiceRoller(Quant,Dice,Mod),sep="")
ReRoll = input("Would you like to reroll? (yes/[n]o, change parameters/[q]uit]").lower()
if ReRoll=='q':
break
Main()
|
786043ce7385257d48e8507810b4c47561cd13e7 | 00ZRHun/ShopeeCodeLeague2020_ProgrammingContest | /Q4_LuckyWinner/REJECTED/index (oldest version).py | 935 | 4 | 4 | def append3in1ContentIntoList(itemList3in1Split):
itemList.append(int(itemList3in1Split[0]))
itemList.append(int(itemList3in1Split[1]))
itemList.append(int(itemList3in1Split[2]))
# print(itemList3in1Split)
def find(number):
index = itemListOri.index(number)
fontIndex = index-1
# print(123)
# itemList = [2, 3, 4, 1, 5]
itemList = []
itemListRange = input('')
print(f'Item List Range: {itemListRange}')
# for i in range(0, 5):
for i in range(0, int(itemListRange)):
# itemListContent = input('')
# itemList.append(int(itemListContent))
# itemList.append(int(input().split))
itemList3in1 = input('')
# print(itemList3in1)
itemList3in1Split = itemList3in1.split()
# print(itemList3in1Split)
append3in1ContentIntoList(itemList3in1Split)
itemListOri = itemList.copy()
itemList.sort(reverse=True)
print(f'itemListOri: {itemListOri}')
print(f'itemList: {itemList}')
|
3a776ac1367c605be833b65feed40a4d80a4df1c | khrystyna21/Python | /lesson11/11.1.py | 1,978 | 3.8125 | 4 |
class Person():
def __init__(self, firstname, lastname, age, weight, height):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.weight = weight
self.height = height
def talk(self):
print(f'Hello, my name is {self.firstname} {self.lastname} and I’m {self.age} years old')
def weight_change(self, number_kg):
self.weight += number_kg
def grow_up(self, number_cm):
self.height += number_cm
def get_older(self, number_year):
self.age += number_year
class Student(Person):
def __init__(self, firstname, lastname, age, weight, height, class_year, avg_mark):
super().__init__(firstname, lastname, age, weight, height)
self.class_year = class_year
self.avg_mark = avg_mark
def next_class(self):
if self.class_year <= 11:
self.class_year += 1
else:
return 'End of school'
def mark(self, test):
if test in range(1, 13):
self.avg_mark = (self.avg_mark + test) / 2
class Teacher(Person):
def __init__(self, firstname, lastname, age, weight, height, salary, year_experience):
super().__init__(firstname, lastname, age, weight, height)
self.salary = salary
self.year_experience = year_experience
def salary_raise(self, raise_number):
self.salary += raise_number
def gain_experience(self):
self.year_experience += 1
person = Person('Khrystyna', 'Tkachuk', 24, 54, 165)
person.talk()
person.weight_change(2)
person.grow_up(5)
person.get_older(2)
print(person.weight)
print(person.height)
print(person.age)
student = Student('Anna', 'Frank', 12, 40, 150, 6, 9.1)
student.next_class()
print(student.class_year)
student.mark(12)
print(student.avg_mark)
teacher = Teacher('Jon', 'Snow', 33, 77, 173, 5500, 3)
teacher.salary_raise(500)
print(teacher.salary)
teacher.gain_experience()
print(teacher.year_experience) |
bb3b710ba0beebdf4ed313cd6ed1a221ce11db94 | MarshallBriggs/ATS_Python_Procedure | /ATS Print PDFs.py | 4,511 | 3.546875 | 4 | # Import PyPDF2 to print pdfs
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject
def extract_information(pdf_path):
with open(pdf_path, 'rb') as f:
pdf = PdfFileReader(f)
information = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
txt = f"""
Information about {pdf_path}:
Author: {information.author}
Creator: {information.creator}
Producer: {information.producer}
Subject: {information.subject}
Title: {information.title}
Number of pages: {number_of_pages}
"""
print(txt)
return information
def split(path, name_of_split):
pdf = PdfFileReader(path)
for page in range(pdf.getNumPages()):
pdf_writer = PdfFileWriter()
pdf_writer.addPage(pdf.getPage(page))
output = f'{name_of_split}{page}.pdf'
with open(output, 'wb') as output_pdf:
pdf_writer.write(output_pdf)
# USE THIS FUNCTION
# path = 'Jupyter_Notebook_An_Introduction.pdf'
# split(path, 'jupyter_page')
def get_first_three(path, name_of_split):
pdf = PdfFileReader(path)
# pdf_writer = PdfFileWriter()
for page in range(pdf.getNumPages()):
if page == 3:
break
pdf_writer.addPage(pdf.getPage(page))
# output = f'{name_of_split}.pdf'
# with open(output, 'wb') as output_pdf:
# pdf_writer.write(output_pdf)
# Corrects an error with the form fillable fields
def set_need_appearances_writer(writer: PdfFileWriter):
# See 12.7.2 and 7.7.2 for more information: http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
try:
catalog = writer._root_object
# get the AcroForm tree
if "/AcroForm" not in catalog:
writer._root_object.update({
NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)
})
need_appearances = NameObject("/NeedAppearances")
writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
# del writer._root_object["/AcroForm"]['NeedAppearances']
return writer
except Exception as e:
print('set_need_appearances_writer() catch : ', repr(e))
return writer
if __name__ == "__main__":
# Import OS to walk through directory
import os
# Get the path of this python file
my_path = os.path.dirname(os.path.abspath(__file__))
# Initialize file variables
found_file = False
input_path = ""
input_file = ""
file_name = ""
folder_name = ""
cwd = ""
# Initialize count variables
eDoc_count = 0
# Initialize pdf writer
pdf_writer = PdfFileWriter()
set_need_appearances_writer(pdf_writer)
for root, dirs, files in os.walk(my_path):
for file in files:
if file.endswith(".pdf"):
input_path = root
input_file = file
file_name = os.path.splitext(input_file)[0]
# print(os.path.join(root, file))
if file_name == "eDocumentation":
path = os.path.join(root, file)
# extract_information(path)
cwd = os.getcwd()
# print(cwd)
# print(os.path.dirname(path))
# print(os.path.basename(path))
folder_name = os.path.split(os.path.dirname(path))[-1]
pdf = PdfFileReader(path)
for page in range(pdf.getNumPages()):
if page == 3:
break
pdf_writer.addPage(pdf.getPage(page))
# get_first_three(path, folder_name)
eDoc_count += 1
if input_file == "":
found_file = False
else:
found_file = True
# File is found
if found_file:
output = f'{os.path.basename(my_path)}_eDocumentation_Combined.pdf'
with open(output, 'wb') as output_pdf:
pdf_writer.write(output_pdf)
print("Found " + str(eDoc_count) + " instance(s) of eDocumentation.pdf")
# File is not found
else:
print("File not found. Please make sure the file is present in folders")
print("Script is finished.")
input("Press enter to stop the script.")
|
2dd98cee525088d2977b371b6ca9e2a3b132a869 | ankita-y/HackerRankProblemSolutions | /Runner-UpScore.py | 427 | 3.625 | 4 | if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
mx1 = arr[0]
mx2 = arr[1]
for num in arr:
if num > mx1:
mx1,mx2 = num,mx1
elif num > mx2 and num != mx1:
mx2 = num
elif mx1 == mx2:
mx2 = num
# for num in arr:
# if num != max(arr) and num > mx1:
# mx1 = num
print(mx2)
|
a97fe9ce3500c428557e220b8f23a29b389b18c5 | dsun092/coding_practice | /cracking/chap3.py | 2,272 | 3.53125 | 4 | class SetOfStacks:
def __init__(self, thresh):
self.limit " thresh
self.stacks " [[]]
def push(self, val):
if len(self.stacks[-1]) "" limit:
self.stacks.append([])
self.stacks[-1].append(val)
def pop(self):
ret " self.stacks[-1].pop()
if len(self.stacks[-1]) "" 0:
self.stacks.pop()
return ret
def popAt(self, i):
ret " self.stacks[i].pop()
if len(self.stacks[i]) "" 0:
self.stacks.pop(i)
return ret
class StackMin:
def __init__(self):
self.stack " []
def peek(self):
if self.stack "" []:
return None
else:
return self.stack[-1]
def push(self, val):
cur_min " self.peek()
if cur_min is None or val < cur_min['min']:
self.stack.append({'val': val, 'min': val})
else:
self.stack.append({'val': val, 'min': cur_min['min']})
def pop(self):
return self.stack.pop()
class QueueS:
def __init__(self):
self.current_stack " []
self.pop_stack " []
def push(self, val):
self.current_stack.append(val)
def peek(self):
if self.pop_stack "" []:
self.swap_stack()
return self.pop_stack[-1]
def pop(self):
if self.pop_stack "" []:
self.swap_stack()
return self.pop_stack.pop()
def swap_stack(self):
while self.current_stack !" []:
self.pop_stack.append(self.current_stack.pop())
class Stack:
def __init__(self):
self.stack " []
def push(self, val):
self.stack.append(val)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def sortStack(s):
sorted_stack " Stack()
while s.stack !" []:
temp " s.pop()
found " False
while not found:
if sorted_stack.stack "" []:
found " True
elif sorted_stack.peek() < temp:
found " True
else:
s.push(sorted_stack.pop())
sorted_stack.push(temp)
while s.stack !" [] and s.peek() > sorted_stack.peek():
sorted_stack.push(s.pop())
return sorted_stack
|
761de52cf8b5e6022b76d05f8de3f0eee4a9c628 | Nikkurer/gb_py_basics | /Lesson_5/ex1.py | 573 | 3.734375 | 4 | # Создать программно файл в текстовом формате, записать в него построчно
# данные, вводимые пользователем. Об окончании ввода данных свидетельствует
# пустая строка.
user_data = None
filename = 'user_data.txt'
with open(filename, mode='wt', encoding='utf-8') as f:
while True:
user_data = input('Введите данные: ')
if not user_data:
break
f.write(f'{user_data}\n')
f.flush()
|
c2994014c78964c188649111c40f7de3670510a6 | fabianrmz/python-course | /built-in-data-structures/tuples.py | 209 | 3.71875 | 4 | x = ()
x = (1,2,3,4,5,6,7)
print(x)
x = 1, 1, 3
print(x)
list1 = [3,6,3]
x = tuple(list1)
print(x, type(x))
# not assignment in tuples x[2]=666, inmutables
print(x[2])
y = ([1,2], 3)
del(y[0][1])
print(y) |
e8b4414ba73185039fbf6aba4bd9b29a9b4261a3 | rarose67/Stocks | /stock_class.py | 3,853 | 3.984375 | 4 | from random import uniform
class Stock:
"""This class represents a stock that is traded daily on the stock market."""
def __init__(self, init_symb, init_name, init_shares, init_price, init_var, init_div):
self.symbol = init_symb
self.name = init_name
self.shares = init_shares
self.price = init_price
self.varience = init_var
self.dividend = init_div
self.weekly_start_price = init_price
self.days_held = 0
def get_symb(self):
return self.symbol
def get_name(self):
return self.name
def get_shares(self):
return self.shares
def get_price(self):
return self.price
def get_var(self):
return self.varience
def get_div(self):
return self.dividend
def get_wk_price(self):
return self.weekly_start_price
def get_days_held(self):
return self.days_held
def set_var(self, new_var):
self.varience = new_var
def set_div(self, change_in_div):
self.dividend += change_in_div
def set_price(self, curr_price):
self.price = curr_price
def set_wk_price(self):
self.weekly_start_price = self.price
def avg_change(self, start_price, days):
"""Return the average change in the stock's price after a given number of days."""
return ((self.price - start_price) / days)
def trade(self):
"""Simulate a day of trading"""
change = uniform(-(self.varience), self.varience) #change in price is a random number between the negative a positive variance of the stock price.
change = round(change, 2)
self.price += change
#if the stock price becomes negative, reset it to 0.
if (self.price < 0):
self.price = 0.00
self.days_held += 1
def buy_shares(self, num_shares):
self.shares += num_shares
def quarter(stock, money):
"""Use stock dividends to buy more shares"""
money += round(((stock.get_div() / 4 ) * stock.get_shares()), 2)
new_shares = (money // stock.get_price())
stock.buy_shares(new_shares)
print("Bought {0} shares of {1} at ${2}".format(new_shares, stock.get_symb() ,stock.get_price()))
money = round((money - (new_shares * stock.get_price())), 2)
return money
def market_open(dotw, date):
"""Determine if the stock market is open"""
if ((dotw % 6 == 0) or (dotw % 7 == 0) or (date == 1) or (date == 15) or (date == 50) or (date == 89) or (date == 148) or (date == 185) or (date == 246) or (date == 326) or (date == 359)):
return False
else:
return True
def main():
Ford = Stock("F", "Ford", 800, 11.33, 0.50, 0.60)
money = 0.0
days = 365
day_of_the_week = 1
trading_days_this_week = 0
new_quarter = False
for day in range(1, days+1):
if(market_open(day_of_the_week, day)):
Ford.trade()
trading_days_this_week += 1
#Each quarter, buy more shares with the dividends.
if(day % 90 == 0) or new_quarter:
money = quarter(Ford, money)
new_quarter = False
else:
#If the market is closed.
if(day % 90 == 0):
new_quarter = True
if (day_of_the_week % 7 == 0): #If it's Sunday, re-evaluate the daily varience of the stock price. Also, reset counters.
Ford.avg_change(Ford.get_wk_price(), trading_days_this_week)
Ford.set_wk_price()
trading_days_this_week = 0
day_of_the_week = 0
day_of_the_week += 1
print("You have", Ford.get_shares(), "shares of", Ford.get_symb(), "at $", Ford.get_price(), "and have $", money, "left to invest.")
if (__name__ == "__main__"):
main() |
bc32e3330b884fb6d9d9b2d068344d8acdbec3ec | prashuym/IKPrograms | /Recursion-LengthBinaryTree.py | 1,178 | 3.578125 | 4 | class btree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxdepth(node):
if node == None: return 0, 0
maxH = minH = 0
treePaths = []
def maxdepthHelper(node, level, path):
nonlocal maxH, minH
# Base condition
# print (node.data, node.left, node.right, path, treePaths)
if node.left == None and node.right == None:
if level > maxH: maxH = level
if minH == 0 or level < minH: minH = level
path.append(node.data)
treePaths.append(path[:])
path.pop()
return
# Parent - left & right
path.append(node.data)
if node.left: maxdepthHelper(node.left, level + 1, path)
if node.right: maxdepthHelper(node.right, level + 1, path)
path.pop()
return
maxdepthHelper(node, 1, [])
return maxH, minH, treePaths
root = btree(1)
root.left = btree(2)
root.right = btree(3)
root.left.left = btree(4)
root.left.right = btree(5)
root.left.left.left = btree(6)
root.left.left.left.left = btree(7)
# root = None
print("max and min depth :", maxdepth(root)) |
c5ed8baec7f6c9683006b2d5d738e8b62689a18e | mygetoer/practice | /Nc_Lotto.py | 2,476 | 3.921875 | 4 | #Obelisk
print()
print("NC EDUCATION LOTTERY, LLC")
print("Welcome to the North Carolina Education Lottery's proprietary number selection and bank deposit interface.")
print()
reg_user = input("Are you a certified lottery official?")
if reg_user == "no":
print("Please contact North Carolina Education Lottery Office in Raleigh")
exit()
else:
user_pin = input("Please enter your four-digit, certified lottery official PIN: ")
if user_pin == "1234":
print("PIN accepted.")
else:
print("PIN invalid.")
print("Goodbye!")
exit()
print()
print("Please set answers to security questions for future logins:")
print()
def security_questions():
q1 = input("Mother's maiden name?")
q2 = input("City of birth?")
q3 = input("Favorite childhood pet?")
security_questions()
print()
user_ssn = input("Thank you, your identity has been confirmed. Please enter your Social Security number, then press enter:")
print()
print("Your account has been verified.")
print()
print("Bank information is required in order to deposit lottery funds. Please answer the following questions to proceed.")
print()
bank_account = input("Please enter your bank account number: ")
routing_number = input("Please enter bank routing number: ")
bank_balance = input("Please enter current account balance to synchronize bank and lottery servers: ")
bank_balance =+ .01
print()
print()
print("Thank you....please wait while our servers connect to your bank")
print()
print()
print("Connection succesful!")
print()
print("Now generating your lottery numbers...")
print()
print()
enter_input = input("Complete! Please press enter to recieve your lottery numbers!")
winning_numbers = [49, 2, 56, 81, 5, 32]
print()
print("Your lottery numbers are " + str(winning_numbers))
print()
winner_response = input("Would you like to compare your numbers against winning numbers?")
print()
if winner_response == "yes":
print("Your numbers are...", winning_numbers)
print( "The winning numbers are...", winning_numbers)
else:
print("Goodbye!")
exit()
print()
print("Congratulations! You are a winner!")
print()
transfer_cnfrm = input("Current Jackpot is: $168,000,000. Would you like to transfer lottery funds to the bank account provided above?")
jp = 168000000
if transfer_cnfrm == "yes":
print()
update = input("Updating your bank balance...")
print()
else:
print("Thank you, goodbye!")
print("Your updated account balance is ", jp + bank_balance)
|
2e973d085ff39772aed4b2a5acd51e80c855a577 | bhagavansprasad/students | /mouni/python/basics/3.16.py | 271 | 3.734375 | 4 | k = 0
for i in range(0,3):
for j in range(i,3):
print(" "),
for k in range(65, 65 +(i * 2) + 1):
print chr(k),
print '\n'
for i in range(1,-1,-1):
for j in range(3,i,-1):
print " ",
for k in range(65, 65 +(i * 2) + 1):
print chr(k),
print '\n'
|
68c7ac2e4ef495d56eb3b4a5c54d2043b424f644 | Vladyslav225/lesson_23-24 | /unique_meanings.py | 584 | 3.859375 | 4 | # Разница двух массивов (Уникальные значения)
# Func([1,3,4], [2,4,5]) -> [2, 3, 5]
# Func([1,2,3], [2,4,5]) -> [3, 5]
def create_new_list_1(list_1, list_2):
list_unique_numbers = []
lists =list_1 + list_2
for number in lists:
user_count = lists.count(number)
if user_count == 1:
user_count = number
list_unique_numbers.append(user_count)
print(f'list_unique_numbers: {list_unique_numbers}')
create_new_list_1([1,2,3], [2,4,5])
create_new_list_1([1,3,4], [2,4,5])
|
c91172c46938c0faddcd9aac0881536d82028557 | everqiujuan/python | /day08/code/11_匿名函数.py | 1,327 | 3.875 | 4 |
# 匿名函数: 不知道名字的函数
def fn(n):
return n
f = lambda n:n # 跟上面的函数定义功能一样
print(f(10))
# 求a+b
f2 = lambda a,b: a+b
# def f2(a, b):
# return a+b
print(f2(10, 20))
# 用途
persons = [
{'name': "张三", "age": 33, "score": 90},
{'name': "李四", "age": 20, "score": 70},
{'name': "王五", "age": 50, "score": 80},
{'name': "赵六", "age": 80, "score": 10},
{'name': "钱七", "age": 70, "score": 30},
]
def fn2(x):
return x['score']
persons.sort(key=lambda x: x['score'], reverse=True)
print(persons)
# 高阶函数
# 排序方法
def my_sort(l, key=None):
# 冒泡排序
for i in range(len(l)-1):
for j in range(len(l)-1 -i):
if key(l[j]) > key(l[j+1]):
l[j], l[j+1] = l[j+1], l[j]
# list1 = [11,2,3,4]
# my_sort(list1)
# print(list1)
# def fn2(x):
# return x['score']
fn3 = lambda dic: dic['age']
my_sort(persons, key=fn3)
print(persons)
# 函数的函数名称: 既是函数的名称,也是指向该函数的变量
def f():
print(1)
# f()
# 将变量f指向的函数赋值给变量f2,则f2和f都指向该函数
f2 = f
f2()
#
list1 = ["a", "B", 'C', 'F', 'd']
list1.sort(key=str.upper)
print(list1)
|
a3d4e8aa5b661e2d83c557cfc3b9c62687c0c640 | rahulcreddy/hackerrank_python | /74. ginortS.py | 617 | 4 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == "__main__":
user_input = sorted(input())
lower = ""
upper = ""
even = ""
odd = ""
for i in range(len(user_input)):
if(user_input[i].isalpha()):
if(user_input[i].isupper()):
upper += user_input[i]
else:
lower += user_input[i]
else:
if(int(user_input[i])%2 == 0):
even += user_input[i]
else:
odd += user_input[i]
print(lower,upper,odd,even, sep = "")
|
91927982ca1e32e124ee3b957258a3bb1945261b | DenisLo-master/python_basic_11.06.2020 | /homeworks/less5/task5.py | 618 | 3.65625 | 4 | """5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран."""
import random
sum = 0
my_list = [str(random.randrange(10, 100)) for i in range(15)]
line = ' '.join(my_list)
for i in range(len(my_list)):
sum += int(my_list[i])
with open('task5-file1.txt', 'w', encoding='Utf-8') as f:
f.write(line)
f.write(f'\nСумма чисел: {sum}')
|
54e9f07c8449bd35a189290ee58e1eb99fe0bed9 | SaulGQB/Aprendizaje-Automatico-Proyecto-1 | /outliers_treatment.py | 1,310 | 4.09375 | 4 | def outliers_detect(df, column):
'''Función para detectar outliers a partir de los cuantiles
df: dataframe
column: columna del data frame
-------------------------------------
return: regresa una lista con los indices de los outliers
'''
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower = Q1 -1.5 * IQR
upper = Q3 + 1.5 * IQR
outliers_index = df.index[(df[column] < lower) | (df[column] > upper)]
return outliers_index
def remove_outliers(df, index_list):
'''Funcion para remover los outliers de un dataframe
df: data frame
index_list: lista de indices donde se encuentran los outliers
------------------------------------------------
return: Dataframe sin outliers
'''
index_list = sorted(set(index_list))
df = df.drop(index_list)
return df
def outliers_replace(df, index_list, value):
'''Reemplaza el valor de los outliers
df: data frame
index_list: lista de indices donde se encuentran los outliers
value: valor con el que se reemplazaran
------------------------------------------------
return: Dataframe con los outliers reemplazados
'''
index_list = sorted(set(index_list))
df.iloc[index_list] = value
return df
|
39fd2a6ace06b132935e9016aab56065410be114 | anmolaithinker/Algorithms-Practise | /Greedy/Count_ways_to_reach_nth_stairs.py | 835 | 3.78125 | 4 |
# Amazon Interview ( steps defined 2 or 3 )
# f(n) = f(n-2) + f(n-3)
def getCountsStairs(n):
if (n==0):
return 1
if (n<0):
return 0
two_steps = getCountsStairs(n-2)
three_steps = getCountsStairs(n-3)
return two_steps + three_steps
storage = []
def storageFunc(n):
# (n -> Result)
for i in storage:
if i[0] == n:
return (True , i[1])
return (False , False)
def dpGetCountStairs(n):
if n == 0:
return 1
if n<0:
return 0
a = storageFunc(n)
if a[0]:
return a[1]
two_steps = getCountsStairs(n-2)
three_steps = getCountsStairs(n-3)
return two_steps + three_steps
print 'Result : ' + str(dpGetCountStairs(10))
# for total stairs = 10
# 2 + 2 + 2 + 2 + 2
# 3 + 3 + 2 + 2
# 2 + 2 + 3 + 3
# 2 + 3 + 2 + 3
# 3 + 2 + 3 + 2
# 3 + 2 + 2 + 3
# 2 + 3 + 3 + 2
# for total stairs = 5
# 2 + 3
# 3 + 2 |
bde13ec8be3b00b8779e32d1ea9e97a850010792 | rakesh08061994/Raka-Python-Code-1 | /Loops_Question (4).py | 546 | 4.5625 | 5 | # Python program to illustrate
# Iterating over a list
# list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] # List is like a bullet box
# for Item in list1: # Item is triger and for loop is like a gun
# print(Item) # loop statement is like fire rounds
# NOTE >
# If we provide a list, tuple, and string to for loop in advance, Then we will not use range() function.
# Because we have already elements in the form of list,tuple,string
for Item in range(1,21):
print(Item)
|
81f5369417d2fd260d824c2edb56dfbc417d0a9c | yyqAlisa/python36 | /Python 基础课/day16.py | 1,683 | 3.828125 | 4 | # 题目5:计算从1到某个值以内所有能被3或者17整除的数的和并输出
# list1 = []
# num = int(input('请输入大于1的整数'))
# for i in range(1,num):
# if i%3==0 or i%17==0:
# list1.append(i)
# print(list1)
# print(sum(list1)) #对列表进行求和,每个元素都必须是number
# 题目11:最多循环问99次 “老婆,你爱我吗?”,如果回答的是“爱”,那么就结束循环,否则就继续问。用程序描述这个故事
# 如果最终没有拿到我要的答案,回复一句话 “对不起打扰了”
# 方式一
# flag = False
# for i in range(3):
# q = input('老婆,你爱我吗?')
# if q=='爱':
# flag = True
# print('老婆我也爱你')
# break
# else:
# print('在给你一次机会')
#
# if not flag:
# print('对不起打扰了')
# 方式二 利用与for 对应的else关键字效果
# for i in range(3):
# q = input('老婆,你爱我吗?')
# if q=='爱':
# print('老婆我也爱你')
# break
# else:
# print('在给你一次机会')
# else: #只要break触发,它就不触发;反之,触发
# print('对不起打扰了')
# 题目1:使用Python编程,求1~100间所有偶数的和。
# list2 = []
# for i in range(2,101,2): #(开始,结束,步长)
# list2.append(i)
# print(sum(list2))
# 题目14:输出1到100之间所有的质数
# list1 = []
# for i in range(2,101):
# for j in range(2,i):
# if i%j==0:
# print('%s不是质数'%i)
# break
# else:
# print('%s是质数' % i)
# list1.append(i)
# print(list1)
|
fc19a682a94a014b1933cd8df5794f2edf5d984d | hollapena/python-data-lab | /data_presenter.py | 2,540 | 3.640625 | 4 | cupcake_invoices=open("CupcakeInvoices.csv")
def all_invoices(cupcake_invoices):
for invoices in cupcake_invoices:
print(invoices)
all_invoices(cupcake_invoices)
cupcake_invoices.seek(0,0)
def find_type(cupcake_invoices):
for invoices in cupcake_invoices:
split_invoices = invoices.split(',')
print(split_invoices[2])
find_type(cupcake_invoices)
cupcake_invoices.seek(0,0)
def find_customer_total(cupcake_invoices):
for invoices in cupcake_invoices:
split_invoices = invoices.split(',')
new_num1=float(split_invoices[3])
new_num2=float(split_invoices[4])
total=new_num1*new_num2
print(total)
find_customer_total(cupcake_invoices)
cupcake_invoices.seek(0,0)
def find_overall_total(cupcake_invoices):
new_total=0
for invoices in cupcake_invoices:
split_invoices=invoices.split(',')
new_num1=float(split_invoices[3])
new_num2=float(split_invoices[4])
customer_total=new_num1*new_num2
new_total += customer_total
rounded_total = round(new_total, 2)
print(rounded_total)
find_overall_total(cupcake_invoices)
cupcake_invoices.seek(0,0)
def find_income_by_flavor(cupcake_invoices):
chocolate=0
vanilla=0
strawberry=0
for invoices in cupcake_invoices:
split_invoices=invoices.split(',')
if split_invoices[2]=="Chocolate":
new_num1=float(split_invoices[3])
new_num2=float(split_invoices[4])
new_total=new_num1*new_num2
chocolate += new_total
if split_invoices[2]=="Vanilla":
new_num1=float(split_invoices[3])
new_num2=float(split_invoices[4])
new_total=new_num1*new_num2
vanilla += new_total
if split_invoices[2]=="Strawberry":
new_num1=float(split_invoices[3])
new_num2=float(split_invoices[4])
new_total=new_num1*new_num2
strawberry += new_total
new_chocolate=round(chocolate, 2)
new_vanilla=round(vanilla, 2)
new_strawberry=round(strawberry, 2)
return (new_chocolate, new_vanilla, new_strawberry)
flavors=find_income_by_flavor(cupcake_invoices)
chocolate=str(flavors[0])
vanilla=str(flavors[1])
strawberry=str(flavors[2])
import matplotlib.pyplot as plt
flavor=['Strawberry', 'Vanilla', 'Chocolate']
income=[strawberry, vanilla, chocolate]
plt.bar(flavor, income)
plt.title('Company Income by Flavor')
plt.xlabel('Flavor')
plt.ylabel('Income')
plt.show()
cupcake_invoices.close()
|
e0c84a9a0679190116ebfcde0906162b918cdc17 | wzc-ob/PycharmProjects | /第九章/迭代器/9-2.py | 208 | 3.65625 | 4 | class Counter:
def __init__(self,x=0):
self.x = x
counter = Counter()
def used_iter():
counter.x +=2
return counter.x
for i in iter(used_iter,10):
print('本次遍历的数值:',i) |
ae8975cb8fb7bfa9ad69473197bbfcaf37e94530 | Adpeen/Some-Random-Stuff-I-created | /idek what this is.py | 1,000 | 4.15625 | 4 | ##AdamGrierson
##26/1/16
print(" hello, its me")
name = "adam"
print(" I saw " + name+ '.')
name = "Dylan"
print(" i also saw " + name + '.')
name = input('What is your name? ')
print('Harry')
print ('she said, "hello!" to us.')
print ("was you not listening?")
message = 'Its Me'
print(message)
print('ab' + 'ab')
print('ab' * 5)
answer = 1,000,000
print('The answer is ' + str(answer))
firstname = input('What is your first name?')
lastname = input('What is your last name?')
print(60 * 60 * 24)
secs_min = 60
mins_hour = 60
hours_day = 24
secs_day= secs_min*mins_hour*hours_day
print(secs_day)
a = input('68')
b = input('70')
print(a + b)
print('5' + '6')
from turtle import*
forward(100)
right(120)
forward(100)
right(120)
forward(100)
raining = input('Is it raining? ')
if raining == 'yes':
print('Pick up an umbrella.')
print('leave the house.')
if name == 'Daniel' :
print("That's My Brothers Name!")
|
364e099365cb0200457445c6c86b0595732d1aeb | fredy-prudente/python-brasil-exercicios | /Estrutura De Decisao/ex14.py | 799 | 3.859375 | 4 | # Faça um programa que lê as duas notas parciais obtidas por um aluno numa disciplina ao longo de um semestre,
# e calcule a sua média. A atribuição de conceitos obedece à tabela abaixo:
n1 = float(input('Digite sua nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
if media >= 9:
print(f'Sua média foi {media:.2f} APROVADO, nota concedida como A')
elif media >= 7.5 or media > 9:
print(f'Sua média foi {media:.2f} APROVADO, nota concedida como B')
elif media >= 6.0 or media > 7.5:
print(f'Sua média foi {media:.2f} APROVADO, nota concedida como C')
elif media >= 4.0 or media > 6.0:
print(f'Sua média foi {media:.2f} REPROVADO, nota concedida como D')
elif media < 4:
print(f'Sua média foi {media:.2f} REPROVADO, nota concedida como E')
|
815a7a55d34b00ca1fdb7b934b77d8aa1910e55c | istiophorus/Codility | /Python/Brackets.py | 1,016 | 3.765625 | 4 | # Brackets
# Task: https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/
# Solution and results: https://app.codility.com/demo/results/training9RBUZY-DVN/
def solution(input):
if input == None:
raise ValueError
if input == '':
return 1
stack = []
for ch in input:
if ch == '(':
stack.append('(')
elif ch == ')':
last = stack.pop()
if last != '(':
return 0
elif ch == '[':
stack.append('[')
elif ch == ']':
last = stack.pop()
if last != '[':
return 0
elif ch == '{':
stack.append('{')
elif ch == '}':
last = stack.pop()
if last != '{':
return 0
else:
raise ValueError("Input string contains invalid characters")
if len(stack) == 0:
return 1
return 0
|
cb76a4667c0837c3a821562a1cf222fcf1f337ee | moustaches/kaftiere | /kaftierev2/objets/objet_geo.py | 6,552 | 3.515625 | 4 | import math
class PointK():
"""class point"""
def __init__(self, longitude=0, latitude=0,hauteur=0, parent=None):
self.parent=parent
self.longitude=longitude
self.latitude=latitude
self.hauteur=hauteur
def distance(self, point):
return math.sqrt(pow(self.longitude - point.longitude, 2) + pow(self.latitude - point.latitude, 2))
def matchingLieu(self, listLieu=None):
"""retourn le lieu le plus proche"""
matching_lieu, matching_dist=None, 1000
for lieu in listLieu:
dist=self.distance(lieu.adresse.point)
if matching_dist>dist:
matching_lieu=lieu
matching_dist=dist
return matching_lieu, matching_dist
@property
def kmlCoordonnees(self):
return (self.longitude,self.latitude,self.hauteur)
@kmlCoordonnees.setter
def kmlCoordonnees(self,coords):
coords=coords.split(",")
self.latitude=float(coords[1])
self.longitude=float(coords[0])
self.hauteur=float(coords[2])
class ShapeK():
"""class shape"""
def __init__(self, shape=None,str_polygon=None,parent=None, mere=None):
self.parent=parent
self._mere=mere
self._mere.dictShape[parent.dbid]=self
self._shape=(PointK(longitude=2.2923,latitude=48.8578, parent=self),
PointK(longitude=2.2951, latitude=48.8596, parent=self),
PointK(longitude=2.2969,latitude=48.8565, parent=self)) #chaine fermé de poink
if shape:self.shape=shape
elif str_polygon:self.shape=shape
elif parent:
if parent.polygon:self._shape=self.formatStrToKaf(parent.polygon)
@property
def shape(self):
return self._shape
@shape.setter
def shape(self,shape):
if isinstance(shape, list):
self._shape=shape
if self.parent:self.parent.polygon=self.formatKaftoStr(shape)
elif isinstance(shape, str):
self._shape=self.formatStrToKaf(shape)
if self.parent:self.parent.polygon=shape
@property
def kmlCoordonnees(self):
return map(lambda poink: poink.kmlCoordonnees,self._shape)
@kmlCoordonnees.setter
def kmlCoordonnees(self,kml_coordonnees):
kml_coordonnees=kml_coordonnees.strip()
list_str_point=kml_coordonnees.split(' ')
kaf_polygon=[]
for str_point in list_str_point:
str_lat_long=str_point.split(',')
lon=float(str_lat_long[0])
lat=float(str_lat_long[1])
point=PointK(longitude=lon,latitude=lat,parent=self)
kaf_polygon.append(point)
self.shape=kaf_polygon
def formatStrToKaf(self, str_polygon):
list_str_point= str_polygon[2:-2]
list_str_point=list_str_point.split('),(')
kaf_polygon=[]
for str_point in list_str_point:
str_lat_long=str_point.split(',')
lon=float(str_lat_long[0])
lat=float(str_lat_long[1])
point=PointK(longitude=lon,latitude=lat,parent=self)
kaf_polygon.append(point)
return kaf_polygon
def formatKaftoStr(self, kaf_polygon):
list_str_point=''
for point in kaf_polygon:
str_point=",({},{})".format(point.longitude,point.latitude)
list_str_point+=str_point
str_polygon= "("+list_str_point[1:]+")"
return str_polygon
def deshaper0bjet(self,objet_geo=None):
"""
prend objet contenant .latitude et .longitude
et rend true ou false s'il appartient a la shape
"""
i=0
point0=self.shape[0]
for point1 in self.shape[1:]:
if (objet_geo.longitude < point0.longitude and objet_geo.longitude > point1.longitude) or (objet_geo.longitude > point0.longitude and objet_geo.longitude < point1.longitude):
if not objet_geo.latitude < min(point0.latitude,point1.latitude):
if ((point0.latitude-point1.latitude)/(point0.longitude-point1.longitude)*(objet_geo.longitude-point0.longitude))+point0.latitude < objet_geo.latitude:i+=1
point0=point1
if i % 2 == 1:return True
else:return False
class CheminK():
"""class chemin"""
def __init__(self, list_point=None,list_lieu=None, parent=None, mere=None):
self.parent=parent
self._mere=mere
self._mere.dictChemin[parent.dbid]=self
self._chemin=None#suite de dbid lieu
if self.parent:
if self.parent.line:self._chemin=self.parent.line
@property
def listLieu(self):
if self.chemin:
return map(lambda dbid: self._mere.Lieu(dbid),self.chemin)
else :return []
@property
def longueur(self):
listLieu=list(self.listLieu)
d0=0
if len(listLieu)>1:
for lieu1, lieu2 in zip(listLieu,listLieu[1:]):d0+=self.distance(lieu1, lieu2)
return d0
def distance(self, lieu1, lieu2):
"""
calcule la distance sur une sphere de deux point
"""
lon1, lat1, lon2, lat2 = map(math.radians, [lieu1.adresse.longitude, lieu1.adresse.latitude, lieu2.adresse.longitude,lieu2.adresse.latitude])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
km = 6367 * c
return km
@property
def kmlCoordonnees(self):
if self.listLieu:
return map(lambda lieu: lieu.adresse.point.kmlCoordonnees, self.listLieu)
else : return [(2.2923,48.8578)]
@kmlCoordonnees.setter
def kmlCoordonnees(self,kml_coordonnees):
kml_coordonnees=kml_coordonnees.strip()
list_str_point=kml_coordonnees.split(' ')
line=[]
for str_point in list_str_point:
str_lat_long=str_point.split(',')
lon=float(str_lat_long[0])
lat=float(str_lat_long[1])
point=PointK(longitude=lon,latitude=lat,parent=self)
lieu=point.matchingLieu(self.parent.listLieu)[0]
if lieu:
line.append(lieu.dbid)
self.chemin=line
@property
def chemin(self):
return self._chemin
@chemin.setter
def chemin(self,chemin):
self._chemin=chemin
if self.parent:self.parent.line=chemin
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.