blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
69e5a631bd60c020499e7d5eda95bb63bb5430a3 | cfcmarc/PythonSandbox | /coinflip.py | 844 | 3.875 | 4 | import random
heads = 1
tails = 0
valid_guesses = [heads, tails]
correct_statement = "Correct! The coin flip landed "
incorrect_statement = "incorrect! The coin flip landed "
guess_list = []
coin_flip_otcme = random.randint(0,1)
for guess in valid_guesses:
def coin_flip(user_guess):
if coin_flip_otcme == user_guess:
if user_guess == heads:
return (correct_statement + heads + "!")
else:
return (correct_statement + tails + "!")
elif coin_flip_otcme == 0:
if user_guess == tails:
return (correct_statement + tails + "!")
elif user_guess == tails:
return(correct_statement + tails + "!")
print(coin_flip(heads))
print(coin_flip(tails))
print(coin_flip("bat"))
print(coin_flip("Heads"))
print(coin_flip("Tails")) |
fe718d73634e8fa02f5064aaeecfac26edafa6c0 | joelmontpetit/us-states-game-start | /main.py | 1,964 | 3.796875 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("50_states.csv")
all_state = data.state.to_list()
guessed_states = []
while len(guessed_states) < 50:
answer_state = screen.textinput(title=f"{len(guessed_states)}/50 States Correct", prompt="What's another state's name?").title()
if answer_state == "Exit":
missing_states = []
for state in all_state:
if state not in guessed_states:
missing_states.append(state)
new_data = pandas.DataFrame(missing_states)
new_data.to_csv("states_to_learn.csv")
break
if answer_state in all_state:
(answer_state)
t = turtle.Turtle()
t.hideturtle()
t.penup()
state_data = data[data.state == answer_state]
t.goto(int(state_data.x), int(state_data.y))
t.write(answer_state)
# t.write(state_data.state.item())
#if right:
#create a turtle to write the name of the state at X Y coordinate
# answer_l = answer_state.lower()
# state_check = data["state"]
# state_list = state_check.to_list()
# low_state = [item.lower() for item in state_list]
# print(state_list)
# # state_set = set(state_list)
# def check_answer():
# if(answer_state.lower() in low_state):
# print("fuck Yeah")
# # print(data.state == answer_state)
#
# return answer_state.capitalize()
# # print(data.state == answer_state)
# else:
# print("Fuck")
#
# fucker = answer_state.capitalize()
# print(fucker)
#
# def check_in_data():
# if data.state != fucker:
# return
# print("yahoo")
#
#
# check_answer()
# check_in_data()
# for i in state_list:
# if(i == "California") :
# print("Element Exists")
# if answer_l in state_list:
# print("WTF")
# else:
# print("Shieeet")
|
d96abaa8b65525a7a3cea60f6e224ac6e2e939f3 | fergatica/python | /rubiks_cube_contest_average.py | 539 | 3.953125 | 4 | def list_function():
my_list = []
for i in range(5):
x = float(input("Enter the time for performance " + str(i+1) + ": "))
my_list.append(x)
i += 1
my_list.sort()
my_list = my_list[1:-1]
return my_list
def main():
my_list = list_function()
index = 0
total = 0
while index < len(my_list):
total += my_list[index]
index += 1
average = total / (len(my_list))
print("The official competition score is " + "{:.2f}".format(average) + " seconds.")
main() |
48090935c800fcf07ff12597adc8d943a9fbcfc0 | byfuls/python | /namedtuple/namedtuple-dict.py | 982 | 4.125 | 4 | from collections import namedtuple
class data:
def __init__(self, name):
self.__name = name;
self.__value1 = 1;
self.__value2 = 2;
@property
def name(self):
return self.__name
@property
def val1(self):
return self.__value1
@property
def val2(self):
return self.__value2
# prepare input data
a = data('a');
b = data('b');
c = data('c');
d = data('d');
# prepare namedtuple
titles = namedtuple('titles', 'a b c d')
# input class data to namedtuple
namedtuple_dict = titles(a,b,c,d)
# show input data
print(namedtuple_dict)
# get input data
print(f'a data: {namedtuple_dict.a}')
print(f'a data.name: {namedtuple_dict.a.name}')
print(f'a data.val1: {namedtuple_dict.a.val1}')
print(f'a data.val2: {namedtuple_dict.a.val2}')
print(f'b data: {namedtuple_dict.b}')
print(f'b data.name: {namedtuple_dict.b.name}')
print(f'b data.val1: {namedtuple_dict.b.val1}')
print(f'b data.val2: {namedtuple_dict.b.val2}') |
836898b7409c3b83c17c2d471d8c759853bf30e7 | gajanlee/leetcode | /python/840. Magic Squares In Grid.py | 1,297 | 4.1875 | 4 | """
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given an N x N grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: [[4,3,8,4],
[9,5,1,9],
[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
438
951
276
while this one is not:
384
519
762
In total, there is only one magic square inside the given grid.
Note:
1 <= grid.length = grid[0].length <= 10
0 <= grid[i][j] <= 15
"""
class Solution:
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def get(i, j):
return grid[i][j]
if len(grid) < 3: return 0
res = 0
for i in range(len(grid)-2):
for j in range(len(grid)-2):
arr = [get(_row, _col) for _row, _col in itertools.product((i, i+1, i+2), (j, j+1, j+2))]
if sorted(arr) == [1, 2, 3, 4, 5, 6, 7, 8, 9]:
if arr[0]+arr[3]+arr[6] == arr[1]+arr[4]+arr[7] == arr[2]+arr[5]+arr[8] == arr[0]+arr[4]+arr[8] == arr[2]+arr[4]+arr[6]:
res += 1
return res |
2bff1ef8bddbd0ac6c7d77982e2b03fa6cd42c71 | lanl/BEE | /beeflow/data/cwl/cwl_validation/ml-workflow/machine_learning/read_dataset.py | 1,054 | 3.546875 | 4 | """Read Data Set."""
import pickle
import click
# import json
import pandas as pd
# import numpy as np
# from sklearn.linear_model import LinearRegression
@click.command()
@click.argument('y3', type=str) # y3 is the input argument for path to dataset
def reader(y3):
"""Reader."""
dataset = pd.read_csv(y3)
print("this dataset", dataset)
dataset['experience'].fillna(0, inplace=True)
dataset['test_score'].fillna(dataset['test_score'].mean(), inplace=True)
# Extracting rows (X-> independent variables and Y-> dependent/target variable)
X = dataset.iloc[:, :3] # Extracting first three columns from the dataset
print('My X', X)
Y = dataset.iloc[:, -1] # Extracting last column from the dataset for target variable
# Exporting X and Y as pickle files on to the disk
pickle.dump(X, open("MyX.p", "wb"))
pickle.dump(Y, open("MyY.p", "wb"))
df1 = X.to_json()
df2 = Y.to_json()
if __name__ == '__main__':
reader(y3="")
# Ignores preserving code for now
# pylama:ignore=C0103,R1732,W0612
|
53a0b8fb02bb3f556aeaa7182d41c558fefa2479 | jsonw99/transfer_learning_inceptionv3_shoes | /download_image.py | 2,178 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import urllib.request
import sys
import getopt
'''
the script may read the url lists from the directory ./imageUrl .
and download the images to corresponding folders within the directory ./imageDownload .
'''
def main(total_number, size):
url_dir = "./imageUrl/"
image_dir = "./imageDownload/"
file_names = os.listdir(url_dir)
for curr_file in file_names:
with open(os.path.join(url_dir, curr_file), "r") as f:
curr_list = f.read().split("\n")
currClass = curr_file.replace(".txt", "", 1)
download_dir = os.path.join(image_dir, currClass)
image_number = 0
if os.path.exists(download_dir):
image_number = len(os.listdir(download_dir))
print(str(image_number) + " images have already been downloaded.")
else:
os.makedirs(download_dir)
i = 0
while image_number < total_number and i < len(curr_list):
curr_url = curr_list[i].split("?")[0] + "?odnHeight=" + size + "&odnWidth=" + size + "&odnBg=ffffff"
# print(curr_url)
curr_file = os.path.join(download_dir, curr_list[i].split("?")[0].split("/")[-1])
if os.path.exists(curr_file):
print("processing record " + str(i) + ": a duplicate image -- " + curr_file)
else:
try:
urllib.request.urlretrieve(curr_url, curr_file)
image_number += 1
print("processing record " + str(i) + ": download image" + str(image_number) + " for " + currClass)
except:
print(arg)
i += 1
if __name__ == "__main__":
n = 10
size = "180" # try 450 or 180, not all values are valid
try:
opts, args = getopt.getopt(sys.argv[1:], "n:s:", ["number=", "size="])
except getopt.GetoptError:
pass
for opt, arg in opts:
if opt in ("-n", "--number"):
n = int(arg)
elif opt in ("-s", "--size"):
size = arg
main(n, size)
|
dd24745bd07c3a47a73133546e2095ff00792808 | AndrePina/Python-Course-Work | /factorial.py | 167 | 3.96875 | 4 |
def factorial(n):
result = 1
for x in range(1,n):
result = result + (result * x)
return result
for n in range(0,10):
print(n, factorial(n )) |
c792fcf3b9f86cdbd19fa9f8129aaf3be618dca0 | simongarisch/pxtrade | /tests/test_strategy2.py | 4,212 | 3.765625 | 4 | """
Here we test a basic strategy that includes an indicator and FX rate movements.
We'll start with an ($100K) AUD denominated portfolio and buy 100 shares of SPY
only if the VIX < 26.
Also, buying in SPY will make us short USD.
Generate funding trades, to be executed the day after we buy SPY, so that
we aren't short USD.
For the sake of testing we'll focus on the dates 1st Sep -> 1st Oct.
Points to note:
- We'll buy 100 shares of SPY @337.11 on Sep 14th VIX=25.85
- Hold until Oct 1st when SPY=337.04, AUDUSD=0.7167
- Because our portfolio is denominated in AUD we need to calculate AUD prices.
- So buying SPY at 337.11 (Sep 14th price) / 0.729682 (fx 15th) = AUD 462
- And holding to a value of 337.04 / 0.716651 = AUD 470.30
- PNL will be $8.30 (= 470.30 - 462.00) for each of 100 shares purchased.
"""
from datetime import date
import pandas as pd
from pxtrade import Trade
from pxtrade.assets import reset, Stock, Cash, FxRate, Portfolio
from pxtrade.backtest import Backtest
from pxtrade.strategy import Strategy
from pxtrade.events.yahoo import load_yahoo_prices
from pxtrade.compliance import Compliance, UnitLimit
from pxtrade.history import History
def test_buy_spy_with_indicator():
# create your stock and portfolio
reset()
spy = Stock("SPY", currency_code="USD")
aud = Cash("AUD")
usd = Cash("USD")
audusd = FxRate("AUDUSD")
portfolio = Portfolio("AUD")
starting_value = 1e5 # start with $100K AUD
portfolio.transfer(aud, starting_value)
# impose a compliance rule so we are unable to
# hold more than 100 shares.
portfolio.compliance = Compliance().add_rule(UnitLimit(spy, 100))
# define a strategy to buy 100 shares of SPY
# if we are short USD then also fund this shortfall with AUD
class BuySpyWithIndicator(Strategy):
def show(self, trades):
if len(trades) == 0:
return
print(backtest.datetime)
print("^VIX: ", backtest.get_indicator("^VIX"))
print("AUDUSD: ", audusd.rate)
print("SPY: ", spy.price)
for trade in trades:
print(trade)
print("-------")
def generate_trades(self):
trades = list()
usd_holding = portfolio.get_holding_units("USD")
if usd_holding < 0:
trades.append(Trade(portfolio, usd, int(-usd_holding) + 1))
if backtest.get_indicator("^VIX") >= 26:
# don't buy any spy, just fund usd (if required)
self.show(trades)
return trades
trades.append(Trade(portfolio, spy, 100))
self.show(trades)
return trades
# create your backtest instance
backtest = Backtest(BuySpyWithIndicator())
history = History(
portfolios=portfolio,
backtest=backtest,
)
# load price events from yahoo for spy, audusd, vix
start_date = date(2020, 9, 1)
end_date = date(2020, 10, 1)
load_yahoo_prices(
[spy, audusd, "^VIX"],
backtest,
start_date=start_date,
end_date=end_date,
)
# run the backtest and check pnl
backtest.run()
df = history.get()
# print(portfolio)
# print(audusd.rate)
print(backtest.datetime)
print(df)
# Note that when running on windows the last FX rate we get from yahoo
# is on the 30 Sep AUDUSD = 7.716651. However, running on linux we get
# a price from 1 Oct of AUDUSD = 0.718288.
# This looks to be an issue with the yahoo api, but it has implications
# for our assertions around portfolio value.
starting_aud_price = 462 # this has not changed
ending_aud_price = 337.04 / audusd.rate
expected_pnl = (ending_aud_price - starting_aud_price) * 100
expected_value = starting_value + expected_pnl
assert round(portfolio.value, -1) == round(expected_value, -1)
start_date = pd.Timestamp(start_date)
end_date = pd.Timestamp(end_date)
assert int(df.at[start_date, "Portfolio"]) == int(starting_value)
assert round(df.at[end_date, "Portfolio"], -1) == round(expected_value, -1)
assert round(df.at[pd.Timestamp(date(2020, 9, 14)), "^VIX"], 2) == 25.85
|
22266770a90936862cd11fd0d7a00c641c8f4426 | davidstaab/AOC17 | /04_passphrase.py | 1,490 | 3.6875 | 4 | # series of all-lower chars
# sep='\s'
# no duplicate words
if __name__ == '__main__':
with open('./passphrases.txt') as file:
unique_ct = 0
no_perm_ct = 0
for line in file:
words = line.rstrip().split(sep=' ') # Remove '\n' from `line` so it doesn't show up in words[-1]
# PART 1
unique_ct += 1 # presume unique words
for w in words:
if words.count(w) > 1:
unique_ct -= 1 # remove presumption
break
# PART 2
no_perm_ct += 1 # presume no permutations
for i, base in enumerate(words):
pre_ct = no_perm_ct
for test in words[i + 1:]:
test = list(test)
for c in base:
try:
test.remove(c)
except ValueError: # "c not in list"
test = True # 'True' fails final check below
break
if not test: # if all chars were mapped from `base` to `test`...
no_perm_ct -= 1 # remove presumption
break
if no_perm_ct < pre_ct:
break # Don't test remaining words in line. Failure already found.
print('Unique-word passphrases: {}'.format(unique_ct))
print('Non-permuted passphrases: {}'.format(no_perm_ct))
|
1d014995f0751a956ec713efdbdc5767035f226f | 17PcNani/Nani-Python | /largeststring@task-8.py | 276 | 4.125 | 4 | str1=input("Enter first string:")
str2=input("Enter second string")
count1=0
count2=0
for i in str1:
count1+=1
temp1=count1
for i in str2:
count2+=1
temp2=count2
if temp1>temp2:
print("str1 is larger")
else:
print("str2 is larger")
|
aaa5643d5667ae6676f738daa41a03b60ee9c644 | Raul92x/University | /512/midterm/midterm_toh.py | 7,678 | 3.6875 | 4 | # midterm_toh.py
# Kerstin Voigt, Nov 2014; to be used for CSE 512 midterm;
import copy
import random
# some global variables ...
MAXNODES = 10000
# MIDTERM (possibly having something to do with
# the size of the toh problem)
TOH = 5
TOHTW = range(TOH+1)[1:]
TOHTW.reverse()
# do not change
def init_toh():
toh = {'a':TOHTW, 'b':[], 'c':[]}
return toh
# do not change
def toh_equal(toh1,toh2):
for k in toh1.keys():
if toh1[k] != toh2[k]:
return False
return True
# MIDTERM: return True if the tower in the initial state (on peg 'a')
# appears on peg 'c', and peb 'b' is empty; return False otherwise;
def toh_solved(toh):
for x in toh.keys():
if (toh.get('c')==TOHTW and toh.get('b')==[]):
return True
return False
# MIDTERM: a use function; given state toh, move the top disk from peg 'frm' to
# peg 'to'; return value None if either moving a disk from peg 'frm' makes no
# sense, or moving it to peg 'to' is not allowed; otherwise compute and return
# the toh state;
def move_disk(toh, frm, to):
if toh[frm] == [] or toh[to] != [] and toh[frm][-1] > toh[to][-1]:
return None
else:
disk = toh[frm][-1]
toh[frm] = toh[frm][:-1]
toh[to].append(disk)
return toh
# MIDTERM: compute all possible immediate successor states of state toh;
# return a list of next possible states;
def toh_successors(toh):
p1 = toh_check_ab(toh)
p2 = toh_check_ac(toh)
p3 = toh_check_ba(toh)
p4 = toh_check_bc(toh)
p5 = toh_check_ca(toh)
p6 = toh_check_cb(toh)
return [p for p in [p1,p2,p3,p4,p5,p6] if p != None]
def toh_check_ab(toh0):
toh = copy.deepcopy(toh0)
if toh['a'] == [] or toh['b'] != [] and toh['a'][-1] > toh['b'][-1]:
return None
else:
if toh['b'] == [] and toh['a'] != [] and toh['a'[-1]] > toh['b'[-1]]:
return move_disk(toh, 'a', 'b')
elif toh['b'] != [] and toh['a'] != [] and toh['a'[-1]] < toh['b'[-1]]:
return move_disk(toh, 'a', 'b')
else:
return False
def toh_check_ac(toh0):
toh = copy.deepcopy(toh0)
if toh['a'] == [] or toh['c'] != [] and toh['a'][-1] > toh['c'][-1]:
return None
else:
if toh['c'] == [] and toh['a'] != [] and toh['a'[-1]] > toh['c'[-1]]:
return move_disk(toh, 'a', 'c')
elif toh['c'] != [] and toh['a'] != [] and toh['a'[-1]] < toh['c'[-1]]:
return move_disk(toh, 'a', 'c')
else:
return False
def toh_check_ba(toh0):
toh = copy.deepcopy(toh0)
if toh['b'] == [] or toh['a'] != [] and toh['b'][-1] > toh['a'][-1]:
return None
else:
if toh['a'] == [] and toh['b'] != [] and toh['b'[-1]] > toh['a'[-1]]:
return move_disk(toh, 'b', 'a')
elif toh['a'] != [] and toh['b'] != [] and toh['b'[-1]] < toh['a'[-1]]:
return move_disk(toh, 'b', 'a')
else:
return False
def toh_check_bc(toh0):
toh = copy.deepcopy(toh0)
if toh['b'] == [] or toh['c'] != [] and toh['b'][-1] > toh['c'][-1]:
return None
else:
if toh['c'] == [] and toh['b'] != [] and toh['b'[-1]] > toh['c'[-1]]:
return move_disk(toh, 'b', 'c')
elif toh['c'] != [] and toh['b'] != [] and toh['b'[-1]] < toh['c'[-1]]:
return move_disk(toh, 'b', 'c')
else:
return False
def toh_check_ca(toh0):
toh = copy.deepcopy(toh0)
if toh['c'] == [] or toh['a'] != [] and toh['c'][-1] > toh['a'][-1]:
return None
else:
if toh['a'] == [] and toh['c'] != [] and toh['c'[-1]] > toh['a'[-1]]:
return move_disk(toh, 'c', 'a')
elif toh['a'] != [] and toh['c'] != [] and toh['c'[-1]] < toh['a'[-1]]:
return move_disk(toh, 'c', 'a')
else:
return False
def toh_check_cb(toh0):
toh = copy.deepcopy(toh0)
if toh['c'] == [] or toh['b'] != [] and toh['c'][-1] > toh['b'][-1]:
return None
else:
if toh['b'] == [] and toh['c'] != [] and toh['c'[-1]] > toh['b'[-1]]:
return move_disk(toh, 'c', 'b')
elif toh['b'] != [] and toh['c'] != [] and toh['c'[-1]] < toh['b'[-1]]:
return move_disk(toh, 'c', 'b')
else:
return False
# ... complete here ...
# do not change
def toh_print(toh):
pegs = toh.keys()
pegs.sort()
for k in pegs:
print "%s |-" % k,
for x in toh[k]:
print x,
print " ",
print "\n"
# MIDTERM: the evaluation function for toh; return the difference in height
# beteeen the given tower on peg 'c' in state toh and the height of the tower
# in the goal state; hint: check out info provided in the global variables
# above;
def toh_eval(toh):
goal = TOH
return (goal-len(toh['c']))
# MIDTERM: DO NOT MAKE CHANGES TO ANY OF THE GRAPHSEARCH RELATED FUNTIONS.
# test all functions by loading them into idle and make functions calls
# that will demonstrate that correctness of the code;
# mode = 1 -- sort by length of path (= depth of node); uniform-cost search
# mode = 2 -- sort by evalfct; best-first search
# mode = 3 -- sort by depth + evalfct; A* if evalfct is "admissible"
# print_info = 0 (default) -- minimal printing of info
# print_info = 1 -- 0 + prints current state as come from open
# print_info = 2 -- 1 + prints contents of open_lst
def graphsearch(start,mode, equal_fct, solved_fct, eval_fct, succ_fct,\
print_fct, print_info = 0):
open_lst = [[[start],start]]
closed_lst = []
count = 1
pathcount = 0
nodecount = 0
while open_lst != [] and nodecount < MAXNODES:
curr0 = open_lst[0]
curr = curr0[1]
pth = curr0[0]
open_lst = open_lst[1:]
closed_lst.append(curr0)
nodecount += 1 # count node about to be expanded
if solved_fct(curr):
if print_info > 0:
print "\n\nGoal found with path of length %d and node cost %d\n" % (len(pth),nodecount)
print_fct(curr)
print "\nThe Path:"
print_path(pth,eval_fct,mode,print_fct)
return (pth,nodecount)
if print_info > 1:
if mode == 1:
print "[step-%d] %s <%d>" % (count, curr, len(pth)-1)
elif mode == 2:
print "[step-%d] %s <%d>" % (count, curr, eval_fct(curr))
else:
print "[step-%d] %s <%d+%d>" % (count, curr, len(pth)-1, eval_fct(curr))
print_fct(curr)
succ = succ_fct(curr)
for s in succ:
if no_cycle(pth,s,equal_fct) and\
not_on_lst(open_lst,s,equal_fct) and\
not_on_lst(closed_lst,s,equal_fct):
newpth = pth[:] + [s]
open_lst.append([newpth,s])
random.shuffle(open_lst)
# sort open_lst according to mode
if mode == 1:
open_lst.sort(key = lambda x: len(x[0])-1)
elif mode == 2:
open_lst.sort(key = lambda x: eval_fct(x[1]))
else:
open_lst.sort(key = lambda x: len(x[0])-1+eval_fct(x[1]))
if print_info > 2:
print "[open-%d]" % count
for x in open_lst:
if mode == 1:
print "%s -- %d" % (x[1], len(x[0])-1)
elif mode == 2:
print "%s -- %d" % (x[1], eval_fct(x[1]))
else:
print "%s -- %d" % (x[1],len(x[0])-1+eval_fct(x[1]))
count += 1
if print_info > 0:
if nodecount >= MAXNODES:
print "\n\nSearch exceeds maximum of %d nodes" % MAXNODES
else:
print "\n\nUnsolvable problem!"
return ([], nodecount)
def no_cycle(path, x, equal_fct):
for y in path:
if equal_fct(x,y):
return False
return True
# lst is list of [pth,state], s is state that should not be on lst
def not_on_lst(lst,s,equal_fct):
for x in lst:
if equal_fct(x[1],s):
return False
return True
def print_path(pth, evalf, mode, print_fct):
for i in range(len(pth)):
if mode == 1:
print " <%d>" % i
elif mode == 2:
print " <%d>" % evalf(pth[i])
else:
print " <%d+%d>" % (i,evalf(pth[i]))
print_fct(pth[i])
print "\n\n"
# MIDTERM TEST RUN ... DO NOT MODIFY
# you may comment these out while debugging; make sure you uncomment later
# for test runs;
#mytoh = init_toh()
#graphsearch(mytoh, 3, toh_equal, toh_solved, toh_eval, toh_successors,\
# toh_print, print_info = 1)
|
f988c50d7c150c78b5386dd396b219b73c0f0ae0 | Adegbenga1/Election_Analysis | /Pypoll.py | 6,436 | 4.09375 | 4 | import csv
import os
# Add a variable to load a file from a path.
csvpath = os.path.join("Resources","election_results.csv")
# Add a variable to save the file to a path.
txtpath = os.path.join("Analysis","election_analysis.txt")
#Initialize a total vote counter.
total_votes = 0
# Candidate Options and candidate votes.
candidate_options = []
candidate_votes = {}
# 1: Create a county list and county votes dictionary.
County_list = []
County_Votes = {}
# Track the winning candidate, vote count and percentage (Winning Candidate and Winning Count Tracker)
winning_candidate = ""
winning_count = 0
winning_percentage = 0
# 2: Track the largest county and county voter turnout.
Largest_county_Vote = ""
Largest_County_turnout = 0
# Open the CSV # Read the csv and convert it into a list of dictionarie
with open(csvpath) as election_results:
csv_reader = csv.reader(election_results)
for row in csv_reader:
print(row[:3])
break
else:
print("Not found")
# Print each row in the CSV file.
# Print each row in the CSV file. Get the candidate name from each row.
for row in csv_reader:
total_votes += 1
# 3. Print the total votes.
# Print the candidate name from each row.
candidate_name = row[2]
# 3: Extract the county name from each row.
County_name = row[1]
# Add the candidate name to the candidate list. If the candidate does not match any existing candidate add it to the candidate list
if candidate_name not in candidate_options:
candidate_options.append(candidate_name)
candidate_votes[candidate_name] = 0
candidate_votes[candidate_name] += 1
# 4a: Write an if statement that checks that the county does not match any existing county in the county list.
if County_name not in County_list:
# 4b: Add the existing county to the list of counties.
County_list.append(County_name)
# 4c: Begin tracking the county's vote count.
County_Votes[County_name] = 0
# 5: Add a vote to that county's vote count.
County_Votes[County_name] += 1
with open(txtpath, "w") as txt_file:
# Print the final vote count (to terminal)
election_results = (
f"\nElection Results\n"
f"-------------------------\n"
f"Total Votes: {total_votes:,}\n"
f"-------------------------\n\n")
print(election_results, end="")
txt_file.write(election_results)
County_Result= (
f"\nCounty Result\n"
f"-------------------------\n")
# f"{county }: {county_vote_percent}%, {county_vote} Total Vote ")
print(County_Result, end="")
# 6e: Save the county votes to a text file.
txt_file.write(County_Result)
# 6a: Write a for loop to get the county from the county dictionary.
for county in County_list:
# 6b: Retrieve the county vote count.
current_votes = County_Votes[county]
# 6c: Calculate the percentage of votes for the county.
county_vote_percent = (current_votes/total_votes) *100
#txtpath.write(f"{County_name }: {county_vote_percent :.1f}% ({county_vote:,})\n")
# 6f: Write an if statement to determine the winning county and get its vote count.
if current_votes > Largest_County_turnout:
Largest_County_turnout = current_votes
Largest_county_Vote = county
# 6d: Print the county results to the terminal.
curr_county_print = f"{county}: {county_vote_percent :.1f}% ({current_votes:,})\n"
print(curr_county_print)
txt_file.write(curr_county_print)
# 7: Print the county with the largest turnout to the terminal.
#print(f"Largest county is {Largest_county_Vote} and the vote is {Largest_County_turnout:,}")
Largest_county_Turnout_print = (
f"\nLargest county Turnout\n"
f"-------------------------\n"
f"{Largest_county_Vote }: {Largest_County_turnout:,}\n\n"
f"-------------------------\n")
print(Largest_county_Turnout_print)
# 8: Save the county with the largest turnout to a text file.
txt_file.write(Largest_county_Turnout_print)
# print(county_vote)
# print(candidate_votes)
# print(candidate_options)
# print(County_Votes)
# print(County_list)
# print(total_votes)
# Iterate through the candidate list.
for candidate_name in candidate_votes:
# Retrieve vote count of a candidate.
votes = candidate_votes[candidate_name]
# 3. Calculate the percentage of votes.
vote_percentage = float(votes) / float(total_votes) * 100
# To do: print out each candidate's name, vote count, and percentage of
candidate_results = (
f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n")
print(candidate_results)
# Save the candidate results to our text file.
txt_file.write(candidate_results)
if (votes > winning_count) and (vote_percentage > winning_percentage):
# If true then set winning_count = votes and winning_percent =
# vote_percentage.
winning_count = votes
# Set the winning_candidate equal to the candidate's name.
winning_candidate = candidate_name
winning_percentage = vote_percentage
# votes to the terminal.
# print(f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n")
# # Print the candidate name and percentage of votes.
# print(f"{candidate_name}: received {vote_percentage} " " % of the vote.")
# Determine if the votes are greater than the winning count.
# Print the winning candidates' results to the terminal.
winning_candidate_summary = (
f"-------------------------\n"
f"Winner: {winning_candidate}\n"
f"Winning Vote Count: {winning_count:,}\n"
f"Winning Percentage: {winning_percentage:.1f}%\n"
f"-------------------------\n")
print(winning_candidate_summary)
# Print the final vote count to the terminal.
election_results = (
f"\nElection Results\n"
f"-------------------------\n"
f"Total Votes: {total_votes:,}\n"
f"-------------------------\n")
print(election_results, end="") |
c702972a71a9d07fcc3042b3ff29d72294bb1180 | JeongHanJun/BOJ | /Python 3 PS Code/BOJ/11050.py | 534 | 3.53125 | 4 | # 11050 이항 계수 1
# math 모듈의 factorial 이용하는 방법
'''
from math import factorial
n, k = map(int, input().split())
print( factorial(n) // (factorial(k) * factorial(n-k)) )
'''
# math module 사용하지 않고 dp로 이항계수 값을 구하는 방법
def com(n, k):
if k == 0 or k == n:
return 1
if dp[n][k] != 0:
return dp[n][k]
return com(n-1, k-1) + com(n-1, k)
n, k = map(int, input().split())
dp = [ [0 for i in range(k+1)] for j in range(n+1)]
print(com(n, k)) |
19d011763478abd3458a5d5833bc86e46e607a44 | candytale55/lambda-challenges-Py_3 | /ends_in_a.py | 256 | 4.03125 | 4 | # named ends_in_a takes an input str and returns True if the last character in the string is an a. Otherwise, return False.
ends_in_a = lambda string : string[len(string)-1] == "a"
print ends_in_a("data") # True
print ends_in_a("aardvark") # False
|
29c5fc8094e5a2109a22b3c408e35cdb0d14e255 | majard/prog1-uff-2016.1 | /Trapezium.py | 212 | 3.890625 | 4 | a = eval(input('A: '))
b = eval(input('B: '))
c = eval(input('C: '))
if a > 0 and b > 0 and c > 0:
area = (a + b) / 2 * c
print('The area is', area)
else:
print('All numbers must be positive!') |
af6caac8b4345546a1c970ade1714f41daf7278e | mooksys/Python_Algorithms | /Chapter32/file_32_4_1.py | 382 | 3.71875 | 4 | ROWS = 5
COLUMNS = 7
a = [ [None] * COLUMNS for i in range(ROWS) ]
for i in range(ROWS):
for j in range(COLUMNS):
print(i, ",", j, "의 요솟값을 입력하여라: ")
a[i][j] = float(input())
for i in range(ROWS):
for j in range(COLUMNS):
if a[i][j] != int(a[i][j]):
print(i, ",", j, "위치에서 실수가 발견되었습니다.")
|
12c9999006b101433c091630d1182d7b7c4b4652 | HarshadGare/Python-Programming | /Operators/06 Identity.py | 55 | 3.8125 | 4 |
a = '5'
z = a is 5
print(z)
y = a is not 5
print(y)
|
c2a2fee06ea493a9cebcbe846fba4da28db57e68 | ant642507com/my-python-foundation | /investigate texts and calls/ZH/Task2.py | 3,603 | 3.75 | 4 | """
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。
输出信息:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
提示: 建立一个字典,并以电话号码为键,通话总时长为值。
这有利于你编写一个以键值对为输入,并修改字典的函数。
如果键已经存在于字典内,为键所对应的值加上对应数值;
如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。
"""
phone_dict = {}
def add_value(phone_dict, key, value):
if key in phone_dict:
phone_dict[key] += value
else:
phone_dict[key] = value
for call_info in calls:
'''主叫电话通话时长累加'''
add_value(phone_dict, call_info[0], int(call_info[3]))
'''被叫电话通话时长累加'''
add_value(phone_dict, call_info[1], int(call_info[3]))
phone_of_longest_call = max(phone_dict, key=phone_dict.get)
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(
phone_of_longest_call, phone_dict[phone_of_longest_call]
))
"""以下是我之前提交的实现
tel_totaltime_map = {}
#组织map数据结构 key 为手机号,value为手机号对应的通话时长
for call_info in calls:
# 主叫电话
originate_phone = call_info[0]
# 被叫电话
terminate_phone = call_info[1]
# 通话时长
time_in_sec = int(call_info[3])
if tel_totaltime_map.__contains__(originate_phone):
tel_totaltime_map[originate_phone] = tel_totaltime_map[originate_phone] + time_in_sec
else:
tel_totaltime_map[originate_phone] = time_in_sec
if tel_totaltime_map.__contains__(terminate_phone):
tel_totaltime_map[terminate_phone] = tel_totaltime_map[terminate_phone] + time_in_sec
else:
tel_totaltime_map[terminate_phone] = time_in_sec
#将 map 按照 value值排序
tel_sorted_dict = dict(sorted(tel_totaltime_map.items(), key = lambda x:x[1], reverse=True))
#取得第一个key值
max_totaltime_phone = list(tel_sorted_dict.keys())[0]
#获取第一个key值对应的value
max_totaltime = tel_sorted_dict[max_totaltime_phone]
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(
max_totaltime_phone,
max_totaltime
))
"""
""" 以下是导师给的解决方案的代码(我写下了自己的理解):
仔细观察这两个 if ... else 语句会发现代码大同小异,这个时候就可以考虑把它们抽象成一个函数,实现代码的复用:
def add_value(phone_dict, key, value):
if key in phone_dict:
phone_dict[key] += value
else:
phone_dict[key] = value
# 定义电话字典,key是电话号码,value值是累积的通话时长
phone_dict = {}
for x in calls:
add_value(phone_dict, x[0], int(x[3]))
add_value(phone_dict, x[1], int(x[3]))
# 字典中 按照value排序取最大值,返回最大值的key
phone_of_longest_call = max(phone_dict, key=phone_dict.get)
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(
phone_of_longest_call, phone_dict[phone_of_longest_call]
))
""" |
1a06130f73292c6edf9fb953196917c056388544 | rollersteaam/maths-graphs-and-all-things-holy | /src/Section1.py | 849 | 3.953125 | 4 | # This is done as a convention! 'np' is just easier to refer to then 'numpy' all the time.
import numpy as np
# Note here that I use 'one' and 'three'. Your variables in Python can't start with a number, such as '1'.
one_dimensional_matrix = np.array([1, 5, 9])
print(one_dimensional_matrix)
one_dimensional_matrix = one_dimensional_matrix * 3
print(one_dimensional_matrix)
# Three Dimensional Time
three_dimensional_matrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
print(three_dimensional_matrix)
three_dimensional_matrix = three_dimensional_matrix * 2
print(three_dimensional_matrix)
print("===")
print("ME CHANGING THE NUMBER 1")
print("===")
three_dimensional_matrix[0][1] = 1
print(three_dimensional_matrix)
print("===")
print("EASIER WAY")
print("===")
an_easier_way = np.array([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
print(an_easier_way) |
6cc52832b6bad48b57c0c7f85a70052c15b7ba4d | AndrewWei-Colosseum/basic-algorithms | /stack_and_queue..gyp | 194 | 3.765625 | 4 | queue1 = [1,2,3,4,5,6]
queue2 = [1,2,3,4,5,6]
# FIFO, the functionality of queue. called queue.
print(queue1.pop(0))
# LIFO, like the stack, even though the name is queue.
print(queue1.pop())
|
1934b5ad7966c2cbb647fcdaf04f430a883416ce | oarthurvictor/codigos | /Python/Atividade 2 - Salarios e Abonos - Arthur Victor.py | 999 | 3.71875 | 4 | #Aluno: Arthur Victor
recebe_salarios = [ [],[] ]
teste = 1
while teste != 0:
teste = float(input("Digite o salário: "))
if teste != 0:
recebe_salarios[0].append(teste)
if (teste*0.2) >= 100:
recebe_salarios[1].append(teste*0.2)
else:
recebe_salarios[1].append(100)
print ('\nSalário - Abono')
for i in range(0,len(recebe_salarios[0])):
print ('R$ {} - R$ {}'.format(recebe_salarios[0][0+i], recebe_salarios[1][0+i]))
print ('\nForam processados {} colaboradores'.format(len(recebe_salarios[0])))
total_abono = 0
for i in range (0,len(recebe_salarios[1])):
total_abono = total_abono + recebe_salarios[1][0+i]
print ('Total gasto com abonos: R$ {}'.format(total_abono))
total_minimo = 0
for i in range(0,len(recebe_salarios[1])):
if (recebe_salarios[1][0+i] == 100):
total_minimo = total_minimo+1
print ('Valor mínimo foi pago a {} colaboradores'.format(total_minimo))
print ('Maior valor de abono pago: R$ {}'.format(max(recebe_salarios[1])))
|
65dd7cde04cf127dfc4d4d1b0fb8e29f56a3eae7 | DevNathanM/Python-IA | /IA-py/aula.py | 464 | 3.796875 | 4 | #-*- coding: utf-8 -*-
from math import sqrt
#a = input("Digite o valor para A:")
a = float(input("Digite o valor para A = "))
b = float(input("Digite o valor para B = "))
c = float(input("Digite o valor para C = "))
b2 = b**2
delta = b2-(4 * a * c)
try:
raiz_quadrada = sqrt(delta)
x1 = (-b - raiz_quadrada)/(2*a)
x2 = (-b + raiz_quadrada) /(2*a)
print("x1 = " + str(x1))
print("x2 = " + str(x2))
except Exception as e:
print(e)
|
524db43cbbedee998719e2b67b7aada85c88c28d | Aasthaengg/IBMdataset | /Python_codes/p03738/s026660485.py | 238 | 3.765625 | 4 | #
import sys
input=sys.stdin.readline
def main():
A=int(input())
B=int(input())
if A>B:
print("GREATER")
elif A==B:
print("EQUAL")
else:
print("LESS")
if __name__=="__main__":
main()
|
9c1945ceda4f1205cc35136d0e2fb3be01d94ed9 | effectivemadness/ct_exercise | /H-index/solution.py | 940 | 3.578125 | 4 | # def solution(citations):
# answer = 0
# max_ci = -1
# print(sorted(citations))
# citations = sorted(citations)
# # for i, value in enumerate(citations):
# # if len(citations) - i >= value and max_ci < value:
# # max_ci = value
# for i in range(len(citations)):
# if len(citations) - i >= citations[i] and max_ci < citations[i]:
# max_ci = citations[i]
# return max_ci
def solution(citations):
answer = 0
citations.sort()
cite_count = []
for i in range(max(citations)+1):
cite = 0
for item in citations:
if item >= i:
cite = cite+1
else:
cite = cite+0
cite_count.append(cite)
# print(num)
if cite_count[i] >= i:
answer = i
else:
break
return answer
print(solution([3, 0, 6, 1, 5]))
print(solution([1, 3, 5, 7, 9, 11])) |
faa0d36ba2dae19a09d88d71b5b52a2db48989f6 | Wakeel03/Sudoku-Solver-using-Backtracking | /main.py | 3,485 | 4.25 | 4 | ### The SUDOKU Solver Using Backtracking ###
#This is the sudoku to be solved
sudoku = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]
#This is the solved sudoku -- it will be used to verify the answer
sudoku_solved = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]]
#Function to print the sudoku board
def printSudoku(sudoku):
for i in range(len(sudoku)):
if i % 3 == 0:
print('--------------------------')
for j in range(len(sudoku[0])):
if j % 3 == 0 and j != 0:
print (' | ', end = " ")
print(sudoku[i][j], end = " ")
print()
#check if the number to be inserted is allowed
def valid(sudoku, row, col, num):
#check same row
for i in range(len(sudoku[0])):
if sudoku[row][i] == num:
return False
#check same column
for i in range(len(sudoku)):
if sudoku[i][col] == num:
return False
#check same box
boxY = row // 3
boxX = col // 3
for i in range(3):
for j in range(3):
if sudoku[(boxY * 3) + i][(boxX * 3) + j] == num:
return False
return True
#Function to check if there empty (0) positions on the board
def solved(sudoku):
for i in sudoku:
for j in i:
if j == 0:
return False
return True
#Main function
def solve(sudoku):
if solved(sudoku):
return True
#Loop through every position on the board and look for empty positions
for i in range(len(sudoku)):
for j in range(len(sudoku[0])):
if sudoku[i][j] == 0:
for k in range(1, 10):
if valid(sudoku, i, j, k):
sudoku[i][j] = k
#Recursive call for next empty position
if solve(sudoku):
return True
#If all values of k fail, this means we need to backtrack
#to previous position (which will get a new value for k)
#and continue with the recursive call till validity
sudoku[i][j] = 0 #set the current position's value back to 0
return False
#Function to verify if the answer matches the expected result
def checkResult(s, s_solved):
for i in range(len(s)):
for j in range(len(s[0])):
if s[i][j] != s_solved[i][j]:
return False
return True
printSudoku(sudoku)
print()#Leave some space to print the solved board
solve(sudoku)
printSudoku(sudoku)
print(checkResult(sudoku, sudoku_solved)) #print True if answer correct
|
031ffcb495a4bde563feaac9327a4768c0a8fb90 | weronikaolejniczak/porter-stemmer | /porter stemmer/stemmer.py | 2,429 | 3.53125 | 4 | import re
import tools
import pandas as pd
# FILENAME = "tests/test1.txt"
# FILENAME = "tests/test2.txt"
FILENAME = "tests/test3.txt"
CSV_FILE = "data/stems.csv"
def clear_file(filename):
open(filename, 'w').close()
def print_table(filename):
column_names = ["word", "stem", "inflection", "steps_taken", "part_of_speech"]
df = pd.read_csv(filename, sep=",", names=column_names)
print(df)
def diff(string1, string2):
if len(string1) > len(string2):
res = ''.join(string1.split(string2)) # get diff
else:
res = ''.join(string1.split(string2)) # get diff
return res.strip()
def write_to_csv(filename, line):
f = open(filename, "a")
f.write(line + "\n")
f.close()
def read_from_file(filename):
content = ""
f = open(filename, "r")
if f.mode == 'r':
content = f.read()
else:
print("No file found!")
f.close()
return content
def lowercase(word_list):
word_list = [element.lower() for element in word_list]
return word_list
def tokenize(arg):
tokens = re.findall(r"[\w']+", arg)
tokens = lowercase(tokens)
return tokens
def main():
content = read_from_file(FILENAME)
tokens = tokenize(content)
# user_input = input("Stem: ")
# tokens = tokenize(user_input)
stemmer = tools.PorterStemmer()
for token in tokens:
if len(token) > 2:
stemmer.clear()
stemmer.word = token
# get the stem
stem = stemmer.stem()
stem = "".join(stem)
# choose diff output
if len(diff(token, stem)) > 0:
difference = "-" + diff(token, stem)
else:
difference = "None"
# line to write to the csv file
line = token + "," + \
stem + "," + \
difference + "," + \
str(len(stemmer.steps) - 1) + "," + \
" or ".join(stemmer.part_of_speech)
# write to the csv file
write_to_csv(CSV_FILE, line)
else:
stemmer.clear()
line = token + "," + token + ",None,None," + " or ".join(stemmer.set_pos(token))
write_to_csv(CSV_FILE, line)
print("_______________________________________________________________")
print_table(CSV_FILE)
clear_file(CSV_FILE)
if __name__ == '__main__':
main()
|
179e0f161624e011a55f15f614ceff75419f11d1 | jjcrab/code-every-day | /day22_lengthOfLastWord.py | 532 | 4.09375 | 4 | # https: // leetcode.com/problems/length-of-last-word/
# Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
# A word is a maximal substring consisting of non-space characters only
def lengthOfLastWord(s):
# list_s = s.split()
# print(list_s)
# if list_s == []:
# return 0
# return len(list_s[-1])
if not s or s.isspace():
return 0
return len(s.split()[-1])
print(lengthOfLastWord(""))
|
b5486a5435c06fe395dae36a31408a0499c26659 | TheoBafrali/UAVSAR-MIT-1 | /Python/FastLinInt.py | 3,913 | 3.5625 | 4 | '''
Performs backprojection using Numpy operations to generate SAR image. Plots in logarithmic and linear scale.
@author: David + Mason
'''
#Import required modules
import matplotlib.pyplot as plt
import numpy as np
from numpy import real, arange, reshape
def FastBackProjection(aligned_data,radar_data,LeftInterval,RightInterval,StepSize):
'''
Inputs:
aligned_data: Properly aligned_data
radar_data: RADAR data
LeftInterval: vector of bounds on x and y from the left
RightInterval: vector of bounds on x and y from the right
StepSize: interval which backprojection steps through
Outputs:
Plots backprojected SAR image, in linear and logarithmic scale
IntensityList: numpy array of image data
'''
#Extracts data
WrongRadarPosition = aligned_data[1] #Actual position of radar in 3D space
PulseData = np.array(aligned_data[0]) #Data of all pulses in file
RangeBins = np.array(radar_data[2]) #Distance in meters between the sampling rate of PulseData
#Parameters:
#LeftInterval = Left boundary of interval of pixels to iterate over
#RightInterval = Right boundary of interval of pixels to iterate over
#StepSize = Step size between left and right boundaries of interval. Must be less than RightInterval-LeftInterval
#Initialize RadarPosition
RadarPosition = []
#This loop changes the (x, y, z) data to (z, x, y) data
for i in range(len(WrongRadarPosition)):
y = WrongRadarPosition[i][0]
x = WrongRadarPosition[i][2]
z = WrongRadarPosition[i][1]
RadarPosition.append([x,y,z])
#Defines distance grid
y_length = arange(LeftInterval[1],RightInterval[1]+StepSize,StepSize)
x_length = arange(LeftInterval[0],RightInterval[0]+StepSize,StepSize)
x_pixel, y_pixel = np.meshgrid(x_length,y_length)
#Initialize IntensityList
IntensityList = np.zeros(np.shape(x_pixel))
#Further extract data
PulseData = PulseData[0:len(RadarPosition)-1]
RadarPosition = np.array(RadarPosition)
PulseData = np.array(PulseData)
#Iterate over pulses
for i in range(len(PulseData)):
squared = np.sqrt(np.square(x_pixel-RadarPosition[i][0])+np.square(y_pixel-RadarPosition[i][1])+np.square(RadarPosition[i][2]))
if np.isnan(RadarPosition[i][0]):
return "Wrong"
#Gives some indication the program is running
if np.mod(i, 200) == 0:
print("Calculating pulse "+str(i)+ " which is "+str(i/len(PulseData)*100) +"% of the data" )
#Adds interpolated data to IntensityList
IntensityList += np.interp(squared, RangeBins,PulseData[i,:], left = 0, right = 0)
IntensityList = np.flip(IntensityList,0) #Reshapes IntensityList to the right size
#plt.imsave('LinIntBP.png',IntensityList)
plt.figure(2)
plt.subplot(122)
plt.set_cmap('jet')
plt.title("Linear")
plt.imshow(abs(IntensityList), extent = (LeftInterval[0], RightInterval[0], LeftInterval[1], RightInterval[1])) #Plots the image
plt.axis('equal')
cbar = plt.colorbar()
#plt.colorbar()
logarithmic_intensity = 20*np.log10(abs(IntensityList))
max_log_intensity = max(logarithmic_intensity.flatten())
plt.subplot(121)
plt.title("Logaritmic")
plt.imshow(logarithmic_intensity, extent = (LeftInterval[0], RightInterval[0], LeftInterval[1], RightInterval[1])) #Plots the image
plt.clim(max_log_intensity-20,max_log_intensity)
plt.axis('equal')
plt.show() #Shows the image in a new window for Mason
np.savetxt("intensity.csv", IntensityList, delimiter=",", fmt='%s')
#Takes absolute value of IntensityList for deconvolution
IntensityList = np.absolute(IntensityList)
return IntensityList
|
fe23b414ed79492df7923e775890038f909abb1a | schatfield/StudentExercises | /reports.py | 4,471 | 4.09375 | 4 | import sqlite3
from student import Student
from cohort import Cohort
from exercise import Exercise
class StudentExerciseReports():
"""Methods for reports on the Student Exercises database"""
# function definition to create a student,
# def create_student(self, cursor, row):
# return Student(row[1], row[2], row[3], row[5])
def __init__(self):
self.db_path = "/Users/shawnachatfield/workspace/pythonTime/StudentExercises/studentexercises.db"
def all_students(self):
"""Retrieve all students with the cohort name"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = lambda cursor, row: Student(
row[1], row[2], row[3], row[5])
db_cursor = conn.cursor()
db_cursor.execute("""
select s.id,
s.first_name,
s.last_name,
s.slack_handle,
s.student_cohort,
c.cohort_name
from Student s
join Cohort c on s.student_cohort = c.cohort_id
order by s.student_cohort
""")
all_students = db_cursor.fetchall()
# Extracting Individual Columns
# this loop is extracting individual columns to display first name [1], last name [2], and cohort name [3]
# for student in all_students:
# print(f'{student[1]} {student[2]} is in {student[5]}')
# for student in all_students:
# print(f'{student.first_name} {student.last_name} is in {student.cohort}')
for student in all_students:
print(student)
# this replaces the for loop we originally had above
# function definition to create a cohort,
# def create_cohort(self, cursor, row):
# return Cohort(row[1])
def all_cohorts(self):
"""Retrieve all cohorts"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory =lambda cursor, row: Cohort(
row[1])
db_cursor = conn.cursor()
db_cursor.execute("""
select c.cohort_id,
c.cohort_name
from Cohort c
""")
all_cohorts = db_cursor.fetchall()
for cohort in all_cohorts:
print(cohort)
# function definition to create an exercise
# def create_exercise(self, cursor, row):
# return Exercise(row[1], row[2])
def all_exercises(self):
"""Retrieve all exercises"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = lambda cursor, row: Exercise(row[1], row[2])
db_cursor = conn.cursor()
db_cursor.execute("""
select e.id,
e.exercise_name,
e.exercise_language
from Exercise e
""")
all_exercises = db_cursor.fetchall()
for exercise in all_exercises:
print(exercise)
def js_exercises(self):
"""Retrieve all Javascript exercises"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = lambda cursor, row: Exercise(row[1], row[2])
db_cursor = conn.cursor()
db_cursor.execute("""
select e.id,
e.exercise_name,
e.exercise_language
from Exercise e
Where e.exercise_language = "Javascript"
""")
js_exercises = db_cursor.fetchall()
for exercise in js_exercises:
print(exercise)
def py_exercises(self):
"""Retrieve all Python exercises"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = lambda cursor, row: Exercise(row[1], row[2])
db_cursor = conn.cursor()
db_cursor.execute("""
select e.id,
e.exercise_name,
e.exercise_language
from Exercise e
Where e.exercise_language = "Python"
""")
py_exercises = db_cursor.fetchall()
for exercise in py_exercises:
print(exercise)
reports = StudentExerciseReports()
reports.all_students()
reports.all_cohorts()
reports.all_exercises()
reports.js_exercises()
reports.py_exercises()
# if __name__ == "__main__":
# print("I'm running this file as main") |
5cef1fd9a1f080c2f7509d43bfc5ce6140b2335c | RyujiOdaJP/python_practice | /ryuji.oda19/week01/c15_random_loop.py | 122 | 3.71875 | 4 | import random
GivenNumber = input('Enter a number: ')
for i in range(int(GivenNumber)):
print(random.randrange(0, 2)) |
a105646b1642988f469d1facad8ccf4972a8655e | kBarbz/jotto | /data management scripts/create-isos.py | 1,030 | 3.578125 | 4 | import sys
def main():
iso = []
try:
with open("portuguese-dict.txt", "r") as file:
line = file.readline()
while line:
if is_isogram(line):
iso.append(line)
line = file.readline()
except IOError:
sys.exit("Could not read file1")
try:
with open('portuguese-iso.txt', 'w') as file:
file.writelines(iso)
except IOError:
sys.exit("could not append")
def is_isogram(word):
# Convert the word or sentence in lower case letters.
clean_word = word.lower()
# Make an empty list to append unique letters
letter_list = []
for letter in clean_word:
# Remove apostrophes
if letter == "\'":
return False
# If letter is an alphabet then only check
if letter.isalpha():
if letter in letter_list:
return False
letter_list.append(letter)
return True
if __name__ == '__main__':
main()
|
bc0e561dd7abb6688bcc71511281bfa5a6198b16 | benbendaisy/CommunicationCodes | /python_module/examples/839_Similar_String_Groups.py | 2,259 | 4.3125 | 4 | from typing import List
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.cnt = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x == root_y:
return False
if self.rank[root_x] < self.rank[root_y]:
root_x, root_y = root_y, root_x
self.parent[root_y] = root_x
if self.rank[root_x] == self.rank[root_y]:
self.rank[root_x] += 1
self.cnt -= 1
return True
class Solution:
"""
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".
Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?
Example 1:
Input: strs = ["tars","rats","arts","star"]
Output: 2
Example 2:
Input: strs = ["omv","ovm"]
Output: 1
"""
def numSimilarGroups(self, strs: List[str]) -> int:
def is_similar(s1, s2):
if s1 == s2:
return True
diff = 0
for c1, c2 in zip(s1, s2):
if c1 != c2:
diff += 1
if diff > 2:
return False
return diff == 2
n = len(strs)
uf = UnionFind(n)
for i in range(n):
for j in range(i + 1, n):
if is_similar(strs[i], strs[j]):
uf.union(i, j)
return uf.cnt
|
8406d7f34995d59f3a60e42e87a4ef07869494bb | swapnilnandedkar/Python-Assignment | /Assignment3/Assignment3_3.py | 650 | 4.0625 | 4 | # 3.Write a program which accept N numbers from user and store it into List. Return Minimum
# number from that List.
# Input : Number of elements : 4
# Input Elements : 13 5 45 7
# Output : 5
import functools
def main():
List = []
print("Enter total number you want to insert in List")
listSize = int(input())
for icnt in range(listSize):
print("Enter {} number".format(icnt+1))
List.append(int(input()))
minNumber = functools.reduce(lambda no1,no2 : no1 if no1 < no2 else no2,List)
print("Minimum number in List is : {}".format(minNumber))
if __name__ == "__main__":
main()
|
1234f6dda89db3be30779baf792e5e14464ad397 | care1e55/algotithms | /fibo.py | 220 | 3.875 | 4 | def fibo(n):
f = 1
f1 = 1
f2 = 1
for i in range(1, n+1):
if i < 3:
continue
else:
f = f1 + f2
f2 = f1
f1 = f
print(f)
fibo(int(input())) |
45871078e6275f635d4d4f8245213aaf40448dc3 | JohnBomber/mon_python | /Chapitre 12 - exercice 2.py | 194 | 3.578125 | 4 | import math
class Circle():
def __init__(self, r):
self.rayon = r
def area(self):
print((self.rayon ** 2) * math.pi)
cercle1 = Circle(5)
Circle.area(cercle1)
|
fcfcd915ada057bb6fedaf9ed0441a4eaafe3aa5 | ealmestica/CS-200 | /Sorting_Movie/Lab6-Sorting_Movie.py | 2,346 | 4.15625 | 4 | # SNHU - CS200
# Elijah Almestica
# Program name: Sorting Movie
# Dictionary of movie collection
Movie_Collection = {
1:[2005, 'Munich','Steven Spielberg'],
2:[2006, 'The Prestige','Christopher Nolan' ],
3:[2006, 'The Departed', 'Martin Scorsese'],
4:[2007, 'Into the Wild', 'Sean Penn'],
5:[2008, 'The Dark Knight', 'Christopher Nolan'],
6:[2009, 'Mary and Max', 'Adam Elliot'],
7:[2010, "The King's Speech", 'Tom Hooper'],
8:[2011, 'The Artist', 'Michel Hazanavicius'],
9:[2011,'The Help', 'Tate Taylor'],
10:[2012, 'Argo', 'Ben Affleck'],
11:[2013, '12 Years a Slave','Steve McQueen'],
12:[2014, 'Birdman','Alejandro G. Inarritu'],
13:[2015, 'Spotlight','Tom McCarthy'],
14:[2016, 'The BFG','Steven Spielberg'],
}
prompt = int(input('Enter a year between 2005 and 2016:\n'))
while (not (2004 < prompt < 2017)):
print ("N/A")
prompt = int(input('Enter a year between 2005 and 2016:\n'))
for key, movies in Movie_Collection.items():
if prompt == movies[0]:
print (movies[1]+", "+movies[2])
# Initial List
movie_list = list(Movie_Collection.values())
user_choice = 's'
while user_choice != "q":
print ("\nMENU")
print ("Sort by:")
print ("y - Year")
print ("d - Director")
print ("t - Movie title")
print ("q - Quit")
user_choice = input('\nChoose an option:')
# User Chose y
if user_choice == 'y':
prev_years =[]
for movie in Movie_Collection.values():
if movie[0] in prev_years:
print ("\t"+movie[1]+", "+movie[2])
else:
print ("\n"+str(movie[0])+":")
print ("\t"+movie[1]+", "+movie[2])
prev_years.append (movie[0])
# User Chose d
elif user_choice == 'd':
def sort_director(x): # sort by director
return x[2]
# prints list sorted by director
sorted_director = sorted(movie_list, key=sort_director)
prev_directors = []
for director in sorted_director:
if director[2] in prev_directors:
print ("\t"+director[1]+", "+str(director[0]))
else:
print ("\n"+director[2]+":")
print ("\t"+director[1]+", "+str(director[0]))
prev_directors.append (director[2])
# User Chose t
elif user_choice == 't':
def sort_title(x): # sort by title
return x[1]
# prints list sorted by title
sorted_title = sorted(movie_list, key=sort_title)
for title in sorted_title:
print ("\n"+title[1]+":")
print ("\t"+title[2]+", "+str(title[0]))
print ()
|
c25ffbbb04479a63aedfcb18bb81b3eda1475e45 | Lackman-coder/tkinter_projects | /agecalculatortk.py | 1,229 | 3.90625 | 4 | from tkinter import *
from datetime import *
root = Tk()
root.geometry("700x500")
root.title("age calculator")
photo = PhotoImage(file="/sdcard/python_projects/tkinter_proj/calc.png")
myimage = Label(image = photo)
myimage.grid(row=0,column=1)
def calculateage():
today = date.today()
birthdate = date(int(Yearentry.get()),int(Monthentry.get()),int(Dayentry.get()))
age = today.year - birthdate.year - ((today.month,today.day) < (birthdate.month,birthdate.day))
Label(text=f"{Namevalue.get()} your age is {age}").grid(row=6,column=1)
Label(text = "Name").grid(row = 1,column= 0,padx=90)
Label(text="Year").grid(row=2,column=0)
Label(text="Month").grid(row=3,column=0)
Label(text="Day").grid(row=4,column=0)
Namevalue = StringVar()
Yearvalue = StringVar()
Monthvalue = StringVar()
Dayvalue = StringVar()
Nameentry = Entry(root,textvar =Namevalue)
Yearentry = Entry(root,textvar=Yearvalue)
Monthentry = Entry(root,textvar=Monthvalue)
Dayentry = Entry(root,textvar=Dayvalue)
Nameentry.grid(row=1,column=1,pady=10)
Yearentry.grid(row=2,column=1,pady=10)
Monthentry.grid(row=3,column=1,pady=10)
Dayentry.grid(row=4,column=1,pady=10)
Button(text="Calculate",command=calculateage).grid(row=5,column=1,pady=10)
root.mainloop() |
391f73ca36e99f7fa9b316abeeac27e84ef7fcc5 | VitalyVorobyev/MultibodyAnalysisTools | /examples/linear_fit_l2.py | 2,388 | 3.828125 | 4 | #! /usr/bin/python2
"""
# L2 regularization tutorial
# Based on tutorial 8.1 from
# http://ipython-books.github.io/cookbook/
"""
import numpy as np
import scipy.stats as st
import sklearn.linear_model as lm
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
plt.rc('font', size=26)
plt.rc('text', usetex=True)
f = lambda x: np.exp(3 * x)
x_tr = np.linspace(0., 2, 200)
y_tr = f(x_tr)
x = np.array([0, .1, .2, .5, .8, .9, 1])
y = f(x) + np.random.randn(len(x))
def plot_data(x_tr=x_tr, y_tr=y_tr, x=x, y=y):
plt.figure(figsize=(9,5))
plt.plot(x_tr, y_tr, '--k', lw=2)
plt.plot(x, y, 'bo', ms=15)
plt.xlim((-0.1, 1.1))
plt.ylim((-4, 24))
plt.grid()
def linear_model(x_tr=x_tr, y_tr=y_tr, x=x, y=y):
# We create the model.
lr = lm.LinearRegression()
# We train the model on our training dataset.
lr.fit(x[:, np.newaxis], y);
# Now, we predict points with our trained model.
y_lr = lr.predict(x_tr[:, np.newaxis])
return y_lr
def plot_linear_model(y_lr, x_tr=x_tr, y_tr=y_tr, x=x, y=y):
plot_data(x_tr, y_tr, x, y)
plt.plot(x_tr, y_lr, 'g', lw=2)
plt.title("Linear regression")
def without_regularization(x_tr=x_tr, y_tr=y_tr, x=x, y=y):
lrp = lm.LinearRegression()
plot_data(x_tr, y_tr, x, y)
for deg, s in zip([2, 5], ['-', '-']):
lrp.fit(np.vander(x, deg + 1), y);
y_lrp = lrp.predict(np.vander(x_tr, deg + 1))
plt.plot(x_tr, y_lrp, s, label='degree ' + str(deg), lw=2);
plt.legend(loc=2);
plt.xlim(-0.1, 1.4);
plt.ylim(-10, 40);
# Print the model's coefficients.
print(' '.join(['%.2f' % c for c in lrp.coef_]))
plt.title("Linear regression");
def with_regularization(x_tr=x_tr, y_tr=y_tr, x=x, y=y):
ridge = lm.RidgeCV()
plot_data(x_tr, y_tr, x, y)
for deg, s in zip([2, 5], ['-', '-']):
ridge.fit(np.vander(x, deg + 1), y);
y_ridge = ridge.predict(np.vander(x_tr, deg + 1))
plt.plot(x_tr, y_ridge, s, label='degree ' + str(deg), lw=2);
plt.legend(loc=2);
plt.xlim(-0.1, 1.5);
plt.ylim(-5, 80);
# Print the model's coefficients.
print(' '.join(['%.2f' % c for c in ridge.coef_]))
plt.title("Ridge regression");
# plot_data()
y_lr = linear_model()
plot_linear_model(y_lr)
# without_regularization()
# with_regularization()
plt.show() |
4abc2e9967d5cc38f54b3cbb1185a5be954dc7ff | AAAKgold/My-test | /python/py_pr/hj黄金分割法.py | 1,208 | 3.6875 | 4 | #黄金分割法确定单峰函数在区间的极小点
import numpy as np
import matplotlib.pyplot as plt
import math
#定义目标函数
def func(x):
return pow(x,4)-14*pow(x,3)+60*pow(x,2)-70*x
#print(func(1)) #for test
#def func(x):
# return pow(x,3)-2*x+1
#定义主函数 黄金分割法计算
def main(a0,b0,l):#区间和精度
global x_opt
global f_opt
global k
#初值区间[0,2] l为精度 注意:1-r为压缩比
r = (math.sqrt(5)-1)/2
k = 0
a1 = a0+(1-r)*(b0-a0)
b1 = a0+r*(b0-a0)
#循环分割 if判断
while abs(b0-a0) > l:
k += 1
f1 = func(a1)
f2 = func(b1)
if f1 >= f2:
a0 = a1
a1 = b1
f1 = f2
b1 = a0+r*(b0-a0)
else:
b0 = b1
b1 = a1
f2 = f1
a1 = a0+(1-r)*(b0-a0)
x_opt = (a0+b0)/2
f_opt = func(x_opt)
return (x_opt,f_opt,k)
#print(a0,b0)#for test
main(0,2,0.3)
#main(0,3,0.15)
#x = np.linspace(0,2,100)
#y = [func(t) for t in x]
#plt.plot(x,y)
#plt.show()
print("%.5f is the optimal point of the function and execute %d steps and the answer is %.5f"%(x_opt,k,f_opt))
|
cd5dbaf0a9eb9362f095e89ae72c2d0976827cbf | rohanaggarwal7997/terrier | /script/testing/oltpbench/reporting/utils.py | 341 | 4.15625 | 4 | #!/usr/bin/python3
def get_value_by_pattern(dict_obj, pattern, default):
"""
This is similar to .get() for a dict but it matches the
key based on a substring. This function is case insensitive.
"""
for key, value in dict_obj.items():
if pattern.lower() in key.lower():
return value
return default |
a632f98a04cb0c1f2102678bfc729c5509a55b0e | bairaju/accumulator | /convolution.py | 412 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
n=input("enter x length:")
k=input("enter h length:")
x=[]
for i in range(n):
z=input("enter elements:")
x.append(z)
print(x)
h=[]
for i in range(n+k-1):
b=input("enter elements:")
h.append(b)
print(h)
s=0
a=[]
for i in range(n+k-1):
for j in range(n):
s=s+((x[j])*(h[i-j]))
a.append(s)
s=0
print(a)
l=np.arange(0,n+k-1,1)
plt.stem(l,a)
plt.show()
|
9a9df25bdcaafb88a54b87369b2eb529550bcfff | vineettiwari456/mnstr_projects | /machine learning/Machine_LearningPractice/Part 2 - Regression/Section 5 - Multiple Linear Regression/pract_multi.py | 730 | 3.65625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv("50_Startups.csv")
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,4].values
# print(y)
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
X_labelencoder = LabelEncoder()
X[:,3] = X_labelencoder.fit_transform(X[:,3])
onehot = OneHotEncoder(categorical_features=[3])
X = onehot.fit_transform(X).toarray()
# print(X)
X = X[:,1:]
from sklearn.model_selection import train_test_split
X_train,X_test,Y_train,Y_test = train_test_split(X,y,test_size=.2)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
y_pred = regressor.predict(X_test)
print(y_pred)
print(Y_test) |
4c5887d63982a6c4e7f46f4a516afc5fa82c396b | andre2w/webserver | /server/request_parser.py | 1,739 | 3.5625 | 4 | def parse_request(request):
"""Parse the entire request request to a dict"""
request_lines = request.split('\r\n\r\n')
# Get the first line with the request info
# and parse the rest has headers
header_lines = request_lines[0].split('\r\n')
request_info = __parse_request_info(header_lines[0])
(headers, cookies) = __parse_headers(header_lines[1:])
request_info['headers'] = headers
request_info['cookies'] = cookies
request_info['body'] = request_lines[1]
return request_info
def __parse_request_info(line):
"""
Parse request info to a dict
input: GET / HTTP/1.1
output: {'method': 'GET', 'path': '/', 'version': 'HTTP/1.1' }
"""
request_info = line.split()
return {
'method' : request_info[0],
'path' : request_info[1],
'version': request_info[2]
}
def __parse_headers(lines):
"""Parse all the headers into a dict"""
headers = {}
cookies = {}
for line in lines:
splitted_line = line.split(':',1)
if splitted_line[0].lower() == 'cookie':
cookies = __parse_cookies(splitted_line[1])
else:
headers[splitted_line[0]] = splitted_line[1].strip()
return headers, cookies
def __parse_cookies(cookies):
cookie_array = cookies.split(';')
result = {}
for cookie in cookie_array:
attributes = cookie.split(',')
name = attributes[0].split('=')[0].strip()
result[name] = {
'value': attributes[0].split('=')[1]
}
for attribute in attributes[1:]:
attribute = attribute.split('=')
result[name][attribute[0].strip()] = attribute[1]
return result
|
9675c151f85d9f85ccf62ffeae4ff4bc43f73000 | aidan-coward/python | /learn-python/ex33-1.py | 256 | 3.875 | 4 | numbers = []
def while_loop(x, y):
for j in range(0, x + 1):
print "At the top i is %d" % j
numbers.append(j)
j = j + y
print "Numbers now: ", numbers
print "At the bottom i is %d" % j
print while_loop(20, 4)
|
5d81fc53bb3414cb48ee8396965dcd8b3ab9fda0 | JamesGilsenan/Python-3 | /Function_Arugments/Project_The_Nile.py | 1,825 | 3.5625 | 4 | from Nile import get_distance, format_price, SHIPPING_PRICES
from Test import test_function
from Test import Driver
from Test import Trip
def calculate_shipping_cost(from_coords, to_coords, shipping_type="Overnight"):
from_long, from_lat = from_coords
to_long, to_lat = to_coords
#distance = get_distance(*from_coords, *to_coords) also unpacks variables and works the same as line below
distance = get_distance(from_lat, from_long, to_lat, to_long)
shipping_rate = SHIPPING_PRICES.get(shipping_type)
price = distance * shipping_rate
return format_price(price)
def calculate_driver_cost(distance, *drivers):
cheapest_driver = None
cheapest_driver_price = None
for driver in drivers:
driver_time = driver.speed * distance
price_for_driver = driver.salary * driver_time
if cheapest_driver is None:
cheapest_driver = driver
cheapest_driver_price = price_for_driver
elif price_for_driver < cheapest_driver_price:
cheapest_driver = driver
cheapest_driver_price = price_for_driver
return cheapest_driver_price, cheapest_driver
def calculate_money_made(**trips):
total_money_made = 0
for trip_id, trip in trips.items():
trip_revenue = trip.cost - trip.driver.cost
total_money_made += trip_revenue
return total_money_made
#print(calculate_shipping_cost([50.8375054, 0.1762299], [53.5586526, 9.6476359], "Ground"))
#test_function(calculate_shipping_cost)
#test_function(calculate_driver_cost)
#test_function(calculate_money_made)
driver1 = Driver(2, 10)
driver2 = Driver(7, 20)
driver3 = Driver(5, 18)
#print(calculate_driver_cost(100, driver1, driver2, driver3))
trip1 = Trip(200, driver1, 15)
trip2 = Trip(300, driver2, 40)
print(calculate_money_made(trip1=trip1,trip2=trip2))
|
09b8f18a72e0f28be0dfaf740567f0aa510001e8 | marksikaundi/python-Overview | /func.py | 1,042 | 4.03125 | 4 | #function execution in python
#user_input
calculation_to_units = 24
name_of_units = "hours"
def days_to_units(num_of_days):
print(f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_units}")
user_input = input("hello can you enter something!\n")
print(user_input)
calculation_to_units = 24
name_of_units = "hours"
def days_to_units(num_of_days):
return f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_units}"
my_var = days_to_units(20)
print(my_var)
#coditional statement
calculation_to_units = 24
name_of_unit = "hours"
def days_to_units(num_of_days):
if num_of_days > 0:
return f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}"
else:
return "you in wrong channel, for the codes."
user_input = input("hello am a convertor, can help you make your convetion easy!\n")
user_input_number = int(user_input)
calculated_value_number = days_to_units(user_input_number)
print(calculated_value_number)
#more users input validation
|
0600c50ef90ae1c0ab1dbf70d926ae36297ca2f7 | amandamorris/codewars | /memoized_fib.py | 300 | 4.03125 | 4 | def fibonacci(n):
"""Returns the nth fibonacci number, works for large n"""
fibs = [0, 1] # start with first two numbers, stored in fibs
for i in range(2, n+1): # for each successive number
fibs.append(fibs[i-1]+fibs[i-2]) # add 2 previous, append to fibs
return fibs[n]
|
30b98ea4765ea671cfa75ce0db3d44a455cec443 | SoraShiro03/pythonPratices | /stack.py | 245 | 3.640625 | 4 | stack = [1,2,3,4,5]
# LIFO last in first out
stack.append(7)
print(stack)
stack.pop()
print(stack)
newStack = [9,0]
stack.extend(newStack)
print(stack)
stack.reverse()
print(stack)
stack.sort()
print(stack)
stack.insert(3, 11)
print(stack) |
28eb38c9be8b6bcde8306006b73bf235622c0b64 | notricky-7709/hangman-py | /hangman.py | 357 | 3.9375 | 4 | from random_word import RandomWords as get_word
import math
def welcome(name_input):
print("Hello," , name_input)
def get_word():
return get_word.get_random_word(hasDictionaryDef = True ,min_Length = 4)
def main():
name = str(input("Hello, what's your name? I'm "))
\
welcome(name)
loop_status = True
while True:
word = str(get_word())
main() |
265c508362b1b13246d3a9fadf344cc8a195277d | juandab07/Algoritmos-y-programacion | /ejercicio_4.py | 205 | 3.71875 | 4 | """
entradas
valorcompra->float->c
salidas
valortotal->float->t
"""
#entradas
c=float(input("digite valor de su compra " ))
#cajanegra
t=c*0.15
#salidas
print("el valor total por su compra es: " +str(c-t)) |
53c20ef34129674051fc4f8e796ef87e8b4acb96 | JUANPER-GITHUB/EJERCICIOS-30-DE-ABRIL | /PUNTO26.py | 189 | 3.921875 | 4 | # PUNTO 26
x = float(input("Digite un numero: "))
if x >= 10:
print("El triple del valor ingresado es:", x * 3)
else:
print("La cuarta parte del numero ingresado es:", x / 4)
|
a81e3ce357470dccb42b942f2a559edbe0ff16c2 | diandraygp/slides | /python-programming/examples/tk/tk_demo.py | 3,143 | 3.59375 | 4 | import tkinter as tk
from tkinter import messagebox, filedialog
import os
def scary_action():
messagebox.showerror(title = "Scary", message = "Deleting hard disk. Please wait...")
def run_code():
text = ""
text += "Name: {}\n".format(name.get())
text += "Password: {}\n".format(password.get())
text += "Animal: {}".format(animal.get())
text += "Colors: "
for ix in range(len(colors)):
if colors[ix].get():
text += color_names[ix] + " "
text += "\n"
text += "Filename: {}\n".format( os.path.basename(filename_entry.get()) )
messagebox.showinfo(title = "Running with", message = text)
def close_app():
app.destroy()
app = tk.Tk()
app.title('Simple App')
menubar = tk.Menu(app)
app.config(menu=menubar)
menu1 = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", underline=0, menu=menu1)
menu1.add_separator()
menu1.add_command(label="Exit", underline=1, command=close_app)
top_frame = tk.Frame(app)
top_frame.pack(side="top")
pw_frame = tk.Frame(app)
pw_frame.pack(side="top")
# Simple Label widget:
name_title = tk.Label(top_frame, text=" Name:", width=10, anchor="w")
name_title.pack({"side": "left"})
# Simple Entry widget:
name = tk.Entry(top_frame)
name.pack({"side": "left"})
#name.insert(0, "Your name")
# Simple Label widget:
password_title = tk.Label(pw_frame, text=" Password:", width=10, anchor="w")
password_title.pack({"side": "left"})
# In order to hide the text as it is typed (e.g. for Passwords)
# set the "show" parameter:
password = tk.Entry(pw_frame)
password["show"] = "*"
password.pack({"side": "left"})
radios = tk.Frame(app)
radios.pack()
animal = tk.StringVar()
animal.set("Red")
my_radio = []
animals = ["Cow", "Mouse", "Dog", "Car", "Snake"]
for animal_name in animals:
radio = tk.Radiobutton(radios, text=animal_name, variable=animal, value=animal_name)
radio.pack({"side": "left"})
my_radio.append(radio)
checkboxes = tk.Frame(app)
checkboxes.pack()
colors = []
my_checkbox = []
color_names = ["Red", "Blue", "Green"]
for color_name in color_names:
color_var = tk.BooleanVar()
colors.append(color_var)
checkbox = tk.Checkbutton(checkboxes, text=color_name, variable=color_var)
checkbox.pack({"side": "left"})
my_checkbox.append(checkbox)
def open_filename_selector():
file_path = filedialog.askopenfilename(filetypes=(("Any file", "*"),))
filename_entry.delete(0, tk.END)
filename_entry.insert(0, file_path)
filename_frame = tk.Frame(app)
filename_frame.pack()
filename_label = tk.Label(filename_frame, text="Filename:", width=10)
filename_label.pack({"side": "left"})
filename_entry = tk.Entry(filename_frame, width=60)
filename_entry.pack({"side": "left"})
filename_button = tk.Button(filename_frame, text="Select file", command=open_filename_selector)
filename_button.pack({"side": "left"})
buttons = tk.Frame(app)
buttons.pack()
scary_button = tk.Button(buttons, text="Don't click here!",fg="red", command=scary_action)
scary_button.pack({"side": "left"})
action_button = tk.Button(buttons, text="Run", command=run_code)
action_button.pack()
app.mainloop()
|
ade2ab74de0090cf17ccf0e28d61e763a2cf35f9 | jincurry/LeetCode_python | /705_Design_HashSet.py | 2,053 | 3.84375 | 4 | # Design a HashSet without using any built-in hash table libraries.
# To be specific, your design should include these functions:
# add(value): Insert a value into the HashSet.
# contains(value) : Return whether the value exists in the HashSet or not.
# remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.
# Example:
# MyHashSet hashSet = new MyHashSet();
# hashSet.add(1);
# hashSet.add(2);
# hashSet.contains(1); // returns true
# hashSet.contains(3); // returns false (not found)
# hashSet.add(2);
# hashSet.contains(2); // returns true
# hashSet.remove(2);
# hashSet.contains(2); // returns false (already removed)
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.buckets = 1000
self.itemsPerBucket = 1001
self.table = [[] for _ in range(self.buckets)]
def hash(self, key):
return key % self.buckets
def pos(self, key):
return key // self.buckets
def add(self, key):
"""
:type key: int
:rtype: void
"""
hashkey = self.hash(key)
if not self.table[hashkey]:
self.table[hashkey] = [0] * self.itemsPerBucket
self.table[hashkey][self.pos(key)] = 1
def remove(self, key):
"""
:type key: int
:rtype: void
"""
hashkey = self.hash(key)
if self.table[hashkey]:
self.table[hashkey][self.pos(key)] = 0
def contains(self, key):
"""
Returns true if this set did not already contain the specified element
:type key: int
:rtype: bool
"""
hashkey = self.hash(key)
return (self.table[hashkey] != []) and (self.table[hashkey][self.pos(key)] == 1)
if __name__ == '__main__':
obj = MyHashSet()
obj.add(12)
obj.add(1002)
print(obj.contains(12))
print(obj.contains(133))
obj.add(12)
print(obj.contains(12))
obj.remove(1002)
print(obj.contains(1002))
|
1253c01a036fca4288293d334f63f4d825c8b3b5 | Ramakanth001/CyberSec-Blogs-Bombe | /bombe/logic.py | 4,952 | 3.6875 | 4 | # Implementation of Affine Cipher in Python
from PIL import Image
# Extended Euclidean Algorithm for finding modular inverse
# eg: modinv(7, 26) = 15
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def modinv(a, m):
gcd, x, y = egcd(a, m)
if gcd != 1:
return None # modular inverse does not exist
else:
return x % m
# affine cipher encrytion function
# returns the cipher text
def affine_encrypt(text, key):
'''
C = (a*P + b) % 26
'''
return ''.join([ chr((( key[0]*(ord(t) - ord('A')) + key[1] ) % 26)
+ ord('A')) for t in text.upper().replace(' ', '') ])
# affine cipher decryption function
# returns original text
def affine_decrypt(cipher, key):
'''
P = (a^-1 * (C - b)) % 26
'''
return ''.join([ chr((( modinv(key[0], 26)*(ord(c) - ord('A') - key[1]))
% 26) + ord('A')) for c in cipher ])
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return(key)
elif len(string) > len(key):
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return("" . join(key))
else:
key = key[:len(string)]
return(key)
print(key)
# This function returns the
# encrypted text generated
# with the help of the key
def cipherText(string, key):
cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) + ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
return("" . join(cipher_text))
# This function decrypts the
# encrypted text and returns
# the original text
def originalText(cipher_text, key):
orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
return("" . join(orig_text))
# Python program implementing Image Steganography
# PIL module is used to extract
# pixels of image and modify it
# Convert encoding data into 8-bit binary
# form using ASCII value of characters
def genData(data):
# list of binary codes
# of given data
newd = []
for i in data:
newd.append(format(ord(i), '08b'))
return newd
# Pixels are modified according to the
# 8-bit binary data and finally returned
def modPix(pix, data):
datalist = genData(data)
lendata = len(datalist)
imdata = iter(pix)
for i in range(lendata):
# Extracting 3 pixels at a time
pix = [value for value in imdata.__next__()[:3] +
imdata.__next__()[:3] +
imdata.__next__()[:3]]
# Pixel value should be made
# odd for 1 and even for 0
for j in range(0, 8):
if (datalist[i][j] == '0' and pix[j]% 2 != 0):
pix[j] -= 1
elif (datalist[i][j] == '1' and pix[j] % 2 == 0):
if(pix[j] != 0):
pix[j] -= 1
else:
pix[j] += 1
# pix[j] -= 1
# Eighth pixel of every set tells
# whether to stop ot read further.
# 0 means keep reading; 1 means thec
# message is over.
if (i == lendata - 1):
if (pix[-1] % 2 == 0):
if(pix[-1] != 0):
pix[-1] -= 1
else:
pix[-1] += 1
else:
if (pix[-1] % 2 != 0):
pix[-1] -= 1
pix = tuple(pix)
yield pix[0:3]
yield pix[3:6]
yield pix[6:9]
def encode_enc(newimg, data):
w = newimg.size[0]
(x, y) = (0, 0)
for pixel in modPix(newimg.getdata(), data):
# Putting modified pixels in the new image
newimg.putpixel((x, y), pixel)
if (x == w - 1):
x = 0
y += 1
else:
x += 1
# Encode data into image
def encode(cipher_text, img):
image = Image.open(img, 'r')
print('Image opened')
data = cipher_text
if (len(data) == 0):
print('Data length is zero')
raise ValueError('Data is empty')
newimg = image.copy()
print(newimg)
encode_enc(newimg, data)
newimg.save(img, str(img.split(".")[1].upper()))
return newimg
# Decode the data in the image
def decode(img):
image = Image.open(img, 'r')
data = ''
imgdata = iter(image.getdata())
while (True):
pixels = [value for value in imgdata.__next__()[:3] +
imgdata.__next__()[:3] +
imgdata.__next__()[:3]]
# string of binary data
binstr = ''
for i in pixels[:8]:
if (i % 2 == 0):
binstr += '0'
else:
binstr += '1'
data += chr(int(binstr, 2))
if (pixels[-1] % 2 != 0):
return data |
222afba2846e3e956afa4cbb0c3e810995470c20 | Aayan-Not-Foundatgit/Greater-Lesser-Guessing-Game | /main.py | 1,929 | 4.09375 | 4 | import random
print('Welcome to the Greater Lesser Guessing Game\n')
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
print('How many times do you want to play this game: ')
no_chances_input = int(input())
no_chances = no_chances_input
no_chances_used = 0
user_points = 0
computer_points = 0
while no_chances > no_chances_used:
user_input = int(input('Guess Any number from 0 - 20:'))
computer_input = random.choice(numbers)
if user_input > 20:
print('Enter a number between 0-20')
elif user_input > computer_input:
print('You got a point\n')
user_points = user_points + 1
print(f'Your points are - {user_points}')
computer_points = computer_points
print(f'Computer points are - {computer_points}\n')
print(f'You guessed - {user_input}')
print(f'Computer guessed - {computer_input}')
no_chances_used = no_chances_used + 1
print(f'Chances Used are - {no_chances_used}\n')
elif user_input < computer_input:
print('Computer got a point\n')
user_points = user_points
print(f'Your points are - {user_points}')
computer_points = computer_points + 1
print(f'Computer points are - {computer_points}\n')
print(f'You guessed - {user_input}')
print(f'Computer guessed - {computer_input}')
no_chances_used = no_chances_used + 1
print(f'Chances Used are - {no_chances_used}\n')
elif no_chances_used == no_chances:
print('Game over')
break
if computer_points > user_points:
print('Oops... Computer won\n')
print(f'Computer points are - {computer_points}')
print(f'Your points are - {user_points}')
elif computer_points < user_points:
print('Yay... You won\n')
print(f'Computer points are - {computer_points}')
print(f'Your points are - {user_points}')
elif computer_points == user_points:
print('Ohh... It tie\n')
print(f'Computer points are - {computer_points}')
print(f'Your points are - {user_points}')
else:
print('No data..')
|
a057826f025143b2bbae11cb07773b03ffb36208 | Maxi100a/pong | /game.py | 5,803 | 3.609375 | 4 | """
sys - system
random - for random numbers
pygame - for GUI
Player - the necessary player Class
Ball - the necessary ball class
Utilities: TEXT_FONT, HEIGHT, WIDTH
"""
import sys
import pygame
from Utilities import TEXT_FONT, HEIGHT, WIDTH, MENU_FONT
from Player import Player
from Ball import Ball
from Button import Button
from Slider import Slider
from SliderCircle import SliderCircle
# Constants
BALL = Ball()
PLAYER1 = Player((WIDTH, HEIGHT / 2), 1)
PLAYER2 = Player((0, HEIGHT / 2), 2)
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
FPS = pygame.time.Clock()
start_button = Button("Start!", (WIDTH / 2 - 100, HEIGHT - 50), \
bg=(69, 171, 0), hc=(41, 102, 0))
quit_button = Button("Quit", ((WIDTH / 2) + 100, HEIGHT - 50), \
bg=(240, 0, 0), hc=(143, 0, 0))
slow_button = Button("Slow", ((WIDTH / 2) - 115, HEIGHT / 2 + 90), \
bg=(255, 0, 0), hc=(200, 0, 0), font=MENU_FONT, size=(100, 35))
medium_button = Button("Medium", ((WIDTH / 2), HEIGHT / 2 + 90), \
bg=(200, 200, 0), hc=(155, 155, 0), font=MENU_FONT, size=(100, 35))
fast_button = Button("Fast", ((WIDTH / 2) + 115, HEIGHT / 2 + 90), \
bg=(0, 255, 0), hc=(0, 200, 0), font=MENU_FONT, size=(100, 35))
size_slider = Slider()
slider_circle = SliderCircle(size_slider.height)
def quit_game():
""" Shuts down the game """
print("Good bye! :(")
pygame.quit()
sys.exit()
def setup():
""" Sets up the pygame """
pygame.init()
pygame.display.set_caption("Pong")
def add_sprites(sprites):
""" Add the sprites to the passed sprite group """
sprites.add(start_button)
sprites.add(quit_button)
sprites.add(slow_button)
sprites.add(medium_button)
sprites.add(fast_button)
sprites.add(size_slider)
sprites.add(slider_circle)
def change_speed(new_speed):
""" Changes the speeds of the ball and both players """
BALL.x_vel = new_speed
BALL.y_vel = new_speed
PLAYER1.vel = new_speed
PLAYER2.vel = new_speed
def paint_messages():
""" Paints the welcome and the game speed messages """
welcome_msg = TEXT_FONT.render("Welcome to Pong!", True, (255, 255, 255))
welcome_msg_rect = welcome_msg.get_rect(center=(WIDTH / 2, 100))
ball_speed = MENU_FONT.render("Game Speed", True, (255, 255, 255))
ball_speed_rect = ball_speed.get_rect(center=(WIDTH/2, HEIGHT / 2 + 50))
SCREEN.blit(welcome_msg, welcome_msg_rect)
SCREEN.blit(ball_speed, ball_speed_rect)
def start_screen():
""" Presents the start screen, allowing user to specify settings """
sprites = pygame.sprite.Group()
add_sprites(sprites)
start = True
while start:
SCREEN.fill((0, 0, 0)) # paint screen black
# capture the mouse
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
# Handling quitting
if event.type == pygame.QUIT:
quit_game()
if event.type == pygame.MOUSEBUTTONDOWN:
if quit_button.rect.collidepoint(mouse_pos): # click quit
quit_game()
if start_button.rect.collidepoint(mouse_pos): # click start
start = False
if slow_button.rect.collidepoint(mouse_pos): # click slow
change_speed(5)
if medium_button.rect.collidepoint(mouse_pos): # click medium
change_speed(7)
if fast_button.rect.collidepoint(mouse_pos): # click fast
change_speed(10)
if slider_circle.rect.collidepoint(mouse_pos): # holding the slider
slider_circle.held = True
if event.type == pygame.MOUSEBUTTONUP:
if slider_circle.held: # let go of the slider
slider_circle.held = False
paint_messages()
# Draw each sprite
for sprite in sprites:
sprite.draw(SCREEN)
# Paint a player for displaying current length
SCREEN.blit(PLAYER2.surf, PLAYER1.rect)
# Handle slider_circle moving
slider_circle.move(PLAYER1, PLAYER2)
# update the display
pygame.display.update()
def paint_score(p1_score, p2_score):
""" Paints the score """
score = TEXT_FONT.render(str(p1_score) + ' : ' +\
str(p2_score), True, (255, 255, 255))
SCREEN.blit(score, ((WIDTH / 2) - score.get_rect().center[0], \
HEIGHT - score.get_rect().bottom ))
def game_loop():
""" Loop to handle the actual game function"""
# Create a sprite group
sprites = pygame.sprite.Group()
sprites.add(BALL)
sprites.add(PLAYER1)
sprites.add(PLAYER2)
run = True
while run:
SCREEN.fill((0,0,0)) # Paint screen black
paint_score(BALL.p1_score, BALL.p2_score) # paint score method
# handle quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game()
# handle mouse click
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
PLAYER1.reset((WIDTH, HEIGHT / 2))
PLAYER2.reset((0, HEIGHT / 2))
run = False
main()
# paint the sprites
for entity in sprites:
SCREEN.blit(entity.surf, entity.rect)
# check for collision
if BALL.rect.colliderect(PLAYER1):
BALL.collide(PLAYER1)
elif BALL.rect.colliderect(PLAYER2):
BALL.collide(PLAYER2)
# handle moving each sprite
PLAYER1.move()
PLAYER2.move()
BALL.move()
pygame.display.update()
FPS.tick(60)
def main():
""" Main loop. """
setup()
start_screen()
game_loop()
if __name__ == "__main__":
main()
|
dfabed759c2d58ecbe026103e57eb455f99e2d15 | Patrick-Ali/PythonLearning | /Lucas.py | 492 | 3.5625 | 4 | def lucas (n):
if n == 0:
return (2)
elif n == 1:
return (1)
else:
return(lucas(n-1)+lucas(n-2))
l = 30
n = lucas(l)
while n > 1:
print (n)
l = l - 1
n = lucas(l)
print ("for")
L = [2,1]
n = 31
for i in range (1):
m = (n-n)+2
while m != n:
l = L[m-1]
print (l)
r = L[m-2]
print(r)
lc = l + r
L.append(lc)
print(L)
m = m + 1
|
fb59dbdc13bb6fead1bc8c0a45288eca619ec34e | javedbaloch4/python-programs | /01-Basics/004-largest_number.py | 291 | 4.09375 | 4 | a = 345
b = 234
c = 456
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
print("The largest number between",a,b," and ",c," is ", largest)
print("<hr>Your task is invert - Write a program to find the smallest number among three") |
cd5ac2516f32eb835d2244dd521242bb2451b473 | tempflip/fin_playground | /learn_regr_polynomi2.py | 3,181 | 3.578125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
def read_stock(stock, usecols = ['Date', 'Adj Close']):
df = pd.read_csv('{}.csv'.format(stock), index_col='Date',
parse_dates=True,
usecols = usecols,
na_values = ['nan'])
df = df.rename(columns={'Adj Close' : stock})
return df
class Model:
def __init__(self):
self.model = None
self.description = "i'm an untrained model"
pass
def __str__(self):
return self.description
def train(self):
pass
def predict(self, x):
pass
class Linear_Model(Model):
def __init__(self):
Model.__init__(self)
pass
def train(self, training_x_matrix, training_y_matrix, degree=1):
self.degree = degree
# creating a 1...n space len of the training matrix
my_space = training_x_matrix.reshape(-1,1)
poly = PolynomialFeatures(degree=self.degree)
# polynominal features of the space
my_space_features = poly.fit_transform(my_space)
# training the model
regr = linear_model.LinearRegression()
regr.fit(my_space_features, training_y_matrix)
self.model = regr
self.description = "i'm a linear model of {} degree".format(self.degree)
def predict(self, x):
## as it is trained on polynominal features, we need to transform x
poly = PolynomialFeatures(degree=self.degree)
polynominal_features = poly.fit_transform(x)
return self.model.predict(polynominal_features)[0]
class Linear_Model_Avg(Linear_Model):
def __init__(self):
Linear_Model.__init__(self)
def predict(self, x):
poly = PolynomialFeatures(degree=self.degree)
polynominal_features = poly.fit_transform(x)
return self.model.predict(polynominal_features).flatten().mean()
def run():
start_date = '2014-01-01'
end_date = '2015-12-31'
df = pd.DataFrame(index=pd.date_range(start_date, end_date))
my_stocks = ['AAPL', 'GOOG', 'IBM', 'CRM'];
for stock in my_stocks:
df = df.join(read_stock(stock), how='inner')
df.sort_index(inplace=True)
daily = df[1:] / df[:-1].values
normalized = df / df.values[1]
train_data = normalized[['AAPL', 'GOOG']]
linear_space = np.arange(len(normalized.index))
m = Linear_Model_Avg()
m.train(linear_space, train_data.values, degree = 12)
normalized['PRE'] = [m.predict(x) for x in linear_space]
fig, ax1 = plt.subplots(1)
normalized['AAPL'].plot(ax = ax1)
normalized['GOOG'].plot(ax = ax1)
normalized['CRM'].plot(ax = ax1)
normalized['PRE'].plot(ax = ax1)
'''
normalized['CRM'].plot(ax = ax1)
linear_space = np.arange(len(normalized.index))
for degree in range(20):
m = Linear_Model()
m.train(normalized.index, normalized['CRM'], degree = degree)
prediction_name = 'CRM_PREDICT_{}'.format(degree)
normalized[prediction_name] = np.array( [m.predict(x) for x in linear_space])
normalized[prediction_name].plot(ax = ax1)
'''
'''
fig, (ax1, ax2, ax3,) = plt.subplots(3, sharex=True)
df.plot(ax=ax1, title='Historical Prices')
normalized['CRM'].plot(ax=ax1, title='CRM')
normalized.plot(ax=ax2, title='Normalized Prices')
daily.plot(ax=ax3, title='Daily Returns')
'''
plt.show()
if __name__ == '__main__':
run() |
3ff9a75ae116add64759faa399ccd03ddbacd201 | lixianjian/brush | /algorithm/sorts.py | 6,739 | 3.875 | 4 | #!/usr/bin/env /usr/local/bin/python3
# -*- coding: utf-8 -*-
'''
Created on 2017年8月30日
@author: lixianjian
'''
def quick_sort(a, low, high):
# 快速排序
if low > high:
return a
mid = a[low]
i = low + 1
head, tail = low, high
while head < tail:
if a[i] > mid:
a[tail], a[i] = a[i], a[tail]
tail -= 1
else:
a[head], a[i] = a[i], a[head]
head += 1
i += 1
a[head] = mid
quick_sort(a, low, head - 1)
quick_sort(a, head + 1, high)
return a
def merge(left, right):
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
def merge_sort(nums):
# 归并排序
if len(nums) <= 1:
return nums
num = len(nums) // 2
left = merge_sort(nums[:num])
right = merge_sort(nums[num:])
nums = merge(left, right)
return nums
# 整数排序 II
# 给一组整数,按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。
# 总耗时: 2942 ms
class Solution:
def merge(self, A, llow, lhigh, rlow, rhigh):
i, j = 0, 0
low = llow
left = A[llow:lhigh]
right = A[rlow:rhigh]
while i < len(left) and j < len(right):
if left[i] <= right[j]:
A[low] = left[i]
i += 1
else:
A[low] = right[j]
j += 1
low += 1
if left[i:]:
A[low:rhigh] = left[i:]
elif right[j:]:
A[low:rhigh] = right[j:]
def merge_sort(self, A, llow=0, rhigh=0):
# 归并排序
length = rhigh - llow
if length <= 1:
return
num = llow + length // 2
self.merge_sort(A, llow, num)
self.merge_sort(A, num, rhigh)
self.merge(A, llow, num, num, rhigh)
def sortIntegers2(self, A):
# Write your code here
# 归并排序
self.merge_sort(A, 0, len(A))
import math
class Solution2:
def sortIntegers2(self, A, radix=10):
k = int(math.ceil(math.log(max(A), radix)))
bucket = [[] for i in range(radix)]
for i in range(1, k + 1):
for j in A:
bucket[j // (radix**(i - 1)) % (radix**i)].append(j)
del A[:]
for z in bucket:
A += z
del z[:]
return A
# 摆动排序
# 给你一个没有排序的数组,请将原数组就地重新排列满足如下性质
# nums[0] <= nums[1] >= nums[2] <= nums[3]....
# 样例
# 给出数组为 nums = [3, 5, 2, 1, 6, 4] 一种输出方案为 [1, 6, 2, 5, 3, 4]
# 总耗时: 522 ms
class Solution3(object):
"""
@param {int[]} nums a list of integer
@return nothing, modify nums in-place instead
"""
def wiggleSort(self, nums):
# Write your code here
def s(nums, low, high):
if low > high:
return nums
mid = nums[low]
i = low + 1
head, tail = low, high
while head < tail:
if nums[i] > mid:
nums[tail], nums[i] = nums[i], nums[tail]
tail -= 1
else:
nums[head], nums[i] = nums[i], nums[head]
head += 1
i += 1
nums[head] = mid
if head > self.k:
s(nums, low, head - 1)
else:
s(nums, head + 1, high)
print(nums)
return nums
length = len(nums)
if length < 3:
if length == 2:
if nums[0] > nums[1]:
nums[0], nums[1] = nums[1], nums[0]
return nums
self.k = (length - 1) // 2
s(nums, 0, length - 1)
print(nums, self.k)
self.k += 1
if length % 2 == 0:
for i in range(1, self.k, 2):
nums[i], nums[self.k + i] = nums[self.k + i], nums[i]
else:
for i in range(1, self.k + 1, 2):
nums[i], nums[length - i] = nums[length - i], nums[i]
return nums
def wiggleSortBak(self, nums):
# Write your code here
for i in range(1, len(nums)):
r = i % 2
c = nums[i - 1]
n = nums[i]
if (r > 0 and c > n) or (r == 0 and c < n):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
def quik_sort_review(nums, low, high):
""" 快速排序
"""
if low > high:
return nums
tmp = nums[low]
i = low + 1
head, tail = low, high
while head < tail:
if nums[tail] > tmp:
nums[tail], nums[i] = nums[i], nums[tail]
tail -= 1
else:
nums[head], nums[i] = nums[i], nums[head]
head += 1
i += 1
nums[head] = tmp
quik_sort_review(nums, low, head - 1)
quik_sort_review(nums, head + 1, high)
return nums
def merge_sort_review(nums):
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
lval = left[i]
rval = right[j]
if lval <= rval:
result.append(lval)
i += 1
else:
result.append(rval)
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
length = len(nums)
if length < 2:
return nums
mid = length // 2
left = merge_sort_review(nums[:mid])
right = merge_sort_review(nums[mid:])
return merge(left, right)
def choose_sort_review(nums):
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if nums[i] <= nums[j]:
continue
nums[i], nums[j] = nums[j], nums[i]
return nums
def bubble_sort_review(nums):
length = len(nums)
for i in range(length):
for j in range(length - i - 1):
if nums[j] <= nums[j + 1]:
continue
nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(nums)
return nums
if __name__ == '__main__':
# s = Solution3()
# nums = [3, 5, 2, 1, 6, 4]
# nums = [1, 1, 1, 1, 2]
# s.wiggleSort(nums)
# print(nums)
nums = [3, 5, 2, 1, 6, 4]
# print(quik_sort_review(nums, 0, 5))
# print(merge_sort_review(nums))
# print(choose_sort_review(nums))
print(bubble_sort_review(nums))
|
bf3b1a0b01eb35a3ce152770b19b02c30c0fff8d | zxycode-2020/python_base | /day06/9-关键字参数/关键字参数.py | 207 | 3.625 | 4 |
'''
概念:允许函数调用时参数的顺序与定义时不一致
'''
def myPrint(str, age):
print(str, age)
#使用关键字参数
myPrint(age = 18, str = "sunck is a good man")
|
deeed8d288208bfc68cc4d7fd11bc3ae55e886c5 | BugChef/yandex_alghoritms | /sprint5/balanced_tree.py | 596 | 3.515625 | 4 | class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.right = right
self.left = left
def solution(root: Node) -> bool:
return is_balanced_helper(root) > -1
def is_balanced_helper(root: Node):
if root is None:
return 0
left_height = is_balanced_helper(root.left)
if left_height == -1:
return -1
right_height = is_balanced_helper(root.right)
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1 |
70c868543ad5c2f5951915ff6dcef59008c01df4 | sandeep-iitr/WebAPI_Databases_Cool_Project_2017 | /LAAC/Assignments/graphs.py | 1,863 | 4.125 | 4 | #!/usr/bin/python2.6
# Graph Theory easy exercises for Social Networks module
# LACC 2016
#*************************************
# This is where you write your code
#
# matrix_load()
#
# Loads an adjacency matrix for a graph from a file
#
# input: none
# output: matrix containing each node
#
# Note: You can open a file using open("filename.txt")
#
# You can get a list containing each line with file.readlines()
#
# You'll need to grab each number from each line, cast it to an
# int using int() and place it into your matrix
#
# A matrix is just a double list (e.g., x[][] )
#*************************************
N= 0
def matrix_load():
file = open("matrix.txt")
matrix = []
string = file.readlines()
global N
N = int(string[0])
for i in range(1, N+1):
dummy = []
for j in range(0, N):
dummy.append(string[i][j])
matrix.append(dummy)
file.close()
return matrix
#*************************************
# This is where you write your code
#
# print_degrees(mat)
#
# Prints the degrees of all nodes in a graph given an adj. matrix
#
# input: the adjacency matrix of the graph
# output: none
#
# Note: You don't need to return anything.
#
# Effectively, you'll need to count the number of 1s in each row
# (or each column) and print this. Use a nested loop (for or while)
#*************************************
def print_degrees():
matrix = matrix_load()
total = []
for i in range(0, N):
count = 0
for j in range(0, N):
if(int(matrix[i][j]) == 1):
count = count + 1
total.append(count)
for i in range(0, N):
print((i+1), total[i])
|
ed072ebf47ba43265ca7ab043f7980cf748263ca | kentronnes/python_crash_course | /python_work/Python Crash Course Chapter 8/8-5 cities.py | 234 | 3.890625 | 4 | def city(city_name, country='the united states'):
"""Diplays a city and the country it is in."""
print("\n" + city_name.title() + " is in " + country.title() + ".")
city('denver')
city(city_name='austin')
city('barcelona', 'spain') |
3b6f4d36144a6c1f48930a76089935dda1d1a988 | Srizon143005/Python-Basic-Learning-Codes | /Numpy/All Exercises (1-9).py | 1,694 | 3.609375 | 4 | # All exercises for numpy
import numpy as np
# Exercise - 1
print("Exercise - 1:")
v = np.array([0,1,2,3,4,5,6,7,8,9])
print(v)
print(), print(), print()
# Exercise
print("Exercise - 2:")
p = []
for i in range(len(v)):
if i%2 != 0:
p.append(v[i])
p = np.array(p)
print(p)
print(), print(), print()
# Exercise - 3
print("Exercise - 3:")
q = []
for i in range(len(v)-1, -1, -1):
q.append(v[i])
q = np.array(q)
print(q)
print(), print(), print()
# Exercise - 4
print("Exercise - 4:")
a = np.array([1,2,3,4,5])
b = a[1:4]
print(a[1])
print(), print(), print()
# Exercise - 5
print("Exercise - 5:")
m = np.array([ [1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25] ])
print("m:\n", m)
print(), print(), print()
# Exercise - 6
print("Exercise - 6:")
s = []
for row in m:
tmp = []
for i in range(len(row)-1, -1, -1):
tmp.append(row[i])
s.append(tmp)
s = np.array(s)
print(s)
print(), print(), print()
# Exercise - 7
print("Exercise - 7:")
rev_s = []
for i in range(len(m)-1, -1, -1):
rev_s.append(m[i])
rev_s = np.array(rev_s)
print(rev_s)
print(), print(), print()
# Exercise - 8
print("Exercise - 8:")
rev_all_s = []
for i in range(len(s)-1, -1, -1):
rev_all_s.append(s[i])
rev_all_s = np.array(rev_all_s)
print(rev_all_s)
print(), print(), print()
# Exercise - 9
print("Exercise - 9:")
n = m[1:len(m)-1, 1:len(m[0])-1]
print(n)
print(), print(), print()
print("All Exercises Done, Bro! Chill...! :D") |
43797ed4ffce33cf52d52c62a7f32869ba7bc324 | karghar/Cracking | /chapter2/task3.py | 358 | 3.515625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteMiddle(self, node):
if not node or not node.next:
return node
node.val = node.next.val
nodeNext = node.next
node.next = None, node.next.next
#garbage collections
nodeNext.next = None
|
aadfae08372e7d487a396c1e767b39e82cc1d0a4 | Bishopbhaumik/python_test | /guess.py | 341 | 3.921875 | 4 | import random
wi=random.randint(0,9)
a=int(input("Guess the no:--"))
if wi==a:
print("YOU WIN THE GAME\n CONGRATS!!!")
elif wi<a:
print("you entered a higher no than actual number>")
elif wi>a:
print("You enterd a lower no than the actual no")
print(f"The actual no is {wi}")
print("nice tutorial\n"*10)
|
ebc095b8d48c85dfa674510054be65fb75c290b0 | marotoku/multi-agent-simulator | /multi-agent-simulator/PsychologicalModel.py | 1,166 | 3.828125 | 4 | import random
from math import tanh
class AbstractModel():
'''
this class provides an abstract model of person's psychological model to decide whether to buy a product.
'''
def __init__(self, market, product):
self.market = market
self.product = product
def purchaseProbability(self):
pass
class SimpleInnovatorModel(AbstractModel):
'''
Innovators purchase a product with a certain probability (free parameter).
'''
def __init__(self, market, product, purchaseProbability):
self.__purchaseProbability = purchaseProbability
def purchaseProbability(self):
return self.__purchaseProbability
class SimpleEarlyAdopterModel(AbstractModel):
'''
Early Adopters decide to purchase based on advertisement and market NPS score.
'''
def __init__(self, market, product, coefNPS, coefAdvertise):
self.market = market
self.product = product
self.coefNPS = coefNPS
self.coefAdvertise = coefAdvertise
def purchaseProbability(self):
return tanh(self.coefNPS * self.market.NPS + self.coefAdvertise * self.product.advertise()) |
96bf8b9ee0cfbf6d7af3ab98c628cbcfd88c3efa | BenRStutzman/kattis | /Open Kattis/cetvrta.py | 327 | 3.640625 | 4 | x_coords = []
y_coords = []
for i in range(3):
coords = input().split()
x_coords.append(coords[0])
y_coords.append(coords[1])
for x_coord in x_coords:
if x_coords.count(x_coord) == 1:
print(x_coord, end = ' ')
for y_coord in y_coords:
if y_coords.count(y_coord) == 1:
print(y_coord)
|
7fdb9274732f3ce61015515d208423981751182d | NicholasFay-CIS/Algorithms | /HW02/hw06Mem.py | 2,787 | 3.765625 | 4 | import sys
import string
from decimal import Decimal
#using Memoization
def get_options(inputfile):
"""
FILE obj->int
This gets the amount of options from the input file
"""
return int(inputfile.readline())
def get_amount(inputfile):
"""
FILE obj->int
This gets the budget from the input file
"""
return int(inputfile.readline())
def createlists(inputfile, v, c, s):
"""
FILE obj->list
This function copies the set of data from the input file into
the value and calorie arrays
"""
for line in inputfile:
line = line.split()
v.append(int(line[0]))
c.append(int(line[1]))
s.append(line[2])
return
def find_items(size, food_array, W, v, s):
"""
list,list,int,list,list -> None
This function will determine exactly how much of
what food items we need to reach our exact cost
"""
while(W > 0):
#while the budget is not zero
#update the frequency array of food items
food_array[size[W]] += 1
#subtract the food item cost from our budget
W -= v[size[W]]
for i in range(0, len(food_array)):
if(food_array[i] != 0):
#go through the food array and print the number of items per non zero menu item
print("{} {}".format(s[i], food_array[i]))
return
def CMINM(w, v, c, MCAL, size, n):
"""
int, list, list, list, list, int -> int
returns the minimum amount of calories that we could eat
"""
#base case if w = zero
if w == 0:
return 0
# if at w it is undefined
if MCAL[w] == sys.maxint:
for i in range(0, n):
#value at index i is less than w
if v[i] <= w:
#recursive call
temp = CMINM(w - v[i], v, c, MCAL, size, n)
if(temp + c[i] < MCAL[w]):
#update the list
MCAL[w] = temp + c[i]
#add to the frequency array
size[w] = i
return MCAL[w]
def main():
#get the input file
inputfile = sys.stdin
#changes the max recursion limit so can pass more test cases
sys.setrecursionlimit(1000000000)
#sets up arrays for the cost, calories
x = sys.maxint
v = []
c = []
s = []
#number of menu items and the amount we want to spend
n = get_options(inputfile)
W = get_amount(inputfile)
size = [x] * (W + 1)
food_array = [0] * n
#create lists for v and c
createlists(inputfile, v, c, s)
#get the min calories
MCAL = [None] * (W + 1)
#created the MCAL ARRAY
#set first index to be zero, (if w = 0, MCAL[w] = 0)
MCAL[0] = 0
#set the remaining indices to be negative infinity
for i in range(1, W + 1):
MCAL[i] = sys.maxint
#print("There are {} menu options".format(n))
#print("We want to spend {}".format(W))
min_cal = CMINM(W, v, c, MCAL, size, n)
if(min_cal == sys.maxint):
print("Not Possible to spend exactly: {}".format(W))
return
print("Possible to spend exactly: {}".format(W))
print("Minimum Calories: {}".format(min_cal))
find_items(size, food_array, W, v, s)
main()
|
719b2cb1b207dfc27058dc1094c6656d0fea2720 | AIHackerTest/nanshanpai_Py101-004 | /Chap0/project/ex37.py | 642 | 3.609375 | 4 | print(True and True)
a = [1,2,3]
del a[0]
print a
from sys import exit
print(not True)
#while a != '0': 循环语句
#with class as b:
#elif 条件语句
# global 全局 变量定义 global x
# or逻辑运算
#assert 断言语句 如果发生错误按约定方式提醒
# if elif else
#pass 让程序什么也不做
#yield 是一个生成器 可以用next() 调用其值
#break 跳出当前条件缩进部分 而非全局exit
#coutinue如果条件为真则继续执行 条件下的动作,
#try except finally 异常处理语句
#return 返回值 ,def定义函数 for 循环语句 lambda是一个表达式 可以快速嵌入函数 |
1c2b6435fc5b5fc88fb6aa037591c61aed44a8ff | mountlovestudy/leetcode | /ProductOfArrayExceptSelf.py | 1,051 | 3.953125 | 4 | """
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
"""
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if [] == nums:
return nums
if len(nums) == 1:
return [1]
result_list = [1]
product_val = nums[0]
for i in range(1, len(nums), 1):
result_list.append(product_val)
product_val *= nums[i]
product_val = nums[-1]
for i in range(len(nums)-2, -1, -1):
result_list[i] *= product_val
product_val *= nums[i]
return result_list |
395ad6767ae5b01b7ea346758f8ae7f093c1238d | Arjun2001/coding | /hackerrank/hackerrank Super Reduced String.py | 216 | 3.546875 | 4 | s = "aaabccddd"
index = 1
while index < len(s):
if s[index] == s[index - 1]:
s = s[:index -1] + s[index +1:]
index = 0
index += 1
if len(s) == 0:
print("Empty String")
else:
print(s)
|
0b7ac723cba81ed8d2b9dac4fe143766295485ed | maskedoverflow/project_euler_lib | /python/problem3.py | 694 | 3.75 | 4 | def factorize_odd(n):
if not isinstance(n, int):
raise TypeError
if n % 2 == 0:
yield 2
for x in range(3, int(n ** .5), 2):
if n % x == 0:
yield x
reverse = n // x
if reverse != x:
yield n // x
def is_prime(n):
if not isinstance(n, int):
raise TypeError
if n & 1 == 0:
return True
for x in range(3, int(n ** .5), 2):
if n % x == 0:
return False
return True
def prime_factors(n):
if not isinstance(n, int):
raise TypeError
return {x for x in factorize_odd(n) if is_prime(x)}
factors = prime_factors(600851475143)
print(max(factors))
|
63b3a3011e71fc5fd46f9c314b767daf266c5760 | Rafaelbarr/100DaysOfCodeChallenge | /day021/003_multiplying_table.py | 422 | 3.796875 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
def run():
length = int(raw_input('How may steps long you want the stairs?: '))
for j in range(1, length):
print(' ')
for i in range(1, length):
k = i * j
if k > 10:
print(k, end=' ')
else:
print(k, end=' ')
if __name__ == '__main__':
run() |
cf6203d17839172a369186b79a58669be2518da7 | outsider4444/python-turtle | /zd10.py | 169 | 3.796875 | 4 | import turtle
t = turtle.Turtle()
t.shape('turtle')
n = 6
x = 1
def flower(x):
while x <= n:
t.circle(50)
t.left(360 / n)
x += 1
flower (x) |
09a976a2911093bfdd547ab28aa940c166086cba | bhavishya18/Let-s-Code-Python- | /Palindrome.py | 701 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
def palindrome(num):
if num<0:
return False
num=str(num)
n=len(num)
low=0
high=n-1
while low<high:
if num[low]==num[high]:
low+=1
high-=1
else:
return False
return True
num = input("Enter a number: ")
palindrome(num)
# In[14]:
# Palindrome program without converting to integer number to string
def palindrome(num):
if num<0:
return False
number=num
n = 0
while num:
n = n*10+(num%10)
num/=10
if n==number:
return True
return False
num = input("Enter a number: ")
palindrome(num)
# In[ ]:
|
d3ce114f01932d8b6ce0830d17e2da55fd1bdc6d | 1Lopez/examrem | /menuCONS.py | 927 | 3.65625 | 4 | j = 1
Asx = []
while j == 1:
print
print("Seleccione una opcion")
print("1)Nueva Tarea")
print("2)Listar Tarea")
print("3)Tareas Hechas")
print("4)Eliminar Tareas")
op = input("Ingrese la opcion:")
if op == "1":
print("NUEVA TAREA")
des = input("Ingrese la descripcion ")
tit = input("Ingrese el titulo ")
hecho = float(input("ingresa 1 si esta hecho o 0 si no "))
for i in M:
Asx.append(hecho,tit,hecho)
print(Asx)
j = 1
elif op == "2":
print("LISTADO DE TAREAS")
for i in M:
Asx.append(des, tit, hecho)
print(Asx)
elif op == "3":
print("LISTAR TAREAS HECHAS")
for i in Asx:
if hecho == 0:
print(i, end=" ")
elif op == "4":
print("TAREAS ELIMINADAS")
letras = ["", ""]
print("Programa terminado")
|
afdb89732a7f993f1c795858d3d443fee7c8511b | MasatakaShibataSS/lesson | /AI/examples/04/4.2.5-1-multiple_orderly.py | 1,156 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
### y = 3x_1 - 2x_2 + 1 のデータを作成
x1 = np.random.rand(100, 1) # 0 〜 1 までの乱数を 100 個つくる
x1 = x1 * 4 - 2 # 値の範囲を -2 〜 2 に変更
x2 = np.random.rand(100, 1) # x2 についても同様
x2 = x2 * 4 - 2
y = 3 * x1 - 2 * x2 + 1
### 学習
from sklearn import linear_model
x1_x2 = np.c_[x1, x2] # [[x1_1, x2_1], [x1_2, x2_2], ..., [x1_100, x2_100]]
# という形に変換
model = linear_model.LinearRegression()
model.fit(x1_x2, y)
### 係数、切片、決定係数を表示
print('係数', model.coef_)
print('切片', model.intercept_)
print('決定係数', model.score(x1_x2, y))
### グラフ表示
y_ = model.predict(x1_x2) # 求めた回帰式で予測
plt.subplot(1, 2, 1)
plt.scatter(x1, y, marker='+')
plt.scatter(x1, y_, marker='o')
plt.xlabel('x1')
plt.ylabel('y')
plt.subplot(1, 2, 2)
plt.scatter(x2, y, marker='+')
plt.scatter(x2, y_, marker='o')
plt.xlabel('x2')
plt.ylabel('y')
plt.tight_layout()
plt.show()
|
2d98663a23c9176ca5c831f0251e26574a2e4095 | grantwilk/barndles | /barndles_assembler/basm/pipeline/disassemble.py | 832 | 3.546875 | 4 | def disassemble_instruction(binary_instr):
"""
Disassembles a binary instruction
:param binary_instr: the binary
:return: the disassembled instruction as a dictionary
"""
# initialize dictionary with universal fields
instr_dict = {
"opcode": binary_instr >> 19,
"imm_flag": binary_instr >> 18 & 0x1,
"cpsr_flag": binary_instr >> 17 & 0x1,
"negate_flag": binary_instr >> 16 & 0x1,
}
# if immediate instruction
if instr_dict["imm_flag"] == 1:
instr_dict["imm"] = binary_instr >> 4 & 0xFFF
instr_dict["rd"] = binary_instr & 0xF
# if non-immediate instruction
else:
instr_dict["rm"] = binary_instr >> 8 & 0xF
instr_dict["rn"] = binary_instr >> 4 & 0xF
instr_dict["rd"] = binary_instr & 0xF
return instr_dict
|
4fc52493bee716dfdb4adcb2f0cc804fad4d8d0d | ToryTechs/calendar | /scheduled_task.py | 3,581 | 3.5 | 4 | #!/usr/bin/env python3
import argparse
import datetime
import os
import subprocess
def create_date_range(startdate, N, prev):
base_date = startdate
range_of_dates = []
if prev is True:
range_of_dates = [base_date - datetime.timedelta(days=x) for x in range(N)]
else:
range_of_dates = [base_date + datetime.timedelta(days=x) for x in range(N)]
return range_of_dates
def run():
argParser = argparse.ArgumentParser()
#change --today into today's date and generate a json file for that
argParser.add_argument("--today", help="Generate JSON file for today", action="store_true", required=False)
#next n amount of days
argParser.add_argument("--next-n-days", dest="nextndays", type=int, help="Generate JSON for next N consecutive days", required=False)
#past n days
argParser.add_argument("--past-n-days", dest="pastndays", type=int, help="Generate JSON for past N days in a row", required=False)
#flag to output a directory
argParser.add_argument("--outputadirectory", help="Output JSON files to directories [HOUSE]/[YEAR]/[MONTH]/[DAY]+[Timestamp].json", action="store_true", required=False)
# The House - Commons or Lords
argParser.add_argument("--house", help="The House (default: Commons)", required=False, default="Commons")
args = argParser.parse_args()
one_date_flag = False
date_range_flag = False
today_date = None
current_house = ""
date_range = []
the_previous_n = 0
the_next_n = 0
if args.today is True:
#call to create a json file just for today
today_date = datetime.date.today()
one_date_flag = True
elif args.nextndays is not None:
#create for next n days
the_next_n = args.nextndays
date_range_flag = True
elif args.pastndays is not None:
#create for past n days
the_previous_n = args.pastndays
date_range_flag = True
if args.house in ["Commons", "Lords"]:
current_house = args.house
if args.outputadirectory is True and one_date_flag is True:
#Commons len = 7, Lords len = 5, rest len = 10
string_range = len(current_house) + 10 - 2
path = current_house + "/" + str(today_date)[0:4] + "/" + str(today_date)[5:7] + "/" + str(today_date)[8:10] + ".json"
if not os.path.exists(path[0:int(string_range)]):
os.makedirs(path[0:int(string_range)])
subprocess.run("./main.py --jsondump --singledate %s --outputfile %s --house %s" % (str(today_date), path, current_house), check=False, shell=True)
elif args.outputadirectory is True and date_range_flag is True:
string_range = len(current_house) + 10 - 2
today_date = datetime.date.today()
date_range = []
if the_next_n != 0:
date_range = create_date_range(today_date, the_next_n, False)
elif the_previous_n != 0:
date_range = create_date_range(today_date, the_previous_n, True)
for date in date_range:
path = current_house +"/" + str(date)[0:4] + "/" + str(date)[5:7] + "/" + str(date)[8:10] + ".json"
if not os.path.exists(path[0:int(string_range)]):
os.makedirs(path[0:int(string_range)])
print(path)
subprocess.run("./main.py --jsondump --singledate %s --outputfile %s --house %s" % (str(date), path, current_house), check=False, shell=True)
if __name__ == '__main__':
run()
|
263d7b8ed2af32856886a4519b03909a3d7881ae | AnhquanNguyenn/PythonPracticeScripts | /Designing a Cash Register/change.py | 2,106 | 4.0625 | 4 | import sys
nameValue = {0.01: 'PENNY', 0.05: 'NICKEL', 0.1: 'DIME',
0.25: 'QUARTER', 0.5: 'HALF DOLLAR', 1.00: 'ONE', 2.00: 'TWO', 5.00: 'FIVE', 10.00: 'TEN', 20.00: 'TWENTY', 50.00: 'FIFTY', 100.00: 'ONE HUNDRED'}
# Array of Values holding each individual change value to loop through to find the change necesary
values = [100, 50, 20, 10, 5, 2, 1, 0.5, 0.25, 0.1, 0.05, 0.01]
def change(purchasePrice, cashGiven):
# If you gave less cash then the purchase price, you still owe money, error
if cashGiven < purchasePrice:
print("ERROR")
return
# if you gave equal cash to the purchase price then there is no change
elif purchasePrice == cashGiven:
print("ZERO")
return
# you gave more cash than the purchase price, find change
else:
# The amount of change necessary is the amount of cash - price
change = cashGiven - purchasePrice
# empty set to hold which values we need to use with change
results = set([])
# looping through each change value to see if it fits within the change
for value in values:
while change >= value:
results.add(value)
change = change - value
results = list(results)
results = [nameValue[result] for result in results]
results = sorted(results)
print(",".join(results))
return
# Tests
inputs = ["15.94;16.00", "17;16", "35;35", "45;50"]
for tests in inputs:
purchasePrice, cashGiven = tests.split(";")
purchasePrice = float(purchasePrice)
cashGiven = float(cashGiven)
change(purchasePrice, cashGiven)
#change(purchasePrice, cashGiven)
'''
for line in sys.stdin:
purchase_price, cashGiven = line.split(";")
purchase_price, cashGiven = float(purchase_price), float(cash)
change(purchase_price, cash)
'''
'''
Test 1
Test Input : 15.94;16.00
Expected Output : NICKEL,PENNY
Test 2
Test Input : 17;16
Expected Output : ERROR
Test 3
Test Input : 35;35
Expected Output : ZERO
Test 4
Test Input : 45;50
Expected Output : FIVE
'''
|
db4a77ff64b44456850c73c5a47d4178e2ead3be | huebschwerlen/Python | /Python_Review/objects.py | 4,750 | 3.703125 | 4 | #lottery_player = {
# 'name': 'sam',
# 'numbers': (12, 45, 67, 88) #values can be list, sets, tuples, dicts
#}
#print(lottery_player['name'])
#print(len(lottery_player['numbers']))
#print(sum(lottery_player['numbers']))
#
#
#
#
#
#
#
#
#class LotteryPlayer:
# def __init__(self):
# self.name = "Sam"
# self.numbers = (5, 6, 8, 3, 1, 20)
#
# def total(self):
# return sum(self.numbers)
#
#
#player = LotteryPlayer()
##player.name = "Josh"
##player.numbers = [(2, 54, 77, 88), {22, 33, 44, 55}]
#print(player.name)
#print(player.numbers)
#
#print(player.total())
#print(sum(player.numbers))
#
#
#
#
#
#player_one = LotteryPlayer()
#player_two = LotteryPlayer()
#
##player_one.name = 'sam'
#
#print(player_one == player_two) #false, two different instances
#print(player_one.name == player_two.name) #true till you define name
#
#
#
#
#
#
#
#
#class LotteryPlayer:
# def __init__(self, name, numbers):
# self.name = name
# self.numbers = numbers
#
# def total(self):
# return sum(self.numbers)
#
#
#player_one = LotteryPlayer('Sam', (22, 33, 44, 55, 66))
#player_two = LotteryPlayer('Tom', (33, 44, 55, 66, 77, 90))
#
#print(player_one.name)
#print(player_two.name)
#print(player_one.numbers)
#print(player_two.numbers)
#print(player_one == player_two)
#print(player_one.name == player_two.name)
#
#
#
#
#
#
###
#
#class Student:
# def __init__(self, name, school):
# self.name = name
# self.school = school
# self.marks = []
#
# def marks_avg(self):
# total = sum(self.marks)
# count = len(self.marks)
# return(total / count)
#
# @staticmethod
# def go_to_school(): #since we don't need to pass self with this, but it would do it by default, we need staticmethod decorator
# print('i am going to school')
#
# @classmethod
# def who(cls):
# print('i am {}'.format(cls))
#
#
##Use @classmethod when you need access to the class, but not an instance;
##
##Use @staticmethod when you want to put a method inside a class because it makes sense logically for it to be there, but you don't need access to the class or the instance.
#
#
#
#anna = Student('Anna', 'MIT')
#anna.marks = [22, 33, 44]
#anna.marks.append(69)
#print(anna.marks)
#print(anna.marks_avg())
#anna.go_to_school()
#anna.who()
#
#
#
###
#
#
#
#class Store:
# def __init__(self, name):
# self.name = name # You'll need 'name' as an argument to this method.
# self.items = [] # Then, initialise 'self.name' to be the argument, and 'self.items' to be an empty list.
#
# def add_item(self, name, price):
# item_dict = {'name': name, 'price': price}# Create a dictionary with keys name and price, and append that to self.items.
# self.items.append(item_dict)
#
# def stock_price(self):
# # Add together all item prices in self.items and return the total.
## naive
## total = 0
## for item in self.items:
## total += item['price']
## return total
#
# return sum([i['price'] for i in self.items])
#
#
#
#store1 = Store('Walgreens')
#store1.add_item('apple', 23)
#print(store1.stock_price())
#
#
#
#
#
#
###
class Store:
def __init__(self, name):
self.name = name
self.items = []
def add_item(self, name, price):
self.items.append({
'name': name,
'price': price
})
def stock_price(self):
total = 0
for item in self.items:
total += item['price']
return total
@classmethod
def franchise(cls, store):
# Return another store, with the same name as the argument's name, plus " - franchise"
return cls(store.name + ' - franchise') #cls is a ref to the class which is Store, so they are interchangeable here, see below
# return Store(store.name + ' - franchise') - - same thing as above
# return cls("{} - franchise".format(store.name)) - - yet another way
# new_store = Store(store.name + " - franchise") - - -also valid
# return new_store
@staticmethod
def store_details(store):
# Return a string representing the argument
# It should be in the format 'NAME, total stock price: TOTAL'
return "{}, total stock price: {}".format(store.name, int(store.stock_price())
|
5702ab9e61ef2d140c8a19c6aa0e2a7f11e038ed | 806334175/pystudy | /05_常用模块/13_re模块/re补充.py | 1,309 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>", "<h1>hello</h1>")) # ['h1']
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>", "<h1>hello</h1>").group()) # <h1>hello</h1>
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>", "<h1>hello</h1>").groupdict()) # <h1>hello</h1>
print(re.search(r"<(\w+)>\w+</(\w+)>", "<h1>hello</h1>").group())
print(re.search(r"<(\w+)>\w+</\1>", "<h1>hello</h1>").group())
# 补充一
# 补充二
# import re
# 使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,所有即使匹配成功小数也不会存入结果
# 而不是小数时,就去匹配(-?\d+),匹配到的自然就是,非小数的数,在此处即整数
#
print(re.findall(r"-?\d+\.\d*|(-?\d+)", "1-2*(60+(-40.35/5)-(-4*3))")) # 找出所有整数['1', '-2', '60', '', '5', '-4', '3']
# 找到所有数字:
print(re.findall('\D?(\-?\d+\.?\d*)', "1-2*(60+(-40.35/5)-(-4*3))")) # ['1','2','60','-40.35','5','-4','3']
# 计算器作业参考:http://www.cnblogs.com/wupeiqi/articles/4949995.html
expression = '1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
content = re.search('\(([\-\+\*\/]*\d+\.?\d*)+\)', expression).group() # (-3-40.0/5)
|
1074fc023a93a361d5f48889cf1bf43102058a2d | fabiobarretopro/Aprendendo-Python | /equi-isos-esca.py | 508 | 4.0625 | 4 | l1 = int(input(f"Digite um lado l1 do triângulo:"))
l2 = int(input(f"Digite um lado l2 do triângulo:"))
l3 = int(input(f"Digite um lado l3 do triângulo:"))
if l2 - l3 < l1 < l2 + l3 and l1 - l3 < l2 < l1 + l3 and l2 - l1 < l3 < l2 + l1:
print("É um triângulo!")
if l1 == l2 == l3:
print("Triângulo equilátero!")
elif l1 == l2 or l1 == l3 or l1 == l3:
print("Triângulo Isósceles!")
else:
print("Triângulo Escaleno!")
else:
print("Não é um triângulo!") |
34944cb24205a173c02b021b0a14a7d5ed2d69b7 | momentum-cohort-2018-10/w2d1-currency-converter-Komor-RP | /currency.py | 1,056 | 3.921875 | 4 |
def convert(rates, value, from_currency, to_currency):
if from_currency == to_currency:
return value
available_rates = []
for conversion in rates:
available_rates.append(conversion[0])
available_rates.append(conversion[1])
if (from_currency in conversion) and (to_currency in conversion):
if from_currency == conversion[0]:
return value * conversion[2]
elif from_currency == conversion[1]:
return value / conversion[2]
for conversion in rates:
if (from_currency in conversion) and (to_currency not in conversion) and (to_currency in available_rates):
if from_currency == conversion[0]:
return convert(rates, value * conversion[2], conversion[1], to_currency)
elif from_currency == conversion[1]:
return convert(rates, value / conversion[2], conversion[0], to_currency)
raise ValueError("Conversion rates unknown.")
|
77e1acdd0c2fa7b2932554c24c107428e117b914 | tryingtokeepup/Whiteboard-Pairing | /CountingVotes/kais_first_pass.py | 1,803 | 4.3125 | 4 | def count_votes(arr):
candidate_vote_tracker = {}
current_winner_votes = 0
current_winner = ''
# so, basically, we have a bunch of candidates who have votes inside the array that is passed to us.
# we need to iterate over the choosen candidates, and everytime they recieve a vote, if they don't have a count
# initialize them into the counts hash table, with their name and how many votes they have recieved.
for candidate in arr:
# if the candidate is not in the array
if candidate not in candidate_vote_tracker:
candidate_vote_tracker[candidate] = 0
# for all other cases, add to the candidate score
candidate_vote_tracker[candidate] += 1
if candidate_vote_tracker[candidate] > current_winner_votes:
current_winner_votes = candidate_vote_tracker[candidate]
# whoever is in the lead is the current presumed winner
current_winner = candidate
# however, we do have the condition that there are two or even more people tied
elif candidate_vote_tracker[candidate] == current_winner_votes:
# do a string comparison, whatever is first alphabetically wins... yeah, i know.
if candidate > current_winner:
current_winner = candidate
return current_winner
print(count_votes([
'veronica',
'mary',
'alex',
'james',
'mary',
'michael',
'alex',
'michael',
]))
# should print 'michael'
# print(
# count_votes([
# 'john',
# 'johnny',
# 'jackie',
# 'johnny',
# 'john',
# 'jackie',
# 'jamie',
# 'jamie',
# 'john',
# 'johnny',
# 'jamie',
# 'johnny',
# 'john',
# ])
# ) # should print 'johnny'
|
e3252fc240b461813f91ce45826f9945ad7e1784 | chukycheese/learning-materials | /python-101/data-structure/performQuickSort.py | 592 | 3.640625 | 4 | import random
N = 10
firstNumbers = list(range(N))
random.shuffle(firstNumbers)
print(firstNumbers)
def performQuickSort(seq, pivot = 0):
if len(seq) <= 1:
return seq
pivotValue = seq[pivot]
less = []
greater = []
for itr in range(len(seq)):
if iter == pivot:
continue
elif seq[itr] > pivotValue:
greater.append(seq[itr])
elif seq[itr] < pivotValue:
less.append(seq[itr])
return performQuickSort(less) + [pivotValue] + performQuickSort(greater)
print(performQuickSort(firstNumbers))
|
6d11fd956434d519b5a5372dabe17f786e73b2ac | boswellgathu/py_learn | /12_strings/longest_word.py | 297 | 3.671875 | 4 | # Program to display the longest word in a given sentence
# The sentence should be given as an input from the key board by the user
# If there are two words of equal length, it displays the first longest word
# for more info on this quiz, go to this url: http://www.programmr.com/longest-word-3 |
5f4f753f88a052ce63afac7cfa2c8610a88139cb | taraspyndykivskiy/python-laboratory | /laboratory7/task1.py | 3,342 | 3.734375 | 4 | #D:\Taras Pyndykivskiy\kpi\programming\programming_1\laboratory_works\#7
"""
Є текстовий файл.
Надрукувати:
його перший рядок;
його п'ятий рядок;
його перші 5 рядків;
його рядки з s1-го по s2-ий;
весь файл.
"""
import sys
import re
pattern=re.compile(r"^[+]?\d+$")
def init():
print("\nЛабораторна робота №7 \nПиндиківський Тарас, КМ-93")
print("16 варіант")
print("Завдання 1: Вивести вміст файлу")
def validator(pattern, prompt):
data=input(prompt)
while not bool(pattern.match(data)):
print("\nУвага! Ви ввели неправильне значення !")
data=input(prompt)
return data
def start_line_validator(pattern, prompt, number_lines):
number=int(validator(pattern, prompt))
while ((number<=0) or (number>number_lines-1)):
print("\nУвага! Ви ввели неправильне значення !")
number=int(validator(pattern, prompt))
return number
def finish_line_validator(pattern, prompt, start_line_to_print, number_lines):
number=int(validator(pattern, prompt))
while ((number<=start_line_to_print) or (number>number_lines)):
print("\nУвага! Ви ввели неправильне значення !")
number=int(validator(pattern, prompt))
return number
init()
cont=''
CGREEN='\033[32m'
CCYAN='\033[36m'
CEND='\033[0m'
CRED='\033[91m'
while cont=='':
cont=input("\nНатисніть Enter, щоб продовжити, будь-що інше, щоб завершити роботу з програмою ")
if(cont!=''):
break
try:
file=open("task1.py", 'r', encoding = "utf-8")
except FileNotFoundError:
print("Вказаного файлу не існує")
sys.exit()
number_lines=0
while True:
s = file.readline()
# print(s)
number_lines+=1
if not s:
break
file.close()
number_lines-=1
print(number_lines)
file=open("task1.py", 'r', encoding = "utf-8")
if number_lines<5:
print("\nУ Вашому файлі менше 5 рядків")
sys.exit()
file_lines = [line.strip() for line in file]
print(CRED + "\nПерший рядок файлу : " + CEND)
print(file_lines[0])
print(CRED + "\nП'ятий рядок файлу : " + CEND)
print(file_lines[4])
print(CRED + "\nПерші 5 рядків файлу" + CEND)
for i in range(5):
print(file_lines[i])
print('\n')
start_line_to_print=start_line_validator(pattern, "\nВведіть початковий номер рядка файлу : ", number_lines)-1
finish_line_to_print=finish_line_validator(pattern, "\nВведіть кінцевий номер рядка файлу : ", start_line_to_print, number_lines)-1
print(CRED + "\nВміст файлу з " + str(start_line_to_print) + " до " + str(finish_line_to_print) + " рядку." + CEND)
for i in range(start_line_to_print, finish_line_to_print+1):
print(CGREEN + file_lines[i] + CEND)
file.close()
file=open("task1.py", 'r', encoding = "utf-8")
print("\nВесь вміст файлу: ")
for i in range (0, number_lines):
s = file.readline()
print(CCYAN + s + CEND)
"""file_lines = [line.strip() for line in file]
for i in range(len(file_lines)):
print(file_lines[i])"""
file.close() |
5592a15e618f17846735f02d1cf1fcc69d90e644 | radoaller/learnpython | /max from input.py | 321 | 4.25 | 4 | a = int(input("Please input the first number."))
b = int(input("Please input the second number."))
c = int(input("Please input the third number."))
my_list = [a, b, c]
max_number = my_list[0]
for element in my_list:
if my_list[0] < element:
max_number = element
print ('The biggest number is', max_number)
|
9144464409140d0be6bff0973c67013e2caf737b | maksympt1/adventure-game | /game.py | 4,388 | 3.859375 | 4 | # Import modules
import time
import random
# Define functions
def print_pause(s):
print(s)
time.sleep(2)
def print_pause_long(s):
print(s)
time.sleep(3)
def main():
global items
items = ["dagger"]
global enemy
enemy = random.choice(enemies)
# Introduction
print_pause_long("You find yourself standing in an open field, filled with"
" grass and yellow wildflowers.")
print_pause_long(f"Rumor has it that a {enemy} is somewhere around here,"
" and has been terrifying the nearby village.")
print_pause("In front of you is a house")
print_pause("To your right is a dark cave")
print_pause("In your hand you hold your trusty (but not very "
"effective) dagger")
field()
def field():
# Things that happen when the player runs back to the field
print("\nEnter 1 to knock on the door of the house.")
print("Enter 2 to peek into the cave.")
print("\nWhat would you like to do?")
choice1 = input("(Please enter 1 or 2).\n")
while True:
if choice1 == '1':
house()
break
elif choice1 == '2':
cave()
break
else:
choice1 = input("(Please enter 1 or 2).\n")
def cave():
# Things that happen to the player goes in the cave
print_pause("You peer cautiously into the cave.")
if "sword" in items:
print_pause("You've been here before, and gotten all the good"
" stuff. It's just an empty cave now.")
print_pause("You walk back out to the field")
elif "sword" not in items:
print_pause("It turns out to be only a very small cave.")
print_pause("Your eye catches a glint of metal behind a rock.")
print_pause("You have found the magical Sword of Ogoroth!")
print_pause("You discard your silly old dagger and take the sword"
" with you.")
items.append("sword")
items.remove("dagger")
print_pause("You walk back out to the field")
field()
def house():
print_pause("You approach the door of the house.")
print_pause("You are about to knock when the door opens and out steps"
f" the {enemy}.")
print_pause(f"Eep! This is the {enemy}'s house!")
print_pause(f"The {enemy} attacks you!")
if "sword" not in items:
print_pause("You feel a bit under-prepared for this, what with only"
" having a tiny dagger.")
print("\nEnter 1 to fight.")
print("Enter 2 to run away.")
print("\nWhat would you like to do?")
choice2 = input("(Please enter 1 or 2).\n")
while True:
if choice2 == '1' and "sword" in items:
won()
break
elif choice2 == '1' and "sword" not in items:
lost()
break
elif choice2 == '2':
print_pause("You run back into the field. Luckily, you don't seem"
" to have been followed.")
field()
break
else:
choice2 = input("(Please enter 1 or 2).\n")
def won():
print_pause(f"As the {enemy} moves to attack, you unsheath your new"
" sword.")
print_pause("The Sword of Ogoroth shines brightly in your hand as you"
" brace yourself for the attack.")
print_pause(f"But the {enemy} takes one look at your shiny new toy and"
" runs away")
print_pause(f"You have rid the town of the {enemy}. You are victorious!")
play_again()
def lost():
print_pause("You do your best...")
print_pause(f"But your dagger is no match for the {enemy}.")
print_pause("You have been defeated!")
play_again()
def play_again():
print("\nWould you like to play again?")
choice3 = input("(Please enter 'y' or 'n').\n")
while True:
if choice3 == 'y':
print_pause("Excellent, restarting the game...")
main()
break
elif choice3 == 'n':
break
else:
choice3 = input("(Please enter 'y' or 'n').\n")
# Global variable
enemies = ["fire dragon", "giant troll", "poisonous pirate"]
enemy = "undefined"
# Launch the game
main()
|
d66161d0a93fecc6f127f6a34e0f884c4baa1586 | MarvelousJudson12/judson-s-project | /flowers.py | 2,961 | 4.25 | 4 | input("what is juds favorite flower? rose, goldenrod, or sunflower?")
def juds_favorite_flowers(flower, color):
if flower == "rose":
print("pick some for my mom and grandma for mothers day")
elif flower == "goldenrod":
print("thats cool, its KY's state flower")
elif flower == "sunflower":
print("sunflowers are cool!")
else:
print("i really dont like other flowers but let me see it")
if color == "yellow":
print("be sure to identify whether if it is a dandelion or not")
def rose(color, thorns):
if color == "red":
print ("you have a red rose.")
elif color == "white":
print ("you have a white rose.")
elif color == "orange":
print ("you have an orange rose.")
elif color == "yellow":
print ("you have a yellow rose.")
elif color == "purple":
print ("you have a purple rose")
else:
print ("you do not have a rose")
if thorns == True:
print ("be safe around the thorns or a rose. or any plant for that matter")
input("what is your favorite color of rose?")
def flower_color(yellow, purple,):
if yellow == True:
print ("these are jud's favorite flowers")
elif flower_color == purple:
print ("these are not jud's favorite flowers")
else:
print ("other colors are cool but not as cool as yellow ones")
flower_color = input("what is judsons favorite flower color?")
def allergies(pollen):
if pollen == True:
print ("take allergy medicene and go lay down")
elif pollen == True:
print ("go take allergy medicene and go to doctor")
elif pollen == False:
print ("enjoy the weather")
else:
("enjoy the weather")
def wildflower(weeds, dandelions, yellow):
if flower_color == yellow:
print ("this may be a weed, or just a flower.")
elif wildflower == dandelions:
print ("go to home depot and buy weed killer that is safe against grass and spray it on weeds")
elif wildflower == weeds:
print ("these are weeds, they will harm your garden or other planting area. kill them with the mind of zues")
else:
print ("if you know its not a weed, wildflower or etc, replant or take care of flower")
wildflower = input("do you know if it is a weed or wildflower?")
(list_of_weeds_in_KY) = {"Bentgrass, Bermudagrass, Bindweed, Black Medic,"
"Broadleaf, Plantain Buckhorn, Plantain Bugleweed, Bull Thistle,"
"Canada Thistle, Carolina Geranium, Carpetweed, Common Mullein"
"Crabgrass, Chickory, Dandelions, English Ivy, Green Kyllinga, Ground Ivy, Knotweed, Mallow,"
"Moss, Mouse-ear Chickweed, Oxalis, Pineapple Weed,"
"Prostrate Spurge, Puncturevine, Purslane, Rice Flatsedge,Virginia Creeper, White Clover,Yellow Nutsedge,"
}
print ("here is a list of weeds/wildflowers you should be aware of when gardening")
print (list_of_weeds_in_KY)
|
1124c0c044053478f1d0ef6822ef68d2cc47f0ac | Peteliuk/Python_Labs | /lab4_2.py | 257 | 3.90625 | 4 | import sys
import math
print('Enter 3 real numbers')
numA = float(input(''))
numB = float(input(''))
numC = float(input(''))
res = (1/numC*math.sqrt(2*math.pi))*math.exp((-1*math.pow((numA-numB),2))/(2*math.pow(numC,2))
print('Result:',res)
|
05024a2c8bd9784bac7daf118dc0c6cb5f2240f7 | ahmetfarukyilmaz/leetcode-solutions | /algorithm/two_sum.py | 260 | 3.515625 | 4 | def twoSum(nums, target):
result = []
for i in range(len(nums)):
for j in range(len(nums)):
if nums[j] + nums[i] == target and i != j:
result.append(i)
result.append(j)
return result
|
2d8d2b6c6a107b42040ddf743bcfd8094be82982 | norskovsen/Python-og-Pita-2019 | /eksempler/del2/lister_for.py | 272 | 3.890625 | 4 | def all_positive_even_numbers(lst):
for numb in lst:
if numb % 2 != 0:
return False
if numb <= 0:
return False
return True
print(all_positive_even_numbers([2, 4, 10, 12]))
print(all_positive_even_numbers([4, 6, 11, 13]))
|
13862f949ba19b6290aed7d4f914d88372d3ae00 | indie-tuna/Vampy-2017-cs | /numGuess.py | 414 | 4.0625 | 4 | lower = 1
upper = 0
guess = 1
ans = ""
while ans != "yes":
ans = input("Is "+ str(guess) +" your number/ is your number more or less? (yes/more/less)").lower()
if ans == "more":
if upper == 0:
guess *= 2
else:
lower = guess
guess = int((lower + upper)/2)
elif ans == "less":
if upper == 0:
lower = int(guess / 2)
upper = guess
guess = int((lower + upper)/2)
print("I found your number!")
|
7f1c5622f5b69403b6a7d040894e8aadca15079c | yakubpeerzade/repo1 | /calculator.py | 889 | 4 | 4 | def add(n1,n2):
res=n1+n2
return res
def sub(n1,n2):
res=n1-n2
return res
def mul(n1,n2):
res=n1*n2
return res
def div(n1,n2):
if n1==0 or n2==0:
print("We cannot divide with zero")
calculator()
else:
res=n1/n2
return res
def calculator():
num1=int(input("Enter Number One:"))
num2=int(input("Enter Number Two:"))
choice=int(input("\n1)Additin\n2)Substraction\n3)Multiplication\n4)Divsion\n5)Exit\n6)clear\nEnter Your choice:"))
if choice==1:
print("Addition =",add(num1,num2))
elif choice==2:
print("Substraction =",sub(num1,num2))
elif choice==3:
print("Multiplication =",mul(num1,num2))
elif choice==4:
print("Division=",div(num1,num2))
elif choice==5:
exit()
elif choice==6:
print("Reset")
calculator()
calculator()
|
9512199580e2b69c7ace7cea5b053900cc8c80c2 | JosephT8ertot/FruitPunch | /Member.py | 1,779 | 3.671875 | 4 | """
Creator: Joseph A Tate
Last Edit: 7/5/2021
The purpose of this class is to store the Player and User classes, which are used throughout the application to
give the user a involved experience
"""
# imports
from Database import db
# Player class
class Player:
def __init__(self, email_or_ID):
self.email_or_ID = email_or_ID
self.name = None
self.beerPong = None
self.snappa = None
# returns dictionary of stats for player for Beer Pong, returns base dict if player not in database
def loadBPStats(self):
self.beerPong = {'shots':0,'sinks':0,'wins':0,'losses':0}
self.snappa = {'throws':0,'hits':0,'sinks':0,'scores':0,'catches':0,'drops':0,'wins':0,'losses':0}
self.name = None
# saves dictionary of stats into player slot in database, creating new slot if player doesn't exist
def saveStats(self):
pass # FIXME add stat save
# User class
class User(Player):
def __init__(self, email):
super().__init__(email)
self.groups = self.groupsLoad()
self.adminGroups = self.adminGroupsLoad()
# loads all the groups a user is a part of but does not have access admin privileges to.
def groupsLoad(self):
return []
# loads all the groups a user is a part of and has admin privileges for.
def adminGroupsLoad(self):
return []
# creates a new Group as long as no group in self.adminGroups has same name
def createGroup(self, name):
pass
# leaves group from database and user lists unless user is only admin, then returns Exception('Only Admin')
def leaveGroup(self):
pass
# deletes group from database and user lists, only option if Exception('Only Admin') returned
def deleteGroup(self):
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.