blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
bd98dd6e684213e86da1292132c6f2d893140aaf | Dirac26/ProjectEuler | /problem003/main.py | 404 | 4.09375 | 4 | def largest_prime(input_num):
"""returns the largest prime factor of a num"""
largest = None
num = input_num
n = 2
while n ** 2 <= input_num:
while num % n == 0:
num = num / n
largest = n
n += 1
if largest is None: return input_num
return largest
def main():
print(largest_prime(600851475143))
if __name__ == "__main__":
main() |
e0dbeb7cbd47525ba55470b51c4d192bd5850c66 | Manith2000/Algorithms-Data-Structures | /Selection_sort.py | 266 | 4.03125 | 4 | # Selection Sort Algorithm
def selectsort(arr):
sorted = []
for i in range(len(arr)): #iterate through unsorted part
sorted += [min(arr)]
arr.remove(min(arr))
return sorted
arr = [4,5,1,6,2,2,5,5,3,3,6]
print(selectsort(arr)) |
9eef6495cc38787fc0a33bdad390beead0225b0b | Manith2000/Algorithms-Data-Structures | /Validparantheses.py | 479 | 4.09375 | 4 | def valid(s):
valid = True
if len(s)%2 != 0: #since pairs of brackets required to be valid. if odd its definitely invalid
valid = False
return valid
for i in range(1,len(s),2): #iterate every potential pair
if (s[i-1] == '(' and s[i] != ')') or (s[i-1] == '{' and s[i] != '}') or (s[i-1] == '[' and s[i] != ']'):
valid = False
return valid
s ='()()[]{}{}[][]()'
print(valid(s))
|
774edd572b1497b9a8bc9e1c0f6107147626f276 | max-moazzam/pythonCoderbyte | /FirstFactorial.py | 541 | 4.1875 | 4 | #Function takes in a number as a parameter and returns the factorial of that number
def FirstFactorial(num):
#Converts parameter into an integer
num = int(num)
#Creates a factorial variable that will be returned
factorial = 1
#While loop will keep multipying a number to the number 1 less than it until 1 is reached
while num > 1:
factorial = factorial * num
num = num - 1
return factorial
#May need to change to raw_input to just input depending on which version of Python used
print(FirstFactorial(raw_input()))
|
9cf1d6c76dae5fe761608b5866774e72105f01b8 | Botany-Downs-Secondary-College/mathquiz-patchigalla | /5CheckEntries.py | 6,032 | 3.765625 | 4 | #Creates GUI with classes, generates questions from Random
#sprint4.py
#P.Patchigalla Feb
from tkinter import * #imports all modules of tool kit interface (Tkinter), * is called wildcard
from random import *
class MathQuiz: #OOP will have classes and funtions will be part of classes
#Keep your widgets in instantiate (__init__) method, each instance (object) must have self. as prefix
def __init__(self, parent):
"""Widgets for frame 1"""
self.frame1 = Frame(parent)
self.frame1.grid(row = 0, column = 0)
self.TitleLabel = Label(self.frame1, bg = "black", fg = "white", width = 30, padx = 30, pady = 10,
text = "Welcome to Math Quiz", font=("Times", "16", "bold italic"))
self.TitleLabel.grid(columnspan = 2)
self.NameLabel = Label(self.frame1, text = "Name", width = 20, font=("Times", "14", "bold italic"))
self.NameLabel.grid (row = 2, column = 0, sticky = W)
"""checking to see something entered"""
self.name = StringVar()
self.name.set("")
self.NameEntry = Entry(self.frame1, textvariable = self.name, width = 20) #Text box
self.NameEntry.grid(row = 2, column = 1, sticky = W)
self.AgeLabel = Label(self.frame1, text = "Age", width = 20, font=("Times", "14", "bold italic"))
self.AgeLabel.grid (row = 3, column = 0, sticky = W)
self.age = IntVar()
self.age.set("")
self.AgeEntry = Entry(self.frame1, width = 20, textvariable = self.age) #Text box
self.AgeEntry.grid(row = 3, column = 1, sticky = W)
self.SelectLabel = Label(self.frame1, text = "Select difficulty", width = 20, font=("Times", "14", "bold italic"))
self.SelectLabel.grid (row = 5, column = 0, sticky = W)
self.warning = Label(self.frame1, text = "")
self.warning.grid(row = 4, column = 1, columnspan = 3)
#Create Radio buttons
self.radio_var = StringVar()
self.radio_var.set(1)
self.rb1 = Radiobutton(self.frame1, width = 20, value = 1, variable = self.radio_var, text = "Easy", anchor = W)
self.rb1.grid(row = 6, column =0)
self.rb2 = Radiobutton(self.frame1, width = 20, value = 2, variable = self.radio_var, text = "Medium", anchor = W)
self.rb2.grid(row = 7, column =0)
self.rb3 = Radiobutton(self.frame1, width = 20, value = 3, variable = self.radio_var, text = "Hard",anchor = W)
self.rb3.grid(row = 8, column =0)
self.button1 = Button(self.frame1, text = "Next" , anchor = W, command = self.show_frame2)
self.button1.grid(row = 9, column = 1)
"""Widgets for frame 2"""
self.frame2 = Frame(parent, height = "450", width = "400") #notice grid() method is missing here
self.questions = Label(self.frame2, bg = "black", fg = "white", width = 20, padx = 30, pady = 10,
text = "Quiz Questions", font=("Times", "14", "bold italic"))
self.questions.grid(columnspan = 2)
self.QuestionLabel = Label(self.frame2, text ="", width =15, height = 3) #empty lable to print questions
self.QuestionLabel.grid(row = 1, column = 0, sticky = W)
self.home = Button(self.frame2, text = "Home" , anchor = W, command = self.show_frame1)
self.home.grid(row = 2, column = 0)
self.next_btn = Button(self.frame2, text = "Next", width = 5, command = self.next_problem, relief = RIDGE)
self.next_btn.grid(row = 2, column = 1)
def show_frame2(self):
try:
#instance created to check if input data is correct for the variables
if self.name.get() == "":
self.warning.configure(text = "Please enter your name")
self.NameEntry.focus()
elif self.name.get().isalpha() == False:
self.warning.configure(text = "Please enter text")
self.NameEntry.delete(0, END)
self.NameEntry.focus()
elif self.AgeEntry.get() == "" :
self.warning.configure(text = "Please enter a number")
self.AgeEntry.delete(0, END)
elif self.age.get() >= 12:
self.warning.configure(text = "Your are too old to play this game!!!")
self.AgeEntry.delete(0, END)
elif self.age.get() <= 0:
self.warning.configure(text = "Please enter a number greater than 0")
self.AgeEntry.delete(0, END)
elif self.age.get() <=7:
self.warning.configure(text = "Oh No! Your too young to play this game!!")
else:
self.frame1.grid_remove()
self.frame2.grid(row = 1, columnspan = 4)
self.next_problem()
except ValueError:
self.warning.configure(text = "Please enter a number")
self.AgeEntry.delete(0, END)
self.AgeEntry.focus()
def show_frame1(self):
self.frame2.grid_remove() #removes frame 2
self.frame1.grid()
def next_problem(self):
""" Creates a problem, stores the correct answer """
x = randrange(10)
y = randrange(10)
self.answer = x + y
problem_text = str(x) + " + " + str(y) + " = "
self.QuestionLabel.configure(text = problem_text)
#code in the main routine
if __name__ == "__main__": #checking to see class name is the main module
root = Tk() #root is a variable that calls the module to create GUI
frames = MathQuiz(root)
root.title("OOP") #Window title appears on top left
root.mainloop()
|
be2a0036b02452fc09c836750e0e21de5d442c8f | KubilayGazioglu/Codility | /TimeComplexity[FrogJump].py | 242 | 3.515625 | 4 | def solution(X, Y, D):
#X start point
#Y Destination point
#D step size
totalDistance = Y-X
if totalDistance % D == 0:
return totalDistance//D
else:
return totalDistance//D + 1
solution(1,1,3)
|
c5ce2fe9720ec9d91c58c65dde28af75b1d04e80 | calt-laboratory/biological_sequence_analyzer | /biological_seq_analyzer.py | 5,535 | 3.578125 | 4 | ##### Class for basic DNA sequence analysis
##### Author: Christoph Alt
# Import modules
import random
from collections import Counter
from typing import Dict, Union
import matplotlib.pyplot as plt
# Import files
from biological_seq_dictionaries import *
class BioSeqAnalyzer:
"""
Class for analyzing biological sequences (RNA, DNA).
"""
def __init__(self, sequence: str = "ACGT", sequence_type: str = "DNA") -> None:
"""
Constructor for initialization of a biological sequence and the type of the sequence.
"""
self.sequence = sequence.upper()
self.sequence_type = sequence_type
def __repr__(self) -> None:
"""
Returns a formal representation of an instanced object as string.
"""
print(f'BiolgicalSeqAnalyzer(sequence={self.sequence}, sequence_type={self.sequence_type}')
def __str__(self) -> None:
"""
Returns an informal representation of an instanced as string.
"""
print(f'Biolgical Sequence Analyzer: Seq = {self.sequence}, Seq_Type = {self.sequence_type}')
def generate_sequence(self, nucleotides: str = "ACGT", sequence_type: str = "DNA", sequence_length: str = 100):
"""
Returns a string representing the randomly generated biological sequence.
"""
random_sequence = "".join([random.choice(nucleotides) for i in range(sequence_length)])
self.__init__(random_sequence, sequence_type)
def sequence_length(self) -> int:
"""
Returns an integer representing the length of a biological sequence.
"""
return len(self.sequence)
def get_seq_info(self) -> str:
"""
Returns 2 strings representing the biological sequence and the type of the sequence.
"""
return 'Sequence: {0}\nSequence type: {1}\n'.format(self.sequence, self.sequence_type)
def nucleotide_freq_counter(self) -> Dict[str, int]:
"""
Returns a dictionary comprising the frequency of each nucleotide in a given sequence.
"""
if self.sequence_type == "DNA":
for i in self.sequence:
dna_nucleotide_dict[i] += 1
return dna_nucleotide_dict
if self.sequence_type == "RNA":
for i in self.sequence:
rna_nucleotide_dict[i] += 1
return rna_nucleotide_dict
def gc_content(self) -> float:
"""
Returns a float representing the GC content of a biological sequence.
"""
return round(((self.sequence.count('C') + self.sequence.count('G')) * 100) / len(self.sequence), 2)
def reverse_sequence(self) -> str:
"""
Returns a string representing the reverse version of the input biological sequence.
"""
return self.sequence[::-1]
def reverse_complement_sequence(self) -> str:
"""
Returns a string representing the reverse complement of a biological sequence.
"""
if self.sequence_type == "DNA":
return ''.join([dna_complement_dict[nuc] for nuc in self.sequence])[::-1]
elif self.sequence_type == "RNA":
return ''.join([rna_complement_dict[nuc] for nuc in self.sequence])[::-1]
def dna_2_rna(self) -> str:
"""
Returns a string representing the RNA sequence translated from a DNA sequence.
"""
if self.sequence_type == "DNA":
return self.sequence.replace('T', 'U')
else:
return "Given sequence is not a DNA sequence!"
def codon_bias(self, amino_acid: str = "A", viz: bool = True) -> Dict:
"""
Returns a dictionary representing the frequency of codons of a given amino acid.
"""
codon_list = []
if self.sequence_type == "DNA":
for i in range(0, len(self.sequence) - 2, 3):
if dna_codon_dict[self.sequence[i:i + 3]] == amino_acid:
codon_list.append(self.sequence[i:i + 3])
if self.sequence_type == "RNA":
for i in range(0, len(self.sequence) - 2, 3):
if rna_codon_dict[self.sequence[i:i + 3]] == amino_acid:
codon_list.append(self.sequence[i:i + 3])
frequency_codon_dict = dict(Counter(codon_list))
sum_codons = sum(frequency_codon_dict.values())
percentage_codon_dict = {codon: round(frequency_codon_dict[codon] / sum_codons, 2) for codon in
frequency_codon_dict}
if viz == True:
labels = list(percentage_codon_dict.keys())
vals = list(percentage_codon_dict.values())
plt.pie(vals, labels=vals , normalize=False)
plt.legend(labels)
plt.title(f'Frequency of codons for the amino acid: {amino_acid}')
plt.show()
return percentage_codon_dict
def rna_2_protein(self) -> Union[str, None]:
"""
Returns a string representing a amino acid sequence translated from a RNA sequence.
"""
if self.sequence_type == "RNA":
print(type(''.join([rna_codon_dict[self.sequence[i:i + 3]] for i in range(0, len(self.sequence) - 2, 3)])))
return ''.join([rna_codon_dict[self.sequence[i:i + 3]] for i in range(0, len(self.sequence) - 2, 3)])
else:
print('Given sequence is not a RNA!')
def main():
seq_analyzer = BioSeqAnalyzer(sequence="ACUGAUUUUUACCCAAAA", sequence_type="RNA")
seq_analyzer.rna_2_protein()
if __name__ == "__main__":
main()
|
ca70bcf88e4c34a54babd0e94ca8e77e9fe17f0b | laufergall/pythonsql_workshop | /scripts/utils_sqlite.py | 1,588 | 4.09375 | 4 | """
This file contains utilities for sqlite data access.
"""
import sqlite3
from typing import List, Tuple
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except sqlite3.Error as e:
print(e)
return conn
def execute(conn, statement) -> List[Tuple]:
""" execute a sql statement with try/except
:param conn: Connection object
:param statement: a sql statement
:return: execution result
"""
if conn is not None:
cursor = conn.cursor()
else:
print('Could not connect to database!')
try:
res = cursor.execute(statement)
except sqlite3.Error as e:
print(e)
return res.fetchall()
def insert_user(conn, record):
"""
Create a new user into the users table
:param conn:
:param record:
:return: user id
"""
sql = """ INSERT INTO users(first_name,last_name,email,gender)
VALUES(?,?,?,?) """
cur = conn.cursor()
cur.execute(sql, record)
return cur.lastrowid
def insert_rental(conn, record):
"""
Create a new rental into the rentals table
:param conn:
:param record:
:return: purchase id
"""
sql = ''' INSERT INTO rentals(user_id,rental_timestamp,title,year,cost)
VALUES(?,?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, record)
return cur.lastrowid
|
d66acd385a21c664082d543f6ae4c9d5bde0ec5b | Baymax15/2048_game | /main.clean.py | 3,923 | 3.515625 | 4 | import random as r
class board:
def __init__(self, size, data=False):
self.size = size
self.data = []
if data:
for x in data:
self.data.append(x[:])
else:
for _ in range(size):
self.data.append([0] * size)
def copy(self):
result = []
for x in self.data:
temp = []
for i in range(self.size):
temp.append(x[i])
result.append(temp)
return result
def match(self, another):
if self.data == another.data:
return True
return False
def place(self, count=1, val=r.choice([4, *[2] * 9])):
x = 0
while x < count:
i = r.randrange(self.size)
j = r.randrange(self.size)
if self.data[i][j] == 0:
self.data[i][j] = val
x += 1
def state(self):
for x in self.data:
if 2048 in x:
return 'won'
for x in self.data:
if 0 in x:
return ''
for i in range(self.size):
for j in range(self.size):
try:
if self.data[i][j] == self.data[i][j+1]:
return ''
except IndexError:
pass
try:
if self.data[i][j] == self.data[i+1][j]:
return ''
except IndexError:
pass
return 'lost'
def draw(self):
rep = {
0: '-', 2: '2', 4: '4', 8: '8', 16: '16', 32: '32', 64: '64',
128: '128', 256: '256', 512: '512', 1024: '1024', 2048: '2048'}
res = ''
for i in range(self.size):
for j in range(self.size):
res += rep[self.data[i][j]].rjust(5)
res += '\n'
return res
def transpose(stat):
result = []
for i in range(stat.size):
temp = []
for x in stat.data:
temp.append(x[i])
result.append(temp)
return board(stat.size, result)
def reverse(stat):
result = []
for x in stat.data:
temp = []
for i in range(1, stat.size+1):
temp.append(x[-i])
result.append(temp)
return board(stat.size, result)
def move(stat):
temp = stat.copy()
def shift(row):
for k in range(len(row)):
if row[k] == 0:
row.insert(0, row.pop(k))
return row
for i in range(stat.size):
if sum(temp[i]) == 0:
continue
temp[i] = shift(temp[i])
prev = False
for k in range(stat.size - 1, 0, -1):
if prev:
prev = False
continue
if temp[i][k] == temp[i][k-1]:
temp[i][k], temp[i][k-1] = 0, temp[i][k] * 2
prev = True
temp[i] = shift(temp[i])
return board(stat.size, temp)
def check(stat, choice):
if choice not in ['w', 'a', 's', 'd']:
return False
if choice in ['s', 'w']:
temp = transpose(stat)
else:
temp = stat
if choice in ['a', 'w']:
temp2 = reverse(temp)
else:
temp2 = temp
done = move(temp2)
if choice in ['a', 'w']:
temp2 = reverse(done)
else:
temp2 = done
if choice in ['s', 'w']:
temp = transpose(temp2)
else:
temp = temp2
if temp.match(stat):
return False
else:
return temp
size = 4
start = board(size)
start.place(count=2)
print('wasd to move. q to quit.')
while True:
choice = input(start.draw())
if choice == 'q':
break
temp = check(start, choice)
if not temp:
continue
print('-' * 20)
temp.place()
start = temp
state = start.state()
if state:
print('You have', state, 'the match!')
break
|
e1b06441f9f3d9175ae5dd4d9d05737916e87a99 | jelockro/launchcode-101 | /goMike.py | 1,599 | 3.84375 | 4 | from turtle import Turtle
from turtle import Screen
import sys
sys.setExecutionLimit(65000)
class Mike(Turtle):
firstname = 'Mike'
def __init__(self, color, speed):
Turtle.__init__(self)
self.shellcolor = color
self.color(color)
self.speed(speed)
def drawAndBack(self, length, angle):
for i in range(2):
self.forward(length / 2)
self.forward(-length)
self.forward(length / 2)
self.left(90)
self.right(180)
def drawSquare(self, length):
# turtle is facing it's right, relative right
self.forward(length/2)
self.left(90)
self.forward(length/2)
for i in range(3):
self.left(90)
self.forward(length)
self.left(90)
self.forward(length/2)
self.right(90)
self.forward(-length/2)
# should end up facing it's relative right
def draw_line(self, length, angle):
self.left(angle)
self.drawAndBack(length, angle)
self.drawSquare(length)
def star(self, lines):
print("Go " + self.firstname + "!!!")
steps = int(180/lines)
for angle in range(0, 180, steps):
if angle == 0:
self.draw_line(200, 0)
else:
compAngle = angle % steps + steps
self.draw_line(200, compAngle)
def main():
wn = Screen()
wn.bgcolor("lightgreen")
mike = Mike('blue', 5)
mike.star(5)
wn.exitonclick()
if __name__ == "__main__" :
main()
|
5db18fbb18655ab731866be1bb25a2289a419a5b | DrakeAlia/Graphs | /projects/ancestor/ancestor.py | 4,231 | 4.03125 | 4 | # Suppose we have some input data describing a graph of relationships between parents and children over multiple generations.
# The data is formatted as a list of (parent, child) pairs, where each individual is assigned a unique integer identifier.
# Write a function that, given the dataset and the ID of an individual in the dataset, returns their earliest known ancestor – the one at the farthest distance from the input individual. If there is more than one ancestor tied for "earliest", return the one with the lowest numeric ID.
# If the input individual has no parents, the function should return -1.
# Example input
# 6
# 1 3
# 2 3
# 3 6
# 5 6
# 5 7
# 4 5
# 4 8
# 8 9
# 11 8
# 10 1
# Example output
# 10
from util import Stack, Queue
test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
def earliest_ancestor(ancestors, starting_node):
# Create the queue, most recent parent and the visited set
q = Queue()
visited = set()
most_recent = []
# Check if the node has no ancestors
if has_parents(ancestors,starting_node) is False:
return -1
# Add the starting Node
q.enqueue(starting_node)
while q.size() > 0:
# Get the first in line
v = q.dequeue()
print(f"Current Node {v}")
# Check if it has been visited or not
# If so, add it to the visited set
if v not in visited:
visited.add(v)
# Check if the node has parents
# If true
if has_parents(ancestors,v):
# Clear the most recent parents list
most_recent.clear()
# Enqueue the parents and add the parents to the most recent list
# Parents list
for parent,child in ancestors:
if child == v:
q.enqueue(parent)
print(f"queueing {parent} as the parents of {v}")
# Reset the most recent parents
most_recent.append(parent)
print()
else:
print(f"{v} has no parents\n")
# Return the smaller of the two parents
return min(most_recent)
def has_parents(ancestors,node):
children = set()
for parent, child in ancestors:
children.add(child)
if node in children:
return True
else:
return False
ancestor = earliest_ancestor(test_ancestors,6)
print(f"The earliest ancestor to the input is {ancestor}")
# First Attempt:
# class Graph:
# """Represent a graph as a dictionary of vertices mapping labels to edges."""
# def __init__(self):
# self.vertices = {}
# def add_vertex(self, vertex_id):
# """
# Add a vertex to the graph.
# """
# self.vertices[vertex_id] = set()
# def add_edge(self, v1, v2):
# """
# Add a directed edge to the graph.
# """
# self.vertices[v1].add(v2)
# def earliest_ancestor(ancestors, starting_node):
# ## using the graph class
# graph = Graph()
# ## build a dictionary of all the connections
# for connection in ancestors:
# graph.add_vertex(connection[1])
# for connection in ancestors:
# graph.add_edge(connection[1], connection[0])
# ## empty set to store the paths (set of lists)
# paths = []
# visited_paths = []
# visited_paths.append([starting_node])
# while len(visited_paths) > 0:
# current_path = visited_paths.pop(0)
# starting_node = current_path[-1]
# if starting_node in graph.vertices:
# for parent in graph.vertices[starting_node]:
# new_path = current_path.copy()
# new_path.append(parent)
# paths.append(new_path)
# visited_paths.append(new_path)
# if len(paths) == 0:
# return -1
# longest = max([len(i) for i in paths])
# plist = []
# for path in paths:
# if len(path) == longest:
# plist.append(path)
# oldest = []
# for path in plist:
# oldest.append(path[-1])
# return min(oldest) |
724ff0664010a44373974733c5bb6732162ff64e | vivek7325/rks369.github.io | /Python/jarvis.py | 2,353 | 3.65625 | 4 | import pyttsx3
import datetime
import pywhatkit as kitty
import speech_recognition as kan
import wikipedia
import webbrowser
jarvis = pyttsx3.init('sapi5')
voices = jarvis.getProperty('voices')
jarvis.setProperty('voice', voices[1].id)
def speak(audio):
jarvis.say(audio)
jarvis.runAndWait() # Without this command, speech will not be audible to us.
def takeCommand():
# It takes microphone input from the user and returns string output
sun = kan.Recognizer()
with kan.Microphone() as source:
print("Listening...")
sun.pause_threshold = 1
audio = sun.listen(source)
try:
print("Recognizing...")
command = sun.recognize_google(audio, language='en-in') # Using google for voice recognition.
print(f"User said: {command}\n") # User query will be printed.
except Exception as e:
print(e)
print("Say that again please...") # Say that again will be printed in case of improper voice
return "None" # None string will be returned
return command
def wishme():
hour = int(datetime.datetime.now().hour)
if 0 <= hour < 12:
speak("Good Morning!")
elif 12 <= hour < 18:
speak("Good Afternoon!")
elif 18 <= hour <= 22:
speak("Good Evening!")
else:
speak("Good Night!")
speak("I am Jarvis Sir. Please tell me how may I help you")
if __name__ == "__main__":
wishme()
while True:
commandline = takeCommand().lower()
if 'wikipedia' in commandline:
speak('Searching Wikipedia...')
commandline = commandline.replace("wikipedia", "")
results = wikipedia.summary(commandline, sentences=5)
results = results.replace(".", ".\n")
speak("According to Wikipedia")
print(results)
speak(results)
elif 'play' in commandline:
commandline = commandline.replace("youtube", "")
commandline = commandline.replace(" ", "+")
kitty.playonyt(commandline)
elif 'google' in commandline:
commandline = commandline.replace("google", "")
commandline = commandline.replace(" ", "+")
webbrowser.open("https://www.google.com/search?q=" + commandline)
|
3834f47fb00e27ecde0db448201e192c22c2b4f6 | indeyo/PythonStudy | /liaoxuefengLessons/FunctionalProgramming/map&reduce.py | 2,199 | 3.765625 | 4 | #-*- coding: utf-8 -*-
"""
@Project : StudyPython0-100
@File : map&reduce.py
@Time : 2019-07-11 08:40:54
@Author : indeyo_lin
@Version :
@Remark :
"""
"""
练习题1
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']
"""
# def normalize(name):
# index = 1
# new_name = ''
# for x in name:
# if index == 1:
# new_name += x.upper()
# index += 1
# else:
# new_name += x.lower()
# return new_name
#网友答案
# def normalize(name):
#
# return name[:][0].upper()+name[:][1:].lower()
#网友答案indeyo改造版
# def normalize(name):
#
# return name[0].upper()+name[1:].lower()
# L1 = ['adam', 'LISA', 'barT']
# L2 = list(map(normalize, L1))
# print(L2)
"""
练习2:
Python提供的sum()函数可以接受一个list并求和,
请编写一个prod()函数,可以接受一个list并利用reduce()求积:
"""
# from functools import reduce
#
# def prod(L):
# def fn (x1, x2):
# return x1 * x2
# return reduce(fn, L)
#
# print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
# if prod([3, 5, 7, 9]) == 945:
# print('测试成功!')
# else:
# print('测试失败!')
"""
练习3:
利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
"""
from functools import reduce
def str2float(s):
def list2int(a, b):
return a * 10 + b
def list2float(a, b):
return a * 0.1 + b
def char2int(c): #这里可以用int()代替
digits = {'0':0, '1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
return digits[c]
index = 0
for x in list(s): # 拿到小数点的位置
if x != '.':
index += 1
else:
break
L1 = list(s)[:index]
L2 = list(s)[:index:-1]
return reduce(list2int, map(char2int, L1)) + reduce(list2float, map(char2int, L2)) * 0.1
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!') |
0a89bb2394039f7265facd42d4e2d58216b60d7d | indeyo/PythonStudy | /algorithm/most_item_in_list.py | 739 | 4.0625 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Author : indeyo_lin
# @Time : 2020/6/5 11:01 下午
# @File : most_item_in_list.py
"""
def get_most_in_list(arr: list):
"""
富途笔试题
找出列表中出现次数最多的元素
"""
if not arr:
return -1
count = {}
result = []
for i in arr:
count[i] = arr.count(i)
max_count = max(count.values())
for key, value in count.items():
if value == max_count:
result.append(key)
return result
if __name__ == '__main__':
a1 = [1, 1, 1, 2, 3, 4]
a2 = [33, 33, 33, 56, 56, 56, 77, 77]
a3 = []
print(get_most_in_list(a1))
print(get_most_in_list(a2))
print(get_most_in_list(a3))
|
dc0f95828705f2f1e42a9726b0e79e6c25e6d8ae | indeyo/PythonStudy | /leetcode/find_coder.py | 551 | 3.765625 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Author : indeyo_lin
# @Time : 2020/5/25 10:48 下午
# @File : find_coder.py
"""
def find_coder(arr):
if not arr:
return -1
coder = []
for s in arr:
if "coder coder" in s:
coder.append(s)
return coder if coder else -1
if __name__ == '__main__':
arr_1 = []
arr_2 = ["coder"]
arr_3 = ["coder coder", "aaa coder coder bbb", "adb", " coder coder "]
print(find_coder(arr_1))
print(find_coder(arr_2))
print(find_coder(arr_3)) |
4fdd9b3423f94460b3faad5262229e374ca3518c | indeyo/PythonStudy | /algorithm/insertion_sort.py | 720 | 4.125 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Author : indeyo_lin
# @Time : 2020/5/28 4:20 下午
# @File : insertion_sort.py
"""
def insertion_sort(arr):
if not arr:
return -1
for i in range(1, len(arr)):
current = arr[i]
# 有序区的索引
pre_index = i - 1
while pre_index >= 0 and arr[pre_index] > current:
# 遇到比当前元素大的就往后挪
arr[pre_index + 1] = arr[pre_index]
pre_index -= 1
arr[pre_index + 1] = current
return arr
if __name__ == '__main__':
# for i in range(0, -1, -1):
# print(i)
arr = [2, 8, 49, 4, 21, 0, 45, 22, 91, 5, 10]
print(insertion_sort(arr))
|
ce5cad544a2fc27a8d36f44d9a3bfd8cc8962f3b | indeyo/PythonStudy | /leetcode/replace_space.py | 3,654 | 3.625 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Project : PythonStudy
@File : replace_space.py
@Time : 2020-04-26 14:47:16
@Author : indeyo_lin
"""
class ReplaceSpace:
"""
面试题05. 替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:0 <= s 的长度 <= 10000
"""
def replaceSpace(self, s):
"""
:type s: str
:rtype: str
"""
# 转换成列表,方便对每个字符进行操作
array = list(s)
# python里面数组的赋值操作,实际上相当于引用,而没有开辟一个新的存储空间
# 如果不copy,直接赋值,那么对array_new进行修改会影响到array
array_new = array.copy()
# 代表当前空格后面的字符串收尾指针
p_head, p_tail = 0, len(array) - 1
# 原字符串扫描指针
p_search = 0
for i in array:
if i == ' ':
# 这种切片赋值法有一种情况不能实现,不能默认输入空字符,赋值后list后面都是有值的
# 当结尾是一个空格加一个字符的时候,最后一个字符会丢失
last = array[p_search + 1:len(array)]
if len(last) < 2:
array_new.append("")
array_new[p_head + 3:p_tail + 3] = last
else:
array_new[p_head + 3:p_tail + 3] = array[p_search + 1:len(array)]
array_new[p_head:p_head + 3] = "%20"
p_head += 3
p_tail += 3
p_search += 1
continue
p_head += 1
p_search += 1
return "".join(array_new)
class SimpleReplaceSpace:
def replaceSpace(self, s):
origin = list(s)
new = []
for i in origin:
if i == " ":
new.append("%20")
else:
new.append(i)
return "".join(new)
class LessSpaceReplaceSpace:
def replaceSpace(self, s):
array = list(s)
length = len(array)
p, blank_num = 0, 0
# 因为会改变数组本身,不能用for遍历
while p < length:
if array[p] == " ":
blank_num += 1
# python不支持给空的list用切片赋值,先用占位符占个坑
array.append('x')
array.append('x')
p += 1
p_orgin_tail = length - 1
p_new_tail = length - 1 + 2 * blank_num
while p_orgin_tail >= 0:
if array[p_orgin_tail] == " ":
array[p_new_tail-2:p_new_tail+1] = ["%", "2", "0"]
p_new_tail -= 3
else:
array[p_new_tail] = array[p_orgin_tail]
p_new_tail -= 1
p_orgin_tail -= 1
return "".join(array)
if __name__ == '__main__':
# a = [1, 2, 3, 4, 5, 6, 7, 8]
# b = ['l', 'o', 'v', 'e']
# 实际上赋值给a[8]
# a[10:11] = b[1:2]
# print(a)
# print(a[:-5:2])
# a[1:3] = [9, 9]
# print(a)
# b[2:4] = "abc"
# print(b)
#
# for i in range(5):
# print(i)
# print(a.index(3))
s = ReplaceSpace()
print(s.replaceSpace(" aeee e"))
s1 = SimpleReplaceSpace()
print(s1.replaceSpace(" aeee e"))
s2 = LessSpaceReplaceSpace()
print(s2.replaceSpace(" aeee e"))
# a = []
# q = queue.Queue()
# q.put(a)
# q.put(0)
# # print(q.get())
# print(q.get())
|
9ea6a64935a14b0c50cbbeae11f077417d0e35f9 | lingkuraki/python | /chapter03/com.kuraki/zip.py | 148 | 3.875 | 4 | names = ['kuraki', 'lingbo', 'damon', 'Jordan']
ages = [26, 25, 100, 50]
for name, age in zip(names, ages):
print(name, 'is', age, 'year old')
|
e6538e04ca9938179eebeae64c7ce506c9854327 | lingkuraki/python | /chapter03/com.kuraki/whileDemo.py | 170 | 4 | 4 | name = ''
while not name or name.isspace():
name = input('Please enter your name: ')
print('Hello, {}!'.format(name))
for number in range(1, 101):
print(number)
|
5b4bcebc35451efa0b90dbf11074a201a110efa0 | lcantillo00/python-exercises | /11-DictionariosDupes/ex1.py | 859 | 3.84375 | 4 | x = input("Enter a sentence")
x = x.lower() # convert to all lowercase
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_count = {} # empty dictionary
for char in x:
if char in alphabet: # ignore any punctuation, numbers, etc
if char in letter_count:
letter_count[char] = letter_count[char] + 1
else:
letter_count[char] = 1
keys = letter_count.keys()
keys.sort()
for char in keys:
print(char, letter_count[char])
# ///////////////////////////////////another way
mystr=input("enter you string")
mystr.lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
count={}
for i in mystr:
if i in alphabet:
if i in count:
count[i]=count[i]+1
else:
count[i]=1
mykeys=count.keys()
mykeys.sort()
for i in mykeys:
print(i,count[i])
|
018c53dca45443f6ffc16b7086735f644593dc45 | lcantillo00/python-exercises | /10-List/ex5.py | 265 | 3.5625 | 4 | import random
def max(alist):
maxnum=0
for i in alist:
if maxnum<i:
maxnum=i
return maxnum
def main():
f=[]
for i in range(100):
f.append(random.randint(0, 1000))
print(max(f))
if __name__=="__main__":
main()
|
1f29fed056ccc1691b630acc4ffbc33526a29276 | lcantillo00/python-exercises | /2-SimplePythonData/ex11.py | 227 | 4.40625 | 4 | deg_f = int(input("What is the temperature in farengeigth? "))
# formula to convert C to F is: (degrees Celcius) times (9/5) plus (32)
deg_c = (deg_f -32)*5/9
print(deg_f, " degrees Celsius is", deg_c, " degrees Farenheit.")
|
5c609d4fbf967bec92af65ec32a8c7b6e7d1d21c | lcantillo00/python-exercises | /Studio/st2.py | 543 | 4.09375 | 4 | print("Welcome to the Loop Hole!")
print("Today's Manager's Special is :")
print("Donnuts: A traditional jelly donut in which the jelly filling is made entirely of Capn' Crunch Berries Oops All Berries")
num_donuts=int(input("How many do you like?"))
price=float(input("How much would you like to pay per donut 'suggested price is $4.35 each'"))
totalprice=(num_donuts*price)+(num_donuts*price*0.05)
print("After tax, your total is: " + "$"+str(totalprice)+ " with taxes included")
print("Thank you for snacking! Loop back around here soon!")
|
88cf45a659416489228d03a71c18e528c2e28770 | lcantillo00/python-exercises | /ex15.py | 159 | 4.09375 | 4 | #Write a function that will return the number of digits in an integer.
def intergerNum(num):
nstring=str(num)
return len(nstring)
print(intergerNum(34))
|
667d442d0c38e26e70f9b0cf7a2e219ccced2f97 | lcantillo00/python-exercises | /exs12.py | 271 | 3.890625 | 4 | #Write a program to draw some kind of picture.
# Be creative and experiment with the turtle methods provided in
import turtle
tanenbaum = turtle.Turtle()
tanenbaum.hideturtle()
tanenbaum.speed(20)
for i in range(350):
tanenbaum.forward(i)
tanenbaum.right(98)
|
681ec03bc494256d93fd8e6482a2aea210cf94d2 | lcantillo00/python-exercises | /4-ModuleTurtle/ex5.py | 772 | 4.15625 | 4 | # draw an equilateral triangle
import turtle
wn = turtle.Screen()
norvig = turtle.Turtle()
for i in range(3):
norvig.forward(100)
# the angle of each vertice of a regular polygon
# is 360 divided by the number of sides
norvig.left(360/3)
wn.exitonclick()
# draw a square
import turtle
wn = turtle.Screen()
kurzweil = turtle.Turtle()
for i in range(4):
kurzweil.forward(100)
kurzweil.left(360/4)
wn.exitonclick()
# draw a hexagon
import turtle
wn = turtle.Screen()
dijkstra = turtle.Turtle()
for i in range(6):
dijkstra.forward(100)
dijkstra.left(360/6)
wn.exitonclick()
# draw an octogon
import turtle
wn = turtle.Screen()
knuth = turtle.Turtle()
for i in range(8):
knuth.forward(75)
knuth.left(360/8)
wn.exitonclick()
|
4ccfffb6a6cea4bd016495075bb967750dfe05d1 | lcantillo00/python-exercises | /9-Strings/ex5.py | 885 | 3.6875 | 4 | # from test import testEqual
#
# def remove_all(substr,theStr):
# newstring=theStr.replace(substr,"",)
# return newstring
#
#
# testEqual(remove_all('an', 'banana'), 'ba')
# testEqual(remove_all('cyc', 'bicycle'), 'bile')
# testEqual(remove_all('iss', 'Mississippi'), 'Mippi')
# testEqual(remove_all('eggs', 'bicycle'), 'bicycle')
#
# from test import testEqual
# ///////////////////////////////////////////////////////////s
def is_palindrome(text):
# your code here
left=0
rigth=len(text)-1
while left<=rigth:
if text[left]==text[rigth] or text=="":
return True
else:
left+=1
rigth+=1
return False
testEqual(is_palindrome('abba'), True)
testEqual(is_palindrome('abab'), False)
testEqual(is_palindrome('straw warts'), True)
testEqual(is_palindrome('a'), True)
testEqual(is_palindrome(''), True)
|
d9fbdc7310218e85b562a1beca25abe48e72ee8b | lcantillo00/python-exercises | /randy_guessnum.py | 305 | 4.15625 | 4 | from random import randint
num = randint(1, 6)
print ("Guess a number between 1 and 6")
answer = int(raw_input())
if answer==num:
print ("you guess the number")
elif num<answer:
print ("your number is less than the random #")
elif num>answer:
print("your number is bigger than the random #")
|
e15b2129dc2bb67a6815679e4f9b3caca092eaa2 | JaredLGillespie/DataStructures | /Python/InsertionSort.py | 1,778 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Jared Gillespie
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
def insertion_sort(arr):
"""Sorts the list in-place using Bubble Sort algorithm.
:param arr: The array.
>>> arr = [1, 2, 3]
>>> insertion_sort(arr)
>>> print(arr)
[1, 2, 3]
>>> arr = [3, 2, 5, 4, 4, 0]
>>> insertion_sort(arr)
>>> print(arr)
[0, 2, 3, 4, 4, 5]
"""
for i in range(len(arr)):
min_val, min_index = None, -1
for j in range(i, len(arr)):
if min_val is None or arr[j] < min_val:
min_val, min_index = arr[j], j
arr[i], arr[min_index] = arr[min_index], arr[i]
if __name__ == '__main__':
import doctest
doctest.testmod()
|
9e71f7ca9e7fc34fe6769a952b923c4d7b8f933f | MusaddiqueahmedDange/python_practice | /COHpythonpractice/chapter 2/02_pr_06_remainder.py | 68 | 3.859375 | 4 | a = 50
b = 8
print("the remainder when a is divided by b is :", a%b) |
6e45d0c329bc846c10cdc4e425d2d8700b1da89c | llewelld/countdown | /countdown.py | 7,550 | 4 | 4 | #!/usr/bin/python
""" Does the Countdown numbers game. Give it a list of numbers. It'll use all
but the last number in a formula using the +, -, * and / operators to try
to generate the last number. Only integer arithmetic is allowed, and not all
of the numbers need to be used.
Syntax: countdown n_1 n_2 ... n_m sum
Licensed under the MIT licence. See the LICENSE file for details.
David Llewellyn-Jones, 2018
david@flypig.co.uk
"""
import copy
import sys
def findprev(layer, cols):
"""For a particular column in a particular layer, find the next earlier
column in the layer that contains a node
"""
found = -1
pos = cols - 1
while (pos >= 0) and (found < 0):
if layer[pos] == 1:
found = pos
pos = pos - 1
return found
def shuntup(layer, end):
""" Given a particular choice of attaching nodes in columns to create a layer
move to the next layer configuration in the enumeration
"""
movedto = -1
last = findprev(layer, end)
if last >= 0:
if last == (end - 1):
movedto = shuntup(layer, last)
if movedto >= 0:
movedto = movedto + 1
layer[last] = 0
layer[movedto] = 1
else:
layer[last] = 0
layer[last + 1] = 1
movedto = last + 1
return movedto
def evaluate(formula, operators, numbers):
""" Evaluate a formula represented as a tree into a single integer result
If the formula involves a non-integer division, NaN will be returned
"""
calc = float("NaN")
left = formula[0]
op = operators[formula[1]]
right = formula[2]
if isinstance(left, list):
left = evaluate(left, operators, numbers)
else:
left = numbers[left]
if isinstance(right, list):
right = evaluate(right, operators, numbers)
else:
right = numbers[right]
if op == 0:
calc = left + right
elif op == 1:
calc = left - right
elif op == 2:
calc = left * right
elif op == 3:
if (right != 0) and (left % right == 0):
calc = left / right
elif op == 4:
calc = left
elif op == 5:
calc = right
return calc
def formulatostring(formula, operators, numbers):
""" Convert a formula represented as a tree into a string representation
"""
calc = ""
left = formula[0]
op = operators[formula[1]]
right = formula[2]
if isinstance(left, list):
left = formulatostring(left, operators, numbers)
else:
left = str(numbers[left])
if isinstance(right, list):
right = formulatostring(right, operators, numbers)
else:
right = str(numbers[right])
if op == 0:
calc = "(" + left + ' + ' + right + ")"
elif op == 1:
calc = "(" + left + " - " + right + ")"
elif op == 2:
calc = "(" + left + " * " + right + ")"
elif op == 3:
calc = "(" + left + " / " + right + ")"
elif op == 4:
calc = left
elif op == 5:
calc = right
return calc
def permutations(elements):
""" From a list of elements return a list of permutations of those elements
"""
if len(elements) <=1:
yield elements
else:
for perm in permutations(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
def buildformula(built):
""" Build a formula from a sparse representation of a binary tree. The tree is
represented as a list of lists, one list for each row. The list in each
row represents list of zeroes and ones. A zero means there are no
children to the node, a one means there are two children of the node.
This provides a cononical encoding of the tree, which can be rebult fully,
and this function converts it into a tree formed as a set of nested lists,
each element either containing a trio containing two subelements and an
operator, or a number representing a leaf node.
"""
formula = copy.deepcopy(built)
leaf = 0
operator = 0
for layer in range(len(built)):
if built[layer] != 0:
for op in range(len(built[layer])):
if built[layer][op] == 1:
formula[layer][op] = [0, operator, 0]
operator = operator + 1
else:
formula[layer][op] = leaf
leaf = leaf + 1
for layer in range(len(built)):
nextpos = 0
if built[layer] != 0:
for op in range(len(built[layer])):
if built[layer][op] == 1:
if (layer < len(built) - 1) and (built[layer + 1] != 0):
formula[layer][op][0] = formula[layer + 1][nextpos]
formula[layer][op][2] = formula[layer + 1][nextpos + 1]
nextpos = nextpos + 2
else:
formula[layer][op][0] = leaf
formula[layer][op][2] = leaf + 1
leaf = leaf + 2
nextpos = nextpos + 2
return formula[0]
def shuntoperator(operators, pos):
if pos >= 0:
operators[pos] = operators[pos] + 1
if operators[pos] > 4:
operators[pos] = 0
return shuntoperator(operators, pos - 1)
return True
else:
return False
def chooselayer(connections, built, start, height, numbers, find, closest):
""" For a given number of nodes set in each layer of a tree (defined by
connections), starting from layer start and going up to layer height, cycle
through all the possible trees that could be created in this configuration.
For each such tree, cycle through all permuutations of the numbers,
and all possible operators, and compare the output from the resulting
formula to the number to find.
The function will print out the closest formula it can find as it goes
along, until hopefully an exact match is found.
"""
if (start < height) and (connections[start] > 0):
hangers = 2*connections[start - 1]
coats = connections[start]
if hangers >= coats:
layer = [1] * coats + [0] * (hangers - coats)
movedto = hangers
while movedto >= 0:
built[start] = layer
closest = chooselayer(connections, built, start + 1, height, numbers, find, closest)
movedto = shuntup(layer, hangers)
else:
formula = buildformula(built)
for perm in permutations(numbers):
operators = [0] * height
more = True
while more:
more = shuntoperator(operators, height - 1)
calc = evaluate(formula[0], operators, perm)
if calc == calc:
distance = abs(calc - find)
if distance <= closest:
if (distance == 0) and (closest != 0):
print "#######################################"
string = formulatostring(formula[0], operators, perm) + " = " + str(calc)
closest = distance
print string
return closest
def shuntconnection(connections, height, maxnodes, nodes):
""" Given a particular configuration of connections, move to
the next connection in the enumeration
"""
changed = 0
if (height >= 1):
current = connections[height - 1]
nodesbelow = nodes - current
if (height <= 1):
prev = 0
else:
prev = connections[height - 2]
if (current >= 2**prev) or (nodesbelow + current >= maxnodes):
changed = shuntconnection(connections, height - 1, maxnodes, nodesbelow)
if nodesbelow + changed < maxnodes:
connections[height - 1] = 1
changed = changed - current + 1
if height == maxnodes:
changed = -1
else:
connections[height - 1] = 0
changed = changed - current
else:
connections[height - 1] = current + 1
changed = 1
return changed
def connections(numbers, find):
""" Cycle through all of the possible trees that contain a given fixed number
of nodes
"""
nodes = len(numbers) - 1
connections = [1] * nodes
changed = 0;
closest = 10000000000
while changed == 0:
#print connections
built = [[1]] + [0] * (nodes - 1)
closest = chooselayer(connections, built, 1, nodes, numbers, find, closest)
changed = shuntconnection(connections, nodes, nodes, nodes)
""" Main entry point
"""
if len(sys.argv) > 3:
find = int(sys.argv[-1])
nums = map(int, sys.argv[1:-1])
connections(nums, find)
else:
print "Syntax: countdown n_1 n_2 ... n_m sum"
|
dbd5be5f5ba49f3ff8340d835c203be524583be3 | michelmora/python3Tutorial | /BegginersVenv/forLoop.py | 1,173 | 3.875 | 4 | # For loops
# The last number (11) is not included. This will output the numbers 1 to 10.
# for i in range(1, 11):
# print(i)
# Python itself starts counting from 0, so this code will also work but will output 0 to 9
# for i in range(0, 10):
# print(i)
# equivalent to
for i in range(10):
print(i)
# using list
x = [i for i in range(10)]
print(x)
# using dict
list_ = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ]
y = {i: list_[i] for i in range(len(list_))}
print(y)
# equivalent to
z = dict(enumerate(list_))
print(z)
a = 42
b = list(a + i for i in range(10))
print(b)
c = 42
d = [a + i for i in range(10)]
print(b)
print(list(range(5)))
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else: # loop fell through without finding a factor
print(n, 'is a prime number')
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
# cat 3
# window 6
# defenestrate 12
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
# ['defenestrate', 'cat', 'window', 'defenestrate']
|
7b692f7ea4d8718261e528d07222061dc3e35de8 | michelmora/python3Tutorial | /BegginersVenv/dateAndTime.py | 757 | 4.375 | 4 | # Computers handle time using ticks. All computers keep track of time since 12:00am, January 1, 1970, known as epoch
# time. To get the date or time in Python we need to use the standard time module.
import time
ticks = time.time()
print("Ticks since epoch:", ticks)
# To get the current time on the machine, you can use the function localtime:
timenow = time.localtime(time.time())
print("Current time :", timenow)
# You can access each of the elements of the array:
timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])
# and use a combination for your own formatting. One alternative is to use the asctime function:
timenow = time.asctime(time.localtime(time.time()))
print(timenow)
|
4dd9a591648531943ccd60b984e1d3f0b72a800c | michelmora/python3Tutorial | /BegginersVenv/switch(HowToSimulate).py | 2,519 | 4.21875 | 4 | # An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
# OPTION No.1
def dog_sound():
return 'hau hau'
def cat_sound():
return 'Me au'
def horse_sound():
return 'R R R R'
def cow_sound():
return 'M U U U'
def no_sound():
return "Total silence"
switch = {
'dog': dog_sound,
'cat': cat_sound,
'horse': horse_sound,
'cow': cow_sound,
}
# value = input("Enter the animal: ")
# if value in switch:
# sound = switch[value]()
# else:
# sound = no_sound()
# # default
#
# print(sound)
# OPTION No.2
# define the function blocks
def zero():
print("You typed zero.\n")
def sqr():
print("n is a perfect square\n")
def even():
print("n is an even number\n")
def prime():
print("n is a prime number\n")
# map the inputs to the function blocks
options = {0: zero,
1: sqr,
4: sqr,
9: sqr,
2: even,
3: prime,
5: prime,
7: prime,
}
# options[10]()
# OPTION NO. 3
# A very elegant way
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
print(numbers_to_strings(2))
# OPTION NO. 4
# Dictionary Mapping for Functions
def zero():
return "zero"
def one():
return "one"
def numbers_to_functions_to_strings(argument):
switcher = {
0: zero,
1: one,
2: lambda: "two",
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "nothing")
# Execute the function
return func()
print(numbers_to_functions_to_strings(3))
# OPTION NO. 5
# Dispatch Methods for Classes
# If we don't know what method to call on a class, we can use a dispatch method to determine it at runtime.
class Switcher(object):
def numbers_to_methods_to_strings(self, argument):
"""Dispatch method"""
# prefix the method_name with 'number_' because method names
# cannot begin with an integer.
method_name = 'number_' + str(argument)
# Get the method from 'self'. Default to a lambda.
method = getattr(self, method_name, lambda: "nothing")
# Call the method as we return it
return method()
def number_2(self):
return "two"
def number_0(self):
return "zero"
def number_1(self):
return "one"
tes = Switcher()
print(tes.numbers_to_methods_to_strings(4))
|
d9eb301592bb6cea584f5bee079947d852dd30a4 | michelmora/python3Tutorial | /BegginersVenv/functions.py | 3,923 | 4.5 | 4 | # Functions
import math
def pythagoras(a, b):
value = math.sqrt(a * a + b * b)
return value
# print([pythagoras(3, 3)])
# The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list
# of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
# The first statement of the function body can optionally be a string literal; this string literal is the function’s
# documentation string, or docstring. (More about docstrings can be found in the section Documentation Strings.)
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=" ")
a, b = b, a + b
print()
fib(200000)
# There are tools which use docstrings to automatically produce online or printed documentation, or to let the user
# interactively browse through code; it’s good practice to include docstrings in code that you write, so make
# a habit of it.
# The execution of a function introduces a new symbol table used for the local variables of the function. More
# precisely, all variable assignments in a function store the value in the local symbol table; whereas variable
# references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the
# global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly
# assigned a value within a function (unless named in a global statement), although they may be referenced.
#
# The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function
# when it is called; thus, arguments are passed using call by value (where the value is always an object reference,
# not the value of the object). [1] When a function calls another function, a new local symbol table is created for
# that call.
#
# A function definition introduces the function name in the current symbol table. The value of the function name has a
# type that is recognized by the interpreter as a user-defined function. This value can be assigned to another
# name which can then also be used as a function. This serves as a general renaming mechanism
# Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t return a
# value. In fact, even functions without a return statement do return a value, albeit a rather boring one. This value
# is called None (it’s a built-in name). Writing the value None is normally suppressed by the interpreter if it would
# be the only value written. You can see it if you really want to using print():
# fib(0)
# print(fib(0))
# None
# It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it
def fib2(n):
a, b = 0, 1
result = []
while a < n:
result.append(a)
a, b = b, a + b
return result
print(fib2(2000))
# The return statement returns with a value from a function. return without an expression argument returns None.
# Falling off the end of a function also returns None.
# The statement result.append(a) calls a method of the list object result. A method is a function that ‘belongs’ to
# an object and is named obj.methodname, where obj is some object (this may be an expression), and methodname is the
# name of a method that is defined by the object’s type. Different types define different methods. Methods of different
# types may have the same name without causing ambiguity. (It is possible to define your own object types and methods,
# using classes, see Classes) The method append() shown in the example is defined for list objects; it adds a new
# element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient.
|
8dee8c987a27474de2b12a4a783dddc7aa142260 | darrengidado/portfolio | /Project 3 - Wrangle and Analyze Data/Update_Zipcode.py | 1,333 | 4.21875 | 4 | '''
This code will update non 5-digit zipcode.
If it is 8/9-digit, only the first 5 digits are kept.
If it has the state name in front, only the 5 digits are kept.
If it is something else, will not change anything as it might result in error when validating the csv file.
'''
def update_zipcode(zipcode):
"""Clean postcode to a uniform format of 5 digit; Return updated postcode"""
if re.findall(r'^\d{5}$', zipcode): # 5 digits 02118
valid_zipcode = zipcode
return valid_zipcode
elif re.findall(r'(^\d{5})-\d{3}$', zipcode): # 8 digits 02118-029
valid_zipcode = re.findall(r'(^\d{5})-\d{3}$', zipcode)[0]
return valid_zipcode
elif re.findall(r'(^\d{5})-\d{4}$', zipcode): # 9 digits 02118-0239
valid_zipcode = re.findall(r'(^\d{5})-\d{4}$', zipcode)[0]
return valid_zipcode
elif re.findall(r'CA\s*\d{5}', zipcode): # with state code CA 02118
valid_zipcode =re.findall(r'\d{5}', zipcode)[0]
return valid_zipcode
else: #return default zipcode to avoid overwriting
return zipcode
def test_zip():
for zips, ways in zip_print.iteritems():
for name in ways:
better_name = update_zipcode(name)
print name, "=>", better_name
if __name__ == '__main__':
test_zip()
|
76873baab78e9765b6339cb3f7e312e7bec2963d | NeniscaMaria/Grades-and-Assignments-Manager-Application | /GUI.py | 24,927 | 3.671875 | 4 | from tkinter import *
from UI import *
class GUI(UI):
def __init__(self,__students,__assignments,__grades,__undoRedo):
UI.__init__(self, __students, __assignments, __grades, __undoRedo)
self.__window=Tk()
#here I write the name of the project
self.__window.title('Assignments')
self.__window.config(background='black')
#here we create the labels and the text entry boxes for students
self.__labelStudent=Label(self.__window,text='Students:',bg='black',fg='white',font='none 10 bold').grid(row=0,column=0,sticky=E)
self.__labelStudentID=Label(self.__window,text='StudentID:',bg='black',fg='white',font='none 10 bold').grid(row=0,column=1,sticky=E)
self.__textEntryStudentsID=Entry(self.__window,width=10,bg='white')
self.__textEntryStudentsID.grid(row=0,column=2,sticky=E)
self.__labelStudentName=Label(self.__window,text='Name:',bg='black',fg='white',font='none 10 bold').grid(row=0,column=3,sticky=E)
self.__textEntryStudentsName=Entry(self.__window,width=30,bg='white')
self.__textEntryStudentsName.grid(row=0,column=4,sticky=E)
self.__labelStudentGroup=Label(self.__window,text='Group:',bg='black',fg='white',font='none 10 bold').grid(row=0,column=5,sticky=E)
self.__textEntryStudentsGroups=Entry(self.__window,width=5,bg='white')
self.__textEntryStudentsGroups.grid(row=0,column=6,sticky=E)
#now we create the submit boxes
self.__buttonStudentAdd=Button(self.__window,text='ADD',width=6,command=self.__addStudent).grid(row=0,column=7,sticky=E)
self.__buttonStudentRemove=Button(self.__window,text='REMOVE',width=6,command=self.__removeStudent).grid(row=0,column=8,sticky=E)
self.__buttonStudentUpdate=Button(self.__window,text='UPDATE',width=6,command=self.__updateStudent).grid(row=0,column=9,sticky=E)
#here we create the labels and the text entry boxes for assignments
self.__labelAssignments=Label(self.__window,text='Assignments:',bg='black',fg='white',font='none 10 bold').grid(row=1,column=0,sticky=E)
self.__labelAssignmentID=Label(self.__window,text='AssignmentID:',bg='black',fg='white',font='none 10 bold').grid(row=1,column=1,sticky=E)
self.__textEntryAssignmentID1=Entry(self.__window,width=10,bg='white')
self.__textEntryAssignmentID1.grid(row=1,column=2,sticky=E)
self.__labelAssignmentDescription=Label(self.__window,text='Description:',bg='black',fg='white',font='none 10 bold').grid(row=1,column=3,sticky=E)
self.__textEntryAssignmentDescription=Entry(self.__window,width=30,bg='white')
self.__textEntryAssignmentDescription.grid(row=1,column=4,sticky=E)
self.__labelAssignmentDeadline=Label(self.__window,text='Deadline:',bg='black',fg='white',font='none 10 bold').grid(row=1,column=5,sticky=E)
self.__textEntryAssignmentDeadline=Entry(self.__window,width=5,bg='white')
self.__textEntryAssignmentDeadline.grid(row=1,column=6,sticky=E)
#now we create the submit boxes
self.__buttonAssignmentAdd=Button(self.__window,text='ADD',width=6,command=self.__addAssignment).grid(row=1,column=7,sticky=E)
self.__buttonAssignmentRemove=Button(self.__window,text='REMOVE',width=6,command=self.__removeAssignment).grid(row=1,column=8,sticky=E)
self.__buttonAssignmentUpdate=Button(self.__window,text='UPDATE',width=6,command=self.__updateAssignment).grid(row=1,column=9,sticky=E)
#here we create the labels and the text entry boxes for grades
self.__labelGrades=Label(self.__window,text='Grades:',bg='black',fg='white',font='none 10 bold').grid(row=2,column=0,sticky=E)
self.__labelGradesStudentID=Label(self.__window,text='StudentID:',bg='black',fg='white',font='none 10 bold').grid(row=2,column=1,sticky=E)
self.__textEntryGradesStduentsID=Entry(self.__window,width=10,bg='white')
self.__textEntryGradesStduentsID.grid(row=2,column=2,sticky=E)
self.__labelGradesAssignmentID=Label(self.__window,text='AssignmentID:',bg='black',fg='white',font='none 10 bold').grid(row=2,column=3,sticky=E)
self.__textEntryAssignmentID=Entry(self.__window,width=10,bg='white')
self.__textEntryAssignmentID.grid(row=2,column=4,sticky=E)
self.__labelGradesValue=Label(self.__window,text='Grade:',bg='black',fg='white',font='none 10 bold').grid(row=2,column=5,sticky=E)
self.__textEntryGradesValue=Entry(self.__window,width=5,bg='white')
self.__textEntryGradesValue.grid(row=2,column=6,sticky=E)
#now we create the submit boxes
self.__buttonGradesAdd=Button(self.__window,text='ADD',width=6,command=self.__grade).grid(row=2,column=7,sticky=E)
#here we create the labels and boxes for assigning
self.__labelAssiging=Label(self.__window,text='Assigning:',bg='black',fg='white',font='none 10 bold').grid(row=3,column=0,sticky=E)
self.__labelAssignStudent=Label(self.__window,text='StudentID:',bg='black',fg='white',font='none 10 bold').grid(row=3,column=1,sticky=E)
self.__textEntryAssignStudentID=Entry(self.__window,width=10,bg='white')
self.__textEntryAssignStudentID.grid(row=3,column=2,sticky=E)
self.__labelAssignGroup=Label(self.__window,text='Group:',bg='black',fg='white',font='none 10 bold').grid(row=4,column=1,sticky=E)
self.__textEntryAssignGroup=Entry(self.__window,width=10,bg='white')
self.__textEntryAssignGroup.grid(row=4,column=2,sticky=E)
self.__labelAssignAssignment=Label(self.__window,text='AssignmentID:',bg='black',fg='white',font='none 10 bold').grid(row=3,column=3,sticky=E)
self.__textEntryAssignAssignmentID=Entry(self.__window,width=30,bg='white')
self.__textEntryAssignAssignmentID.grid(row=3,column=4,sticky=E)
self.__labelAssignAssignment1=Label(self.__window,text='AssignmentID:',bg='black',fg='white',font='none 10 bold').grid(row=4,column=3,sticky=E)
self.__textEntryAssignAssignmentID1=Entry(self.__window,width=30,bg='white')
self.__textEntryAssignAssignmentID1.grid(row=4,column=4,sticky=E)
#here we create the submit boxes
self.__buttonAssign=Button(self.__window,text='ASSIGN',width=6,command=self.__assignStudent).grid(row=3,column=7,sticky=E)
self.__buttonAssign1=Button(self.__window,text='ASSIGN',width=6,command=self.__assignGroup).grid(row=4,column=7,sticky=E)
#here we create the labels and submit boxes for the listings
self.__labelLists=Label(self.__window,text='List:',bg='black',fg='white',font='none 10 bold').grid(row=6,column=0,sticky=E)
self.__buttonList1=Button(self.__window,text='Students',width=7,command=self.__listStudent).grid(row=6,column=1,sticky=E)
self.__buttonList2=Button(self.__window,text='Assignments',width=10,command=self.__listAssignment).grid(row=6,column=2,sticky=W)
self.__buttonList3=Button(self.__window,text='Grades',width=5,command=self.__listGrades).grid(row=6,column=2,sticky=E)
#here we create the labels and submit boxes for the statistics
self.__labelStat=Label(self.__window,text='Statistics:',bg='black',fg='white',font='none 10 bold').grid(row=7,column=0,sticky=E)
self.__labelStat1=Label(self.__window,text='AssignmentID:',bg='black',fg='white',font='none 10 bold').grid(row=7,column=1,sticky=E)
self.__textEntryStat1=Entry(self.__window,width=10,bg='white')
self.__textEntryStat1.grid(row=7,column=2,sticky=W)
self.__buttonStat1=Button(self.__window,text='STAT',width=5,command=self.__stat).grid(row=7,column=3,sticky=W)
self.__buttonStat2=Button(self.__window,text='LATE',width=5,command=self.__late).grid(row=7,column=3)
self.__buttonStat3=Button(self.__window,text='TOP',width=5,command=self.__top).grid(row=7,column=3,sticky=E)
self.__buttonStat4=Button(self.__window,text='ALL',width=5,command=self.__all).grid(row=7,column=4,sticky=W)
#here we create the help and undo/redo buttons
self.__buttonHelp=Button(self.__window,text='Help',width=5,command=self.__help).grid(row=8,column=9,sticky=E)
self.__buttonUndo=Button(self.__window,text='UNDO',width=5,command=self.__undo).grid(row=8,column=0,sticky=E)
self.__buttonRedo=Button(self.__window,text='REDO',width=5,command=self.__redo).grid(row=8,column=1,sticky=W)
#here we create the output box
self.__output=Text(self.__window,width=100,height=25,wrap=WORD, background='white')
self.__output.grid(row=10,column=1,columnspan=6,sticky=W)
def __popUp(self,message):
popup=Tk()
popup.wm_title("!!")
message=str(message)+"\n Check the Help meniu for instructions"
label=Label(popup,text=message,font='Verdana 10')
label.pack(side="top", fill='x', pady=10)
button1=Button(popup,text='Okay',command=popup.destroy)
button1.pack()
popup.mainloop()
def __assignGroup(self,undoable=True):
group=self.__textEntryAssignGroup.get()
assignmentID=self.__textEntryAssignAssignmentID1.get()
command='group '+group+ ' assignment '+assignmentID
try:
UI.checkCommand(self, command)
self._assign.assignToGroup(command)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
v=command.split()
group=int(v[1])
assignmentID=int(v[3])
x='deassignGroup '+str(group)+" "+str(assignmentID)
commandUndo=FunctionCall(UI.deassignGroup,self,x)
commandRedo=FunctionCall(UI.assignGroup,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __assignStudent(self,undoable=True):
studentID=self.__textEntryAssignStudentID.get()
assignmentID=self.__textEntryAssignAssignmentID.get()
command='student '+studentID+ ' assignment '+assignmentID
try:
UI.checkCommand(self, command)
self._assign.assignToStudent(command)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
v=command.split(" ")
studentID=int(v[1])
assignmentID=int(v[3])
commandRedo=FunctionCall(UI.assignStudent,self,command)
x='deassignStudent '+str(studentID)+" "+str(assignmentID)
commandUndo=FunctionCall(UI.deassignStudent,self,x)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __help(self):
self.__output.delete(0.0, END)
self.__output.insert(END,"ATTENTION! All the text boxes are case sensitive!\n\n")
self.__output.insert(END,"When removing a student/an assignment is enough to insert only the ID.\n\n")
self.__output.insert(END,"When you want to update a student, complete the studentID field with the ID of the student you want to update, and complete the group field with the group in which you want to transfer the student.\n\n")
self.__output.insert(END,"When you want to update an assignment, complete the following fields as shown below:\n")
self.__output.insert(END,"\t->assignmentID field: with the ID of the assignment you want to update\n")
self.__output.insert(END,"\t->description field:->complete it with the new description\n")
self.__output.insert(END,"\t\t->complete it with 'None' if you don't want to change the description\n")
self.__output.insert(END,"\t->deadline field:->complete it with the new deadline\n")
self.__output.insert(END,"\t\t->complete it with 'None' if you don't want to change the deadline\n\n")
self.__output.insert(END,"Instructions for statistics:\n")
self.__output.insert(END,"\t->STAT:if you want all students who received a given assignment, ordered alphabetically. This is the only one that requires an assignmentID.\n")
self.__output.insert(END,"\t->LATE:if you want all students who are late in handing in at least one assignment. These are all the students who have an ungraded assignment for which the deadline has passed.\n")
self.__output.insert(END,"\t->TOP:if you want the students with the best school situation, sorted in descending order of the average grade received for all assignments.\n")
self.__output.insert(END,"\t->ALL:if you want all assignments for which there is at least one grade, sorted in descending order of the average grade received by all students who received that assignment.\n")
def __undo(self):
try:
commandUndo=self._undoRedo.undo()
if commandUndo==False:
self.__popUp("No more undos can be done!")
except ValueError as ve:
self.__popUp(ve)
def __redo(self):
try:
commandRedo=self._undoRedo.redo()
if commandRedo==False:
self.__popUp("No more redos can be done!")
except ValueError as ve:
self.__popUp(ve)
def __addStudent(self,undoable=True):
ID=self.__textEntryStudentsID.get()
name=self.__textEntryStudentsName.get()
group=self.__textEntryStudentsGroups.get()
command='add '+ID+" "+name+" "+group
try:
UI.checkCommand(self, command)
self._controllerStudent.addStudent(command,self._groups,self._idlist,self._assignmentDict)
#the following are for when we will undo/redo an operation
self._controllerGrades.restoreStudentGrades(ID,self._removedStudents)
self._assign.restoreStudents(self._removedStudentsAssignment, ID)
#here you put the way to undo/redo in the list of operations
if undoable==True:
command1='remove student '+str(ID)
commandUndo=FunctionCall(UI.remove,self,command1)
commandRedo=FunctionCall(UI.add,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __removeStudent(self,undoable=True):
ID=self.__textEntryStudentsID.get()
command='remove student '+ID
try:
UI.checkCommand(self, command)
command1=self._controllerStudent.removeStudent(command,self._groups)
self._assign.removeStudent(command,self._removedStudentsAssignment)
self._controllerGrades.removeStudent(command,self._removedStudents)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
commandRedo=FunctionCall(UI.remove,self,command)
commandUndo=FunctionCall(UI.add,self,command1)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __updateStudent(self,undoable=True):
ID=self.__textEntryStudentsID.get()
group=self.__textEntryStudentsGroups.get()
command='update student '+ID+" "+group
try:
UI.checkCommand(self, command)
command1=self._controllerStudent.updateStudent(command,self._groups)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
commandUndo=FunctionCall(UI.update,self,command1)
commandRedo=FunctionCall(UI.update,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __addAssignment(self,undoable=True):
ID=self.__textEntryAssignmentID1.get()
description=self.__textEntryAssignmentDescription.get()
deadline=self.__textEntryAssignmentDeadline.get()
command='add '+ID+" description "+description+" deadline "+deadline
try:
UI.checkCommand(self, command)
self._controllerAssignments.addAssignment(command)
self._controllerGrades.restoreGradesAssignment(ID,self._removedAssignments)
self._assign.restoreAssignments(self._removedAssignmentsAssignments, ID)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
command1="remove assignment "+str(ID)
commandUndo=FunctionCall(UI.remove,self,command1)
commandRedo=FunctionCall(UI.add,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __removeAssignment(self,undoable=True):
ID=self.__textEntryAssignmentID1.get()
command='remove assignment '+ID
try:
UI.checkCommand(self, command)
command1=self._controllerAssignments.removeAssignment(command)
self._assign.removeAssignment(command,self._removedAssignmentsAssignments)
self._controllerGrades.removeAssignment(command,self._removedAssignments)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
commandUndo=FunctionCall(UI.add,self,command1)
commandRedo=FunctionCall(UI.remove,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __updateAssignment(self,undoable=True):
ID=self.__textEntryAssignmentID1.get()
description=self.__textEntryAssignmentDescription.get()
if description=="":
description="None"
deadline=self.__textEntryAssignmentDeadline.get()
if deadline=="":
deadline="None"
command='update assignment '+ID+" description "+description+" deadline "+deadline
try:
UI.checkCommand(self, command)
command1=self._controllerAssignments.updateAssignment(command)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
commandUndo=FunctionCall(UI.update,self,command1)
commandRedo=FunctionCall(UI.update,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __grade(self,undoable=True):
studentID=self.__textEntryGradesStduentsID.get()
assignmentID=self.__textEntryAssignmentID.get()
gradeValue=self.__textEntryGradesValue.get()
command='grade '+gradeValue+ ' to student '+studentID+ ' for '+assignmentID
try:
UI.checkCommand(self, command)
self._controllerGrades.add(command)
#here you put the way to undo/redo the command in the list of operations
if undoable==True:
command1='removeGrade '+str(gradeValue)+" from student "+str(studentID)+" for "+str(assignmentID)
commandUndo=FunctionCall(UI.removeGrade,self,command1)
commandRedo=FunctionCall(UI.grade,self,command)
operation=Operation(commandRedo,commandUndo)
self._undoRedo.add(operation)
except ValueError as ve:
self.__popUp(ve)
def __listStudent(self):
self.__output.delete(0.0, END)
listOfStudents=self._repoStudents.getAll()
i=0
self.__output.insert(END,"The students are:\n")
while i<len(listOfStudents):
self.__output.insert(END,str(i+1)+") "+str(listOfStudents[i])+'\n')
i+=1
if i==0:
self.__output.insert(END,"There are no students.")
def __listAssignment(self):
self.__output.delete(0.0, END)
'''
THIS FUNCTION PRINTS ALL THE ASSIGNMENTS
INPUT:ASSIGNMENTS=THE REPOSITORY OF THE ASSIGNMENTS
OUTPUT:-
'''
listOfAssignments=self._repoAssignments.getAll()
i=0
self.__output.insert(END,"The assignmnents are:\n")
while i<len(listOfAssignments):
self.__output.insert(END,str(i+1)+") "+str(listOfAssignments[i])+'\n')
i+=1
if i==0:
self.__output.insert(END,"There are no assignments.")
def __listGrades(self):
self.__output.delete(0.0, END)
'''
THIS FUNCTION PRINTS ALL THE GRADES EXISTING IN THE REPOSITORY
'''
listOfGrades=self._repoGrades.getAll()
if len(listOfGrades)==0:
self.__output.insert(END,"There are no grades yet.")
else:
i=0
while i<len(listOfGrades):
self.__output.insert(END,str(i+1)+") "+str(listOfGrades[i])+'\n')
i+=1
def __stat(self):
self.__output.delete(0.0, END)
assignmentID=self.__textEntryStat1.get()
if assignmentID=='':
self.__popUp("Plese complete the 'AssignmentID' field")
return
command='stat assignment '+assignmentID+ ' alpha'
statistics=Statistics(self._idlist,self._repoGrades,self._assignmentDict,self._repoStudents)
try:
listStat=statistics.stat(command)
if len(listStat)==0:
self.__output.insert(END,"There are no students with this assignment.\n")
for i in range(len(listStat)):
self.__output.insert(END,str(i+1)+") "+str(listStat[i])+'\n')
except ValueError as ve:
self.__output.insert(END,ve)
def __late(self):
self.__output.delete(0.0, END)
repoOfLateStudents=self._assign.getLate()
lateStudents=repoOfLateStudents.getAll()
if len(lateStudents)==0:
self.__output.insert(END,"There are no late students.\n")
else:
i=0
self.__output.insert(END,"The late students are:\n")
while i<len(lateStudents):
self.__output.insert(END,str(i+1)+") "+str(lateStudents[i])+'\n')
i+=1
def __top(self):
'''
THIS LIST listTop WILL HAVE THE FOLLOWING MEANING:
[[studentID,averageGrade],[studentID1,averageGrade1],...]
'''
self.__output.delete(0.0, END)
statistics=Statistics(self._idlist,self._repoGrades,self._assignmentDict,self._repoStudents)
try:
listTop=statistics.top()
for i in range(len(listTop)):
studentID=listTop[i][0]
avg_grade=listTop[i][1]
student=self._repoStudents.search(studentID)
self.__output.insert(END,str(i+1)+") "+str(student)+" with average grade of: "+str(avg_grade)+'\n')
except ValueError as ve:
self.__popUp(ve)
def __all(self):
self.__output.delete(0.0, END)
statistics=Statistics(self._idlist,self._repoGrades,self._assignmentDict,self._repoStudents)
try:
listAll=statistics.all()
for i in range(len(listAll)):
assignmentID=listAll[i][0]
avg_grade=listAll[i][1]
self.__output.insert(END,str(i+1)+") Assignment "+str(assignmentID)+" with average grade of: "+str(avg_grade)+'\n')
except ValueError as ve:
self.__popUp(ve)
def run(self):
self.__window.mainloop()
def populateStudents(self):
UI.populateStudents(self)
def populateAssignments(self):
UI.populateAssignments(self)
'''
students=Repository()
assignments=Repository()
grades=Repository()
undoRedo=UndoRedo()
userInterface=GUI(students,assignments,grades,undoRedo)
userInterface.populateStudents()
userInterface.populateAssignments()
userInterface.run()'''
|
3177bc787712977e88acaa93324b7b43c25016f9 | sudharsan004/fun-python | /FizzBuzz/play-with-python.py | 377 | 4.1875 | 4 | #Enter a number to find if the number is fizz,buzz or normal number
n=int(input("Enter a number-I"))
def fizzbuzz(n):
if (n%3==0 and n%5==0):
print(str(n)+"=Fizz Buzz")
elif (n%3==0):
print(str(n)+"=Fizz")
elif (n%5==0):
print(str(n)+"=Buzz")
else:
print(str(n)+"=Not Fizz or Buzz")
fizzbuzz(n)
#define a function
|
c933295fd67c0499071ea60566b9961dc4491ca1 | krishna-kumar456/Code-Every-Single-Day | /solutions/alarm.py | 357 | 4.03125 | 4 | """ Alarm Clock.
"""
import datetime
def ring():
print('Beep')
user_input_hour = int(input('Enter Hour'))
user_input_minutes = int(input('Enter minutes'))
beep = True
while beep:
now = datetime.datetime.now()
print(now.hour, now.minute, now.second)
if user_input_hour == now.hour and user_input_minutes == now.minute:
ring()
beep = False
|
f0f5449257bb860b1bb294531016869f8883f78f | krishna-kumar456/Code-Every-Single-Day | /solutions/reverse.py | 115 | 4.09375 | 4 | """ Reverse a string.
"""
if __name__ == '__main__':
string = input('Please enter string ')
print(string[::-1]) |
8078d00c4923e26e25e2079bfcbf2110fd8dccda | krishna-kumar456/Code-Every-Single-Day | /solutions/sieveofe.py | 657 | 3.96875 | 4 | """
Sieve of Eratosthenes.
1. Generate numbers to the limit.
2. Start with 2, eliminate multiples of 2.
3. Proceed to next number (3), eliminate multiples of 3
4. Keep looping until p2 > n.
"""
userInput = int(input('Please enter the upper limit'))
def primes_sieve2(limit):
a = [False] * 2 + [True] * (limit-2) # Initialize the primality list
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
yield i
for n in range(i*i, limit, i): # Mark factors non-prime
a[n] = False
result = primes_sieve2(userInput)
for items in result:
print(items)
|
bf90882a0af31c4272a9fee19aa2716760847bbc | krishna-kumar456/Code-Every-Single-Day | /solutions/piglatin.py | 1,060 | 4.375 | 4 | """ Pig Lating Conversion
"""
def convert_to_pig_latin(word):
""" Returns the converted string based on the
rules defined for Pig Latin.
"""
vowels = ['a', 'e', 'i', 'o', 'u']
char_list = list(word)
""" Vowel Rule.
"""
if char_list[0] in vowels:
resultant_word = word + 'way'
""" Consonant Rule.
"""
if char_list[0] not in vowels:
resultant_word = ''.join(char_list[1:]) + str(char_list[0]) + 'a'
""" Consonant Cluster Rule.
"""
if char_list[0] == 'c' and char_list[1] == 'h':
resultant_word = ''.join(char_list[2:]) + char_list[0] + char_list[1] + 'ay'
elif char_list[0] == 's' and char_list[1] == 'h' or char_list[1] =='t' or char_list[1] == 'm':
resultant_word = ''.join(char_list[2:]) + char_list[0] + char_list[1] + 'ay'
elif char_list[0] == 't' and char_list[1] == 'h':
resultant_word = ''.join(char_list[2:]) + char_list[0] + char_list[1] + 'ay'
return resultant_word
if __name__ == '__main__':
word = input('Please enter the word for conversion ')
print('Post conversion ', convert_to_pig_latin(word)) |
d61abfa306531eec1db532e82dff32f2472849fa | Polsonby/cd-python-tictac | /play.py | 2,863 | 3.890625 | 4 | import random
game_in_progress = True
x_char = 'X'
o_char = 'O'
space_char = ' '
board = [space_char, space_char, space_char,
space_char, space_char, space_char,
space_char, space_char, space_char]
player_character = ''
computer_character = ''
def drawBoard(data):
print("""
1 |2 |3
%s | %s | %s
| |
-----------
4 |5 |6
%s | %s | %s
| |
-----------
7 |8 |9
%s | %s | %s
| |
""" % tuple(data))
def validMove(move):
if move > 8:
return False
elif move < 0:
return False
elif not boxFree(move):
return False
else:
return True
def getPlayerMove():
while True:
try:
choice = int(input("Where would you like to go? "))
choice -= 1
except ValueError:
print("This number must be an integer!")
continue
if choice > 8:
print ("This is too high")
elif choice < 0:
print ("This is too low")
elif not boxFree(choice):
print ("This space has already been taken!")
else:
break
writePosition(player_character, choice);
def calculateComputerMove():
while True:
choice = random.randint(1, 9) - 1
if validMove(choice):
break
writePosition(computer_character, choice);
def getPlayerCharacter():
global player_character, computer_character
# loop forever
keep_looping = True
while keep_looping:
test_string = input("Would you like to be %s or %s? " % (x_char, o_char)).upper()
if test_string == x_char or test_string == o_char:
player_character = test_string
computer_character = o_char if player_character == x_char else x_char
keep_looping = False
else:
print("Sorry but this must be either %s or %s - Try again!" % (x_char, o_char))
def boxFree(move):
if board[move] == space_char:
return True
else:
return False
def writePosition(user_character, position):
board[position] = user_character
print("Naughts and Crosses\n")
getPlayerCharacter()
print(player_character)
def isWinner(char):
return (board[0] == char and board[1] == char and board[2] == char) or (board[0] == char and board[4] == char and board[8] == char) or (board[0] == char and board[3] == char and board[6] == char) or (board[1] == char and board[4] == char and board[7] == char) or (board[2] == char and board[4] == char and board[6] == char) or (board[2] == char and board[5] == char and board[8] == char)or (board[3] == char and board[4] == char and board[5] == char)or (board[6] == char and board[7] == char and board[8] == char)
def getGameStatus():
#print("Game won" if isWinner('X') or isWinner('O') else "Game still playing")
if isWinner('X'):
return 1
elif isWinner("O"):
return 2
else:
return 0
def printStatusMessage(status):
if status == 1:
print ("x won!")
elif status == 2:
print ("O won")
while game_in_progress == True:
drawBoard(board)
getPlayerMove()
calculateComputerMove()
status = getGameStatus()
printStatusMessage(status)
|
54ce7655f0a25a5dcbbbefabd772ebcec4b31759 | JackRossProjects/OpenCV2-Notes | /ch4-shapes-and-texts.py | 942 | 3.75 | 4 | import cv2
import numpy as np
# Create an image of size 512x512 with color functionality but initialize to 0 (black)
img = np.zeros((512,512,3), np.uint8)
# (512, 512) = grayscale || (512, 512, 3) = color functionality
# If we want to make the entire ([:]) image (img) blue (255, 0, 0)
# img[:] = 255, 0, 0
# Adding a line
# cv2.line(image, startpoint, end point, color, thickness)
cv2.line(img,(0,0), (300,300), (0, 255, 0), 3)
# Drawing a rectangle (same convention as above)
# cv2.FILLED will fill in any shape i.e. this rectangle
cv2.rectangle(img, (0,0), (250, 350), (0,0,255), 2, cv2.FILLED)
# Drawing a circle
# cv2.circle(image, center, radius, color, thickness)
cv2.circle(img, (400, 200), 30, (255, 255, 0), 2)
# Adding text
# cv2.putText(image, text, start, font, font scale, color, thickness)
cv2.putText(img, "OpenCV ROCKS!", (200, 100), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 150, 0), 1)
cv2.imshow("image", img)
cv2.waitKey(0)
|
cfd8e159d8ba84cfbf47ea88fd83826b3c59c7be | ryanmalani/IT-129 | /quiz2-1.py | 303 | 3.765625 | 4 | fhand = open("therepublic.txt")
count = 0
def find_a_word(fname, key_word):
for line in fhand:
if line.lower().startswith(key_word):
count = count + 1
return count
find_a_word("therepublic.txt", "plato")
print(key_word + " showed up " + str(count) + " times in " + fname)
|
73ad6ddc678473757ca369582a5a49439ac750ee | ryanmalani/IT-129 | /ex_8_4.py | 341 | 3.703125 | 4 | #Ryan Malani
try:
fname = input('Enter file name: ')
fhand = open(fname)
readfile = fhand.read()
words = readfile.split()
for word in words:
if words.count(word) == 1:
uniqueWords = []
uniqueWords.append(word)
print(uniqueWords)
except:
print('Invalid Input for file: ', fname)
|
0ba68f90c272d4db39968f77cbabf5bf578f6546 | tdd-laboratory/tdd-homework-dastardlychimp | /library.py | 3,219 | 3.609375 | 4 | import re
from typing import Tuple
_whole_word = lambda x: re.compile(r"\b{}\b".format(x))
_date_iso8601_pat = _whole_word(r'(\d{4})-(0\d|1[0-2])-(0[1-9]|[12][0-9]|3[01])')
_date_month_word_pat = _whole_word(r'(\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4})');
_mixed_ordinal_pat = _whole_word(r'-?\d+(st|th|nd|rd)')
_integer_pat = _whole_word(r'\d+')
_floating_point_after_pat = re.compile(r'\.\d+[^a-zA-Z.]')
_floating_point_before_pat = re.compile(r'(?<=\d\.)')
DateTuple = Tuple[int, int, int]
def valid_date(date_tuple: DateTuple):
'''Verify that the (year, month, day) DateTuple is a valid date.'''
# Python way is to not check type, but otherwise floats would be valid.
for v in date_tuple:
if not isinstance(v, int):
raise ValueError
(year, month, day) = date_tuple
valid = False
if year > 0 and month > 0 and day > 0 and month < 13:
if month == 2:
if day == 29 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
valid = True
elif day < 29:
valid = True
elif month in [4, 6, 9, 11] and day < 31:
valid = True
elif month in [1, 3, 5, 7, 8, 10, 12] and day < 32:
valid = True
return valid
def dates_iso8601(text):
'''Find iso8601 dates in text, e.g. "2140-01-25" '''
_date_tuple_from_match = lambda match: tuple(map(int, match.groups()))
matches = _date_iso8601_pat.finditer(text)
for match in _date_iso8601_pat.finditer(text):
date_tuple = _date_tuple_from_match(match)
if valid_date(date_tuple):
yield ('iso8601', match)
def dates_month_word(text):
''' Find dates in the format of 21 Dec 1842 '''
months = {
'Jan': 1,
'Feb': 2,
'Mar': 3,
'Apr': 4,
'May': 5,
'Jun': 6,
'Jul': 7,
'Aug': 8,
'Sep': 9,
'Oct': 10,
'Nov': 11,
'Dec': 12
}
for match in _date_month_word_pat.finditer(text):
(day, month, year) = match.groups()
date_tuple = (int(year), months.get(month, -1), int(day))
if valid_date(date_tuple):
yield ('date_month_word', match)
def mixed_ordinals(text):
'''Find tokens that begin with a number, and then have an ending like 1st or 2nd.'''
for match in _mixed_ordinal_pat.finditer(text):
yield ('ordinal', match)
def integers(text):
'''Find integers in text. Don't count floating point numbers.'''
for match in _integer_pat.finditer(text):
# If the integer we're looking at is part of a floating-point number, skip it.
if _floating_point_before_pat.match(text, match.start()) or \
_floating_point_after_pat.match(text, match.end()):
continue
yield ('integer', match)
def scan(text, *extractors):
'''
Scan text using the specified extractors. Return all hits, where each hit is a
tuple where the first item is a string describing the extracted number, and the
second item is the regex match where the extracted text was found.
'''
for extractor in extractors:
for item in extractor(text):
yield item
|
fe448c3f1329e9b50594a396697cc58fd2ab8890 | itielshwartz/protocolAnalyzer | /analyze_protocols.py | 5,560 | 3.65625 | 4 | import csv
import glob
import os
from collections import defaultdict
from collections import namedtuple
base_values = ["first_name", "last_name", "full_name", "position", "committee", "date", "work_place", "role",
"raw_line"]
Person = namedtuple('Person', base_values)
with open("full_names.csv") as f:
raw_names = f.readlines()
# List of israeli names
names = set(name.strip() for name in raw_names)
def is_names_column(column):
"""
:param column - list of names/ position
:return:True if the column contain names
"""
count_valid_name = 0
for maybe_name in column:
try:
first_name, last_name = maybe_name.split(" ", 1)
if first_name in names:
count_valid_name += 1
except Exception as e:
pass
return count_valid_name > len(column) * 0.25
def extract_people(file_name, committee=None, committee_date=None):
"""
:param file_name: the file we are working on
:param committee: the comititee name
:param committee_date: the date the comitee took place
:return: list of peoples, list of comittee_names that could not be parsed
"""
peoples, problematic_names = [], []
with open(file_name) as f:
reader = csv.DictReader(f)
left_column, right_column, raw_lines = [], [], []
for row in reader:
clean_data = row["header"].strip()
if "מוזמנים" in clean_data:
clean_data = row["body"].strip()
if "-" in clean_data:
for line in clean_data.splitlines():
line = line.strip()
if line:
if line.count("-") == 1:
left_side, right_side = line.split("-")
left_column.append(left_side.strip())
right_column.append(right_side.strip())
raw_lines.append(line)
comittee_names, positions = (left_column, right_column) if is_names_column(left_column) else (
right_column, left_column)
for full_name, position, raw_line in zip(comittee_names, positions, raw_lines):
create_person(committee, committee_date, full_name, peoples, position, problematic_names, raw_line)
return peoples, problematic_names
def create_person(committee, committee_date, full_name, peoples, position, problamtic_names, raw_line):
'''
Create the person and person attributes given data.
'''
try:
first_name, last_name = full_name.split(" ", 1)
role, work_place = "", ""
if "," in position:
role, work_place = position.split(",", 1)
person = Person(first_name=first_name, last_name=last_name, position=position, full_name=full_name,
committee=committee, date=committee_date, raw_line=raw_line, role=role.strip(),
work_place=work_place.strip())
peoples.append(person)
except Exception as e:
person = {"date": committee_date, "committee": committee, "line": raw_line}
# pprint.pprint(person)
problamtic_names.append(person)
protocol_dir = os.path.dirname(os.path.abspath(__file__))+"/**/*.csv"
def handle_files(file_path=None, file_prefix="/committee_"):
'''
The main function to start processing the files
the function should be run (by default) with
:return: peoples, errors
'''
peoples, errors = [], []
for file_name in glob.iglob(os.path.dirname(__file__) + file_path, recursive=True):
if file_prefix in file_name:
_, partial_path = file_name.split(file_prefix)
committee_name, raw_date, _ = partial_path.split("/")
committee_date = raw_date.split("_")[1]
people, problems = extract_people(file_name, committee=committee_name, committee_date=committee_date)
peoples.extend(people)
if problems:
errors.append(problems)
return peoples, errors
def analyze_jobs_per_person(peoples):
"""
:param peoples:
:return: full_name -> list of jobs
"""
people_to_jobs = defaultdict(set)
for people in peoples:
if people.work_place:
people_to_jobs[people.full_name].add(people.work_place)
elif people.position:
people_to_jobs[people.full_name].add(people.position)
for people, jobs in people_to_jobs.items():
jobs_to_filter = set()
for curr_job in list(jobs):
if curr_job not in jobs_to_filter:
jobs_to_filter.update(set(filter(lambda job: curr_job != job and curr_job in job, jobs)))
people_to_jobs[people] = jobs - jobs_to_filter
people_to_jobs_clean = {k: "| ".join(v) for k, v in people_to_jobs.items() if len(v) > 1}
return people_to_jobs_clean
def write_to_files(peoples, people_to_jobs_clean):
with open('full_people_list.csv', 'w') as f:
w = csv.writer(f)
w.writerow(base_values) # field header
w.writerows([list(people) for people in peoples])
with open('person_to_positions.csv', 'w') as f:
w = csv.writer(f)
w.writerow(["full_name", "positions"]) # field header
w.writerows([c for c in people_to_jobs_clean.items()])
def main_flow():
peoples, errors = handle_files(file_path=protocol_dir)
people_to_jobs_clean = analyze_jobs_per_person(peoples)
write_to_files(peoples, people_to_jobs_clean)
if __name__ == '__main__':
main_flow()
|
24830cb704c4704fdbc51698ea2d06f523e4f868 | sdelquin/adventofcode | /2017/day4/day4.py | 1,418 | 3.671875 | 4 | """
Advent of Code 2018. Day 4
Usage:
day4.py part1
day4.py part2
day4.py test
"""
from docopt import docopt
PART1_SOLUTION = 337
PART2_SOLUTION = 231
def load_input_data():
with open("input") as f:
return [line.strip() for line in f]
def part1():
passphrases = load_input_data()
valid_passphrases = 0
for passphrase in passphrases:
words = passphrase.split()
if len(words) == len(set(words)):
valid_passphrases += 1
return valid_passphrases
def any_is_anagram(target_word, words):
sorted_target_word = sorted(target_word)
for word in words:
if sorted(word) == sorted_target_word:
return True
return False
def part2():
passphrases = load_input_data()
valid_passphrases = 0
for passphrase in passphrases:
words = passphrase.split()
for i, word in enumerate(words):
current_words = words[:]
current_words.pop(i)
if any_is_anagram(word, current_words):
break
else:
valid_passphrases += 1
return valid_passphrases
def test():
assert part1() == PART1_SOLUTION
assert part2() == PART2_SOLUTION
if __name__ == "__main__":
arguments = docopt(__doc__)
if arguments["part1"]:
print(part1())
elif arguments["part2"]:
print(part2())
elif arguments["test"]:
test()
|
2da617bf9c2451201e2d79197c40afd491fb4906 | michaelkulinich/SS8_assignment | /mycd_python.py | 5,593 | 4.46875 | 4 | """
A program simulating a "cd" Unix command.
The simulated command takes two path strings from the command line and prints
either a new path or an error. The first path is a current directory.
The second path is a new directory. To make it simple let's assume that
a directory name can only contain alphanumeric characters. A single dot (".")
indicates a current directory, and the two dots ("..") indicate a step to a
previous directory, up from the current one. A single forward slash "/" indicates
a root directory. Multiple consecutive slashes are treated as equivalent to a single one.
Typical usage example:
From command line:
$ python3 mycd_python.py <current directory path> <new directory path>
Call from another module:
mycd(current_dir, new_dir)
"""
import sys
# Simulates the Unix "cd" command
def mycd(current_dir, new_dir):
"""Simulates the Unix "cd" command.
Removes unecessary multiple consecutive slashes, '.' and ".."
frome the path
Args:
current_dir: A string representing current directory path
new_dir: A string New directory path
Returns:
A string of the path after the given "cd" command.
If the file or directory is not valid, it returns an error message
Example:
mycd("/home", "Documents) -> "/home/Documents"
mycd("/home", "..) -> "/home"
"""
# if the new directory starts at root, then it is the absolute path
# and we dont need to worry about what was in the current path
if new_dir[0] == '/':
final_path = remove_slashes(new_dir)
# new directory is a relative path, so we concatenate both paths together
else:
final_path = remove_slashes(current_dir + '/' + new_dir)
# # if path is just root, return root
# if final_path == '/':
# return '/'
# split the string path by '/' to create list with each element
# representing a directory.
# then update the list to remove any '.' or ".."
# ex: "/home/Documents/../Downloads/." ->
# ["home", "Documents", "..", "Downloads", "."] ->
# ["home", "Downloads"]
### ERROR FIX ###
# added .strip('/') to get rid of leading and ending '/'
path_list = final_path.strip('/').split('/')
path_list = clean_path_list(path_list)
# list is empty so the path is only root directory
if not path_list:
return "/"
# if one of the directories was invalid (not alphanumeric)
# then the list has 1 element which is an error message, return error message
if "No such file or directory" in path_list[0]:
return path_list[0]
# Join the list back to a string with '/', starting with root
final_path = "/" + "/".join(path_list)
return final_path
# remove multiple consecutive slashes from the path string
def remove_slashes(path):
"""Removes multiple consecutive slashes.
Args:
path: A string representing the path
Returns:
A string of the updated path which replaces
multiple consecutive slashes with a single slash
Example:
remove_slashes("/home//Documents/////foo") -> "/home/Documents/foo"
"""
previous = path[0]
new_path = ''
for i in path[1:]: # start from 1st index
if i == '/':
if previous != '/':
new_path += '/'
else:
new_path += i
previous = i
return new_path
# update the path list to only contain directory names
def clean_path_list(path_list):
"""Updates the list representing the directory path
Args:
path_list: A list consisting of the directories in the path
Returns:
A list without single dots and two dots. If a directory is
non alphanumeric then it returns a list with an error message
Example:
clean_path_list(["home", "Documents", "..", "."]) -> ["home"]
clean_path_list(["home", "Do#@cuments"]) ->
["Do#@cuments: No such file or directory"]
"""
# if the list consists of an empty string, return empty list
if path_list == ['']:
return []
i = 0
while i < len(path_list):
# if the index consists of a single dot
# then we don't do anything to change the path
# and remove this index from list
if path_list[i] == '.':
if i != 0:
path_list.pop(i)
i -= 1
else:
path_list.pop(i)
# if the index constists of two dots
# then we need to step to previous directory
# and remove both this index and previous index from list
elif path_list[i] == '..':
if i != 0:
path_list.pop(i)
path_list.pop(i-1)
i -=2
# if this is only element in list, just remove it and don't
# decrement i because i is already equal to 0
else:
path_list.pop(i)
# this element should represent a valid directory
# check that is is alphanumeric, if not then update the list
# to only contain an error messge
else:
if not path_list[i].isalnum():
path_list = [path_list[i] + ": No such file or directory"]
break
i += 1
return path_list
def main():
if len(sys.argv) != 3:
print("Error: {} <current dir> <new dir>".format(sys.argv[0]))
else:
print(mycd(sys.argv[1], sys.argv[2]))
if __name__ == "__main__":
main()
|
da04ab784745cdce5c77c0b6159e17d802011129 | sclayton1006/devasc-folder | /python/def.py | 561 | 4.40625 | 4 | # Python3.8
# The whole point of this exercise is to demnstrate the capabilities of
# a function. The code is simple to make the point of the lesson simpler
# to understand.
# Simon Clayton - 13th November 2020
def subnet_binary(s):
""" Takes a slash notation subnet and calculates the
number of host addresses """
if s[0] == "/":
a = int(s.strip("/"))
else:
a = int(s)
addresses = (2**(32-a))
return addresses
s = input("Enter your slash notation. Use a number or a slash (/27 or 27): ")
x = subnet_binary(s)
print(x)
|
cc4ad41898b97ba008dde737186709286f089798 | omnidune/ProjectEuler | /Files/problem9.py | 465 | 4.0625 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def triMultiply(num):
for i in range(1, int(num/2)):
for j in range(i, int(num/2)):
if i**2 + j**2 == (num-(i+j))**2:
# print(i, j, num-(i+j))
return i*j*(num-(i+j))
return False
print(triMultiply(1000))
|
c3786bba365334b39c1ec13463c773c760e6f439 | KALAIYARASICHANDRASEKAR/Python_Guvi | /multiply.py | 115 | 4.0625 | 4 | #multiply
num=int(input("enter the number:"))
i=1
sum=0
while(i<=5):
sum=sum+num
print(sum)
i=i+1
|
f4661370ba24875539acc80900070cff792ae01b | fengnianzhuang/atsim-potentials | /atsim/potentials/potentialfunctions.py | 26,934 | 3.84375 | 4 | """Functions for different potential forms.
Most of the potentials in this module are implemented as callable _Potential_Function_Bases. The potential energy
is evaluated by calling one of these objects. By convention the first argument of each is the
atomic separation `r`, with other potential parameters following after. For instance, to
evaluate a Buckingham potential at `r` = 2.0 the following could be called for `A`, `rho` and `C` values
1000.0, 0.2 and 32.0 respectively:
.. code-block:: python
atsim.potentialfunctions.buck(2.0, 1000.0, 0.2, 32.0)
The callable objects also have other useful methods. Perhaps most importantly is the `.deriv()` method
this returns the first derivative of the given potential (force). Again using the Buckingham potential as
an example its derivative can be evaluated for `r` = 2.0 as follows:
.. code-block:: python
atsim.potentialfunctions.buck.deriv(2.0, 1000.0, 0.2, 32.0)
See :ref:`list-of-potential-forms` for descriptions of these potential forms.
"""
import math
class _Potential_Function_Base(object):
is_potential = True
class _buck(_Potential_Function_Base):
"""Callable object for evaluating the Buckingham potential"""
def _as_sympy(self):
import sympy
r, A, rho, C= sympy.symbols("r A rho C")
return A * sympy.exp(-r/rho) - C/r**6
def __call__(self, r, A, rho, C):
"""Buckingham potential form
.. math ::
U(r_{ij}) = A \exp \left( \\frac{-r_{ij}}{\\rho} \\right) - \\frac{C}{r_{ij}^6}
:param r: Atomic separation.
:param A: Buckingham A parameter
:param rho: Buckingham rho parameter :math:`\\rho`
:param C: Buckingham C parameter
:return: Potential energy."""
return A * math.exp(-r/rho) - (C/r**6)
def deriv(self, r, A, rho, C):
"""Return derivative of Buckingham potential at `r`.
:param r: Atomic separation.
:param A: Buckingham A parameter
:param rho: Buckingham rho parameter :math:`\\rho`
:param C: Buckingham C parameter
:return: Derivative of Buckingham potential at `r`"""
return (6.0*C)/r**7 - ((A * math.exp(-r/rho))/rho)
def deriv2(self, r, A, rho, C):
"""Return 2nd derivative of Buckingham potential at `r`.
:param r: Atomic separation.
:param A: Buckingham A parameter
:param rho: Buckingham rho parameter :math:`\\rho`
:param C: Buckingham C parameter
:return: Second derivative of Buckingham potential at `r`"""
return A*math.exp(-r/rho)/rho**2 - 42.0*C/r**8
buck = _buck()
class _bornmayer(_Potential_Function_Base):
"""Callable object for evaluating Born-Mayer Potential"""
def _as_sympy(self):
import sympy
r, A, rho = sympy.symbols("r A rho")
return A * sympy.exp(-r/rho)
def __call__(self, r, A, rho):
"""Born-Mayer potential form
.. math ::
V(r_{ij}) = A \exp \left( \\frac{-r_{ij}}{\\rho} \\right)
:param r: Atomic separation.
:param A: Potential parameter
:param rho: Potential parameter :math:`\\rho`
:return: Potential energy"""
return buck(r, A,rho,0.0)
def deriv(self, r, A, rho):
"""Return derivative of Born-Mayer potential form at `r`
:param r: Atomic separation.
:param A: Potential parameter
:param rho: Potential parameter :math:`\\rho`
:return: Derivative at `r`"""
return buck.deriv(r, A, rho, 0.0)
def deriv2(self, r, A, rho):
"""Return 2nd derivative of Born-Mayer potential form at `r`
:param r: Atomic separation.
:param A: Potential parameter
:param rho: Potential parameter :math:`\\rho`
:return: 2nd derivative at `r`"""
return buck.deriv2(r, A, rho, 0.0)
bornmayer = _bornmayer()
class _coul(_Potential_Function_Base):
"""Callable representing Coulomb potential (including :math:`4\pi \epsilon_0` term)"""
def _as_sympy(self):
import sympy
r, qi, qj = sympy.symbols("r q_i q_j")
return (qi * qj)/(4.0*sympy.pi*0.0055264*r)
def __call__(self,r, qi, qj):
"""Coulomb potential (including :math:`4\pi \epsilon_0` term).
.. math ::
V(r_{ij}) = \\frac{ q_i q_j }{4 \pi \epsilon_0 r_{ij} }
.. note:: Constant value appropriate for :math:`r_{ij}` in angstroms and energy in eV.
:param r: Atomic separation.
:param qi: Charge on species i
:param qj: Charge on species j
:return: Potential energy"""
return (qi * qj)/(4.0*math.pi*0.0055264*r)
def deriv(self, r, qi, qj):
"""Return derivative pf Coulomb potential at `r`
:param r: Atomic separation.
:param qi: Charge on species i
:param qj: Charge on species j
:return: Derivative at `r`"""
return -45.2374059061957*qi*qj/(math.pi*r**2)
def deriv2(self, r, qi, qj):
"""Return second derivative pf Coulomb potential at `r`
:param r: Atomic separation.
:param qi: Charge on species i
:param qj: Charge on species j
:return: 2nd derivative at `r`"""
return 90.4748118123914*qi*qj/(math.pi*r**3)
coul = _coul()
class _constant(_Potential_Function_Base):
"""Callable that returns a constant"""
def __call__(self,r, constant):
"""Function that simply returns the value that is passed to it.
:param r: Separation.
:param constant: The value to be returned by this function.
:return: The value passed in as `constant`"""
return constant
def deriv(self, r, constant):
"""Returns derivative of this potential form. Here this will always be zero
:param r: Separation.
:param constant: Constant value
:return: Derivative (0.0)
"""
return 0.0
def deriv2(self, r, constant):
"""Returns 2nd derivative of this potential form. Here this will always be zero
:param r: Separation.
:param constant: Constant value
:return: 2nd derivative (0.0)
"""
return 0.0
constant = _constant()
class _exponential(_Potential_Function_Base):
"""`exponential` potential type A*r^n"""
def _as_sympy(self):
import sympy
r, A, n = sympy.symbols("r A n")
return A*r**n
def __call__(self, r, A,n):
"""General exponential form:
.. math::
V(r_{ij}) = A r^n
:param r: Atomic separation.
:param A: Potential A parameter
:param n: n
:return: Potential energy"""
return A*r**n
def deriv(self, r, A, n):
"""Derivative of `exponential` at `r`
:param r: Atomic separation.
:param A: Potential A parameter
:param n: Potentials' B parameter
:return: Derivative of `exponential` at `r`"""
return A*n*r**(n-1)
def deriv2(self, r, A,n):
"""Second derivative of `exponential` at `r`
:param r: Atomic separation.
:param A: Potential A parameter
:param n: Potentials' B parameter
:return: 2nd derivative of `exponential` at `r`"""
return A*n*(n-1)*r**(n-2)
exponential = _exponential()
class _hbnd(_Potential_Function_Base):
"""DL_POLY `hbnd` potential type"""
def _as_sympy(self):
import sympy
r, A, B = sympy.symbols("r A B")
return A/r**12 - B/r**10
def __call__(self, r, A,B):
"""DL_POLY hbnd form:
.. math::
V(r_{ij}) = \\frac{A}{r_{ij}^{12}} - \\frac{B}{r_{ij}^{10}}
:param r: Atomic separation.
:param A: Potential A parameter
:param B: Potentials' B parameter
:return: Potential energy"""
return (A/r**12) - (B/r**10)
def deriv(self, r, A,B):
"""Derivative of `hbnd` at `r`
:param r: Atomic separation.
:param A: Potential A parameter
:param B: Potentials' B parameter
:return: Derivative of `hbnd` at `r`"""
return (10.0*B)/r**11 - (12.0 * A)/r**13
def deriv2(self, r, A,B):
"""Second derivative of `hbnd` at `r`
:param r: Atomic separation.
:param A: Potential A parameter
:param B: Potentials' B parameter
:return: 2nd derivative of `hbnd` at `r`"""
return 2*(78*A/r**2 - 55*B)/r**12
hbnd = _hbnd()
class _lj(_Potential_Function_Base):
"""Callable for Lennard-Jones 12-6 potential"""
def _as_sympy(self):
import sympy
r, epsilon, sigma = sympy.symbols("r epsilon sigma")
return 4.0*epsilon*( (sigma**12/r**12) - (sigma**6/r**6))
def __call__(self, r, epsilon, sigma):
"""Lennard-Jones 12-6 potential.
.. math ::
V(r_{ij}) = 4 \epsilon \left( \\frac{\sigma^{12}}{r_{ij}^{12}} - \\frac{\sigma^6}{r_{ij}^6} \\right)
:param r: Atomic separation.
:param epsilon: Epsilon parameter :math:`\epsilon`
:param sigma: Sigma parameter :math:`\sigma`
:return: Potential energy"""
return 4.0*epsilon*( (sigma**12/r**12) - (sigma**6/r**6))
def deriv(self, r, epsilon, sigma):
"""Derivative of Lennard-Jones 12-6 potential at `r`
:param r: Atomic separation.
:param epsilon: Epsilon parameter :math:`\epsilon`
:param sigma: Sigma parameter :math:`\sigma`
:return: Derivative of potential at `r`"""
return (24.0*epsilon*sigma**6)/r**7 - (48.0*epsilon*sigma**12)/r**13
def deriv2(self, r, epsilon, sigma):
"""Second derivative of Lennard-Jones 12-6 potential at `r`
:param r: Atomic separation.
:param epsilon: Epsilon parameter :math:`\epsilon`
:param sigma: Sigma parameter :math:`\sigma`
:return: 2nd derivative of potential at `r`"""
return -168.0*epsilon*sigma**6/r**8 + 624.0*epsilon*sigma**12/r**14
lj = _lj()
class _morse(_Potential_Function_Base):
"""Callable representing the Morse potential"""
def _as_sympy(self):
import sympy
D, gamma, r_star, r = sympy.symbols("D gamma r_star r")
return D*(sympy.exp(-2.0*gamma*(r-r_star)) - 2.0*sympy.exp(-gamma*(r-r_star)))
def __call__(self, r, gamma, r_star, D):
"""Morse potential parametrised with gamma, r_star and D.
Potential function is (where r is interatomic separation):
.. math ::
V(r_{ij}) = D \left[ \exp \left( -2 \gamma (r_{ij} - r_*) \\right) - 2 \\exp \left( -\gamma (r - r_*) \\right) \\right]
:param r: Atomic separation.
:param gamma: Potential parameter :math:`\gamma`
:param r_star: Potential parameter :math:`r_*`
:param D: Potential parameter
:return: Potential energy"""
return D*(math.exp(-2.0*gamma*(r-r_star)) - 2.0*math.exp(-gamma*(r-r_star)))
def deriv(self, r, gamma, r_star, D):
"""Evaluate derivative of Morse potential at `r`.
:param r: Atomic separation.
:param gamma: Potential parameter :math:`\gamma`
:param r_star: Potential parameter :math:`r_*`
:param D: Potential parameter
:return: Derivative of Morse potential at `r`"""
return D*(-2.0*gamma*math.exp(-2.0*gamma*(r - r_star)) + 2.0*gamma*math.exp(-gamma*(r - r_star)))
def deriv2(self, r, gamma, r_star, D):
"""Evaluate derivative of Morse potential at `r`.
:param r: Atomic separation.
:param gamma: Potential parameter :math:`\gamma`
:param r_star: Potential parameter :math:`r_*`
:param D: Potential parameter
:return: Derivative of Morse potential at `r`"""
return D*gamma**2*(4.0*math.exp(-2.0*gamma*(r - r_star)) - 2.0*math.exp(-gamma*(r - r_star)))
morse = _morse()
class _polynomial(_Potential_Function_Base):
"""Callable for polynomials"""
def _split_args(self, args):
return args[0], args[1:]
def __call__(self, *args):
"""Polynomial of arbitrary order.
.. math::
V(r_{ij}) = C_0 + C_1 r_{ij} + C_2 r_{ij}^2 + \dots + C_n r_{ij}^n
This function accepts a variable number of arguments - the first is :math:`r_{ij}`
and with the remainder being :math:`C_0, C_1, \dots, C_n` respectively.
:return: Potential energy for given polynomial"""
r, coefs = self._split_args(args)
v = [r**float(i) * c for (i,c) in enumerate(coefs)]
return sum(v)
def deriv(self, *args):
"""Evaluate polynomial derivative.
This function accepts a variable number of arguments - the first is :math:`r_{ij}`
and with the remainder being the polynomial coefficients :math:`C_0, C_1, \dots, C_n` respectively.
:return: derivative of polynomial at `r` """
r, coefs = self._split_args(args)
v = [float(i) * r**float(i-1) * c for (i,c) in enumerate(coefs)][1:]
return sum([0]+v)
def deriv2(self, *args):
"""Evaluate polynomial second derivative.
This function accepts a variable number of arguments - the first is :math:`r_{ij}`
and with the remainder being the polynomial coefficients :math:`C_0, C_1, \dots, C_n` respectively.
:return: 2nd derivative of polynomial at `r` """
r, coefs = self._split_args(args)
v = [i * float(i-1) * r**float(i-2) * c for (i,c) in enumerate(coefs)][2:]
return sum([0]+v)
polynomial = _polynomial()
class _sqrt(_Potential_Function_Base):
"""Callable representing a square root potential form"""
def _as_sympy(self):
import sympy
r, G = sympy.symbols("r, G")
return G * r**(1/2)
def __call__(self, r, G):
"""Evaluate square root function at `r`.
Potential function is:
.. math ::
U(r_{ij}) = G\sqrt{r_{ij}}
:param r: Atomic separation.
:param r: Variable
:param G: Parameter :math:`G`
:return: G multiplied by the square root of r."""
return G*math.sqrt(r)
def deriv(self, r, G):
"""Evaluate derivative of square root function at `r`.
:param r: Atomic separation.
:param r: Variable
:param G: Parameter :math:`G`
:return: Derivative at `r`. """
return (0.5 * G)/math.sqrt(r)
def deriv2(self, r, G):
"""Evaluate second derivative of square root function at `r`.
:param r: Atomic separation.
:param r: Variable
:param G: Parameter :math:`G`
:return: 2nd derivative at `r`. """
return -G/(4*r**(3/2))
sqrt = _sqrt()
class _tang_toennies(_Potential_Function_Base):
"""Callable for Tang-Toennies potential form"""
def _f2n(self, x, n):
import sympy
v = None
for k in range(2*n+1):
j = x**k / sympy.factorial(k)
if v is None:
v = j
else:
v = v+j
return 1.0 - sympy.exp(-x) * v
def _sp_second_term(self, r, b, C_6, C_8, C_10):
n_3 = self._f2n(b*r, 3) * C_6/r**6
n_4 = self._f2n(b*r, 4) * C_8/r**8
n_5 = self._f2n(b*r, 5) * C_10/r**10
return n_3 + n_4 + n_5
def _as_sympy(self):
import sympy
A,b,C_6,C_8,C_10,r = sympy.symbols("A,b,C_6,C_8,C_10,r")
r = r/0.5292
f = A*sympy.exp(-b*r)
s = self._sp_second_term(r,b,C_6, C_8, C_10)
v = (f-s)*27.211
return v
def __call__(self, r, A,b,C_6,C_8,C_10):
"""Evaluate the Tang-Toennies potential form at a separation `r`.
This potential form describes the Van der Waal's interactions between the noble gases (He to Rn) and is described in:
* K.T. Tang and J.P. Toennies, “The van der Waals potentials between all the rare gas atoms from He to Rn”, *J. Chem. Phys.*\ , **118** (2003) 4976.
The potential has the following form:
.. math::
V(r) = A \\exp(-br) - \\sum_{n=3}^N f_{2N} (bR) \\frac{C_{2N}}{R^{2N}}
Where:
.. math::
f_{2N}(x) = 1- \\exp(-x) \\sum_{k=0}^{2n} \\frac{x^k}{k!}
:param r: Separation.
:param A: Potential parameter.
:param b: Potential parameter.
:param C_6: Potential parameter.
:param C_8: Potential parameter.
:param C_10: Potential parameter.
:return: Potential evaluated at `r`."""
return 27.210999999999998522*A*math.exp(-1.8896447467876*b*r) -\
0.046875170184330419709*C_10*(-(0.00015997002473914140102*b**10*r**10 +\
0.00084656137091953641977*b**9*r**9 + 0.0040320024974155677447*b**8*r**8 +\
0.017069885773058547651*b**7*r**7 + 0.063233684857718089334*b**6*r**6 +\
0.2007795961602264756*b**5*r**5 + 0.53126281143995923717*b**4*r**4 +\
1.1245771192561058172*b**3*r**3 + 1.7853786345309936578*b**2*r**2 +\
1.8896447467876038573*b*r + 1.0)*math.exp(-1.8896447467876*b*r) + 1.0)/r**10 -\
0.59767283277249427798*C_6*(-(0.063233684857718089334*b**6*r**6 +\
0.2007795961602264756*b**5*r**5 + 0.53126281143995923717*b**4*r**4 +\
1.1245771192561058172*b**3*r**3 + 1.7853786345309936578*b**2*r**2 +\
1.8896447467876038573*b*r + 1.0)*math.exp(-1.8896447467876*b*r) + 1.0)/r**6 -\
0.16737985467421556685*C_8*(-(0.0040320024974155677447*b**8*r**8 +\
0.017069885773058547651*b**7*r**7 + 0.063233684857718089334*b**6*r**6 +\
0.2007795961602264756*b**5*r**5 + 0.53126281143995923717*b**4*r**4 +\
1.1245771192561058172*b**3*r**3 + 1.7853786345309936578*b**2*r**2 +\
1.8896447467876038573*b*r + 1.0)*math.exp(-1.8896447467876*b*r) + 1.0)/r**8
def deriv(self, r, A,b,C_6,C_8,C_10):
"""Evaluate the first derivative of Tang-Toennies potential form at a separation `r`.
:param r: Separation.
:param A: Potential parameter.
:param b: Potential parameter.
:param C_6: Potential parameter.
:param C_8: Potential parameter.
:param C_10: Potential parameter.
:return: Derivative evaluated at `r`."""
return (-51.419123204837482888*A*b*r**11 - 0.000014169731923731671203*C_10*b**11*r**11 - 0.000074986221340387997341*C_10*b**10*r**10 -\
0.00039682708333333333072*C_10*b**9*r**9 - 0.0018900080324999999661*C_10*b**8*r**8 - 0.0080015380063920005238*C_10*b**7*r**7 -\
0.029640897390878523376*C_10*b**6*r**6 - 0.094115777395517505322*C_10*b**5*r**5 - 0.24903034698853929174*C_10*b**4*r**4 -\
0.5271474385053400713*C_10*b**3*r**3 - 0.83689927337107783423*C_10*b**2*r**2 - 0.88577419093594889077*C_10*b*r +\
0.46875170184330416934*C_10*math.exp(1.8896447467876*b*r) - 0.46875170184330416934*C_10 - 0.071415448895607608337*C_6*b**7*r**11 -\
0.22675833333333325625*C_6*b**6*r**10 - 0.720003059999999806*C_6*b**5*r**9 - 1.9051280967599995009*C_6*b**4*r**8 -\
4.0327751552215671538*C_6*b**3*r**7 - 6.4024338364297603832*C_6*b**2*r**6 - 6.7763359724772591619*C_6*b*r**5 +\
3.5860369966349656679*C_6*r**4*math.exp(1.8896447467876*b*r) - 3.5860369966349656679*C_6*r**4 - 0.0012752758731358502728*C_8*b**9*r**11 -\
0.0053990079365079353749*C_8*b**8*r**10 - 0.022857239999999997421*C_8*b**7*r**9 - 0.084672359855999981826*C_8*b**6*r**8 -\
0.2688516770147711954*C_8*b**5*r**7 - 0.71138153738108456103*C_8*b**4*r**6 - 1.5058524383282798631*C_8*b**3*r**5 -\
2.3906913310899771119*C_8*b**2*r**4 - 2.5303077048256321646*C_8*b*r**3 + 1.3390388373937245348*C_8*r**2*math.exp(1.8896447467876*b*r) -\
1.3390388373937245348*C_8*r**2)*math.exp(-1.8896447467876*b*r)/r**11
def deriv2(self, r, A,b,C_6,C_8,C_10):
"""Evaluate the second derivative of Tang-Toennies potential form at a separation `r`.
:param r: Separation.
:param A: Potential parameter.
:param b: Potential parameter.
:param C_6: Potential parameter.
:param C_8: Potential parameter.
:param C_10: Potential parameter.
:return: Second derivative evaluated at `r`."""
return 1.0*(97.163876048445729339*A*b**2*r**12 +\
0.000026775759493068161437*C_10*b**12*r**12 + 0.00014169731923731671203*C_10*b**11*r**11 +\
0.0008248484347442676997*C_10*b**10*r**10 + 0.0043650979166666662584*C_10*b**9*r**9 +\
0.02079008835750000006*C_10*b**8*r**8 + 0.088016918070311991884*C_10*b**7*r**7 +\
0.32604987129966372938*C_10*b**6*r**6 + 1.0352735513506925447*C_10*b**5*r**5 + 2.7393338168739322924*C_10*b**4*r**4 +\
5.7986218235587401182*C_10*b**3*r**3 + 9.2058920070818572867*C_10*b**2*r**2 + 9.7435161002954373544*C_10*b*r -\
5.1562687202763459737*C_10*math.exp(1.8896447467876*b*r) + 5.1562687202763459737*C_10 + 0.13494982784506348583*C_6*b**8*r**12 +\
0.428492693373645539*C_6*b**7*r**11 + 1.587308333333332433*C_6*b**6*r**10 + 5.040021419999998642*C_6*b**5*r**9 +\
13.335896677319995618*C_6*b**4*r**8 + 28.229426086550969188*C_6*b**3*r**7 + 44.817036855008325347*C_6*b**2*r**6 +\
47.434351807340810581*C_6*b*r**5 - 25.102258976444758787*C_6*r**4*math.exp(1.8896447467876*b*r) + 25.102258976444758787*C_6*r**4 +\
0.0024098183543761341092*C_8*b**10*r**12 + 0.010202206985086802182*C_8*b**9*r**11 + 0.048591071428571420976*C_8*b**8*r**10 +\
0.2057151599999999525*C_8*b**7*r**9 + 0.76205123870399982255*C_8*b**6*r**8 + 2.4196650931329406475*C_8*b**5*r**7 +\
6.4024338364297603832*C_8*b**4*r**6 + 13.552671944954518324*C_8*b**3*r**5 + 21.516221979809795783*C_8*b**2*r**4 +\
22.772769343430688593*C_8*b*r**3 - 12.051349536543520813*C_8*r**2*math.exp(1.8896447467876*b*r) + 12.051349536543520813*C_8*r**2)*math.exp(-1.8896447467876*b*r)/r**12
tang_toennies = _tang_toennies()
class _zbl(_Potential_Function_Base):
"""Callable representing ZBL potential."""
Ck1=0.1818
Ck2=0.5099
Ck3=0.2802
Ck4=0.02817
Bk1=3.2
Bk2=0.9423
Bk3=0.4029
Bk4=0.2016
def _as_sympy(self):
import sympy
Ck1, Ck2, Ck3, Ck4, Bk1, Bk2, Bk3, Bk4 = sympy.symbols("Ck1:5,Bk1:5")
z1, z2, r = sympy.symbols("z1, z2, r")
a=(0.8854*0.529)/(z1**0.23 + z2**0.23)
f = 14.39942 * (z1*z2)/r * (Ck1*sympy.exp((-Bk1*r)/a) + Ck2*sympy.exp((-Bk2*r)/a) + Ck3*sympy.exp((-Bk3*r)/a) + Ck4*sympy.exp((-Bk4*r)/a))
return f
def __call__(self, r, z1,z2):
"""ZBL potential.
Ziegler-Biersack-Littmark screened nuclear repulsion for describing high energy interactions.
:param r: Atomic separation.
:param z1: Atomic number of species i
:param z2: Atomic number of species j
:return: Potential energy"""
a=(0.8854*0.529)/(float(z1)**0.23 + float(z2)**0.23)
return 14.39942 * (z1*z2)/r * (self.Ck1*math.exp((-self.Bk1*r)/a) + self.Ck2*math.exp((-self.Bk2*r)/a) + self.Ck3*math.exp((-self.Bk3*r)/a) + self.Ck4*math.exp((-self.Bk4*r)/a))
def deriv(self, r, z1, z2):
"""Evaluate derivative of ZBL function at `r`.
:param r: Atomic separation.
:param z1: Atomic number of species i
:param z2: Atomic number of species j
:return: Derivative of function"""
v = -14.39942*z1*z2*(self.Ck1*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
* (self.Bk2 + self.Bk3 + self.Bk4))\
+ self.Ck2*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk3 + self.Bk4))\
+ self.Ck3*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk2 + self.Bk4))\
+ self.Ck4*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk2 + self.Bk3))\
+ 2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1*self.Ck1*math.exp(2.13503407300877\
*r*(z1**0.23 + z2**0.23)*(self.Bk2 + self.Bk3 + self.Bk4))\
+ self.Bk2*self.Ck2*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk3 + self.Bk4))\
+ self.Bk3*self.Ck3*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk2 + self.Bk4)) + self.Bk4*self.Ck4\
*math.exp(2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk2 + self.Bk3))))\
*math.exp(-2.13503407300877*r*(z1**0.23 + z2**0.23)\
*(self.Bk1 + self.Bk2 + self.Bk3 + self.Bk4))/r**2
return v
def deriv2(self, r, z1, z2):
"""Evaluate second derivative of ZBL function at `r`.
:param r: Atomic separation.
:param z1: Atomic number of species i
:param z2: Atomic number of species j
:return: 2nd derivative of function"""
v = z1*z2*(65.6378912429954*(z1**0.23 + z2**0.23)**2* \
(self.Bk1**2*self.Ck1*math.exp(-2.13503407300877*self.Bk1*r*(z1**0.23 + z2**0.23)) + \
self.Bk2**2*self.Ck2*math.exp(-2.13503407300877*self.Bk2*r*(z1**0.23 + z2**0.23)) + \
self.Bk3**2*self.Ck3*math.exp(-2.13503407300877*self.Bk3*r*(z1**0.23 + z2**0.23)) + \
self.Bk4**2*self.Ck4*math.exp(-2.13503407300877*self.Bk4*r*(z1**0.23 + z2**0.23))) + \
28.79884*(2.13503407300877*z1**0.23 + 2.13503407300877*z2**0.23)* \
(self.Bk1*self.Ck1*math.exp(-2.13503407300877*self.Bk1*r*(z1**0.23 + z2**0.23)) + \
self.Bk2*self.Ck2*math.exp(-2.13503407300877*self.Bk2*r*(z1**0.23 + z2**0.23)) + \
self.Bk3*self.Ck3*math.exp(-2.13503407300877*self.Bk3*r*(z1**0.23 + z2**0.23)) + \
self.Bk4*self.Ck4*math.exp(-2.13503407300877*self.Bk4*r*(z1**0.23 + z2**0.23)))/r + \
(28.79884*self.Ck1*math.exp(-2.13503407300877*self.Bk1*r*(z1**0.23 + z2**0.23)) + \
28.79884*self.Ck2*math.exp(-2.13503407300877*self.Bk2*r*(z1**0.23 + z2**0.23)) + \
28.79884*self.Ck3*math.exp(-2.13503407300877*self.Bk3*r*(z1**0.23 + z2**0.23)) + \
28.79884*self.Ck4*math.exp(-2.13503407300877*self.Bk4*r*(z1**0.23 + z2**0.23)))/r**2)/r
return v
zbl = _zbl()
class _zero(_Potential_Function_Base):
"""Callable that returns 0.0 for any given input"""
def __call__(self, r):
"""Returns 0.0 for any value of r.
:param r: Separation.
:return: Returns 0.0"""
return 0.0
def deriv(self, r):
"""Derivative function - always returns 0.0"""
return 0.0
def deriv2(self, r):
"""Second derivative function - always returns 0.0"""
return 0.0
zero = _zero()
class _exp_spline(_Potential_Function_Base):
"""Callable representing exponential spline"""
def _as_sympy(self):
import sympy
r, B0, B1, B2, B3, B4, B5, C = sympy.symbols("r, B0, B1, B2, B3, B4, B5, C")
return sympy.exp(B0 + B1*r + B2*r**2 + B3*r**3 + B4*r**4 + B5*r**5) + C
def __call__(self, r, B0, B1, B2, B3, B4, B5, C):
"""Exponential spline function (as used in splining routines).
.. math::
U(r_{ij}) = \exp \left( B_0 + B_1 r_{ij} + B_2 r_{ij}^2 + B_3 r_{ij}^3 + B_4 r_{ij}^4 + B_5 r_{ij}^5 \\right) + C
:param r: Atomic separation
:param B0: Spline coefficient
:param B1: Spline coefficient
:param B2: Spline coefficient
:param B3: Spline coefficient
:param B4: Spline coefficient
:param B5: Spline coefficient
:param C: C parameter
:return: Splined values"""
return math.exp(B0 + B1*r + B2*r**2 + B3*r**3 + B4*r**4 + B5*r**5) + C
def deriv(self, r, B0, B1, B2, B3, B4, B5, C):
"""Derivative of exponential spline.
:param r: Atomic separation
:param B0: Spline coefficient
:param B1: Spline coefficient
:param B2: Spline coefficient
:param B3: Spline coefficient
:param B4: Spline coefficient
:param B5: Spline coefficient
:param C: C parameter
:return: Derivative of spline at `r`"""
return (B1 + r*(2*B2 + r*(3*B3 + 4*B4*r + 5*B5*r**2))) * math.exp(B0 + r*(B1 + r*(B2 + r*(B3 + r*(B4 + B5*r)))))
def deriv2(self, r, B0, B1, B2, B3, B4, B5, C):
"""Second derivative of exponential spline.
:param r: Atomic separation
:param B0: Spline coefficient
:param B1: Spline coefficient
:param B2: Spline coefficient
:param B3: Spline coefficient
:param B4: Spline coefficient
:param B5: Spline coefficient
:param C: C parameter
:return: 2nd derivative of spline at `r`"""
return (2*B2 + 6*B3*r + 12*B4*r**2 + 20*B5*r**3 \
+ (B1 + 2*B2*r + 3*B3*r**2 + 4*B4*r**3 + 5*B5*r**4)**2) \
* math.exp(B0 + B1*r + B2*r**2 + B3*r**3 + B4*r**4 + B5*r**5)
exp_spline = _exp_spline()
|
46f4e127eca6bdcd2309406a4f7f5a8259b3a896 | zaur557/python.zzz | /taack 1/стоймость покупки.py | 112 | 3.546875 | 4 | a = int(input())
b = int(input())
n = int(input())
cost = n * (100 * a + b)
print(cost // 100, cost % 100)
|
dc1dd25992e4ab98200fe1a4ba28e1211529c6d5 | elston-jja/Personal-Projects | /python/Grade12/unit3/Personal Versions/Zodiac/zodiaccomp.py | 5,201 | 4.03125 | 4 | '''
Elston Almeida
Checks Compatibility of users based on their zodiac sign
2016/30/05
ICS 3U1
'''
'''Get Date'''
def birthday_day(identifier):
verified_input = False
while verified_input is False:
try:
birth_date_input = input("Please enter "+identifier+ " date of birth: ")
if 0 < birth_date_input <= 31:
verified_input = True
return(birth_date_input)
else:
print "Please enter a valid date"
except:
print "Please enter a valid date"
'''Get Month'''
def birthday_month(identifier):
verified_input = False
while verified_input is False:
try:
'''Enter info and check if can be converted to int'''
month_birthday = raw_input ("Please enter the month " +identifier+ " born : ")
if not month_birthday:
print "Please enter a month"
else:
month_birthday_int = int(month_birthday)
month_int = [1,2,3,4,5,6,7,8,9,10,11,12]
if month_birthday_int in month_int:
verified_input = True
return month_birthday_int
else:
print"Please enter a valid int"
except ValueError:
str_birthday = (month_birthday[0]).upper()+(month_birthday[1:]).lower()
month_str = ["January","Febuary","March","April","May","June","July","August","September","October","November","December"]
month_acc = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
#print(str_birthday)
if str_birthday in month_str:
int_birthday = month_str.index(str_birthday) + 1
#print int_birthday
verified_input = True
return int_birthday
elif str_birthday in month_acc:
int_birthday = month_acc.index(str_birthday) + 1
verified_input = True
return int_birthday
else:
print "Please enter a valid month"
except:
print "Please enter a valid input"
'''Cross check data'''
def zodiac_check(month,day):
if (month == 1 and day >= 21) or (month == 2 and day <= 16):
return("Capricon")
elif (month == 2 and day >= 17) or (month == 3 and day <= 11):
return("Aquarius")
elif (month == 3 and day >= 12) or (month == 4 and day <= 18):
return("Pisces")
elif (month == 4 and day >= 18) or (month == 5 and day <= 13):
return("Aries")
elif (month == 5 and day >= 13) or (month == 6 and day <= 21):
return("Taurus")
elif (month == 6 and day >= 22) or (month == 7 and day <= 20):
return("Gemini")
elif (month == 7 and day >= 21) or (month == 8 and day <= 10):
return("Cancer")
elif (month == 8 and day >= 11) or (month == 9 and day <= 16):
return("Leo")
elif (month == 9 and day >= 17) or (month == 10 and day <= 30):
return("Virgo")
elif (month == 10 and day >= 31) or (month == 11 and day <= 23):
return("Libra")
elif (month == 11 and day >= 24) or (month == 11 and day <= 29):
return("Scorpio")
elif (month == 11 and day >= 30) or (month == 12 and day <= 17):
return("Ophiuchus")
elif (month == 12 and day >= 18) or (month == 1 and day <= 20):
return("Sagittarius")
'''Checks compatibility'''
def compatible(person,person_two):
comp_fire = ["Sagittarius","Aries","Leo","Ophiuchus"]
comp_earth = ["Capricorn","Virgo","Taurus","Ophiuchus"]
comp_air = ["Aquarius","Libra","Gemini","Ophiuchus"]
comp_water = ["Pices","Scorpio","Cancer","Ophiuchus"]
#Runs through if statements to check compatibility
if person in comp_fire and person_two in comp_fire:
print "You are compatible"
elif person in comp_earth and person_two in comp_earth:
print "You are compatible"
elif person in comp_air and person_two in comp_air:
print "You are compatible"
elif person in comp_water and person_two in comp_water:
print "You are compatible"
else:
print "You are not compatible"
running = True
while running is True:
'''Set variables to compare, by getting user input'''
user1_month = birthday_month("you were")
user1_day = birthday_day("you")
check_new = True
while check_new is True:
user2_month = birthday_month("your partner")
user2_day = birthday_day("their")
'''Sets Variables for Function Later'''
compatibility_user = zodiac_check(user1_month,user1_day)
compatibility_partner = zodiac_check(user2_month,user2_day)
'''Runs to check compatibilty'''
compatible(compatibility_user,compatibility_partner)
run_again = raw_input("Do you want to check compatibily again with another person?\n(y/N) : ")
if run_again in ("y","yes","Y","YES","Dam straight I'm pissed, I'm not compatible"):
print "Hope t'is the one for you this time"
else:
check_new = False
print "Exiting"
running = False
|
368139b4978ccea8fc599e278be28b0dc3a4d0fd | henaege/python-basics-day-3 | /triangle.py | 322 | 3.671875 | 4 | def print_star():
print((" " * (space_count / 2)) + "*" * star_count + (" " * (space_count / 2)))
total_width = 10
star_count = 1
space_count = total_width - star_count
loop_count = 1
while loop_count <= 10:
if star_count % 2 == 1:
print_star()
star_count += 1
space_count -= 1
loop_count += 1 |
c9412d1862d73c9bffc8d47b7a1b860f8bd8f62e | henaege/python-basics-day-3 | /long_vowels.py | 856 | 3.6875 | 4 | # string = raw_input("Word: ")
# word = list(string)
# for i in range(0,len(word)-1):
# home_slice = word[i:i+2]
# if home_slice == ['a', 'a']:
# word.remove("a")
# word.insert(i, "aaaa")
# if home_slice == ['e', 'e']:
# word.remove("e")
# word.insert(i, "eeee")
# if home_slice == ['i', 'i']:
# word.remove("i")
# word.insert(i, "iiii")
# if home_slice == ['o', 'o']:
# word.remove("o")
# word.insert(i, "oooo")
# if home_slice == ['u', 'u']:
# word.remove("u")
# word.insert(i, "uuuu")
# woooord = "".join(word)
# print woooord
string_to_test = raw_input("Word: ")
result = ""
current = ""
previous = ""
for i in range(0, len(string_to_test)):
current = string_to_test[i]
if current == previous:
result = result + 4 * current
else:
result = result + current
previous = current
print result |
a13a1b0a859f1fa0755e056cfb64552036cf180d | henaege/python-basics-day-3 | /banner.py | 334 | 3.609375 | 4 | def print_top(num):
print("*" * num)
def print_bottom(num):
print("*" * num)
def print_middle(message):
print("*" + " " + message + " " + "*")
text = raw_input("What will the banner say? ")
width = len(text) + 4
# height = int(raw_input("How high is the box? "))
print_top(width)
print_middle(text)
print_bottom(width) |
bb8993ca645aa4bf204163dfdbae3ce2dbd87499 | noltron000/exercisms | /high-scores/high_scores.py | 378 | 3.8125 | 4 | def latest(scores):
return scores[-1]
def personal_best(scores):
return max(scores)
def personal_top_three(scores):
top_scores = [0]*min(len(scores),3)
for score in scores:
for top_score in top_scores:
if score > top_score:
idx = top_scores.index(top_score)
top_scores.insert(idx, score)
top_scores.pop()
break
print(top_scores)
return top_scores
|
312f11f76a042b25bec17dd1f8a19089b44993fd | hello-lx/CodingTest | /3/625.py | 1,250 | 3.515625 | 4 | class Solution:
"""
@param nums: an integer array
@param low: An integer
@param high: An integer
@return: nothing
"""
def partition2(self, nums, low, high):
if not nums:
return
start, end = 0, len(nums) - 1
while start <= end:
while start <= end and nums[start] < low:
start += 1
while start <= end and nums[end] >= low:
end -= 1
if start <= end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
# the ending point will be like
# end | | start
# example: low = 2, high = 3
# 1,1,4,3,2,3,4,2
# j i
while start < len(nums) - 1 and nums[start] <= low:
start += 1
start, end = start, len(nums) - 1
while start <= end:
while start <= end and nums[start] <= high:
start += 1
while start <= end and nums[end] > high:
end -= 1
if start <= end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
return |
75e95c28db08788ac12df8bca709497d68910b38 | adamstockton/Python-Class | /Activities/color groups.py | 2,589 | 3.75 | 4 | # Define Grid
grid = [
["G", "G", "B", "R"],
["G", "B", "R", "B"],
["R", "B", "B", "B"]
]
# Capture Results
highest = {
"color": "",
"count": 0
}
# Compute Result
iterated = {}
def main():
for row in range(len(grid) - 1):
for col in range(len(grid[row]) - 1):
# Check if column has already been iterated over
if "R" + str(row) + "C" + str(col) in iterated:
continue
# Declare Stack
stack = []
count = 1
# Push on the first cell
stack.append({
"row": row,
"col": col
})
iterated["R" + str(row) + "C" + str(col)] = True
while len(stack) > 0:
current = stack.pop()
results = find_neighbors(current['row'], current['col'], grid[row][col])
stack += results
count += len(results)
if highest["count"] < count:
highest['color'] = grid[row][col]
highest['count'] = count
def find_neighbors(row, col, color):
results = []
# North
try:
if grid[row - 1][col] == color and "R" + str(row - 1) + "C" + str(col) not in iterated:
iterated["R" + str(row - 1) + "C" + str(col)] = True
results.append({
"row": row - 1,
"col": col
})
except IndexError:
pass
# South
try:
if grid[row + 1][col] == color and "R" + str(row + 1) + "C" + str(col) not in iterated:
iterated["R" + str(row + 1) + "C" + str(col)] = True
results.append({
"row": row + 1,
"col": col
})
except IndexError:
pass
# East
try:
if grid[row][col + 1] == color and "R" + str(row) + "C" + str(col + 1) not in iterated:
iterated["R" + str(row) + "C" + str(col + 1)] = True
results.append({
"row": row,
"col": col + 1
})
except IndexError:
pass
# West
try:
if grid[row][col - 1] == color and "R" + str(row) + "C" + str(col - 1) not in iterated:
iterated["R" + str(row) + "C" + str(col - 1)] = True
results.append({
"row": row,
"col": col - 1
})
except IndexError:
pass
return results
main()
# Output Results
print('The highest color is {} with a count of {}'.format(highest['color'], highest['count'])) |
5620f2df6da84ab3425626bc24d5cd9d2597e218 | carlemil/ProjectEuler | /completed/euler0026.py | 1,299 | 3.71875 | 4 | ##A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
##
## 1/2 = 0.5
## 1/3 = 0.(3)
## 1/4 = 0.25
## 1/5 = 0.2
## 1/6 = 0.1(6)
## 1/7 = 0.(142857)
## 1/8 = 0.125
## 1/9 = 0.(1)
## 1/10 = 0.1
#Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be
#seen that 1/7 has a 6-digit recurring cycle.
#Find the value of d 1000 for which 1/d contains the longest recurring cycle
#in its decimal fraction part.
def div_period_langd(nam, tal):
namnare = nam
taljare = str(tal)
i = -1
rest = 0
result = ""
rest_list = list()
while i < 1000:
i += 1
if i < len(taljare):
tmp = rest * 10 + int(taljare[i])
else:
tmp = rest * 10
div = tmp / namnare
rest = tmp - (namnare * div)
# debug saker
if i == len(taljare):
result = result + "."
result = result + str(div)
#print result
if rest in rest_list:
return len(rest_list) - rest_list.index(rest)
rest_list.append(rest)
max_val = 0
l = 0
for a in range(1,1000):
tmp = div_period_langd(a,1)
if max_val < tmp:
max_val = tmp
l = a
print l
|
7ce1b872be63182adfc3485073ce25e4d0a037f0 | carlemil/ProjectEuler | /completed/euler0036.py | 725 | 3.703125 | 4 | ##The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.
##
##Find the sum of all numbers, less than one million, which are palindromic
##in base 10 and base 2.
##
##(Please note that the palindromic number, in either base, may not include
## leading zeros.)
from tools import is_palindromic
def to_base_2(n):
n = int(n)
ret = ""
while n > 0:
if n==((n>>1)<<1):
ret = "0" + ret
else:
ret = "1" + ret
n=n>>1
return ret
import math
sum = 0
for p in range(0, 999999):
if p%10!=0 and is_palindromic(p):
b2 = to_base_2(str(p))
if is_palindromic(b2):
sum += int(p)
print sum
|
799b052a493c4fabd53c156db5ae90bcb6960cea | carlemil/ProjectEuler | /completed/euler0107.py | 2,542 | 3.578125 | 4 |
from tools import read_file
class Node:
def __init__(self, nr, edges):
self.nr = nr
self.edges = edges
self.mst_edges = []
self.connected_to = []
self.in_mst = False
def handle_node(nr, inl):
utl = []
for i in range(len(inl)):
t = inl[i].strip()
if not t == '-':
utl.append([i, int(t)])
return Node(nr, sorted(utl, key=lambda x:(x[1], x[0])))
def find(nodes_nrs, node_nr):
for n in nodes_nrs,:
if n == node_nr:
return n
return None
def is_loop(t):
for n in mst:
if n.nr == t:
return True
return False
data = read_file("euler0107_network.txt")
g = []
g_tot = 0
for i in range(0,len(data)):
g.append(handle_node(i, data[i]))
for n in g:
for e in n.edges:
g_tot += e[1]
n.connected_to.append(g[e[0]])
g_tot /= 2
# init tree
mst = []
mst.append(g[0])
g[0].in_mst = True
# done init
#find shortest edge among nodes in mst
while len(mst) < len(g):
shortest_edge_node = mst[0]
for n in mst:
if shortest_edge_node.edges[0][1] >= n.edges[0][1]:
shortest_edge_node = n
if not is_loop(shortest_edge_node.connected_to[0].nr):
# add to mst
mst.append(shortest_edge_node.connected_to[0])
#print "added"
#print "%d -> %d" % (shortest_edge_node.nr, shortest_edge_node.connected_to[0].nr)
# set the other node to in_mst = True
shortest_edge_node.connected_to[0].in_mst = True
# set the edge in the mst list in parrent nodes.
shortest_edge_node.mst_edges.append(shortest_edge_node.edges[0])
# remove edge from both nodes edges lists
# find the possition of the edge to delete in the connected node
delete_index = 0
for i in range(len(shortest_edge_node.connected_to[0].edges)):
if shortest_edge_node.connected_to[0].edges[i][0] == shortest_edge_node.nr:
delete_index = i
del(shortest_edge_node.connected_to[0].edges[delete_index])
del(shortest_edge_node.edges[0])
# remove the connected to connection from both nodes
# use the same index as above for delete in connected node
del(shortest_edge_node.connected_to[0].connected_to[delete_index])
del(shortest_edge_node.connected_to[0])
sum_mst = 0
temp = []
for a in mst:
temp.append( a.nr)
for e in a.mst_edges:
sum_mst += e[1]
temp.sort()
print g_tot-sum_mst
|
87509b879f03bf974906d723e79df69c1c17cc55 | JorgeVidal29/MyMLLearning | /Single Variable Regression/Resturant Population vs Profit/resturantPrediction.py | 1,589 | 3.671875 | 4 |
"""
Created on Mon May 18 21:56:49 2020
@author: Jorge
"""
#These are all the libs we are using
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
#reading the dataset and seperating it
dataset = pd.read_csv('./resturantData.csv')
population = dataset.iloc[:, :-1].values
profit = dataset.iloc[:, 1].values
#this splits the dataset into training and testing sets
populationTraining, populationTesting, profitTraining, profitTesting = train_test_split(population, profit, test_size=.2)
#this is the linear regression object of the sklearn lib
linearRegression = LinearRegression()
#this is the training on the training sets
linearRegression.fit(populationTraining, profitTraining)
# Make predictions using the testing set
profitPrediction = linearRegression.predict(populationTesting)
# The coefficients
print('Coefficients: \n', linearRegression.coef_)
# The mean squared error
print('Mean squared error: %.2f' % (metrics.mean_squared_error(profitTesting, profitPrediction)))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f' % (metrics.r2_score(profitTesting, profitPrediction)))
#this is making the scatter plot for this data
plt.title('Population vs. Profit, Prediction Vs Actual')
plt.xlabel('Population in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.scatter(populationTesting,profitTesting, color = 'black')
plt.plot(populationTesting,profitPrediction, color = 'red')
plt.show()
|
bbfa62e0a73aa476ff8c7a2abd98c021c956d20e | Zeonho/LeetCode_Python | /archives/535_Encode_and_Decode_TinyURL.py | 1,708 | 4.125 | 4 | """
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it
returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your
encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny
URL and the tiny URL can be decoded to the original URL.
"""
class hashMap:
def __init__(self):
self.mapping = [[]]*25
def put(self, key, val):
hash_key = hash(val) % len(self.mapping)
bucket = self.mapping[hash_key]
key_exists = False
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket.append((hash_key, val))
else:
self.mapping[hash_key] = [(hash_key,val)]
return key
def get(self, key):
hash_key = hash(key) % len(self.mapping)
bucket = self.mapping[hash_key]
for i, kv in enumerate(bucket):
k,v = kv
return v
raise KeyError
class Codec:
def __init__(self):
self.urlShortener = hashMap()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
return self.urlShortener.put(hash(longUrl), longUrl)
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.urlShortener.get(shortUrl)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url)) |
3015e58495f0687c0d5270dc3dcd5b0dd8b3592f | Zeonho/LeetCode_Python | /archives/24_Swap_Nodes_in_Pairs.py | 1,422 | 3.859375 | 4 | """
24. Swap Nodes in Pairs
Medium
1720
152
Add to List
Share
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head == None:
return
if head.next == None:
return head
node_lst = []
ptr = head
while ptr != None:
node_lst.append(ptr)
ptr = ptr.next
node_lst_length = len(node_lst)
if node_lst_length % 2 == 0:
for i in range(0, node_lst_length - 1, 2):
node_lst[i], node_lst[i+1] = node_lst[i+1], node_lst[i]
else:
for i in range(0, node_lst_length - 2, 2):
node_lst[i], node_lst[i+1] = node_lst[i+1], node_lst[i]
for i in range(0, node_lst_length - 1):
node_lst[i].next = node_lst[i+1]
node_lst[-1].next = None
head = node_lst[0]
return head |
2e2a2100b44d151a090c6f7835d6c32ccb8750d1 | Zeonho/LeetCode_Python | /archives/997_Find_the_Town_Judge.py | 1,460 | 3.796875 | 4 | """
In a town, there are N people labelled from 1 to N. There is a rumor that one
of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the
person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town
judge. Otherwise, return -1.
"""
"""
Thoughts:
1. Find EveryBody
Note:
dict:
if i in dict
"""
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
# N = 1
# len(trust) = 0
if len(trust) == 0 and N == 1:
return 1
people_trust_others = self.findEveryBody(trust)
is_trust = self.trustDict(trust)
for p, t in is_trust.items():
if p not in people_trust_others and t == N - 1:
return p
return -1
def findEveryBody(self, trust):
people = []
for person in trust:
people.append(person[0])
return set(people)
def trustDict(self, trust):
dic = dict()
for person in trust:
if person[1] in dic:
dic[person[1]] += 1
else:
dic[person[1]] = 1
return dic
|
346e4c2c35f31b80f0858d9109366bfd64d94d19 | Zeonho/LeetCode_Python | /archives/867_Transpose_Matrix.py | 462 | 3.921875 | 4 | """
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main diagonal,
switching the row and column indices of the matrix.
"""
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
res = []
for i in range(len(A[0])):
temp = []
for j in range(len(A)):
temp.append(A[j][i])
res.append(temp)
return res |
ce55003853dc015c58c8d158a37d2a684c5e0b9e | Zeonho/LeetCode_Python | /archives/1_Two_Sum.py | 514 | 3.78125 | 4 | """
Given an array of integers, return indices of the two numbers such that they add up
to a specific target.
You may assume that each input would have exactly one solution, and you may not use
the same element twice.
"""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Solution 1 Brute Force:
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target:
return [nums[i]] + [nums[j]]
|
4f2dff3ef7e3d45d5c94798458a4c543e5c23a26 | shreyaydi/Python-Assignment-II | /10.py | 636 | 4.09375 | 4 | # Write a function that takes camel-cased strings (i.e.
# ThisIsCamelCased), and converts them to snake case (i.e.
# this_is_camel_cased). Modify the function by adding an argument,
# separator, so it will also convert to the kebab case
# (i.e.this-is-camel-case) as well.
def conv(my_string, seperator):
var = [my_string[0].lower()]
for x in my_string[1:]:
if x in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
var.append(seperator)
var.append(x.lower())
else:
var.append(x)
return ''.join(var)
my_string = 'ThisIsCamelCased'
print(conv(my_string, '_'))
print(conv(my_string, '-'))
|
31f60c8ce2e2aa2c827d520e10e174a3c191ff64 | nathanpainchaud/advent-of-code | /src/utils/parsing.py | 773 | 3.5 | 4 | import argparse
class StoreDictKeyPair(argparse.Action):
"""Action that can parse a python from comma-separated key-value pairs passed to the parser."""
def __call__(self, parser, namespace, values, option_string=None):
"""Parses comma-separated key-value pairs passed to the parser into a dict, adding it to the namespace.
Args:
parser: Parser object being parsed.
namespace: Namespace produced from parsing the arguments.
values: Values specified for the option using the current action.
option_string: Option flag.
"""
args_map = {}
for kv in values.split(","):
k, v = kv.split("=")
args_map[k] = v
setattr(namespace, self.dest, args_map)
|
b36f1a653b763f89a09c37100791061577d878ee | nathanpainchaud/advent-of-code | /src/2020/day15/rambunctious_recitation.py | 1,270 | 3.984375 | 4 | from pathlib import Path
def rambunctious_recitation(starting_numbers_path: Path, num_turns: int) -> None:
with open(starting_numbers_path) as file:
starting_numbers = [int(number) for number in file.read().split(",")]
numbers = {number: turn for turn, number in enumerate(starting_numbers[:-1], 1)}
last_number, number = starting_numbers[-1], starting_numbers[-1]
for turn in range(len(starting_numbers) + 1, num_turns + 1):
number = turn - 1 - numbers.get(last_number, 0)
numbers[last_number] = turn - 1 # Mark turn of last number
if number == turn - 1: # If the number had never been said before
number = 0
last_number = number
print(f"The {num_turns}th number spoken will be {number}.")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="AoC 2020 - Day 15: Rambunctious Recitation"
)
parser.add_argument(
"starting_numbers_path",
type=Path,
help="The path to the starting numbers data file to read",
)
parser.add_argument("num_turns", type=int, help="Number of turns to play the game")
args = parser.parse_args()
rambunctious_recitation(args.starting_numbers_path, args.num_turns)
|
1913d89c6503e5c7cb77a29f2c1064d05e3897c4 | Xander999/GeeksForGeeks-Implementation | /Python2.py | 428 | 3.921875 | 4 | '''
https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-3/0
'''
while(n>0):
s=input()
k=0
g=len(s)
odd=0
even=0
for i in range(g-1,-1,-1):
j=g-1-i
if(s[i]=='1'):
if(j%2==0):
odd=odd+1
else:
even=even+1
if((odd-even)%3==0):
print('1')
else:
print('0')
n=n-1
|
c21c5d23e83c85ecd72ce94447852ee00f3e56c8 | HsiaSharpie/My_Python_Note | /TwoSum.py | 406 | 3.6875 | 4 | class Solution:
def TwoSum(self, nums, target):
value_2_index = {}
for index, num in enumerate(nums):
if target - num in value_2_index:
return [value_2_index[target - num], index]
else:
value_2_index[num] = index
given_nums = [2, 7, 11, 15]
target = 9
if __name__ == "__main__":
print(Solution().TwoSum(given_nums, target)
|
f1437255d61fd79d83adc51da504cd2f85f9f534 | gbernich/marchmadness | /src/objects.py | 1,592 | 3.734375 | 4 | # Object holds winning and losing team names and seeds
class Matchup:
def __init__(self, winner_name, winner_seed, loser_name, loser_seed):
self.winner_name = winner_name
self.winner_seed = winner_seed
self.loser_name = loser_name
self.loser_seed = loser_seed
# Object holds all of the matchups within its Tier (round)
# Synonomous with "Round", using Tier because "round" is a python keyword
class Tier:
def __init__(self, number):
self.number = number
self.matchups = []
def addMatchup(self, matchup):
self.matchups.append(matchup)
# Object holds all of the Tiers (rounds) within the Year's tournament
# Its Tiers can be accessed in a loop with year.tierList or directly with year.tierDict['year']
class Year:
def __init__(self, number):
self.number = number
self.tierList = []
self.tierDict = {}
self.tierNumbers = []
def addTier(self, tier):
self.tierList.append(tier)
self.tierDict[tier.number] = tier
self.tierNumbers.append(tier.number)
def hasTier(self, number):
if number in self.tierNumbers:
return True
else:
return False
# Object holds all of the Years within the Dataset
# Its Years can be accessed in a loop with data.yearList or directly with data.yearDict['year']
class Dataset:
def __init__(self):
self.yearList = []
self.yearDict = {}
self.yearNumbers = []
def addYear(self, year):
self.yearList.append(year)
self.yearDict[year.number] = year
self.yearNumbers.append(year.number)
def hasYear(self, number):
if number in self.yearNumbers:
return True
else:
return False
|
3fa38a20a3710de479b5978c953e4633d336b972 | hsamvel/Python_homeworks | /homework8_1(Narek).py | 329 | 3.546875 | 4 | def about_books(author_name,**var):
list_1 = [var]
print(list_1)
for el in list_1:
for elem in el:
if el[elem][0] == author_name:
print(elem,el[elem][1])
about_books('dyuma',askanio = ('dyuma',1965),sherlock = ('conan doyle',1887),thrones=('martin george',1999))
|
20e5826d68fc6be636cf329fbd0a12ae7b9b6202 | hsamvel/Python_homeworks | /homework12_1(Ruben).py | 378 | 3.5625 | 4 | a = [[10,9,6,3,7],
[6,10,2,9,7],
[7,6,3,8,2],
[8,9,7,9,9],
[6,8,6,8,2]]
i = -1
j = 0
new_a = []
def rotateImage(a):
global i,j,new_a
if j >= len(a):
return new_a
row = []
while abs(i) <= len(a):
row.append(a[i][j])
i -= 1
new_a.append(row)
j += 1
i = -1
return rotateImage(a)
print(rotateImage(a))
|
1c86bfd87bff1739ea37ae9f6b2461a99741d61f | hsamvel/Python_homeworks | /homework8_2(Narek).py | 359 | 3.875 | 4 | list_1 = [9,5,8,5,20,1,2,-3,-2,-1,0]
list_1.sort()
list_1.reverse()
list_2 = list_1[0:3]
list_3 = list_1[len(list_1)-2:len(list_1)]
list_3_count=1
for el in list_3:
list_3_count *= el
list_3_count *=list_1[0]
list_2_count = 1
for elem in list_2:
list_2_count*=elem
if list_3_count > list_2_count:
print(list_3_count)
else:
print(list_2_count)
|
08a393d5f3c7ca9e7453a5d78aef9836fbd384fa | rajeevranjan1/Python | /Harry/inheritance.py | 631 | 3.984375 | 4 | class Employee:
company='Collins'
def __init__(self,name,dept):
self.name=name
self.dept=dept
def showDetails(self):
print(f"Employee Name: {self.name}")
print(f"Departmet: {self.dept}")
def showComputerType(self):
print("PC/Laptop")
class Developer(Employee):
# def showComputerType(self):
# print("Macbook")
def pl(self):
print(f"{self.name}'s Programming Language is Python\nwho is working in {self.company} \nand department is {self.dept}.")
emp=Employee("Rajeev","PSW")
dev=Developer('Ranjan',"Digital")
# emp.pl()
dev.pl()
|
0912899fa71c5c4c52cce4a5353a8f1d484f7a4e | rajeevranjan1/Python | /Harry/chap5.py | 211 | 3.875 | 4 |
num=[23,56,72,7]
if num[0]>num[1]:
c1=num[0]
else:
c1=num[1]
if num[2]>num[3]:
c2=num[2]
else:
c2=num[3]
if c1>c2:
greatest = c1
else:
greatest=c2
print("Greatest Number is",greatest)
|
d663b67480d685326887340f0ea774066078e5d5 | rajeevranjan1/Python | /designerMat.py | 448 | 3.8125 | 4 | y=int(input("Enter number of Row (Odd number between 7 and 101: "))
x=y*3
count=3
fill='.|.'
for i in range(y):
if i<y//2:
print('-'*((x-count)//2)+fill*(2*i+1)+'-'*((x-count)//2))
count +=6
filltemp=2*i+1
elif i==y//2:
print('-'*((x-7)//2) + 'WELCOME' + '-'*((x-7)//2))
else:
count -=6
print('-'*((x-count)//2)+fill*(filltemp)+'-'*((x-count)//2))
filltemp -=2
|
6d010e64a36a24e618ff88e49890bade99583435 | davidth4ever2/ai | /modules/offtopic/python/shifttest1.bk.py | 482 | 3.546875 | 4 | count = 1
currentSeries = 0
shiftword = "skull"
alphabet = "abcdefghijklmnopqrstuvwxyz"
g = 0
for i in range(26):
print "{0:5} | {1:5} | {2:5} | {3:5} | {4:5} ".format(i, currentSeries,count, shiftword[g], alphabet.index(shiftword[g]) + 1)
g = g + 1
if(count%len(shiftword) == 0):
g = 0
currentSeries = currentSeries + 1
count = count + 1
for letter in line1:
print (letter + ' ' + str(alphabet.index(letter.lower())))
|
fafab6946720e7e9c5f6756519566d1542f67e16 | littlewindcc/Image-Processing | /Sharping&Smoothing/smooth/smoothing.py | 791 | 3.5625 | 4 | import cv
#function for Smoothing
def MedianFilter(image):
w = image.width
h = image.height
size = (w,h)
iMFilter = cv.CreateImage(size,8,1)
for i in range(h):
for j in range(w):
if i in [0,h-1] or j in [0,w-1]:
iMFilter[i,j] = image[i,j]
else:
a= [0]*9
for k in range(3):
for l in range(3):
a[k*3+l] = image[i-1+k,j-1+l]
a.sort()
iMFilter[i,j] = a[4]
return iMFilter
#load image
image_name=raw_input('Please input the image name:')+'.jpg'
image = cv.LoadImage(image_name,0)
cv.ShowImage('Original',image)
#show aftersmoothing image
iMF = MedianFilter(image)
cv.ShowImage('AfterSmoothing',iMF)
cv.WaitKey(0)
|
88916b3af1c561a590ba0eeca996894a843e1456 | Skparab1/math-codes | /PolynomialFactorizer.py | 16,630 | 3.578125 | 4 | import time
import math
#superscripts! ² ³ ⁴ ⁵ ⁶ ⁷ ⁸
isquadratic = False
def var_args(args):
num = 0
try:
while True:
hello = (args[num])
num += 1
except:
print(' ')
return num - 1
def factorfinder(number):
number = int(number)
if number < 0:
number = number * -1
factortry = 1
factors = list(str(1))
while factortry <= number:
if number % factortry == 0:
if factortry > 1:
factors.append(str(factortry))
else:
factors = list(str(factortry))
factortry += 1
return (factors)
def quadratic_formula(a,b,c):
w = (str(a) + str(b) + str(c))
w = w.lower()
if a == '' or b == '' or c == '' :
notentered, a, b, c = True, '1', '8', '15'
if True:
a = float(a)
b = float(b)
c = float(c)
a, val1, val2, val3 = (99999 if a == 0 else a), (-1 * b), (-1 * b), ((b*b)-4*a*c)
bsign, csign, astring, bstring, cstring, msquared, m = ('+ ' if b >= 0 else ' '), ('+ ' if c >= 0 else ' '), str(a), str(b), str(c), '㎡ ', 'm '
astring, bstring, astring, msquared, bstring, bsign, m, cstring, csign = ('' if astring == '1' else astring), ('' if bstring == '1' else bstring), ('' if astring == '0' else astring), ('' if astring == '0' else msquared), ('' if bstring == '0' else bstring), ('' if bstring == '0' else bsign), ('' if bstring == '0' else m), ('' if cstring == '0' else cstring), ('' if cstring == '0' else csign)
equation = astring + msquared + bsign + bstring + m + csign + cstring
if val3 < 0:
val3 = val3 * -1
sqrtval, val1, = math.sqrt(val3), val1/(2*a)
sqrtval = sqrtval/(2*a)
roundval1 = round(val1,5)
roundsqrtval = round(sqrtval,5)
if val1 == 0:
solutions = str(' ' + str(roundsqrtval) + 'i ' + ' -' + str(roundsqrtval) + 'i ')
else:
solutions = str(roundval1) + ' + ' + str(roundsqrtval) + 'i , ' + str(roundval1) + ' - ' + str(roundsqrtval) + 'i '
else:
val1 = val1 + math.sqrt(val3)
val2 = val2 - math.sqrt(val3)
val1 = round((val1 / (2*a)), 5)
val2 = round((val2 / (2*a)), 5)
solutions = ' ' + str(val1) if val1 == val2 else ' ' + str(val1) + ' ' + str(val2)
return solutions
def synthetic_devision(a,b,c,d,e,f,possible_factors,numsinlist):
foundfactors = ''
foundornot = 'found'
processingnum = 0
while processingnum <= numsinlist - 1:
processingval = float(possible_factors[processingnum])
val1 = float(a)
calculator = processingval * float(a)
val2 = float(b) + calculator
calculator = val2 * processingval
val3 = float(c) + calculator
calculator = val3 * processingval
val4 = float(d) + calculator
vallast = val4
val5, val6 = '', ''
if e != '':
calculator = val4 * processingval
val5 = float(e) + calculator
vallast = val5
if f != '':
calculator = val5 * processingval
val6 = float(f) + calculator
vallast = val6
if vallast == 0:
foundfactors = str(processingval)
break
processingnum += 1
if foundfactors == '':
foundornot = 'not found'
return foundfactors, val1, val2, val3, val4, val5, val6, foundornot
def stringslicer(string):
a = ''
b = ''
c = ''
d = ''
e = ''
f = ''
#scanner below
scanner = 0
variables_scanned = 1
if scanner < len(string):
reader = string[scanner]
if reader != ' ':
while reader != ' ' and scanner < len(string):
a = a + reader
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
break
variables_scanned += 1
#print('came in to A and varscanned was ' ,variables_scanned, ' a is ', a)
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
scanner, reader = 100,' '
while reader != ' ':
b = b + reader
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
break
variables_scanned += 1
#print('came in to B and varscanned was ' ,variables_scanned, ' b is ', b)
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
scanner, reader = 100,' '
while reader != ' ':
c = c + reader
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
break
variables_scanned += 1
#print('came in to c and varscanned was ' ,variables_scanned, ' c is ', c)
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
scanner, reader = 100,' '
while reader != ' ':
d = d + reader
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
break
variables_scanned += 1
#print('came in to D and varscanned was ' ,variables_scanned, ' d is ', d)
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
scanner, reader = 100,' '
while reader != ' ':
e = e + reader
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
break
variables_scanned += 1
#print('came in to E and varscanned was ' ,variables_scanned, ' e is ', e)
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
scanner, reader = 100,' '
while reader != ' ':
f = f + reader
scanner += 1
if scanner < len(string):
reader = string[scanner]
else:
break
variables_scanned += 1
#print('came in to F and varscanned was ' ,variables_scanned, ' f is ', f)
scanner += 1
return a, b, c, d, e, f
wholestring = input('enter all the coeficients, seperated by spaces: ')
a, b, c, d, e, f = stringslicer(wholestring)
print('\n'*50)
#print('a<',a,'> b<',b,'> c<',c,'> d<',d,'> e<',e,'> f<',f,'>')
'''print('scanning inputs',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.'), time.sleep(0.04)
print('extracting variables',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.'), time.sleep(0.04)
print('factoring variables',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.'), time.sleep(0.04)
print('dividing factors',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.'), time.sleep(0.04)
print('doing synthetic division',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.'), time.sleep(0.04)
print('evaluating using quadratic formula',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.',end = ''), time.sleep(0.04), print('.'), time.sleep(0.04)'''
if f == '' and e == '' and d == '' and c == '' and b == '':
isquadratic = True
print('You entered: a = ', a)
print('The equation detected was y = ',a)
elif f == '' and e == '' and d == '' and c == '':
isquadratic = True
print('You entered: a = ', a, ' b = ', b)
bsign = '+ ' if int(float(b)) >= 0 else ''
print('The equation detected was y = ',a,'x ', bsign,b )
elif f == '' and e == '' and d == '':
bsign = '+ ' if int(float(b)) >= 0 else ''
csign = '+ ' if int(float(c)) >= 0 else ''
isquadratic = True
print('The equation detected was y = ',a,'x² ', bsign,b,'x ',csign,c )
print('You entered: a = ', a, ' b = ', b, ' c = ', c)
# ² ³ ⁴ ⁵ ⁶ ⁷ ⁸
elif f == '' and e == '':
lastval = d
bsign = '+ ' if int(float(b)) >= 0 else ''
csign = '+ ' if int(float(c)) >= 0 else ''
dsign = '+ ' if int(float(d)) >= 0 else ''
print('The equation detected was y = ',a,'x³ ', bsign,b,'x² ',csign,c,'x ',dsign,d )
print('You entered: a = ', a, ' b = ', b, ' c = ', c, ' d = ', d)
elif f == '':
lastval = e
bsign = '+ ' if int(float(b)) >= 0 else ''
csign = '+ ' if int(float(c)) >= 0 else ''
dsign = '+ ' if int(float(d)) >= 0 else ''
esign = '+ ' if int(float(e)) >= 0 else ''
print('You entered: a = ', a, ' b = ', b, ' c = ', c, ' d = ', d, ' e = ', e)
print('The equation detected was y = ',a,'x⁴ ',bsign,b,'x³ ',csign,c,'x² ',dsign,d,'x ',esign,e)
else:
lastval = f
bsign = '+ ' if int(float(b)) >= 0 else ''
csign = '+ ' if int(float(c)) >= 0 else ''
dsign = '+ ' if int(float(d)) >= 0 else ''
esign = '+ ' if int(float(e)) >= 0 else ''
fsign = '+ ' if int(float(f)) >= 0 else ''
print('You entered: a = ', a, ' b = ', b, ' c = ', c, ' d = ', d, ' e = ', e, ' f = ', f)
print('The equation detected was y = ',a,'x⁵',bsign,b,'x⁴ ',csign,c,'x³ ',dsign,d,'x² ',esign,e,'x ',fsign,f)
#try:
if True:
if isquadratic == False:
afactors = factorfinder(a)
lastfactors = factorfinder(lastval)
afactornum = var_args(afactors)
lastfactornum = var_args(lastfactors)
univcounter = 0
numsinlist = 0
while univcounter <= afactornum:
counter = 0
while counter <= lastfactornum:
onefactor = int(lastfactors[counter]) / int(afactors[univcounter])
onefactor = round(onefactor,2)
if univcounter == 0 and counter == 0:
possible_factors = list(str(int(onefactor)))
possible_factors.append(str(onefactor * -1))
numsinlist += 2
else:
if str(onefactor) not in str(possible_factors):
possible_factors.append(str(onefactor))
possible_factors.append(str(onefactor * -1))
numsinlist += 2
counter += 1
univcounter += 1
print('\n\nStep 1: Factorize the a coeficient')
print(' you get ', afactors)
print('\nStep 2: Factorize the last coeficient of the polynomial')
print(' you get ', lastfactors)
print('\nStep 3: Find the possible factors by dividing the factors of the last coeficient by the factors of a')
print(' you get ', possible_factors)
print('\nStep 4: Do synthetic devision and find out which factor is divisible without remainder')
finalfactors, val1, val2, val3, val4, val5, val6, foundornot = synthetic_devision(a,b,c,d,e,f,possible_factors, numsinlist)
finalfactors = str(finalfactors)
if 'not found' in foundornot:
print(' we find that there are no factors that are devisible without remainder, so this polynomial is not factorable.')
else:
print(' we find that ', finalfactors, ' is a factor, and the coeficients remaining are ', val1,' ', val2,' ', val3,' ', val4,' ', val5,' ', val6)
if val5 == '' and val6 == '':
print('\nStep 5: Since we end up with a trinomial, we can use the quadratic formula')
quadfactors = str(quadratic_formula(val1, val2, val3))
print(' The quadratic formula gives us solutions ', quadfactors, ' and we had found factor ', finalfactors, 'using synthetic devision')
finalfactors = finalfactors + ' ' + quadfactors
print('\n\nThe factors of the polynomial are ', finalfactors)
elif val6 == '':
print('\nStep 5: Since we end up with a 4-term polynomial, we must use synthetic devision to find another factor')
onefactor, val1, val2, val3, val4, val5, val6, foundornot = synthetic_devision(val1, val2, val3, val4, val5, val6, possible_factors, numsinlist)
if 'not found' in foundornot:
print(' we find that there are no factors that are devisible without remainder, so the only factor of this polynomial is ', finalfactors)
else:
print(' we find that ', onefactor, ' is another factor, and the coeficients remaining are ', val1,' ', val2,' ', val3,' ', val4,' ', val5,' ', val6)
print('\nStep 6: Now, since we end up with a trinomial, we can use the quadratic formula')
quadfactor = str(quadratic_formula(val1, val2, val3))
finalfactors = finalfactors + ' ' + str(onefactor) + quadfactor
print(' The quadratic formula gives us solutions ', quadfactor, ' and we had found factors ', finalfactors, ' and ', onefactor, ' using synthetic devision')
print('\n\nThe factors of the polynomial are ', finalfactors)
else:
print('\nStep 5: Since we end up with a 5-term polynomial, we must use synthetic devision to find another factor')
onefactor, val1, val2, val3, val4, val5, val6, foundornot = synthetic_devision(val1, val2, val3, val4, val5, val6, possible_factors, numsinlist)
if 'not found' in foundornot:
print(' we find that there are no factors that are divisible without remainder, so the only factor of this polynomial is ', finalfactors)
else:
print(' we find that ', onefactor, ' is another factor, and the coeficients remaining are ', val1,' ', val2,' ', val3,' ', val4,' ', val5,' ', val6)
print('\nStep 6: Now, since we end up with a 4-term polynomial, we must use synthetic devision to find another factor')
twofactor, val1, val2, val3, val4, val5, val6, foundornot = synthetic_devision(val1, val2, val3, val4, val5, val6, possible_factors, numsinlist)
if 'not found' in foundornot:
print(' we find that there are no factors that are devisible without remainder, so the only factor of this polynomial is ', finalfactors)
else:
print(' we find that ', twofactor, ' is another factor, and the coeficients remaining are ', val1,' ', val2,' ', val3,' ', val4,' ', val5,' ', val6)
print('\nStep 7: Now, since we end up with a trinomial, we can use the quadratic formula')
quadfactor = str(quadratic_formula(val1, val2, val3))
print(' The quadratic formula gives us solutions ', quadfactor, ' and we had found factors ', finalfactors, ', ', onefactor, 'and ', twofactor, ' using synthetic devision')
finalfactors = finalfactors + ' ' + str(onefactor) + ' ' + str(twofactor) + quadfactor
print('\n\nThe factors of the polynomial are ', finalfactors)
else:
if b == '' and c == '':
print('\n\nStep 1: Since you have entered an integer, this equation cannot be factored')
else:
if c != '':
print('\n\nStep 1: Since this is a quadratic equation, we can use the quadratic formula to factor it')
quadfactors = str(quadratic_formula(a,b,c))
print(' The solutions given by the quadratic formula are ',quadfactors)
else:
print('\n\nStep 1: Since you have entered a linear equation, we must solve for the variable')
a = float(a)
b = float(b)
negb = -1 * b
factor = negb / a
print(' The answer you get is ', factor)
#except:
# print('Invalid inputs. please try again.')
|
e37dc65138bacbf973b20936a5a0cc61c79acc9c | harshOS/python_learning | /ABSWP/isPhoneNumberIN.py | 659 | 3.90625 | 4 | def isPhonenumberIN(num):
if len(num) != 13 :
return False
if num[0:3] != "+91":
return False
if not num[3:13].isdecimal():
return False
return True
message = "On my wall i found some writen number +918108855425 and 913215854512"
for i in range(len(message)):
part = message[i:i+13]
if isPhonenumberIN(part):
print("Phonenumber found: " +part )
print("Done")
print(isPhonenumberIN("+918108855425"))
print(isPhonenumberIN("+91ahaahahahah"))
print(isPhonenumberIN("+45878787878787"))
print(isPhonenumberIN("+91810885542"))
print(isPhonenumberIN("+918108855425h"))
print(isPhonenumberIN("+91810885a425")) |
cca57e92493f2ad94e154191204902799cb12191 | harshOS/python_learning | /ABSWP/phoneNumINRegex.py | 175 | 3.84375 | 4 | import re
isPhoneIn = re.compile(r'(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}')
mo = isPhoneIn.search("wall det +917894561230")
print("Phone number found: "+mo.group()) |
8a4bf0aac904f4c84465b15f47cc358a18215f36 | jeff-a-holland/python_class_2021_B2 | /exercise_4/solution.py | 2,090 | 3.96875 | 4 | #!/Users/jeff/.pyenv/shims/python
import string
def create_password_checker(min_uppercase, min_lowercase, \
min_punctuation, min_digits):
"""Function to return that checks pw for complexity rules"""
def checker(pw):
### Vars
rules_dict = {}
digit_cntr = upper_cntr = lower_cntr = punc_cntr = 0
special_chars = string.punctuation
### Loop through password string checking each char and increment
### counters as applicable
for char in pw:
if char.isdigit():
digit_cntr += 1
elif char.isupper():
upper_cntr += 1
elif char.islower():
lower_cntr += 1
elif char in special_chars:
punc_cntr += 1
### Append each character class pair to dict
rules_dict['uppercase'] = (upper_cntr - min_uppercase)
rules_dict['lowercase'] = (lower_cntr - min_lowercase)
rules_dict['punctuation'] = (punc_cntr - min_punctuation)
rules_dict['digits'] = (digit_cntr - min_digits)
### If any value in the dict is < 0, set password complexity check to
### False and break out of the loop. Otherwise, set check to True and
### clobber as necessary.
for keys,value in rules_dict.items():
if int(value) < 0:
tuple = (False, rules_dict)
break
elif int(value) >= 0:
tuple = (True, rules_dict)
return tuple
### Return the checker function to create_password_checker function
return checker
def main():
"""Main function for password checker"""
pc = create_password_checker(2, 3, 1, 4)
print('\nChecking password for at least: 2 upper chars, 3 lower chars, 1 punctuation char, and 4 digits...\n')
print(' Password is: AB!1')
print(' Results tuple is:',pc('Ab!1'))
print('\n')
print(' Password is: ABcde!1234')
print(' Results tuple is:',pc('ABcde!1234'))
print('\n')
if __name__ == '__main__':
main()
|
5055cf7e2742d3c0374f828534b73bd8cda1043a | Mayurg6832/HackerRank-DataStructures-solutions | /tree-huffman-decoding.py | 332 | 3.6875 | 4 | def decodeHuff(root, s):
#Enter Your Code Here
result=""
current=root
for i in s:
if int(i)==0:
current=current.left
else:
current=current.right
if current.left==None and current.right==None:
result+=current.data
current=root
print(result)
|
bc7208dae8989597af27878f3de2aa535aa141b0 | CGA21/XO_cmd | /game.py | 2,911 | 4.0625 | 4 | board = ["1","2","3",
"4","5","6",
"7","8","9"]
def play_game():
winner="continue"
current_player=choice()
display_board()
while(winner=="continue"):
ask_input(current_player)
display_board()
winner=check_winner(current_player)
if(winner!="continue"):
break
current_player=flip_player(current_player)
if(winner=="win"):
print(" "+current_player + " won!!")
else:
print("it's a tie!!")
return
def choice():
current_player=input("choose X or O to start with: ")
if(current_player=='X' or current_player=='O'):
print("you chose "+current_player+"!!\n let's start the game")
else:
choice()
return current_player
def display_board():
print(" "+board[0]+"|"+board[1]+"|"+board[2])
print(" "+board[3]+"|"+board[4]+"|"+board[5])
print(" "+board[6]+"|"+board[7]+"|"+board[8])
return
def ask_input(current_player):
print(" "+current_player+"\'s turn!")
ask=input("select a place to enter your value(1-9): ")
ask=int(ask)-1
if(ask>=0 and ask<=8 and board[ask]!="X" and board[ask]!="O"):
board[ask]=current_player
else:
print("illegal entry \n try again!!")
ask_input(current_player)
return
def flip_player(current_player):
if(current_player=='X'):
current_player="O"
else:
current_player="X"
return current_player;
def check_winner(current_player):
if(check_rows(current_player) or check_column(current_player) or check_diagonal(current_player)):
return "win"
elif((board[0]=="X" or board[0]=="O") and
(board[1]=="X" or board[1]=="O") and
(board[2]=="X" or board[2]=="O") and
(board[3]=="X" or board[3]=="O") and
(board[4]=="X" or board[4]=="O") and
(board[5]=="X" or board[5]=="O") and
(board[6]=="X" or board[6]=="O") and
(board[7]=="X" or board[7]=="O") and
(board[8]=="X" or board[8]=="O")):
return "tie"
else:
return "continue"
def check_rows(current_player):
if(board[0]==current_player and board[1]==current_player and board[2]==current_player):
return 1
elif(board[3]==current_player and board[4]==current_player and board[5]==current_player):
return 1
elif(board[6]==current_player and board[7]==current_player and board[8]==current_player):
return true
else:
return 0
def check_column(current_player):
if(board[0]==current_player and board[3]==current_player and board[6]==current_player):
return 1
elif(board[1]==current_player and board[4]==current_player and board[7]==current_player):
return true
elif(board[2]==current_player and board[5]==current_player and board[8]==current_player):
return 1
else:
return 0
def check_diagonal(current_player):
if(board[0]==current_player and board[4]==current_player and board[8]==current_player):
return 1
elif(board[2]==current_player and board[4]==current_player and board[6]==current_player):
return 1
else:
return 0
play_game() |
31bb0177c0f21a2264e07113f05a8f06a5030b85 | aparecidapires/Python | /Python para Zumbis/1 - Comecando com o basico/Comentarios e Resolucao de Exercicios/Lista de Exercicios 1/2.py | 222 | 3.984375 | 4 | '''
Escreva um programa que leia um valor em metros e o exiba convertido em milímetros
'''
metros = float(input('Digite a quantidade de metros: '))
print ('%.1f metros equivale a %d milímetros' %(metros, metros*1000))
|
808bdd5149fc9ecc2540f24b32f22c9e505062cd | aparecidapires/Python | /Python para Zumbis/2 - Mastigando estruturas de controle/Repeticoes/2.1 - TWP250 Fatorial e Break.py | 145 | 3.609375 | 4 | #Cálcule o fatorial de dez
i = 10
fatorial = 1
while i > 1:
fatorial = fatorial * (i-1)
i = i -1
print ('Fatorial(10): %d' %fatorial)
|
4022dd869dd119b97a5ca5ca128076f968aa3d96 | aparecidapires/Python | /Python para Zumbis/1 - Comecando com o basico/Comentarios e Resolucao de Exercicios/Lista de Exercicios 1/4.py | 471 | 3.765625 | 4 | '''
Faça um programa que calcule o aumento de um salário. Ele deve solicitar o valor do salário e a porcentagem do aumento.
Exiba o valor do aumento e do novo salário.
'''
salario = float(input('Digite o salario: '))
porcentagem = float(input('Digite a porcentagem de aumento: '))
novoSalario = salario + (salario * porcentagem)/100
aumento = (salario * porcentagem)/100
print ('Novo salario: R$ %.2f ' %novoSalario)
print ('O aumento foi de %2.f reais ' %aumento)
|
4af8683399a7344690ba6e7a3ba749d10852c993 | aparecidapires/Python | /Python para Zumbis/3 - Atacando os tipos basicos/Comentarios e Resolucao de Exercicios/Lista III/1.py | 398 | 4.375 | 4 | '''
Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.
'''
nota = float(input("Digite uma nota entre '0' e '10': "))
while nota < 0 or nota > 10:
print ('Digite uma nota válida!')
nota = float(input("Digite uma nota entre '0' e '10': "))
print ('Nota: %2.f' %nota)
|
6a284e461c5325c9f072614a21a69e667b4210cd | aparecidapires/Python | /Python para Zumbis/2 - Mastigando estruturas de controle/Repeticoes/2.1 - TWP250 Fatorial e Break - c.py | 217 | 4.0625 | 4 | # Calcule o fatorial de um número inteiro n
i = 1
fatorial = 1
numero = int(input('Digite um número: '))
while i <= numero:
fatorial = fatorial * i
i = i + 1
print ('Fatorial(%d) = %d' %(numero, fatorial))
|
b20c934c81250c39f5788138338038ece040949f | Grifo89/Algorithms | /where_do_I_belong/getIndexToIns.py | 539 | 3.78125 | 4 | from typing import List
def getIndexToIns(arr: List, num: int) -> int:
# 1. Sortin list
# list.sort()
for i in range(len(arr) - 1):
for j in range(len(arr) - i -1):
if arr[j + 1] < arr[j]:
tmp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tmp
# 2. Looking the right num position
for i in range(len(arr) - 1):
if arr[i] >= num:
return i
# 3. Return the last position if num is greater then all array's elements
return len(arr) |
b9811d02517fe7e3ab26665d29ff8ffcca068693 | lc-huertas/CodingDojo_Python_Stack | /_python/BankAcc.py | 1,726 | 4.0625 | 4 | class BankAccount:
def __init__(self, int_rate, balance): # don't forget to add some default values for these parameters!
# your code here! (remember, this is where we specify the attributes for our class)
# don't worry about user info here; we'll involve the User class soon.
self.interest = int_rate
self.balance = balance
def deposit(self, amount):
# your code here
self.balance += amount
return self
def withdraw(self, amount):
# your code here
self.balance -= amount
return self
def display_account_info(self):
# your code here
print(f"Account balance: ${self.balance}")
return self
def yield_interest(self):
# your code here
self.balance = self.balance * (1 + self.interest)
return self
# Create a BankAccount class with the attributes interest rate and balance
# Add a deposit method to the BankAccount class
# Add a withdraw method to the BankAccount class
# Add a display_account_info method to the BankAccount class
# Add a yield_interest method to the BankAccount class Create 2 accounts
# To the first account, make 3 deposits and 1 withdrawal,
# then calculate interest and display the account's info all in one line of code (i.e. chaining)
# To the second account, make 2 deposits and 4 withdrawals,
# then calculate interest and display the account's info all in one line of code (i.e. chaining)
Acc1 = BankAccount(0.01,100)
Acc2 = BankAccount(0.03,50)
Acc1.deposit(5).deposit(5).deposit(5).withdraw(5).yield_interest().display_account_info()
Acc1.deposit(5).deposit(5).withdraw(5).withdraw(5).withdraw(5).withdraw(5).yield_interest().display_account_info() |
35461c4770c624d1a7843dc88884113255d74344 | luciangutu/job_test | /salary.py | 963 | 3.890625 | 4 | """
script to calculate how many years it will take to reach a better salary
s1 - current (lower) salary
s2 - future/wanted/promissed salary
i1 - yearly salary increase for the current salary (%)
i2 - yearly salary increase at the other company that you are thinking of going (%)
"""
s1 = 500
s2 = 800
i1 = 5
i2 = 2
########################
# percent calculator
########################
def compute(s, i):
return s*i/100
sal1 = s1
sal2 = s2
x_test = False
for x in range(50):
sal1 += compute(sal1, i1)
sal2 += compute(sal2, i2)
if sal1 >= s2 and not x_test:
x1 = x
x_test = True
if sal1 >= sal2:
print("Your current salary is {}. It will take {} years in order to reach the same aimed salary {}. Good luck!". format(s1, x1, s2))
print("After {} years, you will have the same salary. Your current employee will pay you {} and the one that you aim for will pay you {}.". format(x, sal1, sal2))
break
|
351f49543c5a9d942474a2a34a02543c98b0c92b | luciangutu/job_test | /yield_generator.py | 181 | 3.59375 | 4 | def gen(n):
for i in range(n):
if i % 2 == 0:
yield i
x = 5
g = gen(x)
while True:
try:
print(next(g))
except StopIteration:
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.