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 |
|---|---|---|---|---|---|---|
22b7b2b479501be16f1f9a5e7c416ad930ab616e | pankrac88/jarowinkler | /jaro.py | 1,811 | 3.640625 | 4 | def main():
string1 = 'DWAYNE'
string2 = 'DUANE'
print('Jaro Winkler distance between {} and {} is: {}'.format(string1, string2, jaro_winkler_distance(string1, string2)))
def jaro_winkler_distance(string1, string2):
jaro = jaro_distance(string1, string2)
prefix = 0
for index, char in enumerate(string1[:4]):
if char == string2[index]:
print(char)
prefix = prefix + 1
else:
break
if (jaro > 0.7):
return jaro + ((prefix * 0.1) * (1 - jaro))
else:
return jaro
def jaro_distance(string1, string2):
if len(string1) < len(string2):
longerString = string2
shorterString = string1
else:
longerString = string1
shorterString = string2
# Should be rounded down
allowedRange = (len(longerString) // 2) - 1
mappingIndices = [-1] * len(shorterString)
shortMached = []
longMatched = []
matches = 0
for index, char in enumerate(shorterString):
for secondIndex in range(max(0, index - allowedRange), min(len(longerString), index + allowedRange + 1)):
if char == longerString[secondIndex]:
matches = matches + 1
mappingIndices[index] = secondIndex
shortMached.append(char)
longMatched.insert(secondIndex, char)
break
halfTranspositions = 0
for naturalIndex in range(0, len(shortMached)):
if (mappingIndices[naturalIndex] != naturalIndex) & (shortMached[naturalIndex] != longMatched[naturalIndex]):
halfTranspositions = halfTranspositions + 1
return ((matches / len(longerString)) + (matches / len(shorterString)) + ((matches - (halfTranspositions // 2))/matches)) / 3
if __name__ == "__main__":
main() |
1352e5b2dfc41ea64f3377886a59b7212b6fe19c | basant88/workshop | /atmsolution/atm.py | 564 | 3.71875 | 4 | money=450
request=800
if(request>money):
request=money
if(request<=0):
print"Please enter right request"
while request>0:
if(request>=100 ):
print "give 100"
request=request-100
elif(request>=50):
print "give 50"
request=request-50
elif(request>=10):
print "give 10"
request=request-10
elif(request>=5 ):
print "give 5"
request=request-5
else:
print "give "+str(request)
request=0
|
711de50425119b20d1d9f4235689895dd250332c | joydas65/GeeksforGeeks | /Check_If_Two_Strings_Are_K_Anagrams_Or_Not.py | 303 | 3.5 | 4 | from collections import Counter
def areKAnagrams(str1, str2, k):
# Code here
n,m = len(str1),len(str2)
if n != m:
return False
diff = Counter(str1) - Counter(str2)
if sum(diff.values()) > k:
return False
return True
|
d718154c1e137b75120f98a6d69e7b68543c1a36 | joydas65/GeeksforGeeks | /Remove_duplicate_elements_from_sorted_array.py | 251 | 3.515625 | 4 | def remove_duplicate(n, arr):
#Code here
i,j = 0,1
while j < n:
if arr[i] != arr[j]:
i += 1
arr[i] = arr[j]
j += 1
return i + 1
|
74714d6f271872cd968f90bcfedae438293b9e5e | ignatiusmb/algorithms | /codeforces/736A.py | 134 | 3.734375 | 4 | n = int(input())
if n == 2:
print(1)
else:
res = 0
while n > 1:
n /= 2
res += 1
print(res)
|
f55fec35f55466baad3f0bb42940f95d783c5bb3 | tushgaurav/SpeechSynth | /main.py | 500 | 3.578125 | 4 | import branding
import pyttsx3
branding.welcome()
speaker = pyttsx3.init()
choice = 'Y'
yes = choice.upper()
while choice == yes:
text = str(input("What do you want me to say?"))
speaker.say(text)
speaker.runAndWait()
choice = str(input("Try again? (Y/N)")).upper()
if choice == 'n'.upper():
print("Thanks for using!")
print("Aborting...")
branding.ending()
exit()
else:
print("Wrong input recieved.")
print("Aborting...")
branding.ending()
exit() |
09ffd49011960c69936b0e5a522471ea6aa5f4d0 | ishaansathaye/python | /essentials/files.py | 912 | 4.03125 | 4 | ## 6/25/19 ##
########### Creating, Reading, Writing Files ############
testFile = open("Test.txt", 'w') # overwrite/write into the file
testFile.write("Python is an interpreted, high-level, general-purpose programming language\n")
testFile.write("Created by Guido van Rossum and first released in 1991\n")
testFile.write("Python's design philosophy emphasizes code readability with its notable use of significant whitespace\n")
testFile.write("Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects")
testFile.close()
# file = open("Test.txt", "r") # read the file
# text = file.read()
# print(text)
# file.close()
newFile = open("Test.txt", "a") # append a file and "a+" is to read and append
newFile.write("\nPython is a great language overall!")
newText = newFile.read()
# print(newText) # only use this with a+
newFile.close()
|
0066e31adfc13218b909be728f275dc2809a3a88 | bmanandhar/final_online_coding | /subsets.py | 443 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 24 14:09:36 2018
@author: bijayamanandhar
"""
def subsets(s):
if s == []: return [s]
sets = [s]
for i in range(len(s)):
temp_subsets = subsets(s[:i] + s[i+1:])
for subset in temp_subsets:
if subset not in sets:
sets.append(subset)
return sets
print(subsets(['a', 'b', 'c']))
print(subsets([1, 2, 3])) |
55894d2ab1f45b597e5d13dd3a3ff25a5db7681f | danimtk/distance-similarity-measures | /5_cosine_similarity.py | 1,682 | 3.796875 | 4 | #
#Desenvolvido por Andre H. Costa Silva baseado no codigo fonte
#de Rodrigo Mendes (implementado em javascript): https://github.com/rdgms/hello_cosine_similarity
#
import math
import string
def calculate_frequence(word):
result = {}
for char in string.ascii_lowercase:
if char not in result:
result[char] = 0.0
for w in word:
if char == w:
result[char] += 1.0
return result
def calculate_product(x,y):
return sum([x[i]*y[i] for i in x])
def calculate_magnitude(x):
return sum(((x[i]) ** 2.0) for i in x) ** (0.5)
word_1 = "teste"
word_2 = "testi"
word_3 = "test"
word_1_frequence = calculate_frequence(word_1)
word_2_frequence = calculate_frequence(word_2)
word_3_frequence = calculate_frequence(word_3)
words_product1 = calculate_product(word_1_frequence, word_2_frequence)
words_product2 = calculate_product(word_1_frequence, word_3_frequence)
words_product3 = calculate_product(word_2_frequence, word_3_frequence)
word_1_magnitude = calculate_magnitude(word_1_frequence)
word_2_magnitude = calculate_magnitude(word_2_frequence)
word_3_magnitude = calculate_magnitude(word_3_frequence)
#print word_1_magnitude
#print word_2_magnitude
magnitude_product1 = word_1_magnitude * word_2_magnitude
magnitude_product2 = word_1_magnitude * word_3_magnitude
magnitude_product3 = word_2_magnitude * word_3_magnitude
result1 = words_product1 / magnitude_product1
result2 = words_product2 / magnitude_product2
result3 = words_product3 / magnitude_product3
print word_1, " is " , result1,"% similar to " , word_2
print word_1, " is " , result2,"% similar to " , word_3
print word_2, " is " , result3,"% similar to " , word_3
|
cdec4625a7ff92699a60fd2e15121161ba50dad9 | Lemmy-21/Es_Scuola | /c.[ 10 - 12 ]/2scheda.py | 544 | 3.78125 | 4 | '''
[es 2 - scheda]
Scrivi una programma che data in ingresso una lista A contenente n parole,
restituisca in output una lista B di interi che rappresentano la lunghezza delle parole
contenute in A.
'''
num_parole = int(input("quante parole vuoi inserire?\n"))
parole = []
numeri = []
for i in range(num_parole):
parola = input("inserici una parola\n")
parole.append(parola)
for i in range(num_parole):
lunghezza = len(parole[i])
numeri.append(lunghezza)
print("parole:", parole, "\nlunghezza parole:", numeri, "\n")
|
28ff656b10ad06b6c5e79f3eb948a20f8ff685ce | Lemmy-21/Es_Scuola | /e.[ 20 - 01 ]/2p201.py | 799 | 3.78125 | 4 | '''
[es 2 - pag 201]
Data la parabola y = ax² + bx + c,
definisci due funzioni per calcolarne i punti significativi:
vertice e fuoco.
Le due funzioni ricevono come parametri a, b, c
e restituiscono il valore calcolato
'''
def fuoco(a, b ,c, delta):
x_fuoco = -b/2*a
y_fuoco = (1-delta)/(4*a)
return x_fuoco, y_fuoco
def vertice(a, b, c, delta):
x_vertice = -b/2*a
y_vertice = -delta/4*a
return x_vertice, y_vertice
a = int(input('inserire variabile a\n'))
if a == 0:
while a ==0:
a = int(input('inserire variabile a diversa da 0\n'))
b = int(input('inserire variabile b\n'))
c = int(input('inserire variabile c\n'))
delta = b**2 - 4*a*c
print("il fuoco della parabola e'", fuoco(a, b , c, delta), "\n il vertice della parabola e'", vertice(a, b, c, delta)) |
8660e5a159f3228293182dc2b163c6c2af6321a1 | Lemmy-21/Es_Scuola | /b.[ 03 - 12 ]/28p73.py | 909 | 3.734375 | 4 | '''
[es 28 - pag 73]
Dato un elenco di studenti partecipanti a una gara sportiva
di lancio del peso (nome studente, lancio), visualizza il valore
del lancio del vincitore (valore massimo).
'''
studenti = []
lanci = []
vincitori = []
start = int(input("quanti studenti vuoi immettere?\n\n"))
for i in range(start):
studente = input("studente\n\n")
lancio = int(input("lancio\n\n"))
studenti.append(studente)
lanci.append(lancio)
lancio_max = max(lanci)
massimi = lanci.count(lancio_max)
'''
for i in range(massimi):
index_pos = lanci.index(lancio_max)
vincitore = studenti[index_pos]
vincitori.append(vincitore)
lanci.remove(lanci[index_pos])
studenti.remove(studenti[index_pos])
'''
for i in range(len(lanci)):
if lanci[i] == lancio_max:
vincitori.append(studenti[i])
print("ha/hanno vinto:", vincitori, "facendo", lancio_max)
|
d21ef77fe0a38294473fa75eaebf7064544a2acd | trokas/optimal_polygon | /optimal_polygon.py | 5,076 | 3.5625 | 4 | import numpy as np
def _angle(u, v, w, d='+'):
"""
Measures angle between points u, v and w in positive or negative direction
Args:
u (list): x and y coordinates
v (list): x and y coordinates
w (list): x and y coordinates
d (str, optional): direction of angle '+' = counterclockwise
Returns:
float: angle in radians
"""
vu = np.arctan2(u[1] - v[1], u[0] - v[0])
vw = np.arctan2(w[1] - v[1], w[0] - v[0])
phi = vw - vu
if phi < 0:
phi += 2 * np.pi
if d == '-':
phi = 2 * np.pi - phi
return np.round(phi, 6)
def _intersect(A, B, C, D):
"""
Returns intersection of lines AB and CD
Args:
A (list): x and y coordinates
B (list): x and y coordinates
C (list): x and y coordinates
D (list): x and y coordinates
Returns:
tuple: x and y coordinates of the intersection
"""
d = (B[0] - A[0]) * (D[1] - C[1]) - (D[0] - C[0]) * (B[1] - A[1])
x = ((B[0] * A[1] - A[0] * B[1]) * (D[0] - C[0]) - (D[0] * C[1] - C[0] * D[1]) * (B[0] - A[0])) / d
y = ((B[0] * A[1] - A[0] * B[1]) * (D[1] - C[1]) - (D[0] * C[1] - C[0] * D[1]) * (B[1] - A[1])) / d
return (np.round(x, 6), np.round(y, 6))
def optimal_polygon(y, w=0.5, debug=False):
"""
Constructs optimal polygon and returns pivot points.
Based on 'An Optimal Algorithm for Approximating a. Piecewise Linear
Function. HIROSHI IMAI and MASAO Iri.'
Args:
y (np.array or list): time series
w (float, optional): shift used for tunnel
Returns:
np.array: pivot points
"""
# Make sure that we use numpy array
y = np.array(y)
x = np.arange(len(y))
# Initialization
y = np.round(y, 6)
p_plus = (x[0], y[0] + w)
l_plus = (x[0], y[0] + w)
r_plus = (x[1], y[1] + w)
s_plus = {(x[0], y[0] + w): (x[1], y[1] + w)}
t_plus = {(x[1], y[1] + w): (x[0], y[0] + w)}
p_minus = (x[0], y[0] - w)
l_minus = (x[0], y[0] - w)
r_minus = (x[1], y[1] - w)
s_minus = {(x[0], y[0] - w): (x[1], y[1] - w)}
t_minus = {(x[1], y[1] - w): (x[0], y[0] - w)}
q = []
i = 2
while i < len(y):
# Updating CH_plus (convex hull) and CH_minus
p = (x[i - 1], y[i - 1] + w)
p_i_plus = (x[i], y[i] + w)
while (p != p_plus) and _angle(p_i_plus, p, t_plus[p], '+') > np.pi:
p = t_plus[p]
s_plus[p] = p_i_plus
t_plus[p_i_plus] = p
p = (x[i - 1], y[i - 1] - w)
p_i_minus = (x[i], y[i] - w)
while (p != p_minus) and _angle(p_i_minus, p, t_minus[p], '-') > np.pi:
p = t_minus[p]
s_minus[p] = p_i_minus
t_minus[p_i_minus] = p
# Check if CH_plus and CH_minus intersect
if _angle(p_i_plus, l_plus, r_minus, '+') < np.pi:
q.append((_intersect(l_plus, r_minus, p_plus, p_minus), l_plus, r_minus, p_plus, p_minus))
p_minus = r_minus
p_plus = _intersect(l_plus, r_minus, (x[i - 1], y[i - 1] + w), p_i_plus)
s_plus[p_plus] = p_i_plus
t_plus[p_i_plus] = p_plus
r_plus = p_i_plus
r_minus = p_i_minus
l_plus = p_plus
l_minus = p_minus
while _angle(l_minus, r_plus, s_minus[l_minus], '-') < np.pi:
l_minus = s_minus[l_minus]
elif _angle(p_i_minus, l_minus, r_plus, '-') < np.pi:
q.append((_intersect(l_minus, r_plus, p_minus, p_plus), l_minus, r_plus, p_minus, p_plus))
p_plus = r_plus
p_minus = _intersect(l_minus, r_plus, (x[i - 1], y[i - 1] - w), p_i_minus)
s_minus[p_minus] = p_i_minus
t_minus[p_i_minus] = p_minus
r_minus = p_i_minus
r_plus = p_i_plus
l_minus = p_minus
l_plus = p_plus
while _angle(l_plus, r_minus, s_plus[l_plus], '+') < np.pi:
l_plus = s_plus[l_plus]
else:
# Updating the two seperating and supporting lines
if _angle(p_i_plus, l_minus, r_plus, '+') < np.pi:
r_plus = p_i_plus
while _angle(p_i_plus, l_minus, s_minus[l_minus], '+') < np.pi:
l_minus = s_minus[l_minus]
if _angle(p_i_minus, l_plus, r_minus, '-') < np.pi:
r_minus = p_i_minus
while _angle(p_i_minus, l_plus, s_plus[l_plus], '-') < np.pi:
l_plus = s_plus[l_plus]
i += 1
# Add last change point
a = _intersect(l_plus, r_minus, p_plus, p_minus)
b = _intersect(l_minus, r_plus, p_minus, p_plus)
p = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
q.append((p, r_minus, r_plus, p_minus, p_plus))
end_a = _intersect(p, r_plus, p_i_minus, p_i_plus)
end_b = _intersect(p, r_minus, p_i_minus, p_i_plus)
end = ((end_a[0] + end_b[0]) / 2, (end_a[1] + end_b[1]) / 2)
q.append((end, (None, None), (None, None), p_i_minus, p_i_plus))
if debug:
return np.array(q)
else:
return np.array([o[0] for o in q])
|
2368073e9f1c7eb84b753d111c1d0826cc1f8796 | Bastlwastl42/advent_of_code | /common/word_jitter.py | 581 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Created on 25/12/2020 18:48
@author: Sebastian Lehrack
word_jitter.py is a script for....
"""
from itertools import permutations
import duden
if __name__ == "__main__":
print("Welcome to word_jitter.py")
letters = ['a', 'e', 't', 'i', 'p', 's', 'r']
for word in permutations(letters):
da_word = f'{word[0].capitalize()}{word[1]}{word[2]}{word[3]}{word[4]}{word[5]}{word[6]}'
print(da_word)
w = duden.search(da_word)
if w:
print('found!!:')
print(w)
break
|
902525dacd2a677ed65b4f1bf530e268c225c4ae | Bastlwastl42/advent_of_code | /10/jotage_adpaters.py | 1,808 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Created on 10/12/2020 08:11
@author: Sebastian
jotage_adpaters.py is a script for advent of code day 10
"""
import math
import os
from typing import List
from common import load_input_file
def find_next_drei(counter: int, list_of_diffs: List[int]):
for next_count, val in enumerate(list_of_diffs[counter + 1:]):
if val == 3:
return next_count
return len(list_of_diffs[counter+1:])
def get_kombinations(n: int):
if n in [0, 1]:
return 1
if n == 2:
return 2
if n == 3:
return 4
if n == 4:
return 7
if n == 5:
return 13
raise ValueError
if __name__ == "__main__":
print("Welcome to jotage_adpaters.py")
input_number_sorted = [int(i) for i in load_input_file(os.getcwd(), file='input.txt')]
input_number_sorted.append(0)
input_number_sorted.append(max(input_number_sorted) + 3)
input_number_sorted.sort()
differences = [input_number_sorted[counter + 1] - input_number_sorted[counter] for counter in
range(len(input_number_sorted) - 1)]
eins_jolt_diff = len([i for i in differences if i == 1])
drei_jolt_diff = len([i for i in differences if i == 3])
print(f'Found 1 jolt differences {eins_jolt_diff}, 3 jolt differences {drei_jolt_diff}, '
f'Product {eins_jolt_diff * drei_jolt_diff}')
# in the set of differences, find sequence pattern
list_of_kombination = [get_kombinations(find_next_drei(0, differences)+1)]
for counter, diff in enumerate(differences):
if diff == 1:
continue
if diff == 3:
list_of_kombination.append(get_kombinations(find_next_drei(counter, differences)))
print(f'Part two provided {math.prod(list_of_kombination)}')
|
cf57371e6b6dd439dec168da65702c4e210f1688 | Bastlwastl42/advent_of_code | /09/XMAS_decipher.py | 1,742 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Created on 09/12/2020 08:02
@author: Sebastian
XMAS_decipher.py is a script for advent of code day 9
"""
import os
from typing import List
from common import load_input_file
SUBSET_LENGTH = 25
def find_sum_of_two(number: int, subset: List[int]):
if len(subset) != SUBSET_LENGTH:
print('INVALID SUBSET GIVEN: LENGTH!')
return [summand for summand in subset if number - summand in subset]
if __name__ == "__main__":
print("Welcome to XMAS_decipher.py")
input_numbers = [int(i) for i in load_input_file(os.getcwd())]
max_iter_val = len(input_numbers) - SUBSET_LENGTH - 1
for counter in range(max_iter_val):
findings = find_sum_of_two(number=input_numbers[counter + SUBSET_LENGTH],
subset=input_numbers[counter:SUBSET_LENGTH + counter])
if not findings:
weakness_value = input_numbers[counter + SUBSET_LENGTH]
print(weakness_value)
break
for low_counter in range(max_iter_val):
found_set = []
for up_counter in range(low_counter + 1, max_iter_val, 1):
cur_sum = sum(input_numbers[low_counter:up_counter])
if cur_sum < weakness_value:
continue
elif cur_sum > weakness_value:
break
elif cur_sum == weakness_value:
print('Found set!')
found_set = input_numbers[low_counter:up_counter]
print(found_set)
print(f'Min {min(found_set)} and Max {max(found_set)}')
print(f'Sum is {min(found_set) + max(found_set)}')
break
if found_set:
break
print('Ende')
|
3a21120c6e8e9814b6dad06431ec73beaeee9ff2 | Roha123611/activity-sheet2 | /prog15.py | 366 | 4.1875 | 4 | #prog15
#t.taken
from fractions import Fraction
def addfraction(st_value,it_value):
sum=0
for i in range(st_value,it_value):
sum=sum+Fraction(1,i)
print('the sum of fractions is:',sum)
return
st_value=int(input('input starting value of series:'))
it_value=int(input('enter ending value of series'))
addfraction(st_value,it_value)
|
506e8e1db70f0189b7968120eb48790a65da4f77 | Roha123611/activity-sheet2 | /PROG14.py | 581 | 3.796875 | 4 | #PROGRAM14
#T.TAKEN
def area(l1,l2,b1,b2):
area1=l1*b1
print('area of 1st rectangle is:',area1,'cm\u00b2')
area2=l2*b2
print('area of 2nd rectangle is:',area2,'cm\u00b2')
if l1>l2 or b1>b2:
q=area1-area2
print('the remaining area is:',q,'cm\u00b2')
else:
q=area2-area1
print('the remainig area is:',q,'cm\u00b2')
return
l1=eval(input('enter the 1st lenght:'))
l2=eval(input('enter the 2nd lenght:'))
b1=eval(input('enter the 1st breath:'))
b2=eval(input('enter the 2nd breath:'))
area(l1,l2,b1,b2)
|
32fcf90d6429304258bd4bc490c989c49de69209 | faneyer101/bootcamp-python-day01 | /ex03/matrix.py | 11,544 | 3.65625 | 4 | from numbers import Real
class Vector:
def create_list_with_size(self, size):
i = 0.0
liste = []
if size > 0:
while i < size:
liste.append(float(i))
i += 1
return liste
else:
print("Need size > 0")
quit()
def create_list_with_tuple(self, tab_tuple):
liste = []
if len(tab_tuple) == 2:
if isinstance(tab_tuple[0], int) and isinstance(tab_tuple[1], int):
if tab_tuple[0] < tab_tuple[1]:
i = tab_tuple[0]
while i < tab_tuple[1]:
liste.append(float(i))
i += 1
elif tab_tuple[0] > tab_tuple[1]:
i = tab_tuple[1]
while tab_tuple[0] > i:
liste.append(float(i))
i += 1
else:
print("Error of tuple. Need different number")
quit()
else:
print("Error values on tuple need Integer")
quit()
else:
print("Error Tuple is bad")
quit()
return liste
def __init__(self, value):
if isinstance(value, list):
for d in value:
if not isinstance(d, float):
print("ERROR LIST HAVE NO FLOAT")
quit()
self.values = value
elif isinstance(value, int):
self.values = self.create_list_with_size(value)
elif isinstance(value, tuple):
self.values = self.create_list_with_tuple(value)
else:
print("Type of value is not supported")
quit()
self.size = len(self.values)
class Matrix:
def __init__(self, matrice, value=(0, 0)):
self.data = []
self.shape = []
data_row = []
if isinstance(matrice, list):
columns = 0
for row in matrice:
if isinstance(row, list):
for i in row:
data_row.append(i)
else:
print("Type of value is not supported 1", self.data)
quit()
self.data.append(data_row)
data_row = []
columns += 1
self.shape.append(columns)
self.shape.append(len(row))
elif isinstance(matrice, tuple) and len(matrice) == 2:
if isinstance(matrice[0], int) and isinstance(matrice[1], int):
j = 0
while j < matrice[1]:
i = 0
while i < matrice[0]:
data_row.append(0)
i += 1
self.data.append(data_row)
data_row = []
j += 1
self.shape.append(matrice[0])
self.shape.append(matrice[1])
else:
print("Type of value is not supported 2")
quit()
else:
print("Type of value is not supported 3")
quit()
def __add__(self, operator):
result = []
result_add = []
if isinstance(operator, Real):
for i in self.data:
for j in i:
result_add.append(float(operator + j))
result.append(result_add)
result_add = []
elif isinstance(operator, Vector):
if self.shape[0] == 1:
if self.shape[1] == operator.size:
i = 0
while i < self.shape[1]:
result_add.append(float(self.data[0][i] +
operator.values[i]))
i += 1
result.append(result_add)
else:
print("Error vect + matrix. col matrix need == size Vect")
quit()
else:
print("Error vector + matrix. Dimention matrix need == 1")
quit()
elif isinstance(operator, Matrix):
if self.shape == operator.shape:
y = 0
while y < self.shape[0]:
x = 0
while x < self.shape[1]:
result_add.append(float(self.data[y][x] +
operator.data[y][x]))
x += 1
result.append(result_add)
result_add = []
y += 1
else:
print("addition between two matrix of different size")
quit()
else:
print("unsupported argument for addition")
quit()
return Matrix(result)
def __radd__(self, operator):
return self.__add__(operator)
def __sub__(self, operator):
result = []
result_sub = []
if isinstance(operator, Real):
for i in self.data:
for j in i:
result_sub.append(float(j - operator))
result.append(result_sub)
result_sub = []
elif isinstance(operator, Vector):
if self.shape[0] == 1:
if self.shape[1] == operator.size:
i = 0
while i < self.shape[1]:
result_sub.append(float(self.data[0][i] -
operator.values[i]))
i += 1
result.append(result_sub)
else:
print("Error vect + matrix. col matrix need == size vect")
quit()
else:
print("Error vector + matrix. Dimention matrix need == 1")
quit()
elif isinstance(operator, Matrix):
if self.shape == operator.shape:
y = 0
while y < self.shape[0]:
x = 0
while x < self.shape[1]:
result_sub.append(float(self.data[y][x] -
operator.data[y][x]))
x += 1
result.append(result_sub)
result_sub = []
y += 1
else:
print("substraction between two matrix of different size")
quit()
else:
print("unsupported argument for substraction")
quit()
return Matrix(result)
def __rsub__(self, operator):
result = []
result_sub = []
if isinstance(operator, Real):
for i in self.data:
for j in i:
result_sub.append(float(operator - j))
result.append(result_sub)
result_sub = []
elif isinstance(operator, Vector):
if self.shape[0] == 1:
if self.shape[1] == operator.size:
i = 0
while i < self.shape[1]:
result_sub.append(float(operator.values[i] -
self.data[0][i]))
i += 1
result.append(result_sub)
else:
print("Error vect + matrix. col matrix need == size Vect")
quit()
else:
print("Impossible vector + matrix. Dimention matrix need == 1")
quit()
elif isinstance(operator, Matrix):
if self.shape == operator.shape:
y = 0
while y < self.shape[0]:
x = 0
while x < self.shape[1]:
result_sub.append(float(operator.data[y][x] -
self.data[y][x]))
x += 1
result.append(result_sub)
result_sub = []
y += 1
else:
print("substraction between two matrix of different size")
quit()
else:
print("unsupported argument for substraction")
quit()
return Matrix(result)
def __truediv__(self, operator):
result = []
result_div = []
if operator == 0:
print("Zero division is imposible")
quit()
for y in self.data:
for x in y:
result_div.append(float(x / operator))
result.append(result_div)
result_div = []
return Matrix(result)
def __rtruediv__(self, operator):
result = []
result_div = []
if operator == 0:
print("Zero division is imposible")
quit()
for y in self.data:
for x in y:
if x == 0:
print("Zero division is imposible")
quit()
result_div.append(float(operator / x))
result.append(result_div)
result_div = []
return Matrix(result)
def __mul__(self, operator):
scalar = []
result = 0.0
matrice = []
if isinstance(operator, Real):
for y in self.data:
for x in y:
scalar.append(float(operator * x))
matrice.append(scalar)
scalar = []
elif isinstance(operator, Matrix):
if self.shape[1] == operator.shape[0]:
m = 0
n = 0
y = 0
while y < self.shape[0]:
x = 0
while x < operator.shape[1]:
n = 0
m = 0
result = 0
while n < operator.shape[0]:
result += float(self.data[y][n] *
operator.data[m][x])
n += 1
m += 1
scalar.append(result)
x += 1
matrice.append(scalar)
scalar = []
y += 1
else:
print("multiplcation between two matrix of different size")
quit()
elif isinstance(operator, Vector):
if self.shape[1] == operator.size:
x = 0
while x < self.shape[0]:
n = 0
result = 0
while n < self.shape[1]:
result += float(self.data[x][n] * operator.values[n])
n += 1
scalar.append(result)
x += 1
matrice.append(scalar)
scalar = []
else:
print("Multi between vectors and matrix of different size")
quit()
else:
print("unsupported argument for multiplication")
quit()
return Matrix(matrice)
def __rmul__(self, operator):
return self.__mul__(operator)
def __str__(self):
s = '['
for i, val in enumerate(self.data):
s += "{}".format(val)
if i != self.shape[0] - 1:
s += '\n'
s += ']'
return s
def __repr__(self):
return str(self.data)
|
4a917541eaf35c7e398ec8a4bb6acd1774541c9e | helgurd/Easy-solve-and-Learn-python- | /differBetw_ARR_LIST.py | 978 | 4.4375 | 4 | # first of all before we get into Python lists are not arrays, arrays are two separate things and it is a common mistakes that people think that lists are the same arrays.
#in array if we append different data type will return typeerror which that is not case in the list.
# ARRAY!=LIST
###example 1 python list
import array
#LIST....................................
aList= [1,2,'monkey' ]
print(aList)
#Appending to the LIST.
bList= [1,2,3,5,6,7,8,'limon' ]
bList.append('Name')
print(bList,end='')
print('')
#extra list, in this exersice the program only print the numbers that can be devided by 2:
bList= [1,2,3,5,6,7,8 ]
for x in bList:
if x % 2==0:
print([x],end='')
print(' ')
#ARRAY...................................
num= array.array('i',[1,2,3,4])
num.append(5)
print(num)
#### this code will not work as we add a different data type to the arry which it is string monkey.
# num= array.array('i',[1,2,3,4])
# num.append('monkey')
# print(num) |
bfa347e6247121c5cd10b86b7769eb368d5ae487 | helgurd/Easy-solve-and-Learn-python- | /open_and_read _string.py | 1,310 | 4.6875 | 5 | #write a program in python to read from file and used more than method.
# read from file --------------------------------------------------------------------
#write a program in python to read from file and used more than method.
# method1
# f=open('str_print.txt','r')
# f.close()
#---------
# method2 called context manager where we use (With and as) and in this method we don't need to write close() method.
with open('str_print.txt', 'r') as f:
f_contents = f.read()
print (f_contents)
#print in format -------------------------------------------------------
# Write a Python program to print the following string in a specific format (see the output). Go to the editor
# Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
# Output :
# Twinkle, twinkle, little star,
# How I wonder what you are!
# Up above the world so high,
# Like a diamond in the sky.
# Twinkle, twinkle, little star,
# How I wonder what you are.add()
f='Twinkle, twinkle,\n little star,\n How I wonder what you are!\n Up above the world so high,\n Like a diamond in the sky.\n Twinkle, twinkle, little star,\n How I wonder what you are'
print (f)
|
110009318a4996746d53867b54bf38c1d7505d90 | helgurd/Easy-solve-and-Learn-python- | /test_ideas/test1.py | 11,330 | 3.6875 | 4 | # forels
# nums= [2,3,4,5, 25]
# for num in nums:
# if num %6 ==0:
# print (num)
# break
# else:
# print("not found!")
##Iterable and Itrator
# Class Itrations
# class MyRange:
# def __init__(self, start, end):
# self.value=start
# self.end= end
# def __iter__(self):
# return self
# def __next__(self):
# if self.value >= self.end:
# raise StopIteration
# current = self.value
# self.value +=1
# return current
# nums = MyRange(-5,3)
# for num in nums:
# print(num)
# Itrating with Generator
# def my_iter(start,end):
# current = start
# while current < end:
# yield current
# current +=1
# nums = my_iter(1, 10)
# for num in nums:
# print(num)
# class Base:
# num=0
# def __init__(self):
# Base.num+=1
# def getnum():
# return(Base.num)
# print(Base.getnum)
# class Apples:
# ApllesInTheBasscet= 0
# def __init__(self, apples):
# self.apples= apples
# Apples.ApllesInTheBasscet += 1
# app1= Apples(1)
# app2= Apples(2)
# app3= Apples(3)
# app4= Apples(4)
# print('Number of the Apples in the Basscet are:', str(Apples.ApllesInTheBasscet))
# class Student:
# number_of_students= 0
# def __init__(self, name, grade):
# self.name= name
# self.grade= grade
# Student.number_of_students += 1
# Student1= Student("John Philips", 10)
# Student2= Student("Michelle Matthews", 9)
# Student3= Student("Michael Robers", 11)
# Student4= Student("Yorshew Tomson", 12)
# Student5= Student("Ryan Matts", 12)
# print("The number of students in the class is " + str(Student.number_of_students))
# user directory
# import os
# home = str(os.path.expanduser('~'))
# print(home)
# a = 7
# b= 2
# z = a//b
# print (z)
# test one variable against multiple values
# x=2
# if x in (1,3,4):
# print ('found')
# else:
# print('try again')
# import subprocess
# #import os
# # subprocess.call(['ls', '-l'])
# #command = ' cmd'
# # os.system(command)
# from subprocess import call
# call(["dir"])
# class Test:
# def __init__(self):
# self.foo=11
# self._bar=23
# self.__baz=42
# t = Test()
# print(dir(t))# we see here the baz is reserved to this class only and attached to the class name hinse not to be interact with other names in other modules or classes
# #output
# # \test_ideas\test1.py"
# # ['_Test__baz', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bar', 'foo']
# while True:
# userin= input('>>')
# if len(userin) ==1:
# break
# print('you should enter one chareactor')
# for i in range(10):
# print(i)
# import pdb
# x=20
# y=100
# if x>y:
# pdb.set_trace()
# print('yesgreater')
# else:
# print ( 'nop')
# any= 'x greater' if x > y else ' y greater'
# print (any)
# n = float(input())
# print (n)
# print (type(n))
# def hello_name(name: str) -> str:
# return(f"Hello {name}")
# print(hello_name('helgurd'))
# def add_this(a: int, b: int) -> int:
# return a+b
# # print(add_this(4, 6))
# # p1 = add_this(5, 6)
# # print(p1.__doc__)
# # print (__doc__)
# # print(help(p1))
#-----------------------------------------------
# import datetime
# curr_Month = datetime.date.today().strftime("%B")
# #Functionas are created for each case
# def Jan ():
# print("January - Starting new Year")
# def Feb ():
# print("February - The Second Month")
# def Mar ():
# print("March - The Third Month")
# def Apr ():
# print("April - The Fourth Month")
# def May ():
# print("May - The Fifth Month")
# def Jun ():
# print("June - The Sixth Month")
# def Jul ():
# print("July - The Seventh Month")
# def Aug ():
# print("August - The Eighth Month")
# def Sep ():
# print("September - The Ninth Month")
# def Oct ():
# print("October - The Tenth Month")
# def Nov ():
# print("November - The Eleventh Month")
# def Dec ():
# print("December - The End of Year")
# #Dictionary containing all possible values
# Month_Dict = {
# "January": Jan,
# "February": Feb,
# "March": Mar,
# "April": Apr,
# "May": May,
# "June": Jun,
# "July": Jul,
# "August": Aug,
# "September": Sep,
# "October": Oct,
# "November": Nov,
# "December": Dec
# }
# #The switch alternative
# Month_Dict.get(curr_Month)()
# import os
# home = str(os.path.expanduser('~user'))
# print (home)
# def switch():
# value1= int(input('ENTER FIRST VALUE'))
# value2= int(input('ENTER SECOND VALUE'))
# print( 'press 1 for add \n press 2 for sub \n press 3 for multi \n press 4 for devision')
# option= int(input('Enter your option'))
# def add():
# result= value1 + value2
# print ( result)
# def sub():
# result= value1 - value2
# print ( result)
# def mul():
# result= value1 * value2
# print ( result)
# def dev():
# result= value1 / value2
# print ( result)
# dect={
# 1:add,
# 2:sub,
# 3:mul,
# 4:dev }
# dect.get(option)()
# print (switch())
# b = 2
# if b in (1,3,2,4,5,6):
# print ( 'yes ')
# else:
# print('none')
# import subprocess
# subprocess.call('')
# def myname():
# print('My name Halgurd')
# if __name__ == "__main__":
# myname()
# def main():
# print('Hello Wolrd')
# print (' Guru')
# import subprocess
# out=subprocess.call('ipconfig')
# print (out)
# print (dir())
# def fun():
# x=4
# print(x)
# num=10
# print (dir())
# def outer():
# x=3
# def inner():
# return(x)
# return inner
# a =outer()
# print (a.__name__)
# def outer(num1):
# def inner_increment(num1): # Hidden from outer code
# return num1 + 5
# num2 = inner_increment(num1)
# print(num1, num2)
# outer(2)
# def function1():
# print('Hi i am function1')
# def function2(held):
# print(' Hi iam function2 now i will call vunction1')
# held()
# function2( function1)
# def str_supper(me):
# def inner():
# inn1 = me()
# return inn1.upper()
# return inner
# def print_str():
# return 'good morning'
# print(print_str())
# d = str_supper(print_str)
# print(d())
# def decoUperchanger(me):
# def inner():
# str1=me()
# return str1.upper()
# return inner
# def messagee():
# return ' hello world'
# a = decoUperchanger(messagee)
# print (a())
####-----------------------------------------------------
# def div_decorator(func):
# def inner(x,y):
# if y==0:
# return ' give proper input'
# return func(x,y)
# return inner
# @div_decorator
# def div(a, b):
# return a/b
# print (div(3,0))
# def plus(fun):
# def inner(x,y):
# if x >y:
# return ( x+y , ' But your first number was ', int(x) )
# else:
# return x+y
# return fun(x,y)
# return inner
# @plus
# def add(a,b):
# return a +b
# print (add(7,5))
# def outer(expr):
# def upper_d(func):
# def inner():
# return func() + expr
# return inner
# return upper_d
# @outer('halgurd')
# def ordinary():
# return'Goode Morrning '
# print (ordinary())
# def main_fun(anyage):
# def deco(fun):
# def inner():
# return fun() + anyage
# return inner
# return main_fun
# @main_fun('Helgurd')
# def morning():
# return ' Good morning '
# print (morning())
# def div_decorator(fun):
# def inner(*any):
# list1= []
# list1 = any[1:]
# for i in list1:
# if i ==0:
# return 'give normal input'
# return fun(*any)
# return inner
# @div_decorator
# def div1(a,b):
# return a/b
# @div_decorator
# def div2(a,b,c):
# return a/b/c
# print(div2(3,6,5))
# print(div1(10,0))
### ------------------------------------
# import functools
# def decorator(func):
# @functools.wraps(func)
# def inner():
# str1=func()
# return str1.upper()
# return inner
# @decorator
# def mytext():
# return 'hello world'
# print (mytext.__name__)
# def check_name(method):
# def inner(name_ref):
# if name_ref.name== 'amulya':
# print('Hey my name is alaso same')
# else:
# method(name_ref)
# return inner
# class Printing:
# def __init__(self, name):
# self.name=name
# def print_name(self):
# print('Entered user name' , self.name)
# p= Printing('amulya')
# p.print_name()
# class A:
# pass
# a=A()
# print('This is the type' ,type(a))
# print('this is the Dir' , dir(a))
# def fun1():
# pass
# fun1()
# print(dir(fun1()))
##Getter and Setter in Python
##We use getters & setters to add validation logic around getting and setting a value.
##To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by the external user.
# class Student:
# def __init__(self, marks):
# self.__marks=marks
# def per(self):
# return (self.__marks/600 *100)
# def setter(self,value):
# self.__marks=value
# def getter(self):
# return self.__marks
# s = Student(555)
# #s.marks= 599
# s.setter(666)
# print(s.getter())
# print(s.per(), '%')
# # #print(s.marks)
# class Game:
# def __init__(self):
# self.wins = 0
# self.losses = 0
# def won_level(self):
# self.wins +=1
# def lost_level(self):
# self.losses +=1
# @property
# def __score(self):
# return self.wins - self.losses
# g = Game()
# g.wins
# # print(g.won_level())
# class Getset:
# def __init__(self):
# self.__number= -1
# @property
# def value(self):
# print('Getting3 value')
# return self.__number
# @value.setter
# def value1(self, value):
# print('setting value')
# self.__number= value
# obj2 = Getset()
# print(obj2.value)
# obj2.value1 = 346
# print(obj2.value)
# class Student:
# def __init__(self,name, age):
# self.name=name
# self.age= age
# def msg(self):
# return(self.name + " " + str(self.age))
# print("object 1:")
# s1 = Student('nia', 24)
# print(s1.name)
# print(s1.age)
# s2 = Student('Ram', 55)
# print(s2.name)
# print(s2.age)
# print(s1.msg())
# print(s2.msg())
#..........................................
print('Functions')
print('........................................................')
print('find Avrage')
def avg(n1,n2,n3):
return(n1+n2+n3)/3.0
print (avg(3.9,3,4))
|
f3951834abe42483c298e731ba41af7bc8324249 | helgurd/Easy-solve-and-Learn-python- | /tempCodeRunnerFile.py | 418 | 3.953125 | 4 | s = input("Input a string")
d=0
l=0
for c in s:
if c.isdigit(): #check whether the character is Digit or not. If true, digits value will be incremented
d=d+1
elif c.isalpha():#check whether the character is alphabet f true, alphabets value will be incremented
l=l+1
else: # if not digit and alpa pass and not returning anything
pass
print("Letters", l)
print("Digits", d)
|
0497b119d6b793597533e3c40e51d05f1f51e451 | veekaybee/dailyprogrammer | /abundant.py | 672 | 3.5625 | 4 | #Reddit Daily Programmer Challenge 243 : Abundant and Deficient Numbers
#https://www.reddit.com/r/dailyprogrammer/comments/3uuhdk/20151130_challenge_243_easy_abundant_and/
#Python 2.7 locally
from __future__ import division
def factors(n):
divisors = []
for i in xrange(1, n+1):
if n % i == 0:
divisors.append(i)
return divisors
def deficient(n):
if sum (factors(n)) < 2*n:
print '%s, deficient' % n
elif sum (factors(n)) > 2*n:
abundant_by = sum(factors(n)) - 2*n
print '%s abundant by %s ' % (n, abundant_by)
else:
print '%s' % n
if __name__ == '__main__':
numbers = [111,112,220,69,134,85]
for i in numbers:
deficient(i)
|
2eae3f58e756b2a3204b1a4a8758b5540a4d2fc6 | elenatsvayberg/sandbox | /hout11_ex4.py | 3,993 | 3.6875 | 4 | class InventoryItem(object):
def __init__(self,title, description, price, store_id):
self.title = title
self.description = description
self.price = price
self.store_id = store_id
def __str__(self):
return self.title
def __eq__(self, other):
if self.store_id == other.title:
return True
else:
return False
def change_description(self, description=""):
if not description:
description = input("Please give me a description: ")
self.description = description
def change_price(self, price= -1):
while price < 0:
price = input("Please give me the new price: (X.XX) :")
try:
price = float(price)
break
except:
print("I\'m sorry but () isn't valid. " .format(price))
self.price = price
def change_title(self, title):
if not title:
title = input("Please giveme a new title: ")
self.title = title
class Book(InventoryItem):
def __init__(self, title, description, price, format, author, store_id):
super(Book, self).__init__(title = title,
description = description,
price = price,
store_id= store_id)
self.format = format
self.author = author
def __str__(self):
book_line = "{title} by {author}" .format(title = self.title, author = self.author)
return book_line
def _eq_(self, other):
if self.title == other.title and self.author == other.author:
return True
else:
return False
def change_format(self, format):
if not format:
format = input("Please give me the new format: ")
self.format = format
def change_author(self, author):
if not author:
author = input("Please give me the new author")
self.author = author
hamlet = Book(title = "Hamlet",\
description = "A Dane has abad time ",
price = 5.59,
format = "paperback",
store_id = "123456789",
author = "William Shakespeare")
hamlet = Book(title = "Hamlet",\
description = "A Dane has abad time ",
price = 10.99,
format = "hardback",
store_id = "987654321",
author = "William Shakespeare")
macbeth = Book(title = "Macbeth",\
description = "Don't listen to starnger ladies on the side of the road ",
price = 4.99,
format = "papperback",
store_id = "9876114321",
author = "William Shakespeare")
#print(hamlet == macbeth)
#print(hamlet)
#hamlet.change_description()
#print(hamlet.description)
class Software(InventoryItem):
def __init__(self, title, description, price, os, rating, store_id):
super(Software, self).__init__(title = title, description = description, price = price, store_id = store_id)
self.os = os
self.rating = rating
def __str__(self):
os_rating = "{os} with {rating}".format(
os = self.os,
rating = self.rating)
return os_rating
def change_os(self, os = ""):
if not os:
os = input("Please give me the new operating System: ")
self.os = os
else:
return False
def change_rating(self, rating = ""):
if not rating:
rating = input("Please enter ERSB rating (E, T, M, and so on : ")
self.rating= rating
else:
return False
python = Software(title = "python",
description = "Nice software",
price = 4.99,
store_id = "123",
os = "IOS",
rating = "A")
print(python)
python.change_os()
print(python.os)
print(python)
python.change_rating()
print(python.rating)
print(python) |
f336514c918accb4cf14a2990353cb9fb341bc80 | elenatsvayberg/sandbox | /hour9_pr.py | 235 | 4 | 4 | students = {}
while True:
name = input("Enter student name otherwise input q: ")
if name =='q':
break
else:
grade = (input("Enter letter grade:")).capitalize()
students[name] = grade
print(students)
|
fe2798b7f063cae4f4e4320d95fb68b26ead1ef1 | elenatsvayberg/sandbox | /hour13.py | 285 | 3.625 | 4 | import this
print(this)
from random import randint
for i in range(10):
print(randint(1, 10))
frequency = {}
for i in range (1000):
num = randint(1, 10)
if num in frequency:
frequency[num] = frequency[num] + 1
else:
frequency[num] = 1
print(frequency)
|
f00bb3fb5cc3f5b5c8f867fb37363c604fcbb525 | xrysa13/Hello-Git | /FizzBuzz.py | 310 | 3.796875 | 4 | def FizzBuzz(n):
for i in range (1, n+1):
if (int(i/3)==(i/3)) and (int(i/5)==(i/5)) :
print ('FizzBuzz')
elif int(i/3)==(i/3):
print ('Fizz')
elif int(i/5)==(i/5):
print ('Buzz')
else:
print (i)
FizzBuzz(50)
|
eec230933cd3a5f53c910851b1672bfbbc630895 | sdenisen/python | /euler-problems/euler-problem-96/unittests_2.py | 1,733 | 3.53125 | 4 | import unittest
from sudoku import Sudoku
__author__ = 'Sergey'
class Test(unittest.TestCase):
def setUp(self):
str_sudoku = """003020600
900305001
001806400
008102900
700000008
006708200
002609500
800203009
005010300"""
int_sudoku = []
for line in str_sudoku.split("\n"):
int_sudoku.append([int(i) for i in list(line.strip())])
self.s = Sudoku(int_sudoku)
def testGetRowCells(self):
print "-------------"
for i in range(9):
result = self.s.get_row_cells(i)
for cell in result:
print cell.value,
print ""
def testGetColCells(self):
print "-------------"
for j in range(9):
result = self.s.get_col_cells(j)
for cell in result:
print cell.value,
print ""
def testGetColCells(self):
print "-------------"
for i in range(0, 9, 3):
for j in range(0, 9, 3):
result = self.s.get_sect_cells(i, j)
for cell in result:
print cell.value,
print ""
def testGetCellPositionInSect(self):
print "-------------"
print "testGetCellPositionInSect"
for i in range(0, 9, 3):
for j in range(0, 9, 3):
for cell_place in range(9):
print "i, j, cell_place --> result: %s, %s, %s, %s" % (i, j, cell_place, self.s.get_cell_position_in_sect(i, j, cell_place))
print "-------------"
|
f8e98dae7cba7a462bdb84c56f8ebf24f70c6e00 | Tan2Pi/tictactoe | /game.py | 2,840 | 3.84375 | 4 | from board import Board
from minimax import *
from copy import deepcopy
from math import inf
class Game:
def computerPlayer(self, player):
move = alphabeta(deepcopy(self.board.board), self.board.depth(), -inf, +inf, player)
self.board.makeMove(Board.conversion[(move['i'],move['j'])])
def humanPlayer(self):
while True:
move = int(input('Player {}, enter your move (9 to quit): '.format(self.board.currentPlayer)))
if move == 9:
print('Quit Successfully!')
self.playing = False
break
elif self.board.validMove(move):
self.board.makeMove(move)
break
else:
print('Invalid move! Please try again.')
def menu(self):
while True:
option = int(input('(1) Human vs. Human\n(2) Human vs. Computer\n(3) Exit\nPick a game option: '))
if option > 3 or option < 1:
print('Invalid input! Please try again.')
else:
if option == 1:
self.board = Board()
self.playing = True
self.multiPlayer()
elif option == 2:
self.board = Board()
self.playing = True
self.singlePlayer()
else:
break
def singlePlayer(self):
while self.playing:
self.board.show()
if self.board.currentPlayer == 'O':
print('Player O is thinking...')
self.computerPlayer()
if self.board.won():
self.board.show()
print('Player {} won!'.format(self.board.currentPlayer))
break
elif self.board.full():
self.board.show()
print('It\'s a tie!')
break
else:
self.board.turn()
else:
self.humanPlayer()
if self.board.won():
print('Player {} won!'.format(self.board.currentPlayer))
break
elif self.board.full():
print('It\'s a tie!')
break
else:
self.board.turn()
def multiPlayer(self):
while self.playing:
self.board.show()
self.humanPlayer()
if self.board.won():
print('Player {} won!'.format(self.board.currentPlayer))
break
elif self.board.full():
print('It\'s a tie!')
break
else:
self.board.turn()
if __name__ == "__main__":
game = Game()
game.menu() |
d745c39b69365e6b78fdc10d11888edd82cb45b6 | PDXDevCampJuly/ChelsDevCamp_July27-1 | /Cheapblackjack.py | 1,932 | 4.09375 | 4 | class Deck:
"""
Class for handling a deck of cards.
"""
def __init__(self, cards_in_deck, num_decks=4):
self.num_decks = num_decks
self.cards_in_deck = []
# self._build_deck()
pass
def deal(self, num_cards=1):
"""
input: num_cards
returns: list of card(s)
"""
pass
def _build_deck(self, cards):
"""
input: calls rand.shuffle on cards
returns: a list of cards
"""
class Card:
"""
Class of cards
"""
def __init__(self, face_value, real_value, suit):
self.face_value = face_value
self.real_value = real_value
self.suit = suit
def cheat(self, face_value):
"""
TODO cheats and changes value.
"""
pass
def face_up(self):
"""
returns True cards is face up
"""
def print_card(self):
"""
pretty prints the card.
"""
pass
class Player:
def __init__(self, hand, name, is_dealer=False):
self.hand = hand
self.name = name
self.is_dealer = is_dealer
def score(self):
"""
keeps track player score
returns total points
"""
pass
def hit_stay(self):
"""
Todo place holder for AI bot
"""
pass
def ace_high_low(self, card):
"""
Sets card to low
imput ace to change
"""
pass
def new_card(self, new_card):
"""
Adds new card to hand
imput new card
return hand
"""
pass
def print_hand(self):
"""
Prints players hand
"""
pass
class Game:
def __init__(self, num_players):
self.num_players = num_players
self.players = []
def winner(self, players):
"""
imput = player
prints the hight score and winning player
"""
pass
def define_players(self, num_players):
"""
imput num_players makes players
returns player list
"""
pass
def start_game(self, num_players):
"""
init deck
"""
pass
def turn(self, player):
"""
promts user for hit or stay
"""
pass
def main(self):
"""
kicks off game
loops through the players and plays game
"""
pass
|
c19c60767e32be95a053a19b4e1f30dfffef86e2 | PDXDevCampJuly/ChelsDevCamp_July27-1 | /angrydice_testable/test_check_stage.py | 4,319 | 3.765625 | 4 | __author__ = 'Chelsea'
import unittest
from angry_dice import Angry_dice
class CheckStageTest(unittest.TestCase):
"""Tests if current stage changes if given different die values"""
def setUp(self):
self.angry_game = Angry_dice()
def tearDown(self):
del self.angry_game
#Both dies are equal and both are in stage one goals
def test_stage_one_both_dice_equal(self):
self.angry_game.die_a.currentValue = '1'
self.angry_game.die_b.currentValue = '1'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 1)
#One is in stage one goals and one is not
def test_stage_one_with_one_and_three(self):
self.angry_game.die_a.currentValue = '1'
self.angry_game.die_b.currentValue = '3'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 1)
#Both are in stage goals and they are not equal
def test_stage_one_with_two_and_one(self):
self.angry_game.die_a.currentValue = '2'
self.angry_game.die_b.currentValue = '1'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 2)
#Both are in stage goals and they are not equal but reverse
def test_stage_one_with_one_and_two(self):
self.angry_game.die_a.currentValue = '1'
self.angry_game.die_b.currentValue = '2'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 2)
#Part two
#Both dies are equal and both are in stage goals
def test_stage_two_both_dice_four_ANGRY(self):
self.angry_game.current_stage = 2
self.angry_game.die_a.currentValue = '4'
self.angry_game.die_b.currentValue = '4'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 2)
#One is in stage goals and one is not
def test_stage_two_with_one_and_three(self):
self.angry_game.current_stage = 2
self.angry_game.die_a.currentValue = '1'
self.angry_game.die_b.currentValue = 'ANGRY'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 2)
#Both are in stage goals and they are not equal
def test_stage_two_with_four_and_one(self):
self.angry_game.current_stage = 2
self.angry_game.die_a.currentValue = '4'
self.angry_game.die_b.currentValue = 'ANGRY'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 3)
#Both are in stage goals and they are not equal but reverse
def test_stage_two_with_one_and_four(self):
self.angry_game.current_stage = 2
self.angry_game.die_a.currentValue = '4'
self.angry_game.die_b.currentValue = 'ANGRY'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 3)
#Part three
#Both dies are equal and both are in stage goals
def test_stage_three_die_six_six(self):
self.angry_game.current_stage = 3
self.angry_game.die_a.currentValue = '6'
self.angry_game.die_b.currentValue = '6'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 3)
#One is in stage goals and one is not
def test_stage_three_with_five_and_one(self):
self.angry_game.current_stage = 3
self.angry_game.die_a.currentValue = '5'
self.angry_game.die_b.currentValue = '1'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 3)
#Both are in stage goals and they are not equal
def test_stage_three_with_five_and_six(self):
self.angry_game.current_stage = 3
self.angry_game.die_a.currentValue = '5'
self.angry_game.die_b.currentValue = '6'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 4)
#Both are in stage goals and they are not equal but reverse
def test_stage_three_with_fix_and_five(self):
self.angry_game.current_stage = 3
self.angry_game.die_a.currentValue = '6'
self.angry_game.die_b.currentValue = '5'
self.angry_game.check_stage()
self.assertEqual(self.angry_game.current_stage, 4)
if __name__ == '__main__':
unittest.main()
|
59568bceca27a4b6af2299750e2aca0374a19d94 | thiagohoh/Compiladores- | /syntatic/arvore.py | 604 | 3.90625 | 4 | # Class responsible for creating a tree
class Arvore:
def __init__(self, type, children=None, leaf=''):
"""
:param type:
:param children: Child
:param leaf: leaf
"""
self.type = type
if children:
self.children = children
else:
self.children = []
self.leaf = leaf
def __str__(self):
return self.type
def print_tree(node: Arvore, level=""):
"""
Func for printing the tree
:param node:
:param level:
:return: no return
"""
if node is not None:
print("%s└── %s %s" % (level, node.type, node.leaf))
for son in node.children:
print_tree(son, level+"│\t")
|
00f17d3bdc290dbea3da6ff3688143f7bd5ca929 | FelixOpolka/Statistical-Learning-Algorithms | /decision tree/DecisionTree.py | 20,040 | 3.59375 | 4 | """A C4.5 Decision Tree learner for classification problems"""
import math
def increment_counter(dictionary, key):
"""Increments the counter for a given key in the given dictionary or
sets the counter to 1 if it does not yet exist."""
if key in dictionary:
dictionary[key] += 1
else:
dictionary[key] = 1
def add_to_list(dictionary, key, value):
"""Adds a given value to a list that is specified by its key in the given
dictionary. If the list does not yet exist, it is created on the fly."""
if key in dictionary:
dictionary[key].append(value)
else:
dictionary[key] = [value]
def partitions_class_attribute(data_points, attr_index):
"""Partitions data points using a given class attribute. Data points
with the same class label are combined into a partition.
:param data_points: List of tuples representing the data points.
:param attr_index: Index of the attribute inside the tuple to be used
for partitioning."""
partitioned_data_points = {}
for point in data_points:
add_to_list(partitioned_data_points, point[attr_index], point)
return partitioned_data_points
def partition_sizes_class_attribute(data_points, attribute_index):
"""Returns the number of items in each partition when partitioning
the given data points using a specified attribute
:param data_points: The data points which ought to be partitioned
:param attribute_index: The class-type attribute to use to distinguish
the partitions
:return: A dictionary which maps the given class-attributes labels to
the number of points with this attribute label"""
inputs_per_class = {}
for point in data_points:
increment_counter(inputs_per_class, point[attribute_index])
return inputs_per_class
def information(data_points):
"""Returns the average amount of information of the given data_points
(also known as entropy).
:param data_points: List of tuples representing the data points.
Last tuple component corresponds to output label.
:return: Average amount of information of data_points"""
inputs_per_class = partition_sizes_class_attribute(data_points, -1)
entropy = 0.0
for count in inputs_per_class.values():
relative_frequency = count / len(data_points)
information = relative_frequency * math.log2(relative_frequency)
entropy += (-information)
return entropy
def information_partitioned(point_count, partitioned_data_points):
"""Returns the average amount of information given the partitioned
data_points.
:param point_count: Total number of data_points.
:param partitioned_data_points: Dictionary of partitions where each
partition contains a list of tuples representing the data points.
Last tuple component corresponds to output label."""
partitioned_entropy = 0.0
for partition in partitioned_data_points.values():
partition_size = len(partition)
entropy = information(partition)
partitioned_entropy += partition_size / point_count * entropy
return partitioned_entropy
def split(sorted_data_points, attr_index, split_value):
"""Splits a list of data points sorted by a given element into two
lists with one list containing tuples <= split_value and one list
containing tuples > split_value.
:param sorted_data_points: List of data points sorted by their values
of the attribute specified by attr_index.
:param attr_index: Index of the attribute of the tuple used to
specify order of tuples.
:param split_value: Value of tuple attribute where list of data points
is split.
:return: List containing two lists of data points as specified above."""
for index, value in enumerate(sorted_data_points):
if value[attr_index] > split_value:
return [sorted_data_points[:index], sorted_data_points[index:]]
return [sorted_data_points, []]
def cont_attr_best_split(data_points, attr_index):
"""Finds the split value for partitioning the data points using
the given attribute such that the information gain is maximized.
Searches the partition with minimum information as its minimum maximizes
information gain (gain = information unpartit. - information partit.).
:param data_points: List of tuples representing the data points.
Last tuple component corresponds to output label.
:param attr_index: Index of the attribute for which the best split
value is requested.
:return: The minimum average information when using the optimal split
value along with the optimal split value."""
data_points.sort(key=lambda tup: tup[attr_index])
left_sublist = []
right_sublist = data_points
unique_attr_values = list(set([i[attr_index] for i in data_points]))
unique_attr_values.sort()
min_info = None
best_value = None
for value in unique_attr_values:
for index in range(len(right_sublist)):
if right_sublist[index][attr_index] > value:
left_sublist.extend(right_sublist[:index])
right_sublist = right_sublist[index:]
break
partitioned_data_points = {"l": left_sublist, "r": right_sublist}
info = information_partitioned(len(data_points), partitioned_data_points)
if min_info is None or info < min_info:
min_info = info
best_value = value
return min_info, best_value
def cont_attr_gain(data_points, attr_index, info):
"""Calculates the information gain when partitioning the data points
with the given continuous attribute.
:param data_points: List of tuples representing the data points.
Last tuple component corresponds to output label.
:param attr_index: Index of the attribute used for partitioning
the data points. Must be continuous attribute type.
:param info: Average information of the unpartitioned data points.
:return: Information gain when partitioning with the specified
attribute along with the best split value for creating the partitioning."""
min_info, best_value = cont_attr_best_split(data_points, attr_index)
return info - min_info, best_value
def class_attr_gain(data_points, attr_index, info):
"""Calculates the information gain when partitioning the data points
with the given class attribute.
:param: data_points: List of tuples representing the data points.
Last tuple component corresponds to output label.
:param attr_index: Index of the attribute used for partitioning
the data points. Must be class attribute type.
:param info: Average information of the unpartitioned data points.
:return: Information gain when partitioning with the specified
attribute."""
partitioned_data_points = partitions_class_attribute(data_points, attr_index)
info_partitioned = information_partitioned(len(data_points), partitioned_data_points)
return info - info_partitioned
def gain(data_points, attr_index):
"""Calculate the information gain when partitioning the data points
using the given attribute.
:param data_points: List of tuples representing the data points.
Last tuple component corresponds to output label.
:param attr_index: Index of the attribute used for partitioning
the data points.
:return: Information gain achieved when partitioning the data points
using the given attribute."""
if len(data_points) == 0:
return 0.0
info = information(data_points)
if type(data_points[0][attr_index]) is int:
return class_attr_gain(data_points, attr_index, info)
else:
return cont_attr_gain(data_points, attr_index, info)[0]
def best_split_attribute(data_points):
"""Determines the attribute which results in the highest information
gain when used for partitioning the data points.
:param data_points: List of tuples representing the data points.
Last tuple component corresponds to output label.
:return: Index of the attribute with highest information gain along
with the gain."""
best_attribute = 0
best_gain = 0.0
for attribute_index in range(len(data_points[0])-1):
curr_gain = gain(data_points, attribute_index)
if curr_gain > best_gain:
best_attribute = attribute_index
best_gain = curr_gain
return best_attribute, best_gain
class ClassificationTree:
"""A C4.5 decision tree for classification problems."""
def __init__(self):
self.root = None
def build(self, data_points, depth_constraint=None, gain_threshold=0.01):
"""Builds/trains the decision tree using the given data points.
:param data_points: List of tuples representing the data points.
Last tuple component must corresponds to output label.
:param depth_constraint: Specifies the maximum depth of the decision
tree. A depth constraint of 0 results in a tree with a single
test (i.e. single inner node). Specifying None means that no depth
constraint is applied.
:param gain_threshold: Minimum information gain a test/ inner node
must achieve to be added to the tree. Otherwise, no further test
is added to the current branch."""
self.root = Node.suitable_node(data_points, 0, depth_constraint, gain_threshold)
def evaluate(self, input):
"""Evaluates the decision tree on the given input. Must only be
called after the tree has been built.
:param input: Input point. Should not contain the last component
which corresponds to the output label.
:return: Output label predicted by the decision tree."""
return self.root.evaluate(input)
def __str__(self):
return self.root.description_string(0)
class Node:
"""A node of the decision tree."""
def __init__(self, attr_index=None):
self.successors = []
self.attr_index = attr_index
@staticmethod
def suitable_node(data_points, depth, depth_constraint, gain_threshold):
"""Constructs a suitable node for the given data points. If a
further test results in sufficient information gain and does not
exceed the depth constraint, an inner node with the corresponding
test (continuous or class attribute) is created. Otherwise, a
Leaf with a suitable output label is created.
:param data_points: List of tuples representing the data points.
Last tuple component must corresponds to output label.
:param depth: Depth of the node to be constructed.
:param depth_constraint: Specifies the maximum depth allowed
for the decision tree.
:param gain_threshold: Minimum information gain a test/ inner node
must achieve to be added to the tree. Otherwise, no further test
is added to the current branch.
:return: Suitable node."""
output_class_sizes = partition_sizes_class_attribute(data_points, -1)
output_classes = len(output_class_sizes)
if output_classes == 1: # Recursion ends
return Leaf(data_points[0][-1])
else: # Recursion continues (with exception)
best_split_attr, gain = best_split_attribute(data_points)
if gain > gain_threshold and (depth_constraint is None or
depth <= depth_constraint):
if type(data_points[0][best_split_attr]) is int:
return ClassNode(data_points, best_split_attr, depth,
depth_constraint, gain_threshold)
else:
return ContNode(data_points, best_split_attr, depth,
depth_constraint, gain_threshold)
else: # Gain too small, Recursion ends
value = max(output_class_sizes.items(),
key=lambda item: item[1])[0]
return Leaf(value)
class ContNode(Node):
"""A node of the decision tree which performs a test on a continuous
attribute."""
def __init__(self, data_points, attr_index, depth, depth_constraint,
gain_threshold):
"""Initializes a node for a continuous attribute test using the
given data points.
:param data_points: List of tuples representing the data points.
Last tuple component must corresponds to output label.
:param attr_index: Index of the attribute used for the test.
Must be a continuous attribute.
:param depth: Depth of the node to be constructed.
:param depth_constraint: Specifies the maximum depth allowed
for the decision tree.
:param gain_threshold: Minimum information gain a test/ inner node
must achieve to be added to the tree. Otherwise, no further test
is added to the current branch."""
Node.__init__(self, attr_index)
self.split_value = cont_attr_best_split(data_points, attr_index)[1]
partitioned_data_points = split(data_points, attr_index,
self.split_value)
self.__create_successors(partitioned_data_points, depth + 1,
depth_constraint, gain_threshold)
def __create_successors(self, partitioned_data_points, depth,
depth_constraint, gain_threshold):
"""Adds suitable successor nodes to the current node.
:param partitioned_data_points: Dictionary of partitions where each
partition contains a list of tuples representing the data points.
:param depth: Depth of the node to be constructed.
:param depth_constraint: Specifies the maximum depth allowed
for the decision tree.
:param gain_threshold: Minimum information gain a test/ inner node
must achieve to be added to the tree. Otherwise, no further test
is added to the current branch."""
for partition in partitioned_data_points:
successor = Node.suitable_node(partition, depth, depth_constraint,
gain_threshold)
self.successors.append(successor)
def evaluate(self, input):
"""Evaluates the subtree rooted in the current node on the given
input by performing the test on the input and passes the input
on to its successors.
:param input: Input point. Should not contain the last component
which corresponds to the output label.
:return: Output label predicted by this subtree."""
if input[self.attr_index] <= self.split_value:
return self.successors[0].evaluate(input)
else:
return self.successors[1].evaluate(input)
def description_string(self, depth):
"""String representation of the subtree rooted in the current node.
:param depth: Depth of the current node.
:return: String representation."""
descr = ""
indent = "\t" * depth
descr += indent + "If x[" + str(self.attr_index) + "] <= " + \
str(self.split_value) + ":\n"
descr += self.successors[0].description_string(depth + 1)
descr += indent + "If x[" + str(self.attr_index) + "] > " + \
str(self.split_value) + ":\n"
descr += self.successors[1].description_string(depth + 1)
return descr
class ClassNode(Node):
"""A node of the decision tree which performs a test on a class
attribute."""
def __init__(self, data_points, attr_index, depth, depth_constraint,
gain_threshold):
"""Initializes a node for a class attribute test using the
given data points.
:param data_points: List of tuples representing the data points.
Last tuple component must corresponds to output label.
:param attr_index: Index of the attribute used for the test. Must
be a class attribute.
:param depth: Depth of the node to be constructed.
:param depth_constraint: Specifies the maximum depth allowed
for the decision tree.
:param gain_threshold: Minimum information gain a test/ inner node
must achieve to be added to the tree. Otherwise, no further test
is added to the current branch."""
Node.__init__(self, attr_index)
partitioned_data_points = partitions_class_attribute(data_points,
attr_index)
self.keys = list(partitioned_data_points.keys())
self.__create_successors(partitioned_data_points, depth + 1,
depth_constraint, gain_threshold)
def __create_successors(self, partitioned_data_points, depth,
depth_constraint, gain_threshold):
"""Adds suitable successor nodes to the current node.
:param partitioned_data_points: Dictionary of partitions where each
partition contains a list of tuples representing the data points.
:param depth: Depth of the node to be constructed.
:param depth_constraint: Specifies the maximum depth allowed
for the decision tree.
:param gain_threshold: Minimum information gain a test/ inner node
must achieve to be added to the tree. Otherwise, no further test
is added to the current branch."""
for key in self.keys:
partition = partitioned_data_points[key]
successor = Node.suitable_node(partition, depth, depth_constraint,
gain_threshold)
self.successors.append(successor)
def evaluate(self, input):
"""Evaluates the subtree rooted in the current node on the given
input by performing the test on the input and passes the input
on to its successors.
:param input: Input point. Should not contain the last component
which corresponds to the output label.
:return: Output label predicted by this subtree."""
succ_index = 0
if input[self.attr_index] in self.keys:
succ_index = self.keys.index(input[self.attr_index])
return self.successors[succ_index].evaluate(input)
def description_string(self, depth):
"""String representation of the subtree rooted in the current node.
:param depth: Depth of the current node.
:return: String representation."""
descr = ""
indent = "\t" * depth
for index, key in enumerate(self.keys):
descr += indent + "If x[" + str(self.attr_index) + "] == " + \
str(key) + ":\n"
descr += self.successors[index].description_string(depth + 1)
return descr
class Leaf(Node):
"""Leaf of the decision tree. Holds a value for the output label which
is returned when an input's evaluation leads to this leaf."""
def __init__(self, value):
Node.__init__(self)
self.value = value
def evaluate(self, input):
"""Evaluates the subtree rooted in the current node on the given
input by performing the test on the input and passes the input
on to its successors.
:param input: Input point. Should not contain the last component
which corresponds to the output label.
:return: Output label predicted by this subtree."""
return self.value
def description_string(self, depth):
"""String representation of the subtree rooted in the current node.
:param depth: Depth of the current node.
:return: String representation."""
return "\t" * depth + str(self.value) + "\n"
if __name__ == '__main__':
tree = ClassificationTree()
data = [(0, 1, 0, 0.25, 0), (0, 1, 1, 0.2, 0), (0, 2, 0, 0.5, 1),
(0, 1, 0, 0.55, 1), (0, 2, 0, 0.52, 1), (0, 1, 1, 0.88, 2),
(1, 1, 0, 0.95, 2)]
tree.build(data)
print(tree)
print(tree.evaluate((0, 1, 1, 0.9)))
|
0f07f871dd65bed0be5f75b169d979ac5cddf761 | niusuyun/python_study_2 | /Lesosn03/1_fib.py | 199 | 3.921875 | 4 | #作业1:编写一个函数,用递归的方法输出斐波那契额数列第n项
def fib(lim,a=1,b=0,lev=1):
if lev == lim:return a+b
return fib(lim,b,a+b,lev+1)
n=10
print(n,fib(n))
|
9a4999999cab00a3913b7faab78be296e284e01d | stephaniecanales/Programacion-ISemestre | /Python/Recursion de pila/main2.py | 205 | 3.53125 | 4 | def suma (x):
if isinstance (x, int) and x >= 1:
return suma_aux(x)
else:
return "error"
def suma_aux (x):
if x == 0:
return 0
else:
return (x + 5 *((x*x)**2)) + suma_aux (x-1) |
4910502d44791ee4bbe6e34b53ef3bd8a3b5a1fe | stephaniecanales/Programacion-ISemestre | /Python/Recursion de cola/scanales_true false.py | 324 | 3.578125 | 4 | def true_false (num):
if isinstance (num, int) and (num >= 0):
return true_false_aux (num)
else:
return "Error"
def true_false_aux (num):
if num == 0:
return True
elif ((num % 10) >= 0) and ((num % 10) <= 4):
return true_false_aux(num // 10)
else:
return False
|
919369682856b3cb8b256ca76180c1cdadc82abf | bradleymailbox/hangman | /Hangman/printmodule.py | 1,129 | 3.859375 | 4 |
# list of messages that can be displayed
msgs = ['### W E L C O M E T O H A N G M A N ###\n'
'-----------------------------------------', #0
'Please enter a letter you wish to guess:', #1
'You have already guessed that letter', #2
'Validating the letter entered', #3
'Number of guesses left:', #4
'Great! You have found a letter of the word!', #5
'Sorry the letter guessed is not part of the word',#6
'Well done! You have guessed the entire word!', #7
'Sorry! You did not guess the word', #8
'The correct word was ', #9
'Please enter single letter of the alphabet.', #10
'An error occurred please restart the program', #11
'Good bye! Thanks for Playing ', #12
'HIDDEN WORD:' #13
]
# display a message from the msgs list
def printmsg(m):
print msgs[m]
# print the number of guesses the user has made
def print_guesses(msgno, val):
print msgs[msgno] + str(val)
|
5bf6484ef615dcfa7bccc4809cf09eb79c3dee75 | Zhangjt9317/SOM_GUI | /code_snippets/listbox.py | 4,249 | 3.890625 | 4 | # load a Tkinter listbox with data lines from a file,
# sort data lines, select a data line, display the data line,
# edit the data line, update listbox with the edited data line
# add/delete a data line, save the updated listbox to a data file
# used a more modern import to give Tkinter items a namespace
# tested with Python24 vegaseat 16nov2006
import tkinter as tk # gives tk namespace
def add_item():
"""
add the text in the Entry widget to the end of the listbox
"""
listbox1.insert(tk.END, enter1.get())
def delete_item():
"""
delete a selected line from the listbox
"""
try:
# get selected line index
index = listbox1.curselection()[0]
listbox1.delete(index)
except IndexError:
pass
def get_list(event):
"""
function to read the listbox selection
and put the result in an entry widget
"""
# get selected line index
index = listbox1.curselection()[0]
# get the line's text
seltext = listbox1.get(index)
# delete previous text in enter1
enter1.delete(0, 50)
# now display the selected text
enter1.insert(0, seltext)
def set_list(event):
"""
insert an edited line from the entry widget
back into the listbox
"""
try:
index = listbox1.curselection()[0]
# delete old listbox line
listbox1.delete(index)
except IndexError:
index = tk.END
# insert edited item back into listbox1 at index
listbox1.insert(index, enter1.get())
def sort_list():
"""
function to sort listbox items case insensitive
"""
temp_list = list(listbox1.get(0, tk.END))
temp_list.sort(key=str.lower)
# delete contents of present listbox
listbox1.delete(0, tk.END)
# load listbox with sorted data
for item in temp_list:
listbox1.insert(tk.END, item)
def save_list():
"""
save the current listbox contents to a file
"""
# get a list of listbox lines
temp_list = list(listbox1.get(0, tk.END))
# add a trailing newline char to each line
temp_list = [chem + '\n' for chem in temp_list]
# give the file a different name
fout = open("chem_data2.txt", "w")
fout.writelines(temp_list)
fout.close()
# create the sample data file
str1 = """ethyl alcohol
ethanol
ethyl hydroxide
hydroxyethane
methyl hydroxymethane
ethoxy hydride
gin
bourbon
rum
schnaps
"""
fout = open("chem_data.txt", "w")
fout.write(str1)
fout.close()
# read the data file into a list
fin = open("chem_data.txt", "r")
chem_list = fin.readlines()
fin.close()
# strip the trailing newline char
chem_list = [chem.rstrip() for chem in chem_list]
root = tk.Tk()
root.title("Listbox Operations")
# create the listbox (note that size is in characters)
listbox1 = tk.Listbox(root, width=50, height=6)
listbox1.grid(row=0, column=0)
# create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=listbox1.yview, orient=tk.VERTICAL)
yscroll.grid(row=0, column=1, sticky=tk.N+tk.S)
listbox1.configure(yscrollcommand=yscroll.set)
# use entry widget to display/edit selection
enter1 = tk.Entry(root, width=50, bg='yellow')
enter1.insert(0, 'Click on an item in the listbox')
enter1.grid(row=1, column=0)
# pressing the return key will update edited line
enter1.bind('<Return>', set_list)
# or double click left mouse button to update line
enter1.bind('<Double-1>', set_list)
# button to sort listbox
button1 = tk.Button(root, text='Sort the listbox ', command=sort_list)
button1.grid(row=2, column=0, sticky=tk.W)
# button to save the listbox's data lines to a file
button2 = tk.Button(root, text='Save lines to file', command=save_list)
button2.grid(row=3, column=0, sticky=tk.W)
# button to add a line to the listbox
button3 = tk.Button(root, text='Add entry text to listbox', command=add_item)
button3.grid(row=2, column=0, sticky=tk.E)
# button to delete a line from listbox
button4 = tk.Button(root, text='Delete selected line ', command=delete_item)
button4.grid(row=3, column=0, sticky=tk.E)
# load the listbox with data
for item in chem_list:
listbox1.insert(tk.END, item)
# left mouse click on a list item to display selection
listbox1.bind('<ButtonRelease-1>', get_list)
root.mainloop() |
d1693ef6fcc1b6ba1fef6099fcd59649e92a69ec | bugagashenki666/test_python_at_the_lessons | /use_if.py | 333 | 3.96875 | 4 | """
bla-bla-bla
"""
# a = int(input())
# if a < -10:
# print("Left")
# elif a > 10:
# print("Right")
# else:
# print("Center")
a = float(input())
b = float(input())
if a > b:
print(str(a) + " greater than " + str(b))
print("something again")
else:
print(str(b) + " greater than " + str(a))
|
889360e9b574c5380347bf7285c3aeb003032936 | psarkozy/HWTester | /MIHF/RouteSearch/solution.py | 4,655 | 3.890625 | 4 | import math
import time
# This class represents a node
class Node:
# Initialize the class
def __init__(self, id, location):
self.id = id
self.location = location
self.neighbours = []
self.parent = None
self.g = 0 # Distance to start node
self.h = 0 # Distance to goal node
self.f = 0 # Total cost
def add_neighbour(self, node):
self.neighbours.append(node)
def set_parent(self,parent):
self.parent = parent
# Compare nodes
def __eq__(self, other):
return self.id == other.id
def __hash__(self):
return self.id
# Sort nodes
def __lt__(self, other):
return self.f < other.f
# Print node
def __repr__(self):
return ('({0})'.format(self.id))
def get_distance(self, other_node):
return math.sqrt(
(self.location[0] - other_node.location[0]) ** 2 + (self.location[1] - other_node.location[1]) ** 2)
# A* search
def astar_search(nodes, start, end):
# Create lists for open nodes and closed nodes
open = []
closed = []
# Create a start node and an goal node
start_node = nodes[start]
goal_node = nodes[end]
# Add the start node
open.append(start_node)
start_node.h = 0
start_node.g = 0
start_node.f = 0
# Loop until the open list is empty
while len(open) > 0:
# Sort the open list to get the node with the lowest cost first
open.sort()
# Get the node with the lowest cost
current_node = open.pop(0)
# Add the current node to the closed list
closed.append(current_node)
# Check if we have reached the goal, return the path
if current_node == goal_node:
path = []
while current_node != start_node:
path.append(current_node)
current_node = current_node.parent
# path.append(start)
# Return reversed path
path.append(current_node)
return path[::-1]
# Unzip the current node position
# Get neighbors
neighbors = current_node.neighbours
# Loop neighbors
for neighbor in neighbors:
if (neighbor in closed):
continue
g = current_node.g + current_node.get_distance(neighbor)
h = neighbor.get_distance(goal_node)
f = h + g
# Check if neighbor is in open list and if it has a lower f value
if add_to_open(open, neighbor, f) == True:
# Everything is green, add neighbor to open list
open.append(neighbor)
neighbor.parent = current_node
neighbor.g = g
neighbor.h = h
neighbor.f = f
# Return None, no path is found
return None
# Check if a neighbor should be added to open list
def add_to_open(open, neighbor, f):
for node in open:
if (neighbor == node and f >= node.f):
return False
return True
def get_path_distance(path):
distance = 0
current_node = path[0]
for node in path[1:]:
distance+= current_node.get_distance(node)
current_node = node
return distance
# The main entry point for this module
def solve(input_file):
start_time = time.time()
fp = open(input_file, 'r')
path_count = int(fp.readline().strip())
node_count = int(fp.readline().strip())
edge_count = int(fp.readline().strip())
fp.readline()
paths_to_search = []
for i in xrange(path_count):
line = fp.readline().strip().split("\t")
paths_to_search.append((int(line[0]), int(line[1])))
fp.readline()
nodes = []
for i in xrange(node_count):
line = fp.readline().strip().split("\t")
nodes.append(Node(i,(int(line[0]), int(line[1]))))
fp.readline()
for i in xrange(edge_count):
line = fp.readline().strip().split("\t")
node_1 = nodes[int(line[0])]
node_2 = nodes[int(line[1])]
node_1.add_neighbour(node_2)
node_2.add_neighbour(node_1)
# Close the file pointer
fp.close()
distances = []
# Find the closest path from start(@) to end($)
for start,end in paths_to_search:
path = astar_search(nodes, start, end)
distance = get_path_distance(path)
distances.append(distance)
print path
print 'Steps to goal: %d, distance:%f' % (len(path), distance)
print("--- %s seconds ---" % (time.time() - start_time))
return distances
# Tell python to run main method
if __name__ == "__main__":
solve("greedy_test.json")
|
a7389c1a3072d7e807073d81d23add6e89d0456d | Drawell/DialogGraphRedactor | /acts_system/character_emotion.py | 196 | 3.5 | 4 | from enum import Enum
class CharacterEmotion(Enum):
NEUTRAL = 0
SAD = 1
ANGRY = 2
HAPPY = 3
FRIGHTENED = 4
SURPRISED = 5
def __str__(self):
return self.name
|
75964cfe90c20dbed87347908b79b899f45b593a | sachi-jain15/python-project-1 | /main.py | 1,206 | 4.1875 | 4 | # MAIN FILE
def output(): #Function to take user's choice
print "\nWhich script you want to run??\n Press 1 for students_to_teacher\n Press 2 for battleship\n Press 3 for exam_stats"
choice=int(raw_input('Your choice: ')) # To take users input of their choice
if (choice==1):
print "\n STUDENTS_TO_TEACHER\n"
import students_to_teacher # It will import the code written in students_to_teacher.py
elif (choice==2):
print "\n BATTLESHIP\n"
import battleship # It will import the code written in battleship.py
elif (choice==3):
print "\n EXAM STATISTICS\n"
import exam_stats # It will import the code written in exam_stats.py
else:
print # To print blank line
print "Invalid choice" # To inform user that he/she has entered a wrong number
output() #Function call to start the program
print "\n If you want to continue to run any script once again type yes" # To ask user one more time whether he want to run the code again or not
user_input=raw_input().lower() # This statement will take the input in lower case
if(user_input=='yes' or user_input=='y'):
output() #Function Call
print "\n END"
|
9df2e9950b56a4680da5b5c54bfbc2b94dcbe51f | kjk402/PythonWork | /programmers/7.py | 271 | 3.8125 | 4 | def solution(numbers, hand):
answer = ''
for i in numbers:
if i == 1 or i==4 or i==7:
answer += 'L'
elif i == 3 or i==6 or i ==9:
answer +='R'
return answer
num = [1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5]
print(solution(num)) |
dc3ada013dea708c0e056a4178615fb425fcf83a | kjk402/PythonWork | /leetCode/easy/PalindromeNumber.py | 662 | 3.765625 | 4 | # Palindrome Number
# https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x: int) -> bool:
number = str(x)
length = len(number)
is_even = False
if x < 0:
return False
if length == 0:
return False
if length % 2 == 0:
return False
middle = length // 2
last_index = length -1
for i in range(middle, length):
if not is_even:
is_even = True
continue
opp = last_index - i
if number[opp] != number[i]:
return False
return True |
0d6f051635628848a510784ac928422460f7bfb3 | kjk402/PythonWork | /codeup100/codeup_28~46.py | 1,340 | 3.71875 | 4 | # #28
# var = int(input())
# print(var)
#
# #29
# integer = float(input())
# print(round(integer, 11))
#30
# var = int(input())
# print(var)
# #31
# octal = int(input())
# print(oct(octal)[2:]) #8진수 함수 스면 뒤 두자리만 출력
# 32,33
# hexa = int(input())
# print((hex(hexa)[2:]).upper())
# # 34 8진수 10진수
# octal = '0o' +input()
# print(int(octal, 8))
# # 35 16진수-> 8진수
# hexa = '0x' +input()
# integer = int(hexa, 16)
# print(oct(integer)[2:])
# #36
# askii = ord(input())
# print(askii)
# #37 10진수 -> 아스키
# var = chr(int(input()))
# print(var)
#
#38
# a, b = map(int, input().split(' '))
# print(a+b)
# #40 부호바꿔서출력
# a = int(input())
# if a <= 0:
# print(abs(a))
# else:
# print(-a)
# #41 입력받은 알파벳 또는 숫자 다음 문자 출력 A -> B
# order = ord(input())
# print(chr(order+1))
#42 몫 구하기
# a, b = map(int, input().split(' '))
#print(a//b)
# #43 나머지 구하기
# a, b = map(int, input().split(' '))
# print(a%b)
# 44 정수 +1 구하기
# var = int(input())
# print(var+1)
#
# 45
# a, b = map(int, input().split(' '))
# print(a+b)
# print(a-b)
# print(a*b)
# print(a//b)
# print(a%b)
# print(round(a/b, 2))
# 46
# a, b, c = map(int, input().split(' '))
# print(a+b+c)
# print(round((a+b+c)/3, 1))
|
e0beda07eaee8330ca4e94dfaa8d39785f1f41ae | kjk402/PythonWork | /leetCode/easy/RomanToInteger.py | 500 | 3.6875 | 4 | # Roman to Integer
# https://leetcode.com/problems/roman-to-integer/
class Solution:
def romanToInt(self, s: str) -> int:
dic = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1}
result = 0
for i in range(len(s) - 1):
num = dic[s[i]]
nextNum = dic[s[i + 1]]
if (num >= nextNum):
result += num
else:
result -= num
result += dic[s[len(s) - 1]]
return (result)
|
eb6a972179c098e29ddbfc9c5f53bc518ff21960 | kjk402/PythonWork | /pythonrogic/sentence.py | 489 | 3.59375 | 4 | #문자열
from random import *
sentence = '나는 바보입니다.'
print(sentence)
sentence3 = """
이렇게 출력하면
줄바꿈도 출력가능
"""
print(sentence3)
python = "Python is Amazing"
print(python)
print(python.lower())
print(python.upper())
print(python[0].isupper())
print(python.replace("is", "are"))
print(python)
index1 = python.index("i")
print(index1)
index2 = python.index("i", index1 + 1)
print(index1, index2)
print(python.find("i"))
print(python.count("i")) |
2056443ceb165c88e23cfe66b0ca1aae7292965f | kjk402/PythonWork | /pythonrogic/5quiz4.py | 414 | 3.5625 | 4 |
from random import *
# lst = [1,2,3,4,5]
# print(lst)
# shuffle(lst)
# print(lst)
lst = range(1,21) #1부터 20까지 숫자 생성
print(type(lst))
lst = list(lst)
print(type(lst))
print(lst)
shuffle(lst)
print(lst)
winners = sample(lst, 4) #4명 뽑고
print("==당첨자==")
print("치킨 당첨자 : {0}".format(winners[0]))
print("커피 당첨자 : {0}".format(winners[1:]))
print("==축하합니다==")
|
f106f22e459c9f0ed31faf7d16efd1006adc4e53 | kjk402/PythonWork | /programmers/level1/7.py | 436 | 3.515625 | 4 | # 7번 2016년
def solution(a, b):
answer = ["THU", "FRI", "SAT", "SUN", "MON", "TUE", "WED"]
month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = sum(month[:a - 1]) + b if a > 1 else b
return answer[day % 7]
import datetime
def getDayName(a,b):
t = 'MON TUE WED THU FRI SAT SUN'.split()
return t[datetime.datetime(2016, a, b).weekday()]
a = 5
b = 24
print(solution(a, b))
print(getDayName(a, b)) |
cb82d87fb4935da995f022f73c44b9b1b46947e7 | kjk402/PythonWork | /programmers/level1/24.py | 364 | 3.609375 | 4 | # 로또의 최고 순위와 최저 순위
# https://programmers.co.kr/learn/courses/30/lessons/77484
def solution(lottos, win_nums):
answer = [0, 0]
count = 0
rank = [6, 6, 5, 4, 3, 2, 1]
for i in lottos:
if i in win_nums:
count +=1
answer[0] = rank[count + lottos.count(0)]
answer[1] = rank[count]
return answer
|
099e12e55711c7ae9b88239219a6c1626a2e06e5 | kjk402/PythonWork | /programmers/level1/11.py | 304 | 3.625 | 4 | # 11번 나누어떨어지는 숫자 배열
def solution(arr, divisor):
answer = []
for x in arr:
if x%divisor ==0:
answer.append(x)
answer.sort()
if len(answer) ==0:
answer.append(-1)
return answer
arr= [5,9,7,10]
divi =5
print(solution(arr,divi)) |
716da44f088937e4759bc8c0a7e2f3af60190b5b | kjk402/PythonWork | /programmers/level1/25.py | 518 | 3.625 | 4 | # 숫자 문자열과 영단어
# https://programmers.co.kr/learn/courses/30/lessons/81301
def solution(s):
answer = ''
dic = {'zero': '0', 'one': '1', 'two': '2', 'three': '3',
'four': '4', "five": "5", "six": "6", "seven": "7",
"eight": "8", "nine": "9"}
tmp = ''
for a in s:
if a.isdigit():
answer += a
else:
tmp += a
if tmp in dic.keys():
answer += dic[tmp]
tmp = ''
return int(answer)
|
7deaa37b29bcf3288701d1bb8b5792b808a8c6db | kjk402/PythonWork | /programmers/level1/18.py | 190 | 3.53125 | 4 | # 18 소수찾기
def solution(n):
answer =[]
for i in range(2, n+1):
for j in range(2,i):
if i %j !=0:
answer.append(i)
return len(answer) |
a634ebbf7dfe6a69968c2e7e0423a95cdeaff9fe | kjk402/PythonWork | /pythonrogic/oprator.py | 501 | 3.890625 | 4 | print(1+1)
print(2**3)
print(3**4)
print(5%3)
print(10//3)
# == 같은지 비교
age =3
print( 3 == age )
print(not(1!= age))
print((3>0) and (3>5))
print((3>0) & (3>5))
print((3>0) or (3>5))
print((3>5) | (3>5))
number = 2
number+=2
print(number)
number/=2
print(number)
print(abs(-5)) #절댓값
print(pow(5,3)) #5를 세제곱
print(max(5,12)) #큰값 선택
print(round(3.76))
from math import *
print(floor(4.99))
from random import *
print(int(random()*10))
print(randrange(1,46))
|
e05f2c66c41337248faa49ee5f336f2e8dbcdb7d | kjk402/PythonWork | /programmers/level1/10.py | 297 | 3.59375 | 4 | #10 같은 숫자는 싫어
"""
"""
def solution(arr):
answer = []
if len(arr) ==1:
return arr
answer.append(arr[0])
for i in range(1, len(arr)):
if arr[i] != arr[i-1]:
answer.append(arr[i])
return answer
arr =[4,4,4,3,3]
print(solution(arr)) |
dfc6af52e6e4a5b06a42bdeb592a9e2ff627feed | kjk402/PythonWork | /pythonrogic/practice.py | 425 | 3.546875 | 4 | import random
doc = { "names" : ["준기","승기","길동", "알고", "메튜"]}
with open("info.txt", "w" ) as file :
for i in range(5):
name = random.choice(doc["names"])
weight = random.randrange(40, 100)
height = random.randrange(150, 190)
file.write("{}, {}, {}\n".format(name, weight, height))
# with open("info.txt", "r") as file:
# contents = file.read()
# print(contents) |
634c0129a79fd2449e0a0d515ed6fbb7edb7ee54 | chriskirkpatrick/hello-world | /scratch.py | 160 | 3.984375 | 4 | #!/usr/bin/python
squares = [v ** 3 for v in range(1,3)]
#for v in range(1,25):
# square = v ** 3
# squares.append(square)
#print(squares)
print(squares)
|
1d981238086ff220a2b80856dd013d6c1deabfc0 | chriskirkpatrick/hello-world | /6-7_people.py | 575 | 4.09375 | 4 | #!/usr/bin/python
people = {
'x' : {
'first_name': 'x',
'last_name': 'x',
'age': 'x',
'city': 'x',
},
'x' : {
'first_name': 'x',
'last_name': 'x',
'age': 'x',
'city': 'x',
},
'will' : {
'first_name': 'William',
'last_name': 'Nylander',
'age': '20',
'city': 'Toronto',
},
}
for people, info in people.items():
first_name = info['first_name']
last_name = info['last_name']
age = info['age']
city = info['city']
print("\nFirst name: " + first_name + "\nLast name: " + last_name + "\nAge: " + age + "\nCity: " + city)
|
c78062c13a9017b487ceb39ef66291d43c2718ef | Quetzalcoaltl/Cobra_2 | /neu_net_1.py | 1,575 | 4 | 4 | """video aula sobre criação de redes neurais
link: https://www.youtube.com/watch?v=kft1AJ9WVDk&t=502s
a filosofia eh a seguinte:
1- criamos um vetor com msm numero de pesos das entradas, por exmplo se as entradas necessitam 6 digitps, ciramos um vetor aleatorio com 6 digitos, não importa quantos exemplos diferentes de entradas
2 - multiplicamos o peso aleatoio com os valores das entradas e jogamos o peso na sigmoide para descobrir o output
3 - calculamos o erro, subtraindo o valor gerado no output da sigmoide comm a saida conhecida
"""
import numpy as np
#import math
from numpy import exp, array, random, dot
treino_entrada = array([[0,0,1], [1,1,1], [1,0,1], [0,1,1]])
saida_treino = array([[0,1,1,0]]).T
random.seed(1)#aqui ele usa a random seed para que tenhamos valores esecificos ṕara os primeiros testes, isso para termos um desenvolvimento em ambiente controlado
peso_sinapse = (2*np.random.random((3,2))-1) #maneira de se criar um vetor com valores aleatorios de zero a um
def sigmoid(x):
return 1/(1+exp(-x))
def derivada_sigmoid(x):
return x*(1-x)
print("Peso aleatorio das sinapses: ")
print(peso_sinapse)
for iteracao in range(5000):
camada_entrada = treino_entrada
saida=sigmoid(np.dot(camada_entrada , peso_sinapse))#multiplica a linha de cada entrada vezes o peso e ja joga na sigmoid, para ver o resultado
erro = saida_treino -saida
ajuste = erro*derivada_sigmoid(saida)
peso_sinapse += np.dot(camada_entrada.T,ajuste)
print ("saida das sinapses pos treino: ")
print(peso_sinapse)
print ("saida pos treino: ")
print(saida)
|
25246d0e0e2cb0ed366a2e778d1b3385fb1bd2db | Quetzalcoaltl/Cobra_2 | /OOP_P3.py | 2,735 | 4.53125 | 5 | """
aula 2 de orientação ao objeto,
Professor Corey Schafer
Tema Aula: Python OOP Tutorial 2: Class Variables
https://www.youtube.com/watch?v=BJ-VvGyQxho
"""
class Empregado:
aumento_salario= 1.04
numero_empregado=0
def __init__(self, primeiro_nome, ultimo_nome, pagamento):
self.primeiro_nome= primeiro_nome
self.ultimo_nome= ultimo_nome
self.pagamento=pagamento
self.email=primeiro_nome+'.'+ultimo_nome+"@empresa.com"
Empregado.numero_empregado +=1 #essa conta foi adicionada aqui porque toda vez que um objeto
# "funcionario" for criado __init_ roda, então podemos manter o controle de quantos foram
# criados
def NomeCompleto(self):
return ("{} {} ".format(self.primeiro_nome, self.ultimo_nome))
#operar um aumento na classe
def AplicaAumento(self):
#self.pagamento=int( self.pagamento*Empregado.aumento_salario)
self.pagamento=int(self.pagamento*self.aumento_salario)
"""operar dentro da classe com self é util quando a informaçãoa ser manipulada é importante ao objeto,
self.variavel_intancia
apesar disso, quando precisamos de uma variavel de controle para a classe, por exemplo ṕara contar quantas
vezes a classe foi chamada, então utilizamos a nomeclatura:
classe.variavel_instancia
"""
emp_1=Empregado("Jonas", "Souza", 10000)
emp_2=Empregado("Marcel", "Schunteberg", 12000)
#print("\n",emp_1.__dict__,"\n")
#notação para exibir detalhes intrisecos ao objeto, é importante notar que a variavel aumento salario
# não é exibida, isso porque ela é relativa a classe Empregado, não ao objeto, entretanto, caso eu realize
# uma alteração nessa variavel, aumenta salario essa ira ser mostrada quando esse comando acima for executado
# isso porque a auteração foi relativa ao objeto, a variavel da classe Empregado continua a msm,
#
"""
print("\n o email de ", emp_1.primeiro_nome,"eh", emp_1.email)
print("\n o email de ", emp_2.primeiro_nome,"eh", emp_2.email)
print("\n", Empregado.NomeCompleto(emp_1))
print("\n", emp_1.NomeCompleto() )
"""
print("\n", emp_1.pagamento)
emp_1.AplicaAumento()
print("\n", emp_1.pagamento)
"""pergunta=input("voce quer alterar o aumento? (sim/não):")
if pergunta == "sim":
#funcionario=input("qual funcionario (sim/não):")
inovo=float(input("qual o aumento :" ))
emp_1.pagamento=emp_1.pagamento/emp_1.aumento_salario
emp_1.aumento_salario=inovo
emp_1.AplicaAumento()
print("\n", emp_1.pagamento)
"""
print("\n foram cadastrado(s):", Empregado.numero_empregado, " funcionario(s)")
'''
print(emp_1.numero_empregado)
print(emp_2.numero_empregado)''' |
b73271d0733f80bee1751919642d73408ddc03a7 | Quetzalcoaltl/Cobra_2 | /teste6.py | 5,515 | 4.1875 | 4 | #criando meu primeiro jogo em python 2
#cirando uma tela
# usando turtle mod
#/usr/bin/python
#!coding=utf-8
import turtle
import os
import math
#criar tela
wn = turtle.Screen() #cria a tela e chama de wn
#wn.screensize(700,700)
wn.bgcolor("black") # definindo cor do backgroun
wn.title("space invaders") #titulo
#desenhar as fronteiras do meu role
cane_front= turtle.Turtle()
cane_front.speed(0) #velocidade desenho da linha dos limites
cane_front.color("white")
cane_front.penup() #por default a caneta inicia no meio da tela, isso serve para desencostar a caneta da tela
cane_front.setposition(-270,-270)
cane_front.pendown()
cane_front.pensize(3) #tamanho tela
for size in range(4):
cane_front.fd(540)
cane_front.lt(90)
cane_front.hideturtle
#criando o jogador
jog1= turtle.Turtle()
jog1.speed(0) #velocidade desenho da linha dos limites
jog1.color("blue")
jog1.penup() #por default a caneta inicia no meio da tela, isso
jog1.shape("triangle")
jog1.setposition(0,-250)
#jog1.lt(90) gira o objeto 90 graus, todavia
jog1.setheading(90) #orientacao inicial do personagem
#movimentacao do personagem
vel_jog1=10
'''
def move_esquerda():
xis = jog1.xcor() #okay, aqui pegamos a componente xcor de jog1 e atribuo o valor atual a x
#x = x - vel_jog1 #atribuo menos a velocidade do jogador para a posicao e o novo valor eh atribuido a x, modo arcaico de se fazer// funcao objeto.xcor retorna a posicao em x do objeto
#xis -= vel_jog1 #subtraio vel_jog1 de x
if xis <= -240: jog1.setx(-240)
else: jog1.setx(xis-vel_jog1) # funcao posiciona o objeto(jog1) no eixo x na posicao xis
def move_direita(): #movimentar objeti para a direita
xis = jog1.xcor()
xis += vel_jog1
if xis >= 240: jog1.setx(240)
else: jog1.setx(xis)
#movimentacao vertical
def move_frente(): #movimentar objeti para a direita
yis = jog1.ycor()
yis += vel_jog1
if yis >= 240: jog1.sety(240)
else: jog1.sety(yis)
def move_tras(): #movimentar objeti para a direita
yis = jog1.ycor()
yis -= vel_jog1
if yis <= -240: jog1.sety(-240)
else: jog1.sety(yis)
'''
#criando inimigo:
inimigo= turtle.Turtle()
inimigo.speed(0) #velocidade desenho da linha dos limites
inimigo.color("red")
inimigo.penup() #por default a caneta inicia no meio da tela, isso
inimigo.shape("circle")
inimigo.setposition(-200,250)
vel_inimigo= 2
#### criar varios inimigos, primeiro selecionar o numero de inimigos
num_inimigos = 5
### criar uma lista vazia de inimigos
#criar municao do jogador
bala= turtle.Turtle()
bala.speed(0) #velocidade desenho da linha dos limites
bala.color("yellow")
bala.penup() #por default a caneta inicia no meio da tela, isso
bala.shape("triangle")
bala.setheading(90)
bala.shapesize(.2,.9) #nova funcao, diminui pela metade as caracteristicas do objeto
#bala.setposition(-200,250)
bala.hideturtle()
vel_bala=20
#Definicao do estado da bala(pronta ou disparando)
estado_bala="pronto"
#movimentacao da bala
''' movimentacao do projetil, autoral, problemas
def move_bala():
bala.showturtle();
bala.setposition(jog1.xcor(),jog1.ycor())
while bala.ycor()<250:
bala.sety(bala.ycor()+vel_bala)
bala.hideturtle()
'''
def move_bala():
global estado_bala #definindo como global, para que se altere o valor dentro e fora da funcao
if estado_bala == "pronto":
estado_bala="disparando"
bala.setposition(jog1.xcor(),jog1.ycor()+10)
bala.showturtle()
#ffuncao para conferir distnacia entre inimigo e bala
def ehcolisao(t1,t2):
if ((t1.ycor()-t2.ycor())**2 + (t1.xcor()-t2.xcor())**2)**0.5 <15:
return True
else:
return False
#movimentacao esquerda e direita
def move_esquerda():
if jog1.xcor() > -250: jog1.setx(jog1.xcor()-vel_jog1) # esquerda
def move_direita():
if jog1.xcor() < 250: jog1.setx(jog1.xcor()+vel_jog1) # direita
#movimentacao vertical
def move_frente():
if jog1.ycor() < 250: jog1.sety(jog1.ycor()+vel_jog1) # frente
def move_tras():
if jog1.ycor() > -250: jog1.sety(jog1.ycor()-vel_jog1) # tras
#criando as ligacoes entre as teclas e objetos
turtle.listen()
turtle.onkey(move_esquerda, "Left")
turtle.onkey(move_direita, "Right")
turtle.onkey(move_frente, "Up")
turtle.onkey(move_tras, "Down")
turtle.onkey(move_bala, "a")
#main game loop
while True:
#move inimigo
inimigo.setx(inimigo.xcor()+vel_inimigo)
if inimigo.xcor() > 250 :
vel_inimigo *= -1
inimigo.sety(inimigo.ycor()-20)
if inimigo.xcor() < -250:
vel_inimigo *= -1
inimigo.sety(inimigo.ycor()-20)
########### moviemntacao bala
if estado_bala == "disparando" :
bala.sety(bala.ycor()+vel_bala) #movimentacao bala,
if bala.ycor() > 250 :
estado_bala = "pronto"
bala.hideturtle() #esconder bala, apos a movimentacao
########### reacao projetil e objeto
if ehcolisao(bala, inimigo) == True:
bala.hideturtle()
estado_bala = "pronto"
bala.setposition(0,-400)
inimigo.setposition(-200,250)
########## colisao entre jogador e inimigo
if ehcolisao(jog1, inimigo) == True:
print ("Game over!!!")
exit
''' solucao autoral para movimentaxao e choque entre projetil e inimigo
disBalIni_tot=((inimigo.ycor()-bala.ycor())**2 + (inimigo.xcor()-bala.xcor())**2)**0.5
if disBalIni_tot <15: inimigo.hideturtle()
----------------------------------------------------------------
if bala.ycor() < 250 :
bala.sety(bala.ycor()+vel_bala) #movimentacao bala,
estado_bala="disparando"
if bala.ycor() >= 250 :
estado_bala= "pronto"
bala.hideturtle() #esconder bala, apos a movimentacao
'''
delay =input("press enter")
|
441c5fbd97781cc617059c8a86e5a531c1f2dc16 | PavanRaga/Exercism_python | /kindergarten-garden/kindergarten_garden.py | 1,080 | 3.78125 | 4 | given_students = [
"Alice",
"Bob",
"Charlie",
"David",
"Eve",
"Fred",
"Ginny",
"Harriet",
"Ileana",
"Joseph",
"Kincaid",
"Larry"]
class Garden(object):
def __init__(self, diagram, students=given_students):
diagram = diagram.splitlines()
self.row1 = diagram[0]
self.row2 = diagram[1]
self.students = sorted(students)
@staticmethod
def _mapping_(plant_char):
if plant_char == 'G':
return "Grass"
elif plant_char == 'C':
return "Clover"
elif plant_char == 'R':
return "Radishes"
elif plant_char == 'V':
return "Violets"
else:
return ""
def plants(self, student):
try:
index = self.students.index(student)
except ValueError:
print("student not enrolled")
#as each child gets 2 cups
index *= 2
new = self.row1[index] + self.row1[index+1] + self.row2[index] + self.row2[index+1]
return list(map(self._mapping_,new)) |
ce994466bee4c527a4ccde92dc89072694303ea1 | shibarak/lotterypicks | /main.py | 3,318 | 3.546875 | 4 | import requests
from bs4 import BeautifulSoup
import pandas as pd
from draftdict import clean_draft_dict # cleaned up the data from wikipedia so all player names
# match names on Basketball Reference.
# -------------- Code for scraping draft data from Wikipedia, making the draft dict -----------------#
# for i in range(1966, 2016):
#
# response = requests.get(f"https://en.wikipedia.org/wiki/{i}_NBA_draft")
# sp = BeautifulSoup(response.text, "html.parser")
# draft_table = sp.find(class_="sortable")
# players = draft_table.find_all("tr")
# for p in range(1, 15):
# pick_no = int(players[p].find_all("td")[1].text.split("\n")[0])
# name = players[p].find("a").text
# draft_dict[name] = {"pick_no": pick_no}
#-----------Adding keys to player's dictionaries -------------#
# draft_year = 1966
# count = 0
# for key in draft_dict:
# if count == 14:
# draft_year += 1
# count = 0
# draft_dict[key]["year drafted"] = draft_year
# count += 1
# draft_dict[key]["career_ws"] = 0.0
# draft_dict[key]["years played"] = 0
# draft_dict[key]["avg_ws"] = 0
# print(draft_dict)
#-------------------Code for getting win-shares from basketball reference----------------------#
for i in range(1967, 2021):
print(f"started {i}")
ws_dict = {}
response = requests.get(f"https://www.basketball-reference.com/leagues/NBA_{i}_advanced.html#advanced_stats")
sp = BeautifulSoup(response.text, "html.parser")
table = sp.find(id="advanced_stats")
rows = table.find_all(class_="full_table")
for row in rows:
try:
name = row.find("a").text
ws = float(row.find(attrs={"data-stat": "ws"}).text)
ws_dict[name] = ws
except AttributeError:
pass
for key in ws_dict:
if key in clean_draft_dict:
clean_draft_dict[key]["career_ws"] += ws_dict[key]
clean_draft_dict[key]["years played"] += 1
clean_draft_dict[key]["avg_ws"] = clean_draft_dict[key]["career_ws"] / clean_draft_dict[key]["years played"]
# --------------- Rounding the win shares -----------------#
for key in clean_draft_dict:
clean_draft_dict[key]["avg_ws"] = round(clean_draft_dict[key]["avg_ws"], 2)
clean_draft_dict[key]["career_ws"] = round(clean_draft_dict[key]["career_ws"], 2)
# Mike Dunleavy Sr. also played in the NBA in the 70's (not a top 14 pick)
# On Basketball Reference Jr. and Sr. are both just Mike Dunleavy so Jr. gets his stats added manually.
clean_draft_dict["Mike Dunleavy Jr."] = {'pick_no': 3, 'year drafted': 2002, 'career_ws': 58.50, 'years played': 15, 'avg_ws': 3.90}
# --------------- Creating a data frame and csv ------------#
draft_frame = pd.DataFrame.from_dict(clean_draft_dict, orient="index")
with open("draft.csv", mode="w") as file:
data = draft_frame.to_csv()
file.write(data)
print(draft_frame.head())
# check for players with no data added. Used to find name differences between wikipedia and basketball reference
# and make clean dictionary. Since we're using clean_draft_dict it currently it prints players who never played in the NBA.
# RIP Len Bias.
print(clean_draft_dict)
for key in clean_draft_dict:
if clean_draft_dict[key]["years played"] == 0:
print(key)
|
5b7a8b24ec0006ebf93cd86a56cea5eb0928151e | rafaelmgr12/UNIVESP-AlgeProg2 | /code/main.py | 3,052 | 3.84375 | 4 |
#############################################################################################################
# Esse código foi feito Por Rafael Ribeiro, Facilitador da disciplina Algoritmos e Programação de
# Computadores II
#
#
# Aqui terá esritas funções que, serão usadas durante os exercícios durante a semana.
#
# Os exercícios são tirados do livro : Introduçao a Computacão com Python PERKOVIC, Ljubomir
#############################################################################################################
#Exercicios de 3.15
##############################################################################################################
##############################################################################################################
import turtle
import turtlefunctions
def olimpíadas(t):
'faz tartaruga t desenhar os anéis olímpicos'
t.pensize(3)
turtlefunctions.jump(t, 0, 0) # fundo do círculo superior central
t.setheading(0)
t.circle(100) # círculo superior central
turtlefunctions.jump(t, -220, 0)
t.circle(100) # círculo superior esquerdo
turtlefunctions.jump(t, 220, 0)
t.circle(100) # círculo superior direito
turtlefunctions.jump(t, 110, -100)
t.circle(100) # círculo inferior direito
turtlefunctions.jump(t, -110, -100)
t.circle(100) # círculo inferior esquerdo
s = turtle.Screen()
t = turtle.Turtle()
olimpíadas(t)
#########################################################################################################################
# Exercício do cap 8 do livro
####################################################################################################################################################
#####################################################################################################################################
# Aqui, vamos implementar as classe criadas no arquivo functions
#####################################################################################################################################
from functions import Point
a = Point()
a.setx(10)
a.sety(15)
print('As Coordenadas no plano é\n:',a.get())
print("\nCoordenada em x é",a.getx())
'''
from functions import Retangulo
print("\nAgora vamos fazer uma definição do Retângulo\n")
a = eval(input('Digite a altura\n'))
l = eval(input("\nDigite a largura"))
r = Retangulo(a,l)
print("\nÁrea do Retangulo é ",r.area(),"\n O perimetro é ",r.perimetro())
from functions import funcionario,gerente
f = funcionario('Rafael',900,'25/05/2019')
g = gerente('João',1000,'01/05/2019')
print("\nFuncionario:\n")
print('Nome:',g.getNome(),'\nSalário:',g.getSal(),'\nData de admissão:',g.getData(),'\nBonus:',g.getBonus())
'''
print("\nIniciando a classe baralho:")
from functions import Baralho
baralho = Baralho(['1', '2', '3', '4'])
#baralho = Baralho()
baralho.shuffle()
print(baralho.distribuiCarta())
print(len(Baralho()),'\n')
print(baralho.distribuiCarta())
print("\n",baralho.distribuiCarta())
import functions as f
f.drawSnowflake(4) |
8ee31252af6fde4115d0e1d8b2619b90c8b0ed9a | luoxuesnowy91/ANLY560 | /Assignment 3.py | 2,358 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 13 20:08:15 2018
@author: luoxue
"""
### ASSIGNMENT 3
# import codes to plot histogram
import sys
sys.path.append("/Users/luoxue/Desktop/HU/ANLY 545 Analytical Methods II/ThinkStats2-master/code/")
import thinkstats2
import thinkplot
import matplotlib.pyplot as plt
import numpy as np
# open file
F = open("/Users/luoxue/Desktop/HU/ANLY 545 Analytical Methods II/Assignments/Assignment 3/student-mat.csv", "r")
# set up new list
Mothereducation = list()
absences = list()
familyrelationships= list()
finalmathgrade=list()
# read data by column
list2 = [1, 2, 3, 4, 5 ]
print(list)
for line in F:
spLine = line.split(",")
Mothereducation.append(spLine[6])# read the 7th column "Mother's education"
absences.append(spLine[29])# read the 30th column "absences"
familyrelationships.append(spLine[23])# read the 24th column "famrel"
finalmathgrade.append(spLine[32])# read the 33rd column "G3"
# excluding 1st item (column title)
Mothereducation = Mothereducation[1:len(Mothereducation)] # len() means count total items
Mothereducation=map(int,Mothereducation)
absences= absences[1:len(absences)]
absences=map(int,absences) # convert a list of strings to lisdt of integers
familyrelationships= familyrelationships[1:len(familyrelationships)]
familyrelationships=map(int,familyrelationships) # convert a list of strings to lisdt of integers
finalmathgrade = finalmathgrade[1:len(finalmathgrade)]
finalmathgrade=map(int,finalmathgrade) # convert a list of strings to lisdt of integers
# histogram
hist1 = thinkstats2.Hist(Mothereducation)
print(hist1)
hist2= thinkstats2.Hist(sorted(absences))
print(sorted(absences))
print(hist2)
hist3= thinkstats2.Hist(familyrelationships)
print(hist3)
hist4= thinkstats2.Hist(finalmathgrade)
print(hist4)
# plot histogram
thinkplot.Hist(hist1)
thinkplot.Show(xlabel="Mother's education", ylabel="Frequency", main="Mother's education")
thinkplot.Hist(hist2)
thinkplot.Show(xlabel="absences", ylabel="Frequency", main="Number of days that the student was absent")
thinkplot.Hist(hist3)
thinkplot.Show(xlabel="family relationships", ylabel="Frequency", main="quality of family relationships")
thinkplot.Hist(hist4)
thinkplot.Show(xlabel="grade", ylabel="Frequency", main="final math grade")
plt.hist(absences)
|
277e1ecf426326cf0d0f3e2b75079bf3260fa92a | mnmnc/master | /arrtools/arrtools.py | 343 | 3.734375 | 4 |
def select_from_data(data, attributes):
""" CREATES AN ARRAY FROM DATA DICTIONARY
BY SELECTING GIVEN ATTRIBUTES
"""
results = []
for row in data:
results_row = []
for attribute in attributes:
results_row.append(row[attribute])
results.append(results_row)
return results
def main():
pass
if __name__ == "__main__":
main() |
d2b55e23830c44c2879fed624800a0d962bcee59 | naveeharn/pythonDataStructure | /01_LinkedList/1_SinglyLinkedList/py07_detectloop.py | 5,886 | 4.09375 | 4 | class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class LinkedListSst:
def __init__(self) -> None:
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def check_detectloop_set(self):
print("check_detectloop_set")
current = self.head
element = set()
while current:
if current in element:
print(current.data)
return True
element.add(current)
current = current.next
return False
def print_list(self):
current = self.head
while current and not self.check_detectloop_set(): #warning condition
print(current.data, end=" ")
current = current.next
print()
linkedlist_set = LinkedListSst()
print("\nlinkedlist_set")
for i in range(0,4):
linkedlist_set.push(i)
linkedlist_set.print_list()
print(linkedlist_set.check_detectloop_set())
linkedlist_set.head.next.next.next.next = linkedlist_set.head
linkedlist_set.print_list() #warning condition
print(linkedlist_set.check_detectloop_set())
print()
print(" = = = = = = = = = = = = = = = = = = = = = = = = ")
class NodeWithFlag:
def __init__(self, data) -> None:
self.data = data
self.next = None
self.flag = 0
class LinkedListFlag:
def __init__(self) -> None:
self.head = None
self.isloop = False #think myself
def push(self, new_data):
new_node = Node(new_data)
new_node.flag = 0
new_node.next = self.head
self.head = new_node
def check_detectloop_flag(self):
print("\ncheck_detectloop_flag")
current = self.head
while current:
if current.flag:
print(current.data)
self.isloop = True #think myself
return True
current.flag = 1
current = current.next
self.isloop = False #think myself
return False
def print_list(self):
current = self.head
while current and not self.isloop: #think myself
print(current.data, end=" ")
current = current.next
print()
linkedlist_flag = LinkedListFlag()
for i in range(0,4):
linkedlist_flag.push(i)
print("\nlinkedlist_flag")
linkedlist_flag.print_list()
print(linkedlist_flag.check_detectloop_flag())
linkedlist_flag.head.next.next.next.next = linkedlist_flag.head
print(linkedlist_flag.check_detectloop_flag())
linkedlist_flag.print_list()
print(" = = = = = = = = = = = = = = = = = = = = = = = = ")
class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class LinkedListFloydCycle:
def __init__(self) -> None:
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def check_detectloop_floydcycle(self):
print("\ncheck_detectloop_floydcycle")
slow_current = self.head
fast_current = self.head
while slow_current and fast_current:
slow_current = slow_current.next
fast_current = fast_current.next.next
if slow_current == fast_current:
print(slow_current.data)
return True
return False
def print_list(self):
current = self.head
while current:
print(current.data, end=" ")
current = current.next
print()
linkedlist_floydcycle = LinkedListFloydCycle()
for i in range(0,4):
linkedlist_floydcycle.push(i)
print("\nlinkedlist_floydcycle")
linkedlist_floydcycle.print_list()
print(linkedlist_floydcycle.check_detectloop_floydcycle())
linkedlist_floydcycle.head.next.next.next.next = linkedlist_floydcycle.head
print(linkedlist_floydcycle.check_detectloop_floydcycle())
linkedlist_floydcycle = LinkedListFloydCycle()
for i in range(0,4):
linkedlist_floydcycle.push(i)
linkedlist_floydcycle.head.next.next.next = linkedlist_floydcycle.head
print(linkedlist_floydcycle.check_detectloop_floydcycle())
print(" = = = = = = = = = = = = = = = = = = = = = = = = ")
class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class LinkedListHeadTail:
def __init__(self) -> None:
self.head = None
self.tail = None
def append(self, new_data):
current = self.tail
new_node = Node(new_data)
if self.head == None:
self.head = new_node
self.tail = new_node
return
current.next = new_node
self.tail = new_node
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
if self.head == None:
self.tail = new_node
self.head = new_node
def check_detectloop_headtail(self):
print("\ncheck_detectloop_headtail")
current = self.head
tail = self.tail
while current:
if(current == tail.next):
print(current.data)
return True
current = current.next
return False
def print_list(self):
current = self.head
while current:
print(current.data, end=" ")
current = current.next
print()
linkedlist_headtail = LinkedListHeadTail()
print("\nlinkedlist_headtail")
linkedlist_headtail.append(11)
for i in range(0,10):
linkedlist_headtail.push(i)
linkedlist_headtail.append(10)
linkedlist_headtail.print_list()
print(linkedlist_headtail.check_detectloop_headtail())
linkedlist_headtail.tail.next = linkedlist_headtail.head
print(linkedlist_headtail.check_detectloop_headtail())
|
56c244057251f0af753805ce0fb7fb6971413ec9 | AfiNaufal97/LatihanPython | /medium/dictionary.py | 351 | 3.875 | 4 | # type data dictionary
# key dan value {key:value}
Negara = {"Indonesia":"Jakarta", "Jepang":"Tokyo", "Korea Selatan":"Soul"}
Negara2 = {"Indonesia":"Jakarta", "Jepang":"Tokyo", "Korea Selatan":"Soul"}
print(Negara["Indonesia"])
# mencetak semua keys
print(Negara.keys())
print(Negara.items())
dataNegara = {1:Negara2, 2:Negara}
print(dataNegara[1]) |
cb03f24e19740da57b47df815ce4bbbc8751194d | AfiNaufal97/LatihanPython | /hard/constructorClass.py | 375 | 3.65625 | 4 | class Mahasiswa3():
nama = "nama default"
nim = 123
alamat = "Alamat default"
# constructor
def __init__(self, nama, nim, alamat):
self.nama = nama
self.nim = nim
self.alamat = alamat
def perkenalan(self):
print("perkenalan nama saya adalah ", self.nama)
nama3 = Mahasiswa3("Afi", 12345, "Tegal")
nama3.perkenalan() |
d4e04c7132876544fe0317e7a2934837c8ddd178 | SherMM/coursera-ucsd-algorithms-datastructures | /AlgorithmicToolBox/Week4/inversions/inversions.py | 1,078 | 3.5625 | 4 | # Uses python3
import sys
def get_number_of_inversions(a, b, left, right):
number_of_inversions = 0
if right - left <= 1:
return number_of_inversions
ave = (left + right) // 2
number_of_inversions += get_number_of_inversions(a, b, left, ave)
number_of_inversions += get_number_of_inversions(a, b, ave, right)
number_of_inversions += merge(a, b, left, ave, right)
return number_of_inversions
def merge(a, b, low, mid, high):
count = 0
i, j = low, mid
k = 0
while i < mid and j < high:
if a[i] <= a[j]:
b[k] = a[i]
i += 1
else:
count += (mid - i)
b[k] = a[j]
j += 1
k += 1
# handle remaining elements
if i < mid:
b[k: k+(mid-i)] = a[i: mid]
else:
b[k: k+(high-j)] = a[j: high]
# update a
a[low: high] = b[:(high-low)]
return count
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
b = n * [0]
print(get_number_of_inversions(a, b, 0, len(a)))
|
5d8e50b504b44217ae42a99fc5e54588c5dc94ef | SherMM/coursera-ucsd-algorithms-datastructures | /AlgorithmicToolBox/Week3/change/change.py | 554 | 3.859375 | 4 | # Uses python3
import sys
def get_change(n):
'''
Returns minimum number of 1, 5, 10 denomination
coins to make change for n
'''
assert (1 <= n <= 10**3)
total = n
count = 0
while total != 0:
if total >= 10:
count += total // 10
total %= 10
elif total >= 5:
count += total // 5
total %= 5
else:
count += total // 1
total %= 1
return count
if __name__ == '__main__':
n = int(sys.stdin.read())
print(get_change(n))
|
ee0e90e321aea5f39832d3c2db8d57eaebff3e08 | SherMM/coursera-ucsd-algorithms-datastructures | /AlgorithmicToolBox/Week3/fractional_knapsack/fractional_knapsack.py | 915 | 3.546875 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0 # value of items in bag
weight = 0 # weight of items in bag
items = {v/w: (v,w) for v,w in zip(values, weights)}
while weight != capacity and items:
best = max(items)
item_weight = items[best][1]
item_value = items[best][0]
if item_weight + weight <= capacity:
weight += item_weight
value += item_value
else:
diff = capacity - weight
frac = diff*best
weight += diff
value += frac
del items[best]
return value
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
059e6f213598e015e91edced9ad356f65f1bb616 | SherMM/coursera-ucsd-algorithms-datastructures | /Graphs/Week1/connected_components/connected_components.py | 767 | 3.65625 | 4 | #Uses python3
import sys
def number_of_components(graph):
result = 0
seen = set()
for vertex in graph:
if vertex not in seen:
stack = [vertex]
result += 1
while stack:
curr = stack.pop()
if curr not in seen:
seen.add(curr)
stack.extend(graph[curr])
return result
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
graph = {i: [] for i in range(n)}
for a, b in edges:
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
print(number_of_components(graph))
|
fabac6cb359e78a61802b1945a07a3170efd3ba2 | petrivo/movierate | /movierate/algo.py | 801 | 3.875 | 4 | class Node():
def __init__(self, data=None):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
elif data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
else:
self.data = data
def inorder(self, in_list):
if self.left:
self.left.inorder(in_list)
# print(self.data)
in_list.append(self.data)
if self.right:
self.right.inorder(in_list)
|
0bb60add2d02d615fa8866ded083faf1bdef142a | li3939108/max_bandwidth | /uf.py | 393 | 3.71875 | 4 | def union(x, y):
xRoot = find(x)
yRoot = find(y)
if xRoot.rank > yRoot.rank:
yRoot.parent = xRoot
elif xRoot.rank < yRoot.rank:
xRoot.parent = yRoot
elif xRoot != yRoot: # Unless x and y are already in same set, merge them
yRoot.parent = xRoot
xRoot.rank = xRoot.rank + 1
def find(x):
if x.parent == x:
return x
else:
x.parent = find(x.parent)
return x.parent
|
1757fffc67fc9d547b27b831e7117bde0d1ade59 | shahsanjana/Bioinformatics-Algorithms- | /PERM.py | 185 | 3.53125 | 4 | from itertools import permutations
n=5
num = list(permutations(range(1, n+1)))
permutation=[' '.join(map(str, i)) for i in num]
print len(num)
for item in permutation:
print item |
71a177252d41da4e48114a3a295144ad63fd5818 | last-partizan/pytils | /doc/examples/numeral.in_words.py | 1,104 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytils import numeral
# in_words нужен для представления цифр словами
print(numeral.in_words(12))
#-> двенадцать
# вторым параметром можно задать пол:
# мужской=numeral.MALE, женский=numeral.FEMALE, срелний=numeral.NEUTER (по умолчанию -- мужской)
print(numeral.in_words(21))
#-> двадцать один
# можно передавать неименованным параметром:
print(numeral.in_words(21, numeral.FEMALE))
#-> двадцать одна
# можно именованным
print(numeral.in_words(21, gender=numeral.FEMALE))
#-> двадцать одна
print(numeral.in_words(21, gender=numeral.NEUTER))
#-> двадцать одно
# можно и дробные
print(numeral.in_words(12.5))
#-> двенадцать целых пять десятых
# причем "пишутся" только значимые цифры
print(numeral.in_words(5.30000))
#-> пять целых три десятых
|
06e309b8d414ee29ac1106201cedbf347263d4b2 | mariagt267/python-maria-texcahua | /examen-parcial11/numeros.py | 362 | 3.953125 | 4 | while True:
numero = input("INTRODUZCA UN NUMERO: ")
try:
val = int(numero)
if val == 0:
print('CERO')
break
elif val > 0:
print('POSITIVO')
break
elif val < 0:
print('NEGATIVO')
break
except ValueError:
print("ERROR")
break
|
4e26bc2cf936c772f95409b95b10d1951d342023 | 5ANTI-726/Juego-pintado | /paint.py | 3,009 | 4.09375 | 4 | """Paint, for drawing shapes.
Exercises
1. Add a color.
2. Complete circle.
3. Complete rectangle.
4. Complete triangle.
5. Add width parameter.
"""
# A01701879 María José Díaz Sánchez
# A00829556 Santiago Gonzalez Irigoyen
# Este código funciona permite dibujar líneas, cuadrados, círculos y triángulos de diferentes colores
from turtle import *
from freegames import vector
def line(start, end):
"Draw line from start to end."
#Esta parte hace las líneas rectas
up()
goto(start.x, start.y)
down()
goto(end.x, end.y)
def square(start, end):
"Draw square from start to end."
#Aquí se hacen los rectángulos usando vueltas por grados
up()
goto(start.x, start.y)
down()
begin_fill()
for count in range(4):
forward(end.x - start.x)
left(90)
end_fill()
def circle(start, end):
"Draw circle from start to end."
#Aquí está el código del círculo, con un speed para hacerlo más rápido
up()
goto(start.x, start.y)
down()
begin_fill()
for count in range(130):
speed(10)
forward((end.x - start.x)/4)
speed(10)
left(2.86)
end_fill()
def rectangle(start, end):
"Draw rectangle from start to end."
#Similar al cuadrado el código del rectángulo hace vueltas por ángulos
up()
goto(start.x, start.y)
down()
begin_fill()
for count in range(2):
forward(end.x - start.x)
left(90)
forward(end.y - start.y)
left(90)
end_fill()
def triangle(start, end):
"Draw triangle from start to end."
#El código del triángulo también usa vueltas por ángulos
up()
goto(start.x, start.y)
down()
begin_fill()
for count in range(3):
forward(end.x - start.x)
left(120)
end_fill()
def tap(x, y):
"Store starting point or draw shape."
#funcion para iniciar
start = state['start']
if start is None:
state['start'] = vector(x, y)
else:
shape = state['shape']
end = vector(x, y)
shape(start, end)
state['start'] = None
def store(key, value):
"Store value in state at key."
state[key] = value
state = {'start': None, 'shape': line}
setup(420, 420, 370, 0)
onscreenclick(tap)
listen()
onkey(undo, 'u')#comando para deshacer dibujo
#lista de colores y sus teclas
onkey(lambda: color('black'), 'K')
onkey(lambda: color('white'), 'W')
onkey(lambda: color('green'), 'G')
onkey(lambda: color('blue'), 'B')
onkey(lambda: color('red'), 'R')
onkey(lambda: color('orange'), 'O')#color añadido naranja
onkey(lambda: color('purple'), 'P')#color añadido morado
onkey(lambda: color('yellow'), 'Y')#color añadido amarillo
onkey(lambda: color('pink'), 'N')#color añadido rosa
#lista de las figuras y sus teclas
onkey(lambda: store('shape', line), 'l')
onkey(lambda: store('shape', square), 's')
onkey(lambda: store('shape', circle), 'c')
onkey(lambda: store('shape', rectangle), 'r')
onkey(lambda: store('shape', triangle), 't')
done()
|
58ab7f3e468ef3bd196541d62baf529cd46072ef | DevanTurtle7/geneticAlgorithm | /tests/global_tests.py | 1,773 | 4.03125 | 4 | """
Tests the global functions to make sure it they are functioning properly.
author: Devan Kavalchek
"""
import globals
def test_change_string_first():
"""
Tests the change_string_first() function by giving it a standard input
and checking that the expected string is being returned
"""
# Setup
string = "hello"
index = 0
new_char = "t"
expected_string = "tello"
# Invoke
result = globals.change_string_index(string, index, new_char)
# Analyze
assert(expected_string == result)
print("test_change_string_index_0 passed!") # Prints if the test passes
def test_change_string_last():
"""
Tests the change_string_first() function by giving it a standard input
and checking that the expected string is being returned
"""
# Setup
string = "racecar"
index = 6
new_char = "t"
expected_string = "racecat"
# Invoke
result = globals.change_string_index(string, index, new_char)
# Analyze
assert(expected_string == result)
print("test_change_string_index_last passed!") # Prints if the test passes
def test_change_string_middle():
"""
Tests the change_string_first() function by giving it a standard input
and checking that the expected string is being returned
"""
# Setup
string = "turtoise"
index = 4
new_char = "i"
expected_string = "turtiise"
# Invoke
result = globals.change_string_index(string, index, new_char)
# Analyze
assert(expected_string == result)
print("test_change_string_index_middle passed!") # Prints if the test passes
def run_all_tests():
"""
Runs all the tests
"""
test_change_string_first()
test_change_string_last()
test_change_string_middle()
run_all_tests()
|
6790bffe8af91d0f2331df30d3015b27accf17ba | dennomwas/Room-Allocation | /Model/Amity.py | 16,898 | 3.765625 | 4 | import pickle
import sqlite3
from os import remove
from os import path
from sqlite3 import Error
from random import choice
from Model.People import Staff, Fellow
from Model.Rooms import Office, LivingSpace
class Amity(object):
all_rooms = {"office": [], "livingspace": []}
all_persons = []
unallocated_office = []
unallocated_livingspace = []
def create_room(self, room_type, room_name):
""" Creates rooms in Amity
get a list of all rooms
check room exists
create an office
create a livingspace
"""
all_rooms = self.all_rooms['office'] + self.all_rooms['livingspace']
check_name = [room.room_name for room in all_rooms if room.room_name == room_name]
if check_name:
return room_name + ' already exists!'
room_mapping = {'livingspace': LivingSpace, 'office': Office}
new_room = room_mapping[room_type](room_name)
if room_type.lower() == "office":
Amity.all_rooms['office'].append(new_room)
return room_name + ' created Successfully!'
else:
Amity.all_rooms['livingspace'].append(new_room)
return room_name + ' created Successfully!'
def add_person(self, first_name, last_name, designation, accommodation_request='N'):
""" Adds a person to the system and allocates the person to a random room
add staff
add staff to all persons list
add staff to office
add fellow to all persons list
add fellow to office
add fellow to livingspace if accommodation request is yes
"""
if designation.lower() == 'staff':
staff = Staff(first_name, last_name)
Amity.all_persons.append(staff)
print(first_name + ' added successfully! \n NB: Staff cannot be allocated a Living Space')
self.allocate_office(staff)
elif designation.lower() == 'fellow':
fellow = Fellow(first_name, last_name, accommodation_request='N')
Amity.all_persons.append(fellow)
print(first_name + ' added successfully!')
self.allocate_office(fellow)
if accommodation_request.lower() == 'y':
self.allocate_livingspace(fellow)
def allocate_office(self, person):
""" This is a helper function to add person to office
if there is no office in the system
add person to unallocated_office list
check for empty office
if none exist
return that all offices are full
add person to unallocated_office list
get a list of all offices
get a random office
make random office the persons current office
add person to the persons_allocated list for the office
"""
if not Amity.all_rooms['office']:
Amity.unallocated_office.append(person)
return 'There is no office in the system!'
empty_offices = [all(office for office in Amity.all_rooms['office']
if len(office.persons_allocated) == office.max_capacity)]
if not empty_offices:
Amity.unallocated_office.append(person)
return 'All offices are full!'
all_offices = [office for office in Amity.all_rooms['office']
if len(office.persons_allocated) < office.max_capacity]
random_office = choice(all_offices)
person.current_office = random_office
random_office.persons_allocated.append(person)
def allocate_livingspace(self, person):
"""This is a helper function to add person to livingspaces
if living space does not exist
add to unallocated list
return livingspace does not exist
check for empty living space
if there's no empty living space
add to unallocated list
return livingspace is full
get a random livingspace
make random the livingspace the persons current livingspace
add person to the persons_allocated list for livingspace
"""
if not Amity.all_rooms['livingspace']:
Amity.unallocated_livingspace.append(person)
return 'The living space does not exist!'
empty_livingspace = [all(livingspace for livingspace in Amity.all_rooms['livingspace']
if len(livingspace.persons_allocated) == livingspace.max_capacity)]
if not empty_livingspace:
Amity.unallocated_livingspace.append(person)
return 'All living spaces are full!'
all_living = [livingspace for livingspace in Amity.all_rooms['livingspace']
if len(livingspace.persons_allocated) < livingspace.max_capacity]
random_living = choice(all_living)
person.current_living = random_living
random_living.persons_allocated.append(person)
def reallocate_person(self, identifier, room_name):
""" Reallocate the person with person_identifier to new_room_name
get a list of all rooms.
check for available rooms.
if there's no room assert room not found.
check person exists.
if not return person not found.
pick room to reallocate.
if not return room to reallocate not found.
Check room still has space.
if not return room is filled to capacity.
Check Staff cannot be allocated to a living Space.
if not return allocating space to livingspace not allowed.
pick the previous room a person was in.
check if person is moving to the same room type.
if not return reallocations cannot be done to same room types.
update the persons new office.
update the persons new livingspace if fellow.
check if person is fellow and currently in a livingspace.
return fellow in livingspace cannot move to office.
remove person from room he was in.
assign person to a new room.
if person in unallocated_office move to available office
if person in unallocated_living move to available livingspace
"""
room_to_reallocate = None
previous_room = None
person_found = None
all_rooms = Amity.all_rooms['office'] + Amity.all_rooms['livingspace']
rooms_names = [room.room_name for room in all_rooms]
if room_name not in rooms_names:
return "Room not found!"
person_found = next((person for person in Amity.all_persons if person.identifier == int(identifier)), None)
if not person_found:
return "Person with id" + " " + str(identifier) + " not Found!"
room_to_reallocate = next((room for room in all_rooms if room.room_name == room_name), None)
if not room_to_reallocate:
return "Room to reallocate not Found!"
if len(room_to_reallocate.persons_allocated) == room_to_reallocate.max_capacity:
return "Room is Filled to capacity!"
if isinstance(person_found, Staff) and isinstance(room_to_reallocate, LivingSpace):
return "Reallocating Staff to Living space not Allowed!"
if isinstance(person_found, Fellow) and person_found.current_living:
if room_to_reallocate.room_type == 'OFFICE':
return "Reallocating Fellow in Living space to Office not Allowed!"
if isinstance(room_to_reallocate, Office):
previous_room = person_found.current_office
else:
previous_room = person_found.current_living
if previous_room:
if previous_room == room_to_reallocate:
return "Reallocations cannot be done to the same room or Person is already in the room!"
if isinstance(room_to_reallocate, Office):
person_found.current_office = room_to_reallocate
if isinstance(person_found, Fellow):
person_found.current_living = room_to_reallocate
previous_room.persons_allocated.remove(person_found)
room_to_reallocate.persons_allocated.append(person_found)
return person_found.first_name + ' reallocated to ' + str(room_to_reallocate) + ' successfully!'
if person_found in Amity.unallocated_office and isinstance(room_to_reallocate, Office):
room_to_reallocate.persons_allocated.append(person_found)
Amity.unallocated_office.remove(person_found)
return person_found.first_name + ' allocated to ' + str(room_to_reallocate) + ' successfully!'
if person_found in Amity.unallocated_livingspace and isinstance(room_to_reallocate, LivingSpace):
room_to_reallocate.persons_allocated.append(person_found)
Amity.unallocated_livingspace.remove(person_found)
return person_found.first_name + ' allocated to ' + str(room_to_reallocate) + ' successfully!'
def load_people(self, filename):
""" Adds people to rooms from a txt file
check if filename is a string
get details from the text file
"""
if not isinstance(filename, str):
return "Please check your file name and try again!"
try:
with open(filename, 'r') as persons_file:
persons = persons_file.readlines()
for person in persons:
person_details = person.split()
first_name = person_details[0]
last_name = person_details[1]
designation = person_details[2]
accommodation = person_details[-1]
if accommodation.lower() == 'y':
self.add_person(first_name, last_name, designation, accommodation)
else:
self.add_person(first_name, last_name, designation, accommodation)
return filename + ' successfully loaded to system...'
except FileNotFoundError:
return 'File not found, Please try again...'
except Exception as error:
return error
def print_allocations(self, filename=None):
""" Prints a list of allocations onto the screen
get a list of all rooms
display allocated offices
display allocated livingspaces
export allocations to a text file
"""
all_rooms = self.all_rooms['office'] + self.all_rooms['livingspace']
print('\n', 'OFFICES')
for room in Amity.all_rooms['office']:
print('\n', room.room_name)
print('---------------------')
if room.max_capacity:
print('\n'.join(str(person.identifier) + ', ' + person.first_name + ', '
+ person.last_name + ', ' + person.person_type
for person in room.persons_allocated))
print('\n', 'LIVING SPACES')
for room in Amity.all_rooms['livingspace']:
print('\n', room.room_name)
print('---------------------')
if room.max_capacity:
print('\n'.join(str(person.identifier) + ', ' + person.first_name + ', '
+ person.last_name + ', ' + person.person_type
for person in room.persons_allocated))
if filename:
path = './files/'
with open(path + filename, 'w') as export_file:
for room in all_rooms:
export_file.write(room.room_name + '\n')
export_file.write('---------------- \n')
if room.max_capacity > 0:
export_file.write('\n'.join(str(person.identifier) + ', ' +
person.first_name + ', ' + person.last_name
for person in room.persons_allocated)+'\n\n')
return 'Successfully exported room allocations to ' + filename
def print_unallocated(self, filename=None):
""" Prints a list of unallocated people to the screen
display unallocated offices
display unallocated livingspaces
export all to a text file
"""
print('\n UNALLOCATED TO OFFICES')
print('------------------------')
print('\n'.join(str(person) for person in Amity.unallocated_office), '\n')
print('\n UNALLOCATED TO LIVING SPACE')
print('----------------------------')
print('\n'.join(str(person) for person in Amity.unallocated_livingspace), '\n')
if filename:
try:
path = './files/'
with open(path + filename, 'w') as export_file:
for person in Amity.unallocated_office:
export_file.write('UNALLOCATED TO OFFICES \n')
export_file.write('-------------------------\n')
export_file.write('\n'.join(str(person.identifier) + ' ' + person.first_name + ' ' +
person.last_name
for person in Amity.unallocated_office) + '\n\n')
break
for person in Amity.unallocated_livingspace:
export_file.write('UNALLOCATED TO LIVING SPACES \n')
export_file.write('-------------------------------\n')
export_file.write('\n'.join(str(person) for person in Amity.unallocated_livingspace) + '\n\n')
break
return 'Successfully exported unallocated people file to ' + filename
except FileNotFoundError:
return 'File not found, Please try again!'
except Exception:
return 'Something went wrong!'
def print_room(self, room_name):
""" Prints the names of all the people in the room_name on the screen
get a list of all rooms
check if room name exists
print the room details
"""
all_rooms = self.all_rooms['office'] + self.all_rooms['livingspace']
room = next((room for room in all_rooms if room.room_name == room_name), None)
if not room:
return 'room name not found'
print('\n', room_name)
print('--------------------------')
print('\n'.join(str(person) for person in room.persons_allocated) + '\n\n')
def save_state(self, db_file):
""" Persists all the data stored in the app to an SQLite database
set the directory path
connect to the database
create a table if none exists and push the data to it
save all the data into the database
close the database connection
"""
path = './database/'
db_connect = sqlite3.connect(path + db_file)
conn = db_connect.cursor()
conn.execute("CREATE TABLE IF NOT EXISTS all_data "
"(dataID INTEGER PRIMARY KEY UNIQUE, "
"all_rooms TEXT, all_persons TEXT, unallocated_office TEXT, unallocated_livingspace TEXT)")
all_rooms = pickle.dumps(Amity.all_rooms)
all_persons = pickle.dumps(Amity.all_persons)
unallocated_office = pickle.dumps(Amity.allocate_office)
unallocated_livingspace = pickle.dumps(Amity.unallocated_livingspace)
conn.execute("INSERT INTO all_data VALUES (null, ?, ?, ?, ?);",
(all_rooms, all_persons, unallocated_office, unallocated_livingspace))
db_connect.commit()
db_connect.close()
return 'Data successfully exported to Database'
def load_state(self, db_file):
""" Loads data from a database into the application
set the directory path
connect to the database
select all data from the database table
load the data into the application
close the database connection
"""
try:
path = './database/'
db_connect = sqlite3.connect(path + db_file)
conn = db_connect.cursor()
conn.execute("SELECT * FROM all_data WHERE dataID = (SELECT MAX(dataID) FROM all_data)")
data = conn.fetchone()
Amity.all_rooms = pickle.loads(data[1])
Amity.all_persons = pickle.loads(data[2])
Amity.unallocated_office = pickle.loads(data[3])
Amity.unallocated_livingspace = pickle.loads(data[4])
db_connect.close()
return 'Successfully loaded data from the Database!'
except Error:
remove(path + db_file)
return "Database not found, Please check the name and try again!" |
e5a60154e307e131ee18b128b52df7f644062d00 | Nehanavgurukul/Dictionary | /exist_key.py | 155 | 4.3125 | 4 | dic={"name1": "radha","name2":"neha","name3":"rinki"}
if "name3" in dic:
print("yes it is exist in dic ")
else:
print("no it is not exist in dic")
|
3551578a46aade10996419ba4d96bea70637cd5a | Nehanavgurukul/Dictionary | /dic_value_sum_for.py | 87 | 3.578125 | 4 | dic={"A":56,"B":97,"C":57,"D":28}
sum=0
for x in dic.values():
sum=sum+x
print(sum) |
d471482237922835ff1802c479b4c520269ccd50 | Nehanavgurukul/Dictionary | /update_dict1.py | 65 | 3.578125 | 4 | person= {'1': 'RAM', '2': 17,}
person['3'] = 'male'
print(person) |
4a91036001115a0a01ecf9ce0be221744219ba73 | jaebradley/project_euler | /problems/pe23.py | 4,092 | 4.09375 | 4 | """
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24.
By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
Brute Force:
1. Iterate from 1 to 28123
2. For each number find divisors (if too slow could try caching this step in dictionary)
3. If sum of divisors > than number then log into abundant number list
4. Iterate through every tuple in abundant number list where the tuple sum < 28123 and log into list
5. Iterate from 1 to 28213 and check if number is in tuple list
"""
from __future__ import division
import math
import time
def return_proper_divisors(number):
divisors = list()
square_root = int(math.floor(math.sqrt(number)))
for candidate_divisor in range(1, square_root + 1):
if number % candidate_divisor is 0:
divisors.append(candidate_divisor)
dividend = int(number / candidate_divisor)
if dividend != number and dividend != square_root:
divisors.append(dividend)
return divisors
def is_abundant(number):
divisors = return_proper_divisors(number=number)
if sum(divisors) > number:
return True
else:
return False
def return_abundant_numbers(limit_inclusive):
amicable_numbers = list()
for candidate_number in range(1, limit_inclusive + 1):
if is_abundant(number=candidate_number):
amicable_numbers.append(candidate_number)
return amicable_numbers
def return_abundant_number_sums(limit_inclusive):
amicable_number_sums = list()
amicable_numbers = return_abundant_numbers(limit_inclusive=limit_inclusive)
for first_amicable_number_index in range(0, len(amicable_numbers) - 1):
for second_amicable_number_index in range(first_amicable_number_index + 1, len(amicable_numbers)):
amicable_number_sum = amicable_numbers[first_amicable_number_index] + amicable_numbers[second_amicable_number_index]
if amicable_number_sum <= limit_inclusive:
amicable_number_sums.append(amicable_number_sum)
return set(amicable_number_sums)
def return_sum_of_all_positive_integers_which_cannot_be_written_as_a_sum_of_two_abundant_numbers(limit_inclusive):
abundant_number_sums = return_abundant_number_sums(limit_inclusive=limit_inclusive)
numbers_that_cannot_be_written_as_a_sum_of_two_abundant_numbers = list()
for candidate_number in range(1, limit_inclusive + 1):
if candidate_number not in abundant_number_sums:
numbers_that_cannot_be_written_as_a_sum_of_two_abundant_numbers.append(candidate_number)
return sum(numbers_that_cannot_be_written_as_a_sum_of_two_abundant_numbers)
def main(limit_inclusive):
start_time = time.time()
sum_of_numbers_that_cannot_be_written_as_a_sum_of_two_abundant_numbers = return_sum_of_all_positive_integers_which_cannot_be_written_as_a_sum_of_two_abundant_numbers(
limit_inclusive=limit_inclusive
)
end_time = time.time()
execution_seconds = end_time - start_time
print "sum of numbers from 1 to {0} that cannot be written as two abundant numbers is {1}; took {2} seconds".format(
limit_inclusive,
sum_of_numbers_that_cannot_be_written_as_a_sum_of_two_abundant_numbers,
execution_seconds
)
main(limit_inclusive=28213)
|
bb3f60122c2ecc63b78c98572cb05cffa6c4f72e | jaebradley/project_euler | /problems/pe44.py | 1,410 | 4.25 | 4 | """
Find the pair of pentagonal numbers for which their sum and difference are pentagonal
"""
import time
def is_pentagonal(number):
#inverse function for pentagonal number
return not (1 + (1 + 24 * number) ** 0.5)/6 % 1
def return_pentagonal(n):
return n * (3 * n - 1) / 2
def is_sum_and_difference_of_two_pentagonal_numbers_pentagonal(pentagonal1, pentagonal2):
if is_pentagonal(pentagonal1 + pentagonal2) and is_pentagonal(abs(pentagonal1 - pentagonal2)):
return True
else:
return False
def return_first_pentagonal_number_pentagonal_difference():
found_pentagonal = False
pentagonals = list()
n = 1
while not found_pentagonal:
next_pentagonal = return_pentagonal(n=n)
for previous_pentagonal in pentagonals:
if is_sum_and_difference_of_two_pentagonal_numbers_pentagonal(pentagonal1=next_pentagonal, pentagonal2=previous_pentagonal):
return next_pentagonal, previous_pentagonal
pentagonals.append(next_pentagonal)
n += 1
def main():
start_time = time.time()
pentagonal_number_1, pentagonal_number_2 = return_first_pentagonal_number_pentagonal_difference()
end_time = time.time()
execution_seconds = end_time - start_time
print "pentagonal pair is {0}, {1}; execution took {2} seconds".format(pentagonal_number_1, pentagonal_number_2, execution_seconds)
main()
|
1821384382ef0685f647dbc5f28b11250aa1f6c9 | jaebradley/project_euler | /problems/pe56.py | 1,237 | 3.8125 | 4 | """
https://projecteuler.net/problem=56
A googol (10 ** 100) is a massive number: one followed by one-hundred zeros; 100 ** 100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a ** b, where a, b < 100, what is the maximum digital sum?
"""
from utils import project_euler_helpers as pe
import time
def return_greatest_digit_sum_for_a_and_b(a_limit_inclusive, b_limit_inclusive):
greatest_digit_sum = 0
for a in range(a_limit_inclusive, 0, -1):
for b in range(b_limit_inclusive, 0, -1):
digit_sum = sum(pe.getDigits(a ** b))
if digit_sum > greatest_digit_sum:
greatest_digit_sum = digit_sum
return greatest_digit_sum
def main(a_limit_inclusive, b_limit_inclusive):
start_time = time.time()
greatest_digit_sum = return_greatest_digit_sum_for_a_and_b(
a_limit_inclusive=a_limit_inclusive,
b_limit_inclusive=b_limit_inclusive
)
end_time = time.time()
execution_seconds = end_time - start_time
print "greatest digit sum is {0}; took {1} seconds".format(greatest_digit_sum, execution_seconds)
main(100, 100) |
63976b2ace691b640cd1b20c51bcc16f8b85826c | jaebradley/project_euler | /problems/pe26.py | 711 | 3.546875 | 4 | """
Find the value d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part
do the division, get the remainder
use the remainder, do the division, get the remainder
repeat
you can only know it's a cycle if you see the same pattern exactly twice where pattern length is <= d - 1
"""
recurring_list = list([0,0])
for a in range(2,1001):
print a
mod = 0
rem = 1
dig_list = list()
while rem:
rem = rem % a
if rem in dig_list:
if len(dig_list) - dig_list.index(rem) > recurring_list[1]:
recurring_list = list([a,len(dig_list)])
break
dig_list.append(rem)
rem *= 10
print recurring_list
|
dd316af927b9ba95a75e71e60f4177b621e56bc3 | jaebradley/project_euler | /problems/pe6.py | 1,368 | 4.09375 | 4 | # coding=utf-8
"""
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers
and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
import time
def sum_of_first_n_natural_numbers_squared(n):
squared_sum = 0
for natural_number in range(1, n + 1):
squared_sum += natural_number ** 2
return squared_sum
def square_of_sum_of_first_n_natural_numbers(n):
sum_of_natural_numbers = 0
for natural_number in range(1, n + 1):
sum_of_natural_numbers += natural_number
return sum_of_natural_numbers ** 2
def main():
start_time = time.time()
first_100_natural_numbers = sum_of_first_n_natural_numbers_squared(100)
sum_of_first_100_natural_numbers_squared = square_of_sum_of_first_n_natural_numbers(100)
difference = abs(sum_of_first_100_natural_numbers_squared - first_100_natural_numbers)
end_time = time.time()
execution_time_in_seconds = end_time - start_time
print "difference is {0}; execution time in seconds: {1}".format(difference, execution_time_in_seconds)
main() |
0da5f819770b018f53bd13a4abb57d7b68fb77f8 | jaebradley/project_euler | /problems/pe58.py | 3,039 | 4.03125 | 4 | # coding=utf-8
from utils import project_euler_helpers as pe
__author__ = 'jaebradley'
'''
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
Brute Force Strategy:
1. First thought about how to get diagonal numbers.
Note that the bottom right diagonal number is always side length ** 2 and that the side length is always an odd number
and obviously only 4 diagonal numbers per side length.
2. So to get diagonal numbers for a given side length, find side length ** 2
and subtract (side length - 1) from that, set the answer as the "new" side length and subtract (side length - 1) from that,
then set the answer as the "new" side length, etc. Do this process three times and each time append the answer to
a diagonal numbers list that is returned at the end of the function
3. Next, thought about larger process outside diagonal number getter.
Create an all diagonals list that contains 1. Create a prime count set to 0.
Iterate through odd numbers from 3 to 100000 (didn't come up with an upper bound, so used an arbitrarily large one) to get side length.
Get the diagonals for given side length.
Loop through those diagonals (this process is inefficient) and if diagonal is prime then increment prime count by 1.
If prime count/length(all diagonals list) < 0.1 then print the current side length, which is the answer, and break out of the for loop
'''
import time as time
from decimal import *
def getDiagonals(side_length):
last_number = side_length ** 2
diagonals_list = [last_number]
for i in range(0,3):
number = last_number - (side_length- 1)
diagonals_list.append(number)
last_number = number
return diagonals_list
start_time = time.time()
all_diagonals = [1]
prime_count = 0
answer = "didn't resolve"
for length in range(3,1000000,2):
diagonals = getDiagonals(length)
for diagonal in diagonals:
all_diagonals.append(diagonal)
if pe.prime_test(diagonal):
prime_count += 1
print "Prime Ratio is %s for square length %s." % (round(Decimal(prime_count)/Decimal(len(all_diagonals)),4),length)
if Decimal(prime_count)/Decimal(len(all_diagonals)) < 0.1:
answer = length
break
end_time = time.time()
run_time = end_time - start_time
print "Took %s seconds to run. Answer is %s." % (run_time,answer)
|
59a01e62964c23e5f7d5d8f2da93996a5b3e8ea8 | jaredrobertson21/GamePredictor | /gamepredictor/games/game.py | 2,543 | 3.78125 | 4 | class Game:
"""
Game objects encapsulate game data from the past or future
"""
def __init__(self, game_date=None, away_team=None, away_team_score=None, home_team=None, home_team_score=None,
game_id=None, overtime=None, attendance=None):
self.game_date = game_date
self.away_team = away_team
self.away_team_score = away_team_score
self.home_team = home_team
self.home_team_score = home_team_score
self.game_id = game_id
self.overtime = overtime
self.attendance = attendance
def winner(self):
if self.away_team_score > self.home_team_score:
return self.away_team
else:
return self.home_team
def loser(self):
if self.away_team_score < self.home_team_score:
return self.away_team
else:
return self.home_team
# TODO: add exception handling for winner/loser methods for games that have not been played yet
def __repr__(self):
return "Game date: {}\t{} @ {}".format(self.game_date, self.away_team, self.home_team)
class ScheduleGame:
"""
ScheduleGame objects encapsulate all game data for the purpose of parsing the game schedule.
game_information is a BeautifulSoup tag object
"""
def __init__(self, game_information):
self.game_date = game_information.find('th').get_text()
self.away_team = game_information.find('td', {'data-stat': 'visitor_team_name'}).get_text()
self.home_team = game_information.find('td', {'data-stat': 'home_team_name'}).get_text()
self.game_id = game_information.th.attrs.get('csk')
if game_information.find('td', {'data-stat': 'visitor_goals'}).get_text() == '':
# These fields must be sent to the database as None if the game has not happened yet
self.away_team_score = None
self.home_team_score = None
self.overtime = None
self.attendance = None
else:
self.away_team_score = game_information.find('td', {'data-stat': 'visitor_goals'}).get_text()
self.home_team_score = game_information.find('td', {'data-stat': 'home_goals'}).get_text()
self.overtime = game_information.find('td', {'data-stat': 'overtimes'}).get_text()
self.attendance = game_information.find('td', {'data-stat': 'attendance'}).get_text().replace(',', '')
def __repr__(self):
return "Date: {}\t{} @ {}".format(self.game_date, self.away_team, self.home_team) |
ab4b14981a3ecff06b03e9a39a2d4523cc612967 | decorouz/Google-IT-Automation-with-Python | /using-python-to-interact-with-operating-sys/week3_regex/playground.py | 20,913 | 4.125 | 4 | # # Regular Expressions
import re
# # Regular expressions allow us to search a text for strings matching a specific pattern.
# # Besides Python and other programming languages we can also use command line tools that know how to apply regexs, like grep, sed, or awk.
log = "July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade"
# with string methods:
index = log.index("[")
# print(log[index+1:index+6])
# # using regex:
regex = r"\[(\d+)\]"
result = re.search(regex, log)
# result = re.search(
# regex, "A completely different string that also has numbers []")
# print(result[1])
# # Basic Matching with grep
# CLI: grep thon /usr/share/dict/words
# # pass the -i parameter to the grep to match a string regardless of case
# CLI: grep -i python /usr/share/dict/words
# # a dot matches any character
# grep s.ing /usr/share/dict/words
# # ^ indicates the beginning
# grep ^fruit /usr/share/dict/words
# # & indicates the end
# grep cat$ /usr/share/dict/words
# ## Simple Matching in Python
# import re
# # The r at the beginning of the pattern indicates that this is a rawstring.
# # This means that Python interpreter shouldn't try to interpret any special
# # characters, and instead, should just pass the string to the function as is.
# # In this example, there are no special characters.
# result = re.search(r"aza", "plaza")
# print (result)
# # <re.Match object: span=(2,5), match='aza'>
# print(re.search(r"^x", "xenon"))
# print(re.search(r"p.ng", "Pangaea", re.IGNORECASE))
# # Fill in the code to check if the text passed contains the vowels a, e and i,
# # with exactly one occurrence of any other character in between.
# import re
# def check_aei (text):
# result = re.search(r"a.e.i", text)
# return result != None
# print(check_aei("academia")) # True
# print(check_aei("aerial")) # False
# print(check_aei("paramedic")) # True
# ## Wildcards and Character Classes
# # Character classes are written inside square brackets and let us list the characters we want to match inside of those brackets.
# print(re.search(r"[Pp]ython", "Python"))
# print(re.search(r"[a-z]way", "The end of the highway"))
# match='hway'
# print(re.search(r"[a-z]way", "What a way to go"))
# # match None
# print(re.search(r"cloud[a-zA-Z0-9]", "cloudy9"))
# # match cloudy9
# # Fill in the code to check if the text passed contains punctuation symbols:
# # commas, periods, colons, semicolons, question marks, and exclamation points.
# import re
# def check_punctuation (text):
# result = re.search(r"[a-zA-Z][,.!?:;]$", text)
# return result != None
# print(check_punctuation("This is a sentence that ends with a period.")) # True
# print(check_punctuation("This is a sentence fragment without a period")) # False
# print(check_punctuation("Aren't regular expressions awesome?")) # True
# print(check_punctuation("Wow! We're really picking up some steam now!")) # True
# print(check_punctuation("End of the line")) # False
# # search pattern that looks for any characters that's not a letter
# print(re.search(r"[^a-zA-Z]", "This is a sentence with spaces."))
# # match=' ' span=(4, 5) # match is the first space character
# # add spaces to include SPACE as character that we don't want to match
# print(re.search(r"[^a-zA-Z ]", "This is a sentence with spaces."))
# # match='.' span=(30, 31) # match is the first space character
# # Use | pipe symbol to match either one expression or another. This lets us list alternative options that can get matched.
# print(re.search(r"cat|dog", "I like cats."))
# # match='cat' span=(7, 10)
# print(re.findall(r"cat|dog", "I like both dogs and cats."))
# match='dog','cat'
# ## Repetition Qualifiers
# # Here we match Py followed by any number of other characters followed by n. But with our dot star combination we expanded the range of the match to the whole word.
# print(re.search(r"Pyt*n", "Pygmalion"))
# match='Pygmalion'
# # Star * character takes as many characters as possible. In programming terms, we say that this behavior is greedy.
# print(re.search(r"Pyt*n", "Python Programming"))
# match='Python Programming'
# # for pattern to only match letters we need to use character class instead
# print(re.search(r"Py[a-z]*n", "Python Programming"))
# match='Python Programming'
# # it will also match "0"/zero times:
# print(re.search(r"Py[a-z]*n", "Pyn"))
# match='Pyn'
# # The plus character matches one or more occurrences of the character that comes before it:
# print(re.search(r"o+l+", "goldfish"))
# match='ol'
# print(re.search(r"o+l+", "woolly"))
# match='ooll'
# # The repeating_letter_a function checks if the text passed includes the letter "a" (lowercase or uppercase) at least twice.
# # For example, repeating_letter_a("banana") is True, while repeating_letter_a("pineapple") is False.
# # Fill in the code to make this work.
# import re
# def repeating_letter_a(text):
# result = re.search(r"[aA].*[aA]", text)
# return result != None
# print(repeating_letter_a("banana")) # True
# print(repeating_letter_a("pineapple")) # False
# print(repeating_letter_a("Animal Kingdom")) # True
# print(repeating_letter_a("A is for apple")) # True
# # The question mark symbol is yet another multiplier.
# # It means either zero or one occurrence of the character before it.
# print(re.search(r"p?each", "To each their own"))
# match='each'
# print(re.search(r"p?each", "I like peaches"))
# match='peach'
# Escaping Characters
# What you do when the string contains a special character like $ * etc
# print(re.search(r".com", "welcome"))
# match = 'lcom'
# print(re.search(r"\.com", "welcome"))
# match = None
# print(re.search(r"\.com", "mydomian.com"))
# match= <re.Match object; span=(8, 12), match='.com'>
# \w matches any alphanumeric character including letters, numbers, and underscores (but not spaces)
print(re.search(r"\w*", "This is an example"))
print(re.search(r"\w*", "And_this_is_another_example"))
# there is also \d for matching digits, \s for matching whitespace characters like space, tab or new line, \b for word boundaries and a few others
# Fill in the code to check if the text passed has at least 2 groups of alphanumeric characters (including letters, numbers, and underscores) separated by one or more whitespace characters.
def check_character_groups(text):
result = re.search(r"\w\s", text)
return result != None
print(check_character_groups("One")) # False
print(check_character_groups("123 Ready Set GO")) # True
print(check_character_groups("username user_01")) # True
print(check_character_groups("shopping_list: milk, bread, eggs.")) # False
#
# Regular Expression in Action
print(re.search(r"^A.*a$", "Azerbaijan")) # return None
print(re.search(r"^A.*a$", "Australia"))
# Using regular expressions, we can also construct a pattern that would validate if the string is a valid variable name in Python.
pattern = r"^[a-zA-Z_][a-zA-Z0-9_]*$"
print(re.search(pattern, "_this_is_a_valid_variable_name"))
print(re.search(pattern, "this isn't a valid variable"))
print(re.search(pattern, "Yes_variable_name"))
# Fill in the code to check if the text passed looks like a standard sentence, meaning that it starts with an uppercase letter, followed by at least some lowercase letters or a space, and ends with a period, question mark, or exclamation point.
def check_sentence(text):
result = re.search(r"^[A-Z][a-z\s]*[\.!?]$", text)
return result != None
# print(check_sentence("Is this is a sentence?")) # True
# print(check_sentence("is this is a sentence?")) # False
# print(check_sentence("Hello")) # False
# print(check_sentence("1-2-3-GO!")) # False
# print(check_sentence("A star is born.")) # True
# Practice Quiz: Basic Regular Expressions
# The check_web_address function checks if the text passed qualifies as a top-level web address, meaning that it contains alphanumeric characters (which includes letters, numbers, and underscores), as well as periods, dashes, and a plus sign, followed by a period and a character-only top-level domain such as ".com", ".info", ".edu", etc. Fill in the regular expression to do that, using escape characters, wildcards, repetition qualifiers, beginning and end-of-line characters, and character classes.
def check_web_address(text):
pattern = r"[\.][a-zA-Z0-9]*$"
result = re.search(pattern, text)
return result != None
# print(check_web_address("gmail.com")) # True
# print(check_web_address("www@google")) # False
# print(check_web_address("www.Coursera.org")) # True
# print(check_web_address("web-address.com/homepage")) # False
# print(check_web_address("My_Favorite-Blog.US")) # True
# The check_time function checks for the time format of a 12-hour clock, as follows: the hour is between 1 and 12, with no leading zero, followed by a colon, then minutes between 00 and 59, then an optional space, and then AM or PM, in upper or lower case. Fill in the regular expression to do that. How many of the concepts that you just learned can you use here?
def check_time(text):
pattern = r"[1-9]+:\d[1-9]\s*[Aa]|[Pp][Mm]"
# pattern = r"[1-9]+:\d[1-9]\s*[Aa]|[Pp][Mm]"
result = re.search(pattern, text)
return result != None
# print(check_time("12:45pm")) # True
# print(check_time("9:59 AM")) # True
# print(check_time("6:60am")) # False
# print(check_time("five o'clock")) # False
# The contains_acronym function checks the text for the presence of 2 or more characters or digits surrounded by parentheses, with at least the first character in uppercase (if it's a letter), returning True if the condition is met, or False otherwise. For example, "Instant messaging (IM) is a set of communication technologies used for text-based communication" should return True since (IM) satisfies the match conditions." Fill in the regular expression in this function:
def contains_acronym(text):
pattern = r"\([A-Za-z0-9]{2,}\)"
result = re.search(pattern, text)
return result != None
print(contains_acronym(
"Instant messaging (IM) is a set of communication technologies used for text-based communication")) # True
print(contains_acronym("American Standard Code for Information Interchange (ASCII) is a character encoding standard for electronic communication")) # True
print(contains_acronym("Please do NOT enter without permission!")) # False
print(contains_acronym(
"PostScript is a fourth-generation programming language (4GL)")) # True
print(contains_acronym(
"Have fun using a self-contained underwater breathing apparatus (Scuba)!")) # True
# Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and cannot be at the start of the text
def check_zip_code(text):
result = re.search(r".*\s[0-9]{5}", text)
return result != None
print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code(
"The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
# Advance Regular Expression
# Capturing Groups: They are portion of the pattern that are enclosed in parenthesis
# For example, we may want to extract the hostname or a process ID from a log line and use that value for another operation.
result = re.search(r"^(\w*), (\w*)$", "Ademide, Adeleye")
print(result)
# match=<re.Match object; span=(0, 16), match='Ademide, Adeleye'>
print(result.groups())
# Because we defined two separate groups, the group method returns a tuple of two elements.
('Lovelace', 'Ada')
print(result[0]) # Ademide Adeleye
print(result[1]) # Ademide
print(result[2]) # Adeleye
def rearrange_name(name):
result = re.search(r"^(\w*), (\w*) (\w\.)$", name)
if result is None:
return name
return "{} {}".format(result[2], result[1])
print(rearrange_name('Dennis, Roadman'))
print(rearrange_name('Dennis, Roadman A.'))
# Fix the regular expression used in the rearrange_name function so that it can match middle names, middle initials, as well as double surnames.
def rearrange_name(name):
result = re.search(r"^([\w .]*), ([\w .]*)$", name)
if result is None:
return name
return "{} {}".format(result[2], result[1])
name = rearrange_name("Kennedy, John F.")
print(name)
# Suppose we want to extract username and host name from the email address in the example below.rearrange_name
print("======Capturing Groups====")
# More on repitition qualifiers
# More on Repetition Qualifiers
re.search(r"[a-zA-Z]{5}", "a ghost")
match = 'ghost'
re.findall(r"[a-zA-Z]{5}", "a scary ghost appeared")
match = ['scary', 'ghost', 'appea']
# if we wanted to match all the words that are exactly five letters long? We can do that using \b, which matches word limits
# at the beginning and end of the pattern, to indicate that we want full words
re.findall(r"\b[a-zA-Z]{5}\b", "a scary ghost appeared")
match = ['scary', 'ghost']
# if we wanted to match a range of five to ten letters or numbers, we could use an expression like this one:
re.findall(r"\w{5,10}", "I really like strawberries")
match = ['really', 'strawberri']
re.findall(r"\w{5,}", "I really like strawberries")
match = ['really', 'strawberries']
# Here we look for a pattern that was an S followed by up to 20 alphanumeric characters.
re.search(r"s\w{,20}", "I really like strawberries")
match = ['strawberries']
# Quiz
# The long_words function returns all words that are at least 7 characters. Fill in the regular expression to complete this function.
def long_words(text):
pattern = r"\w{7,}"
result = re.findall(pattern, text)
return result
long_words("I like to drink coffee in the morning.") # ['morning']
# ['chocolate', 'afternoon']
long_words("I also have a taste for hot chocolate in the afternoon.")
long_words("I never drink tea late at night.") # []
log = "July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade"
regex = r"\[(\d+)\]" '''After the square bracket, comes the first parentheses. Since it isn't escaped, we know it'll be used as a capturing group.
The capturing group parentheses are wrapping the backslash d+ symbols. From our discussion of special characters and repetition qualifiers,
we know that this expression will match one or more numerical characters.'''
result = re.search(regex, log)
# After calling the search function, we know that because we're capturing groups in an expression, we can access the matching data by accessing the value at index 1.
# print(result[1])
# We should have a function that extracts the process ID or PID when possible, and does something else if not. It's something like this; will start by defining a function called extract_pid.
def extract_pid(log_line):
regex = r"\[(\d+)\]"
result = re.search(regex, log_line)
if result is None:
return ""
return result[1]
# print(extract_pid(log))
# Add to the regular expression used in the extract_pid function, to return the uppercase message in parenthesis, after the process id.
def extract_pid(log_line):
regex = r"\[(\d+)\].*\s([A-Z]*)\s"
result = re.search(regex, log_line)
if result is None:
return None
return "{} ({})".format(result[1], result[2])
# 12345 (ERROR)
print(extract_pid(
"July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade"))
print(extract_pid("99 elephants in a [cage]")) # None
print(extract_pid(
"A string that also has numbers [34567] but no uppercase message")) # None
# 67890 (RUNNING)
print(extract_pid(
"July 31 08:08:08 mycomputer new_process[67890]: RUNNING Performing backup"))
# Splitting and Replacing
re.split(r"[.?!]", "One sentence. Another one? And the last one!")
['One sentence', 'Another one', 'And the last one', '']
re.split(r"([.?!])", "One sentence. Another one? And the last one!")
['One sentence', '.', 'Another one', '?', 'And the last one', '!', '']
# Another interesting function provided by the RE module is called sub.
# It's used for creating new strings by substituting all or part of them for a different string,
# similar to the replace string method but using regular expressions for both the matching and the replacing.
re.sub(r"[\w.%+-]+@[\w.-]+", "[REDACTED]",
"Received an email for go_nuts95@my.example.com")
re.sub(r"^([\w .-]*), ([\w .-]*)$", r"\2 \1", "Lovelace, Ada")
# If we want to make sure that only the actual words are used to split the text, we need to use the escape character
# or word boundaries, like this: r"\bthe\b|\ba\b". Otherwise, any instance of the given words is used as delimiters,
# no matter where they are in the text, even in the middle of other words like "Another" and "last".
re.split(r"the|a", "One sentence. Another one? And the last one!")
['One sentence. Ano', 'r one? And ', ' l', 'st one!']
print("Practise quiz section======")
# Practice Quiz: Advanced Regular Expressions
# 1 We're working with a CSV file, which contains employee information. Each record has a name field, followed by a phone number field, and a role field. The phone number field contains U.S. phone numbers, and needs to be modified to the international format, with "+1-" in front of the phone number. Fill in the regular expression, using groups, to use the transform_record function to do that.
def transform_record(record):
pattern = r"(\d{3}-\d{3}-?\d{4})"
print(re.search(pattern, record))
new_record = re.sub(pattern, r"+1-\1", record)
return new_record
print(transform_record("Sabrina Green,802-867-5309,System Administrator"))
# Sabrina Green,+1-802-867-5309,System Administrator
print(transform_record("Eli Jones,684-3481127,IT specialist"))
# Eli Jones,+1-684-3481127,IT specialist
print(transform_record("Melody Daniels,846-687-7436,Programmer"))
# Melody Daniels,+1-846-687-7436,Programmer
print(transform_record("Charlie Rivera,698-746-3357,Web Developer"))
# Charlie Rivera,+1-698-746-3357,Web Developer
# 2 Question 2
# The multi_vowel_words function returns all words with 3 or more consecutive vowels (a, e, i, o, u). Fill in the regular expression to do that.
def multi_vowel_words(text):
pattern = r"\w*[aeiou]{3,}\w*"
result = re.findall(pattern, text)
return result
print(multi_vowel_words("Life is beautiful"))
# ['beautiful']
print(multi_vowel_words("Obviously, the queen is courageous and gracious."))
# ['Obviously', 'queen', 'courageous', 'gracious']
print(multi_vowel_words(
"The rambunctious children had to sit quietly and await their delicious dinner."))
# ['rambunctious', 'quietly', 'delicious']
print(multi_vowel_words("The order of a data queue is First In First Out (FIFO)"))
# ['queue']
print(multi_vowel_words("Hello world!"))
# []
# 4
# The transform_comments function converts comments in a Python script into those usable by a C compiler. This means looking for text that begins with a hash mark (#) and replacing it with double slashes (//), which is the C single-line comment indicator. For the purpose of this exercise, we'll ignore the possibility of a hash mark embedded inside of a Python command, and assume that it's only used to indicate a comment. We also want to treat repetitive hash marks (##), (###), etc., as a single comment indicator, to be replaced with just (//) and not (#//) or (//#). Fill in the parameters of the substitution method to complete this function:
def transform_comments(line_of_code):
regex = r"(#)+"
result = re.sub(regex, r"//", line_of_code)
return result
print(transform_comments("### Start of program"))
# Should be "// Start of program"
print(transform_comments(" number = 0 ## Initialize the variable"))
# Should be " number = 0 // Initialize the variable"
print(transform_comments(" number += 1 # Increment the variable"))
# Should be " number += 1 // Increment the variable"
print(transform_comments(" return(number)"))
# Should be " return(number)"
# 5
# The convert_phone_number function checks for a U.S. phone number format: XXX-XXX-XXXX (3 digits followed by a dash, 3 more digits followed by a dash, and 4 digits), and converts it to a more formal format that looks like this: (XXX) XXX-XXXX. Fill in the regular expression to complete this function.
def convert_phone_number(phone):
pattern = r"(\d{3})-(\d{3}-\d{4}\b)"
result = re.sub(pattern, r"(\1) \2", phone)
return result
# My number is (212) 345-9999.
print(convert_phone_number("My number is 212-345-9999."))
# Please call (888) 555-1234
print(convert_phone_number("Please call 888-555-1234"))
print(convert_phone_number("123-123-12345")) # 123-123-12345
# Phone number of Buckingham Palace is +44 303 123 7300
print(convert_phone_number("Phone number of Buckingham Palace is +44 303 123 7300"))
|
91e7da83b03fe16d65782809e07e397a41aabb72 | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A1/Comments_Outputs_Errors.py | 1,379 | 4.65625 | 5 | print('Welcome to Python!')
# Output: Welcome to Python
# Why: String says "Welcome to Python
print(1+1)
# Output: 2
# Why: Math sum / 1 + 1 = 2
# print(This will produce an error)
# Output: This will produce an Error
# Why: The text doesn't have a string, it's invalid
print(5+5-2)
# Output: 8
# Why: 5 + 5 - 2
print(3*3+1)
# Output: 10
# Why: 3 x 3 + 1
print(10+3*2)
# Output: 16
# Why: 10 + 3 x 2
print((10 + 3) *2)
# Output: 26
# Why: 10 + 3 x 2
print(10/5)
# Output: 2
# Why: 10 divided by 5
print(5<6)
# Output: True
# Why: 6 is greater than 5. So, the Boolean statement is true.
print(5>6)
# Output: False
# Why: 5 is not over 6. So, the Boolean statement is false.
print(3==3)
# Output: True
# Why: 3 is the same as 3. So, the Boolean statement is true.
print(3==4)
# Output: False
# Why: 3 is not the same as 4. So, the Boolean statement is false.
print(4!=4)
# Output: False
# Why: != < means not equal. But 4 is equal to 4. So, the Boolean statement is false.
print("The secret number is", 23)
# Output: The secret number is 23
# Why: The print statement said it in a string with a number.
print("The secret number is",23)
# Output: The secret number is 23
# Why: The print statement said it in a string with a number.
print("The sum is ",(5+2))
# Output: The sum is 7
# Why: "The sum is" after that, a mathematical statement was added. Which equalled 7.
|
bbed8da2e0837f77df6ae36a03ef73ac25e172fd | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A4 - Conditional Expressions/programOne.py | 403 | 4.15625 | 4 | # Program One - Write a number that asks the user to enter a number between 1 and 5. The program should output the number in words.
# Code: Nathan Hernandez
from ess import ask
number = ask("Choose a number between 1 and 5.")
if number == 1:
print("One.")
if number == 2:
print("Two.")
if number == 3:
print("Three.")
if number == 4:
print("Four.")
if number == 5:
print("Five.")
|
568a008e308b0ec562b9dbdb99b2edd5d67a2e7b | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A2 - Make Math Easy!/VolumeOfACylinder.py | 137 | 4.15625 | 4 | # Volume of a Cylinder, Nathan Hernandez
import math
h = 8
pi = 3.14
r = math.pow(3, 2)
v = h * pi * r
print('The volume of the cylinder is',v) |
158499a0dbf4b618b191cb64e35a00b16df1b9f5 | eizin6389/The-Self-Taught-Programmer | /Chapter6/Challenge6.py | 83 | 3.796875 | 4 | word ="A screaming comes across the sky."
word = word.replace("s","$")
print(word)
|
70f8c0bf95e89b5b795aac2f7e69f0273b58fec0 | eizin6389/The-Self-Taught-Programmer | /Chapter12/Challenge2.py | 185 | 3.78125 | 4 | import math
class Circle:
def __init__(self, width):
self.width = width
def area(self):
print(self.width*self.width*math.pi)
circle = Circle(3)
circle.area()
|
f47da891c0c808231dab94c9d0559bf434d41326 | darshan527/Practical-DSA-with-Python-Flask-API | /hash_table.py | 2,074 | 3.859375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Data:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self, table_size: int):
self.table_size = table_size
self.hash_table = [None] * table_size
def custom_hash(self, key: str):
hashed_key = 0
for i in key:
hashed_key += ord(i)
hashed_key = (hashed_key * ord(i)) % self.table_size
return hashed_key
def add_data(self, key, value):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is None:
self.hash_table[hashed_key] = Node(Data(key, value))
else:
nod = self.hash_table[hashed_key]
while nod.next:
nod = nod.next
nod.next = Node(Data(key, value))
def get_value(self, key):
hashed_key = self.custom_hash(key)
val = self.hash_table[hashed_key]
if val is not None:
if val.next is None:
return val.data.value
else:
while val:
if val.data.key is key:
return val.data.value
val = val.next
return None
def print_table(self):
print("{")
for i in self.hash_table:
if i is None:
print(None)
else:
tmp = i
while tmp:
print(f"[{tmp.data.key} : {tmp.data.value}]", end=" -> ")
tmp = tmp.next
print("None")
print("}")
if __name__ == "__main__":
ht = HashTable(4)
ht.add_data("title", "Jack and Jill")
ht.add_data("body", "Hello World, learn Programming")
ht.add_data("date", "22-3-15")
ht.add_data("user_id", 2)
# print(ht.get_value("title"))
print(ht.get_value('title'))
print(ht.get_value('body'))
print(ht.get_value('date'))
print(ht.get_value('user_id'))
ht.print_table() |
23c70016339c5b3e283b1824f3c03f46cb23359f | satishgunjal/ml_proj_template | /src/cross_validation.py | 6,410 | 3.625 | 4 | import pandas as pd
from sklearn import model_selection
class CrossValidation:
def __init__(
self,
df,
target_cols,
shuffle,
problem_type = 'binary_classification',
multilabel_delimiter = ',',
num_folds = 5,
random_state = 42
):
self.dataframe = df
self.target_cols = target_cols
self.num_targets = len(target_cols)
self.shuffle = shuffle
self.problem_type = problem_type
self.multilabel_delimiter = multilabel_delimiter
self.num_folds = num_folds
self.random_state = random_state
"""
Code to shuffle the dataframe and reset the index
The frac keyword argument specifies the fraction of rows to return in the random sample, so frac=1 means return all rows (in random order)
specifying 'drop=True' prevents '.reset_index' from creating a column containing the old index entries.
"""
if self.shuffle is True:
self.dataframe = self.dataframe.sample(frac= 1).reset_index(drop = True)
"""
Add kfold column, later we will update it with actual value of fold for each record
"""
self.dataframe['kfold'] = -1
"""
Split the data in kfolds
nunique()> To get the distinct values
StratifiedKFold()> To keep the ratio of positive and negative label values same in each fold
split()> Generates indices to split data into train and test sets
enumerate function will iterate through every indices returned by split()
fold values will be 0 to self.num_folds - 1
remember we have added 'kfold' column in our dataset. We are going to assign the fold number to each new fold
"""
def split(self):
if self.problem_type in ('binary_classification', 'multiclass_classification'):
if self.num_targets != 1:
raise Exception('Invalid number of targets for this problem type')
target = self.target_cols[0]
unique_values = self.dataframe[target].nunique()
if unique_values == 1:
raise Exception('Only one unique value found')
elif unique_values > 1:
kf = model_selection.StratifiedKFold(n_splits= self.num_folds, shuffle=False)
for fold, (train_idx, val_idx) in enumerate(kf.split(X= self.dataframe, y= self.dataframe[target].values )):
self.dataframe.loc[val_idx, 'kfold'] = fold
elif self.problem_type in ('single_col_regression', 'multi_col_regression'):
if self.num_targets != 1 and self.problem_type == 'single_col_regression':
raise Exception('Invalid number of targets for this problem type')
if self.num_targets < 2 and self.problem_type == 'multi_col_regression':
raise Exception('Invalid number of targets for this problem type')
kf = model_selection.KFold(n_splits = self.num_folds, shuffle = False)
# Only X value required
for fold, (train_idx, val_idx) in enumerate(kf.split(self.dataframe)):
self.dataframe.loc[val_idx, 'kfold'] = fold
#Suitable for timeseries data and when data size is very large
elif self.problem_type.startswith('holdout_'):
holdout_percentage = int(self.problem_type.split("_")[1])
print('holdout_percentage= ', holdout_percentage)
num_holdout_samples = int( len(self.dataframe) * holdout_percentage / 100)
print('num_holdout_samples= ', num_holdout_samples)
self.dataframe.loc[:len(self.dataframe) - num_holdout_samples, "kfold"] = 0
self.dataframe.loc[len(self.dataframe) - num_holdout_samples:, "kfold"] = 1
elif self.problem_type == 'multilabel_classification':
if self.num_targets != 1:
raise Exception("Invalid number of targets for this problem type")
target = self.dataframe[self.target_cols[0]].apply(lambda x: len(str(x).split(self.multilabel_delimiter)))
kf = model_selection.StratifiedKFold(n_splits= self.num_folds, shuffle=False)
for fold, (train_idx, val_idx) in enumerate(kf.split(X= self.dataframe, y= target)):
self.dataframe.loc[val_idx, 'kfold'] = fold
else:
raise Exception('Problem type not understood')
return self.dataframe
if __name__ == '__main__':
######## Testing for problem_type = "binary_classification" ########
#_data_file_path = 'input/train.csv'
#_target_cols = ['target']
#_problem_type = "binary_classification"
#_shuffle = True
######## Testing for problem_type = "single_col_regression" ########
#_data_file_path = 'input/house_price_regression_train.csv'
#_target_cols = ['SalePrice']
#_problem_type = "single_col_regression"
#_shuffle = True
######## Testing for problem_type = "holdeout" ########
#_data_file_path = 'input/train.csv'
#_target_cols = ['target'] # Not required TODO modify the class to handle it
#_problem_type = "holdout_10"
#_shuffle = False
######## Testing for problem_type = "multilabel_classification" ########
# kaggle dataset link: https://www.kaggle.com/c/imet-2020-fgvc7/data?select=train.csv
_data_file_path = 'input/multilabel_classification_train.csv'
_target_cols = ["attribute_ids"]
_problem_type = "multilabel_classification"
_multilabel_delimiter = " "
_shuffle = True
df = pd.read_csv(_data_file_path)
print('Shape of the data = ', df.shape)
cv = CrossValidation(df, shuffle=_shuffle, target_cols=_target_cols, problem_type=_problem_type, multilabel_delimiter= _multilabel_delimiter)
df_split = cv.split()
print('Count of kfold values in each fold= \n ', df_split.kfold.value_counts())
print('Top 5 rows from final datframe= \n ', df_split.head())
if _problem_type in ('binary_classification', 'multiclass_classification'):
print('% distribution of classes in given data= \n ', df[_target_cols[0]].value_counts(normalize =True))
for fold in range(df_split.kfold.nunique()):
print('% distribution of classes for kfold= ' + str(fold) + ' is \n', df_split[_target_cols[0]].value_counts(normalize =True))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.