blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
74affd066024bc1bdd0f6f693349f533136b9e12 | Harman-12/Data-Analysis-c107 | /data-analysis.py | 293 | 3.546875 | 4 | import pandas as pd
import csv
import plotly.express as px
df = pd.read_csv("data-student vs level.csv")
mean = df.groupby(["student_id", "level"], as_index = False)["attempt"].mean()
fig = px.scatter(data_frame=mean, x="student_id", y="level", size="attempt", color="attempt")
fig.show() |
ddb22db291456440e84ca30fcb7bd75fce147f02 | ndombrowski20/work_in_progress | /ANNs/scrap/cleaning_data.py | 3,963 | 3.96875 | 4 | import csv
import os
# first we need to be able to tell if a list is a proper week
def check_week(a_list):
# first, cause i'm paranoid
if len(a_list) != 6:
raise Exception("It's monday to monday bruh")
# so first, we grab the number of the date which is the last value. This means we're limiting ourselves to
# sequential data, which is kinda alright.
init = str(a_list[0])[-1]
# was the length of the list
# now changed to 6 so it checks the first 5 days, and then asks if the next one in the list is 2 days more.
# i.e. whether the next day in the list is the next monday after our friday
for i in range(5):
current = str(a_list[i])[-1]
if int(current) != int(init)+ i:
return False
if int(init) + 7 >= 10:
new = int(init) + 7 - 10
if new != a_list[5]:
return False
elif int(init) + 7 != int(str(a_list[5])[-1]):
return False
return True
# next, we try to see if we can find proper weeks within a list of dates
def find_week(a_list, init):
# next five days
# nfd = []
# now next 6 days for the monday too
nsd = []
for i in range(6):
nsd.append(a_list[init + i])
return nsd
# now we can simply find the dates from a datasheet and feed them to the previous functions
def find_dates_sheet(a_str):
with open(a_str, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
date_sheet = []
days = []
for row in reader:
date_sheet.append(row["Date"])
for i in range(len(date_sheet)-6):
nfd = find_week(date_sheet, i)
if check_week(nfd):
days += nfd
i += 6
return days
# now we write the data to a new place, so that we can copy/export it later
def create_data(a_str, days_list):
with open(a_str, newline='') as csvfile:
data = []
reader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
for row in reader:
if row['Date'] in days_list:
data.append(row)
return data
# now we sort the data in a way that makes sense for the program, obtaining both our x and y data
def sorting_data(data_list):
big_list = []
for i in range(int(len(data_list) / 6)):
data = []
data.clear()
for j in range(5):
data.append(data_list[i+j]["Volume"])
data.append(data_list[i+j]["High"])
data.append(data_list[i+j]["Low"])
data.append(data_list[i+j]["Open"])
data.append(data_list[i+j]["Close"])
final = data_list[i+5]["Close"]
friday = data[-1]
y = float(final) - float(friday)
data.append(y)
big_list.append(data)
return big_list
# now that we can produce data from a sheet, we can take
def complete_automation(location_str, filename_list):
mondo_data = []
date_list = []
new_data = []
for name in filename_list:
filename = location_str + name
date_list.clear()
new_data.clear()
print(filename)
date_list = find_dates_sheet(filename)
new_data = create_data(filename, date_list)
new_sorted = sorting_data(new_data)
mondo_data += new_sorted
return mondo_data
# specifically for running this script in a certain folder so that we can get the data
# with open('filenames.txt', newline='') as csvfile:
# reader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
# files = []
# for row in reader:
# files.append(row['name'])
complete_data = complete_automation("", ['a.us.txt', 'aa.us.txt'])
with open('data_full.csv', 'w', newline='') as csvfile:
datawriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for item in complete_data:
print(item)
datawriter.writerow(item) |
3d740557102dfab6aecc79cc58d3c41bd5aa4b08 | MEENUVIJAYAN/python | /python lab 5/name.py | 133 | 4.1875 | 4 | #Python program to print full name
a = str(input("Enter First Name:"))
b = str(input("Enter Second Name:"))
print(a + " " + b)
|
c55369455aa0cbee81b335757eb7b26ead4b225f | LezardWhiteGlint/Practice_backup | /Data filter.py | 723 | 3.859375 | 4 | def listgenerator():
import random
global listbefore
listbefore = []
for i in range(0,10):
num = random.randint(1,100)
listbefore = listbefore + [num]
print('It is the initial list')
print(str(listbefore))
def list_filter():
global listafterbig
global listaftersmall
listafterbig = []
listaftersmall = []
for num in range(len(listbefore)):
if listbefore[num] > 50:
listafterbig = listafterbig + [listbefore[num]]
else:
listaftersmall = listaftersmall + [listbefore[num]]
listgenerator()
list_filter()
print('numbers larger than 50')
print(listafterbig)
print('numbers lesser or equal to 50')
print(listaftersmall)
|
6ed3fd01f6c975af06047f48223e103737b61b64 | TechInTech/pCode | /pNode/node.py | 3,003 | 3.734375 | 4 | #!/usr/bin/python3
#-*- coding:utf-8 -*-
"""
File: node.py
Description: This file defines the class node
Author: Larry Yu
Initial Data: Oct 28th, 2018
"""
import sys
sys.path.append("/cygdrive/d/pCode")
class Node(object):
def __init__(self, data, next):
self._data = data
self._next = next
def setNext(self, next):
self._next = next
def setData(self, data):
self._data = data
def getNext(self):
return self._next
def getData(self):
return self._data
def generateLinkedNodeList(size, initialValue = None):
head = None
if(size > 0):
for _ in range(size):
head = Node(initialValue, head)
return head
def getLinkedList(head):
"""
Input: 1. head: the referece to the first node in list
Output: The list which contains all elements in linked list
"""
lst = []
currentNode = head
while(None != currentNode):
lst.append(str(currentNode.getData()))
currentNode = currentNode.getNext()
return lst
def findElement(lst, itemToFind):
index = 0
if(lst and itemToFind):
currentNode = lst
while(None != currentNode):
if(itemToFind == currentNode.getData()):
return index
else:
currentNode = currentNode.getNext()
index += 1
return -1
def addNodeIntoList(lst, size, InitialValue = None):
"""
To add more nodes into designated list
Input: 1.head: The head of the list
2.size: How many nodes to add
3.initialValue: The initial value of nodes
Output:1. The head of the list
"""
if(type(int) == type(size) and size >= 0):
pass
def removeNode(lst, elementToRemove):
"""
Precondition: The element is in list
"""
head = lst
if(None != lst):
#If the first head is the element to remove
if(elementToRemove == head.getData()):
head = head.getNext()
return(True, head)
else:
currentNode = lst
while(currentNode.getNext() != None):
if(currentNode.getNext().getData() == elementToRemove):
currentNode.setNext(currentNode.getNext().getNext())
return(True, lst)
currentNode = currentNode.getNext()
return(False, None)
def test():
#lst = generateLinkedNodeList(3, 1024)
#print(getLinkedList(lst))
#(result, lst) = removeNode(lst, 1024)
#if(result):
# print(getLinkedList(lst))
#(result, lst) = removeNode(lst, 1024)
#if(result):
# print(getLinkedList(lst))
#(result, lst) = removeNode(lst, 1024)
#if(result):
# print(getLinkedList(lst))
head = None
for index in range(3):
head = Node(index, head)
print(getLinkedList(head))
(result, lst) = removeNode(head, 0)
if(result):
print(getLinkedList(lst))
def main():
test()
if "__main__" == __name__:
main() |
acf9e1e7ce17f77252fd7133164ad7865eaf5e6b | JenZhen/LC | /lc_ladder/Basic_Algo/graph-bfs-dfs/BFS/Rotting_Oranges.py | 2,294 | 3.578125 | 4 | #! /usr/local/bin/python3
# https://leetcode.com/problems/rotting-oranges/submissions/
# Example
# In a given grid, each cell can have one of three values:
#
# the value 0 representing an empty cell;
# the value 1 representing a fresh orange;
# the value 2 representing a rotten orange.
# Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
#
# Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
# Example 1:
#
# Input: [[2,1,1],[1,1,0],[0,1,1]]
# Output: 4
# Example 2:
#
# Input: [[2,1,1],[0,1,1],[1,0,1]]
# Output: -1
# Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
# Example 3:
#
# Input: [[0,2]]
# Output: 0
# Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
#
# Note:
#
# 1 <= grid.length <= 10
# 1 <= grid[0].length <= 10
# grid[i][j] is only 0, 1, or 2.
"""
Algo: BFS 数层
D.S.:
Solution:
注意 Corner cases:
- 有剩余橘子
- 一开始就没有橘子
"""
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
if self.count_of_fresh(grid) == 0:
return 0
row, col = len(grid), len(grid[0])
q = collections.deque([])
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
for i in range(row):
for j in range(col):
if grid[i][j] == 2:
q.append((i, j, 0))
res = 0
while q:
(x, y, step) = q.popleft()
res = max(res, step)
for dx, dy in dirs:
nx, ny = x + dx, y + dy
if 0 <= nx < row and 0 <= ny < col:
if grid[nx][ny] == 1:
q.append((nx, ny, step + 1))
grid[nx][ny] = -1
if self.count_of_fresh(grid) != 0:
return -1
return res
def count_of_fresh(self, grid):
row, col = len(grid), len(grid[0])
cnt = 0
for i in range(row):
for j in range(col):
if grid[i][j] == 1:
cnt += 1
return cnt
# Test Cases
if __name__ == "__main__":
solution = Solution()
|
647c67ab8b03599efa9799a026566703546f66a9 | arindam-1521/moree | /this.py | 221 | 3.515625 | 4 | print("Hello world")
# This is a very basic code which shows how to print a statemnet in python.
print("Hello world")
print("Git hub is available")
print("GitHub is available")
print("This is a new and most usable stuff") |
729da2e49337117daa721f9551771a108c1af489 | luis-manuel352/AvancePIA-Programacion | /main.py | 1,001 | 3.796875 | 4 | # Acceso de datos a la clase Contacto
import re
# Validador de expresiones regulares
def RegEx(_txt,_regex):
coincidencia=re.match(_regex, _txt)
return bool(coincidencia)
# Expresiones regulares para cada campo.
telefonoRegEx="^[0-9]{10}$"
nombreRegEx=""
entidadValida=True
# Pregunta de teléfono que sea de 10 caracteres.
_telefono=""
telefono=0
datoValido=False
while True:
_telefono=input("Teléfono:")
if RegEx(_telefono,telefonoRegEx):
telefono=int(_telefono)
datoValido=True
break
else:
print("Se requieren 10 dígitos como número")
datoValido=False
entidadValida=(entidadValida & datoValido)
# Tendras que ingresar tu nombre.
nombre=""
datoValido=False
while True:
nombre=input("Nombre:")
if RegEx(nombre,telefonoRegEx):
datoValido=True
break
else:
print("Se requiere nombre, apellido, no mayor a 30 catacteresLi.")
datoValido=False
entidadValida=(entidadValida & datoValido) |
dcf098eb229e805a41eb677416d57931ff383037 | ZenithClown/decompose | /pca.py | 2,503 | 3.96875 | 4 | # -*- encoding: utf-8 -*-
import numpy as np
class PCA(object):
"""Dimension Reduction using Principal Component Analysis (PCA)
It is the procces of computing principal components which explains the
maximum variation of the dataset using fewer components.
:type n_components: int, optional
:param n_components: Number of components to consider, if not set then
`n_components = min(n_samples, n_features)`, where
`n_samples` is the number of samples, and
`n_features` is the number of features (i.e.,
dimension of the dataset).
:Attributes:
:type covariance_: np.ndarray
:param covariance_: Coviarance Matrix
:type eig_vals_: np.ndarray
:param eig_vals_: Calculated Eigen Values
:type eig_vecs_: np.ndarray
:param eig_vecs_: Calculated Eigen Vectors
:type explained_variance_: np.ndarray
:param explained_variance_: Explained Variance of Each Principal Components
:type cum_explained_variance_: np.ndarray
:param cum_explained_variance_: Cumulative Explained Variables
"""
def __init__(self, n_components : int = None):
"""Default Constructor for Initialization"""
self.n_components = n_components
def fit_transform(self, X : np.ndarray, **kwargs):
"""
Fit the PCA algorithm into the Dataset
The input data is a n-dimensional vector of shape
`(<records>, <features>)` and the function transforms the
vector using the principles of PCA.
"""
verbose = kwargs.get("verbose", True)
if not self.n_components:
self.n_components = min(X.shape)
self.covariance_ = np.cov(X.T)
# calculate eigens
self.eig_vals_, self.eig_vecs_ = np.linalg.eig(self.covariance_)
# self.eig_pairs_ = [(np.abs(self.eig_vals_[i]), self.eig_vecs_[:, i]) for i in range(len(self.eig_vals_))]
# explained variance
_tot_eig_vals = sum(self.eig_vals_)
self.explained_variance_ = np.array([(i / _tot_eig_vals) * 100 for i in sorted(self.eig_vals_, reverse = True)])
self.cum_explained_variance_ = np.cumsum(self.explained_variance_)
# define `W` as `d x k`-dimension
self.W_ = self.eig_vecs_[:, :self.n_components]
if verbose:
# print the data shape to console when true
print(X.shape, self.W_.shape)
return X.dot(self.W_)
|
0e91628c903662971299334a6b88e3f524e1f9a7 | vedangmehta/Algorithms | /dp/longest_subsequence.py | 861 | 3.78125 | 4 | def longest_seq(seq):
""" returns the longest increasing subseqence
in a sequence """
count = [1] * len(seq)
prev = [0] * len(seq)
for i in range(1, len(seq)):
dist = []
temp_prev = {}
for j in range(i):
if seq[j] < seq[i]:
dist.append(count[j])
temp_prev[count[j]] = j
else:
temp_prev[0] = j
dist.append(0)
count[i] = 1 + max(dist)
prev[i] = temp_prev[max(dist)]
# path
path = [seq[prev.index(max(prev))]]
i = prev.index(max(prev))
while i>1:
path.append(seq[prev[i]])
i = prev[i]
return max(count), path[::-1]
if __name__ == "__main__":
seq = [5, 2, 8, 10, 3, 6, 9, 7]
seq2 = [0, 8, 3, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
print longest_seq(seq2)
|
d2635bd663319cb4415afd3c414db0b1cd4b2f7e | JHuraibi/Python_Assignment_02 | /Question_01.py | 9,591 | 4.09375 | 4 | # Author: Jamal Huraibi, fh1328
# Assignment 2
# Question 1
# Python sorted() Doc: docs.python.org/3/library/functions.html#sorted
import statistics # For .median() and .stddev()
# ----| Functions |--------------------------------------------------------------------------------------------------- #
def write_student_info_to_file(all_students):
"""Writes formatted student information to (file: 'output.txt') """
file = open("output.txt", "w") # (Open) or (Create + Open) "output.txt"
student_num = 1 # Used for numbering the output
file.write("******************\n") # Write section header
file.write(" Students Records \n")
file.write("******************\n")
for student in all_students:
first_name = student[0] # Intermediate var's for ease of reading
last_name = student[1]
average_score = student[2]
high_score = student[3]
low_score = student[4]
letter_grade = student[5]
file.write("{}) {} {}\n".format(student_num, first_name, last_name)) # Write all the student's info
file.write("Average Score: {}\n".format(average_score))
file.write("Highest Score: {}\n".format(high_score))
file.write("Lowest Score: {}\n".format(low_score))
file.write("Letter grade earned: {}\n".format(letter_grade))
file.write("\n") # Write extra space
student_num = student_num + 1 # Increment the numbering
def write_class_stats_to_file(all_students):
"""Writes formatted class information to (preexisting file: 'output.txt') """
file = open("output.txt", "a") # Open "output.txt", in append mode
num_of_students = len(all_students)
class_average = calculate_class_average(all_students)
median_gpa = calculate_median_gpa(all_students)
std_dev_gpa = calculate_std_dev_gpa(all_students)
file.write("******************\n") # Write section header
file.write(" Class Statistics \n")
file.write("******************\n")
file.write("Number of students: {}\n".format(num_of_students))
file.write("Class Average: {}\n".format(class_average))
file.write("Median GPA: {}\n".format(median_gpa))
file.write("Standard deviation: {}\n".format(std_dev_gpa))
def process_raw_line(line_to_process):
"""Removes colon and commas from provided string. Delimits by SPACE and returns as List."""
# Check if time: Why does replace() work here but not strip() for colon and commas?
processed_line = line_to_process # "line_to_process" is immutable
processed_line = processed_line.replace(':', '') # Remove the colon (':')
processed_line = processed_line.replace(',', '') # Remove the commas (',')
processed_line = processed_line.strip() # Remove trailing artifacts (if exist)
return processed_line.split() # Return as list of individual words
def find_high_score(all_scores):
"""Returns highest score of provided list"""
high_score = 0.0 # Set initial value
for score in all_scores:
if float(score) > high_score: # Loop value more than current most?
high_score = float(score)
return high_score # Return highest score found
def find_low_score(all_scores):
"""Returns lowest score of provided list"""
low_score = 100.0 # Set initial value
for score in all_scores:
if float(score) < low_score: # Loop value less than current least?
low_score = float(score)
return low_score # Return lowest score found
def calculate_average_score(all_scores):
"""Returns average score of provided List"""
scores_subtotal = 0.0
num_of_scores = len(all_scores)
for score_value in all_scores:
scores_subtotal += float(score_value) # Sum all the student's scores
return scores_subtotal / num_of_scores # Divide sum by num of scores and return
def convert_to_letter_grade(score):
"""Returns the letter grade for (score: float)"""
if score >= 90.0:
return 'A'
elif score >= 80.0:
return 'B'
elif score >= 70.0:
return 'C'
elif score >= 60.0:
return 'D'
elif score >= 50.0:
return 'E'
else:
return 'F'
def calculate_class_average(class_students):
"""Returns average score of entire class (all students)"""
subtotal_score = 0
num_of_students = len(class_students)
for student in class_students:
student_avg_score = student[2]
subtotal_score += student_avg_score # Sum the avg. score of each student
average_class_score = subtotal_score / num_of_students # Divide sum by class size and return
return "%.2f" % average_class_score # Return formatted to 2 decimal places
def calculate_median_gpa(class_students):
"""Returns median score of entire class (all students)"""
scores = []
for student in class_students:
scores.append(student[2]) # Build a list of all student's scores
return "%.1f" % statistics.median(scores) # Execute Python's built-in median func.
def calculate_std_dev_gpa(class_students):
"""Returns the standard deviation of entire class' avg scores (all students)"""
scores = []
for student in class_students:
scores.append(student[2]) # Build a list of all student's scores
return "%.3f" % statistics.stdev(scores) # Execute Python's built-in stddev func.
def extract_student_information(data):
"""Returns a List of all the student's information extracted from the string"""
student_information = []
first_name = data[0]
last_name = data[1]
scores = extract_student_scores(data[2:]) # Remaining values should only be scores
average_score = calculate_average_score(scores)
high_score = find_high_score(scores)
low_score = find_low_score(scores)
letter_grade = convert_to_letter_grade(average_score)
student_information.append(first_name) # Build the List
student_information.append(last_name)
student_information.append(average_score)
student_information.append(high_score)
student_information.append(low_score)
student_information.append(letter_grade)
return student_information # Return built List of student's info
def extract_student_scores(data):
"""Returns a List of the student's scores. "data" should only be scores.
Checks if each item in data is a number or not also. Appends to "scores" if it is."""
scores = []
for value in data:
try:
float(value)
scores.append(value) # Append the number to the List scores
except ValueError:
print("[INFO]: Non-number value encountered. Offender: {}\n" # If float cast fails then not a number
.format(value))
return scores # Return the built list of scores
# ----| main |-------------------------------------------------------------------------------------------------------- #
if __name__ == '__main__':
students = [] # List of students (will be 2D later)
fileInStream = open("input.txt", 'r') # Open the in-stream file in read mode
for line in fileInStream:
currentLine = process_raw_line(line) # Remove unwanted characters
studentInfo = extract_student_information(currentLine) # Build the list of info
students.append(studentInfo) # Assign the sublist to current index
# Student GPA's: gpa[2] == students[n][2]
students = sorted(students, key=lambda gpa: gpa[2], reverse=True) # Sort the list by GPA, descending
write_student_info_to_file(students) # Write each student's info to file
write_class_stats_to_file(students) # Write class statistics to file
fileInStream.close() # Close the stream
|
abefb67e9a24b4986a174d72fedaefb778e5ac7e | coditza/craps | /fizzbuzz.py | 329 | 3.671875 | 4 | def multi(max, mapping, separator):
result = []
for i in range(1, max + 1):
fbzz = ''.join([mapping[x] for x in mapping if i % x == 0])
result.append(fbzz if len(fbzz) else str(i))
return separator.join(result)
if __name__ == '__main__':
print("USAGE: multi(max, mapping, separator) -> string")
|
c41487fe36c4664f2f3dfc04e40db46f218b5755 | JennyHWAN/box-paradox | /box paradox model.py | 2,230 | 4.59375 | 5 | '''
Bertand's Box Paradox: A Simulation
Version 0.3
further info: https://en.wikipedia.org/wiki/Bertrand%27s_box_paradox
'''
import random
goldright = 0
golddraw = 0
silverright = 0
silverdraw = 0
n = 0
print('''
This model will simulate Bertrand's Box Paradox in the following way:
It will randomly select one of the three boxes and draw a coin from the box.
Then it simulates a guess of the remaining coin in the box by guessing the same color of the coin it just drew.
The final accuracy displayed after the simulation is over proves the correct interpretation of the paradox.\n''')
numsims = int(input('How many times to run the simulation?\n'))
def goldbox():
print('You have drawn a gold coin.\nSo your guess will be gold.')
print('You were right!')
global goldright
goldright += 1
global golddraw
golddraw += 1
def silverbox():
print('You have drawn a silver coin.\nSo your guess will be silver.')
print('You were right!')
global silverright
silverright += 1
global silverdraw
silverdraw += 1
def diffbox():
coindraw = random.choice(['gold', 'silver'])
print('You have drawn a ', coindraw, ' coin.\nSo your guess will be ', coindraw, '.', sep='')
if coindraw == 'gold': # You drew a gold coin, so you've guessed gold.
global golddraw
golddraw += 1
print('You were wrong :(') # But it can't be the gold coin, since the only remaining coin in the box would be the silver coin.
if coindraw == 'silver':
global silverdraw
silverdraw += 1
print('You were wrong :(')
while n < numsims:
box = random.choice(['box SS', 'box SG', 'box GG'])
print(box)
if box == 'box SS':
silverbox()
if box == 'box GG':
goldbox()
if box == 'box SG':
diffbox()
print()
n += 1
print('When you drew a gold coin this was your chance of having drawn another gold coin:\n', ((goldright / golddraw) * 100), '%')
print('When you drew a silver coin this was your chance of having drawn another silver coin:\n', ((silverright / silverdraw) * 100), '%')
print('Your overall accuracy was', (((goldright + silverright) / n) * 100), '%')
input('Thanks for playing! Press Enter to exit...')
|
5dbfa6abe1e6a724afa6ea02acbaba24131f2bb1 | LauritsStokholm/EksFysII | /ex4/Data/dataconverter.py | 706 | 3.609375 | 4 | # # # # # # # # Part 0 ~ Converting csv into good format # # # # # # # # # # #
""" BEWARE: ONLY RUN THIS ONCE!
This file is created to change csv formatting """
for item in data_dir:
# Read only
with open(item, "r") as file:
my_file = file.read()
my_file = my_file.replace(',', '.') # Changing decimal to american
my_file = my_file.replace('\t', ',') # Changing delimiter to commas
my_file = my_file.replace(';', ',') # Changing delimiter to commas
my_file = my_file.replace(' ', '') # Removing spaces
my_file = my_file.replace(',', ', ') # Adding readable spaces
# Write only
with open(item, "w") as file:
file.write(my_file)
|
e8e731c0586e124974c802cf7f774dea242a7d26 | zywh/waterlooccc | /2016/Junior/p5.py | 524 | 3.53125 | 4 | vInput=['1','3','5 1 4','6 2 4']
vInput=['2','3','5 1 4','6 2 4']
#vInput=['2','5','202 177 189 589 102','17 78 1 496 540']
vQuestion=vInput[0]
vCount = int(vInput[1])
vList1 = [int(x) for x in vInput[2].split()]
vList2 = [int(x) for x in vInput[3].split()]
vList1.sort()
if ( vQuestion == '1'):
vList2.sort()
else:
vList2.sort(reverse=True)
print(vList1,vList2)
totalSpeed=0
for i in range(vCount):
totalSpeed = totalSpeed + max(vList2[i],vList1[i])
print("pair:",max(vList2[i],vList1[i]),totalSpeed) |
c0ad7ed37947fa684d9993461b8589200a3df729 | Nafani4/Home_work | /Calendar/calendar_modules/lesson-07.py | 1,916 | 3.8125 | 4 | """
SQL - Standart Query Language
- DDL - Data Definition Language
(CREATE TABLE)
- DML - Data Manipulation Language
(SELECT, INSERT, UPDATE, DELETE)
СУБД - Система управления базами данных
Primary Key (Первичный ключ)
Уникальный идентификатор
Может быть int, может быть str
Может быть составной (суррогатный)
Foreign Key (Внешний ключ)
Алгоритм работы с БД:
1. Установка соединения .connect()
2. Создание объекта курсора conn.cursor()
3. Выполнение SQL-запроса(ов) cursor.execute()
4. Если запрос изменяет данные/структуру
4.1 зафиксировать изменения conn.commit()
4. Если запрос на выборку (получение) данных
4.1 разобрать данные (fetch*)
"""
# SQLite3
import sqlite3
# conn = sqlite3.connect(':memory:')
conn = sqlite3.connect('users.sqlite')
cursor = conn.cursor()
sql = """
CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
firstname TEXT NOT NULL,
lastname TEXT NOT NULL,
created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""
cursor.execute(sql)
conn.commit()
sql = """
INSERT INTO user (
firstname, lastname
) VALUES (
?, ?
)
"""
cursor.execute(sql, ('Вася', 'Пупкин'))
conn.commit()
sql = """
SELECT
id, firstname, lastname, created
FROM
user
"""
cursor.execute(sql)
users = cursor.fetchall()
print(users)
conn.close()
# Используя контекстный мендежер
# все можно сократить
with sqlite3.connect('users.sqlite') as conn:
cursor = conn.execute(sql)
users = cursor.fetchall()
print(users)
|
05aee30f1c578b9daac23be19fec53646e641131 | Richardmb89/Python-101 | /One Array a Rotation of Another.py | 1,168 | 4.0625 | 4 | # Implement your function below.
def is_rotation(list1, list2):
if len(list1) != len(list2) or len(list2) == 0:
return False
if not set(list1) <= set(list2) and not set(list1) >= set(list2):
return False
index = 0
while list1[0] != list2[index]:
index+=1
list2 = list2[index:] + list2[:index]
index = 0
for i in list1:
if i != list2[index]:
return False
index +=1
return True
# NOTE: The following input values will be used for testing your solution.
list1 = [1, 2, 3, 4, 5, 6, 7]
list2a = [4, 5, 6, 7, 8, 1, 2, 3]
# is_rotation(list1, list2a) should return False.
list2b = [4, 5, 6, 7, 1, 2, 3]
# is_rotation(list1, list2b) should return True.
list2c = [4, 5, 6, 9, 1, 2, 3]
# is_rotation(list1, list2c) should return False.
list2d = [4, 6, 5, 7, 1, 2, 3]
# is_rotation(list1, list2d) should return False.
list2e = [4, 5, 6, 7, 0, 2, 3]
# is_rotation(list1, list2e) should return False.
list2f = [1, 2, 3, 4, 5, 6, 7]
# is_rotation(list1, list2f) should return True.
list2g = [7, 1, 2, 3, 4, 5, 6]
# is_rotation(list1, list2g) should return True.
|
cb4c0afffa1b47f2bd03a8e89830cb9702057724 | HIRO-group/roboskin | /roboskin/calibration/convert_to_lowertriangular_matrix.py | 12,714 | 3.90625 | 4 | """
This is a python file containing a test case and a class to convert any matrix which is convertible Lower Triangular(LT)
Matrix to Lower Triangular Matrix
Algorithm:
*) As this is a binary matrix, and also lower triangular, the total sum of elements should be at max n(n+1)/2, else it
can't be a LT matrix
*) There can only be one reference segment, hence only one zero row array, else the algorithm will throw an exception
*) You are only allowed to switch rows and columns to get the LT matrix
Custom Sort Row:
*) Arrange the rows in ascending order of number of ones present in the row
*) If there is a tie in number of ones, then you assume the row as a binary number, with MSB at first and then the
number you get, convert it to a floating point number and add it to the row sum. This mainly signifies as a weight
value to the row sum which are same, so that argsort can give preference. Finally the row sum is arranged in
ascending order
Custom Sort Column:
*) Arrange the columns in the descending order of number of ones in the column
*) *) Arrange the rows in ascending order of number of ones present in the row
*) If there is a tie in number of ones, then you assume the row as a binary number, with MSB at first and then the
number you get, convert it to a floating point number and add it to the row sum. This mainly signifies as a weight
value to the row sum which are same, so that argsort can give preference. Finally the row sum is arranged in
descending order
# TODO: Next PR, I will add more examples of why this approach is correct. I derived some in my IPad
"""
import math
import numpy as np
class ConvertToLT:
"""
This is a class to convert LT convertible matrix to LT matrix
"""
def __init__(self, input_matrix):
"""
Initialize the class and start the main algorithm
Parameters
----------
input_matrix : np.ndarray
the input matrix passed into the class, to convert it to LT matrix
"""
self.input_matrix = input_matrix
self.zero_array_index = []
self.rows = []
self.columns = []
self.main_algorithm()
def _is_there_only_one_zero_array(self):
"""
This function will check if there is only one zero array in the passed matrix. If there are more, it will
throw an exception
"""
# There can be only one zero row in the activity matrix. More info in the exception string
self.zero_array_index = []
# Remove the nd arrays which are zero arrays for now, we can add them back later
for index, each_array in enumerate(self.input_matrix):
if self.find_zero_ndarray(each_array):
self.input_matrix = np.delete(self.input_matrix, index, 0)
self.zero_array_index.append(index)
if len(self.zero_array_index) != 1:
raise Exception("More than one row is a zero row. According to the paper there can be only one reference "
"zero row array, so Activity matrix might be wrong")
def main_algorithm(self):
"""
This is the main algorithm implementation. The algorithm details are at the top of the file.
Returns
-------
None
"""
self._is_there_only_one_zero_array()
# After removing the zero arrays the residue matrix should be a square matrix, be mindful of that
self.is_matrix_lt_convertible(self.input_matrix)
self.input_matrix = self.sort_rows_in_ascending_order(self.input_matrix)
self.input_matrix = self.sort_columns_in_descending_order(self.input_matrix)
# Check if output matrix is an LT matrix
self.is_lower_triangular = self.is_lower_triangular_fn(self.input_matrix)
# The row numbers need to be changed as we removed zero array at the start
self._arrange_row_column_numbers()
# Finally we add zero array at the start of the array
self._append_zero_array_at_start()
# I know I can just return the input matrix, but for the sanity of people who will be using my algorithm in the
# future I am writing this extra line
self.final_matrix = self.input_matrix
# Saving the reference segment number to a variable
self.reference_segment_accelerometer = self.zero_array_index[0] + 1
def _arrange_row_column_numbers(self):
"""
When we remove the zero row array, and then do shuffling of rows and columns, we finally need where our original
row and column were shuffled to, to get the LT matrix. Issue is that as the zero row array can be somewhere in
between we have to change the row numbers of some rows. That algorithm is explained in more detailed in my blog
https://krishnachaitanya9.github.io/posts/lower_triangular_algorithm_problem/
This is just an implementation of that algorithm
"""
self.rows += np.array((self.rows - self.zero_array_index[0] + 1) > 0).astype(int) + 1
# Finally Increment the column number
self.columns += 1
def _append_zero_array_at_start(self):
for _ in range(len(self.zero_array_index)):
self.input_matrix = np.insert(self.input_matrix, 0, 0, axis=0)
def numpyarray_toint(self, my_array, reverse):
"""
This function will convert a numpy 1D array which is considered a binary number into a decimal number
Parameters
----------
my_array : np.ndarray
Input array
reverse : bool
if reverse MSB is considered first, else last
Returns
-------
int
Decimal number
"""
if reverse:
my_array = my_array[::-1]
return my_array.dot(2 ** np.arange(my_array.size)[::-1])
def convert_to_floating_point(self, my_number):
"""
This method is used to convert some number like 768 to 0.768. Basically used to add weight value
Parameters
----------
my_number : int
Input Number
Returns
-------
float
floating point number from the input number
"""
return my_number / math.pow(10, len(str(my_number)))
def sort_rows_in_ascending_order(self, input_array):
"""
Sort rows of input matrix. Algorithm at the top.
References:
# Stackoverflow links: https://stackoverflow.com/questions/52216526/sort-array-columns-based-upon-sum/52216674
# https://stackoverflow.com/questions/7235785/sorting-numpy-array-according-to-the-sum
Parameters
----------
input_array : np.ndarray
the input array we pass into the function, for it to have it's rows sorted
Returns
-------
np.ndarray
The array with its rows sorted
"""
# So each row has to be unique for us to convert to Lower triangular Matrix
row_sum = np.sum(input_array, axis=1, dtype=np.float)
row_sum_unique, counts = np.unique(row_sum, return_counts=True)
duplicates = row_sum_unique[counts > 1]
if len(duplicates) == 0:
# All values are unique, no repetition
self.rows = row_sum.argsort()
return input_array[self.rows, :]
else:
# Values ain't unique, there is repetition
# First find which indices are repeating
for each_duplicate in duplicates:
for index, value in enumerate(row_sum):
if each_duplicate == value:
row_sum[index] = value + \
self.convert_to_floating_point(self.numpyarray_toint(input_array[index], True))
self.rows = row_sum.argsort()
return input_array[self.rows, :]
def sort_columns_in_descending_order(self, input_array):
"""
Sort columns of input matrix. The algorithm is specified at the top.
Parameters
----------
input_array :
Returns
-------
"""
input_array = input_array.transpose()
# So each row has to be unique for us to convert to Lower triangular Matrix
row_sum = np.sum(input_array, axis=1, dtype=np.float)
row_sum_unique, counts = np.unique(row_sum, return_counts=True)
duplicates = row_sum_unique[counts > 1]
if len(duplicates) == 0:
# All values are unique, no repetition
self.columns = row_sum.argsort()[::-1]
return input_array[self.columns, :].transpose()
else:
# Values ain't unique, there is repetition
# First find which indices are repeating
for each_duplicate in duplicates:
for index, value in enumerate(row_sum):
if each_duplicate == value:
row_sum[index] = value + self.convert_to_floating_point(
self.numpyarray_toint(input_array[index], True))
self.columns = row_sum.argsort()[::-1]
return input_array[self.columns, :].transpose()
def get_lt_matrix_infos(self):
"""
This function is just used to return values in the order
bool: Whether the matrix output generated is an LT matrix or not
np.ndarray: The LT matrix, if not possible the near LT matrix. Basically whatever the output generated
from the algorithm
int: The reference segment Accelerometer ID
np.ndarray: The accelerometer ID's in the order of their arrangement on the robotic arm
np.ndarray: The Joint ID's in the order of their arrangement on the robotic arm
Returns
-------
bool, np.ndarray, int, np.ndarray, np.ndarray
"""
return self.is_lower_triangular, self.final_matrix, self.reference_segment_accelerometer, self.rows, self.columns
def is_square_matrix(self, input_array):
"""
This is a function which raises an exception, if the output matrix isn't square matrix
Parameters
----------
input_array : Input Matrix
Returns
-------
None
It doesn't return any value, but throws an exception if the passes matrix isn't a square matrix
"""
if not len(input_array) == len(input_array[0]):
raise Exception("The matrix isn't square")
def find_zero_ndarray(self, input_array):
"""
As this is a binary matrix, with values only 0 and 1, equating min value and max value to 0, we can say
the array is a zero array
Parameters
----------
input_array : np.ndarray
Input matrix is the matrix we want to find out whether it's a zero array or not.
Returns
-------
Bool
True if the array is a zero array, otherwise False
"""
if input_array.min(axis=0) == input_array.max(axis=0) == 0:
return True
return False
def is_lower_triangular_fn(self, input_array):
"""
Directly copied from: https://www.geeksforgeeks.org/program-check-matrix-lower-triangular/
And also checked. Will output if input matrix input_array is a lower triangular matrix or not
Parameters
----------
input_array : np.ndarray
The matrix in question, whether it's lower triangular or not
Returns
-------
bool
True if numpy array inputted is lower triangular, else False
"""
rows, cols = input_array.shape
for i in range(rows):
for j in range(i+1, cols):
if input_array[i][j] != 0:
return False
return True
def is_matrix_lt_convertible(self, input_array):
"""
Assuming that passed triangle is binary matrix, this will only work in that case
Parameters
----------
input_array :
Returns
-------
"""
self.is_square_matrix(input_array)
length_of_input_array = len(input_array)
if np.sum(input_array) <= (length_of_input_array * (length_of_input_array + 1)) / 2:
pass
else:
raise Exception("Matrix is not convertible to lower traiangular matrix")
if __name__ == "__main__":
# Original Matrix given in the paper
TEST_ARRAY = np.array([
[0, 1, 0, 1, 0],
[1, 1, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 1, 0, 1, 1],
[0, 0, 0, 1, 0]
])
print(ConvertToLT(TEST_ARRAY).get_lt_matrix_infos())
|
4bf341bbd114f53be77dbf1d648ea22011f5f2bf | shayd3/Python | /Algorithms/BinarySearch.py | 1,061 | 3.9375 | 4 | import numpy as np
import math
# Creates an array of specified length with random integers from 0-9999
def create_array(arraySize):
return np.random.randint(10000, size=int(arraySize))
# Binary search algorithm
def binary_search(a, target):
# Number of comparisons while searching
comparisons = 0
min = 0
max = len(a)
while min < max: # Will stop once reached smaller number (from left)
x = min + (max - min) / 2
val = a[x]
if target == val:
comparisons += 1
print "Number of Comparisons it took to find: ", comparisons
return x
elif target > val:
comparisons += 1
if min == x: # Will stop once reached higher number (from right)
break
min = x
elif target < val:
comparisons += 1
max = x
size = int(raw_input("What size would you like your array to be?> "))
a = create_array(size)
a.sort()
print a
target = int(raw_input("Pick target> "))
indexFound = binary_search(a,target)
if indexFound != None:
print "Element " + str(target) + " found at index: " + str(indexFound)
else:
print "Element not found."
|
34af9edfefb3677ff9b8053981cf0d6c80e85ee9 | Aghyad1993/programming | /les6/les6_5.py | 144 | 3.71875 | 4 | def swap (lst):
if len(lst) > 1:
lst[0], lst[1] = lst[1], lst[0]
return lst
lst = [4, 0, 1, -2]
res = swap(lst)
print (res) |
db1875ffa7ce9d9ae79b194c44b6859c41f923f8 | fellipegpbotelho/design-patters-python | /src/behavioral/strategy/concept.py | 2,422 | 4.40625 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Strategy(ABC):
"""The Strategy interface declares operations commom to all supported versions of
some algorithm.
The Context uses this interface to call the algotithm defined by Concrete Strategies.
"""
@abstractmethod
def do_algorithm(self, data: List) -> List:
pass
class Context:
"""The Context defines the interface of interest to clients."""
def __init__(self, strategy: Strategy) -> None:
"""Usually, the Context accepts a strategy through the constructor, but also
provides a setter to change it at runtime."""
self._strategy = strategy
@property
def strategy(self) -> Strategy:
"""The Context maintains a reference to one of the Strategy objects. The
Context does not know the concrete class of a strategy. It should work with
all strategies via the Strategy interface."""
return self._strategy
@strategy.setter
def strategy(self, strategy: Strategy) -> None:
"""Usually, the Context allows replacing a Strategy object at runtime."""
self._strategy = strategy
def do_some_business_logic(self) -> None:
"""The Context delegates some work to the Strategy object instead of implementing
multiple versions of the algorithm on its own."""
result = self._strategy.do_algorithm(['a', 'b', 'c'])
print(result)
class ConcreteStrategyA(Strategy):
"""Concrete Strategies implement the algotithm while following the base Strategy
interface. The interface makes them interchangeable in the Context."""
def do_algorithm(self, data: List) -> List:
print('sorting list...')
return sorted(data)
class ConcreteStrategyB(Strategy):
def do_algorithm(self, data: List) -> List:
print('reversing and sorting list...')
return list(reversed(sorted(data)))
def main() -> None:
# The client code picks a concrete strategy and passes it to the context.
# It should be aware of the differences between strategies in order to make the right choice.
context = Context(ConcreteStrategyA())
context.do_some_business_logic()
# The context can change the Strategy in runtime.
context.strategy = ConcreteStrategyB()
context.do_some_business_logic()
if __name__ == '__main__':
main()
|
a0d48d0082caf265096e353555facb7647663947 | ZhangArcher/aufgabenis | /regression/task2.py | 710 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def w0(x: np.ndarray, y: np.ndarray):
return y.mean() - w1(x, y)*x.mean()
def w1(x: np.ndarray, y: np.ndarray):
return ((x*y).mean() - x.mean()*y.mean())/((x**2).mean() - x.mean()**2)
def hypothesis(xval, w0, w1):
return w0 + w1*xval
x = np.array([0, 30, 50, 80, 100, 130, 180])
y = np.array([0, 3.5, 5.0, 6.8, 7.4, 8.0, 12.0])
plt.figure()
plt.plot(x, y, '.')
xnew = np.linspace(x.min(), x.max(), 2)
plt.plot(xnew, hypothesis(xnew, w0(x, y), w1(x, y)))
plt.show()
print("Hypothesis gasoline prices: ")
for i in range(len(x)):
xval = x[i]
print(f"(s, chyp, ctrue) = ({xval}, {hypothesis(xval, w0(x, y), w1(x, y))}, {y[i]})") |
93f7561fd8fc4f5c28833aaa001c6edcc69810b1 | Rogerio-ojr/EstudosPython | /Exercicio27.py | 155 | 3.71875 | 4 | nome = input('Digite um nome: ')
nome = nome.strip()
for i in nome.split():
a = i
print(f'O primeiro nome e {nome.split()[0]}, e o Ultimo nome e {a}')
|
b92372005c418ea6a83bcc9a2d325c5b16ea8af5 | bjbean/python_study | /3_字符串.py | 2,186 | 4.3125 | 4 | tip ="""
python字符串示例
1.python语言,可以使用多种引号来引用。
双引号 "this is a string"
单引号 'this is a string'
2.多行文本,使用三个单引号或双引号引用。
var = '''this is a line
but have multi lines'''
3.文本中含有引号,可在前面使用转义符(\)
var_str='He said:"Are\\'t can\\'t shouldn\\'t would\'t"'
4.字符串嵌入值(%s)
myscore=100
message="I scored %s points"
print(message % myscore)
5.字符串乘法
'A'*5 = 'AAAAA'
"""
print(tip)
print()
print("*"*10,"字符串定义","*"*10)
var_str="this is a string"
print('var_str="this is a string" ')
print("print(var_str)=>",var_str)
print("变量var_str的类型:type(var_str)=",type(var_str))
print()
print("*"*10,"多种引号用法","*"*10)
print("<<<双引号>>>")
var_str="this is a string"
print('var_str="this is a string" ')
print("print(var_str)=>",var_str)
print()
print("<<<单引号>>>")
var_str='this is a string'
print("var_str='this is a string' ")
print("print(var_str)=>",var_str)
print()
print("*"*10,"字符串用法","*"*10)
print("<<<多行文本>>>")
var_str="""this is a string
but have multi lines"""
print("var_str=",'''"""this is a string
but have multi lines""" ''')
print("print(var_str)=>",var_str)
print()
print("<<<包含单引号>>>")
var_str="this'is a string"
print('''var_str="this'is a string" ''')
print("print(var_str)=>",var_str)
print()
print("<<<包含双引号>>>")
var_str='this"is a string'
print("""var_str='this"is a string'""")
print("print(var_str)=>",var_str)
print()
print("<<<使用转义符>>>")
var_str='He said:"Are\'t can\'t shouldn\'t would\'t"'
print("""var_str='He said:"Are\\'t can\\'t shouldn\\'t would\\'t"'""")
print("print(var_str)=>",var_str)
print()
print("<<<字符串占位符>>>")
myscore=100
print("myscore=100")
message="I scored %s points"
print('message="I scored %s points"')
print("print(message % myscore)=>",message % myscore)
print()
print("<<<字符串乘法>>>")
var_str = 'A'
print("var_str = 'A'")
print("print(var_str*10)=>",var_str*10)
print()
|
2fa034e0589bc9120733a0827ba96e608a486cc1 | randell/Project-Euler | /0001-multiples_of_3_or_5-a.py | 502 | 3.828125 | 4 | """
Project Euler Problem 1
Title:
Multiples of 3 or 5
Description:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get
3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Solution:
This version is a naive implementation using a loop and modulus division.
Answer: 233168.
I'm the 311,384th person to solve this problem.
"""
sum = 0
for x in range(0, 10):
sum += x if x % 3 == 0 or x % 5 == 0 else 0
print sum |
fff828c8f8761cc47bcce70944422aa5cc7073da | saranraj-git/pyJanaDay1 | /init_Example.py | 143 | 3.625 | 4 | class MyClass(v1,v2,v3):
def __init__(self,v1,v2,v3):
self.x1 = v1
self.x2 = v1
self.x3 = v1
p1 = MyClass(1,2,3)
print(p1.x1) |
42c5441b31e03e1a3139b184baa5708c5867506e | augusnunes/data-struc-py | /stack/stack_binary.py | 451 | 3.9375 | 4 | """
exemplo de como usar pilha pra passar
um número da base 10 pra base 2
"""
from stack import Stack
def mudaBinario(numero10):
s = Stack()
while numero10 > 0:
remainder = numero10%2
s.push(remainder)
numero10 //=2
numero2 = ""
while not s.is_empty():
numero2 += str(s.pop())
return numero2
numero = int(input())
print(mudaBinario(numero))
print(int(mudaBinario(numero), base=2)," = ",numero) |
69d99375f3295bb2488fc43bdaf72870f4e08812 | PedroRamos360/PythonCourseUdemy | /kivy/aulas/Seção 12 - Estrutura de dados/OperaçõesListas.py | 411 | 4.21875 | 4 | l = list('abc')
# append para adicionar elementos
l.append('d')
print(l)
# insert para adicionar elementos em localizações específicas
l.insert(0, '0')
print(l)
# alterar items
l[0] = 'a0'
print(l)
# clear para tirar todos elementos de uma lista
l.clear()
l = list('abcde')
# pop para deletar um item
print(l.pop(-1))
print(l)
# del para excluir um intervalo de items em uma lista
del(l[1:-1])
print(l) |
797d409ba7eda8e9d84d91633beccdbcdbf7602d | antichown/udemy_courses | /financial_analysis_py/3_python_crash_course/Python Crash Course Exercises - Solutions.py | 3,904 | 4.59375 | 5 | #!/usr/bin/env python
# coding: utf-8
# # Python Crash Course Exercises - Solutions
#
# This is an optional exercise to test your understanding of Python Basics. The questions tend to have a financial theme to them, but don't look to deeply into these tasks themselves, many of them don't hold any significance and are meaningless. If you find this extremely challenging, then you probably are not ready for the rest of this course yet and don't have enough programming experience to continue. I would suggest you take another course more geared towards complete beginners, such as [Complete Python Bootcamp]()
# ## Exercises
#
# Answer the questions or complete the tasks outlined in bold below, use the specific method described if applicable.
# ### Task #1
#
# Given price = 300 , use python to figure out the square root of the price.
# In[3]:
price = 300
# In[4]:
price**0.5
# In[6]:
import math
math.sqrt(price)
# ### Task #2
#
# Given the string:
#
# stock_index = "SP500"
#
# Grab '500' from the string using indexing.
# In[1]:
stock_index = "SP500"
# In[2]:
stock_index[2:]
# ### Task #3
#
# ** Given the variables:**
#
# stock_index = "SP500"
# price = 300
#
# ** Use .format() to print the following string: **
#
# The SP500 is at 300 today.
# In[7]:
stock_index = "SP500"
price = 300
# In[9]:
print("The {} is at {} today.".format(stock_index,price))
# ### Task #4
#
# ** Given the variable of a nested dictionary with nested lists: **
#
# stock_info = {'sp500':{'today':300,'yesterday': 250}, 'info':['Time',[24,7,365]]}
#
# ** Use indexing and key calls to grab the following items:**
#
# * Yesterday's SP500 price (250)
# * The number 365 nested inside a list nested inside the 'info' key.
# In[10]:
stock_info = {'sp500':{'today':300,'yesterday': 250}, 'info':['Time',[24,7,365]]}
# In[12]:
stock_info['sp500']['yesterday']
# In[15]:
stock_info['info'][1][2]
# ### Task #5
#
# ** Given strings with this form where the last source value is always separated by two dashes -- **
#
# "PRICE:345.324:SOURCE--QUANDL"
#
# **Create a function called source_finder() that returns the source. For example, the above string passed into the function would return "QUANDL"**
# In[16]:
def source_finder(s):
return s.split('--')[-1]
# In[18]:
source_finder("PRICE:345.324:SOURCE--QUANDL")
# ### Task #5
#
# ** Create a function called price_finder that returns True if the word 'price' is in a string. Your function should work even if 'Price' is capitalized or next to punctuation ('price!') **
# In[19]:
def price_finder(s):
return 'price' in s.lower()
# In[20]:
price_finder("What is the price?")
# In[22]:
price_finder("DUDE, WHAT IS PRICE!!!")
# In[23]:
price_finder("The price is 300")
# ### Task #6
#
# ** Create a function called count_price() that counts the number of times the word "price" occurs in a string. Account for capitalization and if the word price is next to punctuation. **
# In[46]:
def count_price(s):
count = 0
for word in s.lower().split():
# Need to use in, can't use == or will get error with punctuation
if 'price' in word:
count += 1
# Note the indentation!
return count
# In[43]:
# Simpler Alternative
def count_price(s):
return s.lower().count('price')
# In[44]:
s = 'Wow that is a nice price, very nice Price! I said price 3 times.'
# In[47]:
count_price(s)
# ### Task #7
#
# **Create a function called avg_price that takes in a list of stock price numbers and calculates the average (Sum of the numbers divided by the number of elements in the list). It should return a float. **
# In[27]:
def avg_price(stocks):
return sum(stocks)/len(stocks) # Python 2 users should multiply numerator by 1.0
# In[30]:
avg_price([3,4,5])
# # Great job!
|
ab4147ff177d67dad21cbbbef8798b8349a0b17c | melijov/course_python_essential_training | /kwargs-working.py | 392 | 3.671875 | 4 | #!\usr\bin\env python 3
#Keyword Arguments: diction instead of a tuple
def main():
kitten(Buffy='meow',Zilla='grr',Angel='rawr')
x = dict(Buffy='meow',Zilla='grr',Angel='rawr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k,kwargs[k]))
else:
print('Meow.')
if __name__=='__main__':main() |
b834aa5b0ead3fdf3934d5c367a96b52f3ec4612 | Aquariuscsx/python | /homework/day17/person.py | 763 | 3.859375 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
class Student(Person):
def __init__(self, name, age, grade):
Person.__init__(self, name, age)
self.grade = grade
class Worker(Person):
def __init__(self, name, age, salary,job_content):
Person.__init__(self, name, age)
self.salary = salary
self.job_content = job_content
def show(self):
print(self.name, self.age, self.salary,self.job_content)
if __name__ == '__main__':
person = Person('李鹏', '38岁')
student = Student('周勇', '48岁', 60)
worker = Worker('王震', '25岁', '工资:1888', '工作:搬水泥')
worker.show() |
865281468895281189d0466cb05db7b14b76095f | azozello/swe | /leetcode/medium/search_in_a_matrix.py | 2,408 | 3.796875 | 4 | def solve(matrix: [[int]], target: int) -> bool:
def find_index(start_index: int, is_vertical: bool):
local_index = -1
coords = [[start_index + j, j] for j in range(length)] if is_vertical \
else [[j, start_index + j] for j in range(length)]
for coord in coords:
if matrix[coord[0]][coord[1]] == target:
return -2
elif matrix[coord[0]][coord[1]] > target:
local_index = min(coord)
break
return local_index
def search_in_square(start_index: int, is_vertical: bool) -> bool:
index = find_index(start_index, is_vertical)
if index == -1:
return False
elif index == -2:
return True
else:
if is_vertical:
for j in range(index):
if matrix[start_index + index][j] == target or matrix[start_index + j][index] == target:
return True
else:
for j in range(index):
if matrix[index][start_index + j] == target or matrix[j][start_index + index] == target:
return True
return False
def search_in_line(start_index: int, is_vertical: bool) -> bool:
line = [matrix[start_index][j] for j in range(length)] if is_vertical \
else [matrix[j][start_index] for j in range(length)]
if line[length - 1] == target:
return True
elif line[length - 1] < target:
return False
else:
return target in line
n = len(matrix[0])
m = len(matrix)
length = min([n, m])
squares = n // m if n > m else m // n
lines = n % m if n > m else m % n
vertical = m > n
for i in range(squares):
found = search_in_square(i * length, vertical)
if found:
return True
for i in range(lines):
found = search_in_line(i + (squares * length), vertical)
if found:
return True
return False
if __name__ == '__main__':
print('Search a 2D Matrix II')
test_matrix = [
[1, 4, 7, 11, 15, 16], # n
[2, 5, 8, 12, 19, 21],
[3, 6, 9, 16, 22, 25],
[10, 13, 14, 17, 24, 35],
[18, 21, 23, 26, 30, 37]
] # m
print(solve(test_matrix, 5))
print(solve(test_matrix, 20))
print(solve(test_matrix, 35))
|
960ce48017ee9c7730a4e6471349ec2683d3167c | rahulb246/leetcode-may-challenge | /week-1/isCousins.py | 1,560 | 4.09375 | 4 | # In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
# Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
# We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
# Return true if and only if the nodes corresponding to the values x and y are cousins.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def haveSameParents(self, root, x, y):
if not root:
return 0
return ((root.left and root.right and ((root.left.val == x and root.right.val == y) or
(root.left.val == y and root.right.val == x))) or
self.haveSameParents(root.left, x, y) or
self.haveSameParents(root.right, x, y))
def depth(self, root, val, dpt):
if not root:
return 0
if root.val == val:
return dpt
d = self.depth(root.left, val, dpt+1)
return d if (d != 0) else self.depth(root.right, val, dpt+1)
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
return 1 if((self.depth(root, x, 1) == self.depth(root, y, 1)) and
(not self.haveSameParents(root, x, y))) else 0
|
b3eed46abcdfe7a931c95601a8a4cc2d56ed2bf5 | jimtheguy/PY4E | /course2/week3/words.py | 436 | 4.625 | 5 | # Jim R
# Write a program that prompts for a file name, then
# opens that file and reads through the file, and print
# the contents of the file in upper case.
# Use the file words.txt to produce the output below.
#Get filename from user
fname = input("Enter file name:")
fhandle = open(fname)
#loop through lines in the file, srip \n and capitalize, then print
for line in fhandle:
line = line.rstrip().upper()
print(line) |
21e80d0d76c198e785b1e62c003fb90ce4067ac5 | Shubham1304/Semester6 | /ClassPython/6.py | 1,795 | 4.3125 | 4 | #Class of 5th February 2019
#for loops
#file handling in python
#Why do we need files ? Persistence ie file stores the data permanently
#How to open and create a file in python?
# open : r,w,a
# perform certain operations
# close the file
#Errors that can be encountered if we dont close the file ? We can not use the file in any other program. Also contents wont be saved
fh = open ('test2.txt','r')
#file can also be treated as an object so it is stored in some location similarly to how other values are stored in the memory so we need a file object to point to it.
print (fh,type(fh))
line = fh.readline() #one line at a time
print ()
#rstrip function will remove a new line at the end of the file
#lstrip function will remove a new line at the right of the line ie at the beginning of the line
#line.strip will remove all the new line characters
while line:
line = line.strip()
print(line)
line = fh.readline()
#once the line is read the fh pointer is moved to next location
#then we use readline function to read that line that is pointed out by fh pointer
fg=open('test2.txt','r')
line = fg.readlines() #makes it an iterable #returns as a list with each line as an element of the line
print(line,type(line))
for l in line:
print (l.strip())
#read function reads the whole content of file as a string
#line= fh.read().split('\n')
'''This code is
with open('test2.txt','r') as f: #same as f = open('filename.txt','r') but the advantage is that it closes the file automatically when the while loop ends so we dont have to worry about
line = f.readline().strip() #closing the file.
while line:
line=line.strip()
if line.startswith('From'):
print line
#mbox.txt mboxshort.txt
#www.py4e.com/code/
|
5dae00ec88a28c97cd1f059259afd574c57ffe2f | manu-mannattil/nolitsa | /examples/delay/adfd_roessler.py | 1,026 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ADFD algorithm using time series from the Rössler oscillator.
The time delay is taken to be the delay at which the derivative of the
ADFD falls to 40% of its initial value. The estimated time delay is 5.
Compare with Fig. 6 of Rosenstein et al. (1994).
"""
import numpy as np
import matplotlib.pyplot as plt
from nolitsa import data, delay
sample = 0.10
x = data.roessler(a=0.20, b=0.40, c=5.7, sample=sample, length=2500,
discard=5000)[1][:, 0]
dim = 7
maxtau = 50
tau = np.arange(maxtau)
disp = delay.adfd(x, dim=dim, maxtau=maxtau)
ddisp = np.diff(disp)
forty = np.argmax(ddisp < 0.4 * ddisp[1])
print('Time delay = %d' % forty)
fig, ax1 = plt.subplots()
ax1.set_xlabel(r'Time ($\tau\Delta t$)')
ax1.set_ylabel(r'$\mathrm{ADFD}$')
ax1.plot(tau[1:] * sample, disp[1:])
ax2 = ax1.twinx()
ax2.plot(tau[1:] * sample, ddisp, 'g--')
ax2.plot(tau[forty + 1] * sample, ddisp[forty], 'o')
ax2.set_ylabel(r'$\frac{d}{d\tau}(\mathrm{ADFD}$)')
plt.show()
|
6e35394b0453d96adf9896cf5449865013ca6de1 | zephyr2095/pynet-learning | /lesson5/exercises/exercise1b.py | 1,080 | 3.765625 | 4 | #!/usr/bin/env python3
'''
Expand on the ssh_conn function from exercise1 except add a fourth parameter 'device_type' with a default value of 'cisco_ios'.
Print all four of the function variables out as part of the function's execution.
Call the 'ssh_conn2' function both with and without specifying the device_type
Create a dictionary that maps to the function's parameters. Call this ssh_conn2 function using the **kwargs technique.
'''
def ssh_conn2(ip_addr, username, password, device_type='cisco_ios'):
print('IP address is: {}'.format(ip_addr))
print('Username is: {}'.format(username))
print('Password is: {}'.format(password))
print('Device Type is: {}'.format(device_type))
print()
# Call ssh_conn2 function with and without specifying device_type
ssh_conn2('192.168.1.1', 'cisco', 'admin123', 'cisco_nxos')
ssh_conn2('172.63.17.1', 'admin', 'cisco')
device_info = {
'ip_addr': '10.10.10.1',
'password': 'cisco12345',
'username': 'admin2',
'device_type': 'cisco_xr'
}
# Call ssh_con2 using **kwargs
ssh_conn2(**device_info)
|
05f70859e996636b1da555985f91754d64950afe | Kor-KTW/PythonWorkSpace | /Basic/4_4_set.py | 459 | 4.1875 | 4 | #set : can't overlap, no order
my_set = {1,2,3,3,3}
print(my_set)
alphabet={"a", "b", "c"}
betabet= set(["b", "c", "d"])
# intersection
print(alphabet & betabet)
print(alphabet.intersection(betabet))
# sum of set
print(alphabet|betabet)
print(alphabet.union(betabet))
#differnce of set
print(alphabet-betabet)
print(alphabet.difference(betabet))
#add set element
alphabet.add("f")
print(alphabet)
#remove set element
alphabet.remove("f")
print(alphabet) |
2c4cef117b929c8748e7bc13c3d55c78e74b98c1 | YSreylin/HTML | /1101901079/Tuple/Tuple17.py | 385 | 4.53125 | 5 | #write a Python program to unzip a list of tuple into individual lists
list_of_tuples = [(1,2,3),(4,5,6),(7,8,9)]
print("List of Tuple is:",list_of_tuples)
individual_list = [list(i) for i in list_of_tuples]
print('individual list created: ', *individual_list)
#the following still creates a list of tuples
#print('still creates a list of tuples: ', list(zip(*list_of_tuples)))
|
12da6468257f673c94549bb052d70ee15e1bb9e5 | meck93/hs17-datavis-ex | /ex3/ex3_task7.py | 4,853 | 3.875 | 4 | # -*- coding: utf-8 -*-
""" Data Visualization HS 17
Implemenation of Exercise 3
Moritz Eck - 14 715 296"""
import numpy as np
def readCSV(filename):
"""
Reads the .data file and creates a list of the rows
Input
filename - string - filename of the input data file
Output
data - list containing all rows of the csv as elements
"""
import csv
data = []
with open(filename, 'rt', encoding='utf8') as csvfile:
lines = csv.reader(csvfile)
for row in lines:
data.append(row)
return data
def splitDataIntoGroups(data):
# 3 sepearte dataframes for each type
setosa = []
versicolor = []
virginica = []
for entry in data:
if entry[4] == 'Iris-setosa':
setosa.append(entry)
elif entry[4] == 'Iris-versicolor':
versicolor.append(entry)
elif entry[4] == 'Iris-virginica':
virginica.append(entry)
# Convert to numpy array
setosa = np.array(setosa)
versicolor = np.array(versicolor)
virginica = np.array(virginica)
# Remove the last column: species_names
setosa = np.array(setosa[:, :-1], dtype=float)
versicolor = np.array(versicolor[:, :-1], dtype=float)
virginica = np.array(virginica[:, :-1], dtype=float)
return setosa, versicolor, virginica
def computeMeanAttributes(flower):
# Seperate each column
sepal_length = flower[:, 0]
sepal_width = flower[:, 1]
petal_length = flower[:, 2]
petal_width = flower[:, 3]
# Compute the mean for each attribute of the flower type
mean_sepal_length = sum(sepal_length) / len(sepal_length)
mean_sepal_width = sum(sepal_width) / len(sepal_width)
mean_petal_length = sum(petal_length) / len(petal_length)
mean_petal_width = sum(petal_width) / len(petal_width)
return mean_sepal_length, mean_sepal_width, mean_petal_length, mean_petal_width
def euclideanDistance(point1, point2):
"""Computes the euclidean width between two entires.
Same function as in task 2.
"""
import math
if not len(point1) == len(point2):
print("Wrong dimensions!")
return None
dist = 0
for x in range(len(point1)):
dist += pow((point1[x] - point2[x]), 2)
return math.sqrt(dist)
def dissimilarity(vector1, vector2):
"""
Computes the dissimilarity between two vectors.
In this case the vectors contain the mean values of each attribute.
"""
return round(euclideanDistance(vector1, vector2), 4)
def similarity(vector1, vector2):
"""
Computes the similarity between two vectors.
In this case the vectors cointain the mean values of each attribute.
"""
return round(1 / (1 + dissimilarity(vector1, vector2)), 4)
# =============================================================================
# Main Program
# =============================================================================
# Load the data from csv
data = readCSV('iris.data')
# Dataset per flower types
(setosa, versicolor, virginica) = splitDataIntoGroups(data)
# Mean vectors per flower type
setosa_means = computeMeanAttributes(setosa)
versicolor_means = computeMeanAttributes(versicolor)
virginica_means = computeMeanAttributes(virginica)
# Task 7 - Headline
print("\n############### TASK 7 ############### ")
print("The dissimilarities and similarities of the different flower types: \n")
# Compute the dissimilarity and similarity between setosa and versicolor
dis_setosa_versicolor = dissimilarity(setosa_means, versicolor_means)
sim_setosa_versicolor = similarity(setosa_means, versicolor_means)
print("1. Setosa vs. Versicolor")
print("Dissimilarity:\t", dis_setosa_versicolor, "\nSimilarity:\t", sim_setosa_versicolor)
# Compute the dissimilarity and similarity between setosa and versicolor
dis_setosa_virginica = dissimilarity(setosa_means, virginica_means)
sim_setosa_virginica = similarity(setosa_means, virginica_means)
print("\n2. Setosa vs. Virginica")
print("Dissimilarity:\t", dis_setosa_virginica, "\nSimilarity:\t", sim_setosa_virginica)
# Compute the dissimilarity and similarity between setosa and versicolor
dis_versicolor_virginica = dissimilarity(versicolor_means, virginica_means)
sim_versicolor_virginica = similarity(versicolor_means, virginica_means)
print("\n3. Versicolor vs. Virginica")
print("Dissimilarity:\t", dis_versicolor_virginica, "\nSimilarity:\t", sim_versicolor_virginica)
"""
This is what the printout looks like...
Below the dissimilarities and similarities between the different flower types can be seen:
1. Setosa vs. Versicolor
Dissimilarity: 3.2052
Similarity: 0.2378
2. Setosa vs. Virginica
Dissimilarity: 4.7526
Similarity: 0.1738
3. Versicolor vs. Virginica
Dissimilarity: 1.6205
Similarity: 0.3816
"""
|
fb6052f2350a2f45ebdf777bd1b58aac6937852d | bakunobu/exercise | /1400_basic_tasks/chap_4/4_135.py | 201 | 3.984375 | 4 | def which_season(x:int) -> str:
if 3 <= x < 6:
return('Spring')
elif 6 <= x < 9:
return('Summer')
elif 9 <= x < 12:
return('Fall')
else:
return('Winter') |
265ba7915f9dd05ed927da67179e2cfb0db65ae8 | amarbecaj/MidtermExample | /zadatak 5.py | 1,924 | 3.921875 | 4 | """
=================== TASK 5 ====================
* Name: Del Boy Millionaire
*
* Help Del Boy become a millionaire. Del Boy is
* trading bitcoins on crypto-exchanges with simple
* algorithm. He is buying where the price of bitcoin
* is the lowest and selling where the bitcoin is
* the most expensive. Write a function `get_profit`
* which will take a list of bitcoin prices in USD as
* argument. The function should return what is the
* maximum possible profit for given bitcoin prices
* on different exchanges.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
def get_profit(lista): #najveci moguci profit koji mozemo ostvariti cemo preracunati
# kada najmanju trenutnu vrijednost bitcoin-a oduzmemo od najvece
def min(lista): # defisemo funkcije min i max
min_lista = lista[0] # fiksiramo prvi clan liste, tj postavimo da je on najmanji
for i in range(len(lista) - 1): # prolazimo kroz ostale clanove liste; onaj sto smo fiksirali iskljucujemo
# pa zato pozicija prvog clana u listi kroz koji prolazimo je i+1
if min_lista > lista[i + 1]: # ako je clan kroz koji prolazimo manji od datog minimuma, sada on postaje minimum
min_lista = lista[i + 1]
return min_lista # f-ja vrace minimum liste
def max(lista): # analogno kao za minimum
max_lista = lista[0]
for i in range(len(lista) - 1):
if max_lista < lista[i + 1]:
max_lista = lista[i + 1]
return max_lista
return max(lista) - min(lista) # na kraju f-ja get_profit vrace razliku najvece i najmanje vrijednosti
def main():
lista=[11283.5, 10221, 9896.6 ]
print("Najveci ostvareni profit je: ", get_profit(lista))
pass
main()
|
90301909212503c390145a814665f0b54ddc1538 | AhmedElsagher/algorithm-toolbox | /week3_greedy_algorithms/3_car_fueling/car_fueling.py | 781 | 3.65625 | 4 | # python3
import sys
def compute_min_refills(distance, tank, stops):
# write your code here
whats_left=tank
num_refils=0
for i in range(len(stops)-1):
if (whats_left>0 )and((stops[i+1]-stops[i])<whats_left):
whats_left-=(stops[i+1]-stops[i])
elif tank>(stops[i+1]-stops[i]):
whats_left=tank
whats_left-=(stops[i+1]-stops[i])
num_refils+=1
else:
return -1
# print(stops[i],whats_left,num_refils)
return num_refils
if __name__ == '__main__':
# d, m = map(int, input().split())
d=int(input())
m=int(input())
n=int(input())
stops=list(map(int, input().split()))
stops=[0]+stops+[d]
print(compute_min_refills(d, m, stops))
|
d1b49c773cbd57414e720adb24b11ed68e571905 | catVSdog/design_patterns | /bridge.py | 1,259 | 4.46875 | 4 | """
桥接模式:
又名:柄体模式、 接口模式
使抽象部分与实现部分分离,使他们可以各自变化
但是根据UML类图看,感觉更像两个聚合关系类之间的结合
一个类作为另一个类实例的一个属性
"""
class Car:
def __init__(self):
self.color = None # A类持有 B类 二者时聚合关系, color类是Car类的一个属性.
# 当然也可以反过来,让car类作为color类的属性,但是颜色拥有汽车在尝试上讲不通啊.还是汽车拥有颜色比较合适
def set_color(self, color):
assert isinstance(color, Color)
self.color = color
def get_color(self):
return self.color.name
def __repr__(self):
return f"{self.get_color()} {self.__class__.__name__}"
class Color:
def __init__(self, name):
self.name = name
class Red(Color):
pass
class Blue(Color):
pass
class BMW(Car):
pass
class WW(Car):
pass
if __name__ == '__main__':
red = Red('浅红色')
blue = Blue("星空蓝")
car_1 = BMW()
car_1.set_color(red)
print(car_1)
car_1.set_color(blue)
print(car_1)
car_2 = WW()
car_2.set_color(blue)
print(car_2)
car_2.set_color(red)
print(car_2)
|
75044f537838abe39ed6f74decb96f6de9166d00 | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/easy_algo/4_20.py | 7,888 | 4 | 4 | Check if the given string is K-periodic
Given a string **str** and an integer **K** , the task is to check whether the
given string is **K-periodic**. A string is k-periodic if the string is a
repetition of the sub-string **str[0 … k-1]** i.e. string **“ababab”** is
**2-periodic**. Print **Yes** if the given string is k-periodic else print
**No**.
**Examples:**
> **Input:** str = “geeksgeeks”, k = 5
> **Output:** Yes
> Given string can be generated by repeating the prefix of length k i.e.
> “geeks”
>
> **Input:** str = “geeksforgeeks”, k = 3
> **Output:** No
## Recommended: Please try your approach on **__{IDE}__** first, before moving
on to the solution.
**Approach:** Starting with the sub-string **str[k, 2k-1]** , **str[2k,
3k-1]** and so on, check whether all of these sub-strings are equal to the
prefix of the string of length **k** i.e. **str[0, k-1]**. If the condition is
true for all such sub-strings then print **Yes** else print **No**.
Below is the implementation of the above approach:
## C++
__
__
__
__
__
__
__
// CPP implementation of the approach
#include<bits/stdc++.h>
using namespace std;
// Function that return true if sub-string
// of length k starting at index i is also
// a prefix of the string
bool isPrefix(string str, int len, int i, int k)
{
// k length sub-string cannot start at index i
if (i + k > len)
return false;
for (int j = 0; j < k; j++)
{
// Character mismatch between the prefix
// and the sub-string starting at index i
if (str[i] != str[j])
return false;
i++;
}
return true;
}
// Function that returns true if str is K-periodic
bool isKPeriodic(string str, int len, int k)
{
// Check whether all the sub-strings
// str[0, k-1], str[k, 2k-1] ... are equal
// to the k length prefix of the string
for (int i = k; i < len; i += k)
if (!isPrefix(str, len, i, k))
return false;
return true;
}
// Driver code
int main()
{
string str = "geeksgeeks";
int len = str.length();
int k = 5;
if (isKPeriodic(str, len, k))
cout << ("Yes");
else
cout << ("No");
}
// This code is contributed by
// Surendra_Gangwar
---
__
__
## Java
__
__
__
__
__
__
__
// Java implementation of the approach
class GFG {
// Function that return true if sub-string
// of length k starting at index i is also
// a prefix of the string
static boolean isPrefix(String str, int len, int i, int
k)
{
// k length sub-string cannot start at index i
if (i + k > len)
return false;
for (int j = 0; j < k; j++) {
// Character mismatch between the prefix
// and the sub-string starting at index i
if (str.charAt(i) != str.charAt(j))
return false;
i++;
}
return true;
}
// Function that returns true if str is K-periodic
static boolean isKPeriodic(String str, int len, int k)
{
// Check whether all the sub-strings
// str[0, k-1], str[k, 2k-1] ... are equal
// to the k length prefix of the string
for (int i = k; i < len; i += k)
if (!isPrefix(str, len, i, k))
return false;
return true;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksgeeks";
int len = str.length();
int k = 5;
if (isKPeriodic(str, len, k))
System.out.print("Yes");
else
System.out.print("No");
}
}
---
__
__
## Python3
__
__
__
__
__
__
__
# Python3 implementation of the approach
# Function that returns true if sub-string
# of length k starting at index i
# is also a prefix of the string
def isPrefix(string, length, i, k):
# k length sub-string cannot
# start at index i
if i + k > length:
return False
for j in range(0, k):
# Character mismatch between the prefix
# and the sub-string starting at index i
if string[i] != string[j]:
return False
i += 1
return True
# Function that returns true if
# str is K-periodic
def isKPeriodic(string, length, k):
# Check whether all the sub-strings
# str[0, k-1], str[k, 2k-1] ... are equal
# to the k length prefix of the string
for i in range(k, length, k):
if isPrefix(string, length, i, k) == False:
return False
return True
# Driver code
if __name__ == "__main__":
string = "geeksgeeks"
length = len(string)
k = 5
if isKPeriodic(string, length, k) == True:
print("Yes")
else:
print("No")
# This code is contributed
# by Rituraj Jain
---
__
__
## C#
__
__
__
__
__
__
__
// C# implementation of the approach
using System;
class GFG
{
// Function that return true if sub-string
// of length k starting at index i is also
// a prefix of the string
static bool isPrefix(String str, int len, int i, int k)
{
// k length sub-string cannot start at index i
if (i + k > len)
return false;
for (int j = 0; j < k; j++)
{
// Character mismatch between the prefix
// and the sub-string starting at index i
if (str[i] != str[j])
return false;
i++;
}
return true;
}
// Function that returns true if str is K-periodic
static bool isKPeriodic(String str, int len, int k)
{
// Check whether all the sub-strings
// str[0, k-1], str[k, 2k-1] ... are equal
// to the k length prefix of the string
for (int i = k; i < len; i += k)
if (!isPrefix(str, len, i, k))
return false;
return true;
}
// Driver code
public static void Main()
{
String str = "geeksgeeks";
int len = str.Length;
int k = 5;
if (isKPeriodic(str, len, k))
Console.Write("Yes");
else
Console.Write("No");
}
}
/* This code contributed by PrinciRaj1992 */
---
__
__
## PHP
__
__
__
__
__
__
__
<?php
// PHP implementation of the approach
// Function that return true if sub-
// of length $k starting at index $i
// is also a prefix of the string
function isPrefix($str, $len, $i, $k)
{
// $k length sub- cannot start at index $i
if ($i + $k > $len)
return false;
for ( $j = 0; $j < $k; $j++)
{
// Character mismatch between the prefix
// and the sub- starting at index $i
if ($str[$i] != $str[$j])
return false;
$i++;
}
return true;
}
// Function that returns true if $str is K-periodic
function isKPeriodic($str, $len, $k)
{
// Check whether all the sub-strings
// $str[0, $k-1], $str[$k, 2k-1] ... are equal
// to the $k length prefix of the
for ($i = $k; $i < $len; $i += $k)
if (!isPrefix($str, $len, $i, $k))
return false;
return true;
}
// Driver code
$str = "geeksgeeks";
$len = strlen($str);
$k = 5;
if (isKPeriodic($str, $len, $k))
echo ("Yes");
else
echo ("No");
// This code is contributed by ihritik
?>
---
__
__
**Output:**
Yes
Attention reader! Don’t stop learning now. Get hold of all the important DSA
concepts with the **DSA Self Paced Course** at a student-friendly price and
become industry ready. To complete your preparation from learning a language
to DS Algo and many more, please refer **Complete Interview Preparation
Course** **.**
My Personal Notes _arrow_drop_up_
Save
|
c2da391160141f98f15ac6d926a2a4bacfe9ad11 | royqh1979/PyEasyGraphics | /examples/animates/equilateral.triangles.py | 1,019 | 3.8125 | 4 | """
Rainbow
From "Math Adventures with Python" Part II, Chapter 5, "Drawing Complex Patterns Using Triangles"
"""
import sys
from easygraphics import *
import math
import random
def triangle(size):
"""
Draw an equilateral triangle
:param size:
"""
size_b = size * math.sqrt(3) / 2
size_c = size / 2
polygon(0, -size, -size_b, size_c, size_b, size_c)
def main():
random.seed()
width = 800
height = 600
init_graph(width, height)
set_render_mode(RenderMode.RENDER_MANUAL)
translate(width / 2, height / 2)
t = 0
while is_run():
t = random.randrange(0, 255)
for i in range(90):
if delay_jfps(60):
rotate(360 / 90)
push_transform()
c = color_hsv((t + i * 255 / 90) % 255, 255, 255)
set_color(c)
translate(200, 0)
rotate(2 * i * 360 / 90)
triangle(100)
pop_transform()
close_graph()
easy_run(main) |
5d045cbdf278885ed42cf7fd0b4ac5aafbf0d483 | Ramkrish26/PythonPractice | /primeNumber.py | 326 | 4.25 | 4 | # To check whether a number is prime or not
num = input("Enter the number: ")
flag=0
if(int(num)==1):
print("It is neither neother Prime nor Composite number")
for i in range (2,int(num)):
if(int(num)%i==0):
flag=1
if(flag==0):
print("It is a prime number")
else:
print("It is not a prime number")
|
f20adf22959a59ecf9aa756f8d664395dbc2d215 | valefaraz/lab | /alumnos/58018-Valentin-Faraz/clase01/ejercicio5.py | 720 | 3.84375 | 4 | def fibo(n,a=0,b=1): #Este codigo muestra la serie de Fibonacci
while n!=0: #Mientras n sea distinto de cero se ejecuta la secuencia
return fibo(n-1,b,a+b) #N disminuye en uno, 'a' toma el valor de 'b' y 'b' toma el valor de 'a+b'
return a #La funcion fibo returna el valor de 'a'
for i in range(0,10): #Se imprimen los valores que returna la funcion fibo a medida que se le da valores a 'n'
print(fibo(i)) #'n' toma valores desde el 0 hasta el 10, se returna 'a' 11 veces
#Cambiando los argumentos de range() podriamos obtener los elementos de Fibonacci que queramos |
270f6b2dd1920c304e5ce9349c0d5ad631876975 | AndRoo88/Baseball-Flight-Calculator | /umba/umba1.py | 23,222 | 3.625 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
#This older version does not contain the SSW model but may still be
#useful for comparision
def main():
print("This baseball trajectory calculator models \
still air at sea level with about 60% humidity.\nThe ambient\
conditions are fixed can be adjusted in the code \
if needed or made into variable at a later time.\n\
\nAll initial ball state variables have default values that approximate\
a 90 mph ball with no spin.\nThe release point is only asked once\
and remains the same for subsequent pitches.\nAll other variables\
can be changed for comparison. To retain the current value, just press return")
pX = []
pY = []
pZ = []
IX = []
IY = []
IZ = []
DX = []
DY = []
DZ = []
FX = []
FY = []
FZ = []
#x y and z here are typical of an approximately 6' tall rhp
# these are the defualt initial values and can be changed here or as the code runs
# as the code
x = -1
y = 5.5
z = 6
Vtot = 90
Theta = 0
Psi = 0
SpinRate = 0.001
TiltH = 0
Tiltm = 0
SpinE = 100
print('\n\n\ncurent release distance left to right is', x)
Qx = (input('distance left from center of rubber (right haded pitchers should have negative numbers) (ft): '))
if Qx == "":
x = x
else:
x = float(x)
print('\n\n\ncurent release distance from rubber', y)
Qy = (input('release distance from rubber (should be approximatly the stride lenght)(ft): '))
if Qy == "":
y = y
else:
y = float(Qy)
print('\n\n\ncurent release height is', z)
Qz = (input('height of ball from field at release (ft): '))
if Qz == "":
z = z
else:
z = float(Qz)
i = 0
repeat = True
while repeat == True:
if i == 0:
print('\n\nIf you want to keep the current value simply hit return. Otherwise enter a new value.\n\n')
print("Current initial speed set to ",Vtot)
QVtot = (input('what is the ball\'s total initial speed (mph): '))
if QVtot == "":
Vtot = Vtot
else:
Vtot = float(QVtot)
print("Current vertical release angle set to ",Theta)
QTheta = (input('what is the ball\'s vertical release angle (deg): '))
if QTheta == "":
Theta = Theta
else:
Theta = float(QTheta)
print("Current horizontal release angle set to ", Psi)
QPsi = (input('what is the ball\'s horizontal release angle(deg): '))
if QPsi == "":
Psi = Psi
else:
Psi = float(QPsi)
print("Current initial Spin Rate set to ", SpinRate)
QSpinRate = (input('what is the ball\'s initial spin rate (rpm): '))
if QSpinRate == "":
SpinRate = SpinRate
else:
SpinRate = float(QSpinRate)
print("Current initial tilt hours set to ", TiltH)
QTiltH = (input('what is the ball\'s initial hours tilt (hrs): '))
if QTiltH == "":
TiltH = TiltH
else:
TiltH = float(QTiltH)
print("Current initial tilt minutes set to ", Tiltm)
QTiltm = (input('what is the ball\'s initial minutes tilt (mins): '))
if QTiltm == "":
Tiltm = Tiltm
else:
Tiltm = float(QTiltm)
print("Current initial spin efficiency set to ", SpinE)
QSpinE = (input('what is the ball\'s initial spin efficiency (%): '))
if QSpinE == "":
SpinE = SpinE
else:
SpinE = float(QSpinE)
if SpinE == 100:
Gyro = np.arccos(1 - (SpinE/100))
else:
TiltHnewUp = TiltH + 3
if TiltHnewUp > 12:
TiltHnewUp = int(TiltHnewUp - 12)
else:
TiltHnewUp = int(TiltHnewUp)
TiltHnewDn = TiltH - 3
if TiltHnewDn < 1:
TiltHnewDn = int(TiltHnewDn + 12)
else:
TiltHnewDn = int(TiltHnewDn)
print('if', TiltHnewUp,':',int(Tiltm),'is forward enter " r "')
print('if', TiltHnewDn,':',int(Tiltm),'is forward enter " l "')
leftRightGyro = ''
while leftRightGyro != 'l' and leftRightGyro != 'r':
leftRightGyro = input("l/r")
if leftRightGyro == 'l':
Gyro = np.arccos(1 - (SpinE/100))
elif leftRightGyro == 'r':
Gyro = np.pi - np.arccos(1- (SpinE/100))
print(Gyro)
Tiltr = TimeToTilt(TiltH, Tiltm)
positions = (PitchedBallTraj(x,y,z,Vtot,Theta,Psi,SpinRate,Tiltr,Gyro,0,0,i))
Plotting(positions)
pX.append(positions[0])
pY.append(positions[1])
pZ.append(positions[2])
IX.append(positions[3])
IY.append(positions[4])
IZ.append(positions[5])
DX.append(positions[6])
DY.append(positions[7])
DZ.append(positions[8])
FX.append(positions[9])
FY.append(positions[10])
FZ.append(positions[11])
leave = False
k = 0
while leave == False:
k = k+1
if k == 1:
Again = input("Would you like to look at another pitch?\n")
elif k > 6:
Again = 'n'
elif k > 5:
Again = input("Last Chance.Would you like to look at another pitch (y/n)?\n")
else:
Again = input("Would you like to look at another pitch (y/n)?\n")
if Again == 'y' or Again == 'yes' or Again == 'Y' or Again == 'YES' or Again == 'Yes':
repeat = True
leave = True
elif Again == 'n' or Again == 'no' or Again == 'N' or Again == 'NO' or Again == 'No':
repeat = False
leave = True
else:
leave = False
i = i + 1
plotSFinal(pX,pY,pZ,IX,IY,IZ,DX,DY,DZ,FX,FY,FZ,i)
def anglesTOCart(Vtot, Theta, Psi, SpinRate, Tilt, Gyro, angle1, angle2):
"""
This function is designed merely to generate the balls initial conditions
It will take various options and output x0,y0,z0,u0,v0,w0,Spinx0,\
Spiny0,Spinz0,angle1,angle2 angle 1 and angle 2 are for seam effects
"""
Theta = Theta*np.pi/180
Psi = Psi*np.pi/180
uvmag = Vtot*np.cos(Theta)
w0 = Vtot*np.sin(Theta)
u0 = -uvmag*np.sin(Psi)
v0 = uvmag*np.cos(Psi)
Tilt = (Tilt) # rad tilt
Gyro = (Gyro) # rad gyro
Spinx0 = SpinRate*np.sin(Gyro)*np.sin(Tilt)
Spiny0 = SpinRate*np.cos(Gyro)
Spinz0 = -SpinRate*np.sin(Gyro)*np.cos(Tilt)
angle1 = 0
angle2 = 0
print('\nu:',u0,'\nv:',v0,'\nw:',w0)
print('\nSpinx0:',Spinx0,'\nSpiny0:',Spiny0,'\nSpinz0:',Spinz0)
FullState = [u0,v0,w0,Spinx0,Spiny0,Spinz0,angle1,angle2]
return FullState
def PitchedBallTraj(x,y,z,Vtot, Theta, Psi, SpinRate, Tilt, Gyro, angle1, angle2,i):
"""
Primay inputs are: initial position, x0, y0, and z0 with origin at the
point of home plate, x to the rright of the catcher, y from the catcher
towards the pitcher, and z straight up. Initial velocities
u0, v0, and w0 which are the speeds of the ball in x, y, and z
respectivley. And spin rates
GUMBA1.0: This code uses a constant Cd and rod cross's model for CL
Predictions. Seam Orientation is not accounted for. Air Density is
considered only at sea level at 60% relative humidity. but can be easily
altered
"""
###############################################################################
FullState = anglesTOCart(Vtot, Theta, Psi, SpinRate, Tilt, Gyro, 0,0)
# print(FullState)
x0 = x
y0 = 60.5 - y
z0 = z
u0 = FullState[0]
v0 = FullState[1]
w0 = FullState[2]
Spinx0 = FullState[3]
Spiny0 = FullState[4]
Spinz0 = FullState[5]
angle1 = FullState[6]
angle2 = FullState[7]
###############################################################################
# All air properties are the approximate averages for sea level over the season
# rhoDRY = 0.0765 #lb/ft^3
# relHum = 0.73
# Temp = 60 #deg fahrenheit
rho = 0.074 #lb/ft^3, with humidity at sea level
circ = 9.125/12 #ft
diameter = (2. + 15/16)/12 #ft
Area = .25*np.pi*diameter**2 #ft^2
mass = 0.3203125 #lbm
c0 = 0.5*rho*Area/mass
BallConsts = [circ,diameter,Area,mass,c0]
t0 = 0.0
t = t0
dt = 0.001
u0 = u0 *1.467#ft/sec
v0 = -v0 *1.467#ft/sec
w0 = w0 *1.467#ft/sec
Spinx0 = Spinx0 * .104719754 #rad/s
Spiny0 = Spiny0 * -.104719754
Spinz0 = Spinz0 * .104719754
decisionPoint = 0.2 #sec #time before ball arrives when batter has
#to decide to hit or not.
SpinVec = [Spinx0,Spiny0,Spinz0]
Vel = [u0,v0,w0]
VelTot = np.sqrt(u0**2 + v0**2 + w0**2)
SpinRate0 = np.sqrt(Spinx0**2 + Spiny0**2 + Spinz0**2)
SpinEfficiency0 = 1-abs(np.dot(Vel, SpinVec)/(SpinRate0*VelTot))
#assumes that the efficiency is non-linear and that it follows the sin of the
#angle between the ball direction and the spin.
BallState0 = [x0,y0,z0,u0,v0,w0,Spinx0,Spiny0,Spinz0]
fileBT = open(str(i) + "BallTrajectoryNEW.txt","w+")
fileBT.write("time x y z u v w Spin x Spin y Spin z\n")
fileBT.write("==================================================================================================\n")
fileBT.write("{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}\n"
.format(t,x0,y0,z0,u0,v0,w0,Spinx0,Spiny0,Spinz0))
xP = []
yP = []
zP = []
uP = []
vP = []
wP = []
xD = BallState0[0]
yD = BallState0[1]
zD = BallState0[2]
uD = BallState0[3]
vD = BallState0[4]
wD = BallState0[5]
while BallState0[1] > 0. and BallState0[2] > 0. and t < 10:
#need to input a non-magnus ball path indicator.
t = t + dt
BallState1 = RK4(t, BallState0, dt, BallConsts)
fileBT.write("{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}{:<10.3f}\n"
.format(t,BallState1[0],BallState1[1],BallState1[2],BallState1[3],BallState1[4],BallState1[5],BallState1[6],BallState1[7],BallState1[8]))
BallState0 = BallState1
xP.append(BallState1[0]*12)
yP.append(BallState1[1])
zP.append(BallState1[2]*12)
uP.append(BallState1[3])
vP.append(BallState1[4])
wP.append(BallState1[5])
DecisionPointStep = int(.2/dt)
if t < decisionPoint:
print("WOW! no batter has enough skill to hit a ball thrown that fast")
xD = -10
yD = -10
zD = -10
uD = 0
vD = 0
wD = 0
else:
xD = xP[DecisionPointStep]/12
yD = yP[DecisionPointStep]
zD = zP[DecisionPointStep]/12
uD = uP[DecisionPointStep]
vD = vP[DecisionPointStep]
wD = wP[DecisionPointStep]
BallStateF = BallState1
xF, yF, zF = BallStateF[0], BallStateF[1], BallStateF[2]
fileBT.close()
dzNoSpin = w0*t - (32.2/2)*t*t
zfg = z0 + dzNoSpin
vBreak = BallStateF[2] - zfg
dxNoSpin = u0*t
xfg = x0 + dxNoSpin
hBreak = BallStateF[0] - xfg
SpinVecF = [BallStateF[6],BallStateF[7],BallStateF[8]]
VelF = [BallStateF[3],BallStateF[4],BallStateF[5]]
VelTotF = np.sqrt(BallStateF[3]**2 + BallStateF[4]**2 + BallStateF[5]**2)
SpinRateF = np.sqrt(BallStateF[6]**2 + BallStateF[7]**2 + BallStateF[8]**2)
SpinEfficiencyF = 1-abs(np.dot(VelF, SpinVecF)/(SpinRateF*VelTotF))
totalRotations = SpinRateF/(2*np.pi) #assumes no spin decay
finalApproachAngleyz = np.arctan2(abs(BallStateF[5]), abs(BallStateF[4]))
finalApproachAnglexy = np.arctan2(abs(BallStateF[3]), abs(BallStateF[4]))
Hrs, mins = TiltToTime(Tilt)
# Tiltdegs = TimeToTilt(Hrs,mins)
print('initial conditions:')
print('x0 (ft)------------------------------- ', to_precision(x0,4))
print('y0 (ft)------------------------------- ', to_precision(y0,4))
print('z0 (ft)------------------------------- ', to_precision(z0,4))
print('u0 (mph)------------------------------ ', to_precision(u0/1.467,4))
print('v0 (mph)------------------------------ ', to_precision(v0/1.467,4))
print('w0 (mph)------------------------------ ', to_precision(w0/1.467,4))
print('Total Velocity (mph)------------------ ', to_precision(VelTot/1.467,4))
print('Spinx0 (rpm)-------------------------- ', to_precision(Spinx0/0.104719754,4))
print('Spiny0 (rpm)-------------------------- ', to_precision(Spiny0/-0.104719754,4))
print('Spinz0 (rpm)-------------------------- ', to_precision(Spinz0/0.104719754,4))
print('Total Spin Rate (rpm)----------------- ', to_precision(SpinRate0/0.104719754,4))
print('Tilt (clock face)----------------------', Hrs,':',mins)
# print('Tilt (deg) --------------------------- ', to_precision(Tiltdegs,4))
if SpinRate0 == 0:
print('Initial Efficiency (%)---------------- NA')
else:
print('Initial Efficiency (%)---------------- ', to_precision(SpinEfficiency0*100,4))
print('\n\nconditions at decision point:')
print('x at decision point (ft)------------- ', to_precision(xD,4))
print('y at decision point (ft)------------- ', to_precision(yD,4))
print('z at decision point (ft)--------------', to_precision(zD,4))
print('u at decision point (ft)--------------', to_precision(uD,4))
print('v at decision point (ft)--------------', to_precision(vD,4))
print('w at decision point (ft)--------------', to_precision(wD,4))
print('\n\nconditions across the plate:')
print('xf (ft)-------------------------------', to_precision(BallStateF[0],4))
print('yf (ft)-------------------------------', to_precision(BallStateF[1],4)) # actually just the last point data was taken
print('zf (ft)-------------------------------', to_precision(BallStateF[2],4))
print('uf (mph)------------------------------', to_precision(BallStateF[3]/1.467,4))
print('vf (mph)------------------------------', to_precision(-BallStateF[4]/1.467,4))
print('wf (mph)------------------------------', to_precision(BallStateF[5]/1.467,4))
print('Total Velocity (mph)------------------', to_precision(VelTotF/1.467,4))
print('Spinxf (rpm)--------------------------', to_precision(BallStateF[6]/0.104719754,4))
print('Spinyf (rpm)--------------------------', to_precision( BallStateF[7]/0.104719754,4))
print('Spinzf (rpm)--------------------------', to_precision(BallStateF[8]/0.104719754,4))
print('Total Spin Rate (rpm)-----------------', to_precision(SpinRateF/0.104719754,4))
print('Approach Angle (yz, deg)--------------', to_precision(finalApproachAngleyz*180/np.pi,4))
print('Approach Angle (xy, deg)--------------', to_precision(finalApproachAnglexy*180/np.pi,4))
print('Final Efficiency (%)------------------', to_precision(SpinEfficiencyF*100,4))
print('dx after decision point (ft)----------', to_precision((BallStateF[0] - xD)/12,4))
print('dy after decision point (ft)----------', to_precision((BallStateF[1] - yD)/12,4))
print('dz after decision point (ft)----------', to_precision((BallStateF[2] - zD)/12,4))
print('\n\nTotals:')
print('flight time (t)-----------------------', to_precision(t,4))
print('Vertical break (in)-------------------', to_precision(vBreak*12,4))
print('Horizontal break (in)-----------------', to_precision(hBreak*12,4))
print('Number of Revolutions-----------------', to_precision(totalRotations*t,4))
positions = [xP,yP,zP,x0,y0,z0,xD,yD,zD,xF,yF,zF]
return positions
def Plotting(positions):
"""
xP, yP, and zP are the arrays that contain all the velocity positions. x0,
xD, and xF are the beginning, decision point, and last x poisitions of the
ball. Same for Y and Z
"""
xP = positions[0]
yP = positions[1]
zP = positions[2]
x0 = positions[3]
y0 = positions[4]
z0 = positions[5]
xD = positions[6]
yD = positions[7]
zD = positions[8]
xF = positions[9]
yF = positions[10]
zF = positions[11]
plt.figure(1,figsize=(3,10))
plt.xlabel('x (in)')
plt.ylabel('y (ft)')
plt.title('Bird\'s Eye View')
plt.ylim(0,max(yP) +2.5)
plt.plot(xP,yP)
plt.scatter(x0*12,y0, s=100, c = 'g')
plt.scatter(xD*12,yD, s=100, c = 'y')
plt.scatter(xF*12,yF, s=100, c = 'r')
# hold on
plt.show()
plt.figure(2, figsize=(3,6))
plt.xlabel('x (in)')
plt.ylabel('z (in)')
plt.title('Catcher\'s Perspective')
plt.plot(x0,z0,'g')
# plt.xlim(-17., 17.)
plt.ylim(0,max(zP) + 4)
plt.plot(xP,zP)
plt.scatter(x0*12,z0*12, s=100, c = 'g')
plt.scatter(xD*12,zD*12, s=100, c = 'y')
plt.scatter(xF*12,zF*12, s=100, c = 'r')
plt.show()
plt.figure(3,figsize=(10,3))
plt.xlabel('y (ft)')
plt.ylabel('z (in)')
plt.title('Side View')
plt.xlim(0,62.5)
plt.ylim(0,max(zP) + 9)
plt.plot(yP,zP)
plt.scatter(y0,z0*12, s=100, c = 'g')
plt.scatter(yD,zD*12, s=100, c = 'y')
plt.scatter(yF,zF*12, s=100, c = 'r')
plt.show()
def plotSFinal(pX,pY,pZ,IX,IY,IZ,DX,DY,DZ,FX,FY,FZ,j):
plt.figure(4,figsize=(3,10))
plt.xlabel('x (in)')
plt.ylabel('y (ft)')
plt.title('Bird\'s Eye View')
# plt.ylim(0,max(pY) + 2.5)
for i in range(j):
plt.plot(pX[i],pY[i], label = i)
plt.legend()
plt.scatter(IX[i]*12,IY[i], s=100, c = 'g')
plt.scatter(DX[i]*12,DY[i], s=100, c = 'y')
plt.scatter(FX[i]*12,FY[i], s=100, c = 'r')
plt.savefig("BirdsEye.jpg")
plt.show()
plt.figure(5, figsize=(3,6))
plt.xlabel('x (in)')
plt.ylabel('z (in)')
plt.title('Catcher\'s Perspective')
# plt.ylim(0,max(pZ) + 4)
for i in range(j):
plt.plot(pX[i],pZ[i], label=i)
plt.legend()
plt.scatter(IX[i]*12,IZ[i]*12, s=100, c = 'g')
plt.scatter(DX[i]*12,DZ[i]*12, s=100, c = 'y')
plt.scatter(FX[i]*12,FZ[i]*12, s=100, c = 'r')
plt.savefig("Catcher.jpg")
plt.show()
plt.figure(6,figsize=(10,3))
plt.xlabel('y (ft)')
plt.ylabel('z (in)')
plt.title('Side View')
plt.xlim(0,62.5)
# plt.ylim(0,max(pZ) + 9)
for i in range(j):
plt.plot(pY[i],pZ[i], label=i)
plt.legend()
plt.scatter(IY[i],IZ[i]*12, s=100, c = 'g')
plt.scatter(DY[i],DZ[i]*12, s=100, c = 'y')
plt.scatter(FY[i],FZ[i]*12, s=100, c = 'r')
plt.savefig("Side.jpg")
plt.show()
def TiltToTime(Tilt):
TiltTime = (((Tilt)%360)/360)*12
Hrs = int(TiltTime)
if Hrs == 0:
Hrs = 12
mins = int(TiltTime*60)%60
return(Hrs,mins)
def TimeToTilt(Hrs, mins):
"""
Take the tilt in hrs and mins and turns it into deg
"""
radHrs = ((Hrs-3)*np.pi/6)
radmins = (mins*np.pi/360)
return(radHrs + radmins)
def derivs(t, BallState, BallConsts):
dy = np.zeros(len(BallState))
u = BallState[3]
v = BallState[4]
w = BallState[5]
Spinx = BallState[6]
Spiny = BallState[7]
Spinz = BallState[8]#rad/sec
VelTot = np.sqrt(u**2 + v**2 + w**2)
SpinRate = np.sqrt(Spinx**2 + Spiny**2 + Spinz**2)
diameter = BallConsts[1] #ft
c0 = BallConsts[4]
rw = (diameter/2)*SpinRate
S = (rw/VelTot)*np.exp(-t/10000) #the "np.exp(-t/NUM) is for spin decay
#for no spin decay NUM should be large. When better data is available on
#spin decay will account for it here likely
Cl = 1/(2.32 + (0.4/S))
CdConst = 0.33
aDragx = -c0*CdConst*VelTot*u
aDragy = -c0*CdConst*VelTot*v
aDragz = -c0*CdConst*VelTot*w
aSpinx = c0*(Cl/SpinRate)*VelTot*(Spiny*w - Spinz*v)
aSpiny = c0*(Cl/SpinRate)*VelTot*(Spinz*u - Spinx*w)
aSpinz = c0*(Cl/SpinRate)*VelTot*(Spinx*v - Spiny*u)
ax = aDragx + aSpinx
ay = aDragy + aSpiny
az = aDragz + aSpinz - 32.2
dSpinx = 0
dSpiny = 0
dSpinz = 0
dy[0] = u
dy[1] = v
dy[2] = w
dy[3] = ax
dy[4] = ay
dy[5] = az
dy[6] = dSpinx
dy[7] = dSpiny
dy[8] = dSpinz
return dy
def ClKensrud(r,Spin,u):
""" r is the radius of the ball, Spin is the spin rate and u is the velocity
It still needs to be worked out. As it is it only works for one dimensional
movement. Not in GUMBA1.0
"""
if u == 0. or Spin == 0:
CL = 0.
elif Spin < 0:
CL = -1.1968*np.log(abs(r*Spin/u)) - 4.7096
else:
CL = 1.1968*np.log(abs(r*Spin/u)) + 4.7096
return CL
def to_precision(x,p):
"""
returns a string representation of x formatted with a precision of p
Based on the webkit javascript implementation taken from here:
https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp
"""
x = float(x)
if x == 0.:
return "0." + "0"*(p-1)
out = []
if x < 0:
out.append("-")
x = -x
e = int(math.log10(x))
tens = math.pow(10, e - p + 1)
n = math.floor(x/tens)
if n < math.pow(10, p - 1):
e = e -1
tens = math.pow(10, e - p+1)
n = math.floor(x / tens)
if abs((n + 1.) * tens - x) <= abs(n * tens -x):
n = n + 1
if n >= math.pow(10,p):
n = n / 10.
e = e + 1
m = "%.*g" % (p, n)
if e < -2 or e >= p:
out.append(m[0])
if p > 1:
out.append(".")
out.extend(m[1:p])
out.append('e')
if e > 0:
out.append("+")
out.append(str(e))
elif e == (p -1):
out.append(m)
elif e >= 0:
out.append(m[:e+1])
if e+1 < len(m):
out.append(".")
out.extend(m[e+1:])
else:
out.append("0.")
out.extend(["0"]*-(e+1))
out.append(m)
return "".join(out)
def RK4(t0,y0,dt,BallConsts):
n = len(y0)
k1 = np.zeros(n)
k2 = np.zeros(n)
k3 = np.zeros(n)
k4 = np.zeros(n)
ym = np.zeros(n)
ye = np.zeros(n)
y = np.zeros(n)
slope = np.zeros(n)
k1 = derivs(t0,y0, BallConsts)
ym = y0 + (k1*dt*0.5)
k2 = derivs(t0+dt*0.5, ym, BallConsts)
ym = y0 + k2*dt*0.5
k3 = derivs(t0+dt*0.5,ym, BallConsts)
ye = y0 + k3*dt
k4 = derivs(t0+dt, ye, BallConsts)
slope = (k1 + 2*(k2+k3) + k4)/6.0
y = y0 + slope*dt
return y
main()
|
5789dcd5033b670b406374d3a8d66020efb59566 | weguri/python | /listas_tipos/list/ordena_reverter.py | 241 | 4.125 | 4 | """
reverse()
Não reorganiza em ordem alfabética inversa;
ele simplesmente INVERTE a ordem da lista:
"""
fruits = ["oxicoco", "maça", "kiwi", "melon", "abacaxi", "banana", "mango", "ananás"]
fruits.reverse()
print(fruits)
|
335f43c5d8bfe4b41d5140bbe13d5c600498b1d4 | ArthurSpillere/AulaEntra21_ArthurSpillere | /Exercícios Resolvidos/Maykon/01-Exercicios/Aula008/Ex1.py | 1,404 | 3.96875 | 4 | #--- Exercício 1 - Funções
#--- Escreva uma função para cadastro de pessoa:
#--- a função deve receber três parâmetros, nome, sobrenome e idade
#--- a função deve salvar os dados da pessoa em uma lista com escopo global
#--- a função deve permitir o cadastro apenas de pessoas com idade igual ou superior a 18 anos
#--- a função deve retornar uma mensagem caso a idade informada seja menor que 18
#--- caso a pessoa tenha sido cadastrada com sucesso deve ser retornado um id
#--- A função deve ser salva em um arquivo diferente do arquivo principal onde será chamada
lista_cadastro = []
def cadastrar(nome:str, sobrenome:str, idade:int)->str:
#Valida critérios de entrada
if (nome == "" or nome == None or sobrenome == "" or sobrenome == None or
idade == "" or idade == None or not isinstance(idade, int)):
print("Entrada de dados inválida! Tente novamente!")
return False
#Realiza cadastro que cumpre pré requisito (18 anos)
if idade >= 18:
pessoa = {}
pessoa['Nome'] = nome
pessoa['Sobrenome'] = sobrenome
pessoa['Idade'] = idade
pessoa['ID'] = len(lista_cadastro) + 1
lista_cadastro.append(pessoa)
return print("Pessoa cadastrada com sucesso!")
else:
print("Não é possível cadastrar menor de 18 anos.")
return False
|
dfac620d726ec88245af0acd532aa23bcb6d50fd | ArelyA/TC3048.2 | /Quad.py | 633 | 3.578125 | 4 | class Quad(object):
def __init__(self, op, left, right, dest):
"""
Creates quad dict with contents
OP | LEFT | RIGHT | DEST
"""
self.op = op
self.left = left
self.right = right
self.dest = dest
def reprQ(self, l):
#print(l)
return "".join(["{:^", str(l),"}"]).format(self.op) + " | " + "".join(["{:^", str(l),"}"]).format(str(self.left)) + " | " + "".join(["{:^", str(l),"}"]).format(str(self.right)) + " | " + "".join(["{:^", str(l),"}"]).format(str(self.dest))
def __len__(self):
return max(len(str(self.op)), len(str(self.left)), len(str(self.right)), len(str(self.dest)))
|
7211a3941efc1ab65e343a5cb865eec45bef7950 | luizortega27/Atividades-faculdade | /AC4-Quantidade de dígitos (função iterativa).py | 98 | 3.640625 | 4 | numero = str(input())
contador = 0
for i in numero:
contador = contador + 1
print(contador)
|
f1027bedc2ab107b40c833411cf663fdb8820361 | gmmann/MSPythonCourse | /complexconditions.py | 632 | 4.25 | 4 | # A student makes honour roll if their average is >= 85
# and their lowest grade is not below 70
gpa = float(input('What is your Grade Point Average? '))
lowest_grade = input('What is your lowest grade? ')
lowest_grade = float(lowest_grade)
if gpa >= .85:
if lowest_grade >= .70:
print('You made the honour roll!')
if gpa >= .85 and lowest_grade >= .70:
print('You made the honour roll!')
if gpa >= .85 and lowest_grade >= .70:
honour_roll = True
else:
honour_roll = False
#Somewhere later in your code
if honour_roll:
print('You made the honour roll!')
else:
print('Sorry next time!')
|
8bc128efaee79f0fb6c17e7d3bf27963f0c53d86 | cm1819/carpentries | /hello.py | 146 | 3.921875 | 4 | num=154
if num>100 and num <150:
print("between 100 and 150")
elif num==100:
print ("Less than 100")
else:
print ("greater than 150")
|
4872b147ac8bd1a2fd8a3fc1983cecc90f2bac23 | joelrorseth/Snippets | /Python Snippets/Data Structures/union_find.py | 1,528 | 4.3125 | 4 | #
# Disjoint-Set (Union-Find) data structure
#
# The union-find tracks a set of elements, partitioned into a number of
# disjoint (non-overlapping) subsets. It essentially groups elements into
# subsets by maintaining array of parents for each element. Parents have
# parents, which have parents and so on. Eventually one element is the root,
# the parent of itself, and represents the disjoint subset of all its children.
#
# Without optimizations...
# Worst case time for Union() and Find(): O(n)
#
# Joel Rorseth
#
class DisjointSet:
def __init__(self, num_elements):
self.parent_of = list(range(num_elements))
self.num_subsets = num_elements
def find(self, k):
return k if self.parent_of[k] == k else self.find(self.parent_of[k])
def union(self, a, b):
parent_of_a = self.find(a)
parent_of_b = self.find(b)
if parent_of_a != parent_of_b:
self.num_subsets -= 1
self.parent_of[parent_of_a] = parent_of_b
def print_groups(self):
print("The DisjointSet contains %d subsets" % self.num_subsets)
for k in range(len(self.parent_of)):
print(k, "=> Group", self.find(k))
# This implementation, for simplicity, assumes that for n elements, the items
# contained in the disjoint set are the integers [0,n-1]. For generic use,
# map input objects to index within their original list, use with indices.
# Driver
elements = [0,1,2,3,4,5]
ds = DisjointSet(6)
ds.union(0,1)
ds.union(1,3)
ds.union(4,5)
ds.print_groups()
|
586bf3b38879f91b0c9405c127d5096c13ad7f32 | stofistofi/chess | /test_chessboard.py | 13,846 | 3.84375 | 4 | from chessboard import Chessboard
def test_create_board():
# test whether creating a board is as expected
expected_board = { 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:'P', 11:'P', 12:'P', 13:'P', 14:'P', 15:'P',
16:' ', 17:' ', 18:' ', 19:' ', 20:' ', 21:' ', 22:' ', 23:' ',
24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:' ', 30:' ', 31:' ',
32:' ', 33:' ', 34:' ', 35:' ', 36:' ', 37:' ', 38:' ', 39:' ',
40:' ', 41:' ', 42:' ', 43:' ', 44:' ', 45:' ', 46:' ', 47:' ',
48:'p', 49:'p', 50:'p', 51:'p', 52:'p', 53:'p', 54:'p', 55:'p',
56:'r', 57:'n', 58:'b', 59:'q', 60:'k', 61:'b', 62:'n', 63:'r'}
c = Chessboard()
try:
assert c.current_board() == expected_board
return True
except:
return False
def test_current_board():
# test whether making a few moves changes the board correctly
# this also tests move_pieces, which doesn't validate but only adjusts strings
expected_board = { 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:' ', 11:'P', 12:' ', 13:'P', 14:'P', 15:'P',
16:' ', 17:' ', 18:' ', 19:' ', 20:' ', 21:' ', 22:' ', 23:' ',
24:' ', 25:' ', 26:'P', 27:' ', 28:'P', 29:' ', 30:' ', 31:' ',
32:' ', 33:' ', 34:' ', 35:' ', 36:' ', 37:' ', 38:' ', 39:' ',
40:'p', 41:' ', 42:' ', 43:' ', 44:' ', 45:'n', 46:' ', 47:' ',
48:' ', 49:'p', 50:'p', 51:'p', 52:'p', 53:'p', 54:'p', 55:'p',
56:'r', 57:'n', 58:'b', 59:'q', 60:'k', 61:'b', 62:' ', 63:'r'}
c = Chessboard()
c.move_piece(48,40) # p to A3
c.move_piece(10,26) # P to C5
c.move_piece(62,45) # n to F3
c.move_piece(12,28) # P to E5
try:
assert c.current_board() == expected_board
return True
except:
return False
def test_reveal_piece():
# test whether keys reveal correct pieces before and after a few moves
c = Chessboard()
if ((c.reveal_piece(0) == 'R') and (c.reveal_piece(1) == 'N') and (c.reveal_piece(5) == 'B') and
(c.reveal_piece(11) == 'P') and (c.reveal_piece(49) == 'p') and (c.reveal_piece(56) == 'r') and
(c.reveal_piece(59) == 'q') and (c.reveal_piece(62) == 'n') and (c.reveal_piece(60) == 'k')):
return True
else:
return False
c.move_piece(52,36) # p to E4
c.move_piece(1, 18) # N to C6
c.move_piece(59,31) # q to H4
c.move_piece(13,29) # P to E5
if ((c.reveal_piece(36) == 'p') and (c.reveal_piece(18) == 'N') and (c.reveal_piece(31) == 'q') and
(c.reveal_piece(29) == 'P')):
return True
else:
return False
def test_valid_input():
c = Chessboard()
try:
assert c.valid_input('D2') == True
assert c.valid_input('e5') == True
assert c.valid_input('Zs') == False
assert c.valid_input('1D') == False
assert c.valid_input('231') == False
assert c.valid_input('Þ34') == False
assert c.valid_input('3e') == False
assert c.valid_input('-3') == False
assert c.valid_input(' d2') == False
assert c.valid_input('d2 ') == False
assert c.valid_input('') == False
return True
except:
return False
def test_same_team():
c = Chessboard()
lower_case = True
try:
assert c.same_team(lower_case, 56) == True
assert c.same_team(lower_case, 4) == False
assert c.same_team(not lower_case, 48) == False
assert c.same_team(lower_case, 1) == False
assert c.same_team(not lower_case, 60) == False
assert c.same_team(lower_case, 58) == True
return True
except:
return False
def test_move_pieces():
# as move_pieces() only adjusts strings, the test has been
# implemented in test_current_board()
return test_current_board()
def test_horizontal_travel():
# test horizontal travel of pieces, before data is sent to that function
# another validates that the movement is in the horizontal line on the board
c = Chessboard()
c.move_piece(48,32) # p to A4
c.move_piece(15,31) # P to H5
c.move_piece(56,40) # r to A3
c.move_piece(7,23) # R to H6
c.move_piece(51,43) # p to D3
c.move_piece(11,19) # P to D6
'''{ 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:' ',
8:'P', 9:'P', 10:'P', 11:' ', 12:'P', 13:'P', 14:'P', 15:' ',
16:' ', 17:' ', 18:' ', 19:'P', 20:' ', 21:' ', 22:' ', 23:'R',
24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:' ', 30:' ', 31:'P',
32:'p', 33:' ', 34:' ', 35:' ', 36:' ', 37:' ', 38:' ', 39:' ',
40:'r', 41:' ', 42:' ', 43:'p', 44:' ', 45:' ', 46:' ', 47:' ',
48:' ', 49:'p', 50:'p', 51:' ', 52:'p', 53:'p', 54:'p', 55:'p',
56:' ', 57:'n', 58:'b', 59:'q', 60:'k', 61:'b', 62:'n', 63:'r'}'''
try:
assert c.horizontal_travel(40,41) == True
assert c.horizontal_travel(40,42) == True
# moving r from 40 to 43 on p would be OK with horizontal_travel because it
# only checks whether we've jumped any pieces, other validating functions
# make sure we can't kill our own pieces
assert c.horizontal_travel(40,44) == False
assert c.horizontal_travel(40,24) == False
assert c.horizontal_travel(23,39) == False
assert c.horizontal_travel(23,18) == False
assert c.horizontal_travel(23,20) == True
return True
except:
return False
def test_vertical_travel():
c = Chessboard()
c.move_piece(48,32) # p to A4
c.move_piece(15,31) # P to H5
c.move_piece(56,40) # r to A3
c.move_piece(7,23) # R to H6
c.move_piece(51,43) # p to D3
c.move_piece(11,19) # P to D6
c.move_piece(40,41) # r to B3
'''{ 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:' ',
8:'P', 9:'P', 10:'P', 11:' ', 12:'P', 13:'P', 14:'P', 15:' ',
16:' ', 17:' ', 18:' ', 19:'P', 20:' ', 21:' ', 22:' ', 23:'R',
24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:' ', 30:' ', 31:'P',
32:'p', 33:' ', 34:' ', 35:' ', 36:' ', 37:' ', 38:' ', 39:' ',
40:' ', 41:'r', 42:' ', 43:'p', 44:' ', 45:' ', 46:' ', 47:' ',
48:' ', 49:'p', 50:'p', 51:' ', 52:'p', 53:'p', 54:'p', 55:'p',
56:' ', 57:'n', 58:'b', 59:'q', 60:'k', 61:'b', 62:'n', 63:'r'}'''
try:
assert c.vertical_travel(41,33) == True
assert c.vertical_travel(41,1) == False
assert c.vertical_travel(41,57) == False
assert c.vertical_travel(23,39) == False
assert c.vertical_travel(23,7) == True
return True
except:
return False
def test_diagonal_travel():
# Test diagonal movement, previous functions have validated the movement is only diagonal on the board
c = Chessboard()
c.move_piece(52,44) # p to E3
c.move_piece(11,19) # P to D6
c.move_piece(61,34) # b to C4
c.move_piece(2,29) # B to F5
'''{ 0:'R', 1:'N', 2:' ', 3:'Q', 4:'K', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:'P', 11:' ', 12:'P', 13:'P', 14:'P', 15:'P',
16:' ', 17:' ', 18:' ', 19:'P', 20:' ', 21:' ', 22:' ', 23:' ',
24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:'B', 30:' ', 31:' ',
32:' ', 33:' ', 34:'b', 35:' ', 36:' ', 37:' ', 38:' ', 39:' ',
40:' ', 41:' ', 42:' ', 43:' ', 44:'p', 45:' ', 46:' ', 47:' ',
48:'p', 49:'p', 50:'p', 51:'p', 52:' ', 53:'p', 54:'p', 55:'p',
56:'r', 57:'n', 58:'b', 59:'q', 60:'k', 61:' ', 62:'n', 63:'r'}'''
try:
assert c.diagonal_travel(34,16,9) == True # b to A6
assert c.diagonal_travel(34,6,7) == False # b to G8
assert c.diagonal_travel(29,57,7) == False # B to B2
assert c.diagonal_travel(29,46,9) == True # B to H3
return True
except:
return False
def test_rookValidity():
c = Chessboard()
c.move_piece(48,32) # p to A4
c.move_piece(15,31) # P to H5
c.move_piece(56,40) # r to A3
c.move_piece(7,23) # R to H6
c.move_piece(51,43) # p to D3
c.move_piece(11,19) # P to D6
'''{ 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:' ',
8:'P', 9:'P', 10:'P', 11:' ', 12:'P', 13:'P', 14:'P', 15:' ',
16:' ', 17:' ', 18:' ', 19:'P', 20:' ', 21:' ', 22:' ', 23:'R',
24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:' ', 30:' ', 31:'P',
32:'p', 33:' ', 34:' ', 35:' ', 36:' ', 37:' ', 38:' ', 39:' ',
40:'r', 41:' ', 42:' ', 43:'p', 44:' ', 45:' ', 46:' ', 47:' ',
48:' ', 49:'p', 50:'p', 51:' ', 52:'p', 53:'p', 54:'p', 55:'p',
56:' ', 57:'n', 58:'b', 59:'q', 60:'k', 61:'b', 62:'n', 63:'r'}'''
try:
assert c.rookValidity(40,41) == True # move to the side
assert c.rookValidity(40,44) == False # try to jump over p
assert c.rookValidity(40,48) == True # go back one square
assert c.rookValidity(40,33) == False # try going diagonally
assert c.rookValidity(40,39) == False # try going off board to the side
return True
except:
return False
def test_bishopValidity():
c = Chessboard()
c.move_piece(51,35) # p to D4
c.move_piece(58,37) # b to F4
'''{ 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:'P', 11:'P', 12:'P', 13:'P', 14:'P', 15:'P',
16:' ', 17:' ', 18:' ', 19:' ', 20:' ', 21:' ', 22:' ', 23:' ',
24:' ', 25:' ', 26:' ', 27:' ', 28:' ', 29:' ', 30:' ', 31:' ',
32:' ', 33:' ', 34:' ', 35:'p', 36:' ', 37:'b', 38:' ', 39:' ',
40:' ', 41:' ', 42:' ', 43:' ', 44:' ', 45:' ', 46:' ', 47:' ',
48:'p', 49:'p', 50:'p', 51:' ', 52:'p', 53:'p', 54:'p', 55:'p',
56:'r', 57:'n', 58:' ', 59:'q', 60:'k', 61:'b', 62:'n', 63:'r'}'''
try:
assert c.bishopValidity(37,45) == False # move vertically
assert c.bishopValidity(37,36) == False # move horizontally
assert c.bishopValidity(37,23) == True # move diagonally
assert c.bishopValidity(37,1) == False # jump over piece
assert c.bishopValidity(37,10) == True # kill P
return True
except:
return False
def test_queenValidity():
c = Chessboard()
c.move_piece(52,36) #p to E4
c.move_piece(11,27) #P to D5
c.move_piece(59,49) #q to F3
c.move_piece(3,19) #Q to D6
'''{ 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:'P', 11:' ', 12:'P', 13:'P', 14:'P', 15:'P',
16:' ', 17:' ', 18:' ', 19:' ', 20:' ', 21:' ', 22:' ', 23:' ',
24:' ', 25:' ', 26:' ', 27:'P', 28:' ', 29:' ', 30:' ', 31:' ',
32:' ', 33:' ', 34:' ', 35:' ', 36:'p', 37:' ', 38:' ', 39:' ',
40:' ', 41:' ', 42:' ', 43:' ', 44:' ', 45:'q', 46:' ', 47:' ',
48:'p', 49:'p', 50:'p', 51:'p', 52:' ', 53:'p', 54:'p', 55:'p',
56:'r', 57:'n', 58:'b', 59:' ', 60:'k', 61:'b', 62:'n', 63:'r'}'''
try:
assert c.queenValidity(3,19) == True # move Q two forward
assert c.queenValidity(3,5) == False # try jumping over piece
assert c.queenValidity(45,39) == False # try going off the side
assert c.queenValidity(45,31) == True # move diagonally
assert c.queenValidity(45,28) == False # move like a (k)night
return True
except:
return False
def test_kingValidity():
c = Chessboard()
c.move_piece(52,36) #p to E4
c.move_piece(11,27) #P to D5
c.move_piece(59,49) #q to F3
c.move_piece(3,19) #Q to D6
c.move_piece(4,31) #K to H5 (lil cheat)
'''{ 0:'R', 1:'N', 2:'B', 3:'Q', 4:' ', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:'P', 11:' ', 12:'P', 13:'P', 14:'P', 15:'P',
16:' ', 17:' ', 18:' ', 19:' ', 20:' ', 21:' ', 22:' ', 23:' ',
24:' ', 25:' ', 26:' ', 27:'P', 28:' ', 29:' ', 30:' ', 31:'K',
32:' ', 33:' ', 34:' ', 35:' ', 36:'p', 37:' ', 38:' ', 39:' ',
40:' ', 41:' ', 42:' ', 43:' ', 44:' ', 45:'q', 46:' ', 47:' ',
48:'p', 49:'p', 50:'p', 51:'p', 52:' ', 53:'p', 54:'p', 55:'p',
56:'r', 57:'n', 58:'b', 59:' ', 60:'k', 61:'b', 62:'n', 63:'r'}'''
try:
assert c.kingValidity(60,52) == True # move k one forward
assert c.kingValidity(31,32) == False # try going off the side
assert c.kingValidity(60,59) == True # move to the side
assert c.kingValidity(31,22) == True # move diagonally
assert c.kingValidity(31,38) == True # move diagonally
assert c.kingValidity(31,37) == False # move weirdly
return True
except:
return False
print("Testing create_board(): ", test_create_board())
print("Testing current_board(): ",test_current_board())
print("Testing reveal_piece(): ", test_reveal_piece())
print("Testing valid_input(): ", test_valid_input())
print("Testing same_team: ", test_same_team())
print("Testing move_pieces(): ", test_move_pieces())
print("Testing horizontal_travel():", test_horizontal_travel())
print("Testing vertical_travel(): ", test_vertical_travel())
print("Testing diagonal_travel(): ", test_diagonal_travel())
print("Testing rookValidity(): ", test_rookValidity())
print("Testing bishopValidity():", test_bishopValidity())
print("Testing queenValidity():", test_queenValidity())
print("Testing kingValidity():", test_kingValidity()) |
e5ee779f5b2df4abd73196eea1f675b782f5ff2f | jaroslawrutk/Python- | /09.05.2018/zadanie1.py | 562 | 3.5625 | 4 | import Tkinter as tk
import Tkfron as tkF
root = tk.Tk()
default_font=tkF.nameFront("TkDefaultFont")
default_font.configure(size=20)
root.option_add("*Front",default_font)
def read_v():
x=v.get();
if(v==1)
v=tk.IntVar()
rb1=tk.RadioButton(root,text="R",variable=v,value=1)
rb1.grid(column=0,row=0)
rb2=tk.RadioButton(root,text="G",variable=v,value=2)
rb2.grid(column=1,row=0)
rb3=tk.RadioButton(root,text="B",variable=v,value=3)
rb3.grid(column=2,row=0)
bt=tk.Button(root,text="stop",comand=)
bt.grid(row=1,column=0)
root.mainloop() |
39634af9c0bbad27d02b71d6d69e94003f2de4f6 | nitaicharan/UNIPE-P1-Sudoku | /limpa_digito.py | 784 | 3.625 | 4 | import curses
def limpa_digito(jogo):
menssagem = 'Deseja limpar jogo? (S/N): '
curses.cbreak()
curses.echo()
windowt = curses.newwin(2,100,15,0)
windowt.addstr(1,1,menssagem)
resposta = windowt.getch()
resposta = chr (resposta)
windowt.refresh()
if resposta in ['s', 'S']:
for lin_grade in range(3):
for col_grade in range(3):
for lin_regiao in range(3):
for col_regiao in range(3):
if jogo[lin_grade][col_grade][lin_regiao][col_regiao] ['automatico'] == False:
jogo[lin_grade][col_grade][lin_regiao][col_regiao]['digito'] = '.'
else:
pass
else:
pass
|
47e2b4fbc94a74fd70f53507511fd6d2f2566009 | ananya/HackerSkills | /Solutions/falconis/Task5/task5.py | 355 | 3.5 | 4 | import threading
def exp(x):
print("Square:", x**2)
def fact(x):
i = 1
ans = 1
while(i <= x):
ans *= i
i += 1
print("Factorial:", ans)
x = int(input())
thread1 = threading.Thread(target=exp, args=(x,))
thread2 = threading.Thread(target=fact, args=(x,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
|
973174cb9b3971efcf3f91782a786809d2591de1 | NMCPLindsay/CIT228 | /Chapter6/rivers.py | 525 | 4 | 4 | print("===============6-5==============")
boardman={
"River":"Boardman River",
"State":"Michigan"
}
rioGrande={
"River":"Rio Grande",
"State":"Texas"
}
republican={
"River":"Republican River",
"State":"Kansas"
}
Rivers=[boardman, rioGrande, republican]
print("*****Rivers and States*****")
for r in Rivers:
print(f"The {r['River']} flows through {r['State']}.")
print("****States****")
for r in Rivers:
print(f"{r['State']}")
print("****Rivers****")
for r in Rivers:
print(f"{r['River']}") |
eb14c6f63d265a02e4a73c4750167f0bac32d4f1 | biosharp-dotnet-labs/ParOpt | /paropt/command.py | 626 | 3.859375 | 4 | """Command functions for use with external optimization functions"""
def format_fn(frmat):
"""Create a commandline function that builds a command line from a format string
Upon binding on parameters, String.format will be called to create a command line call.
Example:
>>> fn = format_fn("echo {1} {0}")
>>> fn(["World", "Hello"])
'echo Hello World'
"""
def inner(xval):
"""Inner command line funtion"""
try:
return frmat.format(*xval)
except IndexError:
raise Exception("Format string has more fields than variables!")
return inner
|
679efbb086a7e48811276ffd1e098b51567cc37a | ole511/hello_world | /44翻转单词顺序列.py | 535 | 3.8125 | 4 | # -*- coding:utf-8 -*- 将字符串转换成序列再调整的方法
class Solution:
def ReverseSentence(self, s):
# write code here
if not s: return ""
if s.isspace():return s
temp=s.split()
for i in range(len(temp)//2):
temp[i],temp[-i-1]=temp[-i-1],temp[i]
return ' '.join(temp)
'''
python不支持对源字符串直接进行修改。例如s[:3]="123" s="123"+s[3:]都不能通过
所以我就没用先把字符串整体反转,再局部反转的方法。
'''
|
791c8ab37c6ad715df363fce87f30e8bbb80867b | gschen/sctu-ds-2020 | /1906101074-王泓苏/Day0324/test1.py | 2,121 | 4.15625 | 4 | class Node:
def __init__(self,value):
self.value = value #当前节点的值
self.next = None #下一个节点
class List:
def __init__(self):
#头节点
self.head = Node(-1)
#前插法创建单链表
def insert_before(self,data):
for i in data:
node = Node(i) #创建新节点
#判断头节点的下一个节点是否为空
if self.head.next is None: #如果为空,则将新节点加入到next
self.head.next = node
else:
node.next = self.head.next #将头节点的下一个节点加入到当前节点的next
self.head.next = node
#用尾插法创建单链表
def insert_tail(self,data):
tail = self.head.next #将头节点的下一个节点存在tail里
for i in data:
node = Node(i) #创建新节点
#判断尾结点是否为空
if tail is None: #如果为空,则将新节点加入到next
self.head.next = node
tail = node
else:
tail.next = node #将新节点加入到尾结点的next
tail = node
#打印单链表
def list_print(self):
node = self.head.next
while node:
print(node.value,' ',end='')
node = node.next
print('')
#删除链表中重复元素
def clear_repetition(self):
cur=self.head #将头节点的值赋给cur
while cur: #循环遍历
while cur.next and cur.value==cur.next.value: #判断头节点的值与下一个节点的值是否相同
cur.next=cur.next.next #将指针指向下一个节点(删除元素)
cur=cur.next
#第i个节点前插入值为value的节点
def list_element_add(self,i,value):
node_new=Node(value) #创建新节点
index = 0
node = self.head.next #向后挪一位,避开之前创建的头节点-1
while node: #找位置
index = index + 1
if index == i - 1: #在第i个节点前插入,要先找到第i-1个节点
break
node = node.next
if node is None:
return False
node_new.next = node.next #插入节点
node.next = node_new
|
fbebd19801e0a734ff607d4ff4bd3e472f22bcdb | marcusvinysilva/detetetive | /detetive.py | 740 | 3.75 | 4 | resposta1 = int(input("Você telefonou para a vítima?\nDigite 0 para não ou 1 para sim: "))
resposta2 = int(input("\nVocê esteve no local do crime?\nDigite 0 para não ou 1 para sim: "))
resposta3 = int(input("\nVocê mora perto da vítima?\nDigite 0 para não ou 1 para sim: "))
resposta4 = int(input("\nVocê devia para a vítima?\nDigite 0 para não ou 1 para sim: "))
resposta5 = int(input("\nVocê já trabalhou com a vítima?\nDigite 0 para não ou 1 para sim: "))
contador = resposta1 + resposta2 + resposta3 + resposta4 + resposta5
if contador == 5:
print("\nAssassino")
elif contador == 4 or contador == 3:
print("\nCúmplice")
elif contador == 2:
print("\nSuspeita")
else:
print("\nInocente")
|
72f23c50cf1f5edeccc7b11baab808f38f259ad4 | weezer/fun_scripts | /algo/208. Implement Trie (Prefix Tree).py | 1,781 | 3.9375 | 4 | class Node(object):
def __init__(self):
self.num = 0
self.hash_map = {}
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
current = self.root
for i in word:
if current.hash_map.get(i) is None:
current.hash_map[i] = Node()
current = current.hash_map.get(i)
current.num += 1
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
current = self.root
for i in word:
if current.hash_map.get(i) is None:
return False
current = current.hash_map.get(i)
if current.num != 0:
return True
return False
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
current = self.root
for i in prefix:
if current.hash_map.get(i) is None:
return False
current = current.hash_map.get(i)
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
if __name__ == "__main__":
s = Trie()
s.insert("aa")
s.insert("bb")
s.insert("ab")
s.insert("aa")
print s.root.hash_map['a'].hash_map['a'].num
print s.search("aa")
print s.startsWith("a") |
aa28e719ce2fe95114296f3448fd76b1a7843a2b | jonnytaddesky/python | /Strength HW/game_sticks.py | 678 | 3.75 | 4 | counter_sticks = int(input('Общее колличество палочек: '))
player_number = 1
while counter_sticks > 0:
choise = int(
input(f'Сколько возьмете палочек? Осталось палочек {counter_sticks}: '))
if choise > 3 or choise < 1:
print(f"Вы взяли {choise} палочек. Дозвонлено взять 1, 2 или 3")
continue
counter_sticks -= choise
print(f'Игрок номер {player_number} взял {choise} палочек')
if counter_sticks <= 0:
print(f'Игрок {player_number} проиграл.')
player_number = 1 if player_number == 2 else 2
|
9b1407e584e51e4e2e2672c69d7a7b38be4c9736 | koooge/leetcode | /1603/1603.py | 460 | 3.8125 | 4 | class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.park = [big, medium, small]
def addCar(self, carType: int) -> bool:
if self.park[carType - 1] > 0:
self.park[carType - 1] -= 1
return True
else:
return False
obj = ParkingSystem(1, 1, 0)
assert(obj.addCar(1) == True)
assert(obj.addCar(2) == True)
assert(obj.addCar(3) == False)
assert(obj.addCar(1) == False)
|
58f8d6803a9b4c10c0846a21de84af34941a3748 | gabriellaec/desoft-analise-exercicios | /backup/user_040/ch119_2020_03_23_22_42_43_666993.py | 181 | 3.671875 | 4 | from math import factorial
def fatorial(x):
math.factorial(x)
def calcula_euler(x,n):
euler=1
for y in range (1,n):
euler+=x**y/fatorial(y)
return euler |
345ecab190184efad54f4caa4e3a086c6b937ef6 | Audio10/Curso-Python | /Curso Basico de Python/saludos.py | 92 | 3.984375 | 4 | # -*- coding: utf-8 -*-
name = str(input('Whats your name? '))
print('Hola ' + name + '!') |
7bccf4f471dad7c60dd86ac0f2f5992ac94f8d9e | teppi1995/AtCoder | /GrandContest002/A-RangeProduct/solver.py | 452 | 3.765625 | 4 | import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
#logging.disable(logging.CRITICAL)
def main():
a, b = map(int, input().split())
logging.info("Hello!")
if a * b < 0:
print("Zero")
elif a > 0:
print("Positive")
else:
if (b - a + 1) % 2 == 1:
print("Negative")
else:
print("Positive")
if __name__ == "__main__":
main()
|
f6aecdc9cd8b1f8e81603aef97423d970bd9d369 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2228/60724/288297.py | 176 | 3.796875 | 4 | target=abs(int(input()))
i=0
while i*(i+1)//2<target:
i+=1
if i*(i+1)//2==target or (i*(i+1)//2-target)%2==0:
print(i)
elif i%2==0:
print(i+1)
else:
print(i+2)
|
40a371135f4b835b521f73a44616f04314900406 | Awesome-Kirill/edu | /stepik/cal.py | 815 | 4.1875 | 4 |
arg_1 = float(input())
operand = input()
arg_2 = float(input())
'''
Поддерживаемые операции: +, -, /, *, mod, pow, div, где
mod — это взятие остатка от деления,
pow — возведение в степень,
div — целочисленное деление.
'''
def calc(arg1,arg2,ope):
try:
func_dict = {'+': lambda x, y: x + y,
'-': lambda x, y: x-y,
'/': lambda x, y: x/y,
'*': lambda x, y: x*y,
'mod': lambda x, y: x%y,
'pow': lambda x, y: x**y,
'div': lambda x,y: x//y
}
result=func_dict[ope](arg1,arg2)
except ZeroDivisionError:
result = 'Деление на 0!'
except KeyError:
result = 'Операция не потдерживается'
finally:
return result
print(calc(arg_1,arg_2,operand))
input()
|
11ac1dcd15a75c292d22fa52b9edf42d192ec5d2 | esther-soyoung/Coding-Challenge | /StackQueue/truck.py | 683 | 3.5 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
on_bridge = deque([])
time = 0
for i in truck_weights:
while True:
time += 1
# one truck passed the bridge
if len(on_bridge) == bridge_length:
on_bridge.popleft()
# put truck on the bridge
if ((len(on_bridge) + 1) <= bridge_length) and (sum(on_bridge) + i <= weight):
on_bridge.append(i)
break
# wait one timestamp
else:
on_bridge.append(0)
# wait for the last truck to pass
time += (bridge_length - 1)
return time + 1
|
80856e66a4a52a1594302aab6ca9bc540ea41b3d | GuiJR777/INE5603-01238A-20201---Programa-o-Orientada-a-Objetos-I | /strings/valida_cpf.py | 1,785 | 3.78125 | 4 | # Funções
def higienizador(string):
string = string.lower()
string = string.replace(' ','')
string = string.replace(',','')
string = string.replace('-','')
string = string.replace('.','')
return string
def checa_igualdade(lista):
repetidos = 0
for n in range(len(lista)):
if lista[0] == lista[n]:
repetidos+=1
else:
pass
if repetidos >= len(lista):
resposta = True
else:
resposta = False
return resposta
def modulo_11(numero):
numero.reverse()
soma = 0
peso = 2
for n in numero:
soma = soma + (int(n)*peso)
peso += 1
resto = soma % 11
if resto > 11:
dv = resto - 11
else:
dv = 11 - resto
if dv >= 10:
dv = 0
return dv
def verifica_digito(cpf):
todos_numeros = list(cpf)
nove_numeros = []
dois_ultimos = []
if len(todos_numeros) != 11:
resposta = False
else:
igual = checa_igualdade(todos_numeros)
if igual == True:
resposta = False
else:
for i in range(9):
nove_numeros.append(todos_numeros[i])
dois_ultimos.append(todos_numeros[9::])
dois_ultimos = f'{dois_ultimos[0][0]}{dois_ultimos[0][1]}'
primeiro_digito = modulo_11(nove_numeros)
nove_numeros.reverse()
nove_numeros.append(primeiro_digito)
segundo_digito = modulo_11(nove_numeros)
digito_validador = f'{primeiro_digito}{segundo_digito}'
if digito_validador == dois_ultimos:
resposta = True
else:
resposta = False
return resposta
cpf = higienizador(input())
resposta = verifica_digito(cpf)
print(resposta)
|
a847069fb5fc7b299857c1b42dd804f3af420db4 | thetheos/BAC1INFO1 | /mission7/Q6.py | 315 | 3.9375 | 4 | l = [{"City": "Bruxelles", "Country": "Belgium"}, \
{"City": "Berlin", "Country": "Germany"}, \
{"City": "Paris", "Country": "France"}]
def get_country(l, name):
for ct in l:
if ct["City"] == name:
return ct["Country"]
return False
print(get_country(l,"Toronto")) |
ce22776e7e8a3baea05c7a27c0b63888fb4a291c | akilmarshall/Fractals-and-Friends | /chaos_game/polygons.py | 4,440 | 4.28125 | 4 | '''
This file contains functions that create and concern polygons
Polygons are defined as a list of vertices
'''
from math import pi, cos, sin
from random import choice
import pygame
class Polygon():
"""Polygon implementaion"""
def __init__(self, h, k, r, n):
"""TODO: to be defined.
:h: x-coord of the polygon's center
:k: y-coord of the polygon's center
:r: internal radius of the polygon
:n: number of vertices
:phi: rotational offset from the positive x-axis
"""
self.h = h
self.k = k
self.r = r
self.n = n
self.vertices = list()
self.generate()
def generate(self):
for i in range(self.n):
theta = (((2 * pi) / self.n) * i) - pi/2
x = self.h + (self.r * cos(theta))
y = self.k + (self.r * sin(theta))
self.vertices.append((int(x), int(y)))
def update_r(self, r):
self.r = r
self.vertices.clear()
self.generate()
def __repr__(self):
return f'Polygon({self.h}, {self.k}, {self.r}, {self.n})'
def __len__(self):
return self.n
def __contains__(self, item):
x, y = item
j = self.n - 1
c = False
for i in range(self.n):
if ((self.vertices[i][1] > y) != (self.vertices[j][1] > y)) and (x < self.vertices[i][0] + (self.vertices[j][0] - self.vertices[i][0]) * (y - self.vertices[i][1]) / (self.vertices[j][1] - self.vertices[i][1])):
c = not c
j = i
return c
def random_point(self):
'''
returns a random point interior to the polygon
'''
def random_point_near_polygon(p: Polygon):
max_x = max([x for (x, y) in p.vertices])
max_y = max([y for (x, y) in p.vertices])
min_x = min([x for (x, y) in p.vertices])
min_y = min([y for (x, y) in p.vertices])
x = choice(range(min_x, max_x + 1))
y = choice(range(min_y, max_y + 1))
return (x, y)
while True:
a = random_point_near_polygon(self)
if a in self:
return a
# def translate(V: list, p) -> list:
def translate(p, t) -> Polygon:
'''
t is a point in R^2
p is a Polygon
t is a description of the translation
'''
o = Polygon(p.h, p.k, p.r, p.n) # ghetto deep copy
tx, ty = t
tx = int(tx)
ty = int(ty)
o.vertices = [(x + tx, y + ty) for x, y in p.vertices]
return o
def scale(p: Polygon, s: float) -> Polygon:
'''
Each point in p will be scaled by s
'''
o = Polygon(p.h, p.k, s * p.r, p.n)
return o
def rotate(p: Polygon, phi: float) -> Polygon:
'''
Rotate the polgon p by phi radians
'''
o = Polygon(p.h, p.k, p.r, p.n)
for i in range(p.n):
theta = (((2 * pi) / p.n) * i) - pi/2
x = p.h + (p.r * cos(theta + phi))
y = p.k + (p.r * sin(theta + phi))
o.vertices[i] = (int(x), int(y))
o.vertices = [(int(x), int(y)) for x, y in o.vertices]
return o
def shear(p: Polygon, m: float) -> Polygon:
'''
Shear the polygon p with shear factor m
'''
o = Polygon(p.h, p.k, p.r, p.n)
o.vertices = [(x + (m * y), y) for x, y in p.vertices]
o.vertices = [(int(x), int(y)) for x, y in o.vertices]
return o
def reflect(p: Polygon, m: float, b: float) -> Polygon:
'''
reflect polygon p across the line y = mx + b
'''
def reflect_x(x, y):
return (((1 - m**2) * x) + (2 * m * y) - (2 * m * b)) / (m**2 + 1)
def reflect_y(x, y):
return (((m**2 - 1) * y) + (2 * m * x) - (2 * b)) / (m**2 + 1)
o = Polygon(p.h, p.k, p.r, p.n)
o.vertices = [(reflect_x(x, y), reflect_y(x, y)) for x, y in p.vertices]
o.vertices = [(int(x), int(y)) for x, y in o.vertices]
return o
if __name__ == "__main__":
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
red = (255, 0, 0)
canvas_width = 500
canvas_height = 500
canvas = pygame.display.set_mode((canvas_width, canvas_height))
canvas.fill(black)
pixels = pygame.PixelArray(canvas)
# code here
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
|
15cb4eaa06281d656b5063ddebf7b19b7da4b9de | sukritishah15/DS-Algo-Point | /Python/quicksort.py | 1,790 | 4 | 4 | """ Python program for implementation of Quicksort Sort
This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot"""
def partition(arr, low, high):
i = (low-1) # index of smaller element
pivot = arr[high] # pivot
for j in range(low, high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
# a[] is the array to be sorted,
# low is the Starting index,
# high is the Ending index
# Function to do Quick sort
def quickSort(a, low, high):
if len(a) == 1:
return a
if low < high:
# pi is partitioning index
pi = partition(a, low, high)
quickSort(a, low, pi-1)#this is partition on left side
quickSort(a, pi+1, high)#this is partition on right side
n=int(input('enter the length of array '))
print('enter the elements of the array ')
a=[]# a new dynamic array
for i in range(n):
a.append(int(input()))
print('unsorted array is')
print(a)
quickSort(a, 0,len(a)-1)
print("Sorted array is:")
print(a)
"""
Input/Output
enter the length of array 5
enter the elements of the array
10
6
8
2
4
unsorted array is
[10, 6, 8, 2, 4]
Sorted array is:
[2, 4, 6, 8, 10]
SPACE COMPLEXITY:
Solution: Quicksort has a space complexity of O(logn), even in the worst case.
TIME COMPLEXITY
time complexity in worst case is O(n^2).
"""
|
ad460ff898942ce930655ce4109fe1b53acdc7e4 | dr-manhattan/ai_planning | /missionaries_cannibals.py | 2,513 | 3.71875 | 4 | # License: http://opensource.org/licenses/MIT
# complements of Max Kesin
from collections import namedtuple
Side = namedtuple('Side', ['missionaries', 'cannibals', 'destination'])
sideFrom = Side(missionaries=3, cannibals=3, destination=False)
sideTo = Side(missionaries=0, cannibals=0, destination=True)
start_state = (sideFrom, sideTo)
def is_win(state):
return state[0].destination and state[0].missionaries==3 and state[0].cannibals==3
def dead_side(side):
return (side.missionaries > 0 #some yummy missionaries to eat
and side.cannibals > side.missionaries)
def dead_end(state):
return dead_side(state[0]) or dead_side(state[1])
def boat_trip(state, missionaries, cannibals):
""" state[0] is always the side with the boat """
return (
Side(missionaries=state[1].missionaries+missionaries,
cannibals=state[1].cannibals+cannibals,
destination=state[1].destination),
Side(missionaries=state[0].missionaries-missionaries,
cannibals=state[0].cannibals-cannibals,
destination=state[0].destination)
)
tried_states = set([])
def print_state(state):
if state[0].destination:
print list(reversed(state))
else:
print list(state)
def search_trips(state):
side_from = state[0]
max_missionaries = min(side_from.missionaries, 2)
max_cannibals = min(side_from.cannibals, 2)
for m in range(max_missionaries+1):
for c in range(max_cannibals+1):
if m+c > 0 and m+c <= 2:
new_state = boat_trip(state, m, c)
if new_state in tried_states: continue
tried_states.add(new_state)
if is_win(new_state):
print 'win!'
print_state(new_state)
print 'did m=', m, 'c=', c, 'to side dest=', new_state[0].destination
return True
elif dead_end(new_state):
pass #print 'dead_end'
else:
if search_trips(new_state):
if new_state[0].destination:
print list(reversed(new_state))
else:
print list(new_state)
print 'did m=', m, 'c=', c, 'to side dest=', new_state[0].destination
return True
else:
return False
search_trips(start_state)
|
6ab5075acf9a61745bb24e5c5cd47ea317eed9f9 | mrraj5911/python- | /a1.py | 199 | 3.96875 | 4 | a=input("enter the string: ").strip()
b=['raj','rana','bantu','thakur']
if a in b:
print(a,"is here")
else:
print(a,'not here')
option=input("to get more search type Y ")
if option!='Y':
continue
|
30fd21240ed6955fd16af4e294e6c0c4eadabeef | stewSquared/project-euler | /p062.py | 698 | 4.03125 | 4 | """The cube, 41063625 (345^3), can be permuted to produce two other
cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the
smallest cube which has exactly three permutations of its digits which
are also cube.
Find the smallest cube for which exactly five permutations of its
digits are cube."""
from itertools import count
cubePerms = dict()
for cube in map(lambda n: n**3, count()):
cubeKey = "".join(sorted(str(cube)))
if cubeKey not in cubePerms: cubePerms[cubeKey] = []
cubePerms[cubeKey].append(cube)
# CAVEAT: Problem asks for exactly 5, but this works
if len(cubePerms[cubeKey]) >= 5:
ans = min(cubePerms[cubeKey])
break
print(ans)
|
a5bd15a865b610ec3891caab92d32d843d0ddb4b | entrekid/algorithms | /basic/11931/sort_reverse.py | 209 | 3.59375 | 4 | import sys
input = sys.stdin.readline
num = int(input().strip())
num_list = []
for _ in range(num):
num_list.append(int(input().strip()))
num_list.sort(reverse = True)
for elem in num_list:
print(elem) |
c80297399367c0404f5e2cd0fcb12f8abefee3af | Jsemko/project_euler_solutions | /Euler131.py | 382 | 3.640625 | 4 | def primes_under(m):
primes = [2]
for i in range(3,m,2):
if (i + 1)% 100000 == 0: print('done ' + str(i))
j = 0
while j < len(primes) and i >= primes[j]**2:
if i % primes[j] == 0: break
j+=1
else: primes.append(i)
return primes
primelist = primes_under(int(1000000) + 1)
print(primelist[-1])
|
df61e6b7ad221bfd3c1d4f9607ad8a749abe05d1 | ehdqoddl6/coding-test | /dataSturcture/queue.py | 214 | 3.703125 | 4 |
from collections import deque
queue = deque()
queue.append(5)
queue.append(2)
queue.append(3)
queue.append(7)
queue.pop()
#queue.append(1)
#queue.append(4)
#queue.popleft()
print(queue)
print(queue.reverse()) |
a1e59e159e84e737f3ce33da970adf8af694db37 | TrellixVulnTeam/Python-Projects_4PU5 | /Linear Regression/bestfitline.py | 782 | 3.53125 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
xs =np.array([1,2,3,4,5,6],dtype=np.float64)
ys= np.array([5,4,6,5,6,7],dtype=np.float64)
def best_fit_slope():
num = (mean(xs)*mean(ys))-mean(xs*ys)
denom = (mean(xs)*mean(xs))- mean(xs*xs)
m = num/denom
c = mean(ys)-(m*mean(xs))
return m,c
def squared_error(y_orig,y_line):
return sum(((y_orig-y_line)**2))
def coeff_dete(y_orig,y_line):
y_mean_line = [mean(y_orig) for y in y_orig]
sq_err_regr = squared_error(y_orig,y_line)
sq_err_y_mean = squared_error(y_orig,y_mean_line)
return 1 - (sq_err_regr/sq_err_y_mean)
m,c= best_fit_slope()
line = [(m*x)+c for x in xs]
print(coeff_dete(ys,line))
plt.scatter(xs,ys)
plt.plot(xs,line)
plt.show()
|
29cfe6538743040903621c071fa0a64078e8f7b7 | ANAMIKA1410/DSA-Live-Python-March-2021 | /lecture-10/pivot.py | 297 | 3.6875 | 4 | def pivot(nums, start, end):
p = end
j = start
for i in range(start, end):
if nums[i] > nums[p]:
swap(nums, i, j)
else:
j += 1
swap(nums, p, j)
return j
def swap(nums, i, j):
t = nums[i]
nums[i] = nums[j]
nums[j] = t
|
dc54e2c8d3e9a4eb0a0a49140c6d83def21aac75 | Zhengrui-Liu/FireAlarmingSysCDA | /src/main/python/programmingtheiot/cda/sim/HvacActuatorSimTask.py | 1,619 | 3.59375 | 4 | #####
#
# This class is part of the Programming the Internet of Things project.
#
# It is provided as a simple shell to guide the student and assist with
# implementation for the Programming the Internet of Things exercises,
# and designed to be modified by the student as needed.
#
import logging
import random
from programmingtheiot.data.ActuatorData import ActuatorData
from programmingtheiot.cda.sim.BaseActuatorSimTask import BaseActuatorSimTask
import programmingtheiot.common.ConfigConst as ConfigConst
class HvacActuatorSimTask(BaseActuatorSimTask):
"""
Shell representation of class for student implementation.
"""
def __init__(self):
"""
Constructor:
"""
super(HvacActuatorSimTask, self).__init__(actuatorName = ConfigConst.HVAC_ACTUATOR_NAME, actuatorType = ActuatorData.HVAC_ACTUATOR_TYPE, simpleName = "HVAC")
def activateActuator(self, val: float) -> bool:
"""
Turn actuator on:
@param val: float
@return: bool
"""
logging.info("Emulating HVAC actuator ON:")
super().activateActuator(val)
print("*******")
print("* O N *")
print("*******")
print("HVAC VALUE ->", val)
print("=======")
def deactivateActuator(self) -> bool:
"""
Turn actuator off:
@return: bool
"""
logging.info("Emulating HVAC actuator OFF:")
super().deactivateActuator()
print("*******")
print("* OFF *")
print("*******")
def updateActuator(self, data: ActuatorData) -> ActuatorData:
"""
Renew the latest actuator data
@param data: ActuatorData
@return: ActuatorData
"""
if super().updateActuator(data) == True:
return self.latestActuatorData
|
5a14e5595cea4405010550b90e718cc4fdb07e29 | roodiaz/Curso-Python | /ejercicios/video17_ejercicio02.py | 250 | 4 | 4 | num1 = int(input("ingrese numero entero positivo: "))
suma=0
while(num1>0):
suma+=num1
num1 = int(input("ingrese numero entero positivo: "))
print("\nnumero negativo ingresado, fin del programa")
print("la suma de numeros ingresados es de ",suma) |
026ab609b1083a1f49cc83d7bada532ff3eaa8f8 | sny-tanaka/practicePython | /Practice/ProjectEuler/Problem17.py | 1,277 | 3.6875 | 4 | # coding: utf-8
'''
1 から 5 までの数字を英単語で書けば one, two, three, four, five であり, 全部で 3 + 3 + 5 + 4 + 4 = 19 の文字が使われている.
では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば, 全部で何文字になるか.
'''
def num2str(n): #数字を英単語に変換
units = ['','one','two','three','four','five','six','seven','eight','nine']
teens = ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tys = ['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
hund = 'hundred'
a = ''
b = ''
c = ''
u = n % 10 # 1の位
a = units[u]
n = n // 10
if n > 0:
t = n % 10 # 10の位
if t == 1:
a = ''
b = teens[u]
else:
b = tys[t]
n = n // 10
if n > 0:
h = n % 10 # 100の位
if a == '' and b == '':
c = units[h] + hund
else:
c = units[h] + hund + 'and'
return c + b + a
def main():
s = 0
for i in range(1, 1000):
n = num2str(i)
s += len(n)
s += 11
print(s)
if __name__ == '__main__':
main()
|
2dab900df30c1e565226154a5b91cc91ceae24ad | Sgggser/python_homework | /hw2.py | 134 | 3.703125 | 4 | a = 1
b = 2
result = (a*a + b*b) %2
print('Для значений a=%g b=%g результат функции: %g' % (a, b, result)) |
22586deaa41d4c8049d4911a2ab68293699e6aed | ntrang086/python_snippets | /search_optimize/common_ints.py | 292 | 4.0625 | 4 | """Find the common elements of 2 int arrays.
"""
def common_ints(array_1, array_2):
return set(array_1).intersection(set(array_2))
if __name__ == "__main__":
array_1 = [1, 4, 2, 3, 3]
array_2 = [5, 4, 6, 3, 3]
# Should return 3 and 4
print (common_ints(array_1, array_2)) |
b395b64be6b1dc5040a23c83dafb0243d4bc2130 | CodyDBrown/Physics-331 | /Physics 331/Textbook Programs/Chapter 4/euler_1d_3.py | 1,297 | 3.75 | 4 | def euler_1d_3(y0, t0, tf, dt, deriv_func):
from numpy import arange, zeros
"""
This is a third attempt at making euler_1d a little easier to work with. Inputs are the same as euler_1d_2
but the 'problem' with euler_1d_2 is that it didn't use a numpy array for the 'y' values. This used a np.array
This is acctually surprisingly slower than either of the other two euler_1d's. with a run time of
%timeit euler_1d_3(0,0,10,1,sky_diver)
10 µs ± 141 ns
Input
----------
y0: Starting 'y' value
t0: Starting time
tf: Final time
dt: Size of the step I want to take.
deriv_func: Function that I am trying to numerically solve.
Output
----------
y: Array of values evaluated at each point in time. Should looke like
y = [y(0), y(1), y(2), ... , y(n_steps)]
"""
t = arange(t0, tf, dt) #starts and t0 and makes steps of size dt. Does not get to tf. It gets as
#Close as it can to tf, but will always stop short of it.
t_foo = len(t)
y = zeros(t_foo)
for n in range(t_foo-1):
f = deriv_func(y[n], t[n]) #Evaluate the function f(y,t)
y[n+1] =(y[n] + dt * f) #This is the Euler's method part.
return y,t |
16ee3a97ac173c2e5d3be96c04c4c5d9e57e8c78 | sanmen1593/InteligenciaArtificial | /ColoniaDeHormigas/ColoniaDeHormigas.py | 2,785 | 3.609375 | 4 | __author__ = 'Santiago Mendoza Ramirez'
import math
import random
import ast
class Coordenadas:
def __init__(self, x, y):
self.x = x
self.y = y
def distancia(self, punto):
ValorX = abs(self.x - punto.x)
ValorY = abs(self.y - punto.y)
formula = math.pow(ValorX, 2) + math.pow(ValorY, 2)
return math.sqrt(formula)
class RecorrerCoordenadas:
def __init__(self):
self.Ciudades = []
self.MatrizDistancia = []
self.MatrizDistanciaI = []
self.MatrizFeromonas = []
#Llenamos el array Ciudades con las coordenadas de cada ciudad provenientes del archivo
with open('AgenteViajero.txt') as file:
for line in file:
words = line.split()
x = ast.literal_eval(words[0])
y = ast.literal_eval(words[1])
#x = float(words[0])
#y = float(words[1])
p = Coordenadas(x, y)
self.Ciudades.append(p)
self.CantCiudades=len(self.Ciudades) #Variable para saber el numero de ciudades del problema
# Llenamos la matriz de distancia y la matriz de distancia inversa. Creamos la matriz de feromonas en 0 cada posicion
# Utilizamos una array en el que cada miembro es a su vez otro array para crear las matrices.
for i in self.Ciudades:
DistanciaFila = []
DistanciaFilaI = []
FeromonasArray = []
fila = self.Ciudades.index(i)
CoordenadaPivote = self.Ciudades[fila]
for j in self.Ciudades:
col=self.Ciudades.index(j)
DistanciaL = CoordenadaPivote.distance(self.Ciudades[col])
DistanciaFila.append(DistanciaL)
FeromonasArray.append(0)
if DistanciaL == 0:
DistanciaFilaI.append(0)
else:
DistanciaFilaI.append(1/DistanciaL)
self.MatrizDistancia.append(DistanciaFilaI)
self.MatrizDistanciaI.append(DistanciaFilaI)
self.MatrizFeromonas.append(FeromonasArray)
def HormigasExploradoras(self, numeroHormigas):
j=0
#Mandamos hormigas exploradoras: Hacen un recorrido aleatorio de todas las ciudades.
#El numero de hormigas lo decide el usuario, es decir, es recibido en el "main".
while(j<numeroHormigas):
for i in range(0,self.CantCiudades):
RecorridoHormiga = []
ciudad = self.Ciudades(random.randint(0,self.CantCiudades))
while(RecorridoHormiga.count(ciudad) != 0):
ciudad = self.Ciudades(random.randint(0,self.CantCiudades))
RecorridoHormiga.append(ciudad)
j+=1
|
d120c3ad58eb5d79044a0af706debe452d4bdabf | sivatmam/CCPS109 | /Problems/test.py | 209 | 4.03125 | 4 | import itertools
def is_ascending_generator(n):
for i in range(n):
for seq in itertools.permutations(range(n)):
yield [seq]
for j in is_ascending_generator(3):
print(j, end ="|||") |
eb7030ce69e68296b765ed0c8d32a08a00b782db | iitmaniac/The_Joy_Of_Computing_Using_Python | /Solve_the_Jumbled_word.py | 3,493 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 15 11:51:04 2019
@author: Shrikant Tambe
"""
"""
Here we are developing a game to find the answer of the jumbled word.
Here we are taking an input from user, and checks with the solution of the jumbled word.
If it is correct then a point is added to the player's score. Same goes with another player.
This keeps on happening until they wish to play the game.
"""
import random
def choose():
dictionary = ['Literally','Irregardless','Whom', 'Colonel', 'Nonplussed', 'Disinterested', 'Enormity', 'Lieutenant', 'Unabashed']
selected = random.choice(dictionary)
return selected
def jumble(correctword):
jumbledword="".join(random.sample(correctword,len(correctword)))
return jumbledword
def thanks(a1,a2,b1,b2):
print(a1 + " your total score is: " + str(b1) +" and " + a2 + " your total score is: " + str(b2))
print()
print()
if(b1 > b2):
print("Congratulations! " + a1 + " is the winner.")
print("Thank you for playing. Hope to see you soon!")
elif (b1 == b2):
print("This is a tie! Match is Draw.")
print("Thank you for playing. Hope to see you soon!")
else:
print("Congratulations! " + a2 + " is the winner.")
print("Thank you for playing. Hope to see you soon!")
def play():
p1 = input("Player 1, Please enter your name.\n")
print()
p2 = input("Player 2, Please enter your name.\n")
print()
print()
print()
print("*" * 20)
point1 = 0
point2 = 0
turn = 0
chance = 1
while(chance == 1):
if(turn % 2 == 0):
print()
print("Your chance,",p1)
print()
word = choose()
jumbled = jumble(word)
print(jumbled)
guess = input("Hey! Guess the original word: \n")
if(guess == word):
point1 = point1 + 1
print()
print("Congratulations! Correct answer. Your total score is:", point1)
print()
print("*" * 20)
else:
print()
print("Incorrect Answer! The correct answer was " + word)
print()
print("*" * 20)
else:
print()
print("Your chance,",p2)
print()
word = choose()
jumbled = jumble(word)
print(jumbled)
guess = input("Hey! Guess the original word: \n")
if(guess == word):
point2 = point2 + 1
print("Congratulations! Correct answer. Your total score is:", point1)
print()
print("*" * 20)
else:
print("Incorrect Answer! The correct answer was " + word)
print()
print("*" * 20)
turn = turn + 1
# print()
# print()
chance = int(input("Do you want to Continue the game? Press '0' to exit and Press '1' to continue. \n"))
print()
print("$" * 20)
if(chance == 0):
print()
print()
chance = 0
thanks(p1,p2,point1,point2)
print()
print("#" * 20)
break
play()
|
f2caef803fec6dc7b0898dc41ae5a35a03d7a652 | harman666666/Algorithms-Data-Structures-and-Design | /Algorithms and Data Structures Practice/LeetCode Questions/Algorithms Class Coursework/A9ShortestWordPath.py | 23,318 | 3.703125 | 4 | '''
This assignment has three parts: a written part (Q1), a programming part (Q2), and an
optional written bonus part (Q3). You need to hand them in separately as stated above.
The goal is to design and implement (that is, write a working program for) a shortest
path algorithm to solve a problem about word chains.
Please read these instructions carefully before posting any questions to Piazza. We hope
all clarication questions you have will already be answered here. If not, please read previous
questions on Piazza before posting new ones.
We will say two words (strings) x and y are linked from x to y if
you can get y from x by deleting exactly one letter from x (a \deletion"); or
you can get y from x by inserting exactly one new letter (an \insertion"); or
you can get y from x by interchanging two adjacent letters (this is called a twiddle); or
you can get y by reversing the order of the letters in x ( a \reversal").
For example
=> loose is linked to lose because you can delete one of the o's in loose to get lose;
=> cat is linked to cart because you can insert the letter r;
=> alter is linked to later because you can get one from the other by a twiddle at positions 1 and 2;
=> drawer is linked to reward because you can get one from the other by a reversal.
A word chain is a sequence of words w1;w2; : : : ;wn, where for each i with 1 <= i < n we
have that wi is linked to wi+1. We say the chain links w1 with wn. For example,
spam; maps; map; amp; ramp
is a word chain because
spam and maps are reversals;
maps goes to map by a deletion;
map goes to amp by a twiddle;
amp goes to ramp by an insertion.
The cost of a word chain is obtained by summing the cost of each link of the chain,
where
a deletion costs 3;
an insertion costs 1;
a twiddle costs 2;
a reversal of a n-letter word costs n.
If none of these cases apply, you can say that the link has infinite cost.
Thus, for example, the individual costs of the chain above are given as follows:
spam -> 4 -> maps -> 3 map -> 2 -> amp -> 1 -> ramp
and the total cost of the chain is 4 + 3 + 2 + 1 = 10.
In the (very rare) case where two words satisfy two distinct criteria, like tort and trot,
the cost of the link is the lower of the two costs. Here it would be 2.
Given a word list of valid words, and two words u; v from the word list, the word chain
problem is to nd the lowest-cost chain linking u and v using only words from the word list.
The Assignment
The goal is to create a working program to solve the word chain problem in one of C++,
Java, or Python.
'''
# ANSWER TO QUESTION 1 #########################################################
##################################################################################
'''
Q1. [10 marks] This is the written part. Hand it in via Crowdmark.
(a) Discuss how to efficiently solve the word chain problem using a graph algorithm. What
do the vertices represent? What do the edges represent? How are they weighted? In what
form will you store the graph? Is it directed or undirected? Do you expect the graph to be
sparse or dense for a real word list, such as an English dictionary? Do you expect it to be
connected? And, most importantly, how can you efficiently create the graph from a given
word list?
Hint: if you are careful and think about the problem, you can probably create the graph
from a word list rather efficiently. Probably the obvious idea of comparing each pair of words
in the word list, in order to determine the weight of the edge connecting them, is not the bestmaqq
approach. It should be possible to create the graph in o(n^2) steps (so faster than O(N^2) ), where n is the number of
words, but you might have to make some assumptions about what the word list looks like.
For this part, you are welcome to use techniques like tries, hashing, dictionaries, and so
forth. Make any reasonable assumptions about the running time of anything you use, and
state them. For example, it's reasonable to assume that hashing a string of t letters costs
O(t) time.
We are looking for high-level description here. There is no need to produce pages and
pages of pseudocode.
'''
## PART A ANSWER:
'''
The vertices in the graph will represent each individual word. An edge between 2 vertices will
indicate that the word can be transformed into another word using one of the 4 transformations.
The weight of the edge will be the cost of the transformation (if the transformation can be done in
multiple ways, take the lowest cost of the 4 transformations). In other words the edges are
weighted by the cost of the transformation. The graph will be undirected because the 4 rules
that can be followed to transform one word into another have inverses.
PROOF:
The deletion rule has the addition rule as the inverse and vice versa.
The reverse rule has the reverse rules as its inverse transformation.
The twiddle rule can be inversed by repeating the twiddle on the same 2 letters.
In other words, if a vertex is connected to another vertex, then they can transform into each other
using a rule or the inverse rule (all 4 have inverse rules), so the edges will be undirected in the graph.
For a real word list such as the english dictionary, the graph will be very dense for small words
such as "cat", because there are lots of 3 letter words that can be derived out of cat. For much longer words,
the graph will be sparse because they will be difficult to transform into other words since longer words have more
permutations of characters that reduces the likelihood of 1 particular permutation (english word)
transforming into another one.
The graph will not be connected since the english language has words that are very long and peculiar
such as pneumonoultramicroscopicsilicovolcanoconiosis which does not connect to other words using
the 4 possible transformations.
To efficiently create the graph from a word list,
we need to find all the words that can be transformed to another word using the 4 rules.
We will use a map of lists.
Every word is a key in the map of lists.
The list contains neighbours, and the key for the map is the vertex to those neighbours.
This representation is similar to the adjacency list representation of graphsself.
edge_weights will be represented as a map of a map of values.
The first key is the start vertex, the second key is the end vertex, and the
value is the edge weight between the start and end vertices.
In this way, you can check if an edge exists in a graph in O(1) average time
by indexing into the first map, with the start vertex, indexing into the returned map
with the end vertex, and checking if the value is an integer, or does not exist.
If it does not exist, the edge is not in the graph.
We can use the graph to check if a word in the dictionary exists
by looking up the word in the map of lists, and checking if it exists in that map.
This is a hash operation and can be done in O(t) time where t is the number of characters
in the word and O(1) average case search.
To build the graph, start by taking every word in the dictionary,
hashing it, and storing it as a key for the map of lists. The value will be
an empty list.
At a high level, go through every word in the dictionary,
and manipulate it (using all 4 transformations, or 3 as discussed below)
and check if its in the graph.
If it is, add the undirected edge to the graph. (So add two directed edges)
There are 4 transformations to consider and their runtimes (and if the transformation is valid, add the edge):
1) The addition rule does not need to be checked when looking at words.
You can use the deletion rule on every word. If a deletion of a character in a word matches a word in the
graph, then add the edge for deletion. Additionally, add the edge in the reverse direction for the insertion rule.
2) To check for reversals, you can reverse the string and check if it is in the set. If it is, you can add
an undirected edge. (So 2 edges to the graph).
3) For twiddle, you can look at all possible twiddles for a word, then check if the twiddled word is in the
graph. If it is, add the undirected edge (So 2 edges)
For transformation 2 and 3, check if the reversed word, or the twiddled word
does not transform into itself. If it does, then dont add the edge.
Additionally, twiddling and reversing can cause the case where two words satisfy
the same criteria for transformation. Such as tort, and trot. In our algo, we check for this
by looking up the edge in the edge_weights graph in O(1) time and checking if the edge exists.
If the edge exists, assign the weight in the edge_weights graph as
the smaller of the current weight and the weight we are considering.
FINALLY:
This is faster than comparing all words to all other words, because the above 3 transformations
are bounded by the number of letters in a word instead of the total number of words. If we assume
the words are english words, they wont get too long. Further runtime analysis done below.
'''
'''
(b) Next, explain how you can efficiently search the graph to find the solution to the word
chain problem. Here you can assume the graph has been created, and you are given two
words and want to find the lowest-weight chain linking them, or report that there is no such
chain.
What graph algorithm is appropriate? These choices are for you to decide and explain.
Here you should use one of the shortest-path algorithms we've covered.
There's no need to provide pseudocode (unless you want to). Explain your ideas in
English. Provide examples (if they are useful). Be sure to give as much detail as necessary
to convince a skeptical TA.
PART B ANSWER########################################################################:
Djikstra's algorithm is most suited and most performant for the problem. Djikstra's finds
the shortest path from one vertex to all others, in O(|E| + |V|log|V|) time. BFS would not
work efficiently because the paths have weights and you would have to break up paths longer
than 1 unit into connected 1 unit paths. Floyd Warshall is too powerful, and would find the
shortest paths between all vertices but we do not need to do that for this question. For this
question we only need to find the shortest path from one vertex to another. If the path had
negative weights, we would have to use the less performant Bellman Ford single source shortest
path algorithm but since the edges between words are all positive, we can use Dijkstra's algorithm.
'''
'''
(c) Finally, discuss the running time of both (i) creating the graph from the word list and
(ii) given two words, finding the lowest-cost chain connecting them (if it exists).
When you do your analysis, be sure to specify if you're obtaining a rigorous worst-case
bound, or just a \heuristic" bound based on what you think happens in a typical example.
You can express your running time in terms of the appropriate parameters of the word list,
which might include n, the total number of words in the word list, and q, the total number
of symbols of all words in the word list, and m, the maximum length of a word in the word
list.
We will be generous in marking this problem.
Runtime of creating the graph is:
Building the graph :
Hashing a string of t letters has cost t, so creating the graph will in O(Tn)
where T is the number of words, and n is the length of longest word in the dictionary.
To check that a string is in the set, hash the string and check if the hash
value matches a hash value in the set. With a good hash function, on average, this will be O(t)
where t is the length of the string. We will consider this
as the runtime when checking strings in the set.
All 3 transformations we do to check if an vertex is connected to another
vertex is bounded by the number of characters in the word.
We go through all the words and do the following:
check if the reversed word is in the graph.
Reversing is O(T) and checking if its in the graph is O(T) so worst case O(T).
We delete every character in the string, and check if that string is in the graph.
Deleting the character and forming a string is O(T) and checking it is in the graph
is O(T).
Since we delete every possible version of the string. This check becomes
O(T^2).
We twiddle every adjacent pair of characters in the string. This is similar to
the above deletion runtime. Twiddling and forming a string is O(T). Checking in graph is O(T).
Since we do this for all adjacent pairs and there are T-1 adjacent pairs,
then runtime for this is O(T^2).
Therefor graph creation is O(T^2) * Number of Words which is O(N*T^2)
Runtime of of finding the lowest-cost chain connecting 2 words is:
O(|E| + |V|log|V|) which is the worst case bound for Djikstra's algorithm
using a min fibonnaci heap.
For our problem this runtime becomes O(|E| + |N|log|N|).
Therefore the total runtime of algorithm is O(|E| + |N|log|N| + N*T^2).
'''
'''
PROGRAMMING:
Create a program to solve the word chain problem. Your program should have two
distinct parts: a part that reads in a given word list and creates the graph from the word
list, and a part that processes inputs (pairs of words) and determines the chain of lowest
cost connecting the pairs.
Your program should read its word list from a le called dict.txt. Each line of dict.txt
contains a nonempty lower-case word with no symbols other than the lowercase letters from
a to z. Do not assume anything about the ordering of the word list. In particular, it need not
be in alphabetical order. The word list contains words of many dierent (positive) lengths.
3
Once your program has read in the word list, you should create the graph from it. For
testing you can download a dict.txt from the course web page.
For the input of pairs of words, your program should read from standard input and write
to standard output. Your program should expect, as input, the following: t 1 lines of text,
each containing two nonempty words u; v, with the two words on each line separated by a
single space.
There is no guarantee that the input words are actually in the word list. If either one is
not, #print the number 1 for this pair.
(Don't bother checking for inputs that don't adhere to the specs.)
For example, an input might be
spam ramp
tippy sappy
You are to nd the cost of the lowest-cost chain linking u to v, for each of the t pairs
(u; v) of words given, and to give a chain with this cost. (There might be multiple chains of
the given cost; you only have to nd one.)
The output should be the following for each pair of words in the input: the cost of the
chain, followed by a space, followed by the words of the chain from first to last, separated
by one space. If there is no chain, the output should just be the number 1.
For example, for the input above, if dict.txt were
spam
maps
map
amp
sap
sappy
tip
tippy
ramp
the output would be
10 spam maps map amp ramp
-1
Each line of the input and each line of the output has (of course) a newline nn at the
end.
4
'''
# read in word list from dict.txt
from collections import defaultdict
import heapq
from sys import stdin
def build_graph1(graph):
file = open("dict.txt", "r")
# Sort words by their length.
word_by_lengths = defaultdict(list)
for line in file:
word = line.strip()
word_by_lengths[len(word)].append(word)
# Only have to compare words with length x with words of length x-1
# Deletions for words with length x is addition for words of length x-1
#print(word_by_lengths)
# get ordered keys from dictionary
# given the graph is dense because it is a dictionary of english words,
# there are few unique word lengths so sorting them will be fast and not
# effect runtime
ordered_word_lengths = sorted(word_by_lengths.keys(), reverse=True)
#print("the lengths are: ", ordered_word_lengths)
# for length, words in file:
i = 0
num_of_word_lens = len(ordered_word_lengths)
shorterWordSet = set()
longerWordSet = set()
while i != num_of_word_lens:
the_word_len = ordered_word_lengths[i]
longerWords = word_by_lengths.get(the_word_len)
# check if words of length - 1 exist. If it doesnt,
# returns empty array:
shorterWords = word_by_lengths.get(the_word_len-1)
# TODO OPTIMIZE THIS, REUSE PREVIOUS LONGWORDSET
if(shorterWords is None):
shorterWords = []
# only have to compare these words
shorterWordSet = set(shorterWords)
reverseRelationshipChecked = {}
twiddleRelationshipChecked = {}
# check for additions and deletions
for word in longerWords:
longerWordSet.add(word)
#do every possible deletion, check if it is in the set.
for position in range(the_word_len):
possibleShortWord = word[0:position] + word[position + 1: the_word_len]
#print("word", word)
#print("possible word", possibleShortWord)
if(possibleShortWord in shorterWords):
# THERE IS AN UNDIRECTED EDGE BETWEEN THESE TWO WORDS!
graph[word].append( (possibleShortWord, 3) ) # deletions cost 3. you can actually have a second key which is
graph[possibleShortWord].append( (word, 1)) # insertion costs 1
# check for twiddles and reversals
# dont add relationships twice. Check first.
if(reverseRelationshipChecked.get(word) is None):
reversed_word = word[::-1]
if(reversed_word != word and reversed_word in longerWordSet):
graph[word].append((reversed_word, the_word_len))
graph[reversed_word].append((word, the_word_len))
reverseRelationshipChecked[reversed_word] = True
for position in range(the_word_len - 1):
twiddleWord = word[:position] + word[position+1] + word[position] + word[position+2:]
#temp = twiddleWord[position+1]
#twiddleWord[position+1] = twiddleWord[position]
#twiddleWord[position] = temp
##print("word is", word)
##print("twiddle word is", twiddleWord)
if(twiddleRelationshipChecked.get(twiddleWord) is None):
if(twiddleWord != word and twiddleWord in longerWordSet):
graph[word].append((twiddleWord, 2)) #twiddle costs 2
graph[twiddleWord].append((word, 2))
twiddleRelationshipChecked[twiddleWord] = True
i += 1
#shorterWordsSet = longerWordSet #Todo: optimizatioon
shorterWordSet.clear()
longerWordSet.clear()
def build_graph2(graph):
file = open("dict.txt", "r")
for line in file:
word = line.strip()
graph[word] = []
#word_by_lengths[len(word)].append(word)
reverseRelationshipChecked = {}
twiddleRelationshipChecked = {}
for word in graph.keys():
the_word_len = len(word)
# longerWordSet.add(word)
# do every possible deletion, check if it is in the set.
for position in range(the_word_len):
possibleShortWord = word[0:position] + word[position + 1: the_word_len]
#print("word", word)
#print("possible word", possibleShortWord)
if(possibleShortWord in graph):
# THERE IS AN UNDIRECTED EDGE BETWEEN THESE TWO WORDS!
graph[word].append( (possibleShortWord, 3) ) # deletions cost 3. you can actually have a second key which is
graph[possibleShortWord].append( (word, 1)) # insertion costs 1
# check for twiddles and reversals
# dont add relationships twice. Check first.
if(reverseRelationshipChecked.get(word) is None):
reversed_word = word[::-1]
if(reversed_word != word and reversed_word in graph):
graph[word].append((reversed_word, the_word_len))
graph[reversed_word].append((word, the_word_len))
reverseRelationshipChecked[reversed_word] = True
for position in range(the_word_len - 1):
twiddleWord = word[:position] + word[position+1] + word[position] + word[position+2:]
if(twiddleRelationshipChecked.get(twiddleWord) is None):
if(twiddleWord != word and twiddleWord in graph):
graph[word].append((twiddleWord, 2)) #twiddle costs 2
graph[twiddleWord].append((word, 2))
twiddleRelationshipChecked[twiddleWord] = True
def shortestPathWordList():
'''
Add words to adjacency list using a python map
that maps a key, which is a graph vertex, to an array of values that represent the neighbours
'''
graph = defaultdict(list)
build_graph2(graph)
def djikistra(graph, wordA, wordB):
found = False
visited = set()
dist = {}
prev = {}
dist[wordA] = 0
queue = [(0, wordA)]
while queue:
weight, min_word = heapq.heappop(queue)
if(min_word not in visited):
visited.add(min_word)
#print("min word is", min_word)
if(min_word == wordB): #Found the word
found = True
break
for n in graph[min_word]:
#print("stfsd", graph[min_word])
nb, w = n
#print("fck", nb, w)
weight = dist[min_word] + w
if(weight < dist.get(nb, float("inf"))):
dist[nb] = weight
prev[nb] = min_word
heapq.heappush(queue, (weight, nb))
#print("THE QUEUE", queue)
#print("THE PREV", prev)
#print("THE DIST", dist)
#return dist[wordB]
if(not found):
print("-1")
else:
printer = str(dist[wordB])
node = wordB
lst = []
while(node != wordA):
lst.append(prev[node])
node = prev[node]
for i in reversed(lst) :
printer += " " + i
printer += " " + wordB
print(printer)
#print(djikistra(graph, "stone", "atone"))
'''
while(True):
line = raw_input()
theIn = line.strip()
words = theIn.split()
djikistra(graph, words[0], words[1])
'''
for id, line in enumerate(stdin):
try:
theIn = line.strip()
words = theIn.split()
djikistra(graph, words[0], words[1])
except:
break
shortestPathWordList() |
5033e1cda9da7351559e6e9ef30b1650afb48eae | Macielyoung/LeetCode | /110. Balanced Binary Tree/balanced.py | 1,109 | 3.828125 | 4 | #-*- coding: UTF-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(node, depth):
if not node:
return depth, True
left_depth, left_balance = height(node.left, depth + 1)
right_depth, right_balance = height(node.right, depth + 1)
diff = abs(left_depth - right_depth)
if diff > 1:
return max(left_depth, right_depth), False
return max(left_depth, right_depth), left_balance and right_balance
height, balance = height(root, 0)
return balance
if __name__ == '__main__':
solu = Solution()
A = TreeNode(3)
B = TreeNode(9)
C = TreeNode(20)
D = TreeNode(15)
E = TreeNode(7)
F = TreeNode(5)
G = TreeNode(10)
A.left = B
A.right = C
B.left = D
B.right = E
D.left = F
D.right = G
balance = solu.isBalanced(A)
print balance
|
c5256a70419cb2d448c757ccc7d8372874c5635b | dipprog/Competitive-Programming | /DSA/4. Divide And Conquer/max_subarray_sum_dac.py | 965 | 3.84375 | 4 | # def max_of_three(a, b, c):
# if a >= b and a >= c:
# return a
# if b >= a and b >= c:
# return b
# return c
def max_crossing_sum_subarray(A, low, mid, high):
left_sum = -100000
sum = 0
for i in range(mid, low-1, -1):
sum = sum + A[i]
if sum > left_sum:
left_sum = sum
right_sum = -100000
sum = 0
for i in range(mid+1,high+1):
sum = sum + A[i]
if sum > right_sum:
right_sum = sum
return left_sum + right_sum
def max_sum_subarray(A, low, high):
if high == low:
return A[high]
mid = (low + high)//2
left_subarray_sum = max_sum_subarray(A, low, mid)
right_subarray_sum = max_sum_subarray(A, mid+1, high)
crossing_sum = max_crossing_sum_subarray(A, low, mid, high)
return max(left_subarray_sum, right_subarray_sum, crossing_sum)
if __name__ == '__main__':
A = [3, -1, -1, 10, -3, -2, 4]
print(max_sum_subarray(A,0,6))
|
261e0e8c4905a0071850952e2132b4bd8a6b3e65 | talesritz/Learning-Python---Guanabara-classes | /Exercises - Module II/EX070 - Estatísticas em Produto.py | 1,594 | 3.84375 | 4 | #Crie um programa que leia o nome e o preço de vários produtos. O programa deverá pergntar se o usuário vai continuar. No final mostre:
#a) Qual é o total gasto na compra.
#b) Quantos produtos custam mais de R$1000
#c) Qual é o nome do produto mais barato.
print('\033[34m-=-'*11)
print('\033[33m EX070 - Estatística em Produtos')
print('\033[34m-=-\033[m'*11)
print('\n')
menor = float(100000000000000)
nomemenor = ''
total = float(0)
qtdemil = int(0)
continuar ='s'
while continuar == 's':
nomeprod = str(input('Nome do produto: ')).strip()
#valida se o preco é maior que 0
valpreco = 'n'
while valpreco == 'n':
preco = float(input('Preço: '))
if preco < 0:
print('\033[1;31mValor inválido\033[m')
else:
total+=preco
valpreco = 's'
#mostra a quantidade de precos acima de 1000
if preco > 1000:
qtdemil+=1
#mostra qual o menor valor
if preco < menor:
menor = preco
nomemenor = nomeprod
#valida se o usuário deseja continuar
valcontinuar = 'n'
while valcontinuar == 'n':
continuar = input('Deseja continuar [S/N]? ').lower()
if continuar not in 'nNsS':
print('\033[31mValor Inválido\033[m')
else:
valcontinuar = 's'
print('\n')
print(f'\033[33mTotal gasto:\033[m {total:.2f}')
print(f'\033[33mProdutos acima de R$1000:\033[m {qtdemil}')
if nomemenor == '':
print(f'\033[33mProduto mais barato:\033[m Nenhum nome digitado')
else:
print(f'\033[33mProduto mais barato:\033[m {nomemenor}') |
2ff5c32c07f877d7efd0eff99113d7e017065ca5 | jruas/myWork | /week3/absolute.py | 231 | 4.375 | 4 | #This program takes in a number and give its absolute value
#Author: Joana Ruas
#Taking a number
a=float(input('Please insert a number'))
#Turning the number into absolute
b=abs(a)
print('The absolute value of {} is {}'.format(a,b)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.