blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bc0618eaecd139467ec2cd12ef96f12dc6f21e80 | jayChung0302/DeepPipe | /python_demo/key_frame_selection.py | 4,279 | 3.890625 | 4 | import torch
import cv2
import operator
import numpy as np
def smooth(x, window_len=13, window='hanning'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
import numpy as np
t = np.linspace(-2,2,0.1)
x = np.sin(t)+np.random.randn(len(t))*0.1
y = smooth(x)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
"""
if x.ndim != 1:
print("smooth only accepts 1 dimension arrays.")
raise ValueError
if x.size < window_len:
print("Input vector needs to be bigger than window size.")
raise ValueError
if window_len < 3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
print("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
raise ValueError
s = np.r_[2 * x[0] - x[window_len:1:-1],
x, 2 * x[-1] - x[-1:-window_len:-1]]
# print(len(s))
if window == 'flat': # moving average
w = np.ones(window_len, 'd')
else:
w = getattr(np, window)(window_len)
y = np.convolve(w / w.sum(), s, mode='same')
return y[window_len - 1:-window_len + 1]
# Class to hold information about each frame
class Frame:
def __init__(self, id, frame, value):
self.id = id
self.frame = frame
self.value = value
def __lt__(self, other):
if self.id == other.id:
return self.id < other.id
return self.id < other.id
def __gt__(self, other):
return other.__lt__(self)
def __eq__(self, other):
return self.id == other.id and self.id == other.id
def __ne__(self, other):
return not self.__eq__(other)
def rel_change(a, b):
x = (b - a) / max(a, b)
# print(x)
return x
def key_extraction(video_tensor, USE_TOP_ORDER=True, USE_THRESH=False, USE_LOCAL_MAXIMA=False,
THRESH=0.6, NUM_TOP_FRAMES=1, len_window=13, dir=''):
# cap = cv2.VideoCapture(str(videopath))
curr_frame = None
prev_frame = None
frame_diffs = []
frames = []
# ret, frame = cap.read()
i = 1
key_list = []
for j in range(video_tensor.size(0)):
for i in range(video_tensor.size(2)):
frame = video_tensor[j, :, i, :, :]
frame = frame.numpy().transpose((1, 2, 0))
b, g, r = frame[:, :, 0], frame[:, :, 1], frame[:, :, 2]
frame = np.asarray((r, g, b), dtype=np.uint8).transpose((1, 2, 0))
luv = cv2.cvtColor(frame, cv2.COLOR_BGR2LUV)
curr_frame = luv
if curr_frame is not None and prev_frame is not None:
# logic here
diff = cv2.absdiff(curr_frame, prev_frame)
count = np.sum(diff)
frame_diffs.append(count)
frame = Frame(i, frame, count)
frames.append(frame)
prev_frame = curr_frame
i = i + 1
# ret, frame = cap.read()
# cv2.imshow('frame',luv)
# # if cv2.waitKey(1) & 0xFF == ord('q'):
# # break
if USE_TOP_ORDER:
# sort the list in descending order
frames.sort(key=operator.attrgetter("value"), reverse=True)
for keyframe in frames[:NUM_TOP_FRAMES]:
key_list.append(keyframe.id)
curr_frame = None
prev_frame = None
frame_diffs = []
frames = []
return key_list
if __name__ == '__main__':
video = torch.randn(5, 3, 64, 224, 224)
k = key_extraction(video, True, False, False, dir='video_demo', NUM_TOP_FRAMES=1)
print(k) |
59093ce4b4dd8241159405d6a91774a44237d633 | edagotti689/PYTHON-5-FUNCTIONS | /0_function_NOTE.py | 596 | 4.375 | 4 | 1. Using functions we can give a name to the block of code.
2. Using functions we can re use code.
3. Using def we can create a function.
# Use of Parameters
1. Using parameters we can make a function dynamic
2. Using parameters we can pass values to the function
3. Python function support 4 types of parameters
1. Required and positional arguments
2. Keyword arguments
3. Default arguments
4. Variable length arguments
'''
1.What is function:-
A Function is a set of statements that take inputs.
Do some specific computation and produce output.
''' |
fc4f5c9ee03f686683e1785f452554882fb4c33a | shubham18121993/algorithms-specilaization | /3_greedy_algo_and_dp/maximum_weight.py | 800 | 3.609375 | 4 |
def get_max_weight(n, lst):
optimal_solution = [0]
prev = 0
curr = 0
for elem in lst:
optimal_solution.append(max(prev+elem, curr))
prev = curr
curr = optimal_solution[-1]
solution_set = []
val = optimal_solution[-1]
for i in range(n, 0, -1):
if val < optimal_solution[i]:
pass
elif val == optimal_solution[i] and optimal_solution[i] !=optimal_solution[i-1]:
val -= lst[i-1]
solution_set.append(i)
else:
pass
return solution_set
with open("../../dataset/course3/mwis.txt", 'r') as f0:
lines = f0.readlines()
n = int(lines[0].strip())
lst = []
for line in lines[1:]:
lst.append(int(line.strip()))
sol = get_max_weight(n, lst)
print(sol) |
6085ff54033faf5f2dc438aef6f7420116bccb3f | firstknp/FinalProject | /main.py | 4,285 | 3.609375 | 4 | from game1 import *
from game2 import *
from game3 import *
import sys
userlist = []
# class GameStat:
# def __init__(self,game ,win, user_num , userlist):
# self.game = game
# self.win = win
# self.user_num = user_num
# self.userlist = userlist
# def check_game(self):
# if self.game == "blackjack":
# if self.win == "win":
# self.userlist[self.user_num][1][1] += 1
# elif self.game == "hangman":
# if self.win == "win":
# self.userlist[self.user_num][1][1] += 1
class Player:
def __init__(self, user, userlist):
self.user = user
self.userlist = userlist
def check_user(self):
for i in range(len(userlist)):
if self.user == self.userlist[i][0]:
return i
class PlayerHandler:
def __init__(self,user,list1):
self.user = user
self.list1 = list1
def add_user(self):
self.list1.append([ self.user,[0,0],[0,0],[0,0],1000 ])
def show_user(self):
print(f"{self}")
while True:
menu = input("Enter your status (admin/player): ")
if menu == 'admin':
while True:
print("")
print("Select your choice")
choice = int(input("1. Add new player \n2. Show players \n3. Add player's balance \n4. Quit \n"))
if choice == 1:
name = input("Enter player's name: ")
play = PlayerHandler(name, userlist)
play.add_user()
elif choice == 2:
for i in range(len(userlist)):
print(f"{userlist[i][0]}: Balance = {userlist[i][4]}")
print(f"Blackjack: #plays = {userlist[i][1][0]} #wins = {userlist[i][1][1]}")
print(f"ColorLine: #plays = {userlist[i][2][0]} #wins = {userlist[i][2][1]}")
print(f"Hangman: #plays = {userlist[i][3][0]} #wins = {userlist[i][3][1]}")
elif choice == 3:
name = input("Enter player's name: ")
for i in range(len(userlist)):
if name == userlist[i][0]:
bal = int(input("Enter player's added balance: "))
userlist[i][4] += bal
if choice == 4:
back = input("Back to Main ot Quit(M/Q): ")
if back == 'M':
break
elif back == 'Q':
sys.exit
elif menu == 'player':
name = input("Enter your name: ")
play = PlayerHandler(name, userlist)
play.add_user()
while True:
print("")
print("Select your choice")
selection = int(input("1. Play Blackjack \n2. Play Colorline \n3. Play Hangman \n4. See your profile \n5. Stop playing\n"))
print (f"Welcome {name}")
if selection == 1:
game = Rungame()
game.play()
for i in range(len(userlist)):
userlist[i][4] -= 20
# if game.get_win_game1() == "win":
# a = Player(name,userlist)
# GameStat("blackjack","win",a.check_user ,userlist)
elif selection == 2:
start_colorLine(name)
for i in range(len(userlist)):
userlist[i][4] -= 10
# game = ColorLine(board, play ,int(num_col))
# if game.get_win_game2() == "win":
# GameStat("blackjack","win")
elif selection == 3:
game = Game()
game.play()
for i in range(len(userlist)):
userlist[i][4] -= 15
# if game.get_win_game3() == "win":
# a = Player(name,userlist)
# GameStat("hangman","win",a.check_user ,userlist)
elif selection == 4:
for i in range(len(userlist)):
print(f"{userlist[i][0]}: Balance = {userlist[i][4]}")
elif selection == 5:
break
main = input("Back to Main or Quit (M/Q): ")
if main == "Q":
break
f = open('player.txt', 'r')
|
108620ce4fc02ef179f7b500cd2d33f15960c8fb | code1990/bootPython | /python/05Numpy/NumPy011.py | 972 | 3.6875 | 4 | # NumPy 广播(Broadcast)
# 广播(Broadcast)是 numpy 对不同形状(shape)的数组进行数值计算的方式, 对数组的算术运算通常在相应的元素上进行。
# 如果两个数组 a 和 b 形状相同,即满足 a.shape == b.shape,那么 a*b 的结果就是 a 与 b 数组对应位相乘
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
c = a * b
print(c)
# 当运算中的 2 个数组的形状不同时,numpy 将自动触发广播机制。如:
a = np.array([[0, 0, 0],
[10, 10, 10],
[20, 20, 20],
[30, 30, 30]])
b = np.array([1, 2, 3])
print(a + b)
# 4x3 的二维数组与长为 3 的一维数组相加,等效于把数组 b 在二维上重复 4 次再运算:
a = np.array([[ 0, 0, 0],
[10,10,10],
[20,20,20],
[30,30,30]])
b = np.array([1,2,3])
bb = np.tile(b, (4, 1)) # 重复 b 的各个维度
print(a + bb) |
a6d7a616ef82785a4c3d2e94e3c4a21409c4a86c | EpicureanHeron/automatedEmailMessages | /response.py | 4,903 | 4.09375 | 4 | import datetime
def whichToRun():
# prompts the user for what type of email message this is
voucherOrReceipt = raw_input("Is the PO missing a voucher[1], receipt[2], or no receipt AND no voucher [3]? Please enter 1, 2, or 3: ")
# checks the value, and runs the necessary function to generate the message
if voucherOrReceipt == "1":
noVoucher()
elif voucherOrReceipt == "2":
noReceipt()
#if neither 1 or 2 is passed, then exits the program with this message
elif voucherOrReceipt == "3":
noReceiptOrVoucher()
else:
print "Run this file again, you chose wrong! Either enter 1, 2, or 3."
def noVoucher():
#first line plus formatting
firstLine = "Hello," + "\n" + "\n"
#prompts the user for inputs
PONumber = raw_input("PO Number: ")
supplierName = raw_input("Supplier Name: ")
preparersFirstName = raw_input("Preparer's first name: ")
preparersLastName = raw_input("Preparer's last name: ")
receipt = raw_input("Receipt Number: ")
receiptDate = raw_input("Receipt Date: ")
#gets the date
date = str(datetime.datetime.now().date())
#sets the path of the file in the outputFiles folder and adds the appropriate suffix
fileName = "outputFiles/" + preparersLastName + date + "-novoucher" + ".txt"
#opens a file on the specified path with the name
file_1= open(fileName, "w")
#creates the message with the user's inputs
message = "Supplier " + supplierName + " reached out to the EFS helpline today concerning payment from PO " + PONumber + ". The PO sourced from a req created by " + preparersFirstName + " " + preparersLastName + ". It looks like the PO has been received against by " + preparersFirstName + " via receipt " + receipt + " on " + receiptDate + ". " + "\n" + "\n" + "However, no voucher exists on the system as of yet. If you have the invoice still, please send it to your cluster for imaging. Otherwise, if you need the invoice, I have CC'd the supplier on this email so they should be able to facilitate this. Let us know if we can be of any help, "
#writes the message to the folder
file_1.write(firstLine + message)
#closes the folder
file_1.close
#lets the caller know where the file is ready
print "Success! Your file is ready! Just follow the path: " + fileName
def noReceipt():
firstLine = "Hello," + "\n" + "\n"
PONumber = raw_input("PO Number: ")
supplierName = raw_input("Supplier Name: ")
preparersFirstName = raw_input("Preparer's first name: ")
preparersLastName = raw_input("Preparer's last name: ")
voucher = raw_input("Voucher Number: ")
message = "Supplier " + supplierName + " reached out to the EFS helpline today concerning payment from PO " + PONumber + ". The PO sourced from a req created by " + preparersFirstName + " " + preparersLastName + ". There is a voucher created against this PO, voucher " + voucher + "." + "\n" + "\n" + "However, no receipt has been created against the PO. "+ preparersFirstName + ", please go in and receive against the PO. Once a receipt has been created, the system will match the voucher and a payment should go out. If you need an invoice, I recommend you reach out the supplier who is CC'd in this email. Otherwise, if you have questions or concerns about the receiving process, please let us know. Have a great day."
date = str(datetime.datetime.now().date())
fileName = "outputFiles/" + preparersLastName + date + "-noReceipt" ".txt"
file_1= open(fileName, "w")
file_1.write(firstLine + message)
file_1.close()
print "Success! Your file is ready! Just follow the path: " + fileName
def noReceiptOrVoucher():
firstLine = "Hello," + "\n" + "\n"
PONumber = raw_input("PO Number: ")
supplierName = raw_input("Supplier Name: ")
preparersFirstName = raw_input("Preparer's first name: ")
preparersLastName = raw_input("Preparer's last name: ")
message = "A representative from supplier " + supplierName + " contacted the University Financial Helpline inquiring about payment from PO " + PONumber + "." + "\n" + "\n" + "PO " + PONumber +" was created from a requisition that " + preparersFirstName + " " + preparersLastName + " created. There has been no receipt or voucher against this PO yet." + "\n" + "\n" + "I have CC'd the supplier on this email. " + preparersFirstName + ", if you have received the items, but have not created a receipt in EFS yet, please go ahead and do so. Then send the invoice to your cluster for imaging. If you need either the invoice or have a problem with the order, please reach out the supplier." + "\n" + "\n" + "Let us know if our helpline can assist in anyway."
date = str(datetime.datetime.now().date())
fileName = "outputFiles/" + preparersLastName + date + "-noReceiptNovoucher" ".txt"
file_1= open(fileName, "w")
file_1.write(firstLine + message)
file_1.close()
print "Success! Your file is ready! Just follow the path: " + fileName
whichToRun() |
dce6bff9e08f046f22e8cfc3fdf50a98594c9808 | AK-1121/code_extraction | /python/python_23402.py | 185 | 3.53125 | 4 | # Python adding lists of numbers with other lists of numbers
>>> lists = (listOne, listTwo, listThree)
>>> [sum(values) for values in zip(*lists)]
[10, 9, 16, 11, 13]
|
63daeec489cf006865d8f656693ef8a85e718530 | shayandaneshvar/Introduction-To-Computer-Vision-Labs | /cv-lab5/sobel1.py | 1,205 | 3.75 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
I = cv2.imread("agha-bozorg.jpg", cv2.IMREAD_GRAYSCALE)
# Compute the gradient in x direction using the sobel filter
# Method 1: using filter2D **********
Dx = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]]) # Sobel filter
Ix = cv2.filter2D(I, -1, Dx)
print(I.dtype)
print(Ix.dtype)
Ix = cv2.filter2D(I, cv2.CV_16S, Dx) # cv2.CV_16S: 16 bit signed integer
# print(Ix.dtype)
input('press ENTER to continue... ')
# Method 2: using sobel function **********
Ix2 = cv2.Sobel(I, cv2.CV_16S, 1, 0)
print(np.abs(Ix - Ix2).max())
input('press ENTER to continue... ')
# Plot the gradient image
f, axes = plt.subplots(2, 2)
axes[0, 0].imshow(I, cmap='gray')
axes[0, 0].set_title("Original Image")
axes[0, 1].imshow(Ix, cmap='gray')
axes[0, 1].set_title("Ix (cv2.filter2D)")
axes[1, 0].imshow(Ix2, cmap='gray')
axes[1, 0].set_title("Ix2 (cv2.Sobel)")
axes[1, 1].imshow(np.abs(Ix), cmap='gray')
axes[1, 1].set_title("abs(Ix)")
# Notice that imshow in matplotlib considers the minimums value of I
# as black and the maximum value as white (this is different from
# the behaviour in cv2.imshow
plt.show()
|
0534ec08872413fb1674286b885c8099e478648c | rishabhCMS/IIPP_mini-projects | /Guess_the_number_game.py | 2,919 | 4.03125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
count = 0
trial = 0
secret_number = 0
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number, count, trial
count = math.ceil(math.log(100 - 0 + 1)/math.log(2))
trial = math.ceil(math.log(100 - 0 + 1)/math.log(2))
secret_number = random.randrange(0, 100)
print("\n ----Starting new game-----")
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
new_game()
global secret_number, count, trial
count = math.ceil(math.log(100 - 0 + 1)/math.log(2))
trail = math.ceil(math.log(100 - 0 + 1)/math.log(2))
secret_number = random.randrange(0, 100)
print("----starting game with a new guess range [0,100)-----trials left = ", trial, "\n")
print("intializing new secret number b/w [0, 100) for you to guess \n")
def range1000():
# button that changes the range to [0,1000) and starts a new game
new_game()
global secret_number, count, trial
count = math.ceil(math.log(1000 - 0 + 1)/math.log(2))
trial = math.ceil(math.log(1000 - 0 + 1)/math.log(2))
secret_number = random.randrange(0, 1000)
print("----starting game with a new guess range [0,1000)-----trials left = ", trial, "\n")
print("intializing new secret number b/w [0, 1000) for you to guess \n")
def input_guess(guess):
# main game logic goes here
global trial
trial = trial - 1
print("trials left ", trial)
guess = int(guess)
print("Guess was: ", guess)
if guess < secret_number and trial != 0:
print("Guess something higher")
elif guess > secret_number and trial != 0:
print("Guess something lower")
elif trial == 0:
print("you lost, trials over!")
if count == 7:
range100()
else:
range1000()
elif guess == secret_number:
print("correct guess!")
print("the secret number was :", secret_number)
if count == 7:
range100()
else:
range1000()
# create frame
frame = simplegui.create_frame("guess the number", 300, 300)
# register event handlers for control elements and start frame
frame.add_input("enter your guess", input_guess, 200)
frame.add_button("Restart game!", new_game, 200)
frame.add_button("Range is [0, 100)", range100, 200)
frame.add_button("Range is [0, 1000)", range1000, 200)
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
|
55f84f2c087886d891db3e2b42b93d2dcf4cd2ef | k0syam/workshop01 | /dai13shou/code13-7.py | 385 | 3.625 | 4 | #dfsによる根無し木の走査
from collections import deque
n=5
graph=[[] for _ in range(n)]
edges=[[0,1],[1,2],[1,4],[3,4],[3,0]]
for i in range(len(edges)):
a,b=edges[i][0],edges[i][1]
graph[a].append(b)
graph[b].append(a)
def dfs(v,p=-1):#v:頂点、p:vの親
for c in graph[v]:
if c==p:#親への逆流を防ぐ
continue
dfs(c,v)
|
9eba37b423e09906a92fe117ed5b67c785da26de | jeancre11/PYTHON-2020 | /CLASE3/codigo7.py | 290 | 3.515625 | 4 | """LINSPACE"""
def linspace(to, tf, N):
razon=(tf-to)/N
#primera forma
lv=[]
for val in range(N):
lv.append(to+val*razon)
lv.append(tf)
return lv
#creando una lista desde el valor to hasta tf con N valores
#linspace(to, tf, N)
l1=linspace(0, 20, 4)
print(l1) |
3e1c1b714db2362118ba26b7ef0f1725bf4397e3 | RodMdS/Redes_de_Computadores | /Calculadora_UDP_V2/server/operations.py | 1,042 | 3.609375 | 4 | def add(op1, op2):
try:
return float(op1) + float(op2)
except ValueError:
return "Error: the message isn't correct"
def sub(op1, op2):
try:
return float(op1) - float(op2)
except ValueError:
return "Error: the message isn't correct"
def mpy(op1, op2):
try:
return float(op1) * float(op2)
except ValueError:
return "Error: the message isn't correct"
def div(op1, op2):
try:
return float(op1) / float(op2)
except ValueError:
return "Error: the message isn't correct"
except ZeroDivisionError:
return "Error: division by zero"
def pot(op, exp):
try:
return float(op) ** float(exp)
except ValueError:
return "Error: the message isn't correct"
def sqrt(op):
try:
return float(op) ** (0.5)
except ValueError:
return "Error: the message isn't correct"
def mod(op1, op2):
try:
return int(op1) % int(op2)
except ValueError:
return "Error: the message isn't correct"
|
35a59340498cb189cb0c73227ca982a67269c4d7 | esineokov/ml | /lesson/1/exercise/6.py | 216 | 4 | 4 | a = float(input("Enter start: "))
b = float(input("Enter finish: "))
day = 1
current = a
while current < b:
day += 1
current = current + current*0.1
print(f"You will reach the result on the {day}th day")
|
64aca9510f99b2371e5e2fa541d16688c0bbe469 | xmtsui/python-workspace | /data_process/csv/csv.py | 1,056 | 3.828125 | 4 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: csv
# Purpose: read and write csv files
# Author: tsui
# Created: 9 Apr, 2013
# Copyright: ©tsui 2013
# Licence: GPL v2
#-------------------------------------------------------------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename:file_cut.py
path = raw_input('please enter the file path:')
savepath = raw_input('please enter the save path:(not include the last \'\\\')')
newname = raw_input('please enter the new name:')
fr = file(path,'r')
flag = True
i = 0 #记录数
c = 1 #分割文件
while flag:
line = fr.readline()
i+=1
if i < 2000: #分割200000行
print i
save =savepath +'\\'+ newname + str(c) + ".csv"
file(save,'a').write(line)
else:
i = 0 #记录数清零
c+=1 #文件名+1
continue #继续循环
if len(line) == 0:
flag = False
# if c == 5:
# flag = False
fr.close()
|
77f31d9b29670e12bddc869f4ed80c340333cd52 | MathewTheProgrammer/CLI | /main.py | 3,546 | 3.703125 | 4 | import os
import sys
import datetime
import calendar
import colorama
from colorama import Fore
colorama.init()
print(Fore.RESET + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
# COMMANDS
command = input('Please enter a command:')
while True:
if command == "Help" or command == "help":
print('Commands: help\n'
' hello\n'
' clear\n'
' calculator\n'
' date\n'
' color\n'
' calendar\n'
' echo\n'
' exit')
command = input('Please enter a command:')
if command == "Hello" or command == "hello":
print('Hello!')
command = input('Please enter a command:')
if command == "Clear" or command == "clear":
os.system('cls')
print("Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
command = input('Please enter a command:')
if command == 'Calculator' or command == 'calculator':
num1 = float(input("Enter the first number:"))
num2 = float(input("Enter the second number:"))
op = input("What would you like to do(+ , - , * , / ):")
if op == "+":
sum_ = num1 + num2
print(sum_)
if op == "-":
sum_ = num1 - num2
print(sum_)
if op == "*":
sum_ = num1 * num2
print(sum_)
if op == "/":
sum_ = num1 / num2
print(sum_)
command = input('Please enter a command:')
if command == 'date' or command == 'Date':
now = datetime.datetime.now()
print("The current date and time is:")
print(now.strftime("%y-%m-%d %H:%M:%S"))
command = input('Please enter a command:')
if command == 'color' or command == 'Color':
print("Available colors are : BLUE , CYAN , RED , GREEN and GREY")
color = str(input("What color would you like:"))
if color == "BLUE":
os.system('cls')
print(Fore.BLUE + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
if color == "CYAN":
os.system('cls')
print(Fore.CYAN + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
if color == "RED":
os.system('cls')
print(Fore.RED + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
if color == "GREEN":
os.system('cls')
print(Fore.GREEN + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
if color == "GRAY":
os.system('cls')
print(Fore.RESET + "Welcome to the RandomCLI")
print("Author : MathewTheProgrammer \n")
command = input("Please enter a command:")
if command == "calendar" or command == "Calendar":
year = int(input('What year:'))
month = int(input('What month(1,2,3,4,5,6,7,8,9,10,11,12):'))
mycal = calendar.month(year, month)
print(mycal)
command = input("Please enter a command:")
if command == "echo" or command == "Echo":
echo = input("echo:")
print(echo)
command = input("Please enter a command:")
if command == 'exit' or command == 'Exit':
sys.exit(0)
|
00d7bf36b8369a60a5ed8dcecc1005e4ab6d1f2c | tks2103/python-coding-interview | /3_chapter/stack.py | 814 | 4.0625 | 4 | class Node(object):
def __init__(self, data):
self.next = None
self.data = data
class Stack(object):
def __init__(self):
self.top = None
self.size = 0
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
self.size += 1
def pop(self):
if(self.top != None):
item = self.top.data
self.top = self.top.next
self.size -= 1
return item
return None
def peek(self):
if not self.top:
raise Exception('Empty Stack')
return self.top.data
if __name__ == '__main__':
stack = Stack()
stack.push(3)
stack.push(2)
assert(stack.top.data == 2)
assert(stack.top.next.data == 3)
assert(stack.pop() == 2)
assert(stack.peek() == 3)
assert(stack.pop() == 3)
#stack.peek()
assert(stack.pop() == None)
|
09b785c7e51006b2aa34194879f7b751825af793 | Alejandra2254/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 257 | 3.5625 | 4 | #!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary == {} or a_dictionary is None:
return None
m = sorted(a_dictionary.values())
max = m[-1]
for i in a_dictionary:
if max == a_dictionary[i]:
return i
|
e1e9d30819fe47b8aa749dd324a67df4de94b8aa | PrivateVictory/Leetcode | /src/ziyi/Array/MaximumProductSubarray.py | 666 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-15 09:47:27
# @Author : Alex Tang (1174779123@qq.com)
# @Link : http://t1174779123.iteye.com
'''
description:
'''
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
p_max, n_max = 1, 1
result = nums[0]
for num in nums:
if num < 0:
p_max, n_max = n_max, p_max
p_max = max(p_max * num, num)
n_max = min(n_max * num, num)
result = max(result, p_max)
return result
def main():
s = Solution()
print s.maxProduct([2,3,-2,4])
if __name__ == '__main__':
main()
|
1aff6f75ef1eca9e63961e08d88f8c80458d6f76 | JonhFiv5/aulas_python | /aula_28_desafio_contadores.py | 319 | 3.84375 | 4 | # Criar dois contadores dentro do mesmo laço
# Uma vai de 0 a 8 e o outro de 10 a 2
for progressivo, regressivo in enumerate(range(10, 1, -1)):
print(progressivo, regressivo)
# regressivo vai guardar o valor devolvido pela função range
# progressivo vai guardar o valor de enumerate, o número de iterações
|
e25505b3253f112e8a186e16f19fe3ac1d28ae20 | CosmicTomato/ProjectEuler | /diophantine_min.py | 1,680 | 3.59375 | 4 | #designed for help on project euler problem 66:
#Consider quadratic Diophantine equations of the form:
#x^2 – Dy^2 = 1
#For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
#It can be assumed that there are no solutions in positive integers when D is square.
#By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the following:
#3^2 – 2×2^2 = 1...
#9^2 – 5×4^2 = 1...
#Hence, by considering minimal solutions in x for D ≤ 7, the largest x is obtained when D=5.
#Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
def main(d):
#finds min x for which x^2-d*y^2=1
if d ** 0.5 == int (d ** 0.5):
return 0
#returns 0 if d is square
x = 2
left_side = (x ** 2) - 1
#initializing variables
#want x^2-1 = d*(y^2)
y_floor = int ( int((left_side) / d) ** 0.5 ) - 1
#if solution exists, there should be a y that satisfies y^2 = x^2 - 1
y_mid = y_floor + 1
y_cap = y_floor + 2
right_side_floor = (d * y_floor ** 2)
right_side_mid = (d * y_mid ** 2)
right_side_cap = (d * y_cap ** 2)
check = 0
#switches when solution found
while check == 0 and x < 10 ** 7:
#searches until solution is found, put arbitrary cap so it doesn't hang forever
if left_side == right_side_floor or left_side == right_side_mid or left_side == right_side_cap:
check = 1
else:
x += 1
left_side = (x ** 2) - 1
y_floor = int ( int((left_side) / d) ** 0.5) - 1
y_mid = y_floor + 1
y_cap = y_floor + 2
right_side_floor = (d * y_floor ** 2)
right_side_mid = (d * y_mid ** 2)
right_side_cap = (d * y_cap ** 2)
#increments x and relcalcs values
return x
|
16ba2e84b59d5c324e95f6980e6a8b5b907b8956 | RohitUttam/ProjectEuler | /7-10001st prime number.py | 310 | 3.84375 | 4 |
'''listprime=[]
for num in range(3,1000000,2):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
listprime.append(num)
if len(listprime)==10002:
break
print(listprime[10001])'''
skip=[]
l=range(3,1000,3)
skip.extend(l)
print(18 in skip) |
ff931194f658c93d1a70d2167941cc81b2f07cad | m4mayank/ComplexAlgos | /square_root_of_integer.py | 776 | 4.3125 | 4 | #!/usr/local/bin/python3.7
#Given an integar A.
#
#Compute and return the square root of A.
#
#If A is not a perfect square, return floor(sqrt(A)).
#
#DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY
#
#For Example:
# Input 1:
# A = 11
# Output 1:
# 3
#
# Input 2:
# A = 9
# Output 2:
# 3
def sqrt(A):
def iterativeSqrt(l, h, val):
low = l
high = h
mid = low + ((high-low)//2)
if low > high:
return high
if (mid)**2 > val:
return iterativeSqrt(low, mid-1, val)
if (mid)**2 < val:
return iterativeSqrt(mid+1, high, val)
if (mid)**2 == val:
return mid
b = iterativeSqrt(0, A, A)
return b
print(f"Answer : {sqrt(20)}")
|
1972c072e4bf29edf5d776aa43378dd4cc251c30 | sameertulshyan/python-projects | /NYC_job_listings/NYC_data_scrubbing.py | 4,935 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 17:17:04 2018
Data taken from: https://data.cityofnewyork.us/City-Government/NYC-Jobs/kpav-sd4t/data
@author: sameertulshyan
This program allows the user to extract a list of government jobs in NYC that meet their criteria for salary/work-type/payment schedule etc.
It also cleans the datafile.
"""
import csv
filename = "NYC_Jobs.csv" # name of the input file
try: # try to open the file
f = open(filename)
input_file = csv.reader(f) # use the csv module to read the file
except FileNotFoundError: # file could not be found
print("The input file could not be found. Please ensure that 'NYC_Jobs.csv' is \
placed in the same folder as this program file") # let the user know that we failed to find the file
else:
output_file = open("NYC_Jobs_scrubbed.csv", "w") # open an output file in write mode
output_writer = csv.writer(output_file, delimiter=",") # use the csv module to write to the file
while True: # ask the user whether they want to include the header
header_required = input("Do you want to include a header row? (Y/N) ")
if header_required.lower() not in ('y','n'): # validate their input
print("\nPlease enter a valid response (Y/N)") # let them know their response was invalid and continue to ask them
else: # if the user has entered a valid response
break # break out of the input validation loop and continue with the program
while True: # ask the user whether they would like to be paid hourly or annually or daily
payment_schedule = input("Would you like to be paid on an Hourly, Daily or Annual basis? ")
if payment_schedule not in ['Hourly','Annual','Daily']: # validate their input
print("\nPlease enter a valid response (Hourly/Annual/Daily)") # let them know their response was invalid and continue to ask them
else: # if the user has entered a valid response
break # break out of the input validation loop and continue with the program
while True: # get the user's desired minimum salary for processing
user_minimum = input("What is your minimum salary requirement? $")
if not user_minimum.isnumeric(): # ensure that they enter a number
print("You must enter a number for salary.")
elif int(user_minimum) < 0: # ensure the number is positive
print("You cannot have a negative salary.")
else:
user_minimum = int(user_minimum) # cast the input into an int for processing
break # break out of the input validation loop and continue with the program
while True: # ask the user whether they are interested in working full or part-time
work_type = input("Do you want to work (F)ull or (P)art time? (F/P) ")
if work_type not in ('F','P'): # validate their input
print("\nPlease enter a valid response (F/P)") # let them know their response was invalid and continue to ask them
else: # if the user has entered a valid response
break # break out of the input validation loop and continue with the program
lines_written = 0 # simple counter to keep track of how many entries are produced
for line in input_file:
# handle the line containing the header
if line[0] == "Job ID":
if header_required.lower() == "n":
continue
else:
# get rid of unnecessary columns
line.pop(6)
line.pop(6)
line.pop(7)
line.pop(9)
for i in range(4):
line.pop(-1)
output_writer.writerow(line) # write the header to the output file
continue
# exclude jobs that have a different payment schedule
if line[12] != payment_schedule:
continue
# get the minimum salary for this job
minimum_salary = float(line[10])
# if the salary is less than the user's desired salary, we exclude it
if minimum_salary < user_minimum:
continue
# if the work-type does not match the user's desired work type, we exclude it
if line[9] != work_type:
continue
# get rid of unnecessary columns
line.pop(6)
line.pop(6)
line.pop(7)
line.pop(9)
for i in range(4):
line.pop(-1)
# since this line meets our criteria, write it to the output file
output_writer.writerow(line)
# increment the counter
lines_written += 1
# close the input and output files
f.close()
output_file.close()
# print the number of lines written to the console
print(str(lines_written) + " lines written")
|
8bdff3cfd4fd6c41af4e187bfb0bab7d66d880fc | hsnylmzz/Python-Learning | /pytprojects/ciro.py | 1,406 | 3.546875 | 4 | def calculateCiro(sell_amount, sell_value):
return sell_amount-sell_value
def writeCiro(name, ciro):
try:
with open("ciro.txt","r+") as ciroText:
allData = ciroText.readlines()
already = False
for i in allData:
if i.startswith(name):
allData[allData.index(i)] = name + " " + str(round(ciro, 2)) + "\n"
already = True
break
if not already:
allData.append(name + " " + str(round(ciro, 2)) + "\n")
ciroText.seek(0)
ciroText.writelines(allData)
except Exception:
with open("ciro.txt","r+") as ciroText:
ciroText.write(name + " " + str(round(ciro, 2)) + "\n")
def getCiro(name):
try:
with open("ciro.txt","r") as ciroText:
allData = ciroText.readlines()
for i in allData:
if i.startswith(name):
product = list(i.split())
return float(product[1])
return 0
except Exception as e:
return 0
def printCiro():
try:
with open("ciro.txt","r") as ciroText:
allData = ciroText.readlines()
for i in allData:
if i.startswith(name):
print(i[:-1])
except Exception:
print("Orada ciro verisi yok.")
|
aa987b5b2d13224ea9472f8c8f9061d5401dea87 | sagelga/prepro59-python | /139_LetsFreshIt.py | 485 | 4.03125 | 4 | """This program will ask input then, run the program, later then print out the results"""
def major_branch():
"""This is the main fuction. It will do everything."""
message = input()
count = 0
message.split(" ")
sorted(message)
print(message)
while message[0] != 1:
sorted(message)
for i in range(1, 3):
message[i] = int(message[i]) - 1
print(message)
count += 1
print(message)
major_branch()
|
791df87235f5da634fc62ebc3a3741cea6e2deca | AlbertRessler/itam_python_courses | /homeworks/chapter_2/task_2_1_2.py | 574 | 3.65625 | 4 | def summation(numbers):
positive_numbers = []
normalized_numbers = []
numbers_list = numbers.split()
for idx, arg in enumerate(numbers_list):
int_arg = int(arg)
if int_arg < 0:
new_arg = abs(int_arg) * 2
else:
new_arg = int_arg
positive_numbers.append(new_arg)
max_of_positive_numbers = max(positive_numbers)
for idx, arg in enumerate(positive_numbers):
normalized_arg = arg / max_of_positive_numbers
normalized_numbers.append(normalized_arg)
print(sum(normalized_numbers))
|
309e92f27b2c08d8433115c7eb705a0114966a8d | MiniMidgetMichael/Old-HS-shit | /turtle_test.py | 1,548 | 3.53125 | 4 | #! C:/Users/MichaelLFarwell/AppData/Local/Programs/Python/Python35-32/python.exe
#! C:UsersMichaelLFarwellAppDataLocalProgramsPythonPython35-32python.exe
import turtle
import sys
import os
"""TO REFERENCE TURTLE OBJECTS: 'turtle.module.object'
EX.
print (turtle.math.pi)
>>> 3.14159265
"""
my_turtle = turtle.Turtle()
screen = turtle.Screen()
methods = ["tri", "spiral", "tri_circle"]
def tri():
my_turtle.begin_poly()
for i in range(3):
my_turtle.fd(60)
my_turtle.rt(120)
screen.reset()
my_turtle.end_poly()
def spiral(x, y):
my_turtle.reset()
deg = 90
move = 0.5
for i in range(90):
my_turtle.fd(move)
my_turtle.right(deg)
deg -= 1
move += 0.5
my_turtle.reset()
my_turtle.onclick(spiral)
def tri_circle():
my_turtle.reset()
ghost = turtle.getturtle()
ghost.hideturtle()
ghost.pu()
ghost.begin_fill()
colors = ["red", "green", "blue"]
c_place = 0
for i in range(3):
ghost.fd(60)
my_turtle.fd(60)
my_turtle.begin_fill()
my_turtle.fillcolor(colors[c_place])
my_turtle.circle(10, 360)
my_turtle.end_fill()
c_place += 1
my_turtle.rt(120)
ghost.rt(120)
ghost.end_fill()
my_turtle.hideturtle()
full_reset()
def run():
screen.onkeypress(tri_circle, "a")
screen.listen()
screen.onkeypress(quit, "Escape")
my_turtle.onclick(spiral)
screen.onkeypress(tri, "t")
print (__name__)
if __name__ == "__main__":
run()
|
22ff3d19c404883f438e7c27567fda3e2f2fd8c6 | Yuki-Sakaguchi/python_study | /challenge/part4.py | 842 | 4.21875 | 4 | # 文字列
kamyu = "カミュ"
print(kamyu[0])
print(kamyu[1])
print(kamyu[2])
nani = input('何を書いた?')
dare = input('誰に書いた?')
print("私は昨日、{}を書いて{}に送った".format(nani, dare))
print('aldous Huxley was born in 1894.'.capitalize())
print("だれが? いつ? どこで?".split(' '))
text_list = ['The', 'fox', 'jumped', 'over', 'the', 'fence', '.']
print(' '.join(text_list).replace(' .', '.'))
print('A screaming comes across the sky.'.replace('s', '$'))
print('Hemingway'.index('m'))
# hemingway = 'Hemingwaymmmm'
# for i in range(len(hemingway)):
# if hemingway[i] == 'm':
# print(i)
print("It's demo.")
print('It\'s demo.')
print("three"+"three"+"three")
print("three"*3)
print("四月の晴れた寒い日で、時計がどれも13時を打っていた。".split('、')[0]) |
c715f17e47139246f06b7fbf916c017eb0f87cd5 | af-orozcog/Python3Programming | /Python functions,files and dictionaries/assesment3_5.py | 353 | 3.734375 | 4 | """
Create a dictionary called wrd_d
from the string sent, so that the key is a word and the value is how many times you have seen that word.
"""
sent = "Singing in the rain and playing in the rain are two entirely different situations but both can be good"
words = sent.split()
wrd_d = {}
for word in words:
wrd_d[word] = wrd_d.get(word,0) + 1 |
02d46ae3a4107955c75ff34831295a5e3eee878d | NegiArvind/NeroFuzzyTechniques-Lab-Program | /applyingFilter.py | 1,261 | 3.640625 | 4 | import numpy as np
from PIL import Image
img=Image.open("emma.jpg") #used to open the image
img=np.array(img) # it converts image into numpy array
img.transpose(2,0,1).reshape(3,-1); # converting 3d numpy array into 2d numpy array
img.resize(500,500); # Resizing the given image into 500*500
img=np.insert(img,0,0,axis=1) # adding 1d array of zeroes on first column
img=np.insert(img,0,0,axis=0) # adding 1d array of zeroes on first row
img=np.insert(img,img.shape[1],0,axis=1) # adding 1d array of zeroes on last column
img=np.insert(img,img.shape[0],0,axis=0) # adding 1d array of zeroes on last row
print(img)
Image.fromarray(img).show()
rows=img.shape[0]; # number of rows in matrix
columns=img.shape[1]; # number of column in matrix
print(rows)
print(columns)
myFilter=[[1,1,1],[1,1,1],[1,1,1]] # filters of 3*3 matrix
newImage=[]
for i in range(rows-2):
newList=[]
for j in range(columns-2):
sum1=0
for k in range(3):
for m in range(3):
sum1+=img[i+k,j+m]*myFilter[k][m]
newList.append(int(sum1/9));
newImage.append(newList);
newImage=np.array(newImage)
print(newImage.shape[0])
print(newImage.shape[1])
print(newImage)
filteredImage=Image.fromarray(newImage,'RGB')
filteredImage.save("filteredImageTiger.jpg")
filteredImage.show();
|
d8948abd484ce27096f5ddadc06324ded8251b5a | Ironside-github/python-tutorials | /chapter 5 dictionary&Sets/Setsexample.py | 1,497 | 4.65625 | 5 | #Use of Set along with example
# Set is a collection of non repititive elements./Unordered and unindex/ Bo way to change items in sets/can't contain duplicate values
#defining a set-----first way
a={1,2,3,4,1}
print(type(a))
#defining a set -----second way
b=()
print(type(b)) #Here the type is tupple
c= set()
print(type(c)) #Here the type is set
#Adding data to the set manually
c.add(2)
c.add(1)
c.add(1)
c.add(4)
c.add(5)
c.add(6)
print(c) # Here we can see that any repetion of values ignored by the set
#We can't add dictionaries and list into the set,,,,,,lets try-----because dictionary and lists are not hashable means items can be changed
#c. add({4:5})
#We can add tupple to SET because it is also hashable ie can't contain repetitive elements
c. add((6,8,9,0,1,2,3,4))
print(c)
# Functions which can be performed in SETS
#FUN1. Len()------print the length of a SET
print(len(a))
print(len(c))
#FUN2 remove()-----to remove a value from the set
a.remove(1)
print(a)
a. add(1)
print(a)
#a.remove(15)--------throw an error for every value enered which is not present in the set.
#FUN3 pop()-----removing one element from the set starting from first element
print(a)
a.pop()
print(a)
#FUN4 clear()-------clear whole set ie delete all elements from the set
a. add(1)
#FUN5 Union()--------return all the values of two sets between which union function is used.
print(a.union({9,11}))
#FUN6 intersection()-----return common values in between sets
print(a.intersection({3,4}))
|
de1af259934d2a2d41e456b9a5472fad9d9c17a9 | kingssafy/til | /ps/swea/calculator3.py | 1,122 | 3.515625 | 4 | import sys
sys.stdin = open("calculator3.txt")
priorities = {"+":0, "*":1, "(":-1}
for tc in range(1, 11):
a = input()
given = input()
nums = []
operators = []
stack = []
#convert
for char in given:
if char in '0123456789':
nums.append(char)
elif char == '(':
operators.append(char)
elif char == ')':
while operators and operators[-1] != '(':
nums.append(operators.pop())
operators.pop()
elif operators and priorities[char] <= priorities[operators[-1]]:
while operators and priorities[char] <= priorities[operators[-1]]:
nums.append(operators.pop())
operators.append(char)
else:
operators.append(char)
while operators:
nums.append(operators.pop())
for token in nums:
if token == '+':
stack[-2] += stack[-1]
stack.pop()
elif token == '*':
stack[-2] *= stack[-1]
stack.pop()
else:
stack.append(int(token))
print(f"#{tc} {stack[0]}")
|
ed80018b52ff6041bce5f155a79eafd9851b8f51 | jaycody/mypy | /hardwaypy/ex8.py | 1,249 | 4.34375 | 4 | # Printing Printing
# create variable and assign it a format string composed of only format characters
formatter = "%r %r %r %r"
# print the format string and use a list of ints to inform the format variables
print formatter % (1, 2, 3, 4)
# print the format string and use a list of strings to inform the format variables
print formatter % ("one", "two", "three", "four")
# print the format string and use a list of BOOLEANS to inform the format variables
print formatter % (True, False, False, True)
# print the format string and use a list of VARIABLES to inform the format variables
print formatter % (formatter, formatter, formatter, formatter)
# print the format string and use a list of strings to inform the format variables
# use line breaks at the commas to adhere to the 80 character width 'best practice' of python
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing",
"So I said goodnight."
)
'''
the output of the last print command contains strings with double and single quotes
even thought all the strings in the list used to inform the format variables
are all double quoted. Why?
b/c double quotes are used in the string that contains a single quote used an apostrophe.
'''
|
01c097d17e5ef6c5e08cdc0279be37110f95bd38 | ohjerm/sudoku-solver | /py-sudoku.py | 10,622 | 3.984375 | 4 | import random
import numpy as np
def read_puzzle(in_line):
"""
reads a sudoku puzzle from a single input line
:param in_line: 9 space-separated 9-digit numbers ranging from 0-9
:return: returns the numbers in a numpy array
"""
arr = np.zeros((9,9), dtype=int)
for i, line in enumerate(in_line.split(' ')):
for j, num in enumerate(list(line)):
arr[i, j] = num
return arr
def test_fit(x, y, n, board_state):
"""
tests whether n can be placed in x,y on the current board_state
:param x: horizontal position on the board
:param y: vertical position on the board
:param n: the number to place
:param board_state: the current board state as a numpy array
:return: true if nothing would stop n from being placed in x,y on board_state, else returns false
"""
# first test if something is already in that position
if board_state[x, y] != 0:
return False
# then test if n already exists in that column or row
for i in range(9):
if board_state[x, i] == n:
return False
elif board_state[i, y] == n:
return False
# finally test if it fits in the block
x_block = 0
y_block = 0
if x < 3:
x_block = 0
elif x < 6:
x_block = 1
else:
x_block = 2
if y < 3:
y_block = 0
elif y < 6:
y_block = 1
else:
y_block = 2
for i in range(x_block * 3, x_block * 3 + 3):
for j in range(y_block * 3, y_block * 3 + 3):
if board_state[i, j] == n:
return False
return True
def generate_puzzle(difficulty='easy'):
"""
creates a sudoku puzzle
:param difficulty: easy, medium, hard, impossible accepted
:return: a 9x9 numpy array of valid sudoku
"""
num_clues = 0
# define a random-ish amount of clues based on the difficulty
if difficulty == 'easy':
for i in range(9):
num_clues += random.randint(3,5)
elif difficulty == 'medium':
for i in range(9):
num_clues += random.randint(2,4)
elif difficulty == 'hard':
for i in range(9):
num_clues += random.randint(1,3)
elif difficulty == 'impossible':
for i in range(9):
num_clues += random.randint(0,2)
# create the playboard, or puzzle
playboard = np.zeros((9,9), dtype=int)
# always make sure a number can be placed on the board
while num_clues > 0:
x = random.randint(0, 8)
y = random.randint(0, 8)
n = random.randint(1, 9)
if test_fit(x, y, n, playboard):
playboard[x, y] = n
num_clues -= 1
return playboard
def narrow_solutions(x, y, board_state):
"""
tests all numbers 1-9 whether they could fit in spot x,y on the current board
:param x: horizontal position
:param y: vertical position
:param board_state: current board as a 9x9 valid sudoku puzzle
:return: returns a numpy array of bools indicating whether that index(+1) would fit in x,y
"""
solutions = np.array([True, True, True, True, True, True, True, True, True])
for i in range(1, 10): # numbers from 1 to 9
# test for vertical and horizontal
for j in range(9):
if board_state[x, j] == i:
solutions[i - 1] = False
break
elif board_state[j, y] == i:
solutions[i - 1] = False
break
# finally test if it exists in the block
x_block = 0
y_block = 0
if x < 3:
x_block = 0
elif x < 6:
x_block = 1
else:
x_block = 2
if y < 3:
y_block = 0
elif y < 6:
y_block = 1
else:
y_block = 2
for j in range(x_block * 3, x_block * 3 + 3):
for k in range(y_block * 3, y_block * 3 + 3):
if board_state[j, k] == i:
solutions[i - 1] = False
return solutions
def catch_error(list_like):
"""
if none of the options are true, something has gone wrong
:param list_like: a list_like of bools
:return: true if at least one is true, else returns false
"""
for b in list_like:
if b:
return True
return False
def single_option(list_like):
"""
checks if a single option is true
:param list_like: a list-like of bools
:return: true if exactly 1 is true, else returns false
"""
trues = 0
num = 0
for i, b in enumerate(list_like):
if b:
trues += 1
num = i + 1
if trues > 1:
return 0
return num
def iterate_through_block(n, x, y, state, solution_state):
"""
goes through a 3x3 block to check for n
:param n:
:param x:
:param y:
:param state:
:param solution_state:
:return:
"""
num_n = 0
pos = (0, 0)
# go though each position in the block looking for n
for i in range(x * 3, x * 3 + 3):
for j in range(y * 3, y * 3 + 3):
if state[i, j] == n + 1:
return 0, (0, 0) # break all the way out of the block because the number already exists here
if state[i, j] != 0: # make sure nothing is here already
continue
# this position is valid, check if it can be n
if solution_state[i, j, n]:
num_n += 1
pos = (i, j)
return num_n, pos
def check_area(current_state, current_solution_state):
# first check for rows where only one box can have a number (n)
for n in range(9): # current number we are working with (to access in current_solution_state)
for i in range(9): # current row we are in
num_n = 0
pos = (0, 0)
for j in range(9): # current index in the row
if current_state[i, j] == n + 1:
break # break all the way out of the row because the number already exists here
if current_state[i, j] != 0: # make sure nothing is here already
continue
# this position is valid, check if it can be n
if current_solution_state[i, j, n]:
num_n += 1
pos = (i, j)
# now we are done with that row, so check if there was one single solution
if num_n == 1:
current_state[pos[0], pos[1]] = n + 1 # if one solution existed, the state is updated and we return
return current_state
# then do the same with columns
for n in range(9): # current number we are working with (to access in current_solution_state)
for i in range(9): # current column we are in
num_n = 0
pos = (0, 0)
for j in range(9): # current index in the row
if current_state[j, i] == n + 1:
break # break all the way out of the row because the number already exists here
if current_state[j, i] != 0: # make sure nothing is here already
continue
# this position is valid, check if it can be n
if current_solution_state[j, i, n]:
num_n += 1
pos = (j, i)
# now we are done with that row, so check if there was one single solution
if num_n == 1:
current_state[pos[0], pos[1]] = n + 1 # if one solution existed, the state is updated and we return
return current_state
# finally, check the blocks
# this can be done by just iterating through them
for n in range(9): # the number we are looking for
for x in range(3): # the horizontal block from 0 to 2
for y in range(3): # the vertical block from 0 to 2
num_n, pos = iterate_through_block(n, x, y, current_state, current_solution_state)
if num_n == 1: # there was exactly one square that could be n
current_state[pos[0], pos[1]] = n + 1
return current_state
return current_state # that was a fluke (but it should have worked)
def sudoku_is_complete(state):
for i in range(9):
for j in range(9):
if(state[i,j] == 0):
return False
return True
def solver(puzzle_input):
puzzle_is_solved = False
# create a board of possible solutions of each unsolved square
solutions_board = np.zeros((9,9,9))
for i in range(9):
for j in range(9):
if puzzle_input[i, j] == 0:
solutions_board[i, j] = np.array([True, True, True, True, True, True, True, True, True])
num_iterations = 0
# iterate through these until the puzzle is solved
while not puzzle_is_solved:
did_something = False
for i in range(9):
for j in range(9):
if puzzle_input[i, j] != 0:
continue
# first, narrow down options in that spot based on row, column and block
solutions_board[i, j] = narrow_solutions(i, j, puzzle_input)
# check for errors first
if not catch_error(solutions_board[i, j]):
print("There was an unsolvable error at", i, j)
puzzle_input[i, j] = 69
return puzzle_input
# now check if this position only has one option
single_solution = single_option(solutions_board[i, j])
if single_solution > 0:
puzzle_input[i, j] = single_solution
did_something = True
if not did_something: # only check areas if nothing happened last iteration since it is unnecessary,
# resource intensive, and might break something by using outdated possibilities
puzzle_input = check_area(puzzle, solutions_board)
num_iterations += 1
if sudoku_is_complete(puzzle_input):
print("Sudoku complete")
break
if num_iterations > 1000:
print("Something might be wrong here, aborting")
return puzzle_input
return puzzle_input
# puzzle = generate_puzzle()
puzzle = read_puzzle(input("Please input a string equating a sudoku board: "
"\n9 space-separated 9-long series of numbers from 0-9 where 0 indicates empty"
"\n"))
print(puzzle)
solved = solver(puzzle)
print(solved)
|
b9c4effe0bc2585b0623e91194fea80dec4e2e31 | sudhanshuptl/MyCodeDump | /Python/Algorithm/Binary_search.py | 1,598 | 4.15625 | 4 | # Binary Search Only Applicable on sorted array
import random
def binary_search_recursive(arr, low, high, key):
if high >= low:
mid = int((low + high)/2)
if arr[mid] == key:
return mid
elif arr[mid] > key:
return binary_search_recursive(arr, low, mid-1, key)
else:
return binary_search_recursive(arr, mid+1, high, key)
else:
return -1
def binary_search(arr, low, high, key):
while high >= low:
mid = (low+high)//2
if arr[mid] == key:
return mid
elif arr[mid] > key:
high = mid-1
else:
low = mid+1
return -1
if __name__ == '__main__':
data = [random.randint(1, 100) for x in range(10)]
data.sort()
print(data)
for i in range(20):
if i < 10:
print(f'Searching data at {i}th location output position is :',binary_search_recursive(data,0,len(data)-1, data[i]))
else:
random_number = random.randint(100, 500)
print(f'searching a number that is not available for sure, output position :',binary_search_recursive(data,0,len(data)-1, random_number))
print('None Recursive binary search test')
for i in range(20):
if i < 10:
print(f'Searching data at {i}th location output position is :',binary_search(data, 0, len(data)-1, data[i]))
else:
random_number = random.randint(100, 500)
print(f'searching a number that is not available for sure, output position :',binary_search(data, 0, len(data)-1, random_number))
|
15511bdf4c0d8edc8d767e4f5672ad60ca64ba3d | SanyaBoroda4/Coursera_Python | /2 WEEK/while test 2.py | 166 | 3.984375 | 4 | now = int(input())
max_num = now
while max_num != 0:
now = int(input())
if now == 0:
break
if now > max_num:
max_num = now
print(max_num)
|
a469365d9fb3f23b05018f91730ec069c7ce1bed | jasonxiaohan/DataStructure | /ArrayQueue.py | 1,332 | 3.921875 | 4 | # -*- coding:utf-8 -*-
from DataStructure.Queue import Queue
from DataStructure.Array import Array
"""
数组队列
"""
class ArrayQueue(Queue):
def __init__(self, capacity=10):
self.__array = Array(capacity)
def __str__(self):
res = ('Queue:size = %d,capacity = %d\n') % (self.__array.getSize(), self.__array.getCapacity())
res += "fron ["
for i in range(self.__array.getSize()):
res += str(self.__array.get(i))
if i != self.__array.getSize() - 1:
res += ", "
res += "] tail"
return res
"""
获取队列的长度
"""
def getSize(self):
return self.__array.getSize()
"""
判断队列是否为空
"""
def isEmpty(self):
return self.__array.isEmpty()
def getCapacity(self):
return self.__array.getCapacity()
"""
入队列
"""
def enqueue(self, e):
self.__array.addLast(e)
"""
出队列
"""
def dequeue(self):
return self.__array.removeFirst()
"""
获取队首的元素
"""
def getFront(self):
return self.__array.getFirst()
if __name__ == '__main__':
queue = ArrayQueue()
queue.enqueue(11)
queue.enqueue(22)
queue.enqueue(33)
print(queue)
queue.dequeue()
print(queue) |
5db6e5a662576b871c3216424fe5e2b23f51f33f | markabrennan/code_challenges | /triplet_sum_close_to_target.py | 959 | 3.734375 | 4 | """
From Grokking The Coding Interview
"""
def triplet_sum_close_to_target(arr, target):
triplets = []
for i in range(len(arr)):
if i > 0 and arr[i] == arr[i-1]:
continue
sub(arr, i, target, triplets)
triplets.sort()
return triplets[0][1]
def sub(arr, i, target, triplets):
left = i + 1
right = len(arr) - 1
while left < right:
cur = l[i] + l[left] + l[right]
diff = abs(target - cur)
triplets.append((diff, cur, [l[i], l[left], l[right]]))
if cur < target or (left > i + 1 and l[left] == l[left-1]):
left += 1
elif cur > target or (right < len(l)-1 and l[right] == l[right+1]):
right -= 1
else:
left += 1
right -= 1
return triplets
"""
TEST CASES
"""
# l = [-2, 0, 1, 2]
# target = 2
l = [-3, -1, 1, 2]
target = 1
# l = [1, 0, 1, 1]
# target=100
print(triplet_sum_close_to_target(l, target)) |
da40cd97917a3d11922bc2143ad02e0d2dc5dd14 | Arfameher/3D_houses | /create_csv.py | 1,274 | 3.75 | 4 | import csv # To write a csv file for bounds.
import pandas as pd
import rasterio # We can read in a GeoTiff file into a dataset using rasterio module.
def bounds():
"""Create a csv file that reads each tif file and stores the bounds of
each one of them as a rown in the .csv file
"""
with open('bounds.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter=",")
writer.writerow(["File_number", "Bounds:Left", "Bounds:Bottom" , "Bounds:Right" , "Bounds:Top"])
for i in range(1,44):
if i < 10:
df = rasterio.open(f"DSM/DSM_k0{i}.tif")
with open ("bounds.csv", 'a', newline='') as file:
writer = csv.writer(file, delimiter=",")
writer.writerow([i , df.bounds.left , df.bounds.bottom , df.bounds.right , df.bounds.top])
else:
df = rasterio.open(f"DSM/DSM_k{i}.tif")
with open ("bounds.csv", 'a', newline='') as file:
writer = csv.writer(file, delimiter=",")
writer.writerow([i , df.bounds.left , df.bounds.bottom , df.bounds.right , df.bounds.top])
bounds()
df = pd.read_csv("bounds.csv")
bounds |
eeec7a128558a1274dfe2c0daefedb0c704f38a5 | TonsOfBricks/projects | /iterative-functions.py | 5,314 | 4.1875 | 4 | """
Author: Nikita Sinkha
Date: 1/31/2018
File: iterative-functions.py
"""
def gcd(a, b):
"""
func: gcd():
Takes 2 positive numbers and computes the Greatest Common Divisor using the method
of iteration.
param1: a -> A positive number.
param2: b -> A positive number.
"""
while b != 0:
(a, b) = (b , a%b)
return a
def test_gcd():
"""
test_gcd():
Function that checks the working of the GCD function.
"""
print(gcd(2, 4))
print(gcd(3, 6))
print(gcd(5, 9))
print(gcd(7, 8))
print(gcd(8, 3))
def lcm(x, y):
"""
func: lcm():
Takes 2 positive numbers and computes the Least Common Multiple using the method
of iteration.
param1: x -> A positive number.
param2: y -> A positive number.
"""
if x > y:
x, y = y, x
for i in range(y, x*y+1, y):
if i%x == 0:
return i
def test_lcm():
"""
test_lcm():
Function that checks the working of the LCM function.
"""
print(lcm(2, 4))
print(lcm(4, 4))
print(lcm(7, 13))
print(lcm(8, 5))
print(lcm(9, 8))
def pow(n, e):
"""
func: pow():
Takes in a base and an exponent and computes the output as base to the power exponent
using the mwthod of iteration.
param1: n -> Acts as a base.
param2: e -> Acts as an exponent.
"""
temp = 1
if e == 0:
return 1
for i in range(e):
temp = temp*n
return temp
def test_pow():
"""
test_pow():
Function that checks the working of the pow function.
"""
print(pow(2, 0))
print(pow(3, 3))
print(pow(4, 4))
print(pow(5, 5))
print(pow(6, 2))
def is_factor(q, w):
"""
func: is_factor():
Takes 2 positive numbers and sees if the first number 'q' is a factor of 'w' using the method
of iteration.
param1: q -> A positive number.
param2: w -> A positive number.
"""
if q > w:
print("2nd number should be greater than first")
return "Try again"
else:
temp = 1
for i in range(1):
if w%q != 0:
return False
else:
return True
def test_is_factor():
"""
func: test_is_factor():
Function that checks the working of is_factor function.
"""
print(is_factor(2, 5))
print(is_factor(2, 8))
print(is_factor(3, 9))
print(is_factor(3, 7))
print(is_factor(6, 12))
def main():
"""
func: main()
Executes the program in order to produce the required outcome.
"""
######################################################
#Remove comments to see the working of test functions#
######################################################
"""
print("#################Test Functions#################")
print("Test results for test_pow() function")
test_pow()
print("")
print("Test results for test_gdc() function")
test_gdc()
print("")
print("Test results for test_lcm() function")
test_lcm()
print("")
print("Test results for test_is_factor() function")
test_is_factor()
print("")
"""
print("List of operations:")
print("1. POW")
print("2. GCD")
print("3. LCM")
print("4. is_factor")
print("")
while True:
user = str(input("Enter a number from 1-4 to select an operation (stop to quit):"))
if user in "stop":
return False
else:
if user in '1':
print("You have selected the POW function.")
base = int(input("Enter the base:"))
expo = int(input("Enter the exponent:"))
print("Your output would be processed as", base, "to the power", expo)
print("Answer:", pow(base, expo))
print("")
return main()
elif user in '2':
print("You have selected the GCD function.")
n1 = int(input("Enter a positive number:"))
n2 = int(input("Enter a positive number:"))
print("Your output would be processed as", "gcd("+str(n1)+","+str(n2)+")")
print("Answer:", gcd(n1, n2))
print("")
return main()
elif user in '3':
print("You have selected the LCM function.")
n1 = int(input("Enter a positive number:"))
n2 = int(input("Enter a positive number:"))
print("Your output would be processed as", "lcm("+str(n1)+","+str(n2)+")")
print("Answer:", lcm(n1, n2))
print("")
elif user in '4':
print("You have selected the is_factor function.")
n1 = int(input("Enter a positive number:"))
n2 = int(input("Enter a positive number:"))
print("Your output would be processed as", "is_factor("+str(n1)+","+str(n2)+")")
print("Answer:", is_factor(n1, n2))
print("")
return main()
exit()
if __name__ == "__main__" :
main()
|
67248a4d1f62d5ddfc694fc6b567303572b2ebaa | maomao905/algo | /add-bold-tag-in-string.py | 1,859 | 3.828125 | 4 | """
for word in dict:
find all matching position
save start and end position
result is [[start, end], [start, end]]
sort and if end1 > start2, merge them
string matching takes (SL) each time in worst case
time: O(SLD) + O(D) + O(S) = O(SLD)
S: string s size
L: average dict string length
D: dict size
"""
from typing import List
class Solution:
def addBoldTag(self, s: str, dict: List[str]) -> str:
if not dict:
return s
def find_match_pos(word):
pos = []
start = 0
while True:
r = s.find(word, start)
if r == -1:
break
pos.append([r, r + len(word)-1])
start = r + 1
return pos
def merge(pos):
merged = []
for start, end in pos:
if merged and merged[-1][1] >= start-1:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
pos = []
for word in dict:
pos.extend(find_match_pos(word))
# sort by start position
pos.sort(key=lambda x: x[0])
merged = merge(pos)
if not merged:
return s
# print(merged)
res = []
cur = 0
for start, end in merged:
res.append(s[cur:start])
res.append('<b>')
res.append(s[start:end+1])
res.append('</b>')
cur = end + 1
last_end = merged[-1][1]
res.append(s[last_end+1:])
return ''.join(res)
s = Solution()
# print(s.addBoldTag(s = "abcxyz123", dict = ["abc","123"]))
print(s.addBoldTag(s = "aaabbcc", dict = ["aaa","aab","bc"]))
|
023e23700c85e91cb7bda57f58b07e1b30f40a3c | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/ndxshe013/question4.py | 583 | 3.578125 | 4 |
def main():
x = input("Enter a space-separated list of marks:\n")
marks = x.split()
faL = 0
trd = 0
Low = 0
upper = 0
fst = 0
for i in marks:
if eval(i) < 50:
faL += 1
elif eval(i)<60:
trd += 1
elif eval(i)<70:
Low += 1
elif eval(i)<75:
upper += 1
else:
fst += 1
print("1 |" + "X"*fst)
print("2+|" + "X"*upper)
print("2-|" + "X"*Low)
print("3 |" + "X"*upper)
print("F |" + "X"*faL)
main()
|
ff2565184cfe8370891cdf0b1d1d4b571f4ed892 | EswarAleti/Python | /password_validity.py | 922 | 4.09375 | 4 | def get_validity(password):
# If password have less than 10 character then it is invalid
if len(password)<10:
return False
# Initalize 3 varibales to False
exist_digit = False
exist_alpha = False
exist_symbol = False
# For each letter in password
for letter in password:
# If alphabet exist then make exist_alpha to True
if letter.isalpha():
exist_alpha = True
# If digit exist then make exist_digit to True
elif letter.isdigit():
exist_digit = True
# If symbol exist then make exist_symbol to True
elif letter in '?!*':
exist_symbol = True
# This return true if 3 properties satisfied, False otherwise
return exist_alpha and exist_digit and exist_symbol
# Function calling
print('is abc012 valid: ', get_validity('abc012'))
print('is abcdefg valid: ', get_validity('abcdefg'))
print('is AbC111! valid: ', get_validity('AbC111!'))
print('is AbC111def! valid: ', get_validity('AbC111def!')) |
bb7c25ccd7d508b9e6098e750892758c3867be5d | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/02.Estrutura de Decisão/12. Folha de pagamento.py | 3,050 | 4 | 4 | #coding: utf-8
"""
Faça um programa para o cálculo de uma folha de pagamento,
sabendo que os descontos são do Imposto de Renda, que
depende do salário bruto (conforme tabela abaixo) e 3%
para o Sindicato e que o FGTS corresponde a 11% do
Salário Bruto, mas não é descontado (é a empresa que deposita).
O Salário Líquido corresponde ao Salário Bruto menos os descontos.
O programa deverá pedir ao usuário o valor da sua hora e a
quantidade de horas trabalhadas no mês.
Desconto do IR:
Salário Bruto até 900 (inclusive) - isento
Salário Bruto até 1500 (inclusive) - desconto de 5%
Salário Bruto até 2500 (inclusive) - desconto de 10%
Salário Bruto acima de 2500 - desconto de 20%
Imprima na tela as informações, dispostas conforme
o exemplo abaixo. No exemplo o valor da hora é 5
e a quantidade de hora é 220.
Salário Bruto: (5 * 220) : R$ 1100,00
(-) IR (5%) : R$ 55,00
(-) INSS ( 10%) : R$ 110,00
FGTS (11%) : R$ 121,00
Total de descontos : R$ 165,00
Salário Liquido : R$ 935,00
"""
print(" Bem vindo ao programa de pagamento")
print()
h = float(input(" Informe a quantidade de horas trabalhadas no mês: "))
qg = float(input(" Informe quanto ganha por hora: R$ "))
sb = qg*h
ir = 0
inss = 0
fgts = 0
tdesconto = 0
sl = 0
print()
if sb <= 900:
inss = sb - (sb*0.9)
fgts = sb - (sb*0.89)
tdesconto = ir + inss
sl = sb - tdesconto
print(f" - Salário bruto : R$ {sb:.2f}")
print(f" - (-) IR (isento) : R$ 0,00")
print(f" - (-) INSS (10%) : R$ {inss:.2f}")
print(f" - FGTS (11%) : R$ {fgts:.2f}")
print(f" - Total de descontos : R$ {tdesconto:.2f}")
print(f" - Salário Líquido : R$ {sl:.2f}")
elif sb > 900 and sb <= 1500:
ir = sb - (sb*0.95)
inss = sb - (sb*0.9)
fgts = sb - (sb*0.89)
tdesconto = ir + inss
sl = sb - tdesconto
print(f" - Salário bruto : R$ {sb:.2f}")
print(f" - (-) IR (5%) : R$ {ir:.2f}")
print(f" - (-) INSS (10%) : R$ {inss:.2f}")
print(f" - FGTS (11%) : R$ {fgts:.2f}")
print(f" - Total de descontos : R$ {tdesconto:.2f}")
print(f" - Salário Líquido : R$ {sl:.2f}")
elif sb > 1500 and sb <= 2500:
ir = sb - (sb*0.9)
inss = sb - (sb*0.9)
fgts = sb - (sb*0.89)
tdesconto = ir + inss
sl = sb - tdesconto
print(f" - Salário bruto : R$ {sb:.2f}")
print(f" - (-) IR (5%) : R$ {ir:.2f}")
print(f" - (-) INSS (10%) : R$ {inss:.2f}")
print(f" - FGTS (11%) : R$ {fgts:.2f}")
print(f" - Total de descontos : R$ {tdesconto:.2f}")
print(f" - Salário Líquido : R$ {sl:.2f}")
elif sb > 2500:
ir = sb - (sb*0.8)
inss = sb - (sb*0.9)
fgts = sb - (sb*0.89)
tdesconto = ir + inss
sl = sb - tdesconto
print(f" - Salário bruto : R$ {sb:.2f}")
print(f" - (-) IR (5%) : R$ {ir:.2f}")
print(f" - (-) INSS (10%) : R$ {inss:.2f}")
print(f" - FGTS (11%) : R$ {fgts:.2f}")
print(f" - Total de descontos : R$ {tdesconto:.2f}")
print(f" - Salário Líquido : R$ {sl:.2f}")
input() |
b7ccfcec04d309efb3819534577ad02758b3df10 | perceive203/python_excercise | /quicksort.py | 3,544 | 3.859375 | 4 | #! /usr/bin/env python2.7
# encoding=utf-8
""" 快速排序的练习程序
"""
import sys
import getopt
class QuickSort(object):
""" 快速排序类
"""
def __init__(self, idata = None):
if idata is not None:
self.data = list(idata)
def sort(self, idata = None):
""" 实际排序
Args:
data: 调用者可以给出需要排序的数列,如果为空则默认在对象实例初始化
之时已经给出了输入数列;数据格式为 tuple
Returns:
返回排好序的结果,list 数据格式
Raises:
IOError: 如果没有给出输入数列,直接报错
"""
if idata is not None:
self.data = None # 置空之前的数列
self.data = list(idata)
self._sort(0, len(self.data)-1)
return self.data
def _sort(self, begin, end):
""" 对 self.data 数列的 range 进行排序 [b, end]
Args:
begin: Range 的起始位置 begin
end: Range 的终止位置 end
Returns:
Nothing
"""
if end <= begin:
return
axle = self._select_axle(begin, end) # 选择一个轴
self._dprint("before range: list=", self.data[begin:end+1],
", b=%d, e=%d, m=%d" % (begin, end, axle))
axle = self._sort_range(begin, end, axle)
self._dprint("after range: list=", self.data[begin:end+1],
", b=%d, e=%d, m=%d" % (begin, end, axle))
self._sort(begin, axle-1)
self._sort(axle+1, end)
def _sort_range(self, begin, end, axle):
""" 对 self.data[begin, end] 的范围进行快排
"""
assert begin <= axle <= end
while begin < end:
# e 从右向左找到第一个比 m 小的值
while axle < end and self.data[axle] <= self.data[end]:
end -= 1
if axle < end:
self.data[end], self.data[axle] = self.data[axle], self.data[end]
axle = end
# b 从左向右找到第一个比 m 大的值
while begin < axle and self.data[begin] <= self.data[axle]:
begin += 1
if begin < axle:
self.data[begin], self.data[axle] = self.data[axle], self.data[begin]
axle = begin
return axle
@staticmethod
def _select_axle(begin, end):
""" 选择一个轴
Todo: 暂时选择中间位置,之后可以试探性选择,性能优化
"""
assert begin <= end
return begin+(end-begin)/2 # 之所以不使用 (e+b)/2 为了防止加法溢出
@staticmethod
def _dprint(*message):
""" 输出调试信息
"""
global _DEBUG
try:
type(_DEBUG)
except Exception:
_DEBUG = False
if _DEBUG:
print message
if __name__ == "__main__":
# 参数初始化
global _DEBUG, _TRACE
_DEBUG = _TRACE = False
DATA = list()
# 读入命令行参数
OPTS, ARGS = getopt.getopt(sys.argv[1:], "di:t")
for op, value in OPTS:
if op == "-d":
_DEBUG = True
if op == "-i":
DATA = [int(i) for i in value.split()]
if op == "-t":
_TRACE = True
if _TRACE:
import pdb
pdb.set_trace()
print QuickSort(DATA).sort()
|
ccdc375a3faf3c973712fd60b9c7c8110d8c4a87 | andersonkramer/Python | /Desafio01.py | 205 | 3.9375 | 4 | #Pergunga a idade e responde se você é Adulto
idade = int(input('Qual é a sua idade?'))
type(idade)
if idade > 20:
print('Vocé é uma pessoa adulta!')
else:
print('Vocé é um Adolescente!') |
1b6b956fe17f1b4c6303159d97d30843c8695bea | elitejakey/schoolks4 | /cake.py | 163 | 3.96875 | 4 | print('There are 25 people coming to the party.')
cake = (25*2)
print('This means that if you have 2 cakes per person, there will be', cake, 'cakes!')
|
40e07725b0441dc0093903a959a635691e89f5ce | shen-huang/selfteaching-python-camp | /exercises/1901050029/1001S02E03_calculator.py | 1,019 | 4.0625 | 4 | # Filename : 1001S02E03_calculator
# author by : Ž
# 庯
def add(x, y):
""""""
return x + y
def subtract(x, y):
""""""
return x - y
def multiply(x, y):
""""""
return x * y
def divide(x, y):
""""""
return x / y
########################################################
status = 1
# û
print("ѡ㣺")
print("1","2","3","4")
print("\n")
choice = input("ѡ(1/2/3/4):")
choice_int = int(choice)
if choice_int > 4:
status = 0
print("Ƿ")
if(status == 1):
num1 = int(input("һ: "))
num2 = int(input("ڶ: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
|
6f9cdbf8af7137fab3258868afd267fe39240768 | 4g/reinforce | /classic_control/mountain-car.py | 4,636 | 3.59375 | 4 | # -*- coding: iso-8859-15 -*-
"""
--Learning to balance a pole--
learn a q-network, which learning the q function directly from (s,a,r,s')
http://neuro.cs.ut.ee/demystifying-deep-reinforcement-learning/
As per https://arxiv.org/pdf/1312.5602.pdf
"""
import gym
from keras.layers import Dense, Input, concatenate
from keras.models import Model, Sequential
from keras.optimizers import Adam
import numpy as np
from collections import deque
import random
random.seed(9001)
env = gym.make('MountainCar-v0')
print dir(env)
class Agent:
def __init__(self, action_space, sample_observation):
self.memory_size = 10000
self.events = deque(maxlen=self.memory_size)
self.action_space = action_space
self.model = self.q_network(action_space.size, sample_observation.size)
# agent's age increases whenever
# an episode is over
# it also decreases the exploration probability when that happens
# since episode's length increase with time, agent ages slowly
self.age = 0
self.exploration_prob = 1.0
self.learning_sample_size = 40
def q_network(self, action_size, observation_size):
# lets follow the structure of network used
# in deepminds atari network, where state is mapped
# to q-values
mdl = Sequential()
mdl.add(Dense(32, input_shape=(observation_size,), activation='relu'))
mdl.add(Dense(32, activation='relu'))
mdl.add(Dense(action_size, activation='linear'))
mdl.compile(loss='mse', optimizer=Adam(0.001))
print mdl.summary()
return mdl
def action(self, state):
# explore vs exploit
# we want to agent to do
# exploration in the beginning
# and later go towards exploitation
# or we can control the rate on basis
# of error
if np.random.rand() > self.exploration_prob:
action_probs = self.model.predict(state)
action = self.action_space[np.argmax(action_probs)]
else:
action = random.randrange(self.action_space.size)
return action
def learn(self):
# As per https://arxiv.org/pdf/1312.5602.pdf
# learning directly from consecutive samples is inefficient, due to the strong correlations
# between the samples; randomizing the samples breaks these correlations and therefore reduces the
# variance of the updates.
gamma = 0.95
if len(self.events) < self.learning_sample_size:
return
training_samples = random.sample(self.events, self.learning_sample_size)
# From Bellman's equation
# Q(s,a) = r + γ * (max of Q(s′,a′) for all a')
# Loss = Predicted Q - Real Q
# predicted Q = max Q at a state amongst all actions
# Q(s,a) = r + γ * model.predict(s')
# Loss = model.predict(s) - (r + γ * model.predict(s'))
for sample in training_samples:
state, action, reward, observation, done = sample
current_values = self.model.predict(state)
if not done:
expected_value = -10
else:
expected_value = reward + gamma * max(self.model.predict(observation)[0])
# we only propogate loss from the chosen (state,action)
current_values[0][action] = expected_value
# print state, current_values
self.model.fit(state, current_values, verbose=0)
self.age += 1
self.exploration_prob = self.exploration_prob * .995
return
def save(self, state, action, reward, observation, done):
self.events.append([state, action, reward, observation, done])
def play(max_games):
sample_state = env.reset()
action_space = np.asarray(range(env.action_space.n))
print action_space
agent = Agent(action_space, sample_state)
past_games = deque(maxlen=100)
num_games = 0
while num_games < max_games:
state = env.reset()
state = np.expand_dims(state, axis=0)
game_length = 0
while True:
game_length += 1
action = agent.action(state)
observation, reward, done, info = env.step(action)
# print observation
# env.render()
# save s,a,r,s' in memory of the agent
# don't train the agent directly
# later use the memory to replay and learn
# i.e. learning happens at the end of episode
observation = np.expand_dims(observation, axis=0)
agent.save(state, action, reward, observation, done)
state = observation
if done:
break
# episode is over
# learn by replay
agent.learn()
num_games += 1
past_games.append(game_length)
print num_games, game_length, agent.exploration_prob, sum(past_games)/100.0
if __name__ == '__main__':
play(5000)
|
34120c178132dbea67d72c7528ffd0e35206e0cc | Mux-Mastermann/codewars | /katas.py | 6,327 | 4.0625 | 4 | """This file contains different solution functions from codewars challenges for python"""
def function_test():
"""Test functions here"""
print(halving_sum(25))
def halving_sum(n):
"""Kata: Halving Sum """
x = n
while n != 1:
n = n // 2
x = x + n
return x
def rgb(r, g, b):
"""Kata: RGB To Hex Conversion"""
results = []
for x in [r, g, b]:
if x < 0:
x = 0
elif x > 255:
x = 255
results.append(hex(x)[2:].zfill(2))
return "".join(results).upper()
def josephus(items, k):
"""Kata: Josephus Permutation"""
result = []
index = 0
while len(items) != 0:
for _ in range(k):
if index == len(items):
index = 0
index += 1
result.append(items[index - 1])
items.pop(index - 1)
index -= 1
return result
def list_squared(m, n):
"""Kata: Integers: Recreation One"""
from math import sqrt
results = []
for i in range(m, n + 1):
squared_divisors_sum = sum([x ** 2 for x in range(1, i + 1) if i % x == 0])
if sqrt(squared_divisors_sum) % 1 == 0:
results.append([i, squared_divisors_sum])
def is_solved(board):
"""Kata: Tic-Tac-Toe Checker"""
board_list = [cell for line in board for cell in line]
check_indices = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
for indices in check_indices:
slice_set = set([board_list[i] for i in indices])
if 0 in slice_set:
continue
if len(slice_set) == 1:
return board_list[indices[0]]
if 0 not in board_list:
return 0
return -1
def move_zeros(array):
"""Kata: Moving Zeros To The End"""
result = []
for element in array[::-1]:
if element == 0 and element is not False:
result.append(element)
else:
result.insert(0, element)
return result
def anagrams(word, words):
"""Kata: Where my anagrams at?"""
results = []
dist_letter = [(letter, word.count(letter)) for letter in set(word)]
for word in words:
check_letter = [(letter, word.count(letter)) for letter in set(word)]
if sorted(dist_letter, key=lambda x: x[0]) == sorted(check_letter, key=lambda x: x[0]):
results.append(word)
return results
def next_bigger(n):
"""Kata: Next bigger number with the same digits"""
import itertools
return min([int("".join(i)) for i in itertools.permutations(str(n)) if int("".join(i)) > n], default=-1)
# works but doens't pass on codewars due to timeout. Not my bad.
def valid_parentheses(string):
"""Kata: Valid Parentheses"""
for i, character in enumerate(string):
if character == ")":
if string[:i+1].count("(") < string[:i+1].count(")"):
return False
elif character == "(":
if string[i:].count("(") > string[i:].count(")"):
return False
return True
def queue_time(customers, n):
"""Kata: The Supermarket Queue"""
queues = [0 for _ in range(n)]
for customer in customers:
i = queues.index(min(queues))
queues[i] += customer
return max(queues)
def find_even_index(arr):
"""Kata: Equal Sides Of An Array"""
for i in range(len(arr)):
if sum(arr[:i]) == sum(arr[i + 1:]):
return i
return - 1
def order_weight(strng):
"""Kata: Weight for weight"""
return " ".join(sorted(strng.split(), key=lambda string: (sum(int(i) for i in string), string)))
def find_outlier(integers):
"""kata: Find The Parity Outlier
Input Array of integers. Only one integer is different. Either even or odd. Return this one
"""
modulo_integers = [i % 2 for i in integers]
n = 0 if modulo_integers.count(0) == 1 else 1
return integers[modulo_integers.index(n)]
def dirReduc(arr):
"""kata: Directions Reduction
Takes array of directions. Removes unneccessary oppositive directions next to each other
"""
# creating compare lists
horizontal = ["WEST", "EAST"]
vertical = ["NORTH", "SOUTH"]
# Remove indicator
i = 0
# creating slice of input arr
while True:
check = arr[i:i+2]
if not check:
return arr
if check in [horizontal, horizontal[::-1], vertical, vertical[::-1]]:
[arr.pop(i) for _ in range (2)]
i = 0
continue
i += 1
def likes(names):
"""Kata: Who likes it?
Takes Array of names. Returns Facebook like string telling who likes it
"""
if len(names) == 0:
return "no one likes this"
elif len(names) == 1:
return f"{names[0]} likes this"
elif len(names) == 2:
return f"{names[0]} and {names[1]} like this"
elif len(names) == 3:
return f"{names[0]}, {names[1]} and {names[2]} like this"
else:
return f"{names[0]}, {names[1]} and {len(names) - 2} others like this"
def array_diff(a, b):
"""Kata: Array.diff
Takes two lists. Removes all values from list a, that are in list b.
"""
return [item for item in a if item not in b]
def longest(s1, s2):
"""Kata: Two to One
Take two strings of letters. Return a sorted string of distinct letters.
"""
# combine the two strings, make a set of unique chars, then make a list
s = list(set(s1 + s2))
# sort unique char list
s.sort()
return "".join(s)
def friend(input_list):
"""Kata: Friend or Foe?
Takes list, filters out only strings with 4 letters
"""
# create a new list for the output
friends = []
# loop through input list
for element in input_list:
# has element 4 letters?
if len(element) == 4:
# append element to a new list
friends.append(element)
# return new list
return friends
def alphabet_position(text):
"""Kata: Replace With Alphabet Position
Give a string, replace every letter with position in alphabet
"""
import string
new_str = []
for char in text:
if not char.isalpha():
continue
new_str.append(str(string.ascii_lowercase.index(char.lower()) + 1))
return " ".join(new_str)
if __name__ == "__main__":
function_test()
|
9463611e087d0575c93f3770774ee933548736c9 | vinaykumar7686/Leetcode-Monthly_Challenges | /April/Week4/Powerful Integers.py | 1,511 | 4.1875 | 4 | # Powerful Integers
'''
Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.
An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.
You may return the answer in any order. In your answer, each value should occur at most once.
Example 1:
Input: x = 2, y = 3, bound = 10
Output: [2,3,4,5,7,9,10]
Explanation:
2 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32
Example 2:
Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]
Constraints:
1 <= x, y <= 100
0 <= bound <= 106
'''
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
if x==1 and y == 1:
if bound >= 2:
return [2]
else:
return []
elif x == 1:
x,y = y,x
xi = 0
yi = 0
res = set()
val = 0
lval = -1
while x**xi+1<=bound:
yi = 0
val = 0
lval = -1
while val<=bound:
val = x**xi + y**yi
if lval == val:
break
if val<=bound:
res.add(val)
lval = val
yi+=1
xi+=1
return res
|
934b7cbeac35aa2816efe4bacc97ecb2fe3e50bd | Simurgh818/AutostitchingProject | /DrawingFunctions.py | 777 | 3.625 | 4 | import numpy as np
import cv2
# To create a black image
img = np.zeros((512,512,3), np.uint8)
# To draw a diagonla blue line with 5 pixel thickness
img = cv2.line(img,(0,0),(511,511),(255,0,0),5)
#cv2.imshow('Drawing Practice', img)
img2 = cv2.rectangle(img,(384,0),(510,128),(0,255,0), 3)
img3 = cv2.circle(img,(447,63),63,(0,0,255),-1)
img4 = cv2.ellipse(img,(256,256),(100,50),0,0,180,(0,255,0),-1)
# Drawing multiple lines
pts = np.array([[10,5],[20,30],[70,20],[50,10]],np.int32)
pts = pts.reshape((-1,1,2))
img5 = cv2.polylines(img, [pts], True,(0,255,255))
#Adding Text to Image
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Hi Champ!', (10,500),font, 3,(255,255,255),2,cv2.LINE_AA)
cv2.imshow('Rectangle Practice', img2)
cv2.waitKey(0)
cv2.destroyAllWindows() |
6530f80d3cb30cd28af279977db10de424cd5589 | Yinlianlei/Work | /AI-Learn/test-5.py | 3,407 | 3.765625 | 4 | import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as graph
import numpy as np
from sklearn import linear_model
# %matplotlib inline
graph.rcParams['figure.figsize'] = (15,5)
graph.rcParams["font.family"] = 'DejaVu Sans'
graph.rcParams["font.size"] = '12'
graph.rcParams['image.cmap'] = 'rainbow'
import pandas as pd
# first version
# REPLACE <addFilePath> BELOW WITH 'Data/football data.txt' (INCLUDING THE QUOTES) TO LOAD THE DATA FROM THAT FILE
dataset = pd.read_csv('Data/football_data.txt', index_col = False, sep = '\t', header = 0)
# REPLACE <buildLinearRegression> BELOW WITH linear_model.LogisticRegression() TO BUILD A LOGISTIC REGRESSION MODEL
clf = linear_model.LogisticRegression()
# REPLACE <addWonCompetition> BELOW WITH 'won_competition' (INCLUDING THE QUOTES)
train_Y = dataset['won_competition']
# REPLACE <addAverageGoals> BELOW WITH 'average_goals_per_match' (INCLUDING THE QUOTES)
train_X = dataset['average_goals_per_match']
# This step fits (calculates) the model
# We are using our feature (x - number of goals scored) and our outcome/label (y - won/lost)
clf.fit(train_X[:, np.newaxis], train_Y)
# This works out the loss
def sigmoid(train_X):
return -1 / (1 + np.exp(-train_X))
X_test = np.linspace(-2, 3, 300)
loss = sigmoid(X_test * clf.coef_ + clf.intercept_).ravel()
# REPLACE <printDataHere> BELOW WITH print(dataset.head()) TO PREVIEW OUR DATASET
print(dataset.head())
# The 'won_competition' will be displayed on the vertical axis (y axis)
# The 'average_goals_per_match' will be displayed on the horizontal axis (x axis)
''' #first version
graph.scatter(train_X, train_Y, c = train_Y, marker = 'D')
graph.yticks([0, 1], ['No', 'Yes'])
graph.ylabel("Competition Win")
graph.ylim([-0.5, 1.5])
graph.xlabel("Average number of goals scored per match")
graph.show()
'''
''' #Third version
# This makes the graph
# The data points
graph.scatter(train_X, train_Y, c = train_Y, marker = 'D')
# The curve
graph.plot(X_test, loss, color = 'gold', linewidth = 3)
# Define the y-axis
graph.yticks([0, 1], ['No = 0.0', 'Yes = 1.0'])
graph.ylabel("Competition Win Likelihood")
graph.xlabel("Average number of goals per match")
graph.show()
'''
###
# REPLACE <numberOfGoals> BELOW WITH THE NUMBER OF GOALS IN A MATCH THIS YEAR. USE ANY NUMBER FROM 0 TO 3
###
p = 3
###
# Next we're going to use our model again - clf is the name of our model.
# We'll use a method to predict the probability of a positive result
# Use the variable p which we just made in this method.
###
# REPLACE <replaceWithP> BELOW WITH p TO PREDICT USING THIS VALUE
###
probOfWinning = clf.predict_proba([[p]])[0][1]
###
# This prints out the result
print("Probability of winning this year")
print(str(probOfWinning * 100) + "%")
# This plots the result
graph.scatter(train_X, train_Y, c = train_Y, marker = 'D')
graph.yticks([0, probOfWinning, 1], ['No = 0.0', round(probOfWinning,3), 'Yes = 1.0'])
graph.plot(X_test, loss, color = 'gold', linewidth = 3)
graph.plot(p, probOfWinning, 'ko') # result point
graph.plot(np.linspace(0, p, 2), np.full([2],probOfWinning), dashes = [6, 3], color = 'black') # dashed lines (to y-axis)
graph.plot(np.full([2],p), np.linspace(0, probOfWinning, 2), dashes = [6, 3], color = 'black') # dashed lines (to x-axis)
graph.ylabel("Competition Win Likelihood")
graph.xlabel("Average number of goals per match")
graph.show()
|
590bb202f506ca316634cc8b449e6ff8b61a85fe | merveeMalak/260201043 | /lab6/example1.py | 331 | 4.09375 | 4 | right_email = "ceng113@example.com"
email = input("Enter a email: ")
email_at_index = email.index("@")
email_at_before = email[:email_at_index]
email_at_after = email[email_at_index+1:]
email = email_at_before.replace(".","").lower()+"@"+email_at_after.lower()
if email == right_email:
print("Valid email")
else:
print("Invalid email") |
18932a500044f6fa340fb0c16cfb869ce7014098 | keepmoving-521/LeetCode | /程序员面试金典/面试题 01.08. 零矩阵.py | 2,326 | 4.0625 | 4 | """
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
"""
# 方法一:
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
row, col = len(matrix) * [0], len(matrix[0]) * [0]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
row[i] = 1
col[j] = 1
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if row[i] == 1 or col[j] == 1:
matrix[i][j] = 0
# 方法二:
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
if not matrix:
return
row, col = len(matrix), len(matrix[0])
stack = [] #stack来保存元素为0的下标
for i in range(row):
for j in range(col):
if matrix[i][j] == 0:
stack.append((i, j)) #遍历一遍矩阵,将元素为0的元素下标存入栈中
while stack: #遍历栈中下标组合,分别将对应的行和列置为0即可
i, j = stack.pop()
for k in range(col):
matrix[i][k] = 0
for k in range(row):
matrix[k][j] = 0
matrix1 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
matrix2 = [
[0, 1, 2, 0],
[3, 4, 5, 2],
[1, 3, 1, 5]
]
a = Solution()
b = a.setZeroes(matrix2)
print(b)
'''
方法一:
解题思路
第一次遍历,用两个数组记录哪一行或者哪一列有0。
第二次遍历,若行i或列j有个元素为0,则将当前元素置0.
方法二:
解题思路
step1:定义一个栈 stack来保存元素为0的下标
step2:遍历一遍矩阵,将元素为0的元素下标存入栈中
step3:遍历栈中下标组合,分别将对应的行和列置为0即可
''' |
1578b368b318ebfe4ea4e55e8bc467a009228826 | DanielGB-hub/PythonDZ | /DZ2_1.py | 1,638 | 3.5 | 4 | # 1) Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
result_list = [] # создаем пустой список и добавляем в него элементы
result_list.append("cool") # строка
result_list.append(None) # 'NoneType'
result_list.append(False) # булевое
result_list.append(223) # целочисленное
result_list.append(32.2) # с плавающей запятой
result_list.append(4+5j) # комплексное
result_list.append(b'text') # байт
m_ba = bytearray(b"some text") # массив байт
result_list.append(m_ba)
result_list.append([1, 2, 3]) # список
result_list.append({3, "cat", None}) # множества
m_t = tuple("это кортеж") # кортеж
result_list.append(m_t)
m_d = {a: a ** 2 for a in range(7)} # создаем словарь с помощью генератора
result_list.append(m_d)
print(result_list)
print("Убеждаемся, что наш список - действительно список: ")
print(type(result_list))
print("Типы элементов списка: ")
for el in result_list: # перебираем элементы и выводим типы каждого
print(el)
print(type(el))
|
11f0b3bd1bd3906a20d2bc5aa31db8c84bb9d492 | chendaniely/sphinx-rtd-test | /sphinx_rtd/mod.py | 520 | 3.65625 | 4 | """ Test module and some documentation
"""
def my_square(x):
"""Square a given value
:param x: value to be squared
:type x: a number
:rtype: float
"""
return x ** 2
def my_square_alternative_doc(x):
"""Square a given value
Parameters
----------
x : number
The number you want to square
Returns
-------
x **2 : number
The square of the value
Examples
--------
>>> my_square_alternative_doc(2)
>>> 4
"""
return x ** 2
|
edcb64ff4d5e2baf43c3aaac6236fd46c0d9efcb | xren/algorithms | /4-4.py | 550 | 3.96875 | 4 | # Given a binary tree, design an algorithm which creates linked list of all the
# nodes at each depth
def getLinkedList(root):
result = []
current = getLinkedList()
if not root:
current.add(root)
while current:
result.append(current)
parents = current
currentLinkedList = getLinkedList()
for parent in parents:
if parent.left:
currentLinkedList.add(parent.left)
if parent.right:
currentLinkedList.add(parent.right)
return result
|
de7476dd256feb9153f76a24dd06f8110c0c3355 | jessica1127/python_leetcode | /leetcode/leetcode535_encode-and-decode-tinyurl.py | 1,370 | 4.1875 | 4 | '''
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
'''
import string
import random
class Codec:
def __init__(self):
self.alphaword = string.letters+string.digits
self.url2code = {}
self.code2url = {}
def encode(self, longUrl):
if longUrl not in self.url2code:
code = ''.join(random.choice(self.alphaword) for _ in range(6))
if code not in self.code2url:
self.code2url[code] = longUrl
self.url2code[longUrl] = code
return 'http://tinyurl.com/' + self.url2code[longUrl]
def decode(self, shortUrl):
return self.code2url[shortUrl[-6:]]
# Your Codec object will be instantiated and called as such:
codec = Codec()
url = 'www.baidu.com'
shorturl = codec.encode(codec.encode(url))
print "shorturl = ", shorturl
original = codec.decode(codec.decode(shorturl))
print "original = ", original |
ce08769389a0d4323cc30f9672974d427296232a | JesusAMR/Programas-S1 | /bafu.py | 1,331 | 4.09375 | 4 | #Area bajo una curva
#Funcion (sin(x))^2 de 4 a 7 x³ / 3 - 2x² + 12
from decimal import *
from threading import *
from math import *
def f1(x,power,u=2):
return (pow(x,3))/(3-(2*pow(x,2))+12)
def f2(x):
return Decimal((1/(x+1)))
def smrare(b,a):
sm=((b-a)/6)*(f2(a)+4*f2((a/2+b/2))+f2(b))
return sm
def frange5(limit1, limit2 = None, increment = 1.):
"""
Range function that accepts floats (and integers).
Usage:
frange(-2, 2, 0.1)
frange(10)
frange(10, increment = 0.5)
The returned value is an iterator. Use list(frange) for a list.
"""
if limit2 is None:
limit2, limit1 = limit1, 0.
else:
limit1 = float(limit1)
count = int(ceil(limit2 - limit1)/increment)
return (limit1 + n*increment for n in range(count))
getcontext().prec=200
y=int(input("Inserte el exponente\n"))
u=int(input("Inserte la multp de x\n"))
def test(y,u):
"""
y = El exponente de la funcion
u = El multiplicador de x
"""
n=10000
area=0
a=10
b=12
width=de(b-a)/n
sm=0
for i in frange5(a,b,width):
#fxa=f1(i,y,u)
#fxb=f1(i+width,y,u)
fxa=(i)
fxb=f2(i+width)
area=((fxa+fxb)/2)*width
#fx=f1(i)
#area=fx*width
#print(sm)
sm+=Decimal(area)
#sm+=fx
return sm
print (test(y,u)) |
d120cbb5300504b3b5b0f242ff7ea2f49d860e72 | UCMHSProgramming16-17/github-intro-mshih18 | /addition.py | 451 | 4.25 | 4 | # import sys module
import sys
# assign command line arguments to variables
value1 = int(input("First number: "))
value2 = int(input("Second number: "))
value3 = int(input("Thrid number: "))
# find sum of values
result = value1 + value2 + value3
# checks if number is even or odd
if result%2 == 0:
print ("The sum of your numbers is even")
else:
print("The sum of your numbers is odd")
# print result
print("Your result is" + "result") |
523d9c78dfc4d620b9c069fd42ca2c596b54e965 | cgat-developers/cgat-apps | /cgat/Histogram.py | 19,547 | 3.8125 | 4 | """
Histogram.py - Various functions to deal with histograms
===========================================================
:Author:
:Tags: Python
Histograms can be calculated from a list/tuple/array of
values. The histogram returned is then a list of tuples
of the format [(bin1,value1), (bin2,value2), ...].
"""
import sys
import re
import math
import scipy
import bisect
import numpy
from functools import reduce
def CalculateFromTable(dbhandle,
field_name,
from_statement,
num_bins=None,
min_value=None,
max_value=None,
intervals=None,
increment=None):
"""get a histogram using an SQL-statement.
Intervals can be either supplied directly or are build
from the data by providing the number of bins and optionally
a minimum or maximum value.
If no number of bins are provided, the bin-size is 1.
This command uses the INTERVAL command from MYSQL, i.e. a bin value
determines the upper boundary of a bin.
"""
if not min_value:
min_value = int(math.floor(dbhandle.Execute(
"SELECT MIN(%s) %s" % (field_name, from_statement)).fetchone()[0]))
if not max_value:
max_value = int(math.ceil(dbhandle.Execute(
"SELECT MAX(%s) %s" % (field_name, from_statement)).fetchone()[0]))
if increment:
step_size = increment
elif num_bins:
step_size = int(float(max_value - min_value) / float(num_bins))
else:
step_size = 1
if not intervals:
intervals = list(range(min_value, max_value, step_size))
i_string = ",".join(list(map(str, intervals)))
statement = "SELECT INTERVAL( %s, %s )-1 AS i, COUNT(*) %s GROUP BY i" % (
field_name, i_string, from_statement)
return convert(dbhandle.Execute(statement).fetchall(), intervals)
def CalculateConst(values,
num_bins=None,
min_value=None,
max_value=None,
intervals=None,
increment=None,
combine=None):
"""calculate a histogram based on a list or tuple of values.
"""
if not min_value:
min_value = int(math.floor(min(values)))
if not max_value:
max_value = int(math.ceil(max(values))) + 1
if increment:
step_size = increment
elif num_bins:
step_size = int(float(max_value - min_value) / float(num_bins))
else:
step_size = 1
if not intervals:
intervals = list(range(min_value, max_value, step_size))
histogram = [0] * len(intervals)
for v in values:
i = 0
while i < len(intervals) and v > intervals[i]:
i += 1
if i < len(intervals):
histogram[i] += 1
return intervals, histogram
def Calculate(values,
num_bins=None,
min_value=None,
max_value=None,
intervals=None,
increment=None,
combine=None,
no_empty_bins=0,
dynamic_bins=False,
ignore_out_of_range=True):
"""calculate a histogram based on a list or tuple of values.
use scipy for calculation.
"""
if len(values) == 0:
return []
if not intervals:
if min_value is None:
min_value = min(values)
if max_value is None:
max_value = max(values)
if dynamic_bins:
intervals = list(
set([x for x in values if min_value <= x <= max_value]))
intervals.sort()
else:
if increment:
step_size = increment
elif num_bins and max_value:
step_size = float(max_value - min_value) / float(num_bins)
else:
step_size = 1.0
num_bins = int(
math.ceil((float(max_value) - float(min_value)) / float(step_size)))
intervals = [float(min_value) + float(x) * float(step_size)
for x in range(num_bins + 1)]
if not ignore_out_of_range:
new_values = []
for v in values:
if v < min_value:
v = min_value
elif v > max_value:
v = max_value
new_values.append(v)
values = new_values
return convert(numpy.histogram(values, bins=intervals)[0], intervals, no_empty_bins)
def Scale(h, scale=1.0):
"""rescale bins in histogram.
"""
n = []
for b, v in h:
n.append((b * scale, v))
return n
def convert(h, i, no_empty_bins=0):
"""add bins to histogram.
"""
n = []
for x in range(0, len(h)):
if no_empty_bins and h[x] == 0:
continue
n.append((i[x], h[x]))
return n
def Combine(source_histograms, missing_value=0):
"""combine a list of histograms
Each histogram is a sorted list of bins and counts.
The counts can be tuples.
"""
new_bins = {}
# get all bins
for h in source_histograms:
for data in h:
new_bins[data[0]] = []
# add values
length = 1
l = 0
for h in source_histograms:
# add data for used bins
for data in h:
bin = data[0]
if len(data) != 2:
v = data[1:]
else:
v = data[1]
if isinstance(v, list) or isinstance(v, tuple):
l = len(v)
for x in v:
new_bins[bin].append(x)
else:
l = 1
new_bins[bin].append(v)
# add missing value for unused bins
for b in list(new_bins.keys()):
if len(new_bins[b]) < length:
for x in range(0, l):
new_bins[b].append(missing_value)
length += l
return __ConvertToList(new_bins)
def Print(h, intervalls=None, format=0, nonull=None, format_value=None, format_bin=None):
"""print a histogram.
A histogram can either be a list/tuple of values or
a list/tuple of lists/tuples where the first value contains
the bin and second contains the values (which can again be
a list/tuple).
format
0 = print histogram in several lines
1 = print histogram on single line
"""
Write(sys.stdout, h, intervalls, format, nonull, format_value, format_bin)
def Write(outfile, h, intervalls=None, format=0, nonull=None,
format_value=None, format_bin=None):
"""print a histogram.
A histogram can either be a list/tuple of values or
a list/tuple of lists/tuples where the first value contains
the bin and second contains the values (which can again be
a list/tuple).
:param format: output format.
0 = print histogram in several lines,
1 = print histogram on single line
"""
lines = []
if len(h) == 0:
return
if format_value:
def fv(x):
if x == "na":
return x
else:
return format_value % x
else:
fv = str
if format_bin:
fb = lambda x: format_bin % x
else:
fb = str
if not isinstance(h[0], list) and not isinstance(h[0], tuple):
for x in range(0, len(h)):
if intervalls:
lines.append(fb(intervalls[x]) + "\t" + fv(h[x]))
else:
lines.append(fb(x) + "\t" + fv(h[x]))
else:
for x, v in h:
if isinstance(v, list) or isinstance(v, tuple):
val = "\t".join(list(map(fv, v)))
else:
val = fv(v)
if intervalls:
lines.append(fb(intervalls[x]) + "\t" + val)
else:
lines.append(fb(x) + "\t" + val)
# print values
if nonull is not None:
for l in range(0, len(lines)):
lines[l] = re.sub("\t0", "\t%s" % nonull, lines[l])
if format == 0:
outfile.write("\n".join(lines) + "\n")
elif format == 1:
outfile.write(" | ".join(lines) + "\n")
else:
outfile.write("\n".join(lines) + "\n")
def Fill(h):
"""fill every empty value in histogram with
previous value.
"""
new_h = []
x, v = h[0]
if isinstance(v, list) or isinstance(v, tuple):
l = len(v)
previous_v = [0] * l
else:
previous_v = 0
for x, v in h:
if isinstance(v, list) or isinstance(v, tuple):
for i in range(0, l):
if v[i] == 0:
v[i] = previous_v[i]
else:
previous_v[i] = v[i]
else:
if v == 0:
v = previous_v
else:
previous_v = v
new_h.append((x, v))
return new_h
def Normalize(h):
# first count totals
if isinstance(h[0][1], list) or isinstance(h[0][1], tuple):
l = len(h[0][1])
is_list = 1
else:
is_list = 0
l = 1
totals = [0.0] * l
for bin, v in h:
if is_list:
for x in range(0, l):
try:
totals[x] += v[x]
except TypeError:
pass
else:
totals[0] += v
for x in range(0, l):
if totals[x] == 0:
totals[x] = 1
# first count totals
new_histogram = []
for bin, v in h:
if is_list:
vv = []
for x in range(0, l):
vv.append(float(v[x]) / totals[x])
else:
vv = float(v) / totals[0]
new_histogram.append((bin, vv))
return new_histogram
def Add(h1, h2):
"""adds values of histogram h1 and h2 and
returns a new histogram
"""
new_bins = {}
# get all bins
for h in (h1, h2):
if h:
for bin, v in h:
new_bins[bin] = 0
for h in (h1, h2):
if h:
for bin, v in h:
new_bins[bin] += v
return __ConvertToList(new_bins)
def __ConvertToList(new_bins):
"""converts a hash to a histogram.
"""
# convert to list
keys = list(new_bins.keys())
keys.sort()
new_histogram = []
for k in keys:
new_histogram.append((k, new_bins[k]))
return new_histogram
def SmoothWrap(histogram, window_size):
"""smooth histogram by sliding window-method, where
the window is wrapped around the borders. The sum of
all values is entered at center of window.
"""
new_histogram = [0] * len(histogram)
half_window_size = window_size / 2
length = len(histogram)
# 1. start with window
cumul = 0
for i in range(length - half_window_size, length):
cumul = cumul + histogram[i]
for i in range(0, half_window_size + 1):
cumul = cumul + histogram[i]
# 2. iterate over histogram and add values over windows_size
y = length - half_window_size
z = half_window_size
for i in range(0, length):
new_histogram[i] = cumul
y = y + 1
z = z + 1
if y >= length:
y = 0
if z >= length:
z = 0
cumul = cumul - histogram[y] + histogram[z]
return new_histogram
def GetMaximumIndex(histogram):
return histogram.index(max(histogram))
def GetMinimumIndex(histogram):
return histogram.index(min(histogram))
def PrintAscii(histogram, step_size=1):
"""print histogram ascii-style.
"""
l = len(histogram)
m = max(histogram)
if m == 0:
print("----> histogram is empty")
return
f = 100.0 / m
print("----> histogram: len=%i, max=%i" % (l, m))
for x in range(1, l, step_size):
s = "|"
s += " " * (int(histogram[x] * f) - 1) + "*"
print("%5i" % x, s)
def Count(data):
"""count categorized data. Returns a list
of tuples with (count, token).
"""
counts = []
data.sort()
last_c = None
for c in data:
if last_c != c:
if last_c:
counts.append((t, last_c))
last_c = c
t = 0
t += 1
counts.append((t, last_c))
return counts
def Accumulate(h, num_bins=2, direction=1):
"""add successive counts in histogram.
Bins are labelled by group average.
"""
if len(h) == []:
return []
new_histogram = []
if isinstance(h[0][1], list) or isinstance(h[0][1], tuple):
l = len(h[0][1])
is_list = 1
else:
is_list = 0
l = 1
if direction != 1:
h.reverse()
i = 0
if is_list:
vv = [0] * l
bb = 0
for b, v in h:
bb += b
for x in range(0, l):
vv[x] += v[x]
i += 1
if i % num_bins == 0:
new_histogram.append((float(bb) / float(num_bins), vv))
vv = [0] * l
bb = 0
if (i % num_bins):
new_histogram.append((float(bb) / float(i % num_bins), vv))
else:
vv = 0
bb = 0
for b, v in h:
bb += b
vv += v
i += 1
if i % num_bins == 0:
new_histogram.append(float(bb) / float(num_bins), vv)
vv = 0
bb = 0
if (i % num_bins):
new_histogram.append(float(bb) / float(i % num_bins), vv)
# reorder h and new_histogram
if direction != 1:
h.reverse()
new_histogram.reverse()
return new_histogram
def Cumulate(h, direction=1):
"""calculate cumulative distribution.
"""
if len(h) == []:
return []
new_histogram = []
if isinstance(h[0][1], list) or isinstance(h[0][1], tuple):
l = len(h[0][1])
is_list = 1
else:
is_list = 0
l = 1
if direction != 1:
h.reverse()
if is_list:
vv = [0] * l
for b, v in h:
for x in range(0, l):
vv[x] += v[x]
new_histogram.append((b, [x for x in vv]))
else:
vv = 0
for b, v in h:
vv += v
new_histogram.append((b, vv))
# reorder h and new_histogram
if direction != 1:
h.reverse()
new_histogram.reverse()
return new_histogram
def AddRelativeAndCumulativeDistributions(h):
"""adds relative and cumulative percents to a histogram.
"""
if len(h) == []:
return []
new_histogram = []
total = float(reduce(lambda x, y: x + y, [x[1] for x in h]))
cumul_down = int(total)
cumul_up = 0
for bin, val in h:
percent = float(val) / total
cumul_up += val
percent_cumul_up = float(cumul_up) / total
percent_cumul_down = float(cumul_down) / total
new_histogram.append(
(bin, (val, percent, cumul_up, percent_cumul_up, cumul_down, percent_cumul_down)))
cumul_down -= val
return new_histogram
def histogram(values, mode=0, bin_function=None):
"""Return a list of (value, count) pairs, summarizing the input values.
Sorted by increasing value, or if mode=1, by decreasing count.
If bin_function is given, map it over values first.
Ex: vals = [100, 110, 160, 200, 160, 110, 200, 200, 220]
histogram(vals) ==> [(100, 1), (110, 2), (160, 2), (200, 3), (220, 1)]
histogram(vals, 1) ==> [(200, 3), (160, 2), (110, 2), (100, 1), (220, 1)]
histogram(vals, 1, lambda v: round(v, -2)) ==> [(200.0, 6), (100.0, 3)]"""
if bin_function:
values = list(map(bin_function, values))
bins = {}
for val in values:
bins[val] = bins.get(val, 0) + 1
if mode:
return sort(list(bins.items()), lambda x, y: cmp(y[1], x[1]))
else:
return sort(list(bins.items()))
def cumulate(histogram):
"""cumulate histogram in place.
histogram is list of (bin, value) or (bin, (values,) )
"""
if len(histogram) == 0:
return
if isinstance(h[0][1], list) or isinstance(h[0][1], tuple):
n = len(histogram[0][1])
l = [0] * n
for bin, vv in histogram:
for x in range(n):
vv[x] += l[x]
l[x] = vv[x]
else:
l = 0
for x in range(len(histogram)):
histogram[x] = (histogram[x][0], histogram[x][1] + l)
l = histogram[x][1]
def normalize(histogram):
"""normalize histogram in place.
histogram is list of (bin, value) or (bin, (values,) )
"""
if len(histogram) == 0:
return
if isinstance(histogram[0][1], list) or isinstance(histogram[0][1], tuple):
n = len(histogram[0][1])
m = [0] * n
for bin, d in histogram:
for x in range(n):
m[x] = max(m[x], d[x])
for bin, d in histogram:
for x in range(n):
if m[x] > 0:
d[x] = float(d[x]) / m[x]
else:
m = float(max([x[1] for x in histogram]))
if m > 0:
for x in range(len(histogram)):
histogram[x] = (histogram[x][0], histogram[x][1] / m)
def fill(iterator, bins):
"""fill a histogram from bins.
The values are given by an iterator so that the histogram
can be built on the fly.
Description:
Count the number of times values from array a fall into
numerical ranges defined by bins. Range x is given by
bins[x] <= range_x < bins[x+1] where x =0,N and N is the
length of the bins array. The last range is given by
bins[N] <= range_N < infinity. Values less than bins[0] are
not included in the histogram.
Arguments:
iterator -- The iterator.
bins -- 1D array. Defines the ranges of values to use during
histogramming.
Returns:
1D array. Each value represents the occurences for a given
bin (range) of values.
"""
h = numpy.zeros(len(bins))
# bins might not be uniform, so do a bisect
for value in iterator:
i = bisect.bisect_left(value)
h[i] += 1
return h
def fillHistograms(infile, columns, bins):
"""fill several histograms from several columns in a file.
The histograms are built on the fly.
Description:
Count the number of times values from array a fall into
numerical ranges defined by bins. Range x is given by
bins[x] <= range_x < bins[x+1] where x =0,N and N is the
length of the bins array. The last range is given by
bins[N] <= range_N < infinity. Values less than bins[0] are
not included in the histogram.
Arguments:
file -- The input file.
columns -- columns to use
bins -- a list of 1D arrays. Defines the ranges of values to use during
histogramming.
Returns:
a list of 1D arrays. Each value represents the occurences for a given
bin (range) of values.
WARNING: missing value in columns are ignored
"""
assert(len(bins) == len(columns))
hh = [numpy.zeros(len(bins[x]), numpy.float) for x in range(len(columns))]
for line in infile:
if line[0] == "#":
continue
data = line[:-1].split()
# bins might not be uniform, so do a bisect
for x, y in enumerate(columns):
try:
v = float(data[y])
except IndexError:
continue
i = bisect.bisect(bins[x], v) - 1
if i >= 0:
hh[x][i] += 1
return hh
|
cbd6c7f839a492dbc77dd9f5a2f09135f35395c7 | mattmaggio19/Code_eval | /Easy_challenges/Odds_to_99.py | 258 | 3.84375 | 4 | #print all odd from 1 to n
def isodd(arg): #is a number odd?
if not arg % 2 == 0:
return True
else:
return False
def count_up_execute(n):
for ii in range(1,n):
if isodd(ii):
print(ii)
count_up_execute(100) |
f170d291b1518bc6aae995e89ed207595062c731 | pusparajvelmurugan/ral | /83.py | 250 | 3.859375 | 4 | num=input("Enter your seqence (Mod/Dividee):")
op=['%','/']
for x in num:
if(x=='%'):
k1=int(num.split(x)[0])
k2=int(num.split(x)[1])
ans=k1%k2
elif(x=='/'):
k1=int(num.split(x)[0])
k2=int(num.split(x)[1])
ans=k1//k2
print(ans)
|
ed318faf9b3c8b1525115a857f50e0b93fee37dd | rohinrohin/python-lecture | /Day 1/Assignment/3_wicketfall.py | 311 | 3.515625 | 4 | wicket = []
while True:
print("1. Wicket")
print("2. Game Over")
print("3. Exit")
i = input()
if i=='1':
run = int(input("partnership run:"))
wicket.append(run)
elif i=='2':
print("Highest partnership: ", max(wicket))
break
else:
break
|
6c3ab72e38db4b524408b8352e4a04b59890aeb5 | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 2/Repetições em Python (while)/DESAFIO 057 - Validação de Dados.py | 335 | 4.09375 | 4 | """Faça um programa que leia o sexo, mas só aceite os valores 'M' ou 'F'.
- Caso esteja errado, peça a digitação novamente até ter um valor correto"""
sexo = str(input('Insira o sexo [M/F]: ')).upper()
while sexo != 'M' and sexo != 'F':
sexo = str(input('ERROR!, Digite sexo novamente: ')).upper()
print('Sexo registrado!')
|
f3460d56250f3421f888a07c2799a3e7b85aee31 | im4faang/Coffee-Machine | /main.py | 2,030 | 4.09375 | 4 | from data import MENU, resources
water = resources["water"]
milk = resources["milk"]
coffee = resources["coffee"]
money = 0
turn_off = False
def report():
print(f"Water: {water}ml\nMilk: {milk}ml\nCoffee: {coffee}g\nMoney: ${money}")
def check_resources(choice):
check = True
if choice != "espresso":
if milk < MENU[choice]["ingredients"]["milk"]:
print("Sorry, that's not enough milk.")
check = False
if water < MENU[choice]["ingredients"]["water"]:
print("Sorry, that's not enough water.")
check = False
if coffee < MENU[choice]["ingredients"]["coffee"]:
print("Sorry, that's not enough coffee.")
return check
def insert_money():
print("Please insert coins.")
quarters = float(input("How many quarters?: ")) * 0.25
dimes = float(input("How many dimes?: ")) * 0.10
nickles = float(input("How many nickles?: ")) * 0.05
pennies = float(input("How many pennies?: ")) * 0.01
total = quarters + dimes + nickles + pennies
return total
def coffee_choice(choice):
global milk, water, coffee, money
if choice != "espresso":
milk -= MENU[choice]["ingredients"]["milk"]
water -= MENU[choice]["ingredients"]["water"]
coffee -= MENU[choice]["ingredients"]["coffee"]
money += MENU[choice]["cost"]
return f"Here is your {choice}. Enjoy!"
while not turn_off:
choice = input("What would you like? (espresso/latte/cappuccino): ").lower()
if choice == "report":
report()
elif choice == "off":
turn_off = True
else:
if check_resources(choice):
user_money = insert_money()
if user_money < MENU[choice]["cost"]:
print("Sorry, that's not enough money. Money refunded.")
else:
refund = round(user_money - MENU[choice]["cost"], 2)
print(f"Here is ${refund} in change.")
print(coffee_choice(choice))
|
c5d7e9342af92e657f8e1896567c87cf47028d94 | OmarFaruq502/Python-Basics | /Chanllenges 52-59/random-chapter.py | 1,465 | 3.9375 | 4 | ####################################################
# Python by example
# Problem : 052 - 059
# Author: Omar Rahman
# Date: 1/1/2020
####################################################
import random
#------------------------------------
# Problem 052
#------------------------------------
def fifty_two():
number = random.randint(1,100)
print(number)
# fifty_two()
#------------------------------------
# Problem 053
#------------------------------------
def fifty_three():
fruit = random.choice(["banana","apple","orange","guava","blueberry"])
print(fruit)
# fifty_three()
#------------------------------------
# Problem 054
#------------------------------------
def fifty_four():
userSelection = input("choose heads or tails(h/t):")
computerChoice = random.choice(["h","t"])
if computerChoice == userSelection:
print("You Win!")
else:
print("Bad luck :(")
print("Computer selected ",computerChoice)
# fifty_four()
#------------------------------------
# Problem 056
#------------------------------------
def fifty_six():
random_number = random.randint(1,10)
guess = int(input("Enter your selection: "))
while guess != random_number:
if guess > random_number:
print("Too High")
else:
print("Too Low")
guess = int(input("Enter your selection: "))
print("Congratulations you have picked the number!")
# fifty_six()
|
e4a2060dbdf3d7ea85f2e0f2de9ca00cc2f40dbd | BrandonDoggett/pyapivz | /readinjson04.py | 467 | 3.546875 | 4 | #!/usr/bin/python3
import json
def main():
with open("datacenter.json", "r") as datacenter:
datacenterstr = datacenter.read()
datacenterdict = json.loads(datacenterstr) # gives a dict
print(datacenterdict["row1"])
with open("datacenter.json", "r") as datacenter:
datacentershort = json.load(datacenter) # loads file directly, forms a dict
print(type(datacentershort)) # Will show this is a dict
main()
|
b28beb0c0dbd4f1c023c798a0d9361e976068277 | Swisy/CSC-110 | /decrypter.py | 805 | 3.90625 | 4 | ###
### Author: Saul Weintraub
### Course: CSc 110
### Description:
###
###
###
def main():
encrypted_file_name = input('Enter the name of an encrypted text file:\n')
index_file_name = input('Enter the name of the encryption index file:\n')
encrypted_file = open(encrypted_file_name, 'r')
index_file = open(index_file_name, 'r')
encrypted_list = encrypted_file.readlines()
index_list = index_file.readlines()
decrypted_file = open('decrypted.txt', 'w')
decrypted_list = []
i = 1
while i <= len(index_list):
index = index_list.index(str(i) + '\n')
decrypted_list.append(encrypted_list[index])
i += 1
for line in decrypted_list:
decrypted_file.write(line)
decrypted_file.close()
index_file.close()
encrypted_file.close()
main() |
90e297a786d781b9055895bb7afb554d30b6aaf1 | ramonvaleriano/python- | /Cursos/Curso Em Video - Gustavo Guanabara/Curso em Vídeo - Curso Python/Exercícios/desafio_11.py | 477 | 3.921875 | 4 | # Programa: desafio_11.py
# Author: Ramon R. Valeriano
# Description:
# Updated: 22/09/2020 - 22:47
def area(numero1, numero2):
result = numero1*numero2
return result
def tinta(calculo, num1, num2):
dado = calculo(num1, num2)
quantidade = (dado/2)
return quantidade
comprimento = float(input('Digite o comprimento: '))
altura = float(input('Digite a altura: '))
calculo = area(comprimento,altura)
final = tinta(area, comprimento, altura)
print(calculo)
print(final) |
8784115fdb1a667df3137bcbfce647f51e0b3f52 | Shreyash840/Practice | /util/Single_Linked_List/SLL_base_util.py | 4,881 | 4.125 | 4 | """ Linked List util"""
newline = "\n-------------"
def print_linked_list(head):
itr_node = head
if itr_node is None:
print("Empty List")
return
while itr_node is not None:
print(itr_node.data, sep=' ', end='-->')
itr_node = itr_node.next
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append_at_first(self, data_to_insert):
new_node = Node(data=data_to_insert)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def append_at_last(self, data_to_insert):
new_node = Node(data=data_to_insert)
if self.head is None:
self.head = new_node
else:
itr_node = self.head
while itr_node.next is not None:
itr_node = itr_node.next
itr_node.next = new_node
def append_at_index(self, data_to_insert, index):
pos = 0
new_node = Node(data_to_insert)
if self.head is None or index == 0:
new_node.next = self.head
self.head = new_node
return
itr_node = self.head
while itr_node.next is not None:
pos += 1
if pos == index:
new_node.next = itr_node.next
itr_node.next = new_node
return
itr_node = itr_node.next
if itr_node.next is None:
if pos + 1 < index:
print("out of bound")
else:
itr_node.next = new_node
def total_elements_in_linked_list(self):
if self.head is None:
count = 0
else:
count = 1
itr_node = self.head
while itr_node.next is not None:
count += 1
itr_node = itr_node.next
return count
def print_linked_list(self):
itr_node = self.head
if itr_node is None:
print("Empty List")
return
while itr_node is not None:
print(itr_node.data, sep=' ', end='-->')
itr_node = itr_node.next
def delete_at_beginning(self):
if self.head is None:
print("List is Empty")
# temp_node = self.head //this code is not needed as there is no need to free the head
self.head = self.head.next
# temp_node = None //this code is not needed as there is no need to free the head
def delete_at_last(self):
if self.head is None:
print("List is empty")
else:
itr_node = self.head
while itr_node.next.next is not None:
itr_node = itr_node.next
if itr_node.next.next is None:
itr_node.next = None
def delete_at_index(self, index):
if self.head is None:
print("list is empty")
elif index == 0:
self.delete_at_beginning()
else:
pos = 0
itr_node = self.head
while itr_node.next is not None:
pos += 1
if pos == index:
itr_node.next = itr_node.next.next
break
itr_node = itr_node.next
if itr_node.next is None:
print("Out of bound", newline)
def element_in_middle(self):
if self.head is None:
print("List is empty")
else:
slow_ptr = fast_ptr = self.head
while fast_ptr and fast_ptr.next:
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next.next
self.head = slow_ptr
if __name__ == "__main__":
LinkedList_obj = LinkedList()
LinkedList_obj.append_at_first(7)
LinkedList_obj.append_at_first(6)
LinkedList_obj.append_at_first(5)
LinkedList_obj.print_linked_list()
print(newline)
LinkedList_obj.append_at_last(8)
LinkedList_obj.append_at_last(9)
LinkedList_obj.append_at_last(10)
LinkedList_obj.print_linked_list()
print(newline)
# LinkedList_obj.append_at_index(data_to_insert=6, index=5)
# LinkedList_obj.print_linked_list()
# print(newline)
#
# print("Total number of elements in list is", LinkedList_obj.total_elements_in_linked_list(), end='')
# print(newline)
#
# LinkedList_obj.delete_at_beginning()
# LinkedList_obj.print_linked_list()
# print(newline)
#
# LinkedList_obj.delete_at_last()
# LinkedList_obj.print_linked_list()
# print(newline)
#
# LinkedList_obj.delete_at_index(index=3)
# LinkedList_obj.print_linked_list()
# print(newline)
LinkedList_obj.element_in_middle()
LinkedList_obj.print_linked_list()
print(newline)
|
a47c53b4044019deb7c6c544806c442371c056c9 | pootatookun/Gravity-Engine | /Gravity Engine/Gravity_Maths/Kinematics.py | 1,661 | 4.1875 | 4 | '''
kinematics class used newtonian Kinematics to find out distance travelled by a mass,
under constant acceleration
'''
import numpy as nn
class kinematics(object):
'''
Usage: a = kinematics(delta_time, vector_array, initial_speed_array)
vector_array: contains effective force vector experienced by any member of the system
initial_speed_array: this array contains the velocity of every member of the system. which it
has attained till the last iteration.
Methods: distance_travelled_array()
initial_speed_array()
calc_distance_n_speed_gained()
'''
def __init__(self, time_leap, vector_array, initial_speed_array):
self.distance_gained_array = nn.zeros([len(vector_array)])
self.time_leapt = time_leap
self.resultant_vector_array = vector_array
self.initial_speed_array_ = initial_speed_array
def distance_travelled_array(self):
return self.distance_gained_array
def initial_speed_array(self):
return self.initial_speed_array_
def calc_distance_n_speed_gained(self):
for acceleration_index in range(len(self.resultant_vector_array)):
self.distance_gained_array[acceleration_index] = self.initial_speed_array_[acceleration_index] * self.time_leapt + (
self.resultant_vector_array[acceleration_index][0] * self.time_leapt**2)/2
self.initial_speed_array_[acceleration_index] = self.initial_speed_array_[acceleration_index] + \
self.resultant_vector_array[acceleration_index][0] * \
self.time_leapt
|
d3a77a9df9f1eb222c3fa6d923f9a131ccf6a976 | dsspasov/HackBulgaria | /week1/1-Python-OOP-problems-set/employee_hierarchy.py | 1,509 | 3.78125 | 4 | #employee_hierarchy.py
class Employee:
def __init__(self,name):
self.name = name
def getName(self):
return self.name
class HourlyEmployee(Employee):
def __init__(self,name,hourly_wage):
self.hourly_wage = hourly_wage
super(HourlyEmployee,self).__init__(name)
def weeklyPay(self, hours):
pay = 0
if hours<=0:
pay = 0
elif hours>0 and hours < 40:
pay = hours * self.hourly_wage
else:
pay = 40 * self.hourly_wage + (hours-40) * self.hourly_wage * 1.5
return pay
class SalariedEmployee(Employee):
def __init__(self,name,salary):
self.salary = salary
super(SalariedEmployee,self).__init__(name)
def weeklyPay(self, hours):
pay = self.salary/52
return pay
class Manager(SalariedEmployee):
def __init__(self,name,salary, bonus):
self.bonus = bonus
super(Manager,self).__init__(name,salary)
def weeklyPay(self, hours):
x = super(Manager,self).weeklyPay(hours)
pay = x + self.bonus
return pay
#def main():
# staff = []
# staff.append(HourlyEmployee("Morgan, Harry", 30.0))
# staff.append(SalariedEmployee("Lin, Sally", 52000.0))
# staff.append(Manager("Smith, Mary", 104000.0, 50.0))
# for employee in staff :
# hours = int(input("Hours worked by " + employee.getName() + ": "))
# pay = employee.weeklyPay(hours)
# print("Salary: %.2f" % pay)
#if __name__ == '__main__':
# main() |
eacf33b3950b3959ed13b0ee58523f6ce6f2bae7 | preethika-ajay/N-Queens | /Nqueensmodule.py | 1,093 | 4.03125 | 4 | #Fn to check if queen can be placed at the given position
def is_safe(board,row,col,n):
#For loop to check if the row on the left of the given row is safe
for i in range(col,-1,-1):
if board[row][i]=="Q":
return False
r=row
c=col
#While loop to check is lower diagnal is safe
while r<n and c>=0:
if board[r][c]=="Q":
return False
r+=1
c-=1
i=row
j=col
#While loop to check if upper diagnal is safe
while i>=0 and j>=0:
if board[i][j]=="Q":
return False
i-=1
j-=1
return True
#Fn to place queens in the required positions
def solveNQueens(board,col,n):
#Base condition for recursion
if col == n:
return True
#Recursive loop to place a queen satisfying all constraints in each column
for i in range(n):
if is_safe(board,i,col,n):
board[i][col]="Q"
if solveNQueens(board,col+1,n):
return True
board[i][col]="_"
return False
|
a9704080316b3f4433ce6f5a3b896f21431d86f5 | hahalima/PracticeProbs | /8.py | 140 | 3.984375 | 4 | def alphabetically(n):
items = n.split(',')
items = sorted(items)
return ','.join(items)
print alphabetically("without,hello,bag,world") |
fd9425f915b582edef606dd16f2cab30920db0ac | angrytang/python_book | /python-3/day6-3.py | 168 | 3.8125 | 4 | def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1, 3, 5))
a = (1, 2, 3, 5)
print(add(a)) |
963e8433bbf634518baf07e598ac30a72a4ee768 | Megg25/PROJEKT2 | /main.py | 3,006 | 3.59375 | 4 | import random
def tajne_cislo():
num = []
pocet_cisel = 4
i = 0
if pocet_cisel in range(1, 10):
while i < pocet_cisel:
cislo = random.randint(1, 9)
if cislo not in num:
num.append(cislo)
i += 1
return num
def tvoje_cislo_spravne(tvoje_cislo):
list_tvoje_cislo = list(tvoje_cislo)
kontrola_spravnosti = True
if list_tvoje_cislo[0] == str(0):
kontrola_spravnosti = False
print("Sorry, the number entered must not begin with ´0´.")
if len(list_tvoje_cislo) >= 5 or len(list_tvoje_cislo) <= 3:
print("Sorry, the number you entered does not have the required length")
kontrola_spravnosti = False
exit()
for n in list_tvoje_cislo:
if n.isalpha():
print("Sorry, the number entered cannot contain letters")
kontrola_spravnosti = False
return kontrola_spravnosti
def spravna_pozice(tvoje_cislo, vybrane_cislo):
list_tvoje_cislo = list(tvoje_cislo)
bulls = 0
cows = 0
if list_tvoje_cislo[0] == str(vybrane_cislo[0]):
bulls += 1
elif list_tvoje_cislo[0] in str(vybrane_cislo):
cows += 1
if list_tvoje_cislo[1] == str(vybrane_cislo[1]):
bulls += 1
elif list_tvoje_cislo[1] in str(vybrane_cislo):
cows += 1
if list_tvoje_cislo[2] == str(vybrane_cislo[2]):
bulls += 1
elif list_tvoje_cislo[2] in str(vybrane_cislo):
cows += 1
if list_tvoje_cislo[3] == str(vybrane_cislo[3]):
bulls += 1
elif list_tvoje_cislo[3] in str(vybrane_cislo):
cows += 1
return bulls, cows
def vyhodnotit(bulls):
hodnoceni = 0
if bulls == 0:
hodnoceni == 0
if bulls == 1:
hodnoceni += 1
if bulls == 2:
hodnoceni += 2
if bulls == 3:
hodnoceni += 3
if bulls == 4:
hodnoceni += 4
return hodnoceni
def statistika(soucet_pokusu):
vysledek = []
if soucet_pokusu >= 4:
vysledek.append("not so good")
elif soucet_pokusu >= 2:
vysledek.append("average")
elif soucet_pokusu >= 0:
vysledek.append("amazing")
return vysledek
def hlavni():
print("Hello, I've generated a random 4 digit number for you.\nLet s play a BULLS and COWS game.")
vybrane_cislo = tajne_cislo()
hodnoceni = 0
soucet_pokusu = 0
while hodnoceni != 4:
tvoje_cislo = input("Enter your 4 digit number: ")
kontrola_spravnosti = tvoje_cislo_spravne(tvoje_cislo)
if kontrola_spravnosti == False:
continue
bulls, cows = spravna_pozice(tvoje_cislo, vybrane_cislo)
print(f"{bulls} bulls, {cows} cows")
hodnoceni = vyhodnotit(bulls)
soucet_pokusu += 1
vysledek = statistika(soucet_pokusu)
if hodnoceni == 4:
print(f"Congratulation! You´ve guessed the right number in {soucet_pokusu} guesses.")
print(f"That´s{vysledek}")
exit()
print(hlavni())
|
07397021fc0bb0d4f10c2c6a2f0ead39390b7115 | Ziadpydev/PythonTutorials | /ifelif.py | 157 | 4.09375 | 4 | x = int(input("Enter a number between 1 and 10"))
if x==1:
print("One")
elif x==2:
print("Two")
elif x==3:
print("Three")
else:
print("Ten") |
c295856b36668cff3e7921f2acd252619dca393f | YazanAhmad18/data-structures-and-algorithms-python | /data_structures/stack-and-queue/stack_and_queue/stack_queue_animal_shelter.py | 1,965 | 3.734375 | 4 | class AnimalShelter:
def __init__(self):
self.rearcat=None
self.frontcat=None
self.reardog=None
self.frontdog=None
def enqueue(self,animal):
if animal.type=="cat":
if self.frontcat ==None:
self.frontcat=animal
self.rearcat=animal
else:
self.rearcat.next=animal
self.rearcat=animal
if animal.type=="dog":
if self.frontdog ==None:
self.frontdog=animal
self.reardog=animal
else:
self.reardog.next=animal
self.reardog=animal
def dequeue(self,pref):
if pref == "cat" and self.frontcat != None :
temp=self.frontcat
self.frontcat=temp.next
temp.next=None
return temp.name
elif pref == "dog" and self.frontdog != None :
temp=self.frontdog
self.frontdog=temp.next
temp.next=None
return temp.name
else:
return 'null'
def __str__(self , pref):
content="Null"
if pref == "cat":
current = self.rearcat
elif pref == "dog":
current = self.reardog
else :
return content
while current:
content+= f"-> {{{str(current.name)}}}"
current=current.next
return content
class Cat():
def __init__(self,name):
self.name=name
self.type='cat'
self.next= None
class Dog():
def __init__(self,name):
self.name=name
self.type='dog'
self.next= None
if __name__=="__main__" :
soker = Cat('soker')
bull = Dog('bull')
animal_shelter = AnimalShelter()
animal_shelter.enqueue(bull)
animal_shelter.enqueue(soker)
print(animal_shelter.__str__("dog"))
print(animal_shelter.__str__("cat")) |
4a413666d1d6d9d313a4ae4f66b3599a3827c054 | FedoseevaAlexandra/string.2 | /problema.1.py | 147 | 3.828125 | 4 | cuv=str(input('introdu cuv :'))
k=str(input('introdu o litera :'))
if len(k)==1:
for i in cuv:
x=cuv.replace(i,k)
print(x) |
6301c12dccb74b7c684564268560a2df412dd821 | OskitarSnchz/POO2 | /poo2/vehiculo/Vehiculo.py | 3,242 | 4.125 | 4 | '''
Created on 26 feb. 2019
Crea la clase Vehiculo, así como las clases Bicicleta y Coche como subclases
de la primera. Para la clase Vehiculo, crea los atributos de clase
vehiculosCreadosy kilometrosTotales, así como el atributo de instancia
kilometrosRecorridos. Crea también algún método específico para cada una de
las subclases. Prueba las clases creadas mediante un programa con un menú
como el que se muestra a continuación:
VEHÍCULOS ========= 1. Anda con la bicicleta 2. Haz el caballito con la
bicicleta 3. Anda con el coche 4. Quema rueda con el coche 5. Ver kilometraje
de la bicicleta 6. Ver kilometraje del coche 7. Ver kilometraje total 8.
Salir Elige una opción (1-8):
@author: Álvaro Leiva Toledano
'''
class Vehiculo:
# atributos de la clase
contadorVehiculos = 0
kmTotales = 0
# Constructor de la clase vehiculo
def __init__(self):
self.km = 0
self.contadorVehiculos += 1
# getter de los kilometros totales de todos los vehiculos
def getKmTotales(self):
return Vehiculo.kmTotales
# getter de kilometros del vehiculo
def getKM(self):
return self.km
def anda(self, kilometros):
self.km += kilometros
Vehiculo.kmTotales += kilometros
class Bicicleta(Vehiculo):
tipoFrenos = "por defecto"
def __init__(self, frenos):
Vehiculo.__init__(self)
self.tipoFrenos = frenos
def hacerCaballito(self):
print("¡La bicicleta está haciendo el caballito!")
class Coche(Vehiculo):
color = "blanco"
def __init__(self, color):
Vehiculo.__init__(self)
self.color = color
def quemarRueda(self):
print("¡Chechuuu haz un derrapeee!")
def mostrarMenu():
print("Menú de opciones")
print("----------------")
print("1. Introducir KM Bicicleta")
print("2. Hacer Caballito.")
print("3. Introducir KM Coche.")
print("4. Quemar Rueda")
print("5. Km total con la Bicicleta")
print("6. Km total con el Coche.")
print("7. Km total con los Vehiculos.")
print("8. Terminar.")
if __name__ == "__main__":
coche1 = Coche("rojo")
bicicleta1 = Bicicleta("pastilla")
while True:
mostrarMenu()
opcion = input("Indica la opción: ")
if opcion == "1":
km = int(input("Introduce los KM recorridos con la bicicleta: \n"))
bicicleta1.anda(km)
elif opcion == "2":
bicicleta1.hacerCaballito()
elif opcion == "3":
km = int(input("Introduce los KM recorridos con su coche: \n"))
coche1.anda(km)
elif opcion == "4":
coche1.quemarRueda()
elif opcion == "5":
print("Ha recorrido ", bicicleta1.getKM(), " kms con su bicicleta.")
elif opcion == "6":
print("Ha recorrido ", coche1.getKM(), " kms con su coche.")
elif opcion == "7":
print("Ha recorrido ", Vehiculo.getKmTotales(), " kms en total.")
elif opcion == "8":
print("Saliendo")
break
|
56f5e0ac22dc5ab0086e41e7b8cd56d7e0cbdfe0 | prabodhtr/ComputerSecurityS8 | /complexityCalc.py | 1,406 | 3.78125 | 4 | import math
import matplotlib.pyplot as plt
import numpy
# Function to count total bits in a number
def plotGraph(data):
x_val = numpy.arange(1,10001,1)
y_val = [item[0] for item in data]
plt.plot(x_val, y_val)
plt.scatter(x_val, y_val, c = "black", marker= '^', label = "LenofNum")
y_val = [item[1] for item in data]
plt.plot(x_val, y_val)
plt.scatter(x_val, y_val, c = "red", marker= '+', label = "LenOfRoot")
y_val = [item[2] for item in data]
plt.plot(x_val, y_val)
plt.scatter(x_val, y_val, c = "green", marker= '*', label = "logVal")
y_val = [item[0]/2 for item in data]
plt.plot(x_val, y_val)
plt.scatter(x_val, y_val, c = "blue", marker= '+', label = "halfVal")
plt.grid()
plt.legend()
plt.show()
def countTotalBits(num, data):
# convert number into it's binary and
numRoot = int(math.sqrt(num))
# remove first two characters 0b.
binaryNum = bin(num)[2:]
binaryNumRoot = bin(numRoot)[2:]
logNum = math.log2(len(binaryNum))
data.append([len(binaryNum), len(binaryNumRoot), logNum])
# print(str(len(binaryNum)) + " - " + str(len(binaryNumRoot)) + " (" + str(logNum) + " )")
# Driver program
if __name__ == "__main__":
data = []
for num in range(1,10001):
countTotalBits(num, data)
plotGraph(data)
# print([item[0] for item in data])
|
02cc0bbca8500b695d6b7f772907734300c51d58 | NilsFriman/nilslibrary | /nilslibrary.py | 2,327 | 4.375 | 4 | # Takes input in form of a text that will appear to the user when asked for input, and gives back an integer value only.
def intinput(text):
done = False
while not done:
finaltext = input(text)
try:
finaltext = int(finaltext)
done = True
except Exception:
print("Sorry, you can only enter an integer. For example, 4 or -11.")
return finaltext
# Takes input in form of a text that will appear to the user when asked for input, and gives back a float value only.
def floatinput(text):
done = False
while not done:
finaltext = input(text)
try:
finalfloat = float(finaltext)
done = True
except Exception:
print("Sorry, you can only enter an float. For example, 4.0 or -11.7.")
return finalfloat
# Takes input in form of a text that will appear to the user when asked for input, and gives back a valid string without
# trailing newline or spaces
def stringinput(text):
done = False
while not done:
finaltext = input(text)
if finaltext != "":
finaltext.rstrip()
done = True
else:
print("Sorry, you have to enter some text.")
return finaltext
# Takes input in the form of question and the default answer (either True (Yes) or False (No)),
# and returns True if the user inputs something other than the opposite of default, False if anything else
def boolinput(text, default):
done = False
while not done:
if default:
finaltext = input(text + " (Y/n)\n")
finaltext.lower()
if finaltext == "n":
dabool = False
done = True
else:
dabool = True
done = True
elif not default:
finaltext = input(text + " (y/N)\n")
finaltext.lower()
if finaltext == "y":
dabool = False
done = True
else:
dabool = True
done = True
else:
print("Hey programmer! When you call function boolinput, you must use the format boolinput(text, default),")
print("where default is either True or False and shows which one of the two is the default one.")
return dabool |
200bb0064780ca5ff5b8e419f05e18638a59a409 | orangeblock/fanorona | /src/utils.py | 612 | 3.59375 | 4 | #
#
# Helper functions used by the modules.
#
#
import pygame
def load_image(path):
return pygame.image.load(path).convert_alpha()
def tsub(tup1, tup2):
""" Subtracts tup1 elements from tup2 elements. """
return (tup1[0]-tup2[0], tup1[1]-tup2[1])
def tadd(tup1, tup2):
""" Adds the elements of tup1 and tup2. """
return (tup1[0]+tup2[0], tup1[1]+tup2[1])
def tflip(tup):
"""
Flips tuple elements.
This is useful for list to screen coordinates translation.
In list of lists: x = rows = vertical
whereas on screen: x = horizontal
"""
return (tup[1], tup[0]) |
71911562df07e70e7114eeeae2ce0ee585091269 | kennedycAlves/pythonlab | /exer_if.py | 203 | 3.953125 | 4 | a = int(input("Informe a velovidade de do veículo: "))
if a > 110:
b = a - 110
b = b * 5
print ("Veículo multado no valor de", b, "Reais")
else:
print ("O veículo não foi multado")
|
5fe4d95bd569fb5c9844abd075c8eb69f6df70e4 | Aasthaengg/IBMdataset | /Python_codes/p02843/s348339150.py | 203 | 3.625 | 4 | import sys
input = sys.stdin.readline
def main():
X = int(input())
NUM = X//100
A = X%100
if A <= NUM*5:
print(1)
else:
print(0)
if __name__ == '__main__':
main() |
52822882e7050f48d802b81c295d28da56ed3b51 | MP076/Python_Practicals_02 | /09_User_Input/29_parrot.py | 229 | 3.953125 | 4 | # How the input() Function Works
# 153
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# O/p:
# Tell me something, and I will repeat it back to you: tell me something
# tell me something
|
9600828491147fd3f81a71618a6bcfc46119f4ee | rduvalwa5/BasicPython | /Collections_List_src/mapped_dictionary_example.py | 1,085 | 3.53125 | 4 | '''
Created on Mar 15, 2016
@author: rduvalwa2
'''
class map_dictionary:
def __init__(self):
# self.t_name = t_name
self.name = {}
print(type(self.name))
def add_item(self,element, value):
self.name[element] = value
def print_tuple(self):
print(self.name)
def remove_item(self,key):
# print('key ', key, self.name[key])
try:
del self.name[key]
except KeyError as ex:
print('KeyError exception',ex)
if __name__ == "__main__":
tname = "myTup"
myTup = map_dictionary()
myTup.add_item('length', 10)
myTup.add_item('width', 5)
myTup.add_item('depth', 6)
print(myTup.name['length'])
cube = myTup.name['length'] * myTup.name['width'] * myTup.name['depth']
myTup.add_item('cubed', cube)
myTup.print_tuple()
print(dir(myTup))
print(myTup.__dir__())
print(myTup.__dict__)
myTup.remove_item('big')
myTup.remove_item('length')
print(myTup.__dict__) |
a6fbe55c63c5cecdf621bac4ce1de4166507e52a | Kivike/nlp-project | /app/map/heat_map.py | 2,997 | 3.53125 | 4 | from pandas import DataFrame
import plotly.graph_objects as go
from enum import Enum
class MapboxStyle(Enum):
"""Enum value for mapbox styles.
"""
STAMEN_TERRAIN = "stamen-terrain"
OPEN_STREET_MAP = "open-street-map"
DARK = "dark"
CARTO_POSITRON = "carto-positron"
class HeatMap:
"""Simple browser-based heat map. Uses Plotly Python API for launching the plot.
See the [demo](https://plot.ly/python/mapbox-density-heatmaps/) and
[Densitymapbox docs](https://plot.ly/python/reference/#densitymapbox) online.
Arguments:
data {DataFrame} -- The data to be plotted
Keyword Arguments:
radius {int} -- The radius of plot marker on the map {Default: 10}
style {MapboxStyle} -- Style of the map {Default: MapboxStyle.STAMEN_TERRAIN}
access_token {str} -- Mapbox access token {Default: None}
Example of usage::
# Data has to contain Latitude and Longitude columns
data = load_data()
heat_map = HeatMap(data, style = MapboxStyle.OPEN_STREET_MAP)
heat_map.show()
"""
LAT = 'Latitude'
LON = 'Longitude'
def __init__(
self,
data: DataFrame,
radius: int = 10,
style: MapboxStyle = MapboxStyle.STAMEN_TERRAIN,
access_token: str = None):
assert self.LAT in data.columns, 'Data has to contain column {}'.format(self.LAT)
assert self.LON in data.columns, 'Data has to contain column {}'.format(self.LON)
if style == MapboxStyle.DARK:
assert access_token is not None, 'Access token has to be ' + \
'provided for dark mapbox tiles'
self.data = data
self.fig = go.Figure(
go.Densitymapbox(
lat = data[self.LAT],
lon = data[self.LON],
radius = radius
)
)
self.style = style
self.access_token = access_token
def show(self, **kwargs):
"""Show the map in the default browser. All given keyword arguments are
passed down to `self.fig.update_layout` call before the figure is shown.
"""
min_lat = self.data[self.LAT].min()
max_lat = self.data[self.LAT].max()
min_lon = self.data[self.LON].min()
max_lon = self.data[self.LON].max()
avg_lat = min_lat + (max_lat - min_lat) / 2
avg_lon = min_lon + (max_lon - min_lon) / 2
# TODO: Is it possible to calculate the zoom properly?
zoom = 6
self.fig.update_layout(
mapbox_style = self.style.value,
mapbox_center_lat = avg_lat,
mapbox_center_lon = avg_lon,
mapbox_zoom = zoom,
margin = {
"r": 0,
"t": 0,
"l": 0,
"b": 0
},
# Not necessarily needed
mapbox_accesstoken = self.access_token,
**kwargs
)
self.fig.show()
|
b506089ffadcf5d310d4e0e0a937d4f32b203289 | Ruslan5252/all-of-my-projects-byPyCharm | /курсы пайтон модуль 7/задание 29.py | 250 | 3.765625 | 4 | def dva_chisla(*args):
a=int(input("a="))
b=int(input("b="))
if a%2==0 and b%2==0:
return a*b
elif a%2==1 and b%2==1:
return a+b
elif a%2==1 :
return a
elif b%2==1:
return b
print(dva_chisla())
|
15bd61b556f719421adb8dc46a239c37678b30ab | Logesh-vasanth101/jeya | /reversenum.py | 96 | 3.703125 | 4 | n1=int(input("Enter the number"))
d1=0
while(n1>0):
r1=n1%10
d1=d1*10+r1
n1=n1//10
print(d1)
|
705c522ed09a4e1dd8b783c4956f6bbb6537fc61 | brbbrb/python-challenge | /PyBank/main.py | 2,256 | 3.921875 | 4 | # PyBank
# Import the os module
# This will allow us to create file path to budget data
import os
# Import the module for reading csv files
import csv
# os.path.join would not work, so I had to use full CPU location
#csvpath = os.path.join('Resources','budget_data.csv')
csvpath = '/Users/bradleybarker/Documents/GT_Boot_Camp/GT_Homework/Week_03_Python/python-challenge/PyBank/Resources/budget_data.csv'
# Create lists
months = []
profits = []
monthly_change = []
# Reading using CSV module
with open(csvpath) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Read the header row first (skip this step if there is no header)
csv_header = next(csvreader)
#print(f"CSV Header: {csv_header}")
# Set last month to 0
last_month = 0
# Read each row of data after the header
for row in csvreader:
month = str(row[0])
profit = int(row[1])
#print(row)
# Add data to month, profit, and montly_change lists
months.append(month)
profits.append(profit)
change = profit - last_month
monthly_change.append(change)
last_month = profit
#Determine final calculations
total_months = len(months)
#print(total_months)
total_profit = sum(profits)
#print(total_profit)
avg = round((sum(monthly_change)/len(monthly_change)),2)
#print(avg)
maxprofit = max(profits)
#print(maxprofit)
minprofit = min(profits)
#print(minprofit)
maxrow = profits.index(maxprofit)
#print(maxrow)
minrow = profits.index(minprofit)
#print(minrow)
maxmonth = str(months[maxrow])
#print(maxmonth)
minmonth = str(months[minrow])
#print(minmonth)
# Message
with open ("pybank_financial_analysis.txt","w")as file:
file.write("Financial Analysis" "\n")
file.write("------------------------" "\n")
file.write(f'Total Months: {total_months}' "\n")
file.write(f'Total: ${total_profit}' "\n")
file.write(f'Average Change: ${avg}' "\n")
file.write(f'Greatest Increase in Profits: {maxmonth} (${maxprofit})' "\n")
file.write(f'Greatest Decrease in Profits: {minmonth} (${minprofit})')
file = open("pybank_financial_analysis.txt","r")
print(file.read()) |
a7e642bd72f6c4bb372a7c3ac3e4592e5dbc88db | knishant09/LearnPythonWorks_2 | /Hackerrank/sock_merchant.py | 660 | 3.84375 | 4 | from collections import Counter
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
print(ar)
print(n)
dict_1 = dict(Counter(ar))
print(dict_1)
print(dict_1.values())
# print(type(dict_1.values()))
# print(len(dict_1.values()))
#print(sum(dict_1.values()))
print("*********************")
sum=0
for i in dict_1.values():
sum = sum + int(i // 2)
print(sum)
return sum
if __name__ == '__main__':
n = int(input("Enter the number of socks:"))
ar = list(map(int, input("Ënter the list of socks:").rstrip().split()))
result = sockMerchant(n, ar)
print(result) |
41a515bdc66d89d4a70108e01fb57491c103fde0 | dundunmao/LeetCode2019 | /708. Insert into a Cyclic Sorted List.py | 1,022 | 4 | 4 | # Definition for a Node.
class Node:
def __init__(self, val, next):
self.val = val
self.next = next
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
if not head:
node = Node(insertVal, None)
node.next = node
return node
# 找到最大node
max_node = head
while max_node.next != head and max_node.val <= max_node.next.val:
max_node = max_node.next
# 找到最小node
min_node = max_node.next
cur = min_node
if insertVal >= max_node.val or insertVal <= min_node.val:
node = Node(insertVal, min_node)
max_node.next = node
else:
while cur.next.val < insertVal:
cur = cur.next
new_node = Node(insertVal, cur.next)
cur.next = new_node
return head
s = Solution()
a = None
print(s.insert(a, 2))
a = Node(1, None)
b = Node(4, a)
c = Node(3,b)
a.next = c
print(s.insert(a, 2))
|
362d71f2c73c886573399edfde480c4d9abb2593 | Alexanderklau/Algorithm | /Everyday_alg/2021/06/2021_06_08/coin-change.py | 1,334 | 3.515625 | 4 | # coding: utf-8
__author__ = "lau.wenbo"
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
你可以认为每种硬币的数量是无限的。
示例 1:
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1
示例 2:
输入:coins = [2], amount = 3
输出:-1
示例 3:
输入:coins = [1], amount = 0
输出:0
示例 4:
输入:coins = [1], amount = 1
输出:1
示例 5:
输入:coins = [1], amount = 2
输出:2
"""
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
mono = dict()
def dp(n):
if n in mono:
return mono[n]
if n == 0:
return 0
if n < 0:
return -1
res = float("INF")
for coin in coins:
subproblem = dp(n - coin)
if subproblem == -1:
continue
res = min(res, 1 + subproblem)
mono[n] = res if res != float("INF") else -1
return mono[n]
return dp(amount) |
e87350eafa3570c11b2395ad889d816ced9aff0f | jdibble21/Random-Cipher | /cipher.py | 3,288 | 3.953125 | 4 | #/usr/bin/python3
from random import randrange
import time
import ast
keyMapperFile = "exampleKeyMap.txt"
def main():
print("=== Welcome to python cipher v0.1.0 ===")
userInput = ""
while(True):
print("\nCurrent encrypt/decrypt key mapper is: " + keyMapperFile)
userInput = input("\nChoose a option (or q to exit):\n0 Specify an existing cipher key mapping to use\n1 Generate a cipher key\n2 Encrypt some input or text file \n3 Decrypt some input or a text file\n4 Help and Instructions\n\n")
if userInput == "q":
break
if userInput == "0":
filename = input("Enter filename (.txt) to use an existing key mapping\n")
setKeyMapper(filename)
if userInput == "1":
userInput = input("Enter a filename for the generated key to save to,\ninclude filepath info if applicable\n\n")
generateKey(userInput)
if userInput == "2":
userInput = input("Enter some text to encrypt: \n\n")
encrypt(userInput)
def generateKey(newFile):
#associate letters of alphabet with a random character and save mapped characters to text file
print("Generating new key mapping...")
time.sleep(1.5)
charsToTranslate = ["a","b","c","d", "e", "f" , "g", "h","i","j","k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z"," "]
charsToChoose = ["a", "b", "c" , "d", "A" , "B" , "C" , "E", "Z", "x" , "O","o", "1", "!", "2", "@", "3", "#",
"4", "$", "5","&", "9" , "^", "/", "y", "v"]
chosenIndex = 0
keyMap = {}
for i in range(0,len(charsToTranslate)):
currentChar = charsToTranslate[i]
chosenIndex = randrange(len(charsToChoose))
currentTranslate = charsToChoose[chosenIndex]
charsToChoose.pop(chosenIndex)
keyMap[currentChar] = currentTranslate
print("Saving key map to " + newFile+".txt...")
time.sleep(1)
saveFile = open(newFile+".txt","w")
saveFile.write(str(keyMap))
saveFile.close()
print("Done\n")
time.sleep(2)
def encrypt(toTranslate):
#replace real string values with associated key values
global keyMapperFile
print("Getting key map from " + keyMapperFile+"...")
time.sleep(0.8)
with open(keyMapperFile) as f:
data = f.read()
keyDict = ast.literal_eval(data)
encryptedString = ""
currentEncryptChar = ""
print("Encrypting...")
time.sleep(1.2)
for i in range(0,len(toTranslate)):
currentEncryptChar = keyDict[toTranslate[i]]
encryptedString = encryptedString + currentEncryptChar
print("Done")
time.sleep(0.5)
print("Encrypted string is below\n")
print(encryptedString+"\n\n")
time.sleep(2)
def decrypt(toDecrypt,keyMap):
key = open(r"cipherKey/keyMap.txt", "r")
decryptedString = ""
for i in range(0,len(toDecrypt)):
for i in key.readlines():
currentLine = key.readlines()
realLetter = currentLine[0]
encryptedLetter = currentLine[1]
if(toDecrypt == encryptedLetter):
decryptedString = decryptedString + decryptedString
print("Decrypted String is: " + decryptedString)
def setKeyMapper(filename):
global keyMapperFile
keyMapperFile = filename
main()
|
0a57f38bdb9e7febcf6853b53a9c028e0fd0f303 | csws79/SummerStudy_Python | /0702 day1/day1.py | 318 | 3.890625 | 4 | A = raw_input("subject1: ")
a = input("score: ")
B = raw_input("subject2: ")
b = input("score: ")
C = raw_input("subject3: ")
c = input("score: ")
sum = a + b + c
aver = round(float(sum) / 3, 3)
print A + " " + str(a)
print B + " " + str(b)
print C + " " + str(c)
print "sum: " + str(sum)
print "average: " + str(aver) |
3c0d16d9135d9e582dfb13874726692af22daf8a | ChangHChen/python | /Introduction to Python/09(6.22)/1.py | 1,132 | 3.546875 | 4 | from tkinter import Frame, StringVar, Label, Entry, Button, TOP, LEFT, END
class CountDownTimer(Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.master.title("Count Down Timer")
self.time_left = StringVar()
Label(self, textvariable=self.time_left, font=("Helvetica", 24)).pack(side=TOP)
self.input = Entry(self, font=("Helvetica", 24))
self.input.pack(side=TOP)
frame = Frame(self)
frame.pack()
Button(frame, text="start", command=self.activate, font=("Helvetica", 18)).pack(side=LEFT)
Button(frame, text="quit", command=self.master.destroy, font=("Helvetica", 18)).pack()
def activate(self):
self.set()
self.after(1000, self.count_down)
def set(self):
self.trans = int(self.input.get())
self.time_left.set(int(self.trans))
self.input.delete(0, END)
def count_down(self):
if self.trans > 0:
self.trans -= 1
self.time_left.set(self.trans)
self.after(1000, self.count_down)
CountDownTimer().mainloop()
|
c88e4de0b4600ff390457d16e82d0b0a26a5b4d3 | notexactlyawe/microbit-snake | /snake.py | 3,011 | 4.3125 | 4 | from random import randint
from microbit import *
class Snake:
""" This class contains the functions that operate
on our game as well as the state of the game.
It's a handy way to link the two.
"""
def __init__(self):
""" Special function that runs when you create
a "Snake", ie. when you run
game = Snake()
init stands for "Initialisation"
"""
self.direction = "up"
# snake is a list of the pixels that the snake is at
self.snake = [[2, 2]]
# food is the co-ords of the current food
self.food = [0, 2]
# whether or not to end the game, used after update
self.end = False
def handle_input(self):
""" We'll use this function to take input from the
user to control which direction the snake is going
in.
"""
x = accelerometer.get_x()
y = accelerometer.get_y()
# abs is the absolute function eg -1 => 1, 1 => 1
if abs(x) > abs(y):
if x < 0:
self.direction = "left"
else:
self.direction = "right"
else:
if y < 0:
self.direction = "up"
else:
self.direction = "down"
def update(self):
""" This function will update the game state
based on the direction the snake is going.
"""
# copy the old head
new_head = list(self.snake[-1])
if self.direction == "up":
new_head[1] -= 1
elif self.direction == "down":
new_head[1] += 1
elif self.direction == "left":
new_head[0] -= 1
elif self.direction == "right":
new_head[0] += 1
# make sure co-ords within bounds
if new_head[0] < 0:
new_head[0] = 4
elif new_head[0] > 4:
new_head[0] = 0
if new_head[1] < 0:
new_head[1] = 4
elif new_head[1] > 4:
new_head[1] = 0
if new_head in self.snake:
self.end = True
self.snake.append(new_head)
if new_head == self.food:
self.food = [randint(0, 4), randint(0, 4)]
# make sure we're not generating the food in the snake
while self.food in self.snake:
self.food = [randint(0, 4), randint(0, 4)]
else:
self.snake.pop(0)
def draw(self):
""" This makes the game appear on the LEDs. """
display.clear()
display.set_pixel(self.food[0], self.food[1], 5)
for part in self.snake:
display.set_pixel(part[0], part[1], 9)
# game is an "instance" of Snake
game = Snake()
# this is called our "game loop" and is where everything
# happens
while True:
game.handle_input()
game.update()
if game.end:
display.show(Image.SAD)
break
game.draw()
# this makes our micro:bit do nothing for 500ms
sleep(500)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.