blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f282ab057e0351546f634e05d3425f9bc588bd39 | trent-hodgins-01/ICS3U-Unit3-04-Python | /positive_negative.py | 569 | 4.25 | 4 | # !/user/bin/env python3
# Created by Trent Hodgins
# Created on 09/21/2021
# This is the Positive/ Negative/ 0
# The user enters in a number and the program tells the user if it's a positive, negative, or 0
def main():
# this function checks to see what sign the integer is
# input
number = int(input("Enter in a number to see its sign (integer): "))
print("")
# process and output
if number < 0:
print("-")
elif number > 0:
print("+")
else:
print("0")
print("\nDone")
if __name__ == "__main__":
main()
|
838ed301fc009df8061d63189d62f3c7faa776fa | codigomentor/python-tutorial | /Python/ciclos.py | 394 | 3.9375 | 4 | contador = 0
while contador <= 10:
contador += 1
if contador == 5:
continue
print(contador) # 1 2 ... 9 10 11
# for
print("---------------------------")
colores = ["red", "blue", "green"]
for color in colores:
if color == "blue":
continue
print(color)
texto = "computadora"
for n in texto:
print(n)
#range
for numero in range(5):
print(numero) |
4ab4714339c1944195316c4b1e836b55e48feec1 | adele2020/coding-master | /leetcode/[COMA9]스택_큐.py | 4,157 | 3.90625 | 4 | ####################################################
# p.243
# 연결 리스트를 이용한 스택 ADT 구현
####################################################
class Node:
def __init__(self, item, next):
self.item = item
self.next= next
class Stack:
def __init__(self):
self.last = None
def push(self, item):
self.last = Node(item, self.last)
print("{} = [ {} | {} ]".format(id(self.last), self.last.item, id(self.last.next)))
def pop(self):
item = self.last.item
print("변경전 : {} = [ {} | {} ]".format(id(self.last), self.last.item, id(self.last.next)))
self.last = self.last.next
print("변경후 : {} = [ {} | {} ]".format(id(self.last), self.last.item, id(self.last.next)))
return item
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
stack.pop()
for _ in range(5):
print(stack.pop())
#print("{} = [ {} | {} ]".format(id(self.last), self.last.item, id(self.last.next)))
#print("변경전 : {} = [ {} | {} ]".format(id(self.last), self.last.item, id(self.last.next)))
#print("변경후 : {} = [ {} | {} ]".format(id(self.last), self.last.item, id(self.last.next)))
#################################################################################
# 자료형 deque의 내장 메서드를 사용하여 구현 (double-ended queue) 데이터 양방향으로 추거 제거
# O(1)의 시간 복잡도로 리스트보다 성능 상에 이점
################################################################################
from collections import deque
queue = deque([4, 5, 6])
queue.append(7)
queue.append(8)
queue
queue.popleft()
queue.popleft()
queue
#######################################################################
# 자료형 queue의 내장 메서드를 사용하여 구현
#######################################################################
import queue
q = queue.Queue()
q.put("a")
q.put("b")
q.put("c")
q.qsize() # 3
q.get() # 'a'
q.qsize() # 2
#######################################################################
# 자료형 LifoQueue의 내장 메서드를 사용하여 구현
# Last in First Out Queue 구현하기
#######################################################################
import queue
q= queue.LifoQueue()
q.put("a")
q.put("b")
q.qsize() # 2
q.get() # 'b'
#######################################################################
# 자료형 PriorityQueue의 내장 메서드를 사용하여 구현
# 우선순위가 높은 큐가 먼저 나온다.
#######################################################################
import queue
q = queue.PriorityQueue()
q.put((10, "a"))
q.put((5, "b"))
q.put((15, "c"))
q.qsize() # 3
q.get() # (5, 'b')
#######################################################################
# 23. 큐를 이용한 스택 구현 (리트코드225.) *
# 큐를 이용해 다음 연산을 지원하는 스택을 구현하라.
# push(x): 요소 x를 스택에 삽입한다.
# pop(): 스택의 첫번째 요소를 삭제한다.
# top(): 스택의 첫 번째 요소를 가져온다.
# empty(): 스택이 비어 있는지 여부를 리턴한다.
#######################################################################
import collections
class MyStack:
def __init__(self):
self.q = collections.deque()
def push(self, x):
self.q.append(x)
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self):
return self.q.popleft() #int
def top(self):
return self.q[0] #int
def empty(self):
return len(self.q) == 0 #bool
stack = MyStack()
stack.push(1)
stack.push(2)
stack.top()
stack.pop()
stack.empty()
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
def remove(s: str):
for char in sorted(set(s)):
suffix = s[s.index(char)]
if set(s) == set(suffix)
return char + self.remove(suffix.replace(char,''))
return
print(set('cbacdcbc'))
|
b91efba3bde9cea227bd6469f2aa5dccb0683d37 | csy1993/PythonPractice | /toppings-if.py | 1,592 | 3.921875 | 4 | '''
* @Author: csy
* @Date: 2019-04-28 14:01:32
* @Last Modified by: csy
* @Last Modified time: 2019-04-28 14:01:32
'''
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese'in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!\n")
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print("Adding "+requested_topping)
print("\nFinished making your pizza!\n")
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == "green peppers":
print("Sorry,we are out of green peppers right now.")
else:
print("Adding "+requested_topping)
print("\nFinished making your pizza!\n")
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding "+requested_topping)
else:
print("Are you sure you want a plain pizza?\n")
available_toppings = ['mushrooms', 'olives',
'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding"+requested_topping)
else:
print("Sorry,we are out of "+requested_topping + "right now.")
print("\nFinished making your pizza!\n")
|
d8e515a71d3b3b1cc3e9d5fbd5d60259515e76a8 | javidkhalilov/Differential-Equations-Python-Implementation | /Apollo13Return.py | 5,561 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 19 22:55:55 2016
@author: Javid
"""
import math
import numpy
import matplotlib.pyplot
earth_mass = 5.97e24 # kg
earth_radius = 6.378e6 # m (at equator)
gravitational_constant = 6.67e-11 # m3 / kg s2
moon_mass = 7.35e22 # kg
moon_radius = 1.74e6 # m
moon_distance = 400.5e6 # m (actually, not at all a constant)
moon_period = 27.3 * 24.0 * 3600. # s
moon_initial_angle = math.pi / 180. * -61. # radian
total_duration = 12. * 24. * 3600. # s
marker_time = 0.5 * 3600. # s
tolerance = 100000. # m
def moon_position(time):
# Task 1: Compute the moon's position (a vector) at time t. Let it start at moon_initial_angle, not on the horizontal axis.
###Your code here.
moon_angle=moon_initial_angle+2.*math.pi*time/moon_period
position=numpy.zeros(2)
position[0]=moon_distance*numpy.array(math.cos(moon_angle))
position[1]=moon_distance*numpy.array(math.sin(moon_angle))
return position
def acceleration(time, position):
# Task 2: Compute the spacecraft's acceleration due to gravity
###Your code here.
moon_pos=moon_position(time)
vector_from_moon=position-moon_pos
vector_from_earth=position
acc=-gravitational_constant*(earth_mass/numpy.linalg.norm(vector_from_earth)**3*vector_from_earth\
+moon_mass/numpy.linalg.norm(vector_from_moon)**3*vector_from_moon)
return acc
axes = matplotlib.pyplot.gca()
axes.set_xlabel('Longitudinal position in m')
axes.set_ylabel('Lateral position in m')
# Task 5: (First see the other tasks below.) What is the appropriate boost to apply?
# Try -10 m/s, 0 m/s, 10 m/s, 50 m/s and 100 m/s and leave the correct amount in as you submit the solution.
def apply_boost():
# Do not worry about the arrays position_list, velocity_list, and times_list.
# They are simply used for plotting and evaluating your code, so none of the
# code that you add should involve them.
boost = 10. # m/s Change this to the correct value from the list above after everything else is done.
position_list = [numpy.array([-6.701e6, 0.])] # m
velocity_list = [numpy.array([0., -10.818e3])] # m / s
times_list = [0]
position = position_list[0]
velocity = velocity_list[0]
current_time = 0.
h = 0.1 # s, set as initial step size right now but will store current step size
h_new = h # s, will store the adaptive step size of the next step
mcc2_burn_done = False
dps1_burn_done = False
while current_time < total_duration:
#Task 3: Include a retrograde rocket burn at 101104 seconds that reduces the velocity by 7.04 m/s
# and include a rocket burn that increases the velocity at 212100 seconds by the amount given in the variable called boost.
# Both velocity changes should happen in the direction of the rocket's motion at the time they occur.
###Your code here.
if not mcc2_burn_done and current_time>=101104:
velocity-=7.04/numpy.linalg.norm(velocity)*velocity
mcc2_burn_done=True
if not dps1_burn_done and current_time>=212100:
velocity+=boost/numpy.linalg.norm(velocity)*velocity
dps1_burn_done=True
acc0=acceleration(current_time,position)
velE=velocity+h*acc0
posE=position+h*velocity
velH=velocity+h*0.5*(acc0+acceleration(current_time+h,posE))
posH=position+h*0.5*(velocity+velE)
velocity=velH
position=posH
error=numpy.linalg.norm(posE-posH)+total_duration*numpy.linalg.norm(velE-velH)
h_new=h*math.sqrt(tolerance/error)
#Task 4: Implement Heun's method with adaptive step size. Note that the time is advanced at the end of this while loop.
###Your code here.
###Your code here.
h_new = min(0.5 * marker_time, max(0.1, h_new)) # restrict step size to reasonable range
current_time += h
h = h_new
position_list.append(position.copy())
velocity_list.append(velocity.copy())
times_list.append(current_time)
return position_list, velocity_list, times_list, boost
position, velocity, current_time, boost = apply_boost()
def plot_path(position_list, times_list):
axes = matplotlib.pyplot.gca()
axes.set_xlabel('Longitudinal position in m')
axes.set_ylabel('Lateral position in m')
previous_marker_number = -1;
for position, current_time in zip(position_list, times_list):
if current_time >= marker_time * previous_marker_number:
previous_marker_number += 1
matplotlib.pyplot.scatter(position[0], position[1], s = 2., facecolor = 'r', edgecolor = 'none')
moon_pos = moon_position(current_time)
if numpy.linalg.norm(position - moon_pos) < 30. * moon_radius:
axes.add_line(matplotlib.lines.Line2D([position[0], moon_pos[0]], [position[1], moon_pos[1]], alpha = 0.3, c = 'g'))
axes.add_patch(matplotlib.patches.CirclePolygon((0., 0.), earth_radius, facecolor = 'none', edgecolor = 'b'))
for i in range(int(total_duration / marker_time)):
moon_pos = moon_position(i * marker_time)
axes.add_patch(matplotlib.patches.CirclePolygon(moon_pos, moon_radius, facecolor = 'none', edgecolor = 'g', alpha = 0.7))
matplotlib.pyplot.axis('equal')
plot_path(position, current_time) |
9440fa94feba029d562f113b048af4f264282c0f | nurnisi/algorithms-and-data-structures | /leetcode/0-250/258-1022. Sum of Root To Leaf Binary Numbers.py | 887 | 3.78125 | 4 | # 1022. Sum of Root To Leaf Binary Numbers
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumRootToLeaf2(self, root: TreeNode) -> int:
self.ans = 0
self.dfs(root, '')
return self.ans
def dfs(self, root, cur):
cur += str(root.val)
if not root.left and not root.right:
self.ans += int(cur, 2)
return
if root.left: self.dfs(root.left, cur)
if root.right: self.dfs(root.right, cur)
def sumRootToLeaf(self, root: TreeNode, val=0) -> int:
if not root: return 0
val = val * 2 + root.val
if not root.left and not root.right: return val
return self.sumRootToLeaf(root.left, val) + self.sumRootToLeaf(root.right, val)
|
2e51b00fd2cb7aeb11034301841d5594be35f931 | ManuelMBaumann/coursera_ml | /machine-learning-ex2/ex2-python/ex2.py | 5,602 | 4.15625 | 4 | ## Machine Learning Online Class - Exercise 2: Logistic Regression
#
# Instructions
# ------------
#
# This file contains code that helps you get started on the logistic
# regression exercise. You will need to complete the following functions
# in this exericse:
#
# sigmoid.py
# costFunction.py
# predict.py
# costFunctionReg.py
#
# For this exercise, you will not need to change any code in this file,
# or any other files other than those mentioned above.
#
## Load Data
# The first two columns contains the exam scores and the third column
# contains the label.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
def plotData(X,y):
# Find Indices of Positive and Negative Examples
pos = np.where(y==1)
neg = np.where(y==0)
plt.plot(X[pos, 0], X[pos, 1], 'k+')
plt.plot(X[neg, 0], X[neg, 1], 'yo')
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.legend(['Admitted', 'Not admitted'])
plt.show()
def plotDecisionBoundary(theta, X, y):
# Find Indices of Positive and Negative Examples
pos = np.where(y==1)
neg = np.where(y==0)
plt.plot(X[pos, 1], X[pos, 2], 'k+')
plt.plot(X[neg, 1], X[neg, 2], 'yo')
if(X.shape[1] <= 3):
#Only need 2 points to define a line, so choose two endpoints
plot_x = np.array([min(X[:,1])-2, max(X[:,1])+2])
# Calculate the decision boundary line
plot_y = (-1./theta[2])*(theta[1]*plot_x + theta[0])
plt.plot(plot_x, plot_y)
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score')
plt.legend(['Admitted', 'Not admitted', 'Decision Boundary'])
plt.show()
sigmoid = lambda z: 1.0/(1.0+np.exp(-z))
def costFunction(theta, X, y):
m = len(y)
cost = 0.0
for i in range(m):
cost = cost + (-y[i]*np.log(sigmoid(np.dot(theta.T,X[i,:]))) - (1-y[i])*np.log(1-sigmoid(np.dot(theta.T,X[i,:]))))
return 1.0/m*cost
def costFunction_der(theta, X, y):
m = len(y)
grad = 0.0*theta
for i in range(m):
for j in range(len(theta)):
grad[j] = grad[j] + ( sigmoid(np.dot(theta.T,X[i,:])) -y[i] )*X[i,j]
return 1.0/m*grad
data = np.loadtxt('ex2data1.txt')
X = data[:, :2]
y = data[:, -1]
### ==================== Part 1: Plotting ====================
## We start the exercise by first plotting the data to understand the
## the problem we are working with.
print(['Plotting data with + indicating (y = 1) examples and o indicating (y = 0) examples.'])
plotData(X, y)
input("Press Enter to continue...")
### ============ Part 2: Compute Cost and Gradient ============
## In this part of the exercise, you will implement the cost and gradient
## for logistic regression. You need to complete the code in
## costFunction.py
## Setup the data matrix appropriately, and add ones for the intercept term
m, n = X.shape
## Add intercept term to x and X_test
X = np.ones((m,n+1), dtype=float)
X[:,1:] = data[:, :2]
## Initialize fitting parameters
initial_theta = np.zeros((n+1,1))
## Compute and display initial cost and gradient
cost = costFunction(initial_theta, X, y)
grad = costFunction_der(initial_theta, X, y)
print(['Cost at initial theta (zeros): ', cost])
print('Expected cost (approx): 0.693\n')
print('Gradient at initial theta (zeros): \n')
print([' #f \n', grad])
print('Expected gradients (approx):\n -0.1000\n -12.0092\n -11.2628\n')
## Compute and display cost and gradient with non-zero theta
test_theta = np.array([-24, 0.2, 0.2])
cost = costFunction(test_theta, X, y)
grad = costFunction_der(test_theta, X, y)
print(['Cost at test theta: ', cost])
print('Expected cost (approx): 0.218')
print('Gradient at test theta: ')
print(' #f ', grad)
print('Expected gradients (approx):\n 0.043\n 2.566\n 2.647\n')
input("Press Enter to continue...")
### ============= Part 3: Optimizing using fminunc =============
## In this exercise, you will use a built-in function (fminunc) to find the
## optimal parameters theta.
## Run fminunc to obtain the optimal theta
## This function will return theta and the cost
res = minimize(lambda t: costFunction(t, X, y), initial_theta, method='BFGS', jac=lambda t:costFunction_der(t, X, y),
options={'disp':True, 'maxiter':400})
cost = res.fun
theta = res.x
## Print theta to screen
print(['Cost at theta found by fminunc: ', cost])
print('Expected cost (approx): 0.203')
print('theta:')
print([' #f ', theta])
print('Expected theta (approx):')
print('-25.161 0.206 0.201')
## Plot Boundary
plotDecisionBoundary(theta, X, y)
input("Press Enter to continue...")
### ============== Part 4: Predict and Accuracies ==============
## After learning the parameters, you'll like to use it to predict the outcomes
## on unseen data. In this part, you will use the logistic regression model
## to predict the probability that a student with score 45 on exam 1 and
## score 85 on exam 2 will be admitted.
##
## Furthermore, you will compute the training and test set accuracies of
## our model.
##
## Your task is to complete the code in predict.m
## Predict probability for a student with score 45 on exam 1
## and score 85 on exam 2
#prob = sigmoid([1 45 85] * theta);
#fprintf(['For a student with scores 45 and 85, we predict an admission ' ...
#'probability of #f\n'], prob);
#fprintf('Expected value: 0.775 +/- 0.002\n\n');
## Compute accuracy on our training set
#p = predict(theta, X);
#fprintf('Train Accuracy: #f\n', mean(double(p == y)) * 100);
#fprintf('Expected accuracy (approx): 89.0\n');
#fprintf('\n');
|
349cae191cd984bd5f01a15b3f6046fcbd38687a | TyroneWilkinson/Python_Practice | /climb_leaderboard.py | 960 | 4 | 4 | # https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
# Not fast enough.
def climbingLeaderboard(l, p):
"""
Determine a player's ranking after each game played given his scores
and the leaderboard scores.
Note: The game uses dense ranking.
Parameters:
l (list): An integer list representing the leaderboard scores.
p (list): An integer list representing the player's scores.
Returns:
list: An integer list representing the player's ranking after each score.
"""
ranks = []
l = sorted(list(set(l)), reverse=True)
for ele in p:
if ele not in l:
l.append(ele); l.sort(reverse=True) # Avoids duplicates and reorders
ranks.append(l.index(ele) + 1) # Ranking starts with "1" not "0"
return ranks
input()
leaderboard = [int(x) for x in input().split()]
input()
player = [int(x) for x in input().split()]
print(climbingLeaderboard(leaderboard,player)) |
24a740b20e3e39246d0d02920d05d835ff628cfe | NolanMeacham/Chinese-vocab | /draft_files/char_test.py | 874 | 3.765625 | 4 | """
Tests the functionality of vocab quiz using Chinese Characters
"""
def main():
from numpy import loadtxt
# vocab = loadtxt(f'python_vocab/vocab_quiz/vocab_files/lesson5_vocab_characters.txt', dtype=str, delimiter=',')
vocab = loadtxt('/Users/nolan/Documents/BYUI/BYUI/2021-1-Winter/CHINA101-Mandarin/python_vocab/vocab_quiz/vocab_files/lesson5_vocab_characters.txt', dtype=str, delimiter=',')
# print(vocab)
chars = vocab[:,0]
pinyins = vocab[:,1]
definitions = vocab[:,2]
# run the quiz
for index, word in enumerate(chars):
user_input = input(f'{index+1}. {word}: ')
if user_input.lower() == pinyins[index].lower():
print('correct!')
print()
else:
print(f'Incorrect. {word} means {pinyins[index].lower()}')
print()
if __name__ == "__main__":
main() |
7a7c108b00c7063e806f8f1b50ba02697777e59b | Dewansh1029/covid19_vaccine_detail- | /covid19_vaccine/covid_bl.py | 18,548 | 3.78125 | 4 | import covid_db as database
import sys
from sys import exit
import datetime
# def main():
# val = input(" For adding vaccine name, date and place of manufacturing and date of expiry: \n Press 1 \n For adding vaccine name its availability and quantity: \n Press 2 \n To see vaccine name, date and place of manufacturing and date of expiry: \n Press 3 \n To see vaccine name its availability and quantity: \n Press "\
# "4 \n For updating vaccine manufacture and expiry\n Press 5\n For updating availability and quantity: \n Press 6\n For deleting any information: \n Press 7\n")
# if val == "1" :
# name = input("Enter vaccine name: ")
# detail = input("Enter vaccine detail: ")
# manufacture_place = input("Enter vaccine manufacture place: ")
# manufacture_date = input("Enter vaccine manufacture date(YYYY-MM-DD): ")
# expiry = input("Enter vaccine expiry(YYYY-MM-DD): ")
# if manufacture_date > expiry :
# print ('Incorrect data in date field!')
# sys.exit()
# else :
# col_name = ['vac_name', 'vac_detail', 'vac_manufacture_place', 'vac_manufacture_date', 'vac_expiry']
# col_values = [name, detail, manufacture_place, manufacture_date, expiry]
# table_name = "aboutvac"
# database.insertQuery (col_name, col_values, table_name)
# print("Successfully added, press 3 to see")
# elif val == "2" :
# name = input("Enter vaccine name: ")
# available_in_cities = input("Enter vaccine available in cities: ")
# available_from = input("Enter vaccine availablity start date(YYYY-MM-DD): ")
# available_till = input("Enter vaccine availablity end date(YYYY-MM-DD): ")
# quantity_in_bottles = input("Enter no. of bottles of available vaccine: ")
# if available_from > available_till :
# print ('Incorrect data in date field!')
# sys.exit()
# else :
# col_name = ['vac_name', 'vac_cities', 'vac_startdate' , 'vac_enddate', 'vac_quantity']
# col_values = [name, available_in_cities, available_from, available_till, quantity_in_bottles]
# table_name = "eachvacdetail"
# database.insertQuery (col_name, col_values, table_name)
# print("Successfully added, press 4 to see")
# elif val == "3" :
# print("Vaccine name and manugactured by: \n")
# lst_col = ['vac_name', 'vac_detail']
# table_name = "aboutvac"
# select = database.selectQuery (lst_col, table_name)
# for x in select:
# print(x)
# elif val == "4" :
# print("Vaccine name and quantity: \n")
# lst_col = ['vac_name', 'vac_quantity']
# table_name = "eachvacdetail"
# select = database.selectQuery (lst_col, table_name)
# for x in select:
# print(x)
# elif val == "5" :
# table_name = "aboutvac"
# vac_name = input('Enter vaccine name whose details you want to change: ')
# vac_manufactured_by = input('Enter new manufacturer ')
# vac_manufacture_place = input('Enter new manufacture place ')
# vac_manufacture_date = input('Enter new manufacture date ')
# vac_expiry = input('Enter new expiry date ')
# col_name = ['vac_detail', 'vac_manufacture_place', 'vac_manufacture_date', 'vac_expiry']
# col_values = [vac_manufactured_by, vac_manufacture_place, vac_manufacture_date, vac_expiry]
# database.updateQuery (table_name, col_name, col_values, vac_name)
# print("Successfully updated, press 3 to see")
# elif val == "6" :
# table_name = "eachvacdetail"
# vac_name = input('Enter vaccine name whose details you want to change: ')
# cities = input('Enter new manufacturer: ')
# startdate = input('Enter new manufacture place: ')
# enddate = input('Enter new manufacture date: ')
# quantity = input('Enter new expiry date: ')
# col_name = ['vac_cities', 'vac_startdate', 'vac_enddate', 'vac_quantity']
# col_values = [cities, startdate, enddate, quantity]
# database.updateQuery (table_name, col_name, col_values, vac_name)
# print("Successfully updated, press 4 to see")
# elif val == "7" :
# table_name = input('Enter table name: ')
# vac_name = input('Enter vaccine name to be deleted: ')
# database.deleteQuery (table_name, vac_name)
# print("Successfully deleted")
# else :
# print("Incorrect input")
def input_table2(name, available_in_cities, available_from, available_till, quantity_in_bottles) :
print('Inside businesslayer function')
col_name = ['vac_name', 'vac_cities', 'vac_startdate' , 'vac_enddate', 'vac_quantity']
col_values = [name, available_in_cities, available_from, available_till, quantity_in_bottles]
table_name = "vaccine_loc"
database.insertQuery (col_name, col_values, table_name)
def input_table1(name, detail, manufacture_place, manufacture_date, expiry) :
col_name = ['vac_name', 'vac_detail', 'vac_manufacture_place', 'vac_manufacture_date', 'vac_expiry']
col_values = [name, detail, manufacture_place, manufacture_date, expiry]
table_name = "vaccine_details"
database.insertQuery (col_name, col_values, table_name)
def insert_userDetails(name, userid, password) :
col_name = ['name', 'userid', 'password']
col_values = [name, userid, password]
table_name = "user_details"
database.insertQuery (col_name, col_values, table_name)
def insert_contact(cname, cemail, caddress) :
col_name = ['name', 'email', 'address']
col_values = [cname, cemail, caddress]
table_name = 'contact_details'
database.insertQuery (col_name, col_values, table_name)
# def show_details(vaccine_name) :
# lst_col = ['vac_name']
# table_name = 'vaccine_details'
# names = str(database.selectQuery(lst_col, table_name))
# print(names)
# if vaccine_name not in names or vaccine_name == '':
# print('Vaccine name does not exits in table!')
# return [],0
# # return 0
# else :
# lst_output = database.show_single_row(vaccine_name)
# print(type(lst_output))
# return lst_output,1
# # return 1
def only_vac_name():
lst_col = ['vac_name']
table_name = "vaccine_details"
data = database.selectQuery (lst_col,table_name)
return data
# def select_by_vac_name() :
# lst_col = ['vac_name']
# table_name = "vaccine_details"
# data = selectQuery (lst_col,table_name)
# print(data)
# return data
def update_by_vac_name(vname, vby, vplace, vdate, vexpiry) :
table_name = 'vaccine_details'
col_name = ['vac_detail', 'vac_manufacture_place', 'vac_manufacture_date', 'vac_expiry']
col_values = [vby, vplace, vdate, vexpiry]
vac_name = vname
database.updateQuery (table_name, col_name, col_values, vac_name)
return
def show_details(vaccine_name) :
lst_output = database.show_single_row(vaccine_name)
if len(lst_output)==0 or vaccine_name == '':
print('Vaccine name does not exits in table!')
return [],0
# return 0
else :
return lst_output,1
# return 1
def show_full_table_details(name) :
lst_output = database.search_all_rows(name)
if len(lst_output) == 0 or name == '':
print('Vaccine name does not exits in table!')
return [],0
else :
return lst_output,1
# return 1
def check_user(userid, password) :
table_name = "user_details"
user_lst = ['userid']
users = str(database.selectQuery(user_lst, table_name))
print(users)
pass_lst = ['password']
passwords = str(database.select_where(pass_lst, table_name, userid))
print(passwords)
if userid not in users or len(userid)==0:
print('You are not registered \n Sign up to register yourself!')
return 0
elif password not in passwords or len(password)==0:
print('Incorrect password!')
return 1
return 2
def checkinput(name):
if len(name) == 0 :
print('Data is not valid!')
sys.exit()
def signupDetails(name, uid, password, conpassword) :
if len(name) == 0 or len(uid) == 0 or len(password) == 0:
return 0
elif password != conpassword:
return 1
return 2
# def show_dropdown2val1() :
# table_name = "vaccine_details"
# col_name = [vac_detail, vac_manufacture_place, vac_manufacture_date,vac_expiry]
# updateQuery (table_name, col_name, col_values, vac_name)
def main():
val = input(" For adding vaccine name, date and place of manufacturing and date of expiry: \n Press 1 \n For adding vaccine name its availability and quantity: \n Press 2 \n To see vaccine name, date and place of manufacturing and date of expiry: \n Press 3 \n To see vaccine name its availability and quantity: \n Press "\
"4 \n For updating vaccine manufacture and expiry\n Press 5\n For updating availability and quantity: \n Press 6\n For deleting any information: \n Press 7\n To exit, type exit: \n")
while val :
if val == "exit" :
sys.exit()
# val = input(" For adding vaccine name, date and place of manufacturing and date of expiry: \n Press 1 \n For adding vaccine name its availability and quantity: \n Press 2 \n To see vaccine name, date and place of manufacturing and date of expiry: \n Press 3 \n To see vaccine name its availability and quantity: \n Press "\
# "4 \n For updating vaccine manufacture and expiry\n Press 5\n For updating availability and quantity: \n Press 6\n For deleting any information: \n Press 7\n")
if val == "1" :
name = input("Enter vaccine name: ")
checkinput(name)
detail = input("Enter vaccine detail: ")
checkinput(detail)
manufacture_place = input("Enter vaccine manufacture place: ")
checkinput(manufacture_place)
manufacture_date = input("Enter vaccine manufacture date(YYYY-MM-DD): ")
checkinput(manufacture_date)
expiry = input("Enter vaccine expiry(YYYY-MM-DD): ")
checkinput(expiry)
if manufacture_date > expiry :
print ('Incorrect data in date field!')
return
else :
col_name = ['vac_name', 'vac_detail', 'vac_manufacture_place', 'vac_manufacture_date', 'vac_expiry']
col_values = [name, detail, manufacture_place, manufacture_date, expiry]
table_name = "vaccine_details"
database.insertQuery (col_name, col_values, table_name)
elif val == "2" :
name = input("Enter vaccine name: ")
checkinput(name)
lst_col = ['vac_name']
table_name = 'vaccine_details'
names = str(database.selectQuery(lst_col, table_name))
if name not in names:
print('Vaccine location can not be added, first add vaccine details!')
break
available_in_cities = input("Enter vaccine available in cities: ")
checkinput(available_in_cities)
available_from = input("Enter vaccine availablity start date(YYYY-MM-DD): ")
checkinput(available_from)
try:
datetime.datetime.strptime(available_from, '%Y-%m-%d')
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
continue
available_till = input("Enter vaccine availablity end date(YYYY-MM-DD): ")
checkinput(available_till)
try:
datetime.datetime.strptime(available_till, '%Y-%m-%d')
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
continue
quantity_in_bottles = input("Enter no. of bottles of available vaccine: ")
checkinput(quantity_in_bottles)
# if type(quantity_in_bottles) != int :
# print('Invalid data!')
# print(type(quantity_in_bottles))
# continue
if available_from > available_till :
print ('Incorrect data in date field!')
return
# sys.exit()
else :
col_name = ['vac_name', 'vac_cities', 'vac_startdate' , 'vac_enddate', 'vac_quantity']
col_values = [name, available_in_cities, available_from, available_till, quantity_in_bottles]
table_name = "vaccine_loc"
database.insertQuery (col_name, col_values, table_name)
elif val == "3" :
lst_col = ['vac_name', 'vac_detail']
table_name = "vaccine_details"
select = database.selectQuery (lst_col, table_name)
print('Vaccine name',' ', 'vaccine manufactured by:')
for x in select :
print(x[0],' ',x[1])
elif val == "4" :
lst_col = ['vac_name', 'vac_quantity']
table_name = "vaccine_loc"
select = database.selectQuery (lst_col, table_name)
print('Vaccine name',' ', 'vaccine quantity(in bottles):')
for x in select :
print(x[0],' ',x[1])
elif val == "5" :
table_name = "vaccine_details"
vac_name = input('Enter vaccine name whose details you want to change: ')
checkinput(vac_name)
lst_col = ['vac_name']
names = str(database.selectQuery(lst_col, table_name))
if vac_name not in names:
print('Vaccine name does not exits in table!')
break
else :
vac_manufactured_by = input('Enter new manufacturer ')
checkinput(vac_manufactured_by)
vac_manufacture_place = input('Enter new manufacture place ')
checkinput(vac_manufacture_place)
vac_manufacture_date = input('Enter new manufacture date ')
invalidinput(vac_manufacture_date)
try:
datetime.datetime.strptime(vac_manufacture_date, '%Y-%m-%d')
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
continue
vac_expiry = input('Enter new expiry date ')
invalidinput(vac_expiry)
col_name = ['vac_detail', 'vac_manufacture_place', 'vac_manufacture_date', 'vac_expiry']
col_values = [vac_manufactured_by, vac_manufacture_place, vac_manufacture_date, vac_expiry]
database.updateQuery (table_name, col_name, col_values, vac_name)
elif val == "6" :
table_name = "vaccine_loc"
vac_name = input('Enter vaccine name whose details you want to change: ')
checkinput(vac_name)
lst_col = ['vac_name']
names = str(database.selectQuery(lst_col, table_name))
if vac_name not in names:
print('Vaccine name does not exits in table!')
break
cities = input('Enter new manufacture city: ')
checkinput(cities)
startdate = input('Enter new avalable start date: ')
checkinput(startdate)
try:
datetime.datetime.strptime(startdate, '%Y-%m-%d')
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
continue
enddate = input('Enter new avalable end date: ')
checkinput(enddate)
try:
datetime.datetime.strptime(enddate, '%Y-%m-%d')
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
continue
quantity = input('Enter new quantity ')
checkinput(quantity)
col_name = ['vac_cities', 'vac_startdate', 'vac_enddate', 'vac_quantity']
col_values = [cities, startdate, enddate, quantity]
database.updateQuery (table_name, col_name, col_values, vac_name)
elif val == "7" :
table_name = input('Enter table name: ')
if table_name != 'vaccine_details' and table_name != 'vaccine_loc' :
print('No table exist!')
return
vac_name = input('Enter vaccine name to be deleted: ')
checkinput(vac_name)
lst_col = ['vac_name']
names = str(database.selectQuery(lst_col, table_name))
if vac_name not in names:
print('Vaccine name does not exits!')
break
database.deleteQuery (table_name, vac_name)
print("Successfully deleted!")
else :
print("Incorrect input")
val = input(" For adding vaccine name, date and place of manufacturing and date of expiry: \n Press 1 \n For adding vaccine name its availability and quantity: \n Press 2 \n To see vaccine name, date and place of manufacturing and date of expiry: \n Press 3 \n To see vaccine name its availability and quantity: \n Press "\
"4 \n For updating vaccine manufacture and expiry\n Press 5\n For updating availability and quantity: \n Press 6\n For deleting any information: \n Press 7\n To exit, type exit: \n")
if val == "exit" :
sys.exit()
# unknown error:
# UPDATE aboutvac SET vac_detail= 'sfaf', vac_manufacture_place= 'fsgv', vac_manufacture_date= '2020-02-12', vac_expiry = '2020-02-30' WHERE vac_name = 'coromil';
# INSERT INTO vaccine_loc(vac_name, vac_cities, vac_startdate, vac_enddate, vac_quantity) VALUES ('zvd', 'zv', '2120-03-02', '2910-02-30', '3')
if __name__ == '__main__':
main() |
d1ab9e445949aee4cc120e1cc07eb61406fd1683 | MikaPY/HomeworkPY | /hw13.py | 556 | 4.0625 | 4 |
# # Перевернутый кортеж
# tup = ('Mika', 1995, 'Yerevan') # кортеж
# print(tup[::-1]) # переворачивает кортеж
# # Подсчёт длины символов.
# tup2 = ('Python', 'good','languages') # кортеж
# print(len(tup2)) # изм. длину.
# # Конвертация кортежа в строку.
# tup = ('P','y','t','h','o','n') # кортеж
# str = ''.join(tup) # Конвертация
# print(str) # Вывод
my_tuple = (1,12,15)
res = 0
for i in my_tuple:
res += i
print(res) |
a0ed23df1351cdac15d11a95b46d427d806d0fa3 | mushfiqulIslam/tkinterbasic | /pad.py | 405 | 3.78125 | 4 | from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack(fill=BOTH, expand=TRUE)
l1 = Label(frame, text="Tkinter Label", bg="red", fg="white")
l1.pack(side=TOP, padx=10, pady=10)
l2 = Label(frame, text="Tkinter Label", bg="yellow", fg="black")
l2.pack(side=LEFT, padx=10, pady=10)
l3 = Label(frame, text="Tkinter Label", bg="blue", fg="white")
l3.pack(side=LEFT, padx=10, pady=10)
mainloop()
|
494e0942113264462d58649a93b18a31a5d1fbcb | Indhuu/git-github | /python/name.py | 370 | 4.09375 | 4 | # name program
#print ('What is your Name?')
#Name = input()
#print ('How old are you?')
#Age = input()
#print ('My name is ' + Name)
print('What is your Name?')
Name = input()
print('It is good to meet you ' + Name)
print ('the length of your name is ' + str(len(Name)))
print('What is your Age?')
Age = input()
print('You will be '+ str(int(Age)+1) + 'in a year')
|
a12d44dcce227ecee14ab776dd2d39ef8eb95798 | github5507/geeksforgeeks | /scikit_learn/training-model.py | 1,081 | 3.515625 | 4 | # load the iris dataset as an example
from sklearn.datasets import load_iris
iris = load_iris()
# store the feature matrix (X) and response vector (y)
X = iris.data
y = iris.target
# splitting X and y into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)
# training the model on training set
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# making predictions on the testing set
y_pred = knn.predict(X_test)
# comparing actual response values (y_test) with predicted response values (y_pred)
from sklearn import metrics
print("kNN model accuracy:", metrics.accuracy_score(y_test, y_pred))
# making prediction for out of sample data
sample = [[3, 5, 4, 2], [2, 3, 5, 4]]
preds = knn.predict(sample)
pred_species = [iris.target_names[p] for p in preds]
print("Predictions:", pred_species)
# saving the model
from sklearn.externals import joblib
joblib.dump(knn, 'iris_knn.pkl')
|
ac93f50c51aadae0e7f7e96b22c5bf40483d6b08 | candyer/codechef | /August Challenge 2019/KS1/KS1.py | 1,672 | 3.546875 | 4 | # https://www.codechef.com/AUG19A/problems/KS1
###brute force (Subtask 1)#######################################
def f(array, a, b):
res = array[a]
for i in range(a + 1, b):
res ^= array[i]
return res
def solve1(n, array):
res = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j, n):
if f(array, i, j) == f(array, j, k + 1):
res += 1
return res
###(Subtask 1, 2)################################################
from collections import defaultdict
def solve2(n, array):
count = tmp = 0
prefix_XOR = []
for i in range(n):
tmp ^= array[i]
prefix_XOR.append(tmp)
if tmp == 0:
count += i
d = defaultdict(list)
for i, num in enumerate(prefix_XOR):
d[num].append(i)
for k, v in d.items():
m = len(v)
if m > 1:
for i in range(m):
for j in range(i + 1, m):
count += v[j] - v[i] - 1
return count
###(Subtask 1, 2, 3) AC ############################################
from collections import defaultdict
def solve(n, array):
count = tmp = 0
d = defaultdict(list)
prefix_XOR = []
for i in range(n):
tmp ^= array[i]
prefix_XOR.append(tmp)
d[tmp].append(i)
if tmp == 0:
count += i
for k, v in d.items():
m = len(v)
if m > 1:
for i in range(m):
count += i * v[i] - (m - i - 1) * v[i]
count -= m * (m - 1) / 2
return count
if __name__ == '__main__':
t = int(raw_input())
for _ in range(t):
n = int(raw_input())
array = map(int, raw_input().split())
print solve(n, array)
assert solve(3, [5, 2, 7]) == 2
assert solve(4, [2, 1, 1, 2]) == 4
assert solve(6, [1, 2, 3, 4, 5, 6]) == 5
assert solve1(5, [1, 2, 1, 2, 1]) == 6
assert solve(8, [5, 2, 7, 5, 2, 7, 5, 2]) == 27
|
514616d790659365694e118c983e53eb48d614a8 | NagahShinawy/100-days-of-code | /day_27/config.py | 1,032 | 3.71875 | 4 | """
created by Nagaj at 26/06/2021
"""
import tkinter
def center(window, window_width, window_height):
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x_cordinate = int((screen_width / 2) - (window_width / 2))
y_cordinate = int((screen_height / 2) - (window_height / 2))
window.geometry(f"{window_width}x{window_height}+{x_cordinate}+{y_cordinate}")
def setup(title="", image=None, width=300, height=300, is_center=False) -> tkinter.Tk:
"""
create tkinter window with title and image title bar
:param title: title bar
:param image: image title bar
:param width: window width
:param height: window height
:param is_center: if true center window on screen
:return: tkinter window
"""
window = tkinter.Tk()
window.minsize(width=width, height=height)
if image is not None:
window.iconbitmap(image)
if title:
window.title(title)
if is_center:
center(window, width, height)
return window
|
d1b1fc9b8a61eb0faffdcf63377b13afbbd52a7c | knoopr/3700_a3 | /alphaandbeta.py | 6,308 | 3.640625 | 4 | import sys
from copy import deepcopy
class Node():
def __init__(self,given_Board, the_Player, the_Opponent, goal_Depth, root_Depth, given_Alpha, given_Beta):
self.board = given_Board
self.player = the_Player
self.opponent = the_Opponent
self.depth = goal_Depth
self.root = root_Depth
self.possible_Moves = []
self.max_Score = (0,0)
self.worst_Score = (0,0)
self.alpha = given_Alpha
self.beta = given_Beta
#Return value as 100 or 0
def Get_move(self):
#If the look ahead depth is not reached compare the value of each branch node
if self.depth != 0:
self.Place_pieces()
#If you are the first root node score all next moves to see if you can win the game
if self.depth == self.root:
for i in self.possible_Moves:
possible_Win = Node(i[1], self.player, self.opponent, self.depth - 1, self.root, self.alpha, self.beta)
if possible_Win.Score_easy() == 100:
return (i[0], 100)
# Return Max
if self.depth%2 == 0:
for i in self.possible_Moves:
resultant_Score = Node(i[1], self.player, self.opponent, self.depth - 1, self.root, self.alpha, self.beta).Get_move()
if resultant_Score[1] != None and resultant_Score[1] > self.alpha[1]:
self.alpha = (i[0], resultant_Score[1])
if self.beta[1] < self.alpha[1]:
break
return self.alpha
#Return Min
elif self.depth%2 == 1:
for i in self.possible_Moves:
resultant_Score = Node(i[1], self.player, self.opponent, self.depth - 1, self.root, self.alpha, self.beta).Get_move()
if resultant_Score[1] != None and resultant_Score[1] < self.beta[1]:
self.beta = (i[0], resultant_Score[1])
if self.beta[1] < self.alpha[1]:
break
return self.beta
#If the look ahead depth is reached return the score of each node
elif self.depth == 0:
return (None, self.Score_easy())
#First return function 100 if win -100 if loss
def Score_easy(self):
self.Vertical_score()
self.Horizontal_score()
if self.worst_Score[1] <= -4:
return -100
elif self.max_Score[1] >= 4:
return 100
else:
return 0
#Create every possible board placement
def Place_pieces(self):
if self.depth%2 == 1:
placing = self.opponent
else:
placing = self.player
for the_Move in range(7):
if self.board[0][the_Move] == " ":
for i in range(0,6):
if self.board[i][the_Move] != " ": #If it falls and hits another piece.
new_Board = deepcopy(self.board)
new_Board[i-1] = new_Board[i-1][:the_Move] + placing + self.board[i-1][the_Move+1:]
self.possible_Moves.append((the_Move, new_Board))
break
elif i == 5: #if it reaches the bottom of the Column.
new_Board = deepcopy(self.board)
new_Board[5] = new_Board[5][:the_Move] + placing + self.board[5][the_Move+1:]
self.possible_Moves.append((the_Move, new_Board))
break
#Get the vertical score of the current board
def Vertical_score(self):
for row in range(0,7):
count = 0
for col in range(0,6):
if self.board[5-col][row] == self.player:
if count < 0:
count = 1;
else:
count += 1;
elif self.board[5-col][row] == self.opponent:
if count > 0:
count = -1;
else:
count -= 1;
if count > self.max_Score[1]:
self.max_Score = (row, count)
if count < self.worst_Score[1]:
self.worst_Score = (row, count)
#Get the horizontal score of the current board
def Horizontal_score(self):
for col in range(0,6):
count = 0
for row in range(0,7):
if self.board[col][row] == self.player:
if count < 0:
count = 1;
else:
count += 1;
elif self.board[col][row] == self.opponent:
if count > 0:
count = -1;
else:
count -= 1;
if self.board[col][row] == " ":
count = 0
if count > self.max_Score[1]:
self.max_Score = (row, count)
if count < self.worst_Score[1]:
self.worst_Score = (row, count)
"""
#If the ai player can win on the first move return that they can win
if self.depth == self.root - 1:
for i in self.possible_Moves:
first_Move = Node(i[1], self.player, self.opponent, sys.maxint, self.depth - 1, self.root)
result = first_Move.Score_easy()
if result == 100:
return (first_Move.max_Score[1], result)
#Generate the possible moves
for i in self.possible_Moves:
result = Node(i[1], self.player, self.opponent, sys.maxint, self.depth - 1, self.root).Easy_ai()
if self.depth%2 == 1 and result > self.value:
self.value = result
print self.value
elif self.depth%2 == 0 and result < self.value:
self.value = result
print self.value
if self.depth%2 == 0 and result > self.value:
self.value = result
if self.depth%2 == 1 and result < self.value:
self.value = result
"""
|
726103e3ac5f6adb7ef0d3e5fd2449f7d4ce9dd6 | yatfungleung/amazon-fashion-recommendation | /app.py | 5,432 | 3.53125 | 4 | import streamlit as st
import pandas as pd
from PIL import Image
img = Image.open('image/streamlit/calvin_klein_poster.jpg')
st.image(img, use_column_width='always')
st.title('Amazon Fashion Recommender')
st.write('created by Abraham Leung')
st.write('-------------------------')
img = Image.open('image/streamlit/abraham_leung_logo.jpg')
st.sidebar.image(img, width=300)
st.sidebar.title('Business Value:')
st.sidebar.write('''
This software will recommend customers with similar fashion products with respect to Calvin Klein's products they are browsing.\n
So companies can advertise their own brands by providing products based on customers' recent preferences.
''')
with st.sidebar.beta_expander('Definition'):
st.write('''
"Amazon Fashion Recommender" is a machine learning recommendation application.\n
The product details that used to train the algorithm were collected from the official website of Calvin Klein.\n
The recommender selects similar Amazon products based on the product names and images.
''')
with st.sidebar.beta_expander('Disclaimer'):
st.write('''
This web application is meant for educational and informational purposes only.
''')
st.sidebar.write('-------------------------')
st.sidebar.title('Contact:')
linkedin1, linkedin2 = st.sidebar.beta_columns([1,4])
with linkedin1:
img = Image.open('image/streamlit/linkedin_logo.png')
st.image(img, width=30)
with linkedin2:
link1 = "[Abraham's LinkedIn](https://www.linkedin.com/in/abraham-leung-data-science)"
st.markdown(link1, unsafe_allow_html=True)
github1, github2 = st.sidebar.beta_columns([1,4])
with github1:
img = Image.open('image/streamlit/github_logo.png')
st.image(img, width=30)
with github2:
link2 = "[Abraham's GitHub](https://github.com/yatfungleung)"
st.markdown(link2, unsafe_allow_html=True)
# create function
# main function
def main(apparel):
st.write('-------------------------')
# load data
df = pd.read_csv(f'data/{apparel}_recommender.csv')
for i in range(len(df)):
# ck columns
col0, col1 = st.beta_columns((1,2))
with col0:
# ck product image
img = Image.open(df['img_file'][i])
st.image(img)
with col1:
# ck logo
img = Image.open('image/streamlit/calvin_klein_logo.jpg')
st.image(img, width=100)
ck_name = df['name'][i]
ck_price = df['price'][i]
# ck product name and price
st.write(ck_name)
st.write(ck_price, ' \+ Shipping Fee')
# link to amazon product page
html = df['url'][i]
link = f"[More Details]({html})"
st.markdown(link, unsafe_allow_html=True)
# amazon columns
col0, col1, col2, col3 = st.beta_columns((1,2,1,2))
ck_price = float(ck_price.replace(',','')[4:])
with col0:
# amazon product 1 image
img = Image.open(df['recommend_img_file1'][i])
st.image(img)
with col1:
# amazon logo
img = Image.open('image/streamlit/amazon_logo.jpg')
st.image(img, width=70)
amazon_price = df['recommend_price1'][i]
# amazon prodcut 1 price
st.write(amazon_price, ' \+ Shipping Fee')
# show the price difference
amazon_price = float(amazon_price.replace(',','')[4:])
price_save = round(ck_price - amazon_price)
percent = round(price_save / ck_price * 100)
# show when it is cheaper
if price_save > 0:
st.write('You Save: HKD', str(price_save), '(', str(percent), '%)')
# link to amazon product page
html = df['recommend_url1'][i]
link = f"[Buy Now]({html})"
st.markdown(link, unsafe_allow_html=True)
with col2:
# amazon product 2 image
img = Image.open(df['recommend_img_file2'][i])
st.image(img)
with col3:
# amazon logo
img = Image.open('image/streamlit/amazon_logo.jpg')
st.image(img, width=70)
amazon_price = df['recommend_price2'][i]
# amazon prodcut 2 price
st.write(amazon_price, ' \+ Shipping Fee')
# show the price difference
amazon_price = float(amazon_price.replace(',','')[4:])
price_save = round(ck_price - amazon_price)
percent = round(price_save / ck_price * 100)
# show when it is cheaper
if price_save > 0:
st.write('You Save: HKD', str(price_save), '(', str(percent), '%)')
# link to amazon product page
html = df['recommend_url2'][i]
link = f"[Buy Now]({html})"
st.markdown(link, unsafe_allow_html=True)
st.write('-------------------------')
st.write('Please Select Apparel:')
# default showing 'sweatshirts-hoodies'
apparel = 'sweatshirts-hoodies'
# buttons for selecting apparel
col0, col1, col2 = st.beta_columns(3)
with col0:
if st.button('Activewear'):
apparel = 'activewear'
with col1:
if st.button('Jackets'):
apparel = 'jackets'
with col2:
if st.button('Sweatshirts'):
apparel = 'sweatshirts-hoodies'
# main function
main(apparel)
|
65c76455c53829fd7100ab31889fd094f74f67c3 | creep1g/Datastructures-RU | /extrapractice/yield.py | 317 | 3.640625 | 4 | def factorsone(n):
results = []
for k in range(1,n+1):
if n % k == 0:
results.append(k)
return results
def factorstwo(n):
for k in range(1,n+1):
if n % k == 0:
yield k
print(factorsone(100))
yielded = factorstwo(100)
for i in yielded:
print(i, end=" ")
|
8d1865ca73f058414e9d41ae16a671590793ed64 | why1679158278/python-stu | /第二阶段服务器/day9.11/day12/process_2.py | 503 | 3.875 | 4 | """
进程基础实例2
含有参数的进程函数
"""
from multiprocessing import Process
from time import sleep
# 带有参数的进程函数
def worker(sec,name):
for i in range(3):
sleep(sec)
print("I'm %s"%name)
print("I'm working....")
# 创建进程
# p = Process(target=worker,args=(2,"Tom"))
p = Process(target=worker,
args = (2,),
kwargs={'name':'Levi'})
p.start()
p.join(3) # 最长等待3秒
print("================================") |
538b512043c830e1db1be2d6328316b22c27d45f | novayo/LeetCode | /AlgoExpert/coding_interview_questions/Graphs/Remove_Islands.py | 920 | 3.703125 | 4 | '''
main idea: mark
time comp: O(N)
space comp: O(1)
- where N is the number of elements of the input array
'''
def removeIslands(matrix):
# Write your code here.
height = len(matrix)
width = len(matrix[0])
def dfs(i, j, marked):
if not (0 <= i < height and 0 <= j < width) or matrix[i][j] == 0 or matrix[i][j] == marked:
return
matrix[i][j] = marked
dfs(i+1, j, marked)
dfs(i-1, j, marked)
dfs(i, j+1, marked)
dfs(i, j-1, marked)
for i in range(height):
if matrix[i][0] == 1:
dfs(i, 0, -1)
if matrix[i][width-1] == 1:
dfs(i, width-1, -1)
for j in range(width):
if matrix[0][j] == 1:
dfs(0, j, -1)
if matrix[height-1][j] == 1:
dfs(height-1, j, -1)
for i in range(height):
for j in range(width):
if matrix[i][j] == 1:
matrix[i][j] = 0
for i in range(height):
for j in range(width):
if matrix[i][j] == -1:
matrix[i][j] = 1
return matrix
|
05f0e83e7cf5c6729ad812de4c71eeeccbd8b802 | vibhootiagrawal/python_course | /intersection.py | 202 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 24 17:58:20 2019
@author: Education
"""
list1=[1,3,6,78,35,55]
list2=[12,24,35,24,88,120,15]
s3=[]
s3=list(set(list2).intersection(set(list1)))
print(s3) |
cdd1ae90504bebf647ea5b0eefa122d55225b9d7 | PiperPimientos/PensamientoComputacionalPython | /asserts.py | 870 | 4.09375 | 4 | # Afirmaciones
# Las afirmaciones son un mecanismo en la que podemos determinar si una afirmación se cumple o no se cumple y poder seguir adelante con la ejecución de nuestro programa o darle término.
# Las afirmaciones es un método de programación defensiva, esto significa que nos estamos preparando para verificar que los tipos de inputs de nuestro programa es del tipo que nosotros esperamos. Estos también nos sirven para debuggear.
# Para realizar una afirmación en nuestro programa lo hacemos con la expresión assert <expresion booleana>, <mensaje de error>.
def primera_letra(lista_de_palabras):
primeras_letras = []
for palabra in lista_de_palabras:
assert type(palabra) == str, f'{palabra} no es str'
assert len(palabra) > 0, 'No se permiten str vacios'
primeras_letras.append(palabra[0])
return primeras_letras
|
ab8f3b99a43cabbd8bd9a4a9620241efab15996e | mjigmond/bin-utils | /sqrt.py | 1,695 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import math
import random
def user_sqrt(num: float, decimals: int) -> str:
"""
Calculate the square root of a number. Beyond a certain number of decimals
it will no longer match the `math.sqrt(x)` which is less precise.
Parameters
----------
num : float
Number whose square root we need to find.
decimals : int
How many decimals should the result have.
Returns
-------
str
Square root of `num`.
"""
if num <= 0:
return '0'
e = 3
fmtd_num = f'{num:.{decimals*2+e}f}'[:-e]
left, right = fmtd_num.split('.')
left = left[-1::-1]
left_list = [left[i:i+2][-1::-1] for i in range(0, len(left), 2)]
left_list.reverse()
right_list = [right[i:i+2] for i in range(0, len(right), 2)]
g = 1
n = int(left_list[0])
while g**2 <= n:
g += 1
lo = n - (g - 1)**2
res = str(g - 1)
for n in left_list[1:] + right_list:
lo = int(str(lo) + n)
t = int(res) * 2 * 10
i = 0
while (t + i) * i <= lo:
i += 1
lo = lo - (t + i - 1) * max(0, i - 1)
res += str(max(0, i - 1))
sqrt = res[:len(left_list)] + '.' + res[len(left_list):]
return sqrt
if __name__ == '__main__':
for i in range(100):
num = random.uniform(0, 1e7)
dec = random.randint(0, 9)
math_sqrt = math.sqrt(num)
math_sqrt = f'{math_sqrt:.{dec+5}f}'[:-5]
sqrt = user_sqrt(num, dec)
# print(f'The square root of {num}, up to {dec} decimals is: {sqrt}')
assert sqrt == math_sqrt, f'The square root of {num}, up to {dec} decimals is: {sqrt} vs {math_sqrt}'
|
65b5e13298a8ba59161950933acf3a3d36291a0e | Raviraghul2210/GuviPythonPrograms | /b5.py | 111 | 3.5625 | 4 | u1,v1,w1=input().split()
if u1>v1 and u1>w1:
print("u1")
elif v1>w1:
print("v1")
else:
print("w1")
|
587da275588effe4b6101f6b5a015a366b86cdc4 | Ratna-Sree/techbee | /join list.py | 300 | 3.734375 | 4 | """3)
l1=['A','B','C','D','E','F','G','H','I']
Output should be like below:
ABC
DEF
GHI
"""
l1=['A','B','C','D','E','F','G','H','I']
lst=[]
count=0
for i in range(len(l1)):
lst.append(l1[i])
count+=1
if count %3==0:
print(''.join(lst))
lst=[]
|
a45898fa04aba837d66efc3d7a1aad993dbadcc3 | sangampatel/pythonproject | /pythonproject/atm.py | 1,274 | 3.875 | 4 | print("1-Open Account 2-Bank Operation")
n = input()
if n=='1':
def openaccount():
print("Open Your Account in Sangam Bank Type Your Account Number")
account = int(input())
print("Your Account Number is =", account)
openaccount()
elif n=='2':
def bankoperation():
print("1-Cash Withdraw 2-Cash Deposit\n3-Set Pin 4-Check Balance")
n = (input())
if n == '1':
def cashwithdraw():
print("How Much Money You Want To Withdraw")
n1 = int(input())
print(n1, "₹ Rupees Has Been Deducted From your Account")
cashwithdraw()
elif n == '2':
def cashdeposit():
print("How Much Money You Want To Deposit")
n1 = int(input())
print(n1, "₹ Rupees Has Been Added in your Account")
cashdeposit()
elif n == '3':
def setpin():
print("Set Your Pin No")
n1 = int(input())
print("Your Pin No is =", n1)
setpin()
elif n == '4':
def checkbalance():
print("Total Balance =1000000000000000000₹")
checkbalance()
bankoperation()
|
8dc357643d7e489d7359dc0fb0ef1022d299cb8c | daniel10012/python-onsite | /week_03/03_testing/test_returnwords.py | 725 | 3.65625 | 4 | import unittest
from returnwords import return_word
class TestReturnWords(unittest.TestCase):
def test_returns_false_if_empty_string_as_char(self):
self.assertIs(return_word("abcde",""), False)
def test_returns_false_if_empty_string_as_word(self):
self.assertIs(return_word("","e"), False)
def test_returns_false_if_word_is_not_string(self):
for i in range(10):
self.assertIs(return_word(i,"e"), False)
def test_returns_false_if_char_is_not_string(self):
self.assertIs(return_word("rsg",3), False)
def test_returns_false_if_word_is_blank_spaces(self):
self.assertIs(return_word(" "," "), False)
if __name__ == '__main__':
unittest.main()
|
0bea9899435985bfa967815248f5deeecec9ff62 | hanok2/national_pastime | /baseball/history.py | 4,806 | 4 | 4 | class LeagueHistory(object):
"""The compiled history of a baseball league."""
def __init__(self, league):
"""Initialize a LeagueHistory object."""
self.league = league
self.defunct_teams = set() # Populated as teams _fold
self.charter_teams = set(league.teams)
self.seasons = [] # Appended to by LeagueSeason.__init__()
self.champions_timeline = {} # Maps year to champion that year; updated by LeagueSeason.review()
self.former_players = set()
def __str__(self):
"""Return string representation."""
return "History of the {league} ({founded}-{ceased})".format(
league=self.league.name,
founded=self.league.founded,
ceased=self.league.ceased if self.league.ceased else ''
)
@property
def years_in_existence(self):
"""Return the number of years this league has existed."""
return self.league.cosmos.year-self.league.founded
class FranchiseHistory(object):
"""The compiled history of a baseball franchise."""
def __init__(self, franchise):
"""Initialize a FranchiseHistory object."""
self.franchise = franchise
self.seasons = [] # Appended to by TeamSeason.__init__()
self.championships = []
self.former_players = set()
def __str__(self):
"""Return string representation."""
return "History of the {franchise} ({founded}-{ceased})".format(
franchise=self.franchise.name,
founded=self.franchise.founded,
ceased=self.franchise.ceased if self.franchise.ceased else ''
)
@property
def games(self):
"""Return all the games ever played by this franchise."""
games = []
for season in self.seasons:
games += season.games
return games
@property
def years_in_existence(self):
"""Return the number of years this franchise has existed."""
return self.franchise.cosmos.year-self.franchise.founded
@property
def tradition(self):
"""The accumulated tradition of this franchise (in its current city)."""
if not self.seasons:
return 0
tradition = self.franchise.cosmos.config.calculate_franchise_tradition(
n_championships=len(self.championships), n_years_in_town=self.number_of_years_in_town
)
return tradition
@property
def cumulative_wins(self):
"""Return the cumulative number of wins this franchise has accumulated across its entire history."""
return sum(len(s.wins) for s in self.seasons)
@property
def cumulative_losses(self):
"""Return the cumulative number of losses this franchise has accumulated across its entire history."""
return sum(len(s.losses) for s in self.seasons)
@property
def cumulative_winning_percentage(self):
"""Return this franchise's cumulative winning percentage."""
return float(self.cumulative_wins)/(self.cumulative_wins+self.cumulative_losses)
@property
def number_of_years_in_town(self):
"""Return the number of years this franchise has been located in its current city."""
if not self.seasons:
return 0
else:
first_season_in_this_town = next(s for s in self.seasons if s.city is self.franchise.city)
year_of_that_season = first_season_in_this_town.year
number_of_years_in_town = self.franchise.cosmos.year-year_of_that_season
return number_of_years_in_town
def get_season(self, year, city=None):
"""Return this franchise's season for the given year."""
city = self.franchise.city if not city else city
try:
return next(s for s in self.seasons if s.year == year and s.city is city)
except StopIteration:
return None
def winning_percentage_during_window(self, start_year, end_year, city=None):
"""Return this team's cumulative winning percentage across the specified window.
Note: This method quietly ignores any years in the specified window that are not
applicable for this franchise (either because the franchise did not exist yet, or
it was not in the specified city yet).
"""
city = self.franchise.city if not city else city
wins_during_the_window = 0
losses_during_the_window = 0
for year in xrange(start_year, end_year):
season_that_year = self.get_season(year=year, city=city)
if season_that_year:
wins_during_the_window += season_that_year.wins
losses_during_the_window += season_that_year.losses
return float(wins_during_the_window)/(wins_during_the_window+losses_during_the_window)
|
12a1266ecebf147f2468564bc2eca11134f63f7f | suresh-boddu/algo_ds | /algo/sorting/heapsort.py | 2,364 | 3.875 | 4 | """
Heap Sort Algorithm
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last,
is completely filled, and all nodes are as far left as possible (Source Wikipedia)
A Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes.
The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array.
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient.
If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0)
Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.
"""
def heapify(input, size, index):
'''
Applying the heap properties on input array at given index.
:param input:
:param index:
:return:
'''
if not input or index < 0:
return
lc_index = 2*index + 1
rc_index = 2*index + 2
largest_index = index
if lc_index < size and input[lc_index] > input[index]:
largest_index = lc_index
if rc_index < size and input[rc_index] > input[largest_index]:
largest_index = rc_index
if largest_index != index:
input[largest_index], input[index] = input[index], input[largest_index]
heapify(input, size, largest_index)
def heapsort(input):
'''
heapsort algorithm
:param input:
:return:
'''
if not input:
return
size = len(input)
for index in range(size/2-1, -1, -1):
heapify(input, size, index)
for index in range(size-1, 0, -1):
input[0], input[index] = input[index], input[0]
heapify(input, index, 0)
if __name__ == "__main__":
input = [12, 4, 2, 8, -10, 5, 32, -1, 0, -45]
print "Before Sorting: " + str(input)
heapsort(input)
print "After Sorting: " + str(input) |
222f876ae11ff0c0493c8e6ddf6e463343555977 | Nicolanz/holbertonschool-web_back_end | /0x0D-NoSQL/8-all.py | 285 | 3.90625 | 4 | #!/usr/bin/env python3
"""Module to list all documents in python"""
def list_all(mongo_collection):
"""Function to list the documents of a collection"""
my_list = []
elements = mongo_collection.find({})
for i in elements:
my_list.append(i)
return my_list
|
c021ceff78a5f2e693593de57726e4c970e9af03 | Marcoakira/Desafios_Python_do_Curso_Guanabara | /Mundo2/Desafio037.py | 153 | 3.90625 | 4 | numero = float(input('Escolha um numero a qual deseja converter'))
base = int(input('Digite:\n1 para Binario\n2 para octal\n3para hexadecimal'))
hnivbkj
|
40c7485f29fad1f2f28207bf357eb0a4b45c77c7 | arleybri18/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 155 | 3.6875 | 4 | #!/usr/bin/python3
def append_write(filename="", text=""):
lines = 0
with open(filename, 'a') as f:
lines = f.write(text)
return lines
|
19107413dd92e257efa143b45b56159aee00be1f | lendoly/Memory-Maneuver | /models.py | 2,684 | 3.796875 | 4 | import json
class Node:
"""Class that simbolize a Node of a Tree.
Properties created with the ``@property`` decorator should be documented
in the property's getter method.
Attributes:
root (bool): Indicates if is the root Node of a Tree or not
number_children (int): Number of children for a Node
amount_of_metada (int): Number of metadat on the node
children (list): List of Nodes which are the children of the Node
metadata (list): List of Integers with the metada for the Node
"""
def __init__(self, info_list: list, root: bool = False):
"""Constructor for the Node
Note:
Do not set root to True on the Tree generation
Args:
info_list (list): list of integers with the input
root (bool): indicates if is a ROOT node or not, default to False
"""
self.root = root
self.number_children = info_list.pop(0)
self.amount_of_metada = info_list.pop(0)
self._generate_children(info_list)
self.metadata = [info_list.pop(0)
for _ in range(self.amount_of_metada)]
def _generate_children(self, info_list):
"""Private method that will generate the chidlren for the Node
Args:
info_list: The rest of the list to generate children.
Returns:
None
"""
#: list of Node: caontain the children for the current node
self.children = [Node(info_list) for _ in range(self.number_children)]
def _get_dict(self):
"""Private method that will generate the children for the Node
Args:
info_list: The rest of the list to generate children.
Returns:
dict with the information for the
"""
data = {"number of children": self.number_children,
"amount of metadata": self.amount_of_metada,
"metadata": self.metadata,
"childrens": [child._get_dict() for child in self.children]}
if self.root:
data["total"] = self.get_total()
return data
def get_total(self):
"""Class method that will sum the current metada and add the
sum of the children's metadata
Returns:
total amount of the sum of all the metadata
"""
return sum(self.metadata) + sum(child.get_total()
for child in self.children)
def print_tree(self):
"""Print in JSON format the tree from the current Node
Returns:
None
"""
print(json.dumps(self._get_dict()))
|
6075618d91877bf551dc6b226eb865bee97d3db3 | glennmandagi/compro-1 | /python/Console Structures/While Loops/IncreaseWHILELoops.py | 105 | 3.84375 | 4 | #this program will print number 0 2 4 6 8 10 12 14 16 18 20
i = 0
while i <= 20:
print(i)
i += 2
|
2098c082b4d8db95a5b2b4035693ed3577a88807 | JaberKhanjk/LeetCode | /BinaryTree/height_balanced_binary_tree_from_linked_list.py | 951 | 3.75 | 4 | class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def construct(self,node,nums):
n = len(nums)
if n == 0:
return
mid = n/2
node = TreeNode(nums[mid])
node.left = self.construct(node.left,nums[:mid])
if mid+1 < n:
node.right = self.construct(node.right,nums[mid+1:])
return node
def sortedListToBST(self, head):
nums = []
p = head
while p!=None:
nums.append(p.val)
p = p.next
return self.construct(None,nums)
"""
:type head: ListNode
:rtype: TreeNode
"""
|
ead6e580410498cd7a86b491b685f89b6ef85558 | DiNoWaR/Python.Stepic.org | /com/stepic/module1/ticket/LuckyTicket.py | 396 | 3.765625 | 4 | usual = 'Обычный'
lucky = 'Счастливый'
input_string = input()
first_number = int(input_string[0:3])
second_number = int(input_string[-3:])
z1 = first_number % 10
y1 = (first_number % 100) // 10
x1 = first_number // 100
z2 = second_number % 10
y2 = (second_number % 100) // 10
x2 = second_number // 100
if x1 + y1 + z1 == x2 + y2 + z2:
print(lucky)
else:
print(usual) |
6e0dfaab9d4b137a7898b17f2200b62145b6e1d3 | srbnyk/Algo | /bigger_is_greater.py | 1,419 | 4 | 4 | #Bigger is Greater {https://www.hackerrank.com/challenges/bigger-is-greater}
#Given a word , rearrange the letters of to construct another word in such a way that is lexicographically greater than . In case of multiple possible answers, find the lexicographically smallest one among them.
#Code:
def lex(str):
l = list(str)
c= int()
length = len(l)
if length < 2:
return "no answer"
t=0
count1=1
count2=1
for i in range(0,length-1):
if l[length-2-i] > l[length-1-i]:
count2 += 1
elif l[length-1-i] > l[length-2-i]:
t=1
imbig = l[length-1-i]
c =length-1-i
for k in range(0,i):
if l[length-2-i] < l[length-k-1]:
if imbig > l[length-k-1]:
imbig = l[length-k-1]
c = length -k -1
l[length-2-i], l[c] = l[c], l[length-2-i]
l1 = l[:length-i-1]
l2 = l[-i-1:]
#l3 = l2[::-1]
l2.sort()
l4 = l1+l2
str = ''.join(l4)
return str
else:
count1 += 1
if count1 == length:
return "no answer"
if count1+count2-1 ==length:
return "no answer"
if count2 ==length:
return "no answer"
noi = int(input())
for i in range(0,noi):
print(lex(input()))
|
0ac7a7d06eda326df3c966a95617f24750c8bb60 | Anusien/findingdredge | /fractions.py | 5,322 | 3.71875 | 4 | import string
import os
def deckstring(deck):
return "A" * deck[0] + "B" * deck[1] + "C" * deck[2] + "D" * deck[3] + "E" * deck[4] + "F" * deck[5] + "G" * deck[6] + "H" * deck[7] + "I" * deck[8]
def breakdown(deck):
return [deck.count("A"),deck.count("B"),deck.count("C"),deck.count("D"),deck.count("E"),deck.count("F"),deck.count("G"),deck.count("H"),deck.count("I")]
class Memoize: # stolen from http://code.activestate.com/recipes/52201/
"""Memoize(fn) - an instance which acts like fn but memoizes its arguments
Will only work on functions with non-mutable arguments
"""
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, *args):
if not self.memo.has_key(args):
self.memo[args] = self.fn(*args)
return self.memo[args]
def gcd(i, j):
if j == 0:
return i
return gcd(j, i % j)
class frac:
def __init__(self, num = 0, den = 1):
self.num = num
self.den = den
self.simplify()
def __add__(self, other):
return frac(self.num * other.den + other.num * self.den, self.den * other.den).simplify()
def __sub__(self, other):
return frac(self.num * other.den - other.num * self.den, self.den * other.den).simplify()
def __mul__(self, other):
return frac(self.num * other.num, self.den * other.den).simplify()
def __div__(self, other):
return frac(self.num * other.den, self.den * other.num).simplify()
def simplify(self):
temp = gcd(self.num, self.den)
self.num /= temp
self.den /= temp
return self
def __repr__(self):
if (self.den == 1):
return str(self.num)
# return str(self.num) + " / " + str(self.den),
return str(self.num * 1.0 / self.den)
# Modified range function, because including the actual max you want is handy.
def ranged(x, y):
for z in xrange(x, y + 1):
yield z
# Deck generator
def decks(mini = 12, maxi = 14):
for a in ranged(5, 12):
for b in ranged(0, 4):
for c in ranged(0, 4):
for d in ranged(0, 12):
for e in ranged(0, 4):
for f in ranged(0, 4):
for g in ranged(0, 4):
for h in ranged(0, 16):
for i in ranged(mini, maxi):
if (a + b + c + d + e + f + g + h + i == 60):
yield([a,b,c,d,e,f,g,h,i])
def choose(deck, cards):
total = 0
deck = breakdown(deck)
result = {}
for i in deck:
total += i
if (cards == 1):
for i in range(0,9):
temp = ["A","B","C","D","E","F","G","H","I"][i]
result[temp] = frac(deck[i],total)
return result
# for i in result.keys():
# if (result[i].num > 0):
# yield([i,result[i]])
else:
for i in range(0,9):
if deck[i] > 0:
deck[i] -= 1
card = ["A","B","C","D","E","F","G","H","I"][i]
tempdeck = deckstring(deck)
tempresult = choose(tempdeck, cards - 1)
for j in tempresult.keys():
temp = string.join(sorted(list(card + j)),"")
if result.has_key(temp):
result[temp] += tempresult[j] * frac(deck[i] + 1,total)
else:
result[temp] = tempresult[j] * frac(deck[i] + 1,total)
if result[temp] == 0:
del result[temp]
deck[i] += 1
# for i in result.keys():
# if (result[i].num > 0):
# yield([i,result[i]])
return result
choose = Memoize(choose)
def evalhand(hand):
total = 0
hands = ("AABC", "ABCH", "ACEH", "ACFH", "ABDH", "ADEH", "ADFH", "ADGH", "ABBH", "ABEH", "ABFH", "ABGH", "ABEH", "AEEH", "AEFH", "AEGH", "AEGG", "AEEG", "AEFG")
for winninghand in hands:
good = 1
for card in winninghand:
if hand.count(card) < winninghand.count(card):
good = 0
if good == 1:
return frac(1, 1)
return frac(0, 1)
evalhand = Memoize(evalhand)
for deck in decks(12,14):
#if (1):
# deck = [12, 4, 0, 7, 4, 4, 4, 13, 12]
total = frac(0, 1)
answer = choose(deckstring(deck),7)
for i in sorted(answer.keys()):
total += evalhand(i) * answer[i]
total7 = total
total = frac(0, 1)
answer = choose(deckstring(deck),6)
for i in sorted(answer.keys()):
total += evalhand(i) * answer[i]
total6 = total
total = frac(0, 1)
answer = choose(deckstring(deck),5)
for i in sorted(answer.keys()):
total += evalhand(i) * answer[i]
total5 = total
total = frac(0, 1)
answer = choose(deckstring(deck),4)
for i in sorted(answer.keys()):
total += evalhand(i) * answer[i]
total4 = total
final = total7 + (frac(1, 1) - total7) * total6 + (frac(1, 1) - ((total7 + (frac(1, 1) - total7) * total6))) * total5 + (frac(1, 1) - ((total7 + (frac(1, 1) - total7) * total6 + (frac(1, 1) - ((total7 + (frac(1, 1) - total7) * total6))) * total5))) * total4
print deck, final
|
4da152bd72ebb53b3bff7a3a09f56be9541bbe9f | StaroKep/Python | /Цикл while/python while/P.py | 121 | 3.78125 | 4 | a = int(input())
m = 0
s = 0
while (a != 0):
if (a > m):
s = m
m = a
a = int(input())
print(s)
|
152e6d55aa1d2877afa729b15d8169a9e47eb4be | wangluyi/Principles-of-Computing-Part-1-Coursera | /Tic_Tac_Toe_Monte_Carlo.py | 7,490 | 4.15625 | 4 | '''
a tic tac toe game with monte carlo simulation
'''
# Constants
EMPTY = 1
PLAYERX = 2
PLAYERO = 3
DRAW = 4
SIGNAL = {EMPTY:' ',
PLAYERX: 'X',
PLAYERO: 'O'}
class TTTBoard:
"""
Class to represent a Tic-Tac-Toe board.
"""
def __init__(self, dim, reverse = False, board = None):
"""
Initialize the TTTBoard object with the given dimension and
whether or not the game should be reversed.
"""
self._dim=dim
self._reverse=reverse
if board==None:
self._board=[ [ EMPTY for dummy_col in range(dim)]
for dummy_row in range(dim)]
else:
self._board=[ [ board[row][col] for col in range(dim)]
for row in range(dim)]
def __str__(self):
"""
Human readable representation of the board.
"""
signal = ""
for row in range(self._dim):
for col in range(self._dim):
signal += SIGNAL[self._board[row][col]]
if col == self._dim - 1:
signal += "\n"
else:
signal += " | "
if row != self._dim - 1:
signal += "-" * (4 * self._dim - 3)
signal += "\n"
return signal
def get_dim(self):
"""
Return the dimension of the board.
"""
return self._dim
def square(self, row, col):
"""
Returns one of the three constants EMPTY, PLAYERX, or PLAYERO
that correspond to the contents of the board at position (row, col).
"""
return self._board[row][col]
def get_empty_squares(self):
"""
Return a list of (row, col) tuples for all empty squares
"""
empty=[]
for row in range(self._dim):
for col in range(self._dim):
if self._board[row][col]==EMPTY:
empty.append((row,col))
return empty
def move(self, row, col, player):
"""
Place player on the board at position (row, col).
player should be either the constant PLAYERX or PLAYERO.
Does nothing if board square is not empty.
"""
if self._board[row][col]==EMPTY:
self._board[row][col]=player
def check_win(self):
"""
Returns a constant associated with the state of the game
If PLAYERX wins, returns PLAYERX.
If PLAYERO wins, returns PLAYERO.
If game is drawn, returns DRAW.
If game is in progress, returns None.
"""
lines=[]
lines.extend(self._board)
cols=[ [ self._board[rowid][colid] for rowid in range(self._dim)]
for colid in range(self._dim)]
lines.extend(cols)
diag1 = [ self._board[rowid][rowid] for rowid in range(self._dim)]
diag2 = [ self._board[rowid][self._dim - 1 - rowid]
for rowid in range(self._dim)]
lines.append(diag1)
lines.append(diag2)
for line in lines:
if len(set(line))==1 and line[0]!=EMPTY:
if self._reverse:
return provided.switch_player(line[0])
else:
return line[0]
#check if draw
if len(set(self.get_empty_squares()))==0:
return DRAW
#still in progress
return None
def clone(self):
"""
Return a copy of the board.
"""
return TTTBoard(self._dim,self._reverse,self._board)
#end of the class TTTBoard:
#Monte Carlo Tic-Tac-Toe Player
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
# do not change their names.
NTRIALS = 1 # Number of trials to run
SCORE_CURRENT = 1.0 # Score for squares played by the current player
SCORE_OTHER = 1.0 # Score for squares played by the other player
# Add your functions here.
def mc_trial(board, player):
'''
takes a current board and the next player to move,
play a game starting with the given player by making random moves, alternating between players;
modified board will contain the state of the game, does not return anything
'''
player_win = board.check_win()
while player_win == None:
empty = board.get_empty_squares()
next_move = empty[random.randrange(len(empty))]
board.move(next_move[0], next_move[1], player)
player = provided.switch_player(player)
player_win = board.check_win()
def mc_update_scores(scores, board, player):
'''
takes a grid of scores (a list of lists)
score the completed board and update the scores grid
does not return anything
'''
winner=board.check_win()
for row in range(board.get_dim()):
for col in range(board.get_dim()):
player = board.square(row,col)
if player == PLAYERX:
if winner == PLAYERX:
scores[row][col] += SCORE_CURRENT
elif winner == PLAYERO:
scores[row][col] -= SCORE_OTHER
elif player == PLAYERO:
if winner == PLAYERX:
scores[row][col] -= SCORE_OTHER
elif winner == PLAYERO:
scores[row][col] += SCORE_CURRENT
else:
#0 value
pass
def get_best_move(board, scores):
'''
takes a current board and a grid of scores
find all of the empty squares with the maximum score and randomly return one of them as a (row, column) tuple
board that has no empty squares results in error
'''
empty_squares = board.get_empty_squares()
if len(empty_squares)==0:
return
vals = [scores[square[0]][square[1]] for square in empty_squares]
max_val = max(vals)
moves = []
for row in range(board.get_dim()):
for col in range(board.get_dim()):
if scores[row][col]==max_val and (row,col) in empty_squares:
moves.append((row, col))
return random.choice( moves )
def mc_move(board, player, trials):
'''
takes a current board, which player the machine player is
,and the number of trials to run
use the Monte Carlo simulation to return a move for the machine player in the form of a (row, column) tuple
'''
# creates initial score board with every values sets to 0
initial_scores = [[0 for dummy_col in range(board.get_dim())] for dummy_row in range(board.get_dim())]
for dummy_trial in range(trials):
cloned = board.clone()
mc_trial(cloned, player)
mc_update_scores(initial_scores, cloned, player)
return get_best_move(board, initial_scores)
# Test game with the console or the GUI. Uncomment whichever
# you prefer. Both should be commented out when you submit
# for testing to save time.
provided.play_game(mc_move, NTRIALS, False)
poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False)
|
0c11e462e4e406699839d3a55bdcfb6ba2112d5c | manutdmohit/mypythonexamples | /pythonexamples/area of circle1.py | 93 | 4.09375 | 4 | from math import *
r=int(input('Enter radius of circle:')
print('Area of circle:', pi*r**2)
|
728a446d66fcefeb510bfe5b42e1a3de28a55211 | SATAY-LL/Transposonmapper | /transposonmapper/exporting/save_per_gene.py | 1,710 | 3.546875 | 4 | def save_per_gene(filename, tn_per_gene, reads_per_gene, aliases_designation):
"""Create text file with transposons and reads per gene
NOTE THAT THE TRANSPOSON WITH THE HIGHEST READ COUNT IS IGNORED.
E.G. IF THIS FILE IS COMPARED WITH THE _PERGENE_INSERTIONS.TXT FILE THE
READS DON'T ADD UP (SEE https://groups.google.com/forum/#!category-topic/satayusers/bioinformatics/uaTpKsmgU6Q)
TOO REMOVE THIS HACK, CHANGE THE INITIALIZATION OF THE VARIABLE readpergene
Parameters
----------
filename : str
Path with the filename extension included(e.g "data_file/file.txt")
describing where do you want to store the results.
By default it will be stored in the same location as the bamfile,
with the same basename.
Example, if the bamfile path is data_file/data_1.bam then the file will be data_file/data_1.bam_pergene.txt
tn_per_gene : int
The number of transposons found per gene
reads_per_gene : int
The number of reads found per gene
aliases_designation : dict
Last output of the function read_genes _, _, aliases_designation = read_genes(
gff_file, essential_file, gene_name_file)
"""
with open(filename, "w") as f:
f.write("Gene name\tNumber of transposons per gene\tNumber of reads per gene\n")
for gene in tn_per_gene:
tnpergene = tn_per_gene[gene]
readpergene = reads_per_gene[gene]
if gene in aliases_designation:
gene_alias = aliases_designation.get(gene)[0]
else:
gene_alias = gene
f.write(gene_alias + "\t" + str(tnpergene) + "\t" + str(readpergene) + "\n")
|
0c8036e6cd7d5e580374eb9394617f608ad2ff5e | gitlearn212/My-Python-Lab | /Python/Functions/Ex15_volume_sphere.py | 544 | 4.5 | 4 | # Get the volume of sphere with radius 6
# So many ways of programming for this task
# check each one of them
from math import pi
'''
def volume_sphere(x):
# x = 6.0
result = ((4.0/3.0) * pi * (x ** 3))
# return result
print(result)
r = 6.0
# print(volume_sphere(r))
volume_sphere(r)
'''
# OR write a normal program with function (with out Def)
# import pi as above or assign value to pi as below
pi = 3.1415926535897931
r = 6.0
# result = ((4.0 / 3.0) * pi * (r ** 3))
# print(result)
print(f'{(4.0/3.0) * pi * (r **3)}')
|
2c3128c04efac152810d38ba34f9b838b34cb07b | chc24/ProjectEuler | /Euler35.py | 1,283 | 3.515625 | 4 | import itertools
def rotateNum(num):
digits = [int(x) for x in str(num)]
n_digits = len(digits)
n_power = n_digits - 1
permutations = itertools.permutations(digits)
permutation_list = [sum(v * (10 ** (n_power - i)) for i,v in enumerate(item)) for item in permutations]
return permutation_list
def isCircular(num, markarray):
circularlist = rotateNum(num)
circular = True
for item in circularlist:
if markarray[i] == 1:
circular = False
return circular
circularlist = []
markarray = [0] * 1000000 ##array size 1000000
count = 3 ##start with 3 since first prime is 2
while count < 1000000: ##exit after exceeding 2000000
if markarray[count] == 0: ##First value to be 0 MUST be a prime because the previous number was not
increment = count #take that number and increment rest of multiples so we dont' have to check.
while increment < 1000000: #when to stop
markarray[increment] = 1 #flip to 1
increment += count #increment
count += 2 #move up by 2's
for i in range(len(markarray)):
if markarray[i] == 0:
print i
if isCircular(i, markarray):
print i
circularlist.append(i)
print len(circularlist)
|
e5e91de508440c8996a4aea2f2830dc25bd887e5 | zcollin/TechDegree_Project2 | /TechDegree Project2/affine.py | 1,451 | 4.0625 | 4 | """
Creates a class for the Affine Cipher. Encryption and Decryption
Author: Zachary Collins
Date: July, 2018
"""
import string
from ciphers import Cipher
class Affine(Cipher):
def __init__(self, a=5, b=8, m=26):
"""Creates an instance of the Affine Cipher"""
self.a = a
self.b = b
self.m = m
self.alpha = list(string.ascii_lowercase)
def encrypt(self, text):
"""Encrpyts a given piece of text"""
text = text.lower()
encrypted_word = []
for letter in text:
try:
index = self.alpha.index(letter)
except ValueError:
encrypted_word.append(letter)
else:
# Uses Affine encryption function to encrypt the word
new_index = ((self.a*index)+self.b) % self.m
encrypted_word.append(self.alpha[new_index])
return "".join(encrypted_word)
def decrypt(self, text):
"""Decrpyts a given piece of text"""
decrypted_word = []
for letter in text:
try:
index = self.alpha.index(letter)
except ValueError:
decrypted_word.append(letter)
else:
# Uses Affine decryption function to decrypt the word
new_index = ((21*(index-self.b)) % self.m)
decrypted_word.append(self.alpha[new_index])
return "".join(decrypted_word)
|
27e2d839d5b721bec5382a759086ef7a186ff0c1 | NotQuiteHeroes/HackerRank | /Python/Strings/Capitalize.py | 438 | 4.21875 | 4 | '''
You are given a string s. Your task is to capitalize each word of s.
Input Format
A single line of input containing the string, s.
Preserve whitespace
https://www.hackerrank.com/challenges/capitalize
'''
if __name__ == '__main__':
string = raw_input()
capitalized_string = capitalize(string)
print capitalized_string
def capitalize(string):
s = string.split(' ')
return ' '.join(word.capitalize() for word in s)
|
580c1f069336132ca18d2bf567d32b4bacdb194e | MarcPartensky/Python-Games | /Game Structure/geometry/version4/myforce.py | 3,361 | 3.78125 | 4 | from myabstract import Vector,Point
from mymotion import Motion
import mycolors
p=2 #Number of digits of precision of the objects when displayed
class Force(Vector):
def null(d=2):
"""Return the null force."""
return Force([0 for i in range(d)])
neutral=zero=null
def sum(forces,d=2):
"""Return the sum of the forces."""
result=Force.null(d)
for force in forces:
result+=force
return result
def __init__(self,*args,**kwargs):
"""Create a force."""
super().__init__(*args,**kwargs)
self.d=0
def __call__(self,material_object):
"""Apply a force on a motion."""
material_object.acceleration.components=self.abstract.components
#Keep the other parameters such as the color
def show(self,context,position,m=8,n=2):
"""New dope show method especially for the forces."""
v=self.abstract
x,y=position
nx,ny=v(position)
v.show(context,position,color=self.color)
w=v/m
#color=mycolors.lighten(self.color)
color=mycolors.WHITE
for i in range(n):
if (self.d+2*i)%m<(self.d+1+2*i)%m:
w1=(self.d+2*i)%m*w
w2=(self.d+2*i+1)%m*w
context.draw.line(context.screen,color,w1(position),w2(position),1)
self.d=(self.d+1)%m
def __str__(self):
"""Return the string representation of the object."""
x=round(self.x,p)
y=round(self.y,p)
return "f("+str(x)+","+str(y)+")"
def getAbstract(self):
"""Return the object into its simple vector form."""
return Vector(self.components)
def setAbstract(self,vector):
"""Set the abstract vector to a new vector."""
self.components=vector.components
def delAbstract(self):
"""Set the abstract vector to null."""
self.setNull()
abstract=property(getAbstract,setAbstract,delAbstract,"Reperesentaion of the abstract vector of the force.")
class ForceField:
def __init__(self,force,area):
"""Create a force field object."""
self.force=force
self.area=area
def __contains__(self,body):
"""Determine if a body is contained in the force field."""
#This function should be able to determine which proportion of the object is contained in the force
#field in order to apply some of the force
pass
def exert(self,body):
"""Exert the force of the force field to the object."""
pass
down=Vector([0,-1])
gravity=Force(0,-9.81,color=mycolors.RED)
if __name__=="__main__":
zero=Vector([0,0])
propulsion=Force(0,0)
o=Point.origin()
random_force=Force.random()
#print(random_force)
random_force+=gravity
#print(random_force)
result=Force.sum([gravity,propulsion,random_force])
#print("Force.sum:",result)
x,y=result
#print(x,y) #Unpacking is compatible for vectors
f=gravity
print(result)
from mycontext import Context
context=Context()
position=(0,0)
while context.open:
context.check()
context.control()
context.clear()
context.show()
position=context.point()
f.components=list(position)
f.show(context,o)
context.flip()
#context.wait(0.1)
|
85858aabd6aa4f2ed4f1b74f80ebe7e62406e74c | fstal/DD1320-Applied-Computer-Science | /lab1/lab1.py | 3,214 | 4 | 4 | import time
import csv
class Pokemon:
"""
A class for each pokemon.
Arrtibutes: name, type1, type2, tier and ability1 which all corresponds to the values in the csv-file
"""
def __init__(self, name, type1, type2, tier, ability1):
self.name = name
self.type1 = type1
self.type2 = type2
self.tier = tier
self.ability1 = ability1
def __str__(self):
"""
Method which returns the attributes of a pokemon
"""
string = 'Your Pokemon has the following attributes: %s, %s, %s, %s, %s' % (self.name, self.type1, self.type2, self.tier, self.ability1)
return string
def change_name(self):
"""
Method which changes the "name" attribute of a pokemon
"""
input_name = input('Change name to: ')
self.name = input_name
print('Your new name is: ' + self.name)
def change_tier(self):
"""
Method which changes the "tier" attribute of a pokemon
"""
input_tier = input('Change tier to: ')
self.tier = input_tier
def is_grass_type(self):
"""
Method which checks if a pokemon is a grass-type or not
"""
if self.type1 == 'Grass' or self.type2 == 'Grass':
return 'This is a grass-type pokemon'
else:
return 'This is not a grass-type pokemon'
def one_type_check(self):
"""
Method which checks if a pokemon has more than one type
"""
if self.type2 == '':
print('The pokemon only has one type')
else:
print('The pokemon has type ' + self.type1 + ' and ' + self.type2)
def csv_to_list():
"""
Compiles our CSV file in to a list
"""
with open('Excel Pkdx V5.14 - Pokedex.csv', 'r') as read:
reader = csv.reader(read)
pokemon_list = list(reader)
object_creator(pokemon_list)
def object_creator(pokemon_list):
"""
Function which creates an object for each pokemon in our list
"""
for i in pokemon_list:
if i == pokemon_list[0]:
pass
else:
created_pokemon = Pokemon(i[2], i[10], i[11], i[12], i[13])
object_list.append(created_pokemon)
def search_pokemon():
"""
Function used to search through the names of the pokemon in our list of pokemon objects
"""
search_name = input('Enter a name: ')
for obj in object_list:
if search_name == obj.name:
return(obj)
else:
pass
def menu():
"""
A menu which let's the user decide what he/she want's to do.
Each choice corresponds to a different method in our class.
"""
choice = input('1. Search, 2. Change name, 3. Change Tier, 4. Check if grass type, 5. Check type')
choice = int(choice)
if choice == 1:
print(search_pokemon())
elif choice == 2:
search_pokemon().change_name()
elif choice == 3:
search_pokemon().change_tier()
elif choice == 4:
print(search_pokemon().is_grass_type())
elif choice == 5:
search_pokemon().one_type_check()
else:
print('Nope')
object_list = []
csv_to_list()
menu()
|
76ccad3435220808822ea26b3cdc7f00ed844295 | nmar30/data_structures_assignment | /main.py | 1,291 | 3.96875 | 4 | from sweepstakes import Sweepstakes
from family import Family
from linkedlist import LinkedList
from binarytree import BinaryTree
def months_of_year():
months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
print(months[2])
def celebrate_birthdate():
locations = {'Olive Garden', 'Bahamas', 'Montreal'}
print('Please enter 3 locations you would like to celebrate your birthday!')
i = 0
while i < 3:
locations.add(input(f'Please enter location #{i+1}: '))
i += 1
for location in locations:
print(location)
# months_of_year()
#
# celebrate_birthdate()
#
# sweepstakes1 = Sweepstakes()
# sweepstakes1.pick_winner()
# family1 = Family()
# family1.add_family_member()
# family1.add_family_member()
# family1.print_family_members()
# linked_list1 = LinkedList()
# linked_list1.append_node(55)
# linked_list1.append_node(60)
# linked_list1.append_node(65)
# linked_list1.depend_node(50)
# linked_list1.contains_node(60)
# linked_list1.contains_node(45)
binary_tree1 = BinaryTree()
binary_tree1.append_node(50)
binary_tree1.append_node(75)
binary_tree1.append_node(60)
binary_tree1.append_node(30)
# binary_tree1.contains_node(50)
# binary_tree1.contains_node(35) |
6cffc5ab43a8464fab98153a79b047c2a593ca4d | kernbeisser/UdemyPythonPro | /Chapter11_Packages2/fastvector/fastvector/vector.py | 7,688 | 3.703125 | 4 | '''VectorND class implementation.
'''
from __future__ import annotations
import array
import numbers
from functools import total_ordering
from math import sqrt
from typing import Any
from typing import Union
from .dtypes import Number
from .dtypes import float32
@total_ordering
class VectorND:
'''VectorND class to perform simple vector operations.
'''
def __init__(self, *args: Any, dtype: Any = float32) -> None:
'''Create a vector instance with the given x and y values.
Args:
args (Any): The vector values.
dtype (Any): The dtype of the underlying arry. Defaults to 'float32'.
Raises:
TypeError: If x or y are not a number.
'''
if len(args) == 1 and isinstance(args[0], list):
self.values = array.array(dtype, args[0])
elif len(args) > 0:
values = [val for val in args]
self.values = array.array(dtype, values)
else:
raise TypeError('You must pass in a tuple or list of values!')
def __call__(self) -> str:
'''Callable for the vector instance representation.
Returns:
str: The representation of the vector instance.
'''
print('Calling the __call__ function!')
return self.__repr__()
def __repr__(self) -> str:
'''Return the vector instance representation.
Returns:
str: The representation of the vector instance.
'''
return f'vector.VectorND({self.values})'
def __str__(self) -> str:
'''The vector instance as a string.
Returns:
str: The vector instance as a string.
'''
return f'({self.values})'
def __len__(self) -> int:
'''Return the length of the vector.
Returns:
int: The vector length.
'''
return len(self.values)
def __getitem__(self, idx: int) -> Number:
'''Return the vector item at index *idx*.
Args:
idx (int): The vector index.
Raises:
IndexError: If an invalid index is passed in.
Returns:
Number: Vector value at index *idx*.
'''
if 0 <= idx < len(self.values):
return self.values[idx]
else:
raise IndexError('Invalid index!')
def __setitem__(self, idx: int, val: Number) -> None:
'''Set the vector item at index *idx*.
Args:
idx (int): The vector index.
val (Number): The vector value to set.
Raises:
IndexError: If an invalid index is passed in.
'''
if 0 <= idx < len(self.values):
self.values[idx] = val
else:
raise IndexError('Invalid index!')
def __bool__(self) -> bool:
'''Return the truth value of the vector instance.
Returns:
bool: True, if the vector is not the Null-vector. False, else.
'''
return bool(abs(self))
def __abs__(self) -> float:
'''Return the length (magnitude) of the vector instance.
Returns:
float: Length of the vector instance.
'''
square_sum = sum([val**2.0 for val in self.values])
return sqrt(square_sum)
def __eq__(self, other_vector: object) -> bool:
'''Check if the vector instances have the same values.
Args:
other_vector (object): Other vector instance (right-hand-side of the operator)
Returns:
bool: True, if the both vector instances have the same values. False, else.
'''
is_equal = False
if isinstance(other_vector, VectorND):
if self.values == other_vector.values:
is_equal = True
return is_equal
def __lt__(self, other_vector: VectorND) -> bool:
'''Check if the self instance is less than the other vector instance.
Args:
other_vector (VectorND): Other vector instance (right-hand-side of the operator).
Returns:
bool: True, if the self instance is less than the other vector instance. False, else.
'''
self.check_vector_types(other_vector)
is_less_than = False
if abs(self) < abs(other_vector):
is_less_than = True
return is_less_than
def __add__(self, other_vector: VectorND) -> VectorND:
'''Returns the additon vector of the self and the other vector instance.
Args:
other_vector (VectorND): Other vector instance (right-hand-side of the operator).
Returns:
VectorND: The additon vector of the self and the other vector instance.
'''
self.check_vector_types(other_vector)
add_result = [self_val + other_val for self_val, other_val in zip(self.values, other_vector.values)]
return VectorND(add_result)
def __sub__(self, other_vector: VectorND) -> VectorND:
'''Return the subtraction vector of the self and the other vector instance.
Args:
other_vector (VectorND): Other vector instance (right-hand-side of the operator).
Returns:
VectorND: The subtraction vector of the self and the other vector instance.
'''
self.check_vector_types(other_vector)
sub_result = [self_val - other_val for self_val, other_val in zip(self.values, other_vector.values)]
return VectorND(sub_result)
def __mul__(self, other: Union[Number, VectorND]) -> Union[Number, VectorND]:
'''Return the multiplication of the self vector and the other vector(or number) instance.
Args:
other (Union[Number, VectorND]): Other vector instance or scaler
value (right-hand-side of the operator)
Raises:
TypeError: Not int/float passed in.
Returns:
Union[Number, VectorND]: The multiplication of the self vector and the other
vector(or number) instance.
'''
if isinstance(other, VectorND):
return sum([self_val * other_val for self_val, other_val in zip(self.values, other.values)])
elif isinstance(other, numbers.Real):
mul_result = [val * other for val in self.values]
return VectorND(mul_result)
else:
raise TypeError('You must pass in a vector instance or an int/float number!')
def __truediv__(self, other: Number) -> VectorND:
'''Return the multiplication of the self vector and the other vector(or number) instance.
Args:
other: Other vector instance or scaler value (right-hand-side of the operator).
Raises:
ValueError: Division by zero.
TypeError: Not int/float passed in.
Returns:
Number: The multiplication of the self vector and the other vector(or number) instance.
'''
if isinstance(other, numbers.Real):
if other != 0.0:
div_result = [val / other for val in self.values]
return VectorND(div_result)
else:
raise ValueError('You cannot divide by zero!')
else:
raise TypeError('You must pass in an int/float value!')
@staticmethod
def check_vector_types(vector: object) -> None:
'''Check if the vector is an instance of the VectorND class.
Args:
vector (object): A vector instance.
Raises:
TypeError: If vector is not an instance of the VectorND class.
'''
if not isinstance(vector, VectorND):
raise TypeError('You have to pass in two instances of the vector class!')
|
f4cac784bd7c490121724af0fff2a185240400ac | HiThereItsMeTejas/Python-for-Data-Sciences | /start.py | 1,034 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print "here i start!!"
# In[6]:
# panda stands for Python-based data analysis toolkit.
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
plt.title("sine wave form")
# Plot the points using matplotlib
plt.plot(x, y)
plt.show()
# In[16]:
import numpy as np
import pandas as pd
#series
s = pd.Series([1,3,5,np.nan,6,8])
s
# In[17]:
#Data Frame (Hit tab for suggestions on Jupyterlab)
#setting date range
date = pd.date_range('20200202' , periods=6)
date
# In[20]:
df = pd.DataFrame(np.random.randn(6,4),index=date, columns=list('ABCD'))
df
# In[21]:
df.head()
# In[22]:
df.tail()
# In[23]:
df.head(1) #selecting 1st row from data
# In[24]:
df.tail(2) #selecting last 2 row from data
# In[25]:
df.index
# In[26]:
df.columns
# In[28]:
df.to_numpy
# In[71]:
df.describe()
# In[ ]:
# In[ ]:
# In[ ]:
|
8863412ba7d853cc7deae39ea0db498d6956b168 | topherCantrell/class-AdvancedPython | /Topics/02_Databases/Book.py | 381 | 3.53125 | 4 | '''
A class to represent books in a database.
Is this better than a plain old dict?
'''
class Book:
isbn = ""
name = ""
price = 0.0
publisher = ""
a = Book()
b = Book()
c = Book()
d = Book()
a = Book()
a.isbn = "1234"
a.name = "Learn C++"
a.price = 10.0
a.publisher = "Good Books"
e = {'isbn':"test", 'name':"name"}
print(e)
|
66065636d31095e24f4ecfde1b88375c27758cb7 | tariful-fahim/python | /Beginning of Python/tuples&sets.py | 1,205 | 4.34375 | 4 | #Mutable
List_1 = ['CSE', 'CEP', 'EEE', 'IPE']
List_2 = List_1;
print(List_1)
print(List_2)
List_1[3] = 'Bangla'
print(List_1)
print(List_2)
#Immutable
tuples_1 = ('CSE', 'CEP', 'EEE', 'IPE')
tuples_2 = tuples_1
print(tuples_1)
print(tuples_2)
# tuples_1[3] = 'Bangla' tuples object doesn't support item assignment because it is immutable. most of
# the list method doesn't work at tuple..
print(tuples_1)
print(tuples_2)
#SET
#unordered and doesn't support the duplicate value
courses_1 = {'CSE', 'EEE', 'CEP', 'STAT', 'IPE', 'IPE'}
print(courses_1)
# Intersection, Union, Difference method between two sets
courses_2 = {'Art','EEE','Bangla','STAT','CEP'}
print(courses_1.intersection(courses_2))
print(courses_1.union(courses_2))
print(courses_1.difference(courses_2))
#we can combined set using mathematical expression
first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}
print(first | second)
print(first & second)
print(first - second)
print(second - first)
print(first ^ second)
#Empty list
empty_list = []
#or
empty_list = list()
#Empty tuple
empty_tuple = ()
#or
empty_tuple = tuple()
#Empty set
#empty_set = {} #this isn't right. it creates dictionary.
#or
empty_tuple = tuple() |
c012384cd7d192f31e99cd26547a6df02506a670 | TaniaOstapovych/amis_python71 | /km71/Ostapovych_Tetiana/11/task11_3.py | 236 | 3.890625 | 4 | def numbers(list):
if len(list) < 2:
return list
else:
x = len(list) // 2
return numbers(list[x:]) + numbers(list[:x])
print(numbers(input('Введіть елементи списку').split())) |
8883225b3af0f4c57338f8cf87706435276a7283 | AndersonAlcantar/myFirstPythonProjects | /temperatures.py | 2,004 | 3.71875 | 4 | i = 0
acumulador_total_dias = 0
acumulador_error_dias = 0
acumulador_temp_min = 0
acumulador_temp_max = 0
acumulador_error_ambos_dias = 0
media_temp_minima = 0
media_temp_max = 0
acumulador_ambos_dias = 0
while True:
i = i + 1
print(f"Dia {i}")
temperatura_min = int(input("Ingrese la temperatura minima: "))
temperatura_max = int(input("Ingrese la temperatura maxima: "))
acumulador_total_dias = acumulador_total_dias + 1
if(temperatura_min>temperatura_max):
print("Fuera de rango")
break
if (temperatura_min == 0 and temperatura_max == 0):
break
if(temperatura_min < 5 or temperatura_max > 35):
acumulador_error_dias = acumulador_error_dias + 1
if(temperatura_min < 5):
acumulador_temp_min = acumulador_temp_min + 1
if(temperatura_max > 35):
acumulador_temp_max = acumulador_temp_max + 1
if(temperatura_min < 5 and temperatura_max > 35):
acumulador_error_ambos_dias = acumulador_error_ambos_dias + 1
if (temperatura_min > 4 and temperatura_max < 36):
acumulador_ambos_dias = acumulador_ambos_dias + 1
media_temp_minima = media_temp_minima + temperatura_min
media_temp_max = media_temp_max + temperatura_max
print("/////////////////////////////////////////////////////")
print(f"Numero total de dias registrados: {acumulador_total_dias-1} \n" +
f"Numero total de dias registrados con error: {acumulador_error_dias} \n" +
f"Numero total de dias con temperaturas menores a 5: {acumulador_temp_min} \n" +
f"Numero total de dias con temperaturas mayores a 35: {acumulador_temp_max} \n" +
f"Numero total de dias con ambos errores: {acumulador_error_ambos_dias} \n" +
f"Temperatura media minima: {media_temp_minima / acumulador_ambos_dias} \n" +
f"Temperatura media maxima: {media_temp_max / acumulador_ambos_dias} \n" +
f"Porcentaje de dias que se reportaron errores: {int((acumulador_error_dias/(acumulador_total_dias-1))*100)}%") |
b13a8ecd17cbcbb0fc2a855b07396a6d97f42102 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/169_simple_length_converter/save1_passed.py | 659 | 4.09375 | 4 | def convert(value: float, fmt: str) -> float:
"""Converts the value to the designated format.
:param value: The value to be converted must be numeric or raise a TypeError
:param fmt: String indicating format to convert to
:return: Float rounded to 4 decimal places after conversion
"""
fmt = fmt.casefold()
is_float = None
while is_float is None:
try:
is_float = float(value)
except TypeError:
print('TypeError. Please input float.')
if fmt == 'cm':
return round(value * 2.54, 4)
elif fmt == 'in':
return round(value / 2.54, 4)
else:
raise ValueError |
3c5540dc3556180b7387c2266c833cae99498474 | bcobanoglu/HerkesIcinPython | /bolum5/Ornek5_6_HesapMakinesi.py | 455 | 4.1875 | 4 | '''
Örnek 5.6. Dört işlem (toplama, çıkarma, çarpma ve bölme) yapan bir hesap makinesi programını kodlayunız.
{ Sayı girişi ve işlem operatörü klavyeden girilecek }.
@author:Bülent Çobanoğlu
'''
# -*- coding: UTF-8 -*-
s1=int(input('s1..:'))
s2=int(input('s2..:'))
op =input('islem..:')
if (op=='+'):
S=s1+s2
elif (op=='-'):
S=s1-s2
elif (op=='*'):
S=s1*s2
elif (op=='/'):
S=s1/s2
else:
print("Hatalı seçim")
print("Sonuc=",S)
|
616a143126239ef161b782cd7874c3aef5697fd6 | jarmknecht/Algorithms | /Fermat/fermat.py | 3,612 | 3.921875 | 4 | import random
import math
def prime_test(N, k):
# Has a time complexity of O(n^6)
# Has a space complexity of O(n) since it calls mod_exp and is_carmichael
prime = None # Bool to keep track if prime
carmichael = None # Bool to keep track if carmichael number
numsUsed = [] # Keeps track of numbers used to ensure they are unique
i = 1 # Starting counter for while loop
while i <= k and i is not 0: # Loop that does k random trials the not 0 ensures that we don't loop negative
a = random.randint(1, N - 1) # Creates a random number that is assigned to a for Fermat's Test
if a not in numsUsed: # checks to make sure the number hasn't been used
i += 1
numsUsed.append(a)
mod = mod_exp(a, N - 1, N) # saves the value from modular exponentiation
if not mod == 1: # Failed the Fermat test so it is composite
prime = False
break
else:
prime = True
else:
i -= 1
numsUsed.clear() # Clears the list so it can be used if need to check carmichael numbers
i = 1
if prime: # May be prime or carmichael number so need to check k times again
while i <= k and i is not 0: # Loop that does k random trials the not 0 ensures that we don't loop negative
a = random.randint(1, N - 1)
if a not in numsUsed: # checks to make sure the number hasn't been used so it is unique
i += 1
numsUsed.append(a)
carmichael = is_carmichael(N, a)
if carmichael: # number is a carmichael number so break loop
prime = False
break
else:
prime = True
else:
i -= 1
if prime:
return 'prime'
elif not prime and carmichael:
return 'carmichael'
else:
return 'composite'
def mod_exp(x, y, N):
# Has a time O(n^3) n is the number of bits in x, y or N whichever is biggest
# Space O(n) cause each recursive call of n is stored on the stack and then deleted when returned with each call
if y == 0: # If the exponent is 0 from flooring it stop
return 1
z = mod_exp(x, math.floor(y / 2), N) # Recurse until you get y = 0
if y % 2 == 0: # if y is even
return pow(z, 2) % N
else: # if y is odd
return x * pow(z, 2) % N
def probability(k):
# Has space complexity of this function is O(n) where n is the bit size of k
# cause as k gets larger more space is needed to store the float
# Has time complexity of O(k)
return 1 - (1 / math.pow(2, k)) # calculates the probability that the number is prime
def is_carmichael(N, a):
# The time complexity here is O(n^4) since it is O(n) and calls mod_exp which is O(n^3)
# n is the bit size of y which is the number N - 1
# Space complexity here is O(n) since it calls mod_exp
y = N - 1
while True:
if y == 1: # This breaks if y gets to one since 1 is odd
break
mod = mod_exp(a, y, N)
if not mod == 1: # if mod_exp is not one check if its prime or carmichael
if mod == N - 1: # This means it is prime
return False
else: # This means it is a Carmichael number
return True
if not (y % 2) == 0: # Checks to see if the exponent is divisible by two if not stop
break
y = y / 2 # Divide exponent by 2 which is the same as sqrt the whole equation
return False
|
04982230b66e427b2bae6c613ced04be19e6516c | Leon-Singleton/Forest-Fire-Simulation-Using-Cellular-Automata-Python | /release/ca_descriptions/templates/wind.py | 3,270 | 3.59375 | 4 | import numpy as np
DIRECTIONS = {"NW", "N", "NE", "W", "E", "SW", "S", "SE"}
def opposite(direction): #gets opposite direction e.g opposite of NE is SW
list_directions = np.array(["N", "NE", "E", "SE", "S", "SW", "W", "NW"])
item_index = np.where(list_directions==direction)[0]+4
return list_directions[item_index % len(list_directions)]
def wind_speed(direction, speed):
if direction in DIRECTIONS:
list_directions = np.array(["N", "NE", "E", "SE", "S", "SW", "W", "NW"])
item_index = np.where(list_directions==direction)[0]
listWeights = np.zeros(8)
weight_interval = speed/100
weight = weight_interval*2 #initialises weight
wrapped = False
for x in range(8): #goes through array, including wrapping round and weights the directions
listWeights[(x+item_index) % len(list_directions)] = 1+weight
if weight > -2*weight_interval and not wrapped:
weight= weight-weight_interval
else:
wrapped = True
weight = weight+weight_interval
rearranged_index = [7,0,1,6,2,5,4,3] #rearranges list so is in same order as the CA programme
return listWeights[rearranged_index]
def k_wind(speed, angle):
return np.exp(0.1783*speed* np.cos(np.deg2rad(angle)))
def wind_speed_rvalue(direction, speed):
if direction in DIRECTIONS:
list_directions = np.array(["N", "NE", "E", "SE", "S", "SW", "W", "NW"])
item_index = np.where(list_directions==direction)[0]
listWeights = np.zeros(8)
angle_interval = 45
angle = 0 #initialises weight
wrapped = False
for x in range(8): #goes through array, including wrapping round and weights the directions
listWeights[(x+item_index) % len(list_directions)] = k_wind(speed, angle)
angle = angle + angle_interval
# if angle > -2*angle_interval and not wrapped:
# angle = angle-angle_interval
# else:
# wrapped = True
# weight = weight+weight_interval
rearranged_index = [7,0,1,6,2,5,4,3] #rearranges list so is in same order as the CA programme
return listWeights[rearranged_index]
# for x in listDirections:
# if x==direction: #if x is the same as the direction highest weighting
# listWeights.append(1+speed/100*2)
# elif x == direction[0] || x == direction[1]: #if direction is a diagonal then weight the ones beside it
# listWeights.append(1+speed/100) # e.g. NE, weight N & E a bit
# elif x[0] == direction: #if direction is on the perpendicualr, weight adj
# listWeights.append(1+speed/100) # e.g. N weight NW & NE a bit
# elsif x == opposite_dir: #if x is the opposite direction lowest weighting
# listWeights.append(1-speed/100*2)
# elif x == opposite_dir[0] || x == opposite_dir[1]: #if opp_dir is a diagonal then weight the ones beside it low
# listWeights.append(1-speed/100) # e.g. NE, weight N & E a bit low
# elif x[0] == opposite_dir: #if opp_dir is on the perpendicualr, weight adj lol
# listWeights.append(1-speed/100)
# else:
# listWeights.append(1)
# return listWeights
# else:
# return "no"
print(wind_speed("S", 20))
print(wind_speed_rvalue("S", 6))
|
375082e62a0afaeb8a8b94b5dd74a255107e250c | fgaurat/gsfpython | /tpif.py | 275 | 4.0625 | 4 | # -*- coding: utf-8 -*-
str_x = input("un nombre :")
x = int(str_x)
# print x==0?"oui":"non"
print("oui" if x==0 else "non")
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More') |
7ca9b2057c8e6e1924fd276683183172b48915e0 | hoyj/ProjectEuler | /44.py | 479 | 3.734375 | 4 | from math import sqrt
def pen(n):
return n * (3*n - 1) // 2
def isPentagonal(x):
i = (sqrt(24 * x + 1) + 1) // 6
return (sqrt(24 * x + 1) + 1) / 6 == i
i = 1
pList = [] # list containing p that have already been calculated
while True:
p = pen(i)
for q in pList[::-1]:
if isPentagonal(abs(p-q)) and isPentagonal(abs(p+q)):
# found pentagonal condition
print('Min:',abs(p-q))
exit(0)
pList.append(p)
i += 1
|
d6ce82b1843b04da59e80cd64030df766789de33 | lelollew/capstone | /Code.py | 998 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 21:11:01 2019
@author: llllewellyn
"""
import csv
fileName = "capstoneCSVnoAschool.csv"
with open(fileName) as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ',')
line_count = 0
emplidSet = set()
compSet = set()
posNumSet = set()
posTitleSet = set()
jobFamSet = set()
for row in csv_reader:
if line_count == 0:
print('Column names are {", ".join(row)}')
line_count = 1
else:
emplidSet.add(str(row[0]))
compSet.add(str(row[1]))
posNumSet.add(str(row[2]))
posTitleSet.add(str(row[3]))
jobFamSet.add(str(row[4]))
print("Processed {line_count} lines. ")
print("emplidSet", len(emplidSet))
print("compSet", len(compSet))
print("posNumSet", len(posNumSet))
print("posTitleSet", len(posTitleSet))
print("jobFamSet", len(jobFamSet))
|
654b2fb576f5ab6368e15bd57eaf72363284b02a | advaithb97/Exercises | /data_structures/linked_lists/1_remove/remove.py | 583 | 4 | 4 | # A LinkedList is either:
# None
# Node
class Node:
# first: int
# rest: LinkedList
def __init__(self, first, rest = None):
self.first = first
self.rest = rest
# Write a function named remove that consumes a LinkedList ll and an integer index
# The function returns None and removes the element at the index specified
# Node(1, Node(2, Node(3, None))).remove(2) -> Node(1, Node(2, None))
def remove(ll, index):
if ll is None: return None
cur = ll.head
while index > 1:
cur = cur.rest
index -= 1
cur.rest = cur.rest.rest
|
2488208c81001e16fe32417753d4c132e87657ef | Anand-Deekshit/Menu-Driven-File-Handling | /menudrivenfile.py | 2,697 | 3.84375 | 4 | import os
os.chdir("C:\\Users\\Anand\\Desktop\\")
class File:
def __init__(self):
self.menu()
def ip(self):
self.f = input("Enter the path")
return self.f
def dir_tree(self, f):
path = os.getcwd()
folders = path.split("\\")
folders.append(f)
i = 0
for folder in folders:
print(i * "|_" + folder)
i += 1
def create(self):
f = self.ip()
if os.path.exists(f) == False:
with open(f, "w") as file:
print("File created")
self.menu()
else:
print("File already exists")
self.dir_tree(f)
self.menu()
def write(self):
self.f = self.ip()
if os.path.exists(self.f):
i = input()
with open(self.f, 'w') as file:
file.write(str(i))
self.dir_tree(self.f)
self.menu()
else:
print("File does not exist or it is not empty. Do you want to append?")
choice = input()
if choice == 'Yes' or 'yes':
self.append(self.f)
self.dir_tree()
self.menu()
def append(self, f):
try:
if os.path.exists(self.f):
self.f.append(input())
self.menu()
except:
print("File does not exist")
self.menu()
def append(self):
self.f = self.ip()
try:
if os.path.exists(self.f):
self.f.append(input())
self.dir_tree()
self.menu()
except:
print("File does not exist")
self.menu()
def read(self):
self.f = self.ip()
if os.path.exists(self.f):
with open(self.f) as file:
k = tuple(file.read().split(" "))
k = " ".join(k)
print(k)
self.dir_tree(self.f)
self.menu()
else:
print("File does not exist")
self.menu()
def delete(self):
self.f = self.ip()
try:
if os.path.exists(self.f):
os.remove(self.f)
self.dir_tree()
self.menu()
except:
print("File does not exists")
self.menu()
def red(self):
d1 = input("Enter the first directory")
d2 = input("Enter the second directory")
s1 = set(os.listdir())
s2 = set(os.listdir())
if s1 & s2 != 0:
print(len(s1 & s2), " redundant files exist")
print(s1 & s2)
else:
print('No redundant files exits')
def menu(self):
print("1. Create\n2. Write\n3. Append\n4. Read\n5. Delete\n6. Check redundant files")
ch = int(input("Enter an operation"))
if ch == 1:
self.create()
elif ch == 2:
self.write()
elif ch == 3:
self.append()
elif ch == 4:
self.read()
elif ch == 5:
self.delete()
elif ch == 6:
self.red()
else:
print("Enter a valid choice")
File()
|
91c16f7696edd1ce395e78a6fc60deb6a8db6b32 | chenhh/Uva | /uva_11526.py | 733 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 1
https://uva.onlinejudge.org/external/115/11526.pdf
http://luckycat.kshs.kh.edu.tw/homework/q11526.htm
"""
import math
def orig_H(n):
"""
if n is a very large number, it will TLE
e.g. n= 2**31-1, complexity: O(n)
"""
return sum(n//idx for idx in range(1, n+1))
def H(n):
""" complexity : O(lg n) """
if n <=0:
return 0
root = int(math.sqrt(n)) + 1
res = sum(n//idx for idx in range(1, root))
root -= 1
res = res*2 - root*root
return res
def main():
T = int(input())
for _ in range(T):
n = int(input())
print(H(n))
if __name__ == '__main__':
main() |
28d89cc60cd13bfb8873679aa5b8462f53e7ae96 | apostolistselios/single-lane-bridge | /car.py | 1,452 | 3.953125 | 4 | import threading
import time
class Car(threading.Thread):
"""Simulates a car - thread trying to cross a bridge"""
def __init__(self, type, id, direction, bridge):
threading.Thread.__init__(self)
self.type = type
self.id = id
self.direction = direction
self.bridge = bridge
self.start() # Starting the car when the object is created
try:
time.sleep(1)
except InterruptedError:
print('Interrupted Error')
exit(1)
except KeyboardInterrupt:
print('Keyboard Interrupt')
exit(1)
def _print_waiting(self):
"""Prints a car is waiting, on the correct side depending on the car."""
if self.direction == 'West':
print(f'{self.type}-{self.id} is waiting')
elif self.direction == 'East':
print(f'\t\t\t\t\t\t{self.type}-{self.id} is waiting')
def run(self):
if self.bridge.id in [1, 2]:
self._print_waiting()
self.bridge.cross(self)
elif self.bridge.id in [3, 4]:
self._print_waiting()
if self.type == 'BlueCar':
if self.id == 0:
self.bridge.blue_turn = True
self.bridge.blue_crossing(self)
else:
if self.id == 0:
self.bridge.red_turn = True
self.bridge.red_crossing(self)
|
cf4933c86dbb956f71e2d7312791261f68a35742 | Eomys/SciDataTool | /SciDataTool/Methods/DataLinspace/get_periodicity.py | 555 | 3.703125 | 4 | def get_periodicity(self):
"""Gives periodicity of the axis.
Parameters
----------
self: DataLinspace
a DataLinspace object
Returns
-------
per, is_antiper
"""
per = 1
is_antiper = False
if "antiperiod" in self.symmetries:
if self.symmetries["antiperiod"] > 1:
per = self.symmetries["antiperiod"]
is_antiper = True
elif "period" in self.symmetries:
if self.symmetries["period"] > 1:
per = self.symmetries["period"]
return (per, is_antiper)
|
44cd91cad93df853bb3ed8f719ebf031f53c5b41 | arisestar/radiobuttongui | /radiobuttondemo.py | 2,067 | 3.921875 | 4 | """
program : radiobuttondemo.py
author :audrey 10/19/2020
chapter pg 283-284
simple GUI-based application that highlights the use of check boxes.
"""
from breezypythongui import EasyFrame
import tkinter.filedialog
class RadiobuttonDemo(EasyFrame):
"""Allows the user to place a resturant order from a set of radio button options."""
def __init__(self):
"""Sets up the window and wedgets."""
EasyFrame.__init__(self,title = "radio button demo", width = 300, height = 100)
# add the label,button group, and buttons for meats
self.addLabel(text = "Meat", row = 0, column = 0 )
self .meatGroup = self.addRadiobuttonGroup(row = 1, column = 0, rowspan = 2 )
defaultRB = self.meatGroup.addRadiobutton(text =" chicken")
self.meatGroup.setSelectbutton(defaultRB)
self.meatGroup.addRadiobutton(text = "Beef")
# Add the label, button group, and buttons for potatoes
self.addLabel(text ="potatoes", row =0 , column = 1,)
self.taterGroup = self. addRadiobutton(row = 1, column = 1, rowspan = 2)
defaultRB = self. taterGroup.addRadiobutton(text = "French fries")
self.taterGroup.addRadiobutton( text = "Baked potato")
# add the label, button group, and buttons for veggies
self.addLabel(text = "Vegetable", row = 0 , column = 2)
self.vegGroup = self.addRadiobutton(row = 1, column = 2, rowspan = 2)
defaultRB = self.vegGroup.addRadiobutton(text = "Applesauce")
self.vegGroup.setSelectbutton(defaultRB)
self.vegGroup.addRadiobutton(text = "Green Beans")
self.addRadiobutton(text = "Place order", row = 3, column = 0,columnspan = 3, command = self.placeOrder)
# event handler method.
""" display a message box with the order information."""
message = ""
message += self.meatGroup.getSelectedButton()["text"]+ "\n\n"
message += self.taterGroup.getSelectedButton()["text"] + "\n\n"
message += self.vegGroup.getSelectedButton()["text"]
self.messageBox(title = "Customer order", message = message)
# definintion of the main function
def main():
radiobuttomDemo().mainloop()
#global call to the main() function
main()
|
e150fef69bf153e356df23044243491e8bdcc8ee | gnorambuena/randomCodes | /python/ejercicio6.py | 438 | 3.859375 | 4 | from coprimos import coprimos
#main: int, int -> None
#esta funcion entrega los coprimos del 1 al 20
#ej: main(2,20)
def main(a,b):
if(coprimos(a,b)):
print a,b
return main(a,b-1)
else:
if(a==b):
if(a==20):
return
else:
main(a+1,20)
else:
return main(a,b-1)
main(2,20)
|
8d17f4f6f00ec9edcc5ac6f0b49c12a51b835a7a | QitaoXu/Lintcode | /interviews/FB/primeProduct.py | 749 | 3.5625 | 4 | class Solution:
"""
@param arr: The prime array
@return: Return the array of all of prime product
"""
def getPrimeProduct(self, arr):
# Write your code here
results = []
self.dfs(arr, [], 0, 1, results)
results.sort()
return results
def dfs(self, arr, combination, start_index, product, results):
if len(combination) > 1:
results.append(product)
for i in range(start_index, len(arr)):
combination.append(arr[i])
self.dfs(arr, combination, i + 1, product * arr[i], results)
combination.pop() |
abd658fff277ffae32e5afce77271decef7334cd | yanhualei/about_python | /python_learning/python_base/元类的学习和理解.py | 574 | 4.25 | 4 | """"""
# 元类:创建类对象的类
"""暂时作为了解内容"""
# 元类的作用: 创建类
# 自定义元类作用:修改类的方法和属性,改变类的创建过程
class test1(object):
...
bar="bar"
test = type("test1",(object,),{"bar":print("我是元类type创建的类")})
print(type(test))
# test.bar
"""
orm:对象关系映射(object relationship mapping)
类名对应表名
类属性对应表列
作用:可以使编程直接面向数据库,面向对象编程
当你操作对象时,orm会帮你做映射,去操作数据库
""" |
6cc19db934881d91e9b827d37518524f5c1c4ddd | 6ftunder/open.kattis | /py/One Chicken Per Person!/one_chicken_per_person.py | 401 | 3.796875 | 4 | needed_chicken, chickens_in_stock = map(int, input().split())
# how many chickens are left/needed
leftover = chickens_in_stock - needed_chicken
print('Dr. Chaz will have {} piece{} of chicken left over!'.format(leftover, '' if leftover == 1 else 's')
if needed_chicken < chickens_in_stock else 'Dr. Chaz needs {} more piece{} of chicken!'.format(abs(leftover), '' if leftover == -1 else 's'))
|
60adfbc0ef9e366c71be288dfe0abdef1db86b0a | yiv/py-lab | /datatype/convert.py | 84 | 3.53125 | 4 | def float_to_int():
f = 3.14
i = int(3.14)
print(f, i)
float_to_int()
|
814e42a5a277453c92bcd1c04fe9f8056f530dcf | SophMC/exeter_traffic | /scripts/plot_barplots.py | 3,259 | 3.65625 | 4 | # Make stacked bar plots with various combinations of roads
# Need to have run make_relative_csv.py before this to make the
# Exeter_city_only.csv csv
import pandas as pd
import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# read in all the data make a bar plot for each road
exeter_city = pd.read_csv("../data/Exeter_city_only.csv", header = 0)
years = [2014,2013,2012,2011,2010,2009,2008,2007,
2006,2005,2004,2003,2002,2001,2000]
for year in years:
# select a year and make a barplot with the distribution of vehicles for each road.
exeter_year = exeter_city[exeter_city["AADFYear"] == year]
mode = ['PedalCycles', 'Motorcycles', 'CarsTaxis', 'BusesCoaches', 'LightGoodsVehicles',
'AllHGVs', 'AllMotorVehicles']
# make a dataframe of just the columns we want to stack in the bar plot
exeter_year = exeter_year[["Road","PedalCycles","Motorcycles",
"CarsTaxis","BusesCoaches","LightGoodsVehicles", "AllHGVs"]]
# prepare the dataframe for plotting
exeter_year.set_index(exeter_year["Road"], inplace = True, drop = True)
exeter_year.drop('Road', axis=1, inplace=True)
exeter_year.plot.bar(stacked = True)
plt.title('Road useage by vehicle type (CPs) %s'%str(year))
fig = plt.gcf()
directory = "../plots/barplots/all_roads"
if not os.path.exists(directory):
os.makedirs(directory)
fig.savefig('../plots/barplots/all_roads/eachCP_%s.png'%str(year))
plt.clf()
# Perhaps we just want to focus on the smaller roads in Exeter. Lets drop rows with M5 or
exeter_outer = exeter_year[(exeter_year.index == "M5") | (exeter_year.index == "A30")]
exeter_inner = exeter_year[(exeter_year.index != "M5") & (exeter_year.index != "A30")]
# group by road
# Inner
group_inner = exeter_inner.groupby(exeter_inner.index).mean()
group_inner.plot.bar(stacked = True)
plt.title('Inner Road useage by vehicle type %s'%str(year))
fig = plt.gcf()
directory = "../plots/barplots/inner_roads"
if not os.path.exists(directory):
os.makedirs(directory)
fig.savefig('../plots/barplots/inner_roads/inner_barplot%s.png'%str(year))
plt.clf()
# Outer
group_outer = exeter_outer.groupby(exeter_outer.index).mean()
group_outer.plot.bar(stacked = True)
plt.title('Outer Road useage by vehicle type %s' %str(year))
fig = plt.gcf()
directory = "../plots/barplots/outer_roads"
if not os.path.exists(directory):
os.makedirs(directory)
fig.savefig('../plots/barplots/outer_roads/outer_barplot%s.png'%str(year))
plt.clf()
# Group all roads
group_year = exeter_year.groupby(exeter_year.index).mean()
group_year.plot.bar(stacked = True)
plt.title('All Road useage by vehicle type %s' %str(year))
fig = plt.gcf()
directory = "../plots/barplots/all_roads"
if not os.path.exists(directory):
os.makedirs(directory)
fig.savefig('../plots/barplots/all_roads/each_road_barplot%s.png'%str(year))
plt.clf()
# Make a plot normalised over each road.
|
19698998bc11a9cb3195b3407caa21f11976e50f | RodionLe/Dawson-Python | /1/Не надо оваций.py | 527 | 3.96875 | 4 | print("\t\t\tВоображаемые благодарности")
print("\t\t\tразработчика игры")
print("\t\t\tЛегинькова Родиона")
print("\t\t\t \\ \\ \\ \\ \\ \\ \\ \\")
print("\n")
print("Отдельное спасибо хотелось сказать:")
print("моему парикмахеру Никите по прозвищу \'Демон\', который не знает слова\"невозможно\".")
print("\a")
input("\n\n\nНажмите enter,чтобы выйти.")
|
02245660b40068c1ee097672a19c8538c3157a89 | thedern/algorithms | /recursion/fibonachi.py | 690 | 4.40625 | 4 |
def fibonacci_iterative(n):
a, b = 0, 1
for _ in range(n):
# range 0, n, includes lower, excludes upper
# variable swap: a = b, b = a + b
a, b = b, a + b
return a
def fibonacci_recursive(n):
# base case
if n < 2:
return n
# add two previous terms to get current term
# decrements until n < 2
# this is an expensive call algorithm as it loads up the call stack
# (think about how fibonacci numbers work if one entered 10)
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
def main():
# print(fibonacci_iterative(10))
print(fibonacci_recursive(10))
if __name__ == "__main__":
main()
|
679f2945df34081e4a8e898fabc9638d39a0612b | vikas-t/practice-problems | /full-problems/countNumberOfHops.py | 315 | 3.546875 | 4 | #!/usr/bin//python3
# https://practice.geeksforgeeks.org/problems/count-number-of-hops/0
def sol(n):
if n <= 1:
return 1
if n == 2:
return 2
dp = [0]*(n+1)
dp[0] = 1
dp[1] = 1
dp[2] = 2
for i in range(3, n+1):
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
return dp[n] |
e083ef2ecd3d90bd06eb51a3787b097d82c2b9b6 | Julian-Chu/leetcode_python | /lintcode/lintcode667.py | 1,244 | 3.6875 | 4 | class Solution:
"""
@param s: the maximum length of s is 1000
@return: the longest palindromic subsequence's length
"""
def longestPalindromeSubseq(self, s):
if not s:
return 0
n = len(s)
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = 1
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1]
class Solution:
"""
@param s: the maximum length of s is 1000
@return: the longest palindromic subsequence's length
"""
def longestPalindromeSubseq(self, s):
length = len(s)
if length == 0:
return 0
dp = [[0]*length for _ in range(length)]
for i in range(length-1, -1, -1):
dp[i][i] = 1
for j in range(i+1, length):
if s[i] == s[j]:
dp[i][j] = dp[i+1][j-1]+2
else:
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
return dp[0][length-1] |
08b28bfbb48dabd887ad1b5495de517c0035948b | KITcar-Team/kitcar-gazebo-simulation | /simulation/src/simulation_onboarding/src/onboarding/node.py | 990 | 3.53125 | 4 | """OnboardingNode."""
from simulation.utils.ros_base.node_base import NodeBase
class OnboardingNode(NodeBase):
"""ROS node to teach new members."""
def __init__(self):
"""Initialize the node."""
super().__init__(name="onboarding_node")
# Start running node
# This will do the following
# 1) Call self.start()
# 2) Call self.steer() 60 times a second!
# 3) Call self.stop() when ROS is shutting down
self.run(function=self.steer, rate=60)
def start(self):
"""Start node."""
# When overwriting a function, ensure that the original function (NodeBase.start())
# is also called
super().start()
def stop(self):
"""Turn off node."""
# When overwriting a function, ensure that the original function (NodeBase.stop())
# is also called
super().stop()
def steer(self):
"""Control the car's pose to drive along the road."""
pass
|
ec2c6ce3da49d41d14be59870f717dc7a4b7fe23 | pylangstudy/201706 | /20/01/3.py | 879 | 4.125 | 4 | class Human:
def __init__(self): self.__intro()
def intro(self): print('Human')
__intro = intro
class Programmer(Human):
def intro(self):
print('---------Programmer intro start----------')
# super().__intro() # AttributeError: 'super' object has no attribute '_Programmer__intro'
super()._Human__intro()
# super()._Human__intro(self) # TypeError: intro() takes 1 positional argument but 2 were given
# self.__intro() # AttributeError: 'Programmer' object has no attribute '_Programmer__intro'
self._Human__intro() # プライベートメソッドも継承されているからselfで参照できる?
# self._Human__intro(self) # TypeError: intro() takes 1 positional argument but 2 were given
print('Programmer')
print('---------Programmer intro end----------')
p = Programmer()
p.intro()
|
b90ad266bf0da6be8b574c1c55cb20b8576fd5b8 | gbeeber/Tic-Tac-Toe | /tictactoe.py | 4,732 | 3.921875 | 4 | # Function To Display the Board
def display_board(board):
# Check to see if it's a test board and only print out one board
if len(board)==10:
print('\n'*2)
print(' '*6,' | | ')
print(' '*6,' ',board[6], '|',board[7],'|',board[8])
print(' '*6,'____|___|___')
print(' '*6,' | | ')
print(' '*6,' ',board[3], '|',board[4],'|',board[5])
print(' '*6,'____|___|___')
print(' '*6,' | | ')
print(' '*6,' ',board[0], '|',board[1],'|',board[2])
print(' '*6,' | | ')
print('\n'*4)
else:
print('\n'*100)
print(' '*6,' | | ',' '*20,' | | ')
print(' '*6,' ',board[6], '|',board[7],'|',board[8],' '*21,' ','7', '|','8','|','9')
print(' '*6,'____|___|___',' '*20,'____|___|___')
print(' '*6,' | | ',' '*20,' | | ')
print(' '*6,' ',board[3], '|',board[4],'|',board[5],' '*21,' ','4', '|','5','|','6')
print(' '*6,'____|___|___',' '*20,'____|___|___')
print(' '*6,' | | ',' '*20,' | | ')
print(' '*6,' ',board[0], '|',board[1],'|',board[2],' '*21,' ','1', '|','2','|','3')
print(' '*6,' | | ',' '*20,' | | ')
print('\n'*4)
# A function to ask the player for which box they want to mark
def ask_player(player,board):
while True:
if player=='p1':
strposition=input('Player 1: What square would you like to mark? ')
elif player=='p2':
strposition=input('Player 2: What square would you like to mark? ')
try:
position=int(strposition)
except:
print('Bad input. Please only enter an integer from 1 to 9.')
continue
if position not in range(1,10) :
print('Bad input. Please only enter an integer from 1 to 9.')
continue
if board[position-1] != ' ':
print('This space is taken. Please pick an open space.')
continue
else:
return position
# Check to see if there is a winner
def check_winner(board):
space=False
rows=[str(board[0]+board[1]+board[2]),str(board[3]+board[4]+board[5]),str(board[6]+board[7]+board[8])]
columns=[str(board[0]+board[3]+board[6]),str(board[1]+board[4]+board[7]),str(board[2]+board[5]+board[8])]
diagonals=[str(board[0]+board[4]+board[8]),str(board[6]+board[4]+board[2])]
for check in rows:
if check=='XXX' or check=='OOO':
print('Congratulations! You won!')
return True
for check in columns:
if check=='XXX' or check=='OOO':
print('Congratulations! You won!')
winner==True
return True
for check in diagonals:
if check=='XXX' or check=='OOO':
print('Congratulations! You won!')
winner==True
return True
for c in board:
if c==' ':
space=True
if space==True:
return False
elif space==False:
print("It's a tie! Try again!")
return True
# Ask to play ask to play again
def ask_playagain():
while True:
playagain=input('Would you like to play again?')
if playagain=='y' or playagain=='Y':
return True
elif playagain=='n' or playagain=='N':
print('I hope this game was fun and you want to play it later!')
return False
else:
print('Bad input. Please enter either Y or N.')
# Start The Game
keepplaying=True
while keepplaying==True:
while True:
pinput=input('Player 1: Would you like X or O? ')
if pinput == 'x' or pinput =='X':
players={'p1':'X','p2': 'O'}
break
elif pinput == 'o' or pinput == 'O':
players={'p1':'O','p2': 'X'}
break
else:
print('Bad input. Please only enter X or O')
# Instructions
print('\n'*4)
print('Instructions:')
print('Enter the number of the position you would like to mark based on the pattern')
print('below when it is your turn.')
test_board=list(range(1,11))
display_board(test_board)
# Initialize the game
import random
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
flip=random.randint(0,1)
if flip==0:
player='p1'
else:
player='p2'
winner=False
# Run the game
while winner==False:
pos=ask_player(player,board)
board[pos-1]=players[player]
display_board(board)
if check_winner(board)==True:
winner=True
if player=='p1':
player='p2'
elif player=='p2':
player='p1'
keepplaying=ask_playagain()
|
4dea18817fcdef05240ab2026e30414b7f6283d3 | drzewickidan/PalindromeProtocol | /client.py | 1,773 | 3.640625 | 4 | import socket
import sys
# address and port of server
# for ECEC531, this is hardcoded to run on localhost:5000
host = '127.0.0.1'
port = 5000
def client():
# create client obeject
s = socket.socket()
s.connect((host, port))
if len(sys.argv) == 2:
# non-persistent connection
if sys.argv[1] == "-np" or sys.argv[1] == "--non-persistent":
# user input to send to server
msg = raw_input()
# check if QUIT command was used
if not msg == "QUIT":
# send command
s.send(msg)
# receive response from server
data = s.recv(1024)
# display data received from server
print str(data)
# if QUIT was entered, first tell the server to close connection and then close socket
s.send("QUIT")
s.close()
else:
raise Exception("unrecognized argument")
elif len(sys.argv) > 2:
# if the amount of arguments are greater than two (client.py <arg1> [<arg2>] raise an Exception)
raise Exception("too many arguments")
# default: persistent connection
else:
# user input to send to server
msg = raw_input()
while True:
# if QUIT is entered, send to server and break loop to close connection
if msg == "QUIT":
s.send(msg)
break
# send command
s.send(msg)
# receive response from server
data = s.recv(1024)
# display data received from server
print str(data)
# continue sending commands
msg = raw_input()
s.close()
if __name__ == "__main__":
client()
|
08eeea5f98d48ed7ac523eaaea8de122c427791b | MrAdequate-Bar/Assignment2 | /ForwardIndex.py | 6,426 | 3.5625 | 4 | import sys
import re
import operator
import os
import math
from sys import argv
class Word_Freq:
def __init__(self):
self.word_dict = {}
self.doc_dict = {}
self.doc_count = 0
self.word_count = 0
# opens file and tokenizes it, adding it into a dictionary
def open_f(self, f):
try:
with open(f, 'r') as file:
if os.stat(f).st_size == 0:
print("This file is empty: {0}".format(f))
return
for i in file:
i = i.lower()
i = re.sub(r'\\n+', ' ', i)
i = re.sub(r'\W+|_+', ' ', i)
i = i.split()
for j in i:
if j not in self.word_dict:
self.word_dict[j] = 1
else:
self.word_dict[j] += 1
except IOError:
print("This file does not exist: {0}".format(f))
# sorts the dict in descending order and prints it
def print_word_dict(self, dir):
for k, v in sorted(self.word_dict.items(), key=operator.itemgetter(1), reverse=True):
print("{0} - {1}".format(k, v))
def clear_dict(self):
self.word_dict.clear()
def iterate_directories(self, d):
# Open each file within a directory and make a forward index of the tokens
with open('Index.txt', 'a') as f:
for subdir, dirs, files in os.walk(d):
for file in files:
if file == 'bookkeeping.json' or file == 'bookkeeping.tsv':
continue
self.open_f(os.path.join(subdir, file))
# This nabs the beginning of the directory for URL lookup in the jsons
fileNumber = str(subdir)
while "\\" in fileNumber:
fileNumber = fileNumber[fileNumber.rfind("\\") + 1:]
# This loop creates the inverted index
for (k, tf) in self.word_dict.items():
if k not in self.doc_dict:
self.doc_dict[k] = [[fileNumber + "/" + str(file), tf]]
else:
self.doc_dict[k].append([fileNumber + "/" + str(file), tf])
self.doc_count += 1
self.clear_dict()
# Exchange the tf out with the tf-idf of the token
for (k, v) in self.doc_dict.items():
tmpCount = 0
for e in v:
tf = e[1]
N = self.doc_count
df = len(self.doc_dict[k])
idf = math.log10(N / df)
self.doc_dict[k][tmpCount].append(float(format(idf, '.2f')))
tf_idf = math.log10(1 + int(tf)) * idf
self.doc_dict[k][tmpCount].append(float(format(tf_idf, '.2f')))
tmpCount += 1
# Printing out the inverted index to a text file for testing
#for (k,v) in self.doc_dict.items():
#print(str(k) + " - " + str(v) + "\n")
#f.write(str(k) + " - " + str(v) + "\n")
# This is simply statistics output
# self.word_count = len(self.doc_dict)
# print("Document Count: " + str(self.doc_count))
# print("Word Count: " + str(self.word_count))
return self.doc_dict
# def print_stats(self):
# self.word_count = len(self.doc_dict)
# print("Document Count: " + str(self.doc_count))
# print("Word Count: " + str(self.word_count))
def query_parse(argv):
new_query = []
if len(argv) == 1:
print "No search terms"
return
else:
for x in argv[1:]:
new_query.append(x)
return new_query
def find_docs(token, index_dict):
if token not in index_dict:
return 'No results'
else:
docs = []
for e in index_dict[token]:
docs.append(e[0])
return docs
def make_url_dict(d):
url_dict = {}
for subdir, dirs, files in os.walk(d):
for file in files:
if file == 'bookkeeping.json' or file == 'bookkeeping.tsv':
f = os.path.join(subdir, file)
with open(f, 'r') as document:
if os.stat(f).st_size == 0:
print("This file is empty: {0}".format(f))
return
for i in document: # for each line in the document
'''
"0/0": "www.ics.uci.edu/~rickl/courses/cs-171/2016-smrq-cs171/StudentResources/StudentResources_tournament/Wumpus_World_tournament/Worlds_20160712/TestWorld5x5_787.txt",
'''
i = i.split(':')
if len(i) > 1:
s1 = i[0].strip(' "\'\t\r\n')
s2 = i[1].strip(' "\'\t\r\n')
url_dict[s1] = s2
return url_dict
def find_urls(url_dict, docIDs):
results = []
for e in docIDs:
if e in url_dict:
results.append(url_dict[e])
return results
if __name__ == "__main__":
try:
# We store all data, such a tf, idf, tf-idf, type (e.g. title, bold, h1, h2, h3)
# We still need to append types
# Accepts a query of any length
query = query_parse(sys.argv)
print(query[0])
rootdir = 'WEBPAGES_CLEAN'
w = Word_Freq()
index = w.iterate_directories(rootdir)
# We need to return all docIDs for the first word in the query M1 not M2
docIDs = find_docs(str(query[0]).lower(), index)
print(docIDs)
# We need to use those docIDs to find the URLs and give them to the user
url_dict = make_url_dict(rootdir)
results = find_urls(url_dict, docIDs)
print("Search Results \n")
for e in results:
print(str(e) + "\n")
print("Search Completed")
print("Count of results: " + str(len(results)))
#w.print_stats()
except IndexError:
print("No file was entered.")
|
be73ad5d99f3f3ef87012db3f418a7172e5547b3 | lamida/algorithms-drills | /combinatorics/permutation.py | 1,817 | 3.953125 | 4 | from typing import List
"""
We will recurse based on the idx. The base case will be when idx which is equivalent
with the stack dept reaches the size of len(s). In each of non base case, we will swap
element between idx and len(s) - 1. See permutation1.png for the ilustration.
"""
def permutation(s: List[str]) -> List[List[str]]:
results = []
def backtrack(candidate: List[str], idx: int = 0):
if idx == len(s) - 1: # the base case is when the depth of recursion equal to len(s) - 1
results.append(candidate[:])
else:
for i in range(idx, len(s)): # must start the iteration from idx!
candidate[idx], candidate[i] = candidate[i], candidate[idx]
backtrack(candidate, idx + 1)
candidate[idx], candidate[i] = candidate[i], candidate[idx]
backtrack(s)
return results
"""
We will recurse based on the depth. The base case will be when the resulted
candidate is at the same size as original string. In each of non base case,
we will get what is current character of the current stack, then will insert
the current character in all the index for the next stack. See permutation2.png
for the ilustration.
"""
def permutation2(s: List[str]) -> List[List[str]]:
results = []
def backtrack(candidate: List[str], depth: int = 0):
if len(candidate) == len(s):
results.append(candidate[:])
else:
current = s[depth]
newCandidate = candidate[:]
for i in range(depth + 1):
newCandidate.insert(i, current)
backtrack(newCandidate, depth + 1)
newCandidate = candidate[:]
backtrack([])
return results
if __name__ == "__main__":
print(permutation2([i for i in "ABC"]))
print(permutation2([]))
|
850a4a885af2d2aaa4994980086c300df9d2f669 | divya369/Competitive-Coding | /leetcode/problems/1512. Number of Good Pairs-1.py | 253 | 3.5 | 4 | def good_pair(nums):
count = 0
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] == nums[j] and i < j:
count += 1
print(count)
if __name__ == '__main__':
good_pair([1, 2, 3, 1, 1, 3])
|
e691d7a52b6f43e9b58ff91a650a465eb022f843 | phamtamlinh/coding-challenges | /basic/heap/max_heap.py | 690 | 3.78125 | 4 | import math
class MaxHeap:
def __init__(self):
self.heap = []
def getMax(self):
return self.heap[0]
def getHeap(self):
return self.heap
def insert(self, node):
self.heap.append(node)
if len(self.heap) > 0:
currentIndex = len(self.heap) - 1
while currentIndex > 0 and self.heap[math.floor((currentIndex-1)/2)] < self.heap[currentIndex]:
parentIndex = math.floor((currentIndex-1)/2)
self.heap[parentIndex], self.heap[currentIndex] = self.heap[currentIndex], self.heap[parentIndex]
currentIndex = parentIndex
maxHeap = MaxHeap()
arr = [7, 10, 4, 3, 20, 15]
for a in arr:
maxHeap.insert(a)
print(maxHeap.getHeap())
|
41309cd0868e5bb0c1b2ce46c5081190b365eccd | YuliyaHancharenka/python-basics | /exceptions/using_with.py | 742 | 3.8125 | 4 | with open("poem.txt") as f:
for line in f:
print(line, end='')
# Перед запуском блока кода, содержащегося в нём, оператор with всегда вызы-
# вает функцию thefile.__enter__, а также всегда вызывает thefile.__exit__
# после завершения выполнения этого блока кода.
# Так что код, который мы бы написали в блоке finally, будет автоматически
# обработан методом __exit__. Это избавляет нас от необходимости повторно
# в явном виде указывать операторы try..finally. |
cb5b1d9d00bd769d76fbb6c0a5999c88981768e2 | snowmanunderwater/leetcode | /python/162_problem.py | 1,365 | 3.921875 | 4 | # 162. Find Peak Element
# https://leetcode.com/problems/find-peak-element/
"""A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.
"""
# Runtime: 40 ms, faster than 91.41% of Python3 online submissions for Find Peak Element.
# Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Find Peak Element.
def findPeakElement(nums):
length = len(nums)
if length < 2:
return 0
if length == 2:
return nums.index(max(nums))
for n in range(1, length - 1):
if nums[n - 1] < nums[n] > nums[n + 1]:
return n
return nums.index(max(nums))
assert findPeakElement([1, 2, 3, 1]) == 2
assert findPeakElement([1, 2, 1, 3, 5, 6, 4]) == 1 or 5
|
d559e8727fc7802d031491423275afca0bdf1246 | btoll/howto-algorithm | /python/array/move_zeroes.py | 847 | 3.984375 | 4 | # The `i` variable will maintain the current drop index for any
# non-zero elements found by `j`.
#
# Just be sure to increment `i` every time a non-zero item `j`
# is moved to `i`.
#
# `i` will then also serve as the first index will zeroes will
# be back-filled in the array. Just start at `i` and add zero
# to every slot from there to the end of the array.
#def move_zeroes(nums):
# i = 0
# for j in range(len(nums)):
# if nums[j] != 0:
# nums[i] = nums[j]
# i += 1
#
# for k in range(i, len(nums)):
# nums[k] = 0
#
# return nums
def move_zeroes(nums):
i = 0
for j in range(len(nums)):
if nums[j] != 0:
nums[i], nums[j] = nums[j], nums[i]
i += 1
return nums
nums = [0, 1, 0, 3, 12]
#nums = [5, 0, 4, 0, 3, 0, 2, 0, 1, 0]
print(move_zeroes(nums))
|
d03e22011d1ad762614f2e128fbc9996d49be96c | sagarprasad007/sagar-prasad | /list.py | 285 | 3.875 | 4 | my_list=['python', 'for', 'SIT']
another_list=[3, 4, 6, 1]
my_list.append(another_list)
print(my_list)
lis=[2, 9, 1, 5, 3, 1, 8, 7]
del lis[2:5]
print("list elements after deleting are: ",end=" ")
for i in range(0, len(lis)):
print(lis[i], end=" ")
print("\r")
|
12412620d3dc620ad434606847dedc0556a98734 | fuadchyon/CodingBat_Python-Programming | /String-2/String-2 _ double_char.py | 358 | 4.15625 | 4 | # Problem:
# Given a string, return a string where for every char in the original,
# there are two chars.
# Exercise:
# double_char('The') → 'TThhee'
# double_char('AAbb') → 'AAAAbbbb'
# double_char('Hi-There') → 'HHii--TThheerree'
def double_char(str):
n_str = ""
for char in str:
n_str = n_str+char*2
return n_str
|
c4829a679c9e8bf77f81e1871ee9e888181d590b | LV9652/Mini-games | /Stonehinge/trees_api_mond.py | 2,775 | 4.4375 | 4 | """
This file is from the lecture of Tree classs.
"""
from typing import List
class Tree:
"""
A bare-bones Tree ADT that identifies the root with the entire tree.
"""
def __init__(self, value: object = None,
children: List['Tree'] = None) -> None:
"""
Create Tree self with content value and 0 or more children
"""
self.value = value
self.children = children.copy() if children is not None else []
def __repr__(self) ->str:
"""
Return representation of Tree (self) as string that
can be evaluated into an equivalent Tree.
>>> t1 = Tree(5)
>>> t1
Tree(5)
>>> t2 = Tree(7, [t1])
>>> t2
Tree(7, [Tree(5)])
"""
# Our __repr__ is recursive, because it can also be called
# via repr...!
return ('{}({}, {})'.format(self.__class__.__name__,
repr(self.value),
repr(self.children))
if self.children
else 'Tree({})'.format(repr(self.value)))
def __eq__(self, other: 'Tree') ->bool:
"""
Return whether this Tree is equivalent to other.
>>> t1 = Tree(5)
>>> t2 = Tree(5, [])
>>> t1 == t2
True
>>> t3 = Tree(5, [t1])
>>> t2 == t3
False
"""
return (type(self) is type(other) and
self.value == other.value and
self.children == other.children)
def __str__(self, indent: int = 0) -> str:
"""
Produce a user-friendly string representation of Tree self,
indenting each level as a visual in indent: amount to indent
each level of tree
>>> t = Tree(17)
>>> print(t)
17
>>> t1 = Tree(19, [t, Tree(23)])
>>> print(t1)
23
19
17
>>> t3 = Tree(29, [Tree(31), t1])
>>> print(t3)
23
19
17
29
31
"""
root_str = indent * " " + str(self.value)
mid = len(self.non_none_kids()) // 2
left_str = [c.__str__(indent + 3)
for c in self.non_none_kids()][: mid]
right_str = [c.__str__(indent + 3)
for c in self.non_none_kids()][mid:]
return '\n'.join(right_str + [root_str] + left_str)
def non_none_kids(self):
""" Return a list of Tree self's non-None children.
@param Tree self:
@rtype: list[Tree]
"""
return [c
for c in self.children
if c is not None]
if __name__ == "__main__":
from python_ta import check_all
check_all(config="a2_pyta.txt")
|
2573c73c4508fe37105cf6fcb005e677546e19fe | EvgeniyAzarov/PythonUniversity | /2 term/classworks/30.01.2020/14.4.py | 264 | 3.765625 | 4 | file = input()
try:
f = open(file)
except FileNotFoundError:
print("File doesn't exsist")
except IOError:
print("Input-output error")
except PermissionError:
print("You haven't enought rights")
else:
for line in f:
print(line, end="")
|
5aa621a1093b0a4cb2349c469b7035d93295afd4 | nacho-villanueva/TPE-BD2-1C2021 | /src/utils.py | 4,606 | 3.5 | 4 | import random
import numpy as np
from datetime import datetime, timedelta
from math import radians, sin, atan2, sqrt, cos
def random_datetime(min_year=1900, max_year=datetime.now().year):
# generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
start = datetime(min_year, 1, 1, 00, 00, 00)
years = max_year - min_year + 1
end = start + timedelta(days=365 * years)
return start + (end - start) * random.random()
def get_distance(lat_a, lon_a, lat_b, lon_b):
R = 6373.0
lat1 = radians(lat_a)
lon1 = radians(lon_a)
lat2 = radians(lat_b)
lon2 = radians(lon_b)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat / 2)) ** 2 + cos(lat1) * cos(lat2) * (sin(dlon / 2)) ** 2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
return R * c
def generate_nearby_pos(lat, lon, distance):
r = distance / 111300
u = np.random.uniform(0, 1)
v = np.random.uniform(0, 1)
w = r * np.sqrt(u)
t = 2 * np.pi * v
x = w * np.cos(t)
x1 = x / np.cos(lon)
y = w * np.sin(t)
return float(lat + x1), float(lon + y)
def print_init_title():
print("""
PPPPPPPPPPPPPPPPP kkkkkkkk GGGGGGGGGGGGG
P::::::::::::::::P k::::::k GGG::::::::::::G
P::::::PPPPPP:::::P k::::::k GG:::::::::::::::G
PP:::::P P:::::P k::::::k G:::::GGGGGGGG::::G
P::::P P:::::P ooooooooooo k:::::k kkkkkkk eeeeeeeeeeee mmmmmmm mmmmmmm ooooooooooo nnnn nnnnnnnn G:::::G GGGGGG ooooooooooo
P::::P P:::::Poo:::::::::::oo k:::::k k:::::kee::::::::::::ee mm:::::::m m:::::::mm oo:::::::::::oo n:::nn::::::::nn G:::::G oo:::::::::::oo
P::::PPPPPP:::::Po:::::::::::::::o k:::::k k:::::ke::::::eeeee:::::eem::::::::::mm::::::::::mo:::::::::::::::on::::::::::::::nn G:::::G o:::::::::::::::o
P:::::::::::::PP o:::::ooooo:::::o k:::::k k:::::ke::::::e e:::::em::::::::::::::::::::::mo:::::ooooo:::::onn:::::::::::::::n G:::::G GGGGGGGGGGo:::::ooooo:::::o
P::::PPPPPPPPP o::::o o::::o k::::::k:::::k e:::::::eeeee::::::em:::::mmm::::::mmm:::::mo::::o o::::o n:::::nnnn:::::n G:::::G G::::::::Go::::o o::::o
P::::P o::::o o::::o k:::::::::::k e:::::::::::::::::e m::::m m::::m m::::mo::::o o::::o n::::n n::::n G:::::G GGGGG::::Go::::o o::::o
P::::P o::::o o::::o k:::::::::::k e::::::eeeeeeeeeee m::::m m::::m m::::mo::::o o::::o n::::n n::::n G:::::G G::::Go::::o o::::o
P::::P o::::o o::::o k::::::k:::::k e:::::::e m::::m m::::m m::::mo::::o o::::o n::::n n::::n G:::::G G::::Go::::o o::::o
PP::::::PP o:::::ooooo:::::ok::::::k k:::::ke::::::::e m::::m m::::m m::::mo:::::ooooo:::::o n::::n n::::n G:::::GGGGGGGG::::Go:::::ooooo:::::o
P::::::::P o:::::::::::::::ok::::::k k:::::ke::::::::eeeeeeee m::::m m::::m m::::mo:::::::::::::::o n::::n n::::n GG:::::::::::::::Go:::::::::::::::o
P::::::::P oo:::::::::::oo k::::::k k:::::kee:::::::::::::e m::::m m::::m m::::m oo:::::::::::oo n::::n n::::n GGG::::::GGG:::G oo:::::::::::oo
PPPPPPPPPP ooooooooooo kkkkkkkk kkkkkkk eeeeeeeeeeeeee mmmmmm mmmmmm mmmmmm ooooooooooo nnnnnn nnnnnn GGGGGG GGGG ooooooooooo""")
print("""
\t\t\t\t _____ ___ ___ ___ _ ___ _ ___ ___
\t\t\t\t |_ _| | _ \ | __| | _ ) __ _ ___ ___ ___ __| | ___ | \ __ _ | |_ ___ ___ |_ _| |_ _|
\t\t\t\t | | | _/ | _| | _ \ / _` | (_-< / -_) (_-< / _` | / -_) | |) | / _` | | _| / _ \ (_-< | | | |
\t\t\t\t |_| |_| |___| |___/ \__,_| /__/ \___| /__/ \__,_| \___| |___/ \__,_| \__| \___/ /__/ |___| |___|
""")
|
7ab2b4d506872b119242ad252a638bb34ed413e6 | minlo/smartfix | /evaluation/evaluate.py | 904 | 3.59375 | 4 | import numpy as np
import pandas as pd
class Evaluate:
"""
given predict_y, true_y and error method, calculate accuracy and fluctuation point accuracy
"""
def __init__(self, predict_y, true_y, error):
self.predict_y = predict_y
self.true_y = true_y
self.error = error
def accuracy(self):
"""
calculate the accuracy by error
:return: float, the %accuracy of predict_y and true_y
"""
cnt = 0
for i, j in zip(self.predict_y, self.true_y):
# if abs(i-j)/j <= error:
if abs(i - j) < self.error:
cnt += 1
acc = cnt/len(self.predict_y)*100
return acc
def fluctuation_accuracy(self):
"""
calculate the fluctuation point accuracy by error
:return: float, the fluctuation %accuracy of predict_y and true_y
"""
pass
|
384529f18ab8a051bbab4a5811198da9ac06b9f5 | vijama1/codevita | /testvita1.py | 817 | 3.5625 | 4 | inp=int(input("Enter number of test cases"))
modules=int(input("Enter number of modules"))
list1=[]
list2=[]
hours=[]
list3=[]
dependency=[]
res=[]
sum=0
for i in range(0,modules):
list1.append([int(input("Enter serial number")),int(input("Enter hours")),int(input("Enter dependency"))])
for k in range(0,len(list1)):
hours.append(list1[k][1])
dependency.append(list1[k][2])
print(hours)
print(dependency)
for i in range(0,len(dependency)):
while dependency.count(dependency[i])<2:
sum=sum+hours[i]
list3.append(hours[i])
#dependency.remove(dependency[i])
break
res = list(set(hours)^set(list3))
sum=sum+max(res)
print(res)
print(hours)
#print(hours-list3)
print(sum)
# for i in range(0,len(list1)):
# while list1[i][3]!=list1[i+1][3]:
# sum=sum+list[i][2]
|
2c58faaf70dbeb982e968ba214fe84c67a7e50a1 | BrayanSolanoF/EjerciciosPython | /the martian.py | 1,346 | 3.703125 | 4 | #*****************************************************************************************
# Instituto Tecnologico de Costa Rica
# Ingenieria en Computadores
#Programa: funcaptura_frase
#Lenguaje: Python 3.6.4
#Autor: Brayan Solano Fonseca
#Version: 1.0
#Fecha Ultima Modificacion: Octubre 18/2018
#Entradas:Frase que incluye numeros, caracteres, signo de exclamacion y numeral
#Restricciones: Si es un caracter diferente a los ingresados en la entrada debe seer eliminado
#Salida: Nueva frase eliminando caracteres no admitidos.
#****************************************************************************************
def captura_frase(frase):
lista1=[]
i=0
#input("Ingrese una afirmacion terminada en #, o una pregunta terminada en ?")
lista0=list(frase)
if lista0==[]:
return "Error, debe ingresar una entrada valida"
else: frase_aux(lista0, lista1, i)
def frase_aux(lista0, lista1, i):
if (lista0[i]==""):
lista0.split(i)
print(lista1)
return frase_aux(lista0, lista1, i+1)
elif (lista0[i]==str) or (lista0[i]==int) or (lista0[i]=="?") or (lista0[i]=="#"):
lista0[i].lower()
lista1.append (lista0[i])
frase_aux(lista0,lista1, i+1)
print(lista1)
|
126de00024b0204f1bc477310d18f37aabac66e2 | gabrielx52/code-katas | /src/series_sum.py | 537 | 4.09375 | 4 | """Kata: Sum of the first nth term of Series - Find nth item of series.
#1 Best Practices Solution by MMMAAANNN, doctornick5, Slx64, ninja37,
FablehavenGeek, nabrarpour4 (plus 17 more warriors)
def series_sum(n):
return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n)))
"""
from __future__ import division
def series_sum(n):
"""Return nth item of sum series."""
total = 0
denom = 1
for i in range(n):
total += 1 / denom
denom += 3
return '{:.2f}'.format(total)
|
6e408209e383e44d79edf0a04d17666a6fcc2927 | Archanciel/explore | /numeric.py | 183 | 3.625 | 4 | s = '12423.23'
print(s.isnumeric())
#s = '²3455'
s = '\u00B23455'
print(s.isnumeric())
# s = '½'
s = '\u00BD'
print(s.isnumeric())
s = '1242323'
s='python12'
print(s.isnumeric()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.