blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
a2f57cd856753655ccab498255f391aa1dc33829 | GlenHaber/euler | /problem86.py | 1,617 | 4.15625 | 4 | """
Cuboid route
A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, sits in the opposite corner. By
travelling on the surfaces of the room the shortest "straight line" distance from S to F is 10.
The path is a diagonal along the 6x5 floor, then a diagonal up the 6x3 wall
However, there are up to three "shortest" path candidates for any given cuboid and the shortest route doesn't always
have integer length.
It can be shown that there are exactly 2060 distinct cuboids, ignoring rotations, with integer dimensions, up to a
maximum size of M by M by M, for which the shortest route has integer length when M = 100. This is the least value of M
for which the number of solutions first exceeds two thousand; the number of solutions when M = 99 is 1975.
Find the least value of M such that the number of solutions first exceeds one million.
"""
from math import sqrt
from time import time
def solve(target):
"""
For an AxBxC room, A <= B <= C, the shortest path will be the hypotenuse of a right triangle with legs A+B and C.
Start with C = M = 1, and find all A+B (x) values 2<=x<=2M with integer solutions. Then count the number of A,B
combinations that lead to this right triangle.
"""
solutions = 0
M = 0
while solutions < target:
M += 1
for x in range(2, 2 * M + 1):
if sqrt(M ** 2 + x ** 2).is_integer():
solutions += x // 2
if x > M:
solutions -= x - M - 1
return M
assert solve(2000) == 100
start = time()
print(solve(1000000))
print(time() - start)
|
2fda2c86022e48152f5fd06e5036147fdb10b2d0 | manelbenaissa/learning | /roboc/map.py | 3,107 | 4.25 | 4 | # !usr/bin/python
# -*-coding: utf-8 -*-
"""Define map class."""
class Map:
"""
Create a Map object.
It should be easy to:
- Add a new map
- Delete a map
- Modify a map
"""
def __init__(self, name):
"""
Methode constructeur.
Create a map with a text file.
Define cases with a tuple (i,j) (matrix like)
- line axis: i
- column axis : j
"""
self.name = name
self._accepted_char = ['O', '.', 'U', 'X', ' ']
with open('cartes/%s' % (name), 'r') as my_filemap:
my_map = my_filemap.read()
def read_map(mymap):
# map_data contains the tuples about the positions and the value
map_data = {}
i = -1
lines = mymap.splitlines()
for line in lines:
# Increment line
i += 1
# scroll through every line
j = -1
for value in list(line):
# Increment column
j += 1
if value not in accepted_char:
raise TypeError(
'''
incorrect value : %s
Please change line %s column %s
The map should only contain the following chars:
-O
-U
-.
-X
or blank spaces
''' % (value, i, j))
map_data[(i, j)] = value
return map_data, i, j
self._map_tuple = read_map(my_map)
self.map_data = self._map_tuple[0]
self.ix_last_line = self._map_tuple[1]
self.ix_last_column = self._map_tuple[2]
def __repr__(self):
"""Improve map representation."""
return "<Map {}>".format(self.name)
def __del__(self):
"""Delete object."""
print 'Map Object deleted.'
def change_map(self, **kwargs):
"""
Change a map.
**kwargs is a "dictionnary" with:
- key : a tuple (i,j)
- value : new case value
Raise an error if:
- key is out of border or is not an (i,j) tuple of numbers
- value not in accepted_char
"""
for key in kwargs:
if type(key) is not tuple:
raise TypeError('You should enter a (i,j) tuple')
line = key[0]
column = key[1]
if type(line) != int or type(column) != int:
raise TypeError('Tuple (i,j) should be made of ints')
if line > self.ix_last_line or column > self.ix_last_column:
raise ValueError('Index out of border for i=%s and j=%s'
% (line, column))
if kwargs[key] not in self._accepted_char:
raise ValueError('incorrect value %s for key %s'
% (kwargs[key], key))
else:
self.map_data[(line, column)] = kwargs[key]
|
a189e8d149c87bcabb8efe662683acbb5a2cfecd | coolafabbe/UdemyPythonSandbox | /25_csv/us-states-game-start/main.py | 1,122 | 3.671875 | 4 | import turtle
import pandas
from pandas._libs import missing
# create screen
screen = turtle.Screen()
screen.title("U.S. states game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
my_turtle = turtle.Turtle()
my_turtle.penup()
my_turtle.hideturtle()
data = pandas.read_csv("./50_states.csv")
state_names = data["state"].to_list()
game_over = False
correct_guesses = []
while not game_over:
answer_state = screen.textinput(title=f"Guess the state {len(correct_guesses)}/50", prompt="What's another state's name?").title()
if answer_state == "Exit":
pandas.DataFrame([state for state in state_names if not state in correct_guesses]).to_csv("states_to_learn.csv")
break
if answer_state in state_names and not answer_state in correct_guesses:
state_data = data[data.state == answer_state]
my_turtle.goto(int(state_data.x), int(state_data.y))
my_turtle.write(answer_state, move=False, align="center", font=("Arial", 8, "normal"))
correct_guesses.append(answer_state)
if len(correct_guesses) == 50:
game_over = True
|
e0b7f7489ce80b4807e0aea43135c1875c7c3eb7 | ArloZ/pythonOSC | /data/dataConvert.py | 843 | 3.53125 | 4 | #-*- coding = UTF8 -*-
'''
file : dataConvert.py
date : 2013-3-12
author : [email protected]
note : convert the value the display available
'''
class DataConvert():
'''
brief 将数值转换成电压表示形式,转换后单位为 V(伏特)
bits 量化精度
posV 正向电压
negV 反向电压
'''
def __init__(self,bits = 8,posV = 1,negV = 0):
self.bits = bits
self.negV = negV
self.posV = posV
self.delta = (posV - negV)/((1 << bits)-1)
def setFormat(self,bits = 8,posV = 1,negV = 0):
self.bits = bits
self.negV = negV
self.posV = posV
self.delta = (posV - negV)/((1 << bits)-1)
def convert(self,data):
print("delta:",self.delta)
val = self.delta * data
return val
|
d00aaf70080c6b3541e343066aa526bb3126bb4e | Nermin-Ghith/ihme-modeling | /mortality_code/fataldiscontinuities/gbd_2016_shocks/00_dataCollection/WHO_epidemic_scrape.py | 4,695 | 3.53125 | 4 | ''' Author:NAME
Date: 11/18/16
Purpose: Scrapes data from WHO emergency preparedness and response pages.
Problem: Data are tabluated by conflict and year, but selecting multiple conflicts only allows the user
to select overlapping years. Furthermore, data are returned as HTML tables;
they are just printed on the page. We want to get deaths due to each conflict,
for all years data exists, in one table.
Logic: Starting with the type of table we want already selected (with the base url),
use the selenium package's webdriver to automate our browsing. Using an old version of
Firefox, open a browser, select each conflict's checkbox iteratively, click through to the next page,
then select all year checkboxes for that conflict. Buttons and checkboxes are selected by xpath;
this is a way of specifying the text contained within the HTML tags of items we want.
These tags must be found by right-clicking the page of interest and selecting 'inspect element'
or similar, and discovering the elements of the page you desire.
Next, click through to the page displaying the table,
and grab it using pandas' read_html method. Format the data for cleaner output, append them
to a continuously growing table, and then go back and to the conflict page and repeat.
Clean up any issues with non-ascii values in the table and save it to file.
Dependencies:
Requries selenium and pandas (use "easy_install _______" or "pip install ______" replacing the
underscores with the desired package name.
### others: make sure to export PYTHONPATH=$PYTHONPATH:/path/to_local/site-packages
Requires Firefox v.25.0... I tried the most recent version (49?), but it didn't work. Downgrading to v25
seemed to solve the problem.'''
''' TODO: Let the script take the year(s) as an argument... use argparse!'''
import sys
sys.path.append('FILEPATH')
from selenium import webdriver
import pandas as pd
import time # for time.sleep
import string # for string.printable
import re
# variables
base_url = 'http://www.who.int/csr/don/archive/disease/'
out_path = r'/C drive :('
def go_to_next_page(link_keyword):
x_path_str = "//*[contains(@href, " + '\'' + link_keyword + '\'' + ")]"
next_button = browser.find_element_by_xpath(x_path_str)
next_button.click()
# converts a specific
def ascii_convert(s):
try:
return filter(lambda x: x in string.printable, s)
except:
return s
def get_links_between(front, back):
''' Get all of the links on the page between the two specified. Return a lower-case list of link names.'''
link_list = browser.find_elements_by_xpath("//*[@href]")
links = []
include_flag = 0
i = 0
for link in link_list:
print(str(i))
text = ascii_convert(link.text)
text = text.strip()
print(text)
if text == front:
include_flag = i
if (include_flag >= i) and (text != ''):
url = link.get_attribute('href')
links.append(url)
print(links)
if text == back:
include_flag = 0
i += 1
return links
df_list = [] # empty list to store dataframes in as we grab them
df_list_idx = 0
# get conflicts page
browser = webdriver.Firefox() # note: Firefox v25 works, newer versions may have issues
browser.get(base_url)
disease_urls = get_links_between('Acute diarrhoeal syndrome', 'Zika virus infection')
print(disease_urls)
# iterate over the chosen years
# for disease in disease_urls:
# go_to_next_page(disease)
# # iterate over months in year(s) chosen, grabbing data for all years available
# for month in months:
# time.sleep(1.5) # without this the request frequency is too high (I think)
# try:
# go_to_next_page(month)
# except:
# print('No data for ' + month + ' ' + year)
# break
# # get data for all years of chosen conflict and format it nicely
# new_data = pd.read_html(browser.current_url)[0]
# # replace columns with first row
# new_data.columns = new_data.iloc[0]
# new_data.reindex(new_data.index.drop(0))
# new_data.drop(0, axis=0, inplace=True)
# new_data['month'] = month
# # regex wizardry to pre-clean death numbers
# # new_data.Dead.str.extract('(?P<best>([0-9]+ (?=\() ) ) (?P<low> (?<=\(\+) [0-9]+)')
# new_data['Dead'] = new_data['Dead'].str.extract('^\d+').astype(int)
# df_list.append(new_data)
# print('done with ' + month + ' ' + year + ' events')
# # go back to start page
# browser.back()
# big_data = pd.concat(df_list)
# # # Save table to file
# big_data.to_csv(out_path, encoding='utf-8')
# print("done with 2016 terrorism webscrape!")
# browser.close()
|
97df7c807321fbdca614f9d4bde7df5bb235ae20 | ojenksdev/dataquest | /python-for-data-science-fundamentals/Conditional Statements-313.py | 4,057 | 3.625 | 4 | ## 1. If Statements ##
opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
free_apps_ratings = []
for row in apps_data[1:]:
rating = float(row[7])
# Complete the code from here
price = float(row[4])
if price == 0.0:
free_apps_ratings.append(rating)
avg_rating_free = sum(free_apps_ratings) / len(free_apps_ratings)
n_free_apps = len(free_apps_ratings)
percentage_free_apps = (n_free_apps / len(apps_data[1:])) * 100
## 2. Booleans ##
a_price = 0
prices = [0, 2, 0, 0, 0]
app_and_price = [['Facebook', 0], ['Instagram', 0], ['Plants vs. Zombies', 0.99],
['Minecraft: Pocket Edition', 6.99], ['Temple Run', 0],
['Plague Inc.', 0.99]]
if a_price == 0:
print('This is free.')
if a_price == 1:
print('This is not free')
free = []
for f in prices:
if f == 0:
free.append(f)
n_free_prices = len(free)
free_apps = []
for c in app_and_price:
name = c[0]
price = float(c[1])
if price == 0:
free_apps.append(name)
print(free_apps)
## 3. The Average Rating of Non-free Apps ##
non_free_apps_ratings = []
for app in apps_data[1:]:
rating = float(app[7])
price = float(app[4])
if price != 0.0:
non_free_apps_ratings.append(rating)
avg_rating_non_free = sum(non_free_apps_ratings) / len(non_free_apps_ratings)
## 4. The Average Rating of Gaming Apps ##
non_games_ratings = []
for app in apps_data[1:]:
rating = float(app[7])
genre = app[11]
if genre != "Games":
non_games_ratings.append(rating)
avg_rating_non_games = sum(non_games_ratings) / len(non_games_ratings)
## 5. Multiple Conditions ##
free_games_ratings = []
for app in apps_data[1:]:
rating = float(app[7])
price = float(app[4])
genre = app[11]
if price == 0.0 and genre == "Games":
free_games_ratings.append(rating)
avg_rating_free_games = sum(free_games_ratings) / len(free_games_ratings)
## 6. The or Operator ##
games_social_ratings = []
for app in apps_data[1:]:
rating = float(app[7])
genre = app[11]
if genre == "Social Networking" or genre == "Games":
games_social_ratings.append(rating)
avg_games_social = sum(games_social_ratings) / len(games_social_ratings)
## 7. Combining Logical Operators ##
free_games_social_ratings = []
nonfree_games_social_ratings = []
for row in apps_data[1:]: # apps_data is already saved from previous screens
rating = float(row[7])
genre = row[11]
price = float(row[4])
if (genre == 'Social Networking' or genre == 'Games') and price == 0:
free_games_social_ratings.append(rating)
# Write your code below
if (genre == "Social Networking" or genre == "Games") and price != 0:
nonfree_games_social_ratings.append(rating)
avg_free = sum(free_games_social_ratings) / len(free_games_social_ratings)
avg_non_free = sum(nonfree_games_social_ratings) / len(nonfree_games_social_ratings)
## 8. Comparison Operators ##
over_9 = []
under_9 = []
for app in apps_data[1:]:
price = float(app[4])
rating = float(app[7])
if price > 9.0:
over_9.append(rating)
if price <= 9.0:
under_9.append(rating)
avg_rating = sum(over_9) / len(over_9)
n_apps_more_9 = len(over_9)
n_apps_less_9 = len(under_9)
## 9. The else Clause ##
for app in apps_data[1:]:
price = float(app[4])
if price == 0.0:
app.append('free')
else:
app.append('non-free')
apps_data[0].append('free_or_not')
print(apps_data[0])
## 10. The elif Clause ##
for app in apps_data[1:]:
price = float(app[4])
if price == 0.0:
app.append('free')
elif price > 0.0 and price < 20:
app.append('affordable')
elif price >= 20 and price < 50:
app.append('expensive')
elif price >= 50:
app.append('very expensive')
apps_data[0].append('price_label')
print(apps_data[:5])
|
d2f3a57e360698e5accfe0c86500d01eda9a6948 | thisiswei/udacity-self-driving-car | /tmp.py | 7,789 | 3.6875 | 4 | import math
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
_Y_HEIGHT = 320
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines, color=[255, 0, 0], thickness=10):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1))
to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
left, right = _split_lines(lines)
y_top = _Y_HEIGHT
y_bottom = img.shape[1]
if left:
left_line = _get_line(left, y_top, y_bottom)
cv2.line(img,
(
int(left_line['x_bottom']),
int(left_line['y_bottom']),
),
(
int(left_line['x_top']),
int(left_line['y_top']),
),
color,
thickness=thickness)
if right:
right_line = _get_line(right, y_top, y_bottom)
cv2.line(
img,
(
int(right_line['x_bottom']),
int(right_line['y_bottom']),
),
(
int(right_line['x_top']),
int(right_line['y_top']),
),
color,
thickness=thickness)
def _get_line(lines, y_top, y_bottom):
avg_point = _get_avg_point(lines)
avg_slope = _get_avg_slope(lines)
b = _calculate_b(avg_point, avg_slope)
x_top = _get_x(b, y_top, avg_slope)
x_bottom = _get_x(b, y_bottom, avg_slope)
return {
'x_bottom': int(x_bottom),
'y_bottom': int(y_bottom),
'x_top': int(x_top),
'y_top': int(y_top),
}
def _get_avg_point(lines):
'''
Given lines return the avg point: (x,y)
'''
x_sum = sum(
(x1+x2)/2.
for line in lines
for x1,_,x2,_ in line
)
y_sum = sum(
(y1+y2)/2.
for line in lines
for _,y1,_,y2 in line
)
num_of_lines = len(lines) + 0.0
return x_sum/num_of_lines, y_sum/num_of_lines
def _get_avg_slope(lines):
'''
Give lines return the average slope of the lines
'''
slope_sum = sum(
((y2-y1)/(x2-x1)+0.0)
for line in lines
for x1,y1,x2,y2 in line
)
return slope_sum / (len(lines) + 0.0)
def _get_x(b, y, slope):
x = (y - b) / slope
return x
def _calculate_b(point, slope):
"""
calculate the b in the following formula:
mx+b = y
"""
x1, y1 = point
# avg_right_slope * x1 + b = y1
b = y1 - (slope * x1)
return b
def _split_lines(lines):
left = []
right = []
for line in lines:
for x1,y1,x2,y2 in line:
slope = ((y2-y1)/(x2-x1))
if (slope > 0.45 and slope < 0.75):
left.append(line)
elif (slope < -0.6 and slope > -0.9):
right.append(line)
return left, right
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + λ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, λ)
def process_image(image):
'''
it says, "try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines."
but I can't figure out how to extrapolate out the lines
'''
gray = grayscale(image)
blur_gray = gaussian_blur(gray, 5)
low_threshold = 50
high_threshold = 150
edges = canny(blur_gray, low_threshold, high_threshold)
# Next we'll create a masked edges image using cv2.fillPoly()
imshape = image.shape
vertices = np.array([[(0,imshape[0]),(450, 320), (490, 320), (imshape[1],imshape[0])]], dtype=np.int32)
masked_edges = region_of_interest(edges, vertices)
plt.imshow(masked_edges)
# This time we are defining a four sided polygon to mask
# Define the Hough transform parameters
# Make a blank the same size as our image to draw on
rho = 2 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 20 # minimum number of votes (intersections in Hough grid cell)
min_line_length = 60 #minimum number of pixels making up a line
max_line_gap = 30 # maximum gap in pixels between connectable line segments
line_image = np.copy(image)*0 # creating a blank to draw lines on
# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments
line_image = hough_lines(masked_edges, rho, theta, threshold, min_line_length, max_line_gap)
# Iterate over the output "lines" and draw lines on a blank image
# Create a "color" binary image to combine with line image
color_edges = np.dstack((edges, edges, edges))
# Draw the lines on the edge image
lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0)
plt.imshow(lines_edges)
return lines_edges
|
a45f83ab331a1438df86a746e7aa12d383fc5fbf | anoubhav/30-Day-SDE-Challenge | /Day_23/1_clone_graph.py | 1,594 | 3.671875 | 4 | # Q: https://leetcode.com/problems/clone-graph/
# Ref: https://leetcode.com/problems/clone-graph/discuss/42314/Python-solutions-(BFS-DFS-iteratively-DFS-recursively)./420527
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
# BFS - iterative
def cloneGraph(node):
from collections import deque
if not node:
return None
q = deque([node])
nodeCopy = Node(node.val)
dic = {node: nodeCopy}
while q:
node = q.popleft()
for nbr in node.neighbors:
if nbr not in dic:
tempNode = Node(nbr.val)
dic[nbr] = tempNode
dic[node].neighbors.append(dic[nbr])
q.append(nbr)
else:
dic[node].neighbors.append(dic[nbr])
return nodeCopy
# DFS - iterative
def cloneGraphDFS(node):
from collections import deque
if not node:
return None
stack = [node]
nodeCopy = Node(node.val)
dic = {node: nodeCopy}
while stack:
node = stack.pop()
for nbr in node.neighbors:
if nbr not in dic:
tempNode = Node(nbr.val)
dic[nbr] = tempNode
stack.append(nbr)
dic[node].neighbors.append(dic[nbr])
else:
dic[node].neighbors.append(dic[nbr])
return nodeCopy |
7b617c0e5b2ae908f38fba4c7a22701a39275d2c | danilglinianiy/Python | /LAB1/lab1_task_2.py | 286 | 3.828125 | 4 | from random import randint
userNum = input('Enter your number:')
a = int(userNum)
n = randint(0, 100)
if(a>n):
print('Your number is higher')
if(a<n):
print('Your number lower')
if(a==n):
print('Thats fantastic, you guessed the number!')
print('\nRand number is: ', n1)
|
8d1faf1d194b170da71fa9224e49bfa9fe018590 | RhythmG/Unit-6 | /lenofcurve.py | 760 | 3.984375 | 4 | #Stephen Wang + Maia Reynolds
#Calculus Programming Week
#Length of a Curve
from math import *
nInterval = 10000
def f(x):
return sin(x)
def derivative(x):
h = 1.0/nInterval
rise = (f(x+h)-f(x-h))*0.5
run = h
slope = rise/run #definition of derivative
return slope
def lenf(x):
df = derivative(x)
return sqrt(1+(df*df))
lower = float(input('Enter a lower bound: '))
upper = float(input('Enter an upper bound: '))
def rectangles(a, b, numofrectangles):
sum = 0
x = a
dx = (b-a)/numofrectangles
n = 0
while n < numofrectangles:
rate = lenf(x)
ds = rate*dx
sum += ds
x += dx
n += 1
print('')
print('Length: ', abs(sum))
rectangles(lower, upper, nInterval)
|
18020c4f50b78b0fe35baf22dc529ee9e07fd7a4 | citlalygonzale/TC1014 | /e.py | 208 | 3.71875 | 4 | def calculate_e(c):
x = c
ce = (1+1/x)**x
return float(ce)
r = int(input("Number of decimal points of accuracy: "))
resulte = calculate_e(r)
print("The estimate of the constant e is:",resulte)
|
99f4446ae78945dd72fd230fb629837e0c561623 | ConnorCairns/New-Summer-Assignment | /Database Creation.py | 740 | 3.75 | 4 | #This only needs to be run once
import sqlite3
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute("""CREATE TABLE student
(ID INTEGER NOT NULL,
name TEXT NOT NULL,
userName TEXT NOT NULL,
PRIMARY KEY(ID))""")
conn.commit()
c.execute("""CREATE TABLE results
(ID INTEGER NOT NULL,
question TEXT NOT NULL,
answer TEXT NOT NULL,
correct BOOLEAN NOT NULL,
sessionID INTEGER NOT NULL,
studentID INTEGER NOT NULL,
FOREIGN KEY(studentID) REFERENCES student(ID)
PRIMARY KEY(ID))""")
conn.commit()
print("tbl has successfully been created... please close this window")
|
7997868a33ce0b76b9fe914d73ee6d1b0929dbb4 | Jovamih/PythonProyectos | /class/People.py | 346 | 3.65625 | 4 | # /usr/bin/env python3
class People(object):
def __init__(self,name,edad,dni,region):
self.name=name
self.edad=edad
self.dni=dni
self.region=region
def crecer(self):
self.edad=self.edad+1
def __str__(self):
return "{}, {} años con DNI {}".format(self.name,self.edad,self.dni) |
8af6d1baec693e15e7eba6afda965f35d4791950 | syamsss6/imagepuzzle | /.code/1.py | 336 | 3.828125 | 4 | #!/usr/bin/python
def print_urls(file):
#Each line is of the form: GET /foo/bar/a.jpg
#remove the GET and print only /foo/bar/a.jpg
#use a for-loop to iterate through each line of `file'
#split the line and print second part
for line in f:
print line.split()[1]
f = open('1.txt')
print_urls(f)
|
ba11ffb81fa5610c04fe3cb4c1a15d42ef72174b | karanshah743/Fibonacci-Numbers | /Fibonacci Numbers.py | 414 | 4.375 | 4 | terms = int(input("Enter a number up to how many terms you want the Fibonacci Numbers : "))
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
if terms <= 0:
print("Please enter a positive number rather than 0.")
else:
print("The Fibonacci numbers : ", end=" ")
for i in range(terms):
print(fibonacci(i), end=" ")
|
07fd9e8378a29ac83090db23146ba1fd52b944c2 | notsoseamless/python_training | /principles_of_computing/1_4_Yahtzee/gen_all_sequences.py | 1,991 | 4.0625 | 4 | """
Functions to enumerate sequences of outcomes
Repetition of outcomes is allowed
"""
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length
"""
ans = set([()])
for _ in range(length):
temp = set()
for seq in ans:
for item in outcomes:
new_seq = list(seq)
new_seq.append(item)
temp.add(tuple(new_seq))
ans = temp
return ans
# example for digits
def run_example1():
"""
Example of all sequences
"""
#outcomes = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#outcomes = set(['a', 'a', 'b'])
outcomes = set(['ajh'])
#outcomes = set(["Red", "Green", "Blue"])
#outcomes = set(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
length = 3
seq_outcomes = gen_all_sequences(outcomes, length)
print "Computed", len(seq_outcomes), "sequences of", str(length), "outcomes"
print "Sequences were", seq_outcomes
run_example1()
def gen_sorted_sequences(outcomes, length):
"""
Function that creates all sorted sequences via gen_all_sequences
"""
all_sequences = gen_all_sequences(outcomes, length)
sorted_sequences = [tuple(sorted(sequence)) for sequence in all_sequences]
return set(sorted_sequences)
def run_example2():
"""
Examples of sorted sequences of outcomes
"""
# example for digits
outcomes = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#outcomes = set(["Red", "Green", "Blue"])
#outcomes = set(["Sunday", "Mondy", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
length = 2
seq_outcomes = gen_sorted_sequences(outcomes, length)
print "Computed", len(seq_outcomes), "sorted sequences of", str(length) ,"outcomes"
print "Sequences were", seq_outcomes
run_example2()
|
b7514da5593ab0f35bee6e003a0f6cfbc32f156b | Ojenge/python-sandbox | /loop_tuples.py | 282 | 3.859375 | 4 | test_tuple = ('I', 'am', 'a', 'test', 'tuple')
new_tuple = ()
size = len(test_tuple)
new_size = size + 1
#new_tuple = new_tuple + (test_tuple[2],)
#print(new_tuple)
for i in range(size):
if i % 2 == 0:
new_tuple = new_tuple + (test_tuple[i],)
print(new_tuple)
|
c02faeb8fa488f2b0f482f079271a823bd01bc17 | zhenyzha/envtool | /base/base_vmt.py | 1,126 | 3.65625 | 4 | #-*-coding:utf-8-*-
class Base(object):
pass
class Color(object):
def __init__(self):
self._red = '\033[31m'
self._green = '\033[32m'
self._yellow = '\033[33m'
self._blue = '\033[34m'
self._fuchsia = '\033[35m'
self._cyan = '\033[36m'
self._white = '\033[37m'
#: no color
self._reset = '\033[0m'
def color_str(self, color, s):
return '{}{}{}'.format(
color,
s,
self._reset
)
def print_red(self, s):
print(self.color_str(self._red, s))
def print_green(self, s):
print(self.color_str(self._green, s))
def print_yellow(self, s):
print(self.color_str(self._yellow, s))
def print_blue(self, s):
print(self.color_str(self._blue, s))
def print_fuchsia(self, s):
print(self.color_str(self._fuchsia, s))
def print_cyan(self, s):
print(self.color_str(self._cyan, s))
def print_white(self, s):
print(self.color_str(self._white, s))
if __name__ == '__main__':
a = Color()
a.print_red('aaa')
pass |
9e3ca114c564d7dbd48b76c7d177105aaef2810c | RuiwenP2018/hwcpg2018 | /hw5/p2.py | 229 | 4 | 4 | currentNumber = float (raw_input ("Pleace enter a random number? "))
if (currentNumber%2 == 0):
finalNumber = 3 * (currentNumber + 1)
print (finalNumber)
else:
finalNumber = currentNumber / 2
print (finalNumber)
|
0ea6339a7b9e08e70630607e8a21c06de0013851 | Hunter-Dinan/cp1404practicals | /prac_01/menus.py | 375 | 3.96875 | 4 | name = str(input("Enter name: "))
menu = """(H)ello
(G)oodbye
(Q)uit"""
print(menu)
menu_input = str(input())
while menu_input != "Q":
if menu_input == "H":
print("Hello {}".format(name))
elif menu_input == "G":
print("Goodbye {}".format(name))
else:
print("Invalid input")
print(menu)
menu_input = str(input())
print("Finished")
|
0c722d71ae87ad6b1ca5fb803daaeaefe3f3483e | anniechannon/h07-pypt-submission | /capitalizer.py | 71 | 3.671875 | 4 | word = input("Enter the word:")
word_cap = word.upper()
print(word_cap) |
6ec2e21e277acd0b18a98c0bb6b120301b71838f | millu94/joshuas_weekend_hw_01 | /src/pet_shop.py | 2,182 | 3.6875 | 4 | # WRITE YOUR FUNCTIONS HERE
import pdb
#1 find the name of the pet shop
def get_pet_shop_name(pet_shop_info):
name = pet_shop_info["name"]
return name
#2 find the total cash
def get_total_cash(pet_shop_info):
total_cash = pet_shop_info["admin"]["total_cash"]
return total_cash
#3 + #4 add or remove cash
def add_or_remove_cash(pet_shop_info, cash_amount):
pet_shop_info["admin"]["total_cash"] = pet_shop_info["admin"]["total_cash"] + cash_amount
#5 find how many pets have sold
def get_pets_sold(pet_shop_info):
return pet_shop_info["admin"]["pets_sold"]
#6 increase number of pets sold
def increase_pets_sold(pet_shop_info, pets_sold):
pet_shop_info["admin"]["pets_sold"] += pets_sold
#7 find the stock count
def get_stock_count(pet_shop_info):
return len(pet_shop_info["pets"])
#8 + #9
# find how many there are of a given breed
def get_pets_by_breed(pet_shop_info, breed):
#pdb.set_trace()
x = 0
number_of_breeds = []
while x < 6:
if pet_shop_info["pets"][x]["breed"] == breed:
number_of_breeds.append(pet_shop_info["pets"][x])
x = x + 1
return number_of_breeds
#10 + #11
def find_pet_by_name(pet_shop_info, name):
x = 0
while x < len(pet_shop_info["pets"]):
if pet_shop_info["pets"][x]["name"] == name:
return pet_shop_info["pets"][x]["name"]
x = x + 1
return None
#12 remove pet by name
def remove_pet_by_name(pet_shop_info, name):
#pdb.set_trace()
for pet in pet_shop_info["pets"]:
if pet["name"] == name:
pet_shop_info["pets"].remove(pet)
#13 add pet to stock
def add_pet_to_stock(pet_shop_info, add_pet):
pet_shop_info["pets"].append(add_pet)
#14 get customer cash
def get_customer_cash(customer_list):
return customer_list["cash"]
#15 remove customer cash
def remove_customer_cash(customers, cash_remove):
customers["cash"] -= cash_remove
return customers["cash"]
#16 get customer pet_count
def get_customer_pet_count(customers_pets):
return len(customers_pets["pets"])
#17 add pet to customer
def add_pet_to_customer(customers_pets, add_pet):
customers_pets["pets"].append(add_pet) |
1ae968ac2d42a6a6d79d16a6ab97e1d08c813365 | imscs21/myuniv | /1학기/programming/basic/파이썬/파이썬 과제/homework/hw1.py | 4,622 | 3.65625 | 4 | Grade_A = [int(90),int(100)]
Grade_B = [int(80),int(89)]
Grade_C = [int(70),int(79)]
Grade_D = [int(60),int(69)]
Grade_F = [int(0),int(59)]
def GetGrade(score):
if(score>=Grade_A[0] and score <= Grade_A[1]):
return "A"
elif(score<Grade_A[0] and score >= Grade_B[0]):
return "B"
elif(score<Grade_B[0] and score >= Grade_C[0]):
return "C"
elif(score<Grade_C[0] and score >= Grade_D[0]):
return "D"
else:
return "F"
def GetQuestion(idx):
if (idx==0):
return "백분위 점수: "
elif (idx == 1 ):
return "더할래?(y/n)"
elif ( idx == 2 ):
return "1-가 프로그램 안녕"
elif ( idx == 3):
return "1-나 프로그램 안녕"
elif ( idx== 4 ):
return "학점:"
else: return "error"
class CoreFunctionContainer:
def DoCoreFunction(score):
loopControl0 = True
temoValue1 = ""
loopCount=int(0)
while (loopControl0):
yourscore=0
loopCount=loopCount+1
if(loopCount > 200):
loopControl0=False
break
try:
tempValue1 = input(GetQuestion(0))
if(not tempValue1.isnumeric()):
continue
else:
yourscore = int(tempValue1)
if(yourscore>100 or yourscore<0):
continue
else:
print(GetQuestion(4),GetGrade(yourscore))
break
except:continue
del loopControl0
def grade0():
cfc = CoreFunctionContainer()
cfc.DoCoreFunction()
del cfc
print(GetQuestion(2))
exit()
def grade1():
cfc = CoreFunctionContainer()
loopControl1 = True
while loopControl1:
cfc.DoCoreFunction()
loopControl2 = True
tempReply=""
while loopControl2:
tempReply = input(GetQuestion(1))
tempReply = str(tempReply)
if(tempReply == "n"):
loopControl1 = False
loopControl2 = False
elif(tempReply =="y" ):
loopControl1 = True
loopControl2 = False
else:
loopControl1 = True
loopControl2 = True
continue
del tempReply
del loopControl2
del loopControl1
del cfc
print(GetQuestion(3))
exit()
def bigger(a,b) :
if a > b :
return a
else :
return b
def biggest(a,b,c):
return bigger(bigger(a,b),c)
def median(a,b,c):
if( biggest(a,b,c) == a):
return bigger(b,c)
elif( biggest(a,b,c) == b):
return bigger(a,c)
elif( biggest(a,b,c) == c):
return bigger(b,a)
import math
def format_ok(f,m,b) :
if((not f.isnumeric()) or (not b.isnumeric()) or(not (m=="-"))):
return False
f1 = int(f)
b1 = int(b)
numberPosCount = int(math.log10(f1))
if(numberPosCount != 5):
return False
numberPosCount = int(math.log10(b1))
if(numberPosCount != 6):
return False
del numberPosCount
import datetime
tyear = int(f[:2])
if (tyear > 20):
tyear = int("19"+f[:2])
else:
tyear = int("20"+f[:2])
try:
tmonth = int(f[2:4])
tday = int(f[4:])
tdate = datetime.date(tyear, tmonth, tday);
checkyear = tdate.year
checkmonth = tdate.month
checkday = tdate.day
del checkday
del checkmonth
del checkyear
except:
return False
return True
def last_digit_ok(vals) :
return (11 - ((2*int(vals[0])+3*int(vals[1])+4*int(vals[2])+5*int(vals[3])+6*int(vals[4])+7*int(vals[5])+8*int(vals[6])+9*int(vals[7])+2*int(vals[8])+3*int(vals[9])+4*int(vals[10])+5*int(vals[11])) % 11))==int(vals[12])
def isRRN(message) :
s = input(message)
(front,mid,back) = s.partition("-")
while not (format_ok(front,mid,back) and last_digit_ok(front+back)) :
print("Invalid number")
s = input(message)
(front,mid,back) = s.partition("-")
return s
#run function here
f = input("앞자리");
print(format_ok(f,"-","1234567"))
#tester.sh 파일에서 #/bin/sh가 아니라 #!/bin/sh라 생각됩니다
#chmod 777 tester.sh
# ./tester.sh myhomework.py
|
be0a5ffdea0ad26392950b25c7f99975b7122ceb | JoshKarpel/euler-python | /problems/033.py | 1,070 | 3.65625 | 4 | import itertools
from math import ceil
from problems import mymath
def solve():
numerators = range(10, 100)
denominators = range(10, 100)
fractions = []
for numerator in numerators:
for denominator in denominators:
if denominator > numerator:
fractions.append([numerator, denominator])
answers = []
for fraction in fractions:
numerator_str = str(fraction[0])
denominator_str = str(fraction[1])
for i in numerator_str:
if i == str(0):
break
elif i in denominator_str:
numerator_str_cancelled = numerator_str.replace(i, '', 1)
denominator_str_cancelled = denominator_str.replace(i, '', 1)
if denominator_str_cancelled != str(0) and int(numerator_str_cancelled) / int(denominator_str_cancelled) == fraction[0] / fraction[1]:
answers.append(fraction[0] / fraction[1])
return int(ceil(1 / mymath.iterable_product(answers)))
if __name__ == '__main__':
print(solve())
|
40a50773bc32105e2ccb62cbfc8436be741b57d9 | jonahswift/pythonStudy1 | /firstDay/studyGames.py | 833 | 4.09375 | 4 | '''
需求:游戏 石头剪刀 布
分析:
玩家:a
电脑:b
剪子:1 布:2 石头3
输赢
玩家:剪子 电脑 布
a==1 and b==2
'''
import random
#随机数
#num = random.randint(1,3)
#print(num)
puit = str(input('请猜拳,你出了:'))
num = random.randint(1,3)
#print(f'电脑出的是{num}')
if num ==1:
num1 = '石头'
elif num ==2:
num1 = '剪子'
else:
num1 ='布'
print(f'电脑出的是{num1}')
if (puit == '石头' and num == 1)or(puit == '剪子' and num == 2)or(puit == '布' and num == 3):
print(f'你出的{puit},电脑出的{num1},打平了')
elif (puit == '石头' and num == 2)or(puit == '剪子' and num == 3)or(puit == '布' and num == 1):
print(f'你出的{puit},电脑出的{num1},你赢了')
else:
print(f'你出的{puit},电脑出的{num1},你输了')
|
abc69507fac7e69a2624958f1ffb0e6aedfbf83e | DavidBlazek18/Python-Projects | /Web_Generator_Assignment/webConstructorWithGUI,II.py | 3,940 | 4.0625 | 4 |
# Python: Ver. 3.7
# Author: David Blazek
# Program: Web Page Generator (Python Course Assignment Page 250, The Tech Academy)
import webbrowser # imports the module which allows the display of Web-based documents to users.
import tkinter as tk # Imports the toolkit which enables the building of a GUI.
from tkinter import * # Allows all modules to be used from the toolkit.
class ParentWindow(Frame): # Class parent window and our Frame inherits the attributes
def __init__ (self, master): # Dunder initialize and pass in class self and named master(can be any name)
Frame.__init__ (self) # The frame is going to initialize itself and then run the code below.
# put all the above into function
win = Tk() # Allows tkinter to install a window widget and assigns the variable "f" as the window frame
f = Frame(win)
l = Label(win, text="Enter new message below then click the SUBMIT button.")# Creates the label variable and label instructions.
v = StringVar() # Creates the variable for the new message in Entry window which we can get (with Get func.).
e = Entry(win, width = 80, textvariable = v)
b1 = Button(f, text="SUBMIT") # Creates the button variable and button name.
l.pack(pady = 10)
e.pack(padx = 10) # Uses the "pack" method to vertically align the label, entry window and SUBMIT button in the frame.
b1.pack(pady = 10)
f.pack()
def but1(): # defining the function for our button.
print("The SUBMIT button was pushed") # This shows up in the console that the button was pushed.
newVariable = e.get()
fileToWrite = open("webConstructor.html", "w") # Defines the variable that opens an HTML document the user can write to.
newTextToWrite = "Stay tuned for our amazing summer sale!" # Defines the variable for the text string a user can change in the script.
newScript = ("<html><body><h1>" + newVariable + "</h1></body></html>") # Defines the variable which concatenates the python script with new text from the user.
fileToWrite.write(newScript) # Overwrites the HTML file with a new script which includes the new text.
fileToWrite.close() # Close file per Best Coding Practices.
webbrowser.open_new_tab("webConstructor.html") # Runs the new HTML file in the browser.
b1.configure(command=but1)
v.get()
webbrowser.get()
if __name__ == "__main": # Controls program flow. All lines below are read and then the above code is run (if needed).
root = Tk() # Instantiates the TKinter...
App = ParentWindow(root) # then passes it over to our class program ParentWindow...
root.mainloop() # and create a main loop for the program to run so it constantly stays open.
#self.btnSubmit = Button(self.master, text='Submit', width=10, height=2, command=self.submit) # (Code contained in TK GUI Video Part 5)
|
5ca8a7ae523847c564707606057c43dbc34883c1 | nishantchaudhary12/Starting-with-Python | /Chapter 5/loan_payment_calculator.py | 501 | 4.3125 | 4 | #loan payment calculator
def payment_calculator(rate, amount, months):
payment_per_month = (rate * amount)/(1 - (1 + rate)**-months)
print('The month payment amount will be $',format(payment_per_month, '.2f'))
def main():
rate = float(input('Enter the rate of interest as a decimal (e.g. 2.5% 5 0.025): '))
amount = float(input('Enter the amount of the loan: $'))
months = int(input('Enter the desired number of months: '))
payment_calculator(rate, amount, months)
main() |
f66cef37ef09bf9df6c2f031ae189a21ae0d386d | liuminzhao/eulerproject | /euler69.py | 1,001 | 3.59375 | 4 | __author__ = 'liuminzhao'
import math
prime= [x for x in range(2,50) if not [t for t in range(2,int(math.sqrt(x))+1) if not x%t]]
def isprime(x):
return not [t for t in range(2,int(math.sqrt(x))+1) if not x%t]
def isrprime(a, b):
minab = min(a, b)
maxab = max(a, b)
for i in range(2, minab + 1):
if not a%i and not b%i :
return False
return True
def countprime(n):
count = 1
for i in range(2, n):
if isrprime(n, i):
count += 1
return count
rate = 0
want = 1
target = [one for one in range(2, 10001) if not isprime(one)]
for i in target:
tmp = float(i)/countprime(i)
if tmp > rate:
rate = tmp
want = i
if i%10000 == 0:
print i
print want, rate
### bad idea
## borrow from online
prime= [x for x in range(2,50) if not [t for t in range(2,int(math.sqrt(x))+1) if not x%t]]
n = 1000000
tmp = 1
i = 0
for i in prime:
if tmp * i > n:
break
else:
tmp *= i
print tmp |
af454bbdbcef95b21a70c16068a542b6bdb8cd02 | brenonorberto/Cursos | /Curso em Vídeo/Python/Desafio39_aula12_alistamento militar.py | 685 | 3.828125 | 4 | print('='*12, 'Desafio 39', '='*12)
print()
from datetime import date
atual = date.today().year
nasc = int(input('Digite o seu ANO de nascimento: '))
idade = atual - nasc
print()
print('Quem nasceu em {}, tem {} anos em {}'.format(nasc, idade, atual ))
if idade == 18:
print('Esse ano você deve se ALISTAR')
elif idade < 18:
saldo = 18 - idade
ano = atual + saldo
print('Ainda faltam {} anos para o ALISTAMENTO'.format(saldo))
print('Seu alistamento seré em {}'.format(ano))
elif idade > 18:
saldo = idade - 18
ano = atual - saldo
print('Você deveria ter se alistado a {} anos'.format(saldo))
print('Se alistamento foi em {}'.format(ano))
|
f749d84b97d5bcd6feeb2a083fc49ef8e15c546c | Lackman-coder/backup | /python.py | 92 | 3.71875 | 4 | a = input("Enter the firstname: ")
b = input("Enter the secondname: ")
c = a + b
print(c)
|
a005b83c3c7cefd95627f75c36c03dee0421e383 | maxnoodles/data_strcuture | /algorithm(2020-01-24)/back_tracking/search_word.py | 1,797 | 3.5 | 4 |
class WordSearch:
def __init__(self):
self.d = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1]
]
self.m = 0
self.n = 0
self.visited = []
# board 搜索的二维数组, word 搜索词
def exist(self, board, word):
self.m = len(board)
assert self.m > 0
self.n = len(board[0])
self.visited = [[False for _ in range(self.n)] for _ in range(self.m)]
for i in range(len(board)):
for j in range(len(board[0])):
if self.search_world(board, word, 0, i, j):
return True
return False
# 从 board[start_x][start_y] 开始, 寻找 word[index...word.size()]
def search_world(self, board, word, index, start_x, start_y):
if index == len(word) - 1:
return board[start_x][start_y] == word[index]
if board[start_x][start_y] == word[index]:
self.visited[start_x][start_y] = True
# 从 start_x, start_y 出发,向四个方向寻找
for i in self.d:
new_x = start_x + i[0]
new_y = start_y + i[1]
if self.in_area(new_x, new_y) and not self.visited[new_x][new_y]:
if self.search_world(board, word, index+1, new_x, new_y):
return True
self.visited[start_x][start_y] = False
return False
def in_area(self, x, y):
return 0 <= x < self.m and 0 <= y < self.n
if __name__ == '__main__':
w = WordSearch()
board = [
['a', 'b', 'c', 'd'],
['a', 'b', 'c', 'd'],
['a', 'b', 'c', 'd']
]
# board = [
# ['a', 'b'],
# ['a', 'b'],
# ]
res = w.exist(board, 'abcdc')
print(res)
|
e9f9ebfe7b5c0df1b63cb31c5e968d0bfd2b2be6 | GLucky31/py2020 | /guitictactoe.py | 4,151 | 3.5625 | 4 | from tkinter import *
from tkinter import messagebox
#(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7) Zmagovalne kombinacije
root = Tk()
poteza = True
a= 0
stevec=0
zmaga=False
root.title("Tic Tac Toe")
root.config(background='Dark gray')
root.resizable(0,0)
label1 = Label(text = " d", font='Times 20 bold', height=1, width=12,)
label1.grid(row=0, column=0, columnspan=8)
def stanjeCheck():
if poteza == True:
label1.configure(text="X so na potezi.", fg="blue")
elif poteza == False:
label1.configure(text="O so na potezi.", fg="red")
stanjeCheck()
def btnClick(button):
global poteza, stevec
if button['text'] == ' ' and poteza == True and zmaga == False:
button['text'] = 'X'
poteza=False
stevec+=1
checkForWin()
stanjeCheck()
elif button['text'] == ' ' and poteza == False and zmaga == False:
button['text'] = 'O'
stevec += 1
poteza=True
checkForWin()
stanjeCheck()
elif(zmaga == False and button["text"] != " "):
messagebox.showinfo("Opozorilo.", "Gumb je že bil kliknjen.")
gumb1 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb1))
gumb1.grid(row=1, column=0)
gumb2 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb2))
gumb2.grid(row=1, column=1)
gumb3 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb3))
gumb3.grid(row=1, column=2)
gumb4 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb4))
gumb4.grid(row=2, column=0)
gumb5 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb5))
gumb5.grid(row=2, column=1)
gumb6 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb6))
gumb6.grid(row=2, column=2)
gumb7 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb7))
gumb7.grid(row=3, column=0)
gumb8 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb8))
gumb8.grid(row=3, column=1)
gumb9 = Button(root, text=" ", bg='gray', height=4, width=8, command=lambda: btnClick(gumb9))
gumb9.grid(row=3, column=2)
def checkForWin():
global zmaga,label1
if (gumb1['text'] == 'X' and gumb2['text'] == 'X' and gumb3['text'] == 'X' or
gumb4['text'] == 'X' and gumb5['text'] == 'X' and gumb6['text'] == 'X' or
gumb7['text'] =='X' and gumb8['text'] == 'X' and gumb9['text'] == 'X' or
gumb1['text'] == 'X' and gumb5['text'] == 'X' and gumb9['text'] == 'X' or
gumb3['text'] == 'X' and gumb5['text'] == 'X' and gumb7['text'] == 'X' or
gumb1['text'] == 'X' and gumb2['text'] == 'X' and gumb3['text'] == 'X' or
gumb1['text'] == 'X' and gumb4['text'] == 'X' and gumb7['text'] == 'X' or
gumb2['text'] == 'X' and gumb5['text'] == 'X' and gumb8['text'] == 'X' or
gumb3['text'] == 'X' and gumb6['text'] == 'X' and gumb9['text'] == 'X'):
zmaga = True
messagebox.showinfo("Konec", "Križci so zmagali.")
elif(stevec == 8):
zmaga = True
messagebox.showinfo("Konec", "Igralca sta izenačena.")
elif (gumb1['text'] == 'O' and gumb2['text'] == 'O' and gumb3['text'] == 'O' or
gumb4['text'] == 'O' and gumb5['text'] == 'O' and gumb6['text'] == 'O' or
gumb7['text'] =='O' and gumb8['text'] == 'O' and gumb9['text'] == 'O' or
gumb1['text'] == 'O' and gumb5['text'] == 'O' and gumb9['text'] == 'O' or
gumb3['text'] == 'O' and gumb5['text'] == 'O' and gumb7['text'] == 'O' or
gumb1['text'] == 'O' and gumb2['text'] == 'O' and gumb3['text'] == 'O' or
gumb1['text'] == 'O' and gumb4['text'] == 'O' and gumb7['text'] == 'O' or
gumb2['text'] == 'O' and gumb5['text'] == 'O' and gumb8['text'] == 'O' or
gumb3['text'] == 'O' and gumb6['text'] == 'O' and gumb9['text'] == 'O'):
zmaga = True
messagebox.showinfo("Konec", "Krogci so zmagali.")
root.mainloop()
|
265f87c7e95f9fe66bcffaf61fb1fbcd710664b6 | Cohiba3310/Ask-Name | /name.py | 171 | 3.859375 | 4 | while True:
name = input('請輸入這台電腦主人名字: ')
if name == '楊育哲':
print('正確無誤')
break
else:
print('請回去使用自己的電腦!') |
430c16e2db754d9cb9d4c5a4a1808a6022bf6164 | statco19/doit_pyalgo | /ch6/merge.py | 597 | 3.625 | 4 | from typing import Sequence, MutableSequence
import heapq
def merge_sorted_list(a: Sequence,b: Sequence, c: MutableSequence):
pa, pb, pc = 0, 0, 0
na, nb, nc = len(a), len(b), len(c)
while pa<na and pb<nb:
if a[pa] <= b[pb]:
c[pc] = a[pa]
pa += 1
else:
c[pc] = b[pb]
pb += 1
pc += 1
while pa < na:
c[pc] = a[pa]
pa += 1
pc += 1
while pb < nb:
c[pc] = b[pb]
pb += 1
pc += 1
return c
if __name__ == "__main__":
a = [2,4,6,8,11,13]
b = [1,2,3,4,9,16,12]
c = [None] * len(a+b)
print(merge_sorted_list(a,b,c))
print(list(heapq.merge(a,b)))
|
8a04f48141364aeb2ac90848ecfea99d022e610c | sera0506/PythonKerasTensorflowPractice | /demo2.py | 335 | 3.890625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# y = ax + b
b = 5
a = 3
x = np.arange(-10, 10, 0.1)
print(x)
y = a * x + b
plt.plot(x, y, label=f"y = {a}x + {b}")
plt.legend(loc=2)
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.title("demo2 figure")
plt.xlabel("label for x")
plt.ylabel("label for y")
plt.show()
|
25d53f62abcac9fe151df4b1cc30a6a66cac7ad5 | TarasKindrat/SoftServe_Python-online-marathon | /5_sprint/6_task.py | 1,635 | 4.53125 | 5 | """
Write the function solve_quadric_equation(a, b, c) the three input parameters of which are numbers.
The function should return
the solution of quadratic equation ax2+bx+c=0, where coefficients a, b, c are input parameters of
the function solve_quadric_equation:
in case of correct data the function should displayed the corresponding message –
"The solution are x1=… and x2=…"
in the case of division by zero the function should displayed the corresponding message –
"Zero Division Error"
in the case of incorrect data the function should displayed the message –
"Could not convert string to float"
Note: in the function you must use the "try except" construct.
Function example:
solve_quadric_equation(1, 5, 6) #output: " The solution are x1=(-2-0j) and x2=(-3+0j)"
solve_quadric_equation(0, 8, 1) #output: "Zero Division Error"
solve_quadric_equation(1,”abc”, 5) #output: "Could not convert string to float"
ax2 +bx +c = 0
"""
def solve_quadric_equation(a, b, c):
import logging
import cmath
logging.basicConfig(level=logging.DEBUG)
try:
a = float(a)
b = float(b)
c = float(c)
d = b ** 2 - 4 * a * c
x1 = (-b - cmath.sqrt(d)) / (2 * a)
x2 = (-b + cmath.sqrt(d)) / (2 * a)
print(f"The solution are x1={x1} and x2={x2}")
except ValueError:
print("Could not convert string to float")
except ZeroDivisionError:
print("Zero Division Error")
solve_quadric_equation(1, 5, 6)
solve_quadric_equation(0, 8, 1)
solve_quadric_equation(1,"abc", 5) |
c3a0e58d4f9186028304bed0a5bca61f62c23cec | jrcapriles/armSimulator | /Point.py | 1,122 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 2 01:17:09 2014
@author: Jose Capriles
"""
from math import sqrt
class Point( object ):
def __init__( self, x, y, z):
self.x, self.y, self.z = x, y, z
def distFrom( self, x, y, z ):
return sqrt( (self.x-x)**2 + (self.y-y)**2 + (self.z-z)**2 )
def getPoint(self):
return ((self.x, self.y, self.z))
def getPointX(self):
return self.x
def getPointY(self):
return self.y
def getPointZ(self):
return self.z
#
#
#class PendulumState( object ):
# def __init__( self, x, y):
# self.x, self.y = x, y
#
# def getState(self):
# return ((self.x, self.y))
#
# def getStateX(self):
# return self.x
#
# def getStateY(self):
# return self.y
#
# def __add__(self, other):
# return PendulumState(self.x + other.x,self.y + other.y)
#
# def __sub__(self, other):
# return PendulumState(self.x - other.x,self.y - other.y)
#
# def __abs__(self):
# return PendulumState(abs(self.x),abs(self.y)) |
b3478accf7f1a173832d3cbf8c063b626286981c | S-samira2020/New-python-code2 | /program7.py | 634 | 3.890625 | 4 | #MATH fUNCTION PRACTICE
'''x = 2.9
print(round(x))
print()
x = 3.8
print(abs(-3.8))
print()
'''
import math
print(math.ceil(2.1)) # it will show 3 bcz ceil means it is up 2.0
print(math.floor(2.9)) # it will show 2 bcz floor means under 3
print(math.comb(6,3)) # it will show 20 bcz n!/k!+(n-k)! here n is 6 and 3 is k
print(math.copysign(6.1, -5.9)) # it will show -6.1 it is only copy y's sign i mean minus sign
x = 3
print(math.fabs(x))# it will show exact value of x 3.5
print(math.factorial(x)) # it will show 6
print(math.fmod(2.0,1.0)) # it will show 0.0
print(math.fmod(2.0, 6.0)) # it will show 2.0
|
60e0d4c655bb755f43000c20fc15b416a618e2d3 | myamullaciencia/Bayesian-statistics | /_build/jupyter_execute/09_predict_soln.py | 14,147 | 3.78125 | 4 | # Bite Size Bayes
Copyright 2020 Allen B. Downey
License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## Review
[In the previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/08_soccer.ipynb) I introduced the World Cup problem:
>In the 2018 FIFA World Cup final, France defeated Croatia 4 goals to 2. Based on this outcome:
>
>1. How confident should we be that France is the better team?
>
>2. If the same teams played again, what is the chance Croatia would win?
I started with the assumption that for any team against any other team there is some unknown goal-scoring rate, λ.
And I showed that if we know λ, we can compute the probability of scoring $k$ goals in a game:
$f(k; λ) = λ^k \exp(-λ) ~/~ k!$
This function is the [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution), and we can use SciPy to compute it.
For example, if we know that λ is 1.4, we can compute the distribution of $k$ like this:
from scipy.stats import poisson
λ = 1.4
xs = np.arange(11)
ys = poisson.pmf(xs, λ)
pmf_goals = pd.Series(ys, index=xs)
pmf_goals
In theory, the values of $k$ go to infinity, but I cut it off at 10 because higher values have very low probability.
Here's what the distribution of $k$ looks like:
pmf_goals.plot.bar(color='C0', alpha=0.5, label='Poisson distribution')
plt.xlabel('Number of goals')
plt.ylabel('Probability')
plt.title('Distribution of goals scored')
plt.legend();
Because the values of $k$ are discrete integers, I use a bar chart to plot the distribution.
Next I used a gamma distributon to represent the prior distribution of λ. I set the parameter of the gamma distribution, α, to 1.4, which is the average number of goals each team scores in World Cup play.
I broke the range of values for λ into 101 discrete possibilities and used SciPy to compute the prior probabilities:
from scipy.stats import gamma
α = 1.4
qs = np.linspace(0, 10, 101)
ps = gamma.pdf(qs, α)
prior = pd.Series(ps, index=qs)
prior /= prior.sum()
Here's what the prior distribution looks like:
prior.plot(label='prior', color='gray')
plt.xlabel('Goal scoring rate')
plt.ylabel('Probability')
plt.title('Prior distribution')
plt.legend();
Because the values of $λ$ are continuous, I use a line to plot the distribution.
Next we did a Bayesian update, using the Poisson distribution to compute the likelihood of the data, $k$, for each possible goal scoring rate, $λ$
$ f(k; λ) = λ^k \exp(-λ) ~/~ k! $
Since France scored 4 goals, the likelihood of the data is:
λs = prior.index
k = 4
likelihood = poisson.pmf(k, λs)
And we can use the following function to do the update:
def bayes_update(pmf, likelihood):
"""Do a Bayesian update.
pmf: Series that represents the prior
likelihood: sequence of likelihoods
returns: float probability of the data
"""
pmf *= likelihood
prob_data = pmf.sum()
pmf /= prob_data
return prob_data
france = prior.copy()
bayes_update(france, likelihood)
And we can do the same thing for Croatia, given that they scored 2 goals:
k = 2
λs = prior.index
likelihood = poisson.pmf(k, λs)
croatia = prior.copy()
bayes_update(croatia, likelihood)
Here's what the results look like.
prior.plot(label='prior', color='gray')
france.plot(label='France', color='C0')
croatia.plot(label='Croatia', color='C3')
plt.xlabel('Goal scoring rate')
plt.ylabel('Probability')
plt.title('Posterior distributions for France and Croatia')
plt.legend();
In the previous notebook we used the following function to compute the mean of a PMF.
def pmf_mean(pmf):
"""Compute the mean of a PMF.
pmf: Series representing a PMF
return: float
"""
return np.sum(pmf.index * pmf)
We can use it to compute the posterior means for France and Croatia.
pmf_mean(france), pmf_mean(croatia)
Based on the outcome of the game, we have some reason to think France is the better team.
But if we look at the posterior distribution of λ for France and Croatia, there is still a lot of overlap, which means we are still not certain which is the better team.
In the next section, we'll use the posterior distributions to compute the "probability of superiority".
### Probability of superiority
Now that we have a posterior distribution for each team, we can answer the first question: How confident should we be that France is the better team?
In the model, "better" means having a higher goal-scoring rate against the opponent. We can use the posterior distributions to compute the probability that a random value drawn from France's distribution exceeds a value drawn from Croatia's.
The following function takes a Series that represents a PMF and draws a sample from it.
def pmf_choice(pmf, n):
"""Draw a random sample from a PMF.
pmf: Series representing a PMF
n: number of values to draw
returns: NumPy array
"""
return np.random.choice(pmf.index,
size=n,
replace=True,
p=pmf)
`pmf_choice` uses `np.random.choice`, which chooses `n` values from the PMF with replacement, so the same value can appear more than once. It uses the probabilities from the PMF as weights, so the number of times each value appears is proportional to its probability.
Here's a sample from the posterior distribution for France.
sample_france = pmf_choice(france, 1000)
sample_france.mean()
And here's a sample for Croatia.
sample_croatia = pmf_choice(croatia, 1000)
sample_croatia.mean()
To estimate the probability of superiority, we can count the number of times the value from France's distribution exceeds the value from Croatia's distribution.
np.mean(sample_france > sample_croatia)
On the basis of one game, we have moderate confidence that France is actually the better team.
### Predicting the rematch
Now we can take on the second question: If the same teams played again, what is the chance Croatia would win?
To answer this question, we'll generate a sample from the "posterior predictive distribution", which is the number of goals we expect a team to score.
If we knew the goal scoring rate, λ, the distribution of goals would be a Poisson distributon with parameter λ.
Since we don't know λ, we can use the sample we generated in the previous section to generate a sample of goals, like this:
goals_france = np.random.poisson(sample_france)
`np.random.poisson` uses each element of `sample_france` to generate a random value; that is, each value in the result is based on a different value of λ.
To see what the resulting distribution looks like, we'll use this function from a previous notebook:
def pmf_from_seq(seq):
"""Make a PMF from a sequence of values.
seq: sequence
returns: Series representing a PMF
"""
pmf = pd.Series(seq).value_counts(sort=False).sort_index()
pmf /= pmf.sum()
return pmf
pmf_france = pmf_from_seq(goals_france)
pmf_france.plot.bar(color='C0', label='France')
plt.xlabel('Goals scored')
plt.ylabel('Probability')
plt.title('Predictive distribution')
plt.legend()
goals_france.mean()
This distribution represents two sources of uncertainty: we don't know the actual value of λ, and even if we did, we would not know the number of goals in the next game.
**Exercise:** Generate and plot the predictive distribution for Croatia.
# Solution
goals_croatia = np.random.poisson(sample_croatia)
pmf_croatia = pmf_from_seq(goals_croatia)
pmf_croatia.plot.bar(label='Croatia', color='C3')
plt.xlabel('Goals scored')
plt.ylabel('Probability')
plt.title('Predictive distribution')
plt.legend()
goals_croatia.mean()
In a sense, these distributions represent the outcomes of 1000 simulated games.
**Exercise:** Compute the fraction of simulated rematches Croatia would win, how many France would win, and how many would end in a tie.
# Solution
np.mean(goals_croatia > goals_france)
# Solution
np.mean(goals_france > goals_croatia)
# Solution
np.mean(goals_france == goals_croatia)
Assuming that Croatia wins half of the ties, their chance of winning the rematch is about 33%.
## Summary
In this notebook, we finished off the World Cup problem:
* We used posterior distributions to generate samples of goal-scoring rates.
* We compared samples to compute a "probability of superiority".
* We used samples and `np.random.poisson` to generate samples of goals score and to estimate their distributions.
* We used those distributions to compute the probabilities of winning, losing, and tying in a rematch.
The goal distributions we computed are called "[posterior predictive distributions](https://en.wikipedia.org/wiki/Posterior_predictive_distribution)" because they use posterior distribution to make predictions.
[In the next notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/10_joint.ipynb) we'll take a break from Bayesian methods and learn about an important idea in probability: joint distributions.
But first, here's an exercise where you can practice what you learned in this notebook.
## Exercise
**Exercise:** Here's a variation on the World Cup Problem:
>In the 2014 FIFA World Cup, Germany played Brazil in a semifinal match. Germany scored after 11 minutes and again at the 23 minute mark. At that point in the match, how many goals would you expect Germany to score after 90 minutes? What was the probability that they would score 5 more goals (as, in fact, they did)?
In this version, notice that the data is not the number of goals in a fixed period of time, but the time between goals.
To compute the likelihood of data like this, we can take advantage of the theory of [Poisson processes](https://en.wikipedia.org/wiki/Poisson_point_process). In our model of a soccer game, we assume that each team has a goal-scoring rate, λ, in goals per game. And we assume that λ is constant, so the chance of scoring a goal in the same at any moment of the game.
Under these assumptions, the distribution of goals follows a Poisson distribution, as we've already seen. Also, the time between goals follows an [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution).
If the goal-scoring rate is λ, the probability of seeing an interval between goals of $t$ is proportional to the PDF of the exponential distribution:
$f(t; λ) = λ~\exp(-λ t)$
Because $t$ is a continuous quantity, the value of this expression is not really a probability; technically it is a [probability density](https://en.wikipedia.org/wiki/Probability_density_function). However, it is proportional to the probability of the data, so we can use it as a likelihood in a Bayesian update.
To see what the exponential distribution looks like, let's assume again that λ is 1.4; we can compute the distribution of $t$ like this:
def expo_pdf(t, λ):
"""Compute the PDF of the exponential distribution.
t: time
λ: rate
returns: probability density
"""
return λ * np.exp(-λ * t)
λ = 1.4
ts = np.linspace(0, 4, 101)
ys = expo_pdf(ts, λ)
pmf_time = pd.Series(ys, index=ts)
pmf_time /= pmf_time.sum()
pmf_time.plot(label='λ = 1.4')
plt.xlabel('Time between goals (games)')
plt.ylabel('Probability')
plt.title('Distribution of time between goals')
plt.legend();
It is counterintuitive, but true, that the most likely time to score a goal is immediately. After that, the probability of each possible interval is a little lower.
With a goal-scoring rate of 1.4, it is possible that a team will take more than one game to score a goal, but it is unlikely that they will take more than two games.
Now we're ready to solve the problem. Here are the steps I recommend:
1. Starting with the same gamma prior we used in the previous problem, compute the likelihood of scoring a goal after 11 minutes for each possible value of λ. Don't forget to convert all times into units of games.
2. Use `bayes_update` to compute the posterior distribution of λ for Germany after the first goal. If the total probability of the data is greater than 1, don't panic; because the likelihoods are not probabilities, the return value from `bayes_update` is not a probability either. But the posterior distribution is still valid.
3. Compute the likelihood of scoring another goal after 12 more minutes and do another update. Plot the prior, posterior after one goal, and posterior after two goals.
4. Use `pmf_choice` to generate a sample of 1000 values from the posterior distribution of goal scoring rate.
5. Use `np.random.poisson` to compute a sample of goals Germany might score during the remaining time in the game, `90-23` minutes. Note: you will have to think about how to generate predicted goals for a fraction of a game.
6. Compute and plot the PMF of possible goals scored and select from it the probability of scoring 5 more goals.
# Solution
germany = prior.copy()
λs = germany.index
# Solution
t = 11/90
likelihood = expo_pdf(t, λs)
# Solution
bayes_update(germany, likelihood)
# Solution
t = 12/90
likelihood = expo_pdf(t, λs)
# Solution
germany2 = germany.copy()
bayes_update(germany2, likelihood)
# Solution
pmf_mean(germany), pmf_mean(germany2)
# Solution
prior.plot(color='gray', label='Prior')
germany.plot(color='C3', label='Posterior after 1 goal')
germany2.plot(color='C8', label='Posterior after 2 goals')
plt.xlabel('Goal scoring rate')
plt.ylabel('Probability')
plt.title('Prior distribution')
plt.legend();
# Solution
sample_germany = pmf_choice(germany2, 1000)
sample_germany.mean()
# Solution
remaining_time = (90-23) / 90
goals_germany = np.random.poisson(sample_germany * remaining_time)
# Solution
pmf_germany = pmf_from_seq(goals_germany)
pmf_germany.plot.bar(color='C8', label='germany')
plt.xlabel('Goals scored')
plt.ylabel('Probability')
plt.title('Predictive distribution')
plt.legend()
goals_germany.mean()
# Solution
pmf_germany[5]
|
ff2ea3db5b146e015fef770715b5c09357af237d | pkostereva/ES_Python | /LSN_7/DZ_7.1.py | 823 | 3.75 | 4 | from pprint import pprint
n=0
z=0
task=dict()
while True:
print('\n1. Добавить задачу.\n2. Вывести список задач.\n3. Выход.')
n=input('Выберете пункт: ')
if n.isnumeric():
if int(n) == 1:
print('\n')
a=input('Задача: ')
b=input('Категория: ')
c=input('Время: ')
task[z]={0 : a, 1: b,2: c}
z+=1
elif int(n) == 2:
print('\n')
for i in range(len(task)):
#out=''.join(i)
print(f'Задача: {task[i][0]}, Категория: {task[i][1]}, Время: {task[i][2]}')
elif int(n) == 3:
break
else:
print('\nОшибка ввода')
|
5a0aa1de444c94123abfa5d734e5c6a3a660705c | AceMouty/Python | /2.Variables_and_Strings/milage_converter.py | 329 | 3.96875 | 4 | def main():
MILE = 1.60934
distance_ran = input("How many kilometers did you run?\n")
print(f"Ok you said {distance_ran}")
miles = float(distance_ran) // MILE
# round(thing to round, how many decimal places)
print("So you ran " + str(round(miles, 2)) + " miles")
if __name__ == "__main__":
main()
|
a634e6838cbb60be7ae229fda3494ece0fd7fd87 | pscx142857/python | /上课代码/Python基础第七天/练习.py | 173 | 3.671875 | 4 | # 全局变量定义在调用函数下面,是否能使用,不能
def show():
print(name)
# name = "丫丫"
show()
name = "丫丫" # NameError: name 'name' is not defined |
26022934bf205b2d2d517c52dfb36326e1145097 | sandeepm96/cormen-algos | /Alice/Sorting/radix_sort.py | 759 | 3.578125 | 4 | class RadixSort:
def __init__(self,array):
self.array = array
def sort(self,exp):
count = [0]*(10)
sorted_array = [0]*(len(self.array))
for i in range(len(self.array)):
index = int(self.array[i]/exp)
count[index%10] += 1
for j in range(1,10):
count[j] += count[j-1]
for k in range(len(self.array)-1,-1,-1):
index = int(self.array[k]/exp)
sorted_array[count[index%10]-1] = self.array[k]
count[index%10] -= 1
self.array = sorted_array
def result(self):
max_element = max(self.array)
exp = 1
while (max_element/exp) > 0:
self.sort(exp)
exp *= 10
return self.array
|
7878dd86bd9357823444f5f1e10eba84af79a50e | yash0423/attack-the-castle-AI-Based-Game- | /model/rune.py | 1,192 | 3.734375 | 4 | import random
class Rune:
"""
A model class used to represent the rune.
"""
def __init__(self,atk_plus=2,hp_plus=2,step_plus=2):
self.atk_plus = atk_plus #random.randrange(1,4)
self.hp_plus = hp_plus #random.randrange(1,4)
self.step_plus = step_plus #random.randrange(1,2)
self.x = None
self.y = None
def buff_pawn(self, pawn, randoming=True):
"""
Get all the rune list.
...
Parameters
----------
pawn : Pawn
Change the parameter of our pawn randomly
get buff of one of the following attribute: atk, hp, step
"""
rand_num = random.randrange(0,3)
if randoming:
if rand_num == 0:
pawn.add_atk(self.atk_plus)
elif rand_num == 1:
pawn.add_hp(self.hp_plus)
else:
pawn.add_step(self.step_plus)
else:
pawn.add_atk(self.atk_plus)
pawn.add_hp(self.hp_plus)
pawn.add_step(self.step_plus)
def __repr__(self):
return "a" + str(self.atk_plus) + "h" + str(self.hp_plus) + "s" + str(self.step_plus) + "+r"
|
b4a2a2ad36fd7184ac03a7704528c1903418acfc | IsraMejia/AnalisisNumerico | /c19-Simpson38.py | 842 | 3.515625 | 4 | import numpy as np
print('\n\tMetodo Simpson 3/8 ')
a= 0 #Limite inferior
b= 2 #Limite superior
n=3 #Numero de intervalos , Se tiene que verificar si es valido con el numero de puntos que hay (5)
#puntos = n+1
# x en funcion de intervalos
x = np.zeros(n+1)
# f(x) en funcion anonima
f = lambda x: x**5
def simpson38 ( a, b, n, x, f):
h = (b-a) / n
x[0] = a
x[n] = b
for k in range( len(x)- 1):
x[k+1] = x[k] + h
sum1= 0
sum2= 0
sum3= 0
for k in range(1, n-1, 3):
sum1 += f( x[k])
for k in range(2, n, 3):
sum2 += f(x[k])
for k in range(3, n-2, 3):
sum3 += f(x[k])
return (3/8) *h *( f(x[0]) + f(x[n]) + 3*sum1 + 3*sum2 + 2*sum3 )
integral = simpson38(a, b , n, x, f)
print(f'El valor de la integral de x**5, en el intervalo de {a} a {b} es : {integral}')
#10.7037 |
544ae5147b4eef8c08142a0b79339533bddec5f4 | ar1vit0r/Numerical_Calculus_Methods | /Algoritmo Matemática Intervalar.py | 5,973 | 3.8125 | 4 | a = []
b = []
c = []
# define the function blocks
def intersec_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
if( a[0] > b[1] or a[1] < b[0]):
return None
else:
c.append(max(a[0],b[0]))
c.append(min(a[1],b[1]))
print("\nA Intersecção é: [" + str(c[0]) + "," + str(c[1]) + "]")
def uni_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
c.append(min(a[0],b[0]))
c.append(max(a[1],b[1]))
print("\nA União é: [" + str(c[0]) + "," + str(c[1]) + "]")
def convexUni_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
c.append(min(a[0],b[0]))
c.append(max(a[1],b[1]))
print("\nA União Convexa é: [" + str(c[0]) + "," + str(c[1]) + "]")
def w_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
w = a[1] - a[0]
print("\nO diâmetro de A é: " + str(w) )
def r_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
r = 0.5 * (a[1] - a[0])
print("\nO raio de A é: " + str(r) )
def m_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
m = 0.5 * (a[0] + a[1])
print("\nO Ponto médio de A é: " + str(m) )
def mod_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
m = max(abs(a[0]),abs(a[1])) #módulo
print("\nO módulo de A é: " + str(m) )
def dist_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
d = max(abs(a[0]-b[0]),abs(a[1]-b[1]))
print("\nA Distância entre A e B é: " + str(d))
def add_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
c.append(a[0] + b[0])
c.append(a[1] + b[1])
print("\nA Adição é: [" + str(c[0]) + "," + str(c[1]) + "]")
def sub_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
c.append(a[0] - b[1])
c.append(a[1] - b[0])
print("\nA Subtração é: [" + str(c[0]) + "," + str(c[1]) + "]")
def mult_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
c.append( min(a[0]*b[0],a[0]*b[1],a[1]*b[0],a[1]*b[1]) )
c.append( max(a[0]*b[0],a[0]*b[1],a[1]*b[0],a[1]*b[1]) )
print("\nA Multiplicação é: [" + str(c[0]) + "," + str(c[1]) + "]")
def div_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
b.append(float(input("\nInsira o x do conjunto B: ")))
b.append(float(input("\nInsira o y do conjunto B: ")))
c.append( min(a[0]/b[0],a[0]/b[1],a[1]/b[0],a[1]/b[1]) )
c.append( max(a[0]/b[0],a[0]/b[1],a[1]/b[0],a[1]/b[1]) )
print("\nA Divisão é: [" + str(c[0]) + "," + str(c[1]) + "]")
def neg_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
c.append( -1*a[1] )
c.append( -1*a[0] )
print("\nO Negativo é: [" + str(c[0]) + "," + str(c[1]) + "]")
def recip_():
a.append(float(input("\nInsira o x do conjunto A: ")))
a.append(float(input("\nInsira o y do conjunto A: ")))
c.append( 1/a[1] )
c.append( 1/a[0] )
print("\nA Recíproca é: [" + str(c[0]) + "," + str(c[1]) + "]")
# map the inputs to the function blocks
options = {1 : intersec_,
2 : uni_,
3 : convexUni_,
4 : w_,
5 : r_,
6 : m_,
7 : mod_,
8 : dist_,
9 : add_,
10 : sub_,
11 : mult_,
12 : div_,
13 : neg_,
14 : recip_,
}
op = int(input("Digite 1 Intersecção\nDigite 2 para União\nDigite 3 para União Convexa\nDigite 4 para w(A) - Diâmetro de A\nDigite 5 para r(A) - Raio de A\nDigite 6 para m(A) - Ponto Médio de A\nDigite 7 para |A| - Módulo de A\nDigite 8 para d(A,B) - Distância entre A e B\nDigite 9 para A + B - Adição entre A e B\nDigite 10 para A - B - Subtração entre A e B\nDigite 11 para A * B - Multiplicação entre A e B\nDigite 12 para A / B - Divisão entre A e B\nDigite 13 para -A - Negativo de A\nDigite 14 para 1/A - Recíproca de A\nOpção: "))
if op == 1:
options[1]()
elif op ==2:
options[2]()
elif op == 3:
options[3]()
elif op == 4:
options[4]()
elif op == 5:
options[5]()
elif op == 6:
options[6]()
elif op == 7:
options[7]()
elif op == 8:
options[8]()
elif op == 9:
options[9]()
elif op == 10:
options[10]()
elif op == 11:
options[11]()
elif op == 12:
options[12]()
elif op == 13:
options[13]()
elif op == 14:
options[14]()
else:
print("\nErro, não há esta opção.\n") |
568abdf43f6da9ee630c48bf089553864379a71b | raghunadraju/Practise | /Loops.py | 434 | 4.125 | 4 | # There are only two main loops in Python (FOR, WHILE)
Names = ["RAGHU", 'SRINI', '', 1, 'SHREYA', 'SURYA']
for Names in Names:
if Names == "SHREYA":
print("Found him "+Names)
break # for loop stops after the condition satisfied
print('Student Name is {0}'.format(Names)) # Printing all the objects in the list using for loop
a = 2
for index in range(2):
a += 2
print("iterations {0}".format(a))
|
2357536524cba763e93b22075004f59567fe8ad2 | csany2020c/Demo | /a_kocka.py | 571 | 3.78125 | 4 |
from turtle import Turtle
from turtle import Screen
class TurtleOOP:
def __init__(self):
screen = Screen()
turtle = Turtle()
a = 45
turtle.width(3)
for i in range(4):
turtle.forward(250)
turtle.left(a)
turtle.forward(88)
turtle.backward(88)
turtle.right(a)
a = a - 90
turtle.left(90)
turtle.goto(62.5, 62.5)
for u in range(4):
turtle.forward(250)
turtle.left(90)
screen.mainloop()
TurtleOOP() |
4d6e7fa3efd4a6e2d1b00eaad09ab7edd8d487ba | Ling-Cheng-Nan/Python_programming_practice | /python_practice/Json.py | 660 | 3.96875 | 4 | import json
# some JSON format string
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse jason into python object
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
# a Python object (dict):
p = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert python object into JSON:
q = json.dumps(p)
# the result is a JSON string:
print(q)
r = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(r)) |
4f314144fa3951444193cda5739966e7927911b6 | kunpengku/learn_python | /build_in/max_test.py | 120 | 3.84375 | 4 |
print max([1,2,3,4])
def f(x):
if x==2:
return 2
else:
return 1
print max([1,2,3,4], key=f)
|
2dcf2de6358dd160a02a34dfa038cdcd2835e4dc | MatheusOldAccount/Exerc-cios-de-Python-do-Curso-em-Video | /exercicios/ex004.py | 704 | 4.03125 | 4 | #valor = input('Digite algo: ')
#print('O tipo primitivo do que foi digitado é {0}'.format(type(valor)))
#print('O que foi digitado é letra? ', valor.isalpha())
#print('O que foi digitado é número? ', valor.isnumeric())
#print('O que foi digitado é letra e ou número? ', valor.isalnum())
valor = input('Digite algo: ')
print('O tipo primitivo desse valor é ', type(valor))
print('Só tem espaços? ', valor.isspace())
print('É um número? ', valor.isnumeric())
print('É alfabético? ', valor.isalpha())
print('É alfanumérico? ', valor.isalnum())
print('Está em maiúsculas? ', valor.isupper())
print('Está em minúsculas? ', valor.islower())
print('Está capitalizada? ', valor.istitle())
|
8a6c878b22e4e2a166274760e9d2ee3a02f89dee | MayurSaxena/Ciphers | /CaesarCipher.py | 10,107 | 4.25 | 4 | """
Mayur Saxena
2013-09-31
To perform a Caesar cipher
"""
import random
def encode(inputString,shiftValue):
#if the user inputs r or R for random, change shiftValue to a random number
if shiftValue == "R" or shiftValue == "r":
# the random number should be between 1 and 25
shiftValue = random.randrange(1,26)
stringElements = []
#creates a list from each letter of the string
lst = list(inputString)
for letter in lst:
#any letter that can be regularly processesd
if ord(letter) < (91-int(shiftValue)) and ord(letter) > 64:
stringElements.append(chr(ord(letter)+int(shiftValue)))
#Tests for spaces, punctuation, etc. adds them as is
elif ord(letter) < 65 or ord(letter) > 90:
stringElements.append(letter)
# If the letter does go past A-Z after encode, keep in boundaries
else:
# We have to move S letters forward, so we see what is already covered
# from the current letter to Z, and add the remaining from A
# eg. if X with shift of 5, we can cover 2 letters until Z, and then add A,B,C
# Start from 64 so A is included in addition
stringElements.append(chr(64+(int(shiftValue)-(90-ord(letter)))))
#exit the function, returning the whole word
return("".join(stringElements))
def moveCharsDecode(inputString,shiftValue):
lst = list(inputString)
stringElements = []
for letter in lst:
#Letters can be moved around without going past A-Z
if ord(letter) < (91) and ord(letter) > (64+shiftValue):
stringElements.append(chr(ord(letter)-shiftValue))
#Tests for spaces, punctuation, etc.
elif ord(letter) < 65 or ord(letter) > 90:
stringElements.append(letter)
else:
# We have to move S letters backward, so we see what is already covered
# from the current letter to A, and subtract the remaining from Z
# eg. if E with shift of 5, we can cover 4 letters until A, and then add Z
# Start from 91 so Z is included in addition
stringElements.append(chr(91-(shiftValue-(ord(letter)-65))))
#return just the list
return stringElements
print("Mayur's Caesar Shift Cipher Encoder/Decoder - v1.0\n")
# Does user want to encode or decode, keep going until proper response
while 1:
while True:
mode=input("Would you like to encode or decode? E/D/EXIT: ").upper()
if mode == "e".upper() or mode == "d".upper() or mode == "exit".upper():
break
# User wants to encode
if mode == "E":
shiftValue = "invalid"
inputString = ''
allowedShifts = '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 r R'.split(' ')
# make a var with name inputString containing string
#and shiftValue, an integer between 1 and 25
print('')
while len(inputString) == 0:
inputString = (input("Enter string to be encoded: ")).upper()
print('')
while shiftValue not in allowedShifts:
shiftValue = (input("Enter shift value from 1-25 or R (random): "))
#print out the result of encode function, which is the joined word
print ("\nYour encoded string is: "+ encode(inputString,shiftValue)+'\n')
# User wants to decode
elif mode == "D":
shiftKnown = ''
inputString = ''
print('')
while len(inputString)==0:
inputString = input("Enter string to be decoded: ").upper()
print('')
while shiftKnown != 'Y' and shiftKnown != 'N':
shiftKnown = input("Is shift value known? Y/N: ").upper()
print('')
# Shift value is known
if shiftKnown == "Y":
#S is the shift value
S = ''
allowedShifts = '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'.split(' ')
while S not in allowedShifts:
S = input("Enter shift value from 1-25: ")
S = int(S)
#print our the result of moveChars decode, after joining the list elements together
print ("\nYour decoded string is: "+ "".join(moveCharsDecode(inputString,S))+'\n')
# Shift value is unknown
else:
# from here on is natural language processing
points = 0
pointsArray = []
#Move through 1-25 (different shift values
for i in range(1,26):
#reset points after each number
points = 0
#assign different point values based on frequency of letters in English
#loop through every character
for character in moveCharsDecode(inputString,i):
if character == "A":
points += 8.167
if character == "B":
points += 1.492
if character == "C":
points += 2.782
if character == "D":
points += 4.253
if character == "E":
points += 12.702
if character == "F":
points += 2.228
if character == "G":
points += 2.015
if character == "H":
points += 6.094
if character == "I":
points += 6.966
if character == "J":
points += 0.153
if character == "K":
points += 0.772
if character == "L":
points += 4.025
if character == "M":
points += 2.406
if character == "N":
points += 6.749
if character == "O":
points += 7.507
if character == "P":
points += 1.929
if character == "Q":
points += 0.095
if character == "R":
points += 5.987
if character == "S":
points += 6.327
if character == "T":
points += 9.056
if character == "U":
points += 2.758
if character == "V":
points += 0.978
if character == "W":
points += 2.360
if character == "X":
points += 0.150
if character == "Y":
points += 1.974
if character == "Z":
points += 0.074
#still part of NLP, checks for pairs of the same letters
for j in range(0,len(moveCharsDecode(inputString,i))-1):
nextDoubleSet = moveCharsDecode(inputString,i)[j] + moveCharsDecode(inputString,i)[j+1]
if nextDoubleSet == "LL":
points += 56
if nextDoubleSet == "EE":
points += 48
if nextDoubleSet == "SS":
points += 43
if nextDoubleSet == "OO":
points += 36
if nextDoubleSet == "TT":
points += 56
if nextDoubleSet == "FF":
points += 11
if nextDoubleSet == "RR":
points += 14
if nextDoubleSet == "NN":
points += 8
if nextDoubleSet == "PP":
points += 10
if nextDoubleSet == "CC":
points += 4
if nextDoubleSet == "AA":
points += 1
if nextDoubleSet == "BB":
points += 1
if nextDoubleSet == "DD":
points += 13
if nextDoubleSet == "GG":
points += 4
if nextDoubleSet == "HH":
points += 6
if nextDoubleSet == "II":
points += 1
if nextDoubleSet == "JJ":
points += 0
if nextDoubleSet == "KK":
points += 0
if nextDoubleSet == "MM":
points += 5
if nextDoubleSet == "QQ":
points += 0
if nextDoubleSet == "UU":
points += 0
if nextDoubleSet == "VV":
points += 0
if nextDoubleSet == "WW":
points += 2
if nextDoubleSet == "XX":
points += 0
if nextDoubleSet == "YY":
points += 2
if nextDoubleSet == "ZZ":
points += 0
#for each shift value, a different item in the array will have a value
pointsArray.append(points)
# the highest points value is the most likely shift, and add 1 because list elements start at 0
actualShift = pointsArray.index(max(pointsArray)) + 1
#print out the result, passing in actualShift
print ("The most likely string is: "+"".join(moveCharsDecode(inputString,actualShift))+", where shift is "+str(actualShift))
print('')
seeMore = ''
#what if our NLP was wrong? Let the user see more...
while seeMore != 'Y' and seeMore != 'N':
seeMore = input(("Output doesn't make sense? Would you like to see more? (Y/N): ")).upper()
if seeMore == "Y":
#every single shift value, print it out
for i in range(1,26):
print ("\n"+"".join(moveCharsDecode(inputString,i))+", where shift is "+str(i))
print('')
else:
break
|
b9a3f5e9264993776168662d45ab821a83466014 | pwnmeow/Basic-Python-Exercise-Files | /ex/guessingv2.py | 495 | 4.03125 | 4 | import random
random_number = random.randint(1,10)
num = None
while True:
num = int(input("guess the number bw 1 - 10 "))
if num == random_number:
print("you guessed it right!")
elif num < random_number:
print("you guessed too low")
else:
print("thats too high")
play_again = input("Do you want to play again (y/n) ")
if play_again == "y":
random_number = random.randint(1,10)
num = None
else: print("thanks for playing")
break
print(random_number)
|
66ff889ab7a5e4d283cc83b06e9aceb6b4f5933a | OndrejHudecek/PythonAcademy | /Exercises/Task034_MinMax.py | 615 | 3.640625 | 4 | # Tvým úkolem je vytvořit dvě funkce:
# Funkce my_min(), která imituje built-in funkci min().
# Funkce by měla přijmout jakoukoli sekvenci a vrátit položku s nejmenší hodnotou.
seq = [43,45,87,21,23]
def main(sequence):
my_max(seq)
my_min(seq)
def my_min(sequence):
minimum = seq[0]
for num in seq[1:]:
if num < minimum:
minimum = num
return print(f"Minimum number is {minimum}")
def my_max(sequence):
maximum = seq[0]
for num in seq[1:]:
if num > maximum:
maximum = num
return print(f"Maximum number is {maximum}")
main(seq) |
ffaa25a66686d7f7956f40ba5beee9e9907c1a9b | Dinowa/Ormuco_test | /Q2/compareVersion.py | 539 | 3.609375 | 4 | def compareVersion(version1: str, version2: str) -> str:
v1, v2 = version1.split('.'), version2.split('.')
d1, d2 = {}, {}
for i in range(len(v1)):
d1[i] = int(v1[i])
for i in range(len(v2)):
d2[i] = int(v2[i])
for i in range(max(len(d1), len(d2))):
tmp = d1.get(i, 0) - d2.get(i, 0)
if tmp > 0:
return f'{version1} is larger than {version2}'
elif tmp < 0:
return f'{version1} is smaller than {version2}'
return f'{version1} is the same as {version2}' |
35a0e66776f0e7f42cfa6baeacb32312056f81bc | bksahu/dsa | /dsa/patterns/two_pointers/triplet_with_smaller_sum.py | 1,146 | 4.25 | 4 | """
Given an array arr of unsorted numbers and a target sum, count all triplets in it such
that arr[i] + arr[j] + arr[k] < target where i, j, and k are three different indices.
Write a function to return the count of such triplets.
Example 1:
Input: [-1, 0, 2, 3], target=3
Output: 2
Explanation: There are two triplets whose sum is less than the target: [-1, 0, 3], [-1, 0, 2]
Example 2:
Input: [-1, 4, 2, 1, 3], target=5
Output: 4
Explanation: There are four triplets whose sum is less than the target:
[-1, 1, 4], [-1, 1, 3], [-1, 1, 2], [-1, 2, 3]
"""
def search_pair(arr, firstIdx, target):
first = arr[firstIdx]
left, right = firstIdx+1, len(arr)-1
curr_count = 0
while left < right:
if arr[left] + arr[right] + first < target:
curr_count = right - left
left += 1
else:
right -= 1
return curr_count
def solution(arr, target):
arr.sort()
count = 0
for i in range(len(arr)):
count += search_pair(arr, i, target)
return count
if __name__ == "__main__":
print(solution([-1, 0, 2, 3], 3))
print(solution([-1, 4, 2, 1, 3], 5)) |
2416803bed860770c1524fa5be29b761c85a141e | antonpetkoff/Programming101 | /Programming101/week0/is_prime.py | 397 | 4.03125 | 4 |
def is_prime(n):
if n < 2:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
for i in range(3, n, 2):
if n % i == 0:
return False
return True
def main():
print(is_prime(1))
print(is_prime(2))
print(is_prime(8))
print(is_prime(11))
print(is_prime(-10))
if __name__ == '__main__':
main()
|
943a69e69e964c101794fa514f934df56fe09323 | baozi1110/python-100-learn | /07/string/string1.py | 429 | 3.8125 | 4 | s1 = 'hello, world!'
s2 = "hello, world!"
# 以三个双引号或单引号开头的字符串可以折行
s3 = """
hello,
world!
"""
print(s1, s2, s3, end='')
print('\n', end='')
s1 = '\'hello, world!\''
s2 = '\n\\hello, world!\\\n'
print(s1, s2, end='')
print()
s1 = '\141\142\143\x61\x62\x63\n'
s2 = '\u9a86\u660a'
print(s1, s2)
print()
s1 = r'\'hello, world!\''
s2 = r'\n\\hello, world!\\\n'
print(s1, s2, sep="\n", end='')
|
f4cbcbd1bb77b397966893e2c5e4d2d5cfdcf330 | anoobishnoob/Least-Common-Multiple | /LeastCommonMultiple.py | 474 | 3.96875 | 4 | #Title: Lab #3 Least Common Multiple, Samme Qandil
#input: two positive ints a and b
#output: prints the least common multiple
import math
print ("please put two ints above zero please and thank you")
a = int(input())
b = int(input())
lcm = a * b / math.gcd(a, b)
print (lcm)
'''
so the lcm in number theory is basically just a *b / the gcd of a*b. Since we are allowed to use the math library of code, then I suppose we are allowed to use the gcd function
'''
|
78cbaaea56931a4bc413f9f3cc8acb056a9bbe1e | minseunghwang/YouthAcademy-Python-Mysql | /작업폴더/34_실습문제4/main.py | 403 | 3.765625 | 4 | # 사용자가 종료할 때까지 입력받은 문자열을 "c:/새파일.txt' 파일에 계속 추가하는 코드를 작성하시오
# C드라이브는 권한문제있어서 D드라이브나 현재위치에 ㄱㄱ
while True :
data = input('입력 : ')
if not data:
break
with open('D:\새파일.txt', 'at', encoding='utf-8') as fp :
fp.write(data+' ')
print(data) |
6d8f61da3fc7bf2a3f3be617795600fde0da2a98 | gdfelt/competition | /euler/python3/euler035.py | 876 | 3.859375 | 4 | #!/usr/bin/env python3
"""
Project Euler Problem 35
========================
The number, 197, is called a circular prime because all rotations of the
digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37,
71, 73, 79, and 97.
How many circular primes are there below one million?
"""
import utils
sieve = utils.get_prime_sieve(1000000)
def check_rotation_list(list_rotations):
for r in list_rotations:
if sieve[int(r)] == False:
return False
return True
def get_rotations(str):
rotations = []
for x in range(len(str)):
rotations.append(str[x:] + str[0:x])
#print(rotations)
return rotations
def main():
count = 0
for index, n in enumerate(sieve):
if n == True:
if check_rotation_list(get_rotations(str(index))):
count += 1
print(count)
if __name__ == "__main__":
main() |
adb9c91d4560f45727e5ad8da97334eccd1e58a9 | wrr123/Python-100-Days | /Day01-15/code/Day04/for1.py | 170 | 3.859375 | 4 | """
用for循环实现1~100求和
Version: 0.1
Author: 骆昊
Date: 2018-03-01
"""
sum1 = 0
for x in range(1, 101):
sum1 += x
print(sum1)
print(sum(range(1, 101)))
|
0aba1816d2bde4e3f5bbcd589d8ed702fd608769 | gitktlee88/MPS-project | /tests_mytest/primes.py | 1,083 | 4.28125 | 4 | """
A prime number is a whole number greater than 1 whose only factors are 1 and itself.
If a number n is not a prime, it can be factored into two factors a and b: n = a * b
If both a and b were greater than the square root of n, then a * b would be greater than n.
So at least one of those factors must be less than or equal to the square root of n,
and if we can't find any factors less than or equal to the square root, n must be prime.
"""
import math
def is_prime(num):
# Prime numbers must be greater than 1
if num < 2:
return False
# The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result.
# The sqrt() method returns the square root of a number.
for n in range(2, math.floor(math.sqrt(num) + 1)):
# print(n)
if num % n == 0:
return False
return True
def sum_of_primes(nums):
# sum_of_prime_nums = 0
# for i in nums:
# if is_prime(i):
# sum_of_prime_nums += i
# return sum_of_prime_nums
return sum([x for x in nums if is_prime(x)])
|
329172870569340508b553f94e9db1ca44737a56 | jdelacruz9/CODE2040-API-Challenge | /stage1.py | 1,174 | 3.5625 | 4 | #author: Julio de la Cruz
#email: [email protected]
import requests
import json
#my identifying token
token = 'jcUHJ3Axst'
#this is the JSON dictionary, with my token, that I will use to get the string
data = {
'token': token
}
#this is the response of the request that will contain the json with the string. I have
#post the request with the endpoint url and my dictionary. To use the dictionary in the
#request I have to encode it, that's why I used json.dumps.
r = requests.post('http://challenge.code2040.org/api/getstring', json.dumps(data))
#the string to be reversed, received in the request
string = r.json()['result']
#printing the string to be reversed
print "This is the string: %s" %(string)
#the reversed string
reversedString = string[::-1]
#printing the reversed string
print "This is the reversed string: %s" %(reversedString)
#final dictionary with my token and the reversed string to use in the final request
finalData = {
'token': token,
'string': reversedString
}
#response of the final request
response = requests.post('http://challenge.code2040.org/api/validatestring', json.dumps(finalData))
#lets see if I passed the stage 1
print response.json()
|
62e753a5521c62b372aa1a302bb95adcc1c00ad6 | imaheshaher/Python-OOP | /oop2.py | 483 | 3.71875 | 4 | class Rectangle:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def square(self):
return "hello"
return self.length*self.breadth
class Calculate(Rectangle):
def __init__(self,id,list):
self.id=id
self.list=list
def calcsq(self):
for i in self.list:
# super().__init__(i.length,i.breadth)
v=self.square()
print(v)
l=[]
ob=Rectangle(10,20)
ob2=Rectangle(20,30)
l.append(ob)
l.append(ob2)
cob=Calculate(1,l)
cob.calcsq()
|
f1bf57f85f372848a950b45fbaecc3ad7e67395c | naveensiwas/python | /7.python_operators.py | 837 | 4.34375 | 4 | #Example 1: Arithmetic operators in Python
x = 15
y = 4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
#Example 2: Comparison operators in Python
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
#Example 3: Logical Operators in Python
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
#Example 4: Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
#Example 5: Membership operators in Python
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
|
2ed9d90841a988a85b02517975ad33fb6017cf33 | DOG-BREAD/hackdfwProj | /proj.py | 1,574 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def main():
with open("writes.txt", "w+") as file:
with open('reads.txt', "r+") as reads:
contents = reads.read()
while True:
# writes a string to a file
file.write(str(getTemperatureMoniter()))
file.write(str(getHumidityMoniter()))
file.write(str(getInventoryCount()))
file.write(str(getLocation()))
file.write(str(copylogs()))
file.write(str(fileuploader()))
file.write(str(encryption()))
def getTemperatureMoniter():
temp = input("Gathering current temperature")
print("current temperature" + temp)
return temp
def getHumidityMoniter():
humidity = input("Humidity %")
print("current temperature" + humidity)
return humidity
def getInventoryCount():
inventory = input("Gathering current temperature")
print("current temperature" + inventory)
return inventory
def getLocation():
location = input("Gathering current temperature")
print("current temperature" + location)
return location
def copylogs():
copy = input("Gathering current temperature")
return
def fileuploader():
temp = input("Gathering current temperature")
print("current temperature" + temp)
return
def encryption():
temp = input("Gathering current temperature")
print("current temperature" + temp)
return temp
|
b2e46834a41d67e2872ceb067c8201090a55cedf | virajs/codeeval | /1-moderate/overlapping-rectangles/main.py | 2,178 | 3.71875 | 4 | import sys
class Rectangle:
def __init__(self,
upper_left_x, upper_left_y,
lower_right_x, lower_right_y):
self.upper_left_x = upper_left_x
self.upper_left_y = upper_left_y
self.lower_right_x = lower_right_x
self.lower_right_y = lower_right_y
def contains_point(self, x, y):
fits_in_x = self.upper_left_x <= x <= self.lower_right_x
fits_in_y = self.lower_right_y <= y <= self.upper_left_y
return fits_in_x and fits_in_y
def overlaps_with_rectangle(self, rectangle):
# Left side
for y in range(self.lower_right_y, self.upper_left_y+1):
if rectangle.contains_point(self.upper_left_x, y):
return True
# Top side
for x in range(self.upper_left_x, self.lower_right_x+1):
if rectangle.contains_point(x, self.upper_left_y):
return True
# Right side
for y in range(self.lower_right_y, self.upper_left_y+1):
if rectangle.contains_point(self.lower_right_x, y):
return True
# Bottom side
for x in range(self.upper_left_x, self.lower_right_x+1):
if rectangle.contains_point(x, self.lower_right_y):
return True
return False
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.strip()
if len(test) == 0:
continue
coordinates = test.split(",")
# Upper left and lower right corners of rectangle A.
a_upper_left_x = int(coordinates[0])
a_upper_left_y = int(coordinates[1])
a_lower_right_x = int(coordinates[2])
a_lower_right_y = int(coordinates[3])
# Upper left and lower right corners of rectangle B.
b_upper_left_x = int(coordinates[4])
b_upper_left_y = int(coordinates[5])
b_lower_right_x = int(coordinates[6])
b_lower_right_y = int(coordinates[7])
a = Rectangle(a_upper_left_x, a_upper_left_y,
a_lower_right_x, a_lower_right_y)
b = Rectangle(b_upper_left_x, b_upper_left_y,
b_lower_right_x, b_lower_right_y)
print(a.overlaps_with_rectangle(b))
test_cases.close()
|
3bbe3dc72196c7ce8b6b9a5cce31d5de65a7c393 | Fariddeniro/Python-for-everybody | /8.5. Lists and Strings 2 (L2-W4).py | 277 | 3.90625 | 4 | fname = input("Enter file name: ")
fh = open(fname)
count = 0
lst=list()
for line in fh:
if line.startswith('From '):
lst=line.rstrip().split()
print(lst[1])
count=count+1
print("There were", count, "lines in the file with From as the first word")
|
526105de5fe98691b2179c2131243e9c0a2ee90b | ashwini1025/KurzBot | /process.py | 7,438 | 3.5625 | 4 | def get_sentences(file_name):
# Extract sentences from a text file.
reader = open(file_name)
sentences = reader.read()
reader.close()
sentences = sentences.replace("\n", "")
sentences = convert_abbreviations(sentences)
sentences = sentences.replace("?", ".")
sentences = sentences.replace("!", ".")
sentences = sentences.split(".")
sentences = fix_broken_sentences(sentences)
sentences = remove_whitespace_list(sentences)
sentences = remove_blanks(sentences)
sentences = add_periods(sentences)
#print(sentences)
sentences = clean_up_quotes(sentences)
sentences = group_quotes(sentences)
sentences = comma_handler(sentences)
return sentences
def get_words(file_name):
reader = open(file_name)
words = reader.read()
reader.close()
words = words.replace("\n", " ")
words = convert_abbreviations(words)
words = words.split(" ")
words = remove_blanks(words)
for i in range(0, len(words)):
words[i] = clean(words[i])
return words
def comma_handler(sentences):
new_list = []
skip = False
for i in range(0, len(sentences)):
if skip:
skip = False
continue
if i+1 < len(sentences) and sentences[i+1][0] == ",":
new_list.append(sentences[i] + sentences[i+1])
skip = True
else:
new_list.append(sentences[i])
return new_list
def group_quotes(sentences):
new_list = []
skip = 0
for i in range(0, len(sentences)):
if skip > 0:
skip -= 1
continue
sentence = sentences[i]
while sentence.count("\"") % 2 == 1:
skip += 1
if i+skip >= len(sentences):
break
if sentences[i+skip][0].isalnum():
sentence += " " + sentences[i+skip]
else:
sentence += sentences[i+skip]
new_list.append(sentence)
return new_list
def clean_up_quotes(sentences):
generified = []
for sentence in sentences:
sentence = sentence.replace('“', '\"')
sentence = sentence.replace('”', '\"')
generified.append(sentence)
new_list = [generified[0]]
for i in range(1, len(generified)):
sentence = generified[i]
isolated_quotation = generified[i][0] == "\"" and generified[i][1] == " "
quotation_with_period = generified[i][0] == "\"" and generified[i][1] == "."
if isolated_quotation and quotation_with_period:
sentence = sentence[2:]
new_list[-1] += "\""
new_list.append(sentence)
return new_list
def add_periods(sentences):
new_list = []
for sentence in sentences:
new_list.append(sentence + ".")
return new_list
def remove_blanks(sentences):
new_list = []
for sentence in sentences:
if sentence != "":
new_list.append(sentence)
return new_list
def fix_broken_sentences(sentences):
file = open("word_lists/abbreviations.txt")
abbreviations = str(file.read()).split("\n")
file.close()
new_list = []
flag = False
for i in range(0, len(sentences)):
if flag:
flag = False
continue
last_word = sentences[i].split(" ")[-1]
last_word = remove_punctuation(last_word)
last_word = to_singular(last_word)
last_word = remove_punctuation(last_word)
last_word += "."
new_list.append(sentences[i])
for abbreviation in abbreviations:
if abbreviation == last_word:
new_list[-1] += "." + sentences[i+1]
flag = True
break
return new_list
def convert_abbreviations(string):
file = open("word_lists/abbreviations_multi.txt")
abbreviations = str(file.read()).split("\n")
file.close()
new_string = string
abbreviations_in_string = []
for abbreviation in abbreviations:
if abbreviation in string:
abbreviations_in_string.append(abbreviation)
abbreviations_in_string.sort(key=str.__len__)
abbreviations_in_string.reverse()
for abbreviation in abbreviations_in_string:
if abbreviation in new_string:
new_string = str(new_string).replace(abbreviation, abbreviation.replace(".", ""))
return new_string
def clean(word):
new_word = remove_punctuation(word)
new_word = to_singular(new_word)
new_word = remove_punctuation(new_word)
new_word = str(new_word).lower()
return new_word
def to_singular(word):
new_word = word
if word.endswith("'s") or word.endswith("s'"):
new_word = word[:-2]
elif word.endswith("ies"):
new_word = word[:-3] + "y"
return new_word
def remove_punctuation(word):
new_word = word
while new_word is not "" and not str(new_word)[0].isalnum():
new_word = new_word[1:]
while new_word is not "" and not str(new_word)[-1].isalnum():
new_word = new_word[:-1]
return new_word
def remove_whitespace_list(sentences):
new_list = []
for sentence in sentences:
new_list.append(remove_whitespace(sentence))
return new_list
def remove_whitespace(word):
new_word = word
while new_word is not "" and str(new_word).startswith(" "):
new_word = new_word[1:]
while new_word is not "" and str(new_word).endswith(" "):
new_word = new_word[:-1]
return new_word
def get_transition_phrases():
lines = open("word_lists/transition_phrases.txt").readlines()
result = []
for line in lines:
result.append(line.lstrip().rstrip())
return result
def is_transition_phrase(transition_phrases, sentence):
lower = sentence.lower()
for phrase in transition_phrases:
if lower.startswith(phrase):
return True
return False
def omit_transition_sentences(sentences):
transition_phrases = get_transition_phrases()
result = []
for sentence in sentences:
if not is_transition_phrase(transition_phrases, sentence):
result.append(sentence)
return result
def get_word_scores(all_words):
file = open("word_lists/words_to_ignore.txt")
words_to_ignore = file.read().split("\n")
file.close()
dictionary = {}
for word in all_words:
if word in words_to_ignore:
continue
count = 1
if word in dictionary:
count += dictionary.get(word)
temp = {word: count}
dictionary.update(temp)
return dictionary
def score(sentence, word_scores):
denominator = 1.0
score = 0.0
words = sentence.split(" ")
for word in words:
if word not in word_scores:
continue
if sentence.count(word) == 1:
denominator += 1.0
word = clean(word)
score += word_scores.get(word)
return score/denominator
def get_sentence_scores_list(all_sentences, word_scores):
scores = []
for sentence in all_sentences:
scores.append(score(sentence, word_scores))
return scores
def x_highest_score(sentence_scores, x):
list = []
for score in sentence_scores:
list.append(score)
list.sort()
return list[-x]
def top_sentences(all_sentences, sentence_scores, threshold):
result = []
for i in range(0, len(all_sentences)):
if sentence_scores[i] >= threshold:
result.append(all_sentences[i])
return result
|
ff54beafcbdddd43323e27a9fe801a9c5c7ebef8 | maddygohan/madhan | /python24.py | 103 | 3.546875 | 4 | n = int(input(""))
li=list(map(int, input("").split()))
for i in range(n):
li.sort()
print("",*li)
|
ff9caac14fbe4f24c62fd9a8814302fc26d80e31 | Dizzie42/MegaProjects-Solutions | /MortgageCalc.py | 1,041 | 4.3125 | 4 | #Mortgage Calculator - Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate.
#Also figure out how long it will take the user to pay back the loan. For added complexity, add an option for users to select the
#compounding interval (Monthly, Weekly, Daily, Continually).
#No edit checks, we're lazy
terms = int(input('Enter number of months (terms): '))
int_rate = float(input('Enter an interest rate: '))
loan = float(input('Enter a loan value: '))
#Mortgage payment calc formula :
#Mortgage_Payment = Principal [i(1+i)^n]/[(1+i)^n-1]
#i = monthly interest rate (total /12)
#n = number of payments over life of the loan
def calculate(t, i, amt):
monthly_rate = (i/100)/12 #/100 to get decimal, /12 for monthly
p = amt * (monthly_rate*((1+monthly_rate)**t)) / ((1+monthly_rate)**(t)-1)
return p;
result = calculate(terms, int_rate, loan)
print( "M. payment for a $%.2f %s year mortgage at %.2f%% int rate is: $%.2f" % (loan, (terms/12), int_rate, result) ) |
e30dc755fcfa3cf0ef3cf564c09c188c170acf14 | cadebaker/343-Project3 | /neighborhood.py | 3,299 | 3.515625 | 4 | from observer import Observer
from player import *
from home import *
"""******************************************************
*A class that represents the entire neighborhood of the
*Zork game
******************************************************"""
class Neighborhood(Observer):
#constructor
def __init__(self):
super(Neighborhood, self).__init__()
self.rows = 0
self.cols = 0
self.totalNumMonster = 0
self.neighborhood = []
#creates the neighborhood
def createNeighborhood(self, rows, cols):
self.rows = rows
self.cols = cols
for row in range(0, self.rows):
self.neighborhood.append([])
for col in range(0, self.cols):
h = Home()
h.add_observer(self)
self.neighborhood[row].append(h)
#getter for the number of monsters in the neighborhood
def getTotalNumMonster(self):
return self.totalNumMonster
#getter for the number of monsters in the neighborhood
def getHouse(self, row, col):
return self.neighborhood[row][col]
#prints the neighborhood and updates the total number of monsters
def printNeighborhood(self, location):
currentLocation = [0, 0]
for row in range(0, self.rows):
#print the current location
for col in range(0, self.cols):
currentLocation = [row, col]
if col == self.cols-1:
print(" {}".format(currentLocation))
else:
print(" {}".format(currentLocation), end = '' )
#print format for horizontal lines
for col in range(0, self.cols):
if col == self.cols-1:
print(" _____ ")
else:
print(" _____ ", end = '' )
#print format for vertical lines
for col in range(0, self.cols):
if col == self.cols-1:
print("| |")
else:
print("| |", end = '' )
#print number of monsters in the house inside the formatted box
for col in range(0, self.cols):
h = self.neighborhood[row][col]
self.totalNumMonster = self.totalNumMonster + h.getNumMonster()
if col == self.cols-1:
if(self.neighborhood[row][col].getNumMonster() != 10):
print("| {} |".format(self.neighborhood[row][col].getNumMonster()))
else:
print("| {} |".format(self.neighborhood[row][col].getNumMonster()))
else:
if(self.neighborhood[row][col].getNumMonster() != 10):
print("| {} |".format(self.neighborhood[row][col].getNumMonster()), end ='')
else:
print("| {} |".format(self.neighborhood[row][col].getNumMonster()), end ='')
for col in range(0, self.cols):
if col == self.cols-1:
print("|_____|")
else:
print("|_____|", end = '' )
#show the selected house
for col in range(0, self.cols):
currentLocation = [row, col]
if currentLocation == location:
if col == self.cols-1:
print(" * ")
else:
print(" * ", end = '')
else:
if col == self.cols-1:
print(" ")
else:
print(" ", end = '')
print(" ")
#updates the number of monsters in the neighborhood
def updateCl(self):
self.totalNumMonster = 0
for row in range(0, self.rows):
for col in range(0, self.cols):
self.totalNumMonster = self.totalNumMonster + self.neighborhood[row][col].getNumMonster()
|
962175eca64f513e8c9fa87aa927c70ccc84f8ba | IronE-G-G/algorithm | /leetcode/前100题/019removeNthNode.py | 1,338 | 3.5625 | 4 | """
思路1:维护一个n+1长的队列,按顺序压入结点,遍历完第一个结点就是倒数n+1个结点。
思路2:双指针;让快指针先走n+1步,这样遍历完慢指针就能指在倒是n+1个结点(如果n不等于链表长度的话)
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
queue = []
if not head:
return None
while head:
queue.append(head)
head = head.next
if n == len(queue):
# 写queue[1]有可能出界
return queue[0].next
# -(n+1)可能出界,所以需要判断n的值
cur = queue[-(n + 1)]
cur.next = cur.next.next
return queue[0]
class Solution2:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
fast = head
slow = head
count = n + 1
while count > 0 and fast:
fast = fast.next
count -= 1
# n(前提有效) 为链表长度
if count == 1:
return head.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
|
87ac345667c0c7d255f34cbe4199135968952d35 | MartySalamea/CS50x | /ProblemSet7/houses/roster.py | 802 | 3.890625 | 4 | # TODO
from cs50 import SQL
from sys import argv
# check that we launched the code with proper arguments, otherwise it exits the program
if len(argv) < 2:
print("usage error, roster.py houseName")
exit()
# open the database in a variable and then execute a query that list all the people from a particular house in alphabetical order
db = SQL("sqlite:///students.db")
students = db.execute("SELECT * FROM students WHERE house = (?) ORDER BY last", argv[1])
# print each person showing their information and their middle name if they have one
for student in students:
if student['middle'] != None:
print(f"{student['first']} {student['middle']} {student['last']}, born {student['birth']}")
else:
print(f"{student['first']} {student['last']}, born {student['birth']}")
|
e0c41605ffe00deb308db273d6fb6cc7a9da1ef0 | Spas52/Python_Fundamentals | /Exams/final_exam_2.03.py | 2,097 | 3.640625 | 4 | number_of_heroes = int(input())
party = {}
# {'Solmyr': ['85' hp, '120' mana], 'Kyrre': ['99', '50']}
for _ in range(number_of_heroes):
hero = input().split()
party[hero[0]] = [int(hero[1]), int(hero[2])]
data = input()
while not data == "End":
command = data.split(" - ")
action = command[0]
if action == "CastSpell":
hero_name = command[1]
mp_needed = int(command[2])
spell_name = command[3]
if party[hero_name][1] >= mp_needed:
party[hero_name][1] -= mp_needed
print(f"{hero_name} has successfully cast {spell_name} and now has {party[hero_name][1]} MP!")
else:
print(f"{hero_name} does not have enough MP to cast {spell_name}!")
elif action == "TakeDamage":
hero_name = command[1]
damage = int(command[2])
attacker = command[3]
party[hero_name][0] -= damage
if party[hero_name][0] > 0:
print(f"{hero_name} was hit for {damage} HP by {attacker} and now has {party[hero_name][0]} HP left!")
else:
del party[hero_name]
print(f"{hero_name} has been killed by {attacker}!")
elif action == "Recharge":
hero_name = command[1]
amount = int(command[2])
if party[hero_name][1] + amount > 200:
amount = 200 - party[hero_name][1]
party[hero_name][1] = 200
else:
party[hero_name][1] += amount
print(f"{hero_name} recharged for {amount} MP!")
elif action == "Heal":
hero_name = command[1]
amount = int(command[2])
if party[hero_name][0] + amount > 100:
amount = 100 - party[hero_name][0]
party[hero_name][0] = 100
else:
party[hero_name][0] += amount
print(f"{hero_name} healed for {amount} HP!")
data = input()
party = dict(sorted(party.items(), key=lambda kvp: (- kvp[1][0], kvp[0])))
for hero in party:
print(f"{hero}")
print(f" HP: {party[hero][0]}")
print(f" MP: {party[hero][1]}")
|
6b202b219144d4488c5102e11fb08c35b346bcfc | brcmst/python-tutorials | /iterator/iterator-kumanda-class.py | 651 | 4.03125 | 4 | #iter sınıfı olusturma
#__iter()__ ve __next()__ metodlarını tanımlamak gerek
class Kumanda():
def __init__(self, kanallar):
self.kanallar = kanallar
self.index = -1
def __iter__(self):
return self
def __next__(self):
self.index += 1
if (self.index < len(self.kanallar)):
return self.kanallar[self.index]
else:
self.index = -1
raise StopIteration
kumanda = Kumanda(["a","b","c"])
ıterator3 = iter(kumanda)
print(next(ıterator3))
print(next(ıterator3))
print(next(ıterator3))
|
536064e7d26750d78fac6bacb2a0c608792be95b | IMDCGP105-1819/portfolio-louisvagner | /why.py | 746 | 4.15625 | 4 | month_counter = 0
portion_deposit = 0.20
current_savings = 0
r = 0.04
annual_salary = input ("Please enter your current annual salary: ")
portion_saved = input ("Please enter how much you would like to be saved, as a decimal: ")
total_cost = input ("Please enter the cost of your dream home: ")
annual_salary = int(annual_salary)
portion_saved = float(portion_saved)
total_cost = float(total_cost)
monthly_salary = annual_salary/12
while current_savings != total_cost:
current_savings = monthly_salary + (monthly_salary/r)
month_counter = month_counter + 1
if current_savings == total_cost:
print (current_savings)
print (total_cost)
else:
print (current_savings)
print (total_cost)
|
b15da753d086c729faaddad779ae7d38c6c9d664 | hs634/algorithms | /python/misc/OrderedDict.py | 1,842 | 3.5625 | 4 | __author__ = 'hs634'
#from collections import OrderedDict
# d = OrderedDict()
# d['a'] = 1
# d['b'] = 2
# d['c'] = 3
# d['a'] = 5
# for k, v in d.iteritems():
# print k, v
# __setitem__, __getitem__, pop, popitem
# self.map = {'key': 'value, next'}
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
class OrderedDict(object):
def __init__(self):
self.map = {}
self.most_recent = None
def __setitem__(self, key, value):
#if item not in self.map:
# self.most_recent = item
#self.map[item] = value
if key not in self.map:
node = Node(key, value)
if self.most_recent is not None:
node.prev = self.most_recent
self.most_recent.next = node
self.most_recent = node
self.map[key] = node
else:
self.map[key].val = value
def __getitem__(self, key):
return self.map[key].val
def pop(self, item):
node = self.map[item]
temp = node.val
if node.prev and node.next:
node.prev.next = node.next
node.next.prev = node.prev
else:
if node.prev:
node.prev.next = node.next
self.most_recent = node.prev
elif node.next:
node.next.prev = node.prev
else:
self.most_recent = None
del self.map[item]
return temp
# def popitem(self):
# if len(self.map.keys()) == 0:
# raise KeyError("Dict is empty")
# self.pop(self.most_recent)
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['a'] = 5
print d.pop('c')
d.pop('b')
d.pop('a')
#print d.most_recent.val, d.most_recent.key |
d9726a7d26b8b58f437f6333d7ffae08e943938c | RicardoVeronica/python-little-projects | /projects/phonebook_dir/phonebook-modules/functions.py | 1,949 | 4.03125 | 4 | contacts = {}
def add_contact():
name = input('\nGive a name for you new contact: ')
name = name.upper()
try:
phone = int(input('Give a number for you new contact: '))
contacts[name] = phone
print('\nContact: {}\nPhone number: {}\nAdded'.format(name, phone))
except ValueError:
print('\nWrite a phone number')
def update_contact():
if len(contacts) == 0:
print("\nYou dont't have any contact")
else:
contact_to_change = input('\nGive me the name to update: ')
contact_to_change = contact_to_change.upper()
change_number = input('Write the new number: ')
contacts[contact_to_change] = change_number
print('\nThe contact {} has change number for {}'.
format(contact_to_change, change_number))
def remove_conntact():
if len(contacts) == 0:
print("\nYou don't have any contact")
else:
name = input('\nGive me the name of the contact to delete: ')
name = name.upper()
contacts.pop(name)
print('\nThe contact {} was deleted'.format(name))
def see_a_contact():
if len(contacts) == 0:
print("\nYou don't have any contact")
else:
contact = input('\nGive me the name for the query: ')
contact = contact.upper()
if contact in contacts:
query = contacts[contact]
print('\n{} : {}'.format(contact, query))
else:
print('\nContact {}, do not exist'.format(contact))
def see_all_contacts():
if len(contacts) == 0:
print("\nYou don't have any contact")
else:
for idx, contact in enumerate(contacts):
print('\n{} - {} : {}'.format(idx + 1, contact,
contacts[contact]))
def clear_phonebook():
if len(contacts) == 0:
print("\nYou don't have any contact")
else:
contacts.clear()
print('\nThe phonebook is clear')
|
7c308618eb27cb32087bbdb477cbf49bf0886e62 | RossCZ/PythonLearning | /topics/3_loops/1_for_loops.py | 278 | 3.640625 | 4 | # for cyklus (smycka)
for i in range(5):
print(f"Apple {i}")
# priklad: suma i pro range(5)
sum = 0
for i in range(5):
# tady se to secte
sum += i # sum = sum + i
print(sum) # 10
print("")
# range(od, do, krok)
for cislo in range(3, 15, 2):
print(cislo)
|
4922d04faaf85d49fbe90e385d90633f0e8b4897 | Aasthaengg/IBMdataset | /Python_codes/p02675/s747790578.py | 135 | 3.71875 | 4 | g = str(input())
x = g[-1]
p = ["0", "1", "6", "8"]
if x == "3":
print("bon")
elif x in p:
print("pon")
else:
print("hon")
|
c2fe3d064c23649196b29de76dc664c5b8018193 | lordjuacs/ICC-Trabajos | /Ciclo 1/MRUV/velocidad final2.py | 253 | 3.65625 | 4 | v_inicial = float(input("Ingrese velocidad inicial: "))
aceleracion = float(input("Ingrese aceleracion: "))
distancia = float(input("Ingrese distancia: "))
v_final = ((v_inicial**2)+2*aceleracion*distancia)**(0.5)
print("Velocidad final:",v_final,"m/s") |
812a30a0750240fba4365dc1183c73388c33d612 | Chavi99/set-4 | /8.py | 116 | 3.8125 | 4 | def swap_n(x,y):
x=x^y
y=x^y
x=x^y
print(x,y)
n=list(map(int,input().split(' ')))
swap_n(n[0],n[1])
|
c2845e4ac0ebd952dc3319a2dd1afe379bdbfbc5 | alexangupe/clasesCiclo1 | /P45/Clase10/clasificarEmpleados.py | 3,055 | 4.3125 | 4 | #Requerimiento: Se requiere una función que recoja la información
#de una cantidad determinada de empleados (nombre y salario).
#Se espera recibir el nombre del empleado y el salario del empleado (dólares).
# Retornar cuáles empleados deben pagar impuestos
#(salario superior a 10.000) en una lista. Retornar otra lista que contiene
#toda la nómina ingresada y mostrar en pantalla el salario promedio de los empleados
#registrados. Agregar en el listado de los empleados que pagan impuestos, el valor
#correspondiente (5%)
#Algoritmo:
# 1) Mientras el usuario esté ingresando nómina (quiera continuar):
# 2) Coleccionar el empleado ingresado
# 3) Si el empleado tiene un salario superior a 10.0000
# Agregarlo en el listado de los que pagan impuestos (con los impuestos)
# 4) Calcular el salario promedio
# 5) Mostrarlo en pantalla
# 6) Retornar las listas correspondientes (empleados y empleadosImp)
#Traducción -> Python
def impuestosEmpleados():
#Colecciones
bdEmpleados = list()
#bdEmpleados = []
empleadosImpuestos = list()
#empleadosImpuestos = []
#El usuario está especificando la nómina
continuar = True
while continuar:
# informacionSinFormato = input('Ingrese el nombre y salario (nom salario):')
# infoEmpleado = informacionSinFormato.split(' ')
infoEmpleado = input('Ingrese el nombre y salario (nom salario):').split(' ')
infoEmpleado[-1] = int(infoEmpleado[-1])#Formato numérico al salario
#Coleccionar el empleado
bdEmpleados.append(infoEmpleado)
#Revisar si debe pagar impuestos
#if infoEmpleado[-1] > 10000:
if bdEmpleados[-1][-1] > 10000:
#Colección (lista) empleados que pagan impuestos
#Por referencia
#empleadosImpuestos.append(bdEmpleados[-1])
#Por parámetro
empleadosImpuestos.append(bdEmpleados[-1].copy())
#empleadosImpuestos.append(list(bdEmpleados[-1]))
#Agregar los impuestos en la penúltima posición
empleadosImpuestos[-1].insert( -1, empleadosImpuestos[-1][-1] * 0.05 )
#Criterio de finalización del while indeterminado o loop
if input("Ha terminado el registro? (s)").lower() == 's':
continuar = False
#Calcular el salario promedio general
salarioPromedio = 0
for empleado in bdEmpleados:
salarioPromedio += empleado[-1]
salarioPromedio = salarioPromedio / len(bdEmpleados)
print(f"El slario promedio de la nómina ingresada es {round(salarioPromedio,2)}")
#Retornar los listados solicitados
return bdEmpleados, empleadosImpuestos
#Sección principal
nomina, detalleEmpleadosPagandoImpuesto = impuestosEmpleados()
print('---Nómina completa---')
for i,empleado in enumerate(nomina):
print(f"{i+1}) {empleado}")
print('---Empleados que pagan impuestos---')
for i,empleado in enumerate(detalleEmpleadosPagandoImpuesto):
print(f"{i+1}) {empleado}")
|
991a10f2f37ccfac7670a22fa2ada19a05c1895c | Sahith-8055/XYZ | /CSPP1-ASSIGNMENTS/M10/p1/assignment1.py | 890 | 3.921875 | 4 | '''
Exercise : Assignment-1
implement the function get_available_letters that takes in one parameter
a list of letters, letters_guessed.
'''
def get_available_letters(letters_guessed):
'''
:param letters_guessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
import string
letter_count = dict((key, 0) for key in string.ascii_lowercase)
str_out = ''
for char in letter_count.keys():
if char not in letters_guessed:
str_out = str_out + char
return str_out
def main():
'''
Main function for the given program
'''
user_input = input()
user_input = user_input.split()
data = []
for char in user_input:
data.append(char[0])
print(get_available_letters(data))
if __name__ == "__main__":
main()
|
18f1aeb03c0d397a18607b0b9ce5ba6b2ef4792b | ValtteriV/freetime_Notify | /main/domain/notifications.py | 809 | 3.515625 | 4 | class Notifications:
def __init__(self):
self.notificationlist = []
def add_notification(self, name, timer):
new_notification = Notification(name,timer)
self.notificationlist.append(new_notification)
self.sort_notifications()
print("notification added, timer is {}".format(new_notification.timer))
def sort_notifications(self):
self.notificationlist.sort(key=get_timer)
def next_timer(self):
return self.notificationlist[0].timer if len(self.notificationlist) > 0 else -1
def give_notification(self):
return self.notificationlist.pop(0)
class Notification:
def __init__(self, name, timer):
self.name = name
self.timer = timer
def get_timer(notification):
return notification.timer
|
3f3407d3773c27b348848e34aa27d8adc03fa136 | mayanksha/CS251 | /a3/160392_a3/1.py | 1,891 | 3.625 | 4 | #!/usr/bin/env python3
import re
import sys
import string
minus_flag = 0
values = (string.digits + string.ascii_lowercase)
valid_reg = re.compile('^\-{0,1}[0-9a-zA-Z]+(\.{0,1}[0-9a-zA-Z]+)?$')
def base_n(x, base):
if base == "10" :
base = 10
temp = 0
x = x[::-1]
for i in range(len(x)):
j = values.find(x[i])
if(j >= 10):
sys.exit("Invalid Input!")
t = (j)*(base**(i))
temp += t
# print("Temp = ", temp)
return temp
base = base_n(base, "10")
temp = 0
temp2 = x.split('.')
# print(temp2)
if(len(temp2) == 2):
# print("Decimal found")
x = temp2[1]
for i in range(len(x)):
j = values.find(x[i])
if(j >= base):
sys.exit("Invalid Input!")
t = (j)*(1/(base**(i+1)))
temp += t
# print("Temp = ", temp)
x = temp2[0]
x = x[::-1]
for i in range(len(x)):
j = values.find(x[i])
if(j >= base):
sys.exit("Invalid Input")
t = (j)*(base**(i))
temp += t
# print("Temp = ", temp)
return temp
def validate():
if (len(sys.argv) != 3):
print("Please provide sufficient number of arguments (Two) and re run.")
sys.exit
elif (valid_reg.match(sys.argv[1]) == None):
print("The input is not valid number.")
sys.exit
elif (base_n(sys.argv[2], "10") < 2 or base_n(sys.argv[2], "10") > 36):
print("Base is out of range")
sys.exit
else:
global minus_flag
if(sys.argv[1].find('-') == 0):
minus_flag = 1
sys.argv[1] = sys.argv[1][1:]
sys.argv[1] = sys.argv[1].lower()
print(0 - (base_n(sys.argv[1], sys.argv[2]))) if (minus_flag) else print(base_n(sys.argv[1], sys.argv[2]));
validate()
|
f19afb58e3749fc41f3117c99bab2caab4bb389c | estraviz/codewars | /7_kyu/Finding length of the sequence/length_of_sequence.py | 244 | 3.984375 | 4 | """
Finding length of the sequence
"""
def length_of_sequence(arr, n):
if arr.count(n) != 2:
return 0
else:
gen = (i for i, c in enumerate(arr) if c == n)
first = next(gen)
return next(gen) - first + 1
|
7c6feac6c2deadc353f3a0a9fdce26f09da66417 | onkar2612/Python | /Recurrsion_programs/1_Fibonacci_Using_recurssion.py | 273 | 3.78125 | 4 | def febonacci(n):
if n<=1:
return n
else:
return febonacci(n-1)+febonacci(n-2)
Terms = int(input("Enter a terms: "))
if(Terms<=0):
print("Please enter positive number")
else:
for i in range(Terms):
print(febonacci(i)) |
04476c853ee5351c551ee3313d9e369386aa452b | chelseazhao/Leetcode-for-fun | /61-Rotate-List/Solution.py | 836 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head is None:
return head
hh = head
num = 0
while hh:
num += 1
hh = hh.next
if k >= num:
k %= num
if k == 0:
return head
h = head
pointer = head.next
for i in range(num - k - 1):
h = h.next
pointer = pointer.next
h.next = None
newHead = pointer
while pointer.next:
pointer = pointer.next
pointer.next = head
return newHead
|
19b9054f704d916c6d35b6500919397476111ab2 | paul0920/leetcode | /question_leetcode/215_2.py | 548 | 3.796875 | 4 | # Bubble sort algorithm
# Time complexity: O( k(n - (k+1)/2) ); if k = n, O( n(n-1)/2 )
# Best case: O(n)
# Worst case: O(n^2)
# Space complexity: O(1)
# If j+1 > j, just swap and so on
# nums = [3, 2, 1, 5, 6, 4]
# k = 2
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6]
k = 4
for i in range(k):
for j in range(len(nums) - 1 - i):
print i, j
if nums[j] > nums[j+1]:
print nums
nums[j], nums[j+1] = nums[j+1], nums[j]
print nums
print ""
print "the Kth largest:", nums[len(nums)-k]
|
663d6a372dcd7978a3adeea6f7a6c4a92645931b | azatsatklichov/z-Py | /py3/sahet/g_Join.py | 962 | 3.90625 | 4 |
s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print (s.join( seq ))
seq = ("a", "b", "c"); # This is sequence of strings.
print (s.join( seq))
_str = "this is string example....wow!!!";
print (_str.ljust(50, '0'))
print (_str.rjust(100, '0'))
_str = " this is string example....wow!!! ";
print (_str.rstrip())
_str = "88888888this is string example....wow!!!8888888";
print (_str.rstrip('8'))
_str = " this is string example....wow!!! ";
print (_str.lstrip())
_str = "88888888this is string example....wow!!!8888888";
print (_str.lstrip('8'))
_str = "0000000this is string example....wow!!!0000000";
print (_str.strip( '0' ))
_str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print (_str.splitlines( ))
print (_str.splitlines( 0 ))
print (_str.splitlines( 3 ))
print (_str.splitlines( 4 ))
print (_str.splitlines( 5 ))
_str = "this is string example....wow!!!";
print ("_str.capitalize() : ", _str.upper()) |
6ca11dcc66d2a057caba351c5fb038f22a958c13 | henriquecl/Aprendendo_Python | /Exercícios/Lista 4.1 - Seção 7 - Matrizes/Questão 23 - Elevar matriz ao quadrado.py | 448 | 4.21875 | 4 | """
Questão 23 - Faça um programa que leia uma matriz A de tamanho 3x3 e calcule B = A²
"""
a = [[], [], []]
b = [[], [], []]
for i in range(3):
for j in range(3):
numero = float(input(f'Digite o valor equivalente a posição [{i}][{j}]da primeira matriz '))
a[i].append(numero)
for i1 in range(3):
for j1 in range(3):
numero = a[i1][j1] ** 2
b[i1].append(numero)
for i2 in range(3):
print(b[i2])
|
783536c5b7332f15c52b3a05ce9445903a481c89 | kaminskyalexander/tkinter-jet-fighter | /vector.py | 1,711 | 4.3125 | 4 | from math import sqrt
class Vector2:
"""
Two dimensional vector.
Supports adding, subtracting, multiplying, dividing, comparisons, etc.
"""
def __init__(self, x, y):
self.x = x
self.y = y
@property
def normalized(self):
"""
Normalizes the vector (sets it to a length of 1)
"""
length = sqrt(self.x**2 + self.y**2)
if length == 0: return self
else: return self / length
def normalize(self):
self.x, self.y = self.normalized
@staticmethod
def dot(vector1, vector2):
"""
Finds the dot product of two vectors.
"""
return round(sum(vector1 * vector2), 5)
def __add__(self, other):
if isinstance(other, Vector2):
return Vector2(
self.x + other.x,
self.y + other.y,
)
else:
return Vector2(
self.x + other,
self.y + other,
)
def __sub__(self, other):
if isinstance(other, Vector2):
return Vector2(
self.x - other.x,
self.y - other.y,
)
else:
return Vector2(
self.x - other,
self.y - other,
)
def __mul__(self, other):
if isinstance(other, Vector2):
return Vector2(
self.x * other.x,
self.y * other.y,
)
else:
return Vector2(
self.x * other,
self.y * other,
)
def __truediv__(self, other):
if isinstance(other, Vector2):
return Vector2(
self.x / other.x,
self.y / other.y,
)
else:
return Vector2(
self.x / other,
self.y / other,
)
def __neg__(self):
return self * -1
def __abs__(self):
return Vector2(
abs(self.x),
abs(self.y),
)
def __str__(self):
return "({}, {})".format(self.x, self.y)
def __iter__(self):
return iter((self.x, self.y))
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y) |
b07ebb58dc8af5994581361e262ffc0130b7a535 | amleigh/SI206 | /HW3-StudentCopy/twitterhw3b.py | 907 | 3.671875 | 4 | import tweepy
from textblob import TextBlob
# In this assignment you must do a Twitter search on any term
# of your choice.
# Deliverables:
# 1) Print each tweet
# 2) Print the average subjectivity of the results
# 3) Print the average polarity of the results
# Be prepared to change the search term during demo.
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth)
public_tweets = api.search("friends")
subjectivity=[]
polarity=[]
for tweet in public_tweets:
print(tweet.text)
analysis = TextBlob(tweet.text)
subjectivity.append(analysis.sentiment.subjectivity)
polarity.append(analysis.sentiment.polarity)
print(analysis.sentiment)
sub_av= sum(subjectivity)/len(subjectivity)
pol_av= sum(polarity)/len(polarity)
print("Average subjectivity is " + str(sub_av))
print("Average polarity is " + str(pol_av))
|
3089fc459ced5b4b1c97513f938e50c3376c1ad6 | paulomachadof/lab_metodos | /raiz/newton.py | 1,325 | 3.84375 | 4 | # coding: utf-8
'''
Created on Nov 9, 2015
@author:
'''
from math import *
def newton(f, df, x0, epsilon, maxIter = 50):
"""Executa o método de Newton a para achar o zero de f
com precisão epsilon. O método executa no máximo maxIter
Retorna uma tupla (houveErro, raiz), onde houveErro é booleano.
"""
#Testando se X0 já é raiz
if abs(f(x0)) <= epsilon:
return (False, x0)
print("K\t X\t F(x)")
for k in range(1, maxIter+1):
x1 = x0 - f(x0)/df(x0)
## Mostra valores na tela
print("%d\t %e\t %e"%(k,x1,f(x1)))
## Teste do critério de parada módulo da função
if abs(f(x1)) <= epsilon:
return (False, x1)
x0 = x1
## Se chegar aqui é porque o número máximo de iterações foi atingido
print("O Número máximo de interações foi atingido")
return(True, x1)
if __name__ == "__main__":
def f(x):
return x**3-9*x+3
def df(x):
return 3*x**2-9
x0 = 0.5
epsilon = 0.0001
maxIter = 20
print("Método de Newton-Raphson")
(houveErro, raiz) = newton(f,df,x0,epsilon)
if houveErro:
print("O Método de Newton-Raphson a retornou um erro.")
if raiz is not None:
print("Raiz encontrada: %s"%raiz)
|
5e300c1a4a7a4d88eceebccf1cf90e34205d646c | hessifer/Python | /ProgrammingExpert/method_overloading/dunder_methods/vector_class_test.py | 1,208 | 3.8125 | 4 | import unittest
import math
from vector_class import Vector
class TestProgram(unittest.TestCase):
def test_case_1(self):
self.assertTrue(hasattr(Vector, '__repr__'))
self.assertNotEqual(repr(Vector(1, 2)), repr(Vector(2, 1)))
self.assertNotEqual(repr(Vector(1, 2)), repr(Vector(1, 3)))
self.assertEqual(repr(Vector(1, 2)), repr(Vector(1, 2)))
def test_case_2(self):
self.assertTrue(hasattr(Vector, '__eq__'))
self.assertNotEqual(Vector(1, 2), Vector(2, 1))
self.assertNotEqual(Vector(1, 2), Vector(1, 3))
self.assertEqual(Vector(1, 2), Vector(1, 2))
def test_case_3(self):
self.assertTrue(hasattr(Vector, '__add__'))
v1 = Vector(4, 5)
v2 = Vector(1, 2)
self.assertEqual(Vector(5, 7), (v1 + v2))
def test_case_4(self):
self.assertTrue(hasattr(Vector, '__sub__'))
v1 = Vector(4, 5)
v2 = Vector(1, 2)
self.assertEqual(Vector(3, 3), (v1 - v2))
def test_case_5(self):
self.assertTrue(hasattr(Vector, '__mul__'))
v1 = Vector(3, 4)
v2 = Vector(2, 7)
self.assertEqual(34, v1 * v2)
if __name__ == "__main__":
unittest.main()
|
23723f1611f05855133747fb62caae21b94827de | caim03/PythonEcm | /Curve.py | 1,397 | 4.40625 | 4 | """ This class defines an elliptic curve """
from random import randint
class Curve:
""" This method is the constructor of the Curve class
@:param n The number that must be factorized
@:return Nothing
"""
def __init__(self, n, point):
self.a = randint(0, n - 1)
self.b = (point.get_y()**2 - point.get_x()**3 - (self.a * point.get_x())) % n
self.delta = ((4 * (self.a**3)) + (27 * (self.b**2))) % n
""" This method is the getter for a coefficient variable
@:param Nothing
@:return a Return the a coefficient of the curve
"""
def get_a(self):
return self.a
""" This method is the getter for b coefficient variable
@:param Nothing
@:return a Return the b coefficient of the curve
"""
def get_b(self):
return self.b
""" This method is the getter for delta discriminant variable
@:param Nothing
@:return a Return the delta discriminant of the curve
"""
def get_delta(self):
return self.delta
""" This method represents the curve class as a string to improve readability
@:param Nothing
@:return Nothing
"""
def to_string(self):
print "Elliptic curve: Y^2 = X^3 + aX + b"
print "a = " + self.a.__str__()
print "b = " + self.b.__str__()
print "delta = " + self.delta.__str__()
|
e6dfc2042be615951a190fc57dcd1fadd15dfdb7 | grizzly-ops/python-crash-corse | /chap02/TryItOut.py | 775 | 4.03125 | 4 | #2.1
message = "hi human"
print (message)
#2.2
message = "hello mars"
print (message)
#2.3
name = "jhon"
message = f"hello, {name} would you like to go to the movies"
print (message)
#2.4
name = "ruth"
print (name.title())
print (name.upper())
print (name.lower())
#2.5
message = f'albert instine once said "a person who never made a mistake never tried anything new"'
print (message)
#2.6
famous_person = "albert instine"
message = f'{famous_person.title()} once said"a person who never made a mistake never tried anything new"'
print (message)
#2.7
name = "\tjames\t"
print (name)
print (name.rstrip())
print (name.lstrip())
print (name.strip())
#2.8
print (5+3)
print (10-2)
print (2*4)
print (64/8)
#2.9
favorit_number = "12"
message = f"{favorit_number}"
print (message)
#2.10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.