blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9fb4042c554473553486d2e9c2bfe22484c535fa | VDSMath/SudokuLogica2018.2 | /GridToString.py | 1,303 | 3.5 | 4 | #TRABALHO 1 - ESTUDO DIRIGIDO: SUDOKU
#GRUPO: Gabriel Raposo(115117041), Matheus Vinicius(116023504), Pedro Nascimento(116037448)
#PROFESSOR: Joao Carlos DISCIPLINA: Logica PERIODO: 2018/2
from SudokuCheck import CheckIfValid
SAVE_PATH = "Maps/"
DEFAULT_NAME = "correctInput"
LIST_SIZE = 1000
currentMap = 0
def SaveGrid(X):
global currentMap
fileName = SAVE_PATH + DEFAULT_NAME + str(currentMap) + ".txt"
file = open(fileName,'w')
txt = ""
for i in range(0,LIST_SIZE):
txt += str(X[i]) + "\n"
print(txt)
file.write(txt)
currentMap += 1
def FindSolutions(X):
auxX = [False] * 1000
current = 0
maxCurrent = 0
while not(auxX[970]):
if not(auxX[999-current]):
auxX[999-current] = True
current = 0
ReplaceAndCheck(X,auxX)
else:
auxX[999-current] = False
current = current + 1
if current > maxCurrent:
maxCurrent = current
print("Current: X[" + str(999 - maxCurrent) + "]")
return
def ReplaceAndCheck(X, auxX):
auxSec = auxX
for i in range(0,1000):
if X[i]:
auxSec[i] = True
if CheckIfValid(auxSec):
print("VALIDO")
SaveGrid(auxSec)
return True
return False
def GetInput():
X = [False]*1000
input_file = open('input.txt','r').read()
for p in input_file.split():
X[int(p)] = True
return X
|
cef02555c04d85baaab43d484ab3ff5786e21644 | CodecoolBP20172/pbwp-3rd-si-game-statistics-PeterBernath | /reports.py | 2,238 | 3.59375 | 4 | def create_list(file_name):
results = []
with open(file_name) as inputfile:
for line in inputfile:
results.append(line.strip().split('\t'))
return results
def count_games(file_name):
results = create_list(file_name)
return len(results)
def decide(file_name, year):
results = create_list(file_name)
results = list(map(lambda x: [x[0], x[1], int(x[2]), x[3], x[4]], results))
for i in range(len(results)):
if results[i][2] == year:
return True
def get_latest(file_name):
results = create_list(file_name)
latest = max(results, key=lambda x: x[2])
latest_name = latest[0]
return latest_name
def count_by_genre(file_name, genre):
results = create_list(file_name)
genre_count = sum(x.count(genre) for x in results)
return genre_count
def get_line_number_by_title(file_name, title):
try:
results = create_list(file_name)
for i in range(len(results)):
if results[i][0] == title:
return i + 1
except ValueError:
print("That game is not in the list. Please give another title!")
def sort_abc(file_name):
results = create_list(file_name)
results = sorted(list(map(lambda x: x[0], results)))
return results
def get_genres(file_name):
results = create_list(file_name)
results = list(map(lambda x: x[3], results))
results = set(results)
results = sorted(list(results))
return results
def when_was_top_sold_fps(file_name):
results = create_list(file_name)
results = list(map(lambda x: [x[0], float(x[1]), int(x[2]), x[3], x[4]], results))
most_games_sold = sorted(results, key=lambda x: x[1], reverse=True)
for i in range(len(most_games_sold)):
if most_games_sold[i][3] == 'First-person shooter':
return most_games_sold[i][2]
def main():
create_list('game_stat.txt')
count_games('game_stat.txt')
decide('game_stat.txt', 2000)
get_latest('game_stat.txt')
count_by_genre('game_stat.txt', 'First-person shooter')
get_line_number_by_title('game_stat.txt', 'EverQuest')
sort_abc('game_stat.txt')
get_genres('game_stat.txt')
when_was_top_sold_fps('game_stat.txt')
main()
|
26a24947f2c2f7b8cf589f1466f864467a26b6e6 | shivaverma/Machine-Learning-Intro | /codes/k-mean _basic.py | 517 | 3.5 | 4 | # author: Shiva Verma, Mail: shivajbd@gmail.com
# k-mean clustering
import numpy as np
from sklearn.cluster import KMeans
def predict_label(feature_data, p):
c = KMeans(n_clusters=2) # initialize with two centers
c.fit(feature_data) # fitting the data
return c.predict(p) # predicting new data
if __name__ == '__main__':
x = np.array([[12, 0], [13, 0], [2, 4], [3, 5]])
point = ([[13, 0], [14, 0]])
pred = predict_label(x, point)
print(pred)
|
e2dba5567511a1b835a5c221e419f7f78b9ff556 | SR2k/leetcode | /second-round/92.反转链表-ii.py | 3,373 | 3.953125 | 4 | #
# @lc app=leetcode.cn id=92 lang=python3
#
# [92] 反转链表 II
#
# https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
#
# algorithms
# Medium (55.02%)
# Likes: 1133
# Dislikes: 0
# Total Accepted: 242.2K
# Total Submissions: 440K
# Testcase Example: '[1,2,3,4,5]\n2\n4'
#
# 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left 。请你反转从位置 left 到位置 right 的链表节点,返回
# 反转后的链表 。
#
#
# 示例 1:
#
#
# 输入:head = [1,2,3,4,5], left = 2, right = 4
# 输出:[1,4,3,2,5]
#
#
# 示例 2:
#
#
# 输入:head = [5], left = 1, right = 1
# 输出:[5]
#
#
#
#
# 提示:
#
#
# 链表中节点数目为 n
# 1
# -500
# 1
#
#
#
#
# 进阶: 你可以使用一趟扫描完成反转吗?
#
#
# Definition for singly-linked list.
class ListNode:
@staticmethod
def from_arr(l: list[int]):
dummy = ListNode(-1)
curr = dummy
for n in l:
curr.next = ListNode(n)
curr = curr.next
return dummy.next
def __init__(self, val=0, next:'ListNode'=None):
self.val = val
self.next = next
def __str__(self) -> str:
result = []
curr = self
while curr:
result.append(curr.val)
curr = curr.next
return ",".join(str(x) for x in result)
# @lc code=start
# class Solution:
# def reverse(self, begin: ListNode, end: ListNode):
# prev = None
# curr = begin
# while True: # todo
# next = curr.next
# curr.next = prev
# if curr == end:
# break
# prev = curr
# curr = next
# def find_n(self, dummy: ListNode, n: int) -> tuple[ListNode, ListNode, ListNode]:
# prev = dummy
# curr = dummy.next
# while n > 1:
# prev = curr
# curr = curr.next
# n -= 1
# return prev, curr, curr.next
# def reverseBetween(self, head: ListNode, l: int, r: int) -> ListNode:
# dummy = ListNode(-1, head)
# prev, left, _ = self.find_n(dummy, l)
# _, right, next = self.find_n(dummy, r)
# self.reverse(left, right)
# left, right = right, left
# prev.next = left
# right.next = next
# return dummy.next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy = ListNode(-1, head)
prev = dummy
curr = dummy.next
n = 0
prev_begin, post_end = None, None
begin, end = None, None
while n < right:
n += 1
next = curr.next
if n == left:
prev_begin = prev
begin = curr
if n == right:
post_end = next
end = curr
if n > left:
curr.next = prev
prev = curr
curr = next
prev_begin.next = end
begin.next = post_end
return dummy.next
# @lc code=end
s = Solution()
print(s.reverseBetween(ListNode.from_arr([1,2,3,4,5]), 2, 4))
print(s.reverseBetween(ListNode.from_arr([1,2,3,4,5]), 1, 5))
print(s.reverseBetween(ListNode.from_arr([1,2,3,4,5]), 3, 5))
print(s.reverseBetween(ListNode.from_arr([1]), 1, 1))
|
e64450c52f65ff365c173d3ec4226c08969d8072 | vim-hjk/python-algorithm | /code/merge_2.py | 910 | 4 | 4 | def mergesort(num):
if len(num) > 1:
mid = len(num) // 2
left = num[:mid]
right = num[mid:]
left_list = mergesort(left)
right_list = mergesort(right)
return merge(left_list, right_list)
else:
return num
def merge(left_list, right_list):
left_idx = 0
right_idx = 0
num = []
while left_idx < len(left_list) and right_idx < len(right_list):
if left_list[left_idx] < right_list[right_idx]:
num.append(left_list[left_idx])
left_idx += 1
else:
num.append(right_list[right_idx])
right_idx += 1
while left_idx < len(left_list):
num.append(left_list[left_idx])
left_idx += 1
while right_idx < len(right_list):
num.append(right_list[right_idx])
right_idx += 1
return num
num = [3, 5, 1, 2, 9, 6, 4, 8, 7]
print(mergesort(num)) |
30918426df8675f94c22725eec6b02ef35510d3b | Foknetics/AoC_2018 | /day11/day11-1.py | 829 | 3.671875 | 4 | def power_level(x, y):
serial_number = 5034
rack_id = x+10
power_level = rack_id*y
power_level += serial_number
power_level = power_level * rack_id
try:
power_level = int(str(power_level)[-3])
except IndexError:
power_level = 0
return power_level - 5
best_cell = (0, 0)
best_power = 0
for x in range(1, 299):
for y in range(1, 299):
total = power_level(x,y) + power_level(x+1, y) + power_level(x+2, y) + \
power_level(x,y+1) + power_level(x+1, y+1) + power_level(x+2, y+1) + \
power_level(x,y+2) + power_level(x+1, y+2) + power_level(x+2, y+2)
if total > best_power:
best_cell = (x, y)
best_power = total
print('The best 3x3 square has the top left fuel cell of', best_cell, 'with', best_power, 'power') |
c1659bf55cf21f40eaf6aff2b2f6fe6b91c016d6 | iriza99/RepoWorkflow | /AnalisisPyhton.py | 689 | 3.578125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
# Read the dataset
athletes_data = pd.read_csv("Forbes Richest Atheletes (Forbes Richest Athletes 1990-2020).csv")
# Group athletes by year and calculate mean earnings for each group
athletes_by_year = athletes_data.groupby('Year')
mean_earnings_by_year = athletes_by_year.mean(numeric_only=True)
# Plot the temporal evolution of the earnings
plt.plot(mean_earnings_by_year.index, mean_earnings_by_year['earnings ($ million)'])
plt.xlabel('Year')
plt.ylabel('Mean earnings ($ million)')
plt.title('Temporal Analysis of the Earnings of the Top 10 Athletes per Year')
plt.savefig('Top10EarningsPerYear.png')
plt.show()
|
b43df81d1e999e1bdad2278727f0bff951884a64 | thiagomachadox/datascience-visualizacaocompython | /datascience_visualization/7_salvarfiguras.py | 745 | 3.71875 | 4 | #Grafico Scatterplot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 7, 1, 0]
#variavel do tamanho dos x no plt.scatter()
z = [30, 40 , 50, 100]
#Variaveis a serem acessadas na plotagem
titulo = "Scatterplot: gráfico de dispersão"
eixox = "Eixo x"
eixoy = "Eixo y"
#Legendas
plt.title(titulo)
plt.xlabel(eixox)
plt.ylabel(eixoy)
#Plotagem
plt.scatter(x,y, label = "pontos", color = "#31b404", marker = "o", s=z) #s recebe z
plt.plot(x,y, label = "linha", color = "k", linestyle = "--")
plt.legend()
#plt.show()
#plt.savefig("figura1.png")
#Para salvar em melhor definiçao:
#plt.savefig("figura1.pdf") #melhor qualidade
plt.savefig("figura1.png", dpi=300) #quanto maior a dpi, melhor a qualidade |
9e1d63c13e5fa7d99a8ac77cec4dfc78bcac4edd | kmark1625/Project-Euler | /p35.py | 1,823 | 3.765625 | 4 | def main():
print num_circular_primes(1000000)
def num_circular_primes(max_num):
count = 0
for i in range(1,max_num):
if is_circular_prime(i):
count += 1
return count
def is_circular_prime(num):
circular = True
rotations = circular_rotations(num)
for num in rotations:
if not is_prime(num):
circular = False
break;
return circular
def circular_rotations(num):
rotations = []
rotations.append(num)
string_num = str(num)
for i in range(1, len(string_num)):
last_char = string_num[-1]
string_num = string_num[:-1]
string_num = last_char + string_num
rotations.append(int(string_num))
return rotations
def is_prime(n):
'''check if an integer n is prime'''
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**.5)+1, 2):
if n % x == 0:
return False
return True
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(6) == False
assert is_prime(7) == True
assert is_prime(8) == False
assert is_prime(9) == False
assert is_prime(10) == False
assert is_prime(11) == True
def test_circular_rotations():
assert circular_rotations(197) == [197, 719, 971]
assert circular_rotations(2193) == [2193, 3219, 9321, 1932]
def test_is_circular_prime():
assert is_circular_prime(197) == True
assert is_circular_prime(3) == True
assert is_circular_prime(37) == True
assert is_circular_prime(19) == False
def test_num_circular_primes():
assert num_circular_primes(100) == 13
def test():
test_is_prime()
test_circular_rotations()
test_is_circular_prime()
test_num_circular_primes()
if __name__ == '__main__':
test()
main() |
a57bed7e8e1807d505ec50d1f1ea915666a53576 | ZhengyangXu/LintCode-1 | /Python/Search a 2D Matrix II.py | 1,452 | 3.9375 | 4 | """
Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.
This matrix has the following properties:
* Integers in each row are sorted from left to right.
* Integers in each column are sorted from up to bottom.
* No duplicate integers in each row or column.
"""
class Solution:
"""
@param matrix: An list of lists of integers
@param target: An integer you want to search in matrix
@return: An integer indicates the total occurrence of target in the given matrix
"""
def searchMatrix(self, matrix, target):
# write your code here
if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
m, n = len(matrix), len(matrix[0])
def searchMatrixHelper(left, top, right, bottom):
if top > bottom or left > right:
return 0
if target < matrix[top][left] or target > matrix[bottom][right]:
return 0
mid, row, result = left + (right - left) / 2, top, 0
while row <= bottom and matrix[row][mid] <= target:
if matrix[row][mid] == target:
result += 1
row +=1
result += searchMatrixHelper(mid + 1, top, right, row - 1)
result += searchMatrixHelper(left, row, mid - 1, bottom)
return result
return searchMatrixHelper(0, 0, n - 1, m - 1)
|
23ccb927a00abafb519db980859ae354fab3080d | Thmyris/COMU-BilimselHesaplama | /Odev2.Root finding, Newton Raphson Method.py | 852 | 3.71875 | 4 | def f(x):
return(x**2-4*x+3)
def dfdx(x):
return (2*x-4)
x = int(input("koke yakin bir x sayisi tahmin edin: "))
if (f(x) == 0): # yani fonksiyona gonderdigimiz x'in
# y degeri 0 ise direk koku bulmusuz demektir.
print("tahmininiz denklemin kokudur")
else:
print("En yakin kok hesaplaniyor...")
for i in range(1000):
tegetde
if(abs(f(temp)-f(xr)) < 0.01):
print("kok bulundu: ", xr)
print("Hesaplama bitene kadar 2ye bolme miktari: ", i+1)
break
if(f(xr) == 0):
print("kok bulundu: ", xr)
print("Hesaplama bitene kadar 2ye bolme miktari: ", i+1)
break
elif(f(xr)*f(x1) < 0): # kok x1 ile xr arasinda
x2 = xr
else: # kok xr ile x2 arasinda
x1 = xr
temp = xr
print(xr)
|
528062e3ad00a55e7f33743dae5280a4fbd30e49 | SergeyMikhaylov21/Test | /training4.py | 279 | 3.6875 | 4 | import re
patt = re.compile('^«[А-ЯЁ]?, [а-яё]*, [1-9]»$')
with open ('C:\\Users\\student\\Desktop\\Китай.txt', 'r', encoding='utf-8') as f:
s = f.read()
words = s.split()
for word in words:
if patt.search(word):
print (word)
|
9e132d0343059d0387378d11cd7c6213a576db76 | matijanjic/XLSXtoPPTX | /XLSXtoPPTX.py | 3,084 | 3.640625 | 4 |
# A script that takes an existing excel file, reads the required columns that hold the info
# (word, sentence, word audio, sentence audio, sentence picture etc.) and arranges it all into a
# pptx presentation. The use case is pretty specific, my wife needed it for her phd experiment.
# Audio files were generated using another script I made that uses the Google text-to-speech
# (gTTS) library that read the words and sentences from a csv file and exported them as .mp3's
from openpyxl import load_workbook
from collections import defaultdict
from slideshow import *
# returns a dictionary of lists where each letter key has a value that is a list of values from that column
# in the worksheet.
def getDictFromXlsx(xlsxFile, colList):
wb = load_workbook(xlsxFile, data_only=True)
ws = wb.active
values = defaultdict(list)
for letter in colList:
column = ws[letter]
for cell in column:
if cell.value != None:
print(cell.column_letter)
values[cell.column_letter].append(cell.value)
return values
def main():
# some constants declared here
xlsxFile = 'excel\spreadsheet_gorilla_learning_pictures_-all.xlsx'
wordSoundFolder = 'sounds\words\\'
sentenceSoundFolder = 'sounds\sentences\\'
pictureFolder = 'images\pictures_learning\\'
# these could be changed to what ever fits your needs, but are column letters that hold the data for the powerpoint
wordTextCol = 'F'
wordSoundCol = 'G'
sentenceSoundCol = 'I'
sentencePictureCol = 'J'
# list of all the columns so they can be searched more easily. If the number of columns were bigger, it would pay off to automate it
colList = ['F', 'G', 'I', 'J']
# create a new instance of the SlideShow class that takes the width and the height in inches
# and the and the slide layout (further explained in the python-pptx documentation
# https://python-pptx.readthedocs.io/en/latest/user/slides.html)
# e.g. SlideShow(16, 9, 6) creates a 16x9 presentation file with a blank slide template (layout number 6)
slideShow = SlideShow(16, 9, 6)
# use the getDictFromXlsx function that returns a filled out dictionary where the keys are the column letters
# and the values are lists that contain the data in those columns.
xlsxDict = getDictFromXlsx(xlsxFile, colList)
numberOfRows = len(list(xlsxDict.values())[0])
# -- MAIN SLIDE LAYOUT --#
# for each row create a following slide layout:
for i in range(numberOfRows):
slideShow.addSlide()
slideShow.addText(80, 'X', 4, 1)
slideShow.addSlide()
slideShow.addText(44, xlsxDict[wordTextCol][i], 4, 1)
slideShow.addSound(wordSoundFolder + xlsxDict[wordSoundCol][i])
slideShow.addSlide()
slideShow.addPicture(pictureFolder + xlsxDict[sentencePictureCol][i], 400)
slideShow.addSound(sentenceSoundFolder + xlsxDict[sentenceSoundCol][i])
# and save it
slideShow.save('test.pptx')
if __name__ == '__main__':
main()
|
5e10e6c3148a4c7722901811788eb24257719622 | GolfettoGuilherme/EstudoPython | /estudo_funcoes.py | 205 | 3.75 | 4 | print("Estudo de funcoes")
def soma(num1, num2):
total = num1 + num2
print(total)
return total
total_soma = soma(100,155)
total_soma_1 = soma(7, 1000)
print(total_soma)
print(total_soma_1)
|
377c0e6d5b65461e706dccc549a7f1e960e30808 | spendyala/deeplearning-docker | /01-PythonAlgorithms/random/ques_1.py | 2,118 | 3.84375 | 4 | '''You have a list of timestamps. Each timestamp is a time when there was a glitch in the network.
If 3 or more glitches happen within one second (duration), you need to print the timestamp of the first glitch in that window.
input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9]
The output list should be:
[2.1, 5.2, 11.3]
Glitch windows: [2.1, 2.5, 2.9, 3.0], [5.2, 5.9, 6.1], [11.3, 11.8, 11.9]
You can't consider [3.6, 3.9] since the number of glitches < 3
A particular timestamp will fall into one window only. So since 3.0 already fell into the first window, it can't fall into the second window.
Try to solve this today we can discuss tomorrow.'''
input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9]
previous_sec = 0
output_list = []
#while input_lst:
# try:
# peak_first = input_lst[0]
# peak_third = input_lst[2]
# if (int(peak_first) == int(peak_third) or
# peak_third < int(peak_first)+1.2):
# current_sec = int(peak_first)
# if previous_sec+1.2 > peak_third:
# previous_sec = peak_third
# input_lst.pop(0)
# continue
# if previous_sec != current_sec:
# output_list.append(peak_first)
# previous_sec = current_sec
# input_lst.pop(0)
# except Exception:
# break
#print(output_list)
input_lst = [2.1, 2.5, 2.9, 3.0, 3.6, 3.9, 5.2, 5.9, 6.1, 8.2, 10.2, 11.3, 11.8, 11.9]
previous = 0
output_lst = []
current_window = []
gitches_window = []
while input_lst:
try:
first_peek = input_lst[0]
third_peek = input_lst[2]
if third_peek <= first_peek+1:
if first_peek <= previous+1:
print(first_peek)
input_lst.pop(0)
continue
previous = first_peek
output_lst.append(previous)
#print('Starting {}, previous {}'.format(first_peek, previous))
except IndexError:
break
input_lst.pop(0)
print(output_lst)
|
e7696743425c10dede99b88f8a4d7039120e5d5a | pakey/leetcode | /Leetcode/spiral_iterator.py | 1,078 | 3.8125 | 4 | # 给定二维数组实现螺形输出
# arrays = [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9, 10, 11, 12],
# ]
# 输出:[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
def myfunc(arrays):
rows = len(arrays)
if rows == 0:
return []
elif rows == 1:
return arrays[0]
else:
cols = len(arrays[0])
if cols == 0:
return []
if cols == 1:
for i in arrays:
return i[0]
else:
l = []
r = []
new_arrays =[]
for i in range(1, rows - 1):
l.append(arrays[i][0])
r.append(arrays[i][-1])
new_arrays.append(arrays[i][1:-1])
return arrays[0] + r + arrays[-1][::-1] + l[::-1] + myfunc(arrays=new_arrays)
if __name__ == '__main__':
arrays = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
# arrays = [
# [1],
# [5],
# [9]
# ]
# arrays = [[1, 2, 3, 4]]
m = myfunc(arrays)
print(m)
|
7f51c7f32b7864714f706236bc58a93499bf3c4a | Combatjuan/adventofcode | /2018/day02/day2a.py | 1,044 | 3.84375 | 4 | #!/usr/bin/env python3
DEBUG = False
def debug_print(s):
print(s)
def check(s):
"""Returns two booleans, the first is whether there are character twins. The second is whether there are character triplets."""
t = sorted(s)
t.append("\n")
has_twins = False
has_triplets = False
run_count = 1
prev = None
for x in t:
if x == prev:
run_count = run_count + 1
else:
if run_count == 2:
has_twins = True
elif run_count == 3:
has_triplets = True
run_count = 1
prev = x
prev = x
debug_print("{}: {} {}".format(s, has_twins, has_triplets))
return has_twins, has_triplets
twins_count = 0
triplets_count = 0
with open("input.txt") as the_file:
for line in the_file:
s = line.strip()
has_twins, has_triplets = check(s)
if has_twins: twins_count = twins_count + 1
if has_triplets: triplets_count = triplets_count + 1
print(twins_count * triplets_count)
|
d6f97f1b3ccec803b57faaf2ea543c0437016e73 | 24sh1999/Imaportant | /Cousion_fo_binaryTree.py | 1,737 | 3.5625 | 4 | ## Problem Name: Cousion in Binary Tree(leetcode 30 day challenge)
##
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def dfs(root, depth, parent):
if not root or len(result) == 2:
return
if root.val == x or root.val == y:
result.append([depth, parent])
dfs(root.left, depth + 1, root)
dfs(root.right, depth + 1, root)
result = []
dfs(root, 0, None)
######################################################################3
######This Was my solution to the above Problem
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
xValue = []
yValue = []
depth = 0
Parent = None
if root == None:
return False
self.Buttom(root, x, y, 0, None, xValue, yValue)
return xValue[0][0] == yValue[0][0] and xValue[0][1] != yValue[0][1]
def Buttom(self, root, x, y, depth, Parent, xValue, yValue):
if root is None:
return None
if root.val == x:
xValue.append((depth, Parent))
if root.val == y:
yValue.append((depth, Parent))
self.Buttom(root.left, x, y, depth + 1, root, xValue, yValue)
self.Buttom(root.right, x, y, depth + 1, root, xValue, yValue)
|
a0a0ed5db95408a3963dffb4100a4ab71a2627a3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/187/usersdata/265/65010/submittedfiles/al1.py | 123 | 3.9375 | 4 | # -*- coding: utf-8 -*-
c = float(input('digite o valor da temperatura em celcius: '))
f = ((9*c)+160)/5
print('%.2f' %f)
|
edfaa589b3233ab9b054ff973d69dd2215c0c1fa | sakurasakura1996/Leetcode | /leetcode_weekly_competition/201weekly_competition/problem1554_整理字符串.py | 1,687 | 3.734375 | 4 | """
1544. 整理字符串
给你一个由大小写英文字母组成的字符串 s 。
一个整理好的字符串中,两个相邻字符 s[i] 和 s[i + 1] 不会同时满足下述条件:
0 <= i <= s.length - 2
s[i] 是小写字符,但 s[i + 1] 是相同的大写字符;反之亦然 。
请你将字符串整理好,每次你都可以从字符串中选出满足上述条件的 两个相邻 字符并删除,直到字符串整理好为止。
请返回整理好的 字符串 。题目保证在给出的约束条件下,测试样例对应的答案是唯一的。
注意:空字符串也属于整理好的字符串,尽管其中没有任何字符。
示例 1:
输入:s = "leEeetcode"
输出:"leetcode"
解释:无论你第一次选的是 i = 1 还是 i = 2,都会使 "leEeetcode" 缩减为 "leetcode" 。
示例 2:
输入:s = "abBAcC"
输出:""
解释:存在多种不同情况,但所有的情况都会导致相同的结果。例如:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
示例 3:
输入:s = "s"
输出:"s"
提示:
1 <= s.length <= 100
s 只包含小写和大写英文字母
"""
# 感觉每次这种题目我都没怎么想出过可以用栈来解决
class Solution:
def makeGood(self, s: str) -> str:
if not s:
return s
while True:
flag = True
for i in range(len(s)-1):
if abs(ord(s[i]) - ord(s[i+1])) == 32:
s=s[:i]+s[i+2:]
flag = False
break
if flag:
return s
return s
solu = Solution()
s = "leEeetcode"
ans = solu.makeGood(s)
print(ans)
|
c653b82f51e3f15a3d9259180c2e82e611be5cbe | alesandroninazarena/frro-soporte-2019-06 | /Practico-01/ejercicio-14.py | 1,031 | 4.15625 | 4 | #Programe un algoritmo recursivo que encuentre la salida de un laberinto.
lab = [[True, False, True, True],
[False, False, True, False],
[True, True, True, False],
[True, False, True, True]]
def salida_laberinto(fila, columna):
if (fila == 3) and (columna ==1):
print("Salida encontrada en posición: ", str(fila), ",", str(columna))
elif (lab[fila][columna] == True):
print("Obstaculo en posición: ", str(fila) + ",", str(columna))
return False
elif (lab[fila][columna] == False):
print("Avanza a la posición: ", str(fila), ",", str(columna))
lab[fila][columna] = 2
elif (lab[fila][columna] == 2):
print("Ya pasó por la posición: ", str(fila), ",", str(columna))
return False
salida = (salida_laberinto(fila+1, columna) or salida_laberinto(fila, columna+1) or salida_laberinto(fila-1, columna) or salida_laberinto(fila, columna-1))
if salida:
return True
return False
a = 0
b = 1
salida_laberinto(a, b)
|
8146cf27c4f9456b13ea359a574bff98b8b9a21c | ljyadbefgh/python_test | /test1/test2_1.py | 75 | 3.703125 | 4 | #if语句
a=5
if a>10:
print("a大于10")
else:
print("a小于10")
|
d41c527cf5ea31817dca7ad4fe99ca1989f6c2ea | bruiken/ModelChecking | /variableorderings/baseordering.py | 730 | 3.96875 | 4 | class Ordering:
"""
Abstract class for variable ordering.
Implementations should implement the "order_variables" function.
"""
def __init__(self, ordering_type):
"""
Constructor for a variable ordering.
:param ordering_type: type of the ordering (algorithm used)
"""
self._ordering_type = ordering_type
def order_variables(self, fault_tree):
"""
Returns a variable ordering that just takes the order of
variables of in the Fault Tree.
"""
return list(fault_tree.get_basic_events().keys())
def get_ordering_type(self):
"""
Returns the name of the ordering.
"""
return self._ordering_type
|
ab2c0267f4a8588da803034ab985fc31da2fac3f | frankschmitt/advent_of_code | /2022/01-calorie_counting/CalorieCounting.py | 1,150 | 3.515625 | 4 | from pipe import Pipe, map, sort, take
class Elf:
calories = []
def __init__(self, calories = []):
self.calories = calories
self.sum_calories = sum(self.calories)
@Pipe
def split_elves(iterable):
e = []
for line in iterable:
if line == "\n":
yield Elf(e)
e = []
else:
e.append(int(line))
yield Elf(e)
class CalorieCounting:
elves = []
def __init__(self, elves = []):
self.elves = elves
def read_input_file(filename):
with open(filename) as f:
lines = f.readlines()
elves = list(lines
| split_elves
)
cc = CalorieCounting(elves)
return cc
def sum_top_n_scores(self, n):
return sum(self.elves
| map(lambda e: e.sum_calories)
| sort(reverse = True)
| take(n)
)
def solve_part_I(self):
return self.sum_top_n_scores(1)
def solve_part_II(self):
return self.sum_top_n_scores(3)
if __name__ == '__main__':
cc = CalorieCounting.read_input_file('input.txt')
print("{} {}".format(cc.solve_part_I(), cc.solve_part_II()))
|
d1ea58bfdf46067949d310551e9b3fd80f4ba0bd | 1mozolacal/Machine_Learning_Challenge | /refCode/testPlot.py | 749 | 3.75 | 4 | # example from https://python-graph-gallery.com/122-multiple-lines-chart/
# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Data
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21) })
print(df)
# multiple line plot
plt.plot( 'x', 'y1','', data=df, marker='o', linewidth=4)
plt.plot( 'x', 'y2','', data=df, marker='1', linewidth=2)
plt.plot( 'x', 'y3','', data=df, marker='', linewidth=2, linestyle='dashed', label="toto")
plt.legend()
plt.show()
'''
The third parameter is the formating string, it is being passed as black to suppress warning message
'''
# marker reference
# https://matplotlib.org/api/markers_api.html |
4d7e78b8b438933d6d60b9425e958c12524edcb5 | MrMohammadY/dollar-toman-exchanger | /main.py | 401 | 3.90625 | 4 | from constants import dollar_to_toman
def price_menu():
show_menu = True
while show_menu:
number_of_dollars = int(input('how much dollar you have?\n enter 0 to quit\n'))
if not number_of_dollars:
show_menu = False
result = dollar_to_toman(dollar = number_of_dollars)
print(f"{number_of_dollars} dollar = {result} toman")
price_menu() |
ac13f29f084aa3a4b13c627ac33cdb5c77ff781b | graytoli/pdxcode_labs | /python_labs/pdx_lab11.py | 628 | 4.1875 | 4 | # Lab 11: Simple Calculator, version 1
operator = input('What operation would you like to perform? ').strip()
operand1 = float(input('What is the first number? ').strip())
operand2 = float(input('What is the second number? ').strip())
if operator == '+':
solution = operand1 + operand2
elif operator == '-':
solution = operand1 - operand2
elif operator in ['*', 'x']:
solution = operand1 * operand2
elif operator == '/':
solution = operand1 / operand2
else:
solution = 'Invalid entry.'
if solution == 'Invalid entry.':
print(solution)
else:
print(f'{operand1} {operator} {operand2} = {solution}')
|
36d9c23461c7ccce151b5b06fc746888889a0ae6 | mryyomutga/TechnicalSeminar | /src/textbook/chapter6/chapter6-1/chapter6-1-3.py | 922 | 4.125 | 4 | # -:- coding: utf-8 -*-
# オブジェクト指向について3
class BMI:
"""BMIを計算する"""
def __init__(self, weight, height):
"""コンストラクタ"""
self.weight = weight
self.height = height
self.calcBMI()
def calcBMI(self):
"""BMIを計算する"""
h = self.height / 100
self.bmi = self.weight / (h ** 2)
def printJudge(self):
"""結果の表示"""
print("---")
print("BMI =", self.bmi)
b = self.bmi
if b < 18.5:
print("痩せ型")
elif b < 25:
print("標準")
elif b < 30:
print("肥満(軽)")
else:
print("肥満(重)")
p1 = BMI(weight = 65, height = 170)
p1.printJudge()
p1 = BMI(weight = 76, height = 165)
p1.printJudge()
p1 = BMI(weight = 50, height = 180)
p1.printJudge()
|
5f5ba40c58089852a49998739f358e3e02ac3f13 | koten0224/Leetcode | /1137.n-th-tribonacci-number/n-th-tribonacci-number.py | 183 | 3.609375 | 4 | class Solution:
def tribonacci(self, n: int) -> int:
a,b,c=0,1,1
if n<3:return (a,b,c)[n]
for _ in range(2,n):
a,b,c=b,c,a+b+c
return c |
2c962fc4dc6957ce1ab4bc9cd18e67171ad91662 | Jfprado11/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 141 | 3.578125 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_list = [list(map(lambda x: x * x, x)) for x in matrix]
return (new_list)
|
d371488a2a4a7cf643d377a3d15176e37535dc55 | satori-koishi/Spider_All | /GitImgcaptcha/Calculation.py | 1,274 | 3.71875 | 4 | def calculation(expression):
ChartDict = {'零': '0', '一': '1', '二': '2', '三': '3', '四': '4',
'五': '5', '六': '6', '七': '7', '八': '8', '九': '9',
'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5',
'6': '6', '7': '7', '8': '8', '9': '9'}
test = expression
symbol = test[1]
zz = ChartDict.keys()
result = ''
if symbol == '+':
symbol = '+'
if symbol == '一':
symbol = '-'
number = ChartDict[test[0]]
if test[2] in zz:
number2 = ChartDict[test[2]]
else:
try:
number2 = ChartDict[test[-1]]
except:
number2 = 1
if symbol == 'x' or symbol == '乘' or symbol == 'X':
result = int(number) * int(number2)
elif symbol == '+' or symbol == '加':
result = int(number) + int(number2)
elif symbol == '-' or symbol == '减' or symbol == '-':
result = int(number) - int(number2)
elif symbol == '✲':
result = int(number) * int(number2)
elif symbol == '除':
try:
result = int(number) // int(number2)
except:
result = int(number) + int(number2)
print(result)
return result
calculation('3除零=')
|
12c7065f8de6b34641092c344ec4a7ed9680e7d6 | Ritvik-Sapra/IDEA2 | /code.py | 1,829 | 3.828125 | 4 | import json
# Function to convert txt file to json
def json_converter(filename):
# Creating an empty dictionary
dict = {}
firstPass = True
out_file = open('output.json', 'w')
with open(filename) as fh:
# Processing meta data
for line in fh:
# Starting of meta data
if((line == "---\n" and firstPass) or line == '\n'):
firstPass = False
continue
# Ending of meta data
elif(line == "---\n" and firstPass == False):
break
# Spliting the line for obtaining key-value pairs
key, value = line.strip().split(None, 1)
# Removing "" from the key
key = key[:-1]
if(value[0] == "\""):
value = value[1:-1]
if(key == "tags"):
# Converting 'tags' into list
value = list(value.split(", "))
dict[key] = value
# Meta data completely proccessed
# Now processing 'short-content'
for line in fh:
if(line == '\n'):
continue
elif(line == "READMORE\n"):
break
dict['short-content'] = line[:-1]
# Now processing 'content'
content_str = ""
for line in fh:
if(line == '\n'):
content_str += " "
else:
content_str += line[:-1]
dict['content'] = content_str
# Writing 'dict' to json file
json.dump(dict, out_file, indent = 4, sort_keys = False)
# Closing output file
out_file.close()
# Main function
def main():
filename = 'input.txt'
json_converter(filename)
print("Converted to JSON successfully!")
# Calling the main() for starting the execution
if __name__ == '__main__': main()
|
c216c1c29270c9e66a64c4efe91777ea2f635bfd | Dawinia/LeetCode | /Array/605. 种花问题.py | 418 | 3.6875 | 4 | class Solution:
def canPlaceFlowers(self, flowerbed, n: int) -> bool:
size, i = len(flowerbed), 0
cnt = 0
while i < size:
if flowerbed[i] == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == size - 1 or flowerbed[i + 1] == 0):
flowerbed[i] = 1
cnt += 1
if cnt >= n:
return True
i += 1
return False |
67f45200f327edc790034183d06e4c17e4120528 | wissenschaftler/PythonChallengeSolutions | /Level 2/ocr.py | 292 | 3.53125 | 4 | # The URL of this level: http://www.pythonchallenge.com/pc/def/ocr.html
strFile = open("ocr.txt",'r') #ocr.txt is where the data is
wholeStr = strFile.read()
fnlStr = []
for i in wholeStr:
if (65 <= ord(i) <= 90) or (97 <= ord(i) <= 122):
fnlStr.append(i)
print ''.join(fnlStr)
|
c63f1d78a9ddff61c1cf24a68b1e734a74d3cb42 | datim/tools | /file_sorter.py | 9,417 | 3.875 | 4 | #!/bin/python
#
# This program sorts files into directorys by year. It also re-names the files to put a date and timestamp at the front
import sys
import os
import argparse
import time
import shutil
import datetime
import pdb
import hashlib
######################################
class FileSorter:
""" Sorts and copies files into destination directories by year. Discovers duplicates by checksum """
DUPLICATE_PATH = "duplicates"
def __init__(self):
""" initialize the destination directory """
self.total_file_count = 0
self.duplicates_count = 0
self.yearCount = {}
self.duplicateYearCount = {}
def sortFiles(self, source_dirs, dest_dir, tag, by_month, test_only):
""" Initialize the sorting of files by year """
if test_only:
print "Test only mode"
file_metadata_dict = self._parseFiles(source_dirs)
# create destination directories
st = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H-%M-%S')
dest_dir = os.path.join(os.path.dirname(dest_dir), st + "_" + os.path.basename(dest_dir))
# create duplicate path directory
duplicate_dir = os.path.join(dest_dir, self.DUPLICATE_PATH)
# we've finished reading every file. Now copy and re-name them
self._transferFiles(file_metadata_dict, dest_dir, duplicate_dir, tag, test_only)
# print statistics when we're done
self._printStatistic()
def _parseFiles(self, source_dirs):
""" Parse each file in the list of source directories for meta data """
file_list = []
file_metadata_dict = {}
files_dict = {}
# validate every source directory
for source in source_dirs:
if not os.path.exists(source):
raise Exception("Source directory %s does not exist!" % source)
# read all files in the nested directory structure
for root, dirs, files in os.walk(source):
# save metadata for each file in the discovered in the file path
for name in files:
full_file_path = os.path.join(source, root, name)
file_list.append(full_file_path)
file_count = len(file_list)
print "Discovered %d files" % file_count
count = 0
for full_file_path in file_list:
count += 1
sys.stdout.write("Parsing file %d of %d \r" % (count, file_count))
sys.stdout.flush()
# extract the file's meta data
year, create_datetime, file_checksum = self._extractFileMetaData(full_file_path)
# save metadata for the file
file_metadata_dict[full_file_path] = {"year" : year, "create_dt" : create_datetime, "chksum" : file_checksum}
return file_metadata_dict
def _extractFileMetaData(self, file_name):
""" For each file path, internally catalog the file by getting its timestamp and checksum """
# FIXME -log it
# print "reading file %s\n" % file_name
# get the hash of the file, used for detecting duplicates later
file_checksum = self._getFileChecksum(file_name)
# get the file creation time stamp
create_time = os.path.getmtime(file_name)
create_datetime = datetime.datetime.fromtimestamp(create_time)
# get the create year
create_year = str(create_datetime.year)
return create_year, create_datetime, file_checksum
def _getFileChecksum(self, file_name_and_path):
""" Generate the checksum of a file """
# algorithm from http://pythoncentral.io/hashing-files-with-python/
hasher = hashlib.md5()
with open(file_name_and_path, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
return hasher.hexdigest()
def _transferFiles(self, file_metadata_dict, dest_dir, duplicate_dir, tag, test_only):
""" copy files from a source location to the destiation location. Copy duplicates
to a duplicate directory """
# look for duplicates
checksum_list = []
count = 0
file_count = len(file_metadata_dict.keys())
pdb.set_trace()
# iterate through every file
for file_path, metadata in file_metadata_dict.iteritems():
create_ts = metadata.get("create_dt")
checksum = metadata.get("chksum")
year = metadata.get("year")
# create the new directory for the year
year_dir_name = os.path.join(dest_dir, year, tag)
if not os.path.exists(year_dir_name):
os.makedirs(year_dir_name)
# generate the destination file name
dest_file_name = create_ts.strftime("%Y%m%d_%H%M%S") + "_" + os.path.basename(file_path)
# check whether this file has been encountered before
if checksum in checksum_list:
## This is a duplicate file. Move it to the duplicate directory ##
if not os.path.exists(duplicate_dir):
os.makedirs(duplicate_dir)
# copy the file to the duplicate directory
dest_file_name = os.path.join(duplicate_dir, dest_file_name)
# lower case file names only
dest_file_name = dest_file_name.lower()
# write statistics
self._recordDuplicate(year)
else:
## Copy the file
checksum_list.append(checksum)
# file is not a duplicate, copy it
dest_file_name = os.path.join(year_dir_name, dest_file_name)
# lower case file names only
dest_file_name = dest_file_name.lower()
# write statistics
self._recordCopy(year)
# print status
count += 1
sys.stdout.write("Copying file %d of %d \r" % (count, file_count))
sys.stdout.flush()
if not test_only:
# Copy the file to the destination
shutil.copyfile(file_path, dest_file_name)
def _recordDuplicate(self, year):
""" Record statistics about duplicate files """
self._recordStatistic(year, True)
def _recordCopy(self, year):
""" Record statistics about successful copies """
self._recordStatistic(year, False)
def _recordStatistic(self, year, duplicate):
""" record statistics about the copying of files """
# increment total count
self.total_file_count += 1
if duplicate:
# this was a duplicate file. Record it
self.duplicates_count += 1
# track duplicate by year
if year in self.duplicateYearCount:
self.duplicateYearCount[year] += 1
else:
# first duplicate of this year
self.duplicateYearCount[year] = 1
else:
# create a year statistic directory if it doesn't exist
if year in self.yearCount:
self.yearCount[year] += 1
else:
# first file of this year
self.yearCount[year] = 1
def _printStatistic(self):
print "\n============================================================================"
print "Total files organized: %d" % self.total_file_count
for year, count in self.yearCount.iteritems():
print " For year %s: %d" % (year, count)
# print duplicate statistics
print "Total duplicates: %d" % self.duplicates_count
for year, count in self.duplicateYearCount.iteritems():
print " For year %s : %d" % (year, count)
print "============================================================================"
def defineArgs(parser):
""" Set the arguments of the arg parser """
parser.add_argument('-d', '--dest', required=False, default="./parse_output", help='the destination directory to write files to')
parser.add_argument('-m', '--month', required=False, action='store_true', help='if set, organize files by month in addition to year')
parser.add_argument('-l', '--label', required=False, default="mobile", help='the label to apply to result directories')
parser.add_argument('source_dirs', nargs='+', help='the source directories')
parser.add_argument('-t', '--test', required=False, action='store_true', help='test only')
def main():
print "Sorting files"
parser = argparse.ArgumentParser(description = "Sort files into directories by year and optionally by month")
defineArgs(parser)
# parse the arguments
args = parser.parse_args()
sorter = FileSorter()
sorter.sortFiles(args.source_dirs, args.dest, args.label, args.month, args.test)
if __name__ == "__main__":
main() |
c434a7faff005b69e03c49e16c3681a288b91940 | jinliangyu/LeetCode | /137. Single Number II.py | 1,298 | 3.921875 | 4 | """
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"""
# Time: O(n)
# Space: O(1)
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
one, two = 0, 0
for x in nums:
one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one)
return one
class Solution2(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
one, two = 0, 0
for x in nums:
one = (one ^ x) & ~two
two = (two ^ x) & ~one
return one
# easy to understand
class Solution3(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
one, two, three = 0, 0, 0
for x in nums:
two |= one & x
one ^= x
three = one & two
one &= ~three
two &= ~three
print one, two, three
return one
if __name__ == '__main__':
nums = [1,2,2,1,2,3,3,1,5,3]
print Solution3().singleNumber(nums)
|
fe4f71cf1194e0df8507cd7b654da1ca23b2d6b0 | dankoga/URIOnlineJudge--Python-3.9 | /URI_1171.py | 380 | 3.5625 | 4 | if __name__ == '__main__':
number_freq = dict()
data_size = int(input())
for _ in range(data_size):
n = int(input())
if n in number_freq:
number_freq[n] += 1
else:
number_freq[n] = 1
for number, freq in [(x[0], x[1]) for x in sorted(number_freq.items())]:
print('{} aparece {} vez(es)'.format(number, freq))
|
7240c24b4748df9dfb107d62dabd25b23ac790b6 | daniel-reich/ubiquitous-fiesta | /H3t4MkT9wGdL9P6Y3_18.py | 173 | 4.0625 | 4 |
def oddish_or_evenish(num):
total = 0
for i in str(num):
total += int(i)
if total % 2 == 0:
return 'Evenish'
else:
return 'Oddish'
|
15c7409661d31ed26dacd6bdd58bd817a39637e2 | siddharth-mallappa/1BM17CS103 | /P2a_SearchList.py | 290 | 3.859375 | 4 | lst1=[]
def check(num):
if num in lst1:
return True
return False
n=int(input("Enter the number of elements in the list"))
for i in range(0,n):
ele=int(input())
lst1.append(ele)
key=int(input("Enter the search element"))
res=check(key)
print(res)
|
8ca928328c372128d344e31dc18e3d5a488d976a | rickandersonaia/ud036_StarterCode | /media.py | 1,230 | 3.765625 | 4 | import webbrowser
class Movie():
""" This class defines a movie object and displays movies in a browser
def __init__() takes 6 parameters
self -
movie_title - the title of the movie - what?!
Blah, blah, blah, all the rest of this documentation is redundant because
the code is self documenting. More documentation than the first line
simply makes the code less maintainable.
So, I know I'm just a student but the amount of documentation suggested by
http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
is absurd given that you understand how classes work and all of the
variable and method names are descriptive.
I still stand by my original as the best level of documentation"""
VALID_RATINGS = ["G", "PG", "PG-13", "R", "NC-17"]
def __init__(self, movie_title, mpaa_rating, movie_story_line,
poster_image, trailer_youtube):
self.title = movie_title
self.movie_story_line = movie_story_line
self.mpaa_rating = mpaa_rating
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube)
|
8d2cdb511765122b12d9b2550e31bbe30a5ab4b5 | Se7enquick/Python-HW | /HW5/hw5.1.py | 739 | 3.5625 | 4 | '''def lower(a): #ex 1
return a.lower()
def upper(b):
return b.upper()
list1 = ['LOWER']
list2 = ['upper']
result1 = list(map(lower, list1))
result2 = list(map(upper, list2))
print(result1, result2)
def square(num): #ex 2
for x in range (2, num):
if num % x == 0:
return '.'
return num ** 2
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
square_nums = list(map(square, numbers))
print(square_nums)
file = open('file.txt', 'r')
f = file.read()
def count_word(word):
if word in total_count:
total_count[word] += 1
else:
total_count[word] = 1
total_count = {}
list(map(lambda x: count_word(''.join(filter(str.isalpha, x.lower()))), f.split()))
print(total_count)
|
a5ee9185ac4c0f21909aae7851ccf6b5b74dfd69 | abhinai96/Python_conceptual_based_programs | /datastructures/Lists/sort using without inbult function.py | 177 | 3.609375 | 4 | lst=[5,2,3,4,1]
for i in range(len(lst)):
min_val=min(lst[i:])
min_index=lst.index(min_val)
lst[i],lst[min_index]=lst[min_index],lst[i]
print(lst)
|
c42d55490407bfcfd3a591030db63cd5be9b2b58 | kmgowda/kmg-leetcode-python | /find-and-replace-in-string/find-and-replace-in-string.py | 768 | 3.65625 | 4 | // https://leetcode.com/problems/find-and-replace-in-string
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
d ={}
for i, ind in enumerate(indexes):
d[ind]=[sources[i], targets[i]]
start = 0
out=""
for ind in sorted(d.keys()):
out+=S[start:ind]
src, dst = d[ind]
if src == S[ind:ind+len(src)]:
out+=dst
else:
out+=S[ind:ind+len(src)]
start = ind+len(src)
out+=S[start:]
return out |
7f73d3f4fb8e15af1c22ed96a4b2818edf625988 | Christopher-Cannon/python-docs | /Example code/25 - class.py | 484 | 4 | 4 | # Define person class
class person:
def __init__(self, first, last):
self.first, self.last = first, last
def return_full_name(self):
return "{} {}".format(self.first, self.last)
# Get names from user
first_name = str(input("What is your first name? -> "))
last_name = str(input("What is your last name? -> "))
# Instantiate class
instance = person(first_name, last_name)
# Print full name of person instance
name = instance.return_full_name()
print(name)
|
338538af142456f1907d3b0476148e4a38862707 | stvnc/Python-Project | /Modul01/day03/umurBudiAndi.py | 619 | 3.546875 | 4 | '''
Rasio umur Budi dan Andi adalah 4:10
Total umur keduanya adalah 49
Budi = 4/10 Andi
Andi + 4/10 Andi = 49 ----- x10
10 Andi + 4 Andi = 490
14 Andi = 490
Andi = 35
Andi + Budi = 49
35 + Budi = 49
Budi = 14
2 tahun lagi?
Andi + 2 = 37
Budi + 2 = 16
'''
rasioAndi = 4
rasioBudi = 10
totalUmur = 49
umurAndi = (totalUmur*rasioAndi)/(rasioAndi+rasioBudi)
print(f'Umur Andi: {umurAndi}')
umurBudi = (totalUmur*rasioBudi)/(rasioAndi+rasioBudi)
print(f'Umur Budi: {umurBudi}')
print(f'Umur Andi dan Budi 2 tahun yang akan mendatang: {umurAndi+2}, {umurBudi+2}')
|
de1dfae1c63ad672645df6b3a675c779e6ec8c79 | luhao2013/Algorithms | /offer/32.从1到n整数中1出现的次数.py | 1,538 | 3.765625 | 4 | """
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?
为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。
ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
"""
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
if n <= 0:
return 0
if n < 10:
return 1
digit = self.get_digits(n) # 位数
high = int(str(n)[0]) # 最高位
low = n - high * 10 ** (digit - 1) # 去掉最高位的低位
# 如果是21345,先考虑四位数,再考虑1346到9999四位数的,剩下就是递归了
# 最高位1的个数
numFirstDigit = 0
# 假设n是112345
if high == 1:
numFirstDigit = low + 1
# 假设最高位大于1
else:
numFirstDigit = 10 ** (digit - 1)
# numOtherDigit是1346到21345除了第一位之外的数位中的数目,有两万个,所以可以这么乘
numOtherDigits = high * (digit - 1) * 10 ** (digit - 2)
numRecursive = self.NumberOf1Between1AndN_Solution(low)
return numFirstDigit + numOtherDigits + numRecursive
def get_digits(self, n):
count = 0
while n:
n = n // 10
count += 1
return count
|
3963cb955a88492c0be78848ca6f3e87765d2b9c | jettthecoder/Cool-Python-Projects | /Email Validator.py | 349 | 4.5 | 4 | print("Email Validator")
email = input("Enter Your Email: ")
valid_email_domains = ["gmail.com", "hotmail.com", "aol.com", "ymail.com"]
name, domain = email.split("@")
if domain in valid_email_domains:
print(f"Hello {name} you have a valid domain name of {domain}")
else:
print(f"Hello {name} you have a less known domain name of {domain}")
|
3a5558d313dfd7bd9e0a6968cff75c52a635c0dc | Dzhevizov/SoftUni-Python-Advanced-course | /File Handling - Exercise/03. File Manipulator/solution.py | 1,092 | 3.59375 | 4 | import os
command_data = input()
while not command_data == "End":
command_data = command_data.split("-")
command = command_data[0]
if command == "Create":
file_name = command_data[1]
file = open(file_name, "w")
file.close()
elif command == "Add":
file_name = command_data[1]
content = command_data[2]
with open(file_name, "a") as file:
file.write(f"{content}\n")
elif command == "Replace":
file_name = command_data[1]
old_string = command_data[2]
new_string = command_data[3]
if os.path.exists(file_name):
with open(file_name, "r") as file:
data = file.read()
with open(file_name, "w") as file:
file.write(data.replace(old_string, new_string))
else:
print("An error occurred")
elif command == "Delete":
file_name = command_data[1]
if os.path.exists(file_name):
os.remove(file_name)
else:
print("An error occurred")
command_data = input()
|
7e182f73008c97658b5a2208dd45cc4ddb56b782 | vlikevanilla/drawbot_examples | /floating_bezier_lines.py | 4,386 | 3.859375 | 4 | ##############################
# Draw Wiggles using Drawbot #
##############################
"""
Script by Roberto Arista, you can find the related tutorial here: https://medium.com/@roberto_arista/how-to-draw-a-wiggle-between-two-points-with-python-and-drawbot-788006c18fb0
You can find drawbot here: http://www.drawbot.com/
Code distributed with no guarantee, use at your own risk
"""
### Modules
from math import radians, atan2, sqrt, sin, cos
from collections import namedtuple
### Constants
BLACK = (0, 0, 0)
Point = namedtuple('Point', ['x', 'y'])
### Function & procedures
def calcAngle(pt1, pt2):
return atan2((pt2.y - pt1.y), (pt2.x - pt1.x))
def calcDistance(pt1, pt2):
return sqrt((pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2)
def calcWiggle(pt1, pt2, waveLength, waveHeight, curveSquaring=.57, polarity=1):
assert 0 <= curveSquaring <= 1, 'curveSquaring should be a value between 0 and 1: {}'.format(curveSquaring)
assert waveLength > 0, 'waveLength smaller or equal to zero: {}'.format(waveLength)
diagonal = calcDistance(pt1, pt2)
angleRad = calcAngle(pt1, pt2)
howManyWaves = diagonal//int(waveLength)
waveInterval = diagonal/float(howManyWaves)
maxBcpLength = sqrt((waveInterval/4.)**2+(waveHeight/2.)**2)
bcpLength = maxBcpLength*curveSquaring
bcpInclination = calcAngle(Point(0,0), Point(waveInterval/4., waveHeight/2.))
wigglePoints = [pt1]
prevFlexPt = pt1
for waveIndex in range(0, int(howManyWaves*2)):
bcpOutAngle = angleRad+bcpInclination*polarity
bcpOut = Point(prevFlexPt.x+cos(bcpOutAngle)*bcpLength, prevFlexPt.y+sin(bcpOutAngle)*bcpLength)
flexPt = Point(prevFlexPt.x+cos(angleRad)*waveInterval/2., prevFlexPt.y+sin(angleRad)*waveInterval/2.)
bcpInAngle = angleRad+(radians(180)-bcpInclination)*polarity
bcpIn = Point(flexPt.x+cos(bcpInAngle)*bcpLength, flexPt.y+sin(bcpInAngle)*bcpLength)
wigglePoints.append((bcpOut, bcpIn, flexPt))
polarity *= -1
prevFlexPt = flexPt
return wigglePoints
def drawCurvesSequence(wigglePoints):
myBez = BezierPath()
myBez.moveTo(wigglePoints[0])
for eachBcpOut, eachBcpIn, eachAnchor in wigglePoints[1:]:
myBez.curveTo(eachBcpOut, eachBcpIn, eachAnchor)
myBez.endPath()
drawPath(myBez)
def invertPoints(pt1, pt2):
newPt1 = Point((canvasSize-pt2.x), pt2.y)
newPt2 = Point((canvasSize-pt1.x), pt1.y)
return newPt1, newPt2
def createXSlider():
"""made this double the length because I can't think of a better way now"""
xSlider = []
for i in range(int(nFrames/4)):
xSlider.append(i)
for i in reversed(range(int(nFrames/4))):
xSlider.append(i)
for i in range(int(nFrames/4)):
xSlider.append(-i)
for i in reversed(range(int(nFrames/4))):
xSlider.append(-i)
for i in range(int(nFrames/4)):
xSlider.append(i)
for i in reversed(range(int(nFrames/4))):
xSlider.append(i)
for i in range(int(nFrames/4)):
xSlider.append(-i)
for i in reversed(range(int(nFrames/4))):
xSlider.append(-i)
return xSlider
# variables
waveLength = 16
waveHeight = 75
curveSquaring = .5
polarity = 1
### Instructions
canvasSize = 400
nFrames = 100
# create the invidividual frame adjustments before we apply them to each frame
xSlider = createXSlider()
for frame in range(nFrames):
newPage(canvasSize, canvasSize)
frameDuration(1/20)
fill(0)
rect(0, 0, canvasSize, canvasSize)
strokeWidth(2)
stroke(1)
fill(None)
# adjustments
waveHeight += xSlider[frame]/20
curveSquaring += (xSlider[frame]/5000)
if curveSquaring > 1:
curveSquaring = 1
elif curveSquaring < 0:
curveSquaring = 0
for i in range(50, 400, 50):
### Variables
# XXX Need to play with the (i/10) to and adjust the speed
pt1 = Point(50-xSlider[frame]+(i/10), i)
pt2 = Point(150-xSlider[frame]+(i/10), i+10)
wigglePoints = calcWiggle(pt1, pt2, waveLength, waveHeight, curveSquaring, polarity)
drawCurvesSequence(wigglePoints)
invertPt1, invertPt2 = invertPoints(pt1, pt2)
wigglePoints_inverted = calcWiggle(invertPt1, invertPt2, waveLength, waveHeight, curveSquaring, -polarity)
drawCurvesSequence(wigglePoints_inverted)
saveImage("~/tmp/drawbot/lines40.gif")
|
440c08735d36b094209f0dee6063421244ab2dd6 | chelsea-banke/p2-25-coding-challenges-ds | /Exercise_50.py | 416 | 4 | 4 | # Create a function that will receive n as argument and return an array of n
# random numbers from 1 to n. The numbers should be unique inside the array.
import random
def array_of_random_numbers(n):
result = []
count = 0
while count < n:
x = random.randint(1, n)
if x not in result:
result.append(x)
count += 1
return result
print(array_of_random_numbers(10)) |
2061fc140a1a90e7f722eb58a26e6e952399b591 | CaMeLCa5e/Notes-on-functions | /BuiltInFunc.py | 4,815 | 3.8125 | 4 | """
Standard Library Built-in functions
"""
abs()
#Returns absolute value
all()
Return True if all elements in iterable are True
def all(iterable)
for element in interable:
if not element:
return False
return True
any()
def any(iterable)
for element in iterable:
if element:
return True
return False
basestring()
#superclass for str and unicode used for testing
bin()
#convert an int to a binary string. if x =! int need to define __index__() to return an int.
bool()
#class. Returns True or False
bytearray()
Return a new array of bytes. the bytearray class is a mutable sequence of integers in the range 0<= x <256
It has most of the usual methods of mutable sequences as well as str() methods
callable()
Return True if argument appears callable. False if not.
chr()
return a string of one character whose ASCII code is the inteder i.
classmethod()
receives class as implicit argument.
class C(object):
@classmethod
def f(cls, arg1, arg2, ...)
cmp()
compare two objects (takes, a, touple) and return an int according to the outcome.
compile()
turn code into object.
complex()
return a complex number made from ([real[,imag]])
delattr()
(del attr) deletes named attr.
dict()
Dictionary
dir()
divmod()
take two complex numbers and return a pair of their quotient and remainder.
takes a touple argument
enumerate()
Return an enumerate object. sequence an iterator or some object that supports iteration.
seasons = ["Spring", "Summer", "Fall", "Winter"]
list(enumerate(seasons))
list(enumerate(seasons, start=1))
def enumerate(sequence, start = 0):
n = start
for elem in sequence:
yield n, elem
n+=1
eval()
evaluate or =
x = 1
print eval("x + 1")
execfile()
similar to exec() but it parses to a file instead of a string.
file()
same as open()
filter(func, iterable)
Construct a list from elements of iterable for which function returns true. returns tuple or string depending on input
float()
get dat '.'
format()
convert value to "formatted" representation.
format(value, format_spec) == value.__format__(format_spec)
frozenset()
set type- "frozen set module" uses elements taken from the iterable
getattr(obj, name, [,default]) ##why is the ',' inside the []? why wouldn't it be listed-
getattr(obj, name[default])? maybe because this is a str and it is for mutable obj?
globals()
return dict representing current global symbol.
hasattr()
has attr- returns True or False
hash()
return the value of the object. ints are always returned. I feel like the data could get messy with this.
help()
hex()
Hexidecimal string prefix!!
hex(255)
hex(-42)
hex(1L)
id()
returned as int() number that is assigned to object.
input()
input() == eval(raw_input(prompt))
int()
return integer object
isinstance()
return true if object argument is an instance of class argument.
issubclass()
return True if class is a subclass...
iter()
return an iterator object.
with open('mydata.txt') as fp:
for line in iter(fp.readline, ""):
process_line(line)
len()
length
list()
this is a class- []
locals()
update and return a {}
long()
return a long int.
map(func, iterable)
apply func to all iterables and return a [] of results.
max()
largest argument within (),[],{}
memoryview()
return object. memory view.
min()
return smallest value possible
next()
call the next method
object()
oct()
convert int to octal string
open()
ord()
return int() with unicode
pow()
to the ^ power- returns power.
print()
property()
returns class property
class c(object):
def__init__(self):
self._x = None
def getx(x):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx "The 'x' property")
class Parrot(object):
def __init__(self):
self._voltage = 10000
@property
def voltage(self):
"""get current voltage"""
return self._voltage
class C(object):
def__init__(self):
self._x= None
@property
def x(self):
"""the 'x' """
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
range()
start + end + step
raw_input()
takes input from user
reduce()
def reduce(func, iterable, initializer = None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError("reduce() of empty sequence")
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
reload()
all code is recompiled.
try:
cache
except NameError:
cache = {}
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
unichr()
unicode()
vars()
xrange()
zip()
__import__()
apply()
buffer()
coerce()
intern()
|
a180779aeacea89646d3c44591d073601a509d9a | arian81/playground | /python3_hard_way/ex4.py | 502 | 3.8125 | 4 | cars=100
space_in_a_car=4
drivers=30
passengers=90
cars_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_per_car=passengers/cars_driven
print("There are", cars, "cars available")
print("There are only", drivers, "drivers available")
print("There will be" , cars_not_driven, "empty cars today")
print("We can transport", carpool_capacity,"people today")
print("We need to put about", average_passengers_per_car, "in each car.")
|
fbd52b6923aea96c0a980e36948bddd386f1899d | amusitelangdan/pythonTest | /20200103py/var_args.py | 1,914 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def power(x, n = 2):
if not isinstance(n , int):
raise TypeError('n must be int')
if not isinstance(x, (int, float)):
raise TypeError( 'x must be int or float ' )
return x ** n
print (power(2))
# 可变参数, 计算值
def calc(numbers, n = 2):
sum = 0
if not isinstance(numbers, ( list, tuple)):
raise TypeError('numbers must be list or tuple')
for number in numbers:
if not isinstance(number, (int, float)):
raise TypeError('Afferent inside value must be int or float')
sum = sum + (number**n)
return sum
print (calc((1,2,3,4,5)))
def calec(*numbers):
sum = 0
if not isinstance(numbers, ( list, tuple)):
raise TypeError('numbers must be list or tuple')
for number in numbers:
if not isinstance(number, (int, float)):
raise TypeError('Afferent inside value must be int or float')
sum = sum + (number**2)
return sum
print (calec(1,2,3,4,5))
print (calec())
# 关键字参数
def person(name, age, **kv):
print ('name', name, 'age', age, 'other', kv)
person('zhai', 30)
person('zhai', 24, city='beijing')
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('jack', 24, **extra)
# 命名关键字参数
def delete(name, age, **kv):
if 'city' in kv:
pass
#delattr(kv, 'city') # 删除city属性
print ('name', name, 'age', age, 'other', kv)
delete('mary', 24, city = 'shanghai')
#def del_person(name, *, city, job):
# print (name, city, job)
# 允许接受一个或多个数并计算乘积
def product(x, y = 1):
if not isinstance(x, (int, float)):
raise TypeError('x must be int or float')
return x*y
print (product(2, 8))
# 别人关于这个的写法:利用了可变参数
def product_other(x, *args):
s = x
for z in args:
print (z)
s = s * z
return s
print (product_other(5)) |
362f1f1eaa46d846a0deda4b6e1c9aad80586873 | hefrankeleyn/pythonWP | /homework_003/demo02.py | 226 | 3.78125 | 4 | usernames=[]
if usernames:
print('There have people.')
else:
print('This is empty.')
num=3
if num<5:
print('you are lower 5.')
elif num<10:
print('you are lower 10')
elif num<15:
print('you are lower 15')
|
fd5eeaeb16d6dd39522b0c20b65257c301f17585 | kateamon/trees | /photo_process.py | 3,578 | 3.59375 | 4 | """
This Python script takes photos from a source directory:
Flips those image left-right
Saves the flipped images into a separate output directory,
with _flip appended to the original filename before .jpg.
Use glob2 third-party library to generate a list of all jpg image filenames.
The string indexing [:-4] gets the filename cutting off the .jpg extension minus last 4 characters.
Image processing can be also be used to resize images to 64x64 pixel resolution. But we don't need to resize, just keeping for reference.
"""
import glob2
# import cv2 # OpenCV is a pain to install
# Using the Python Imaging Library (PIL) instead of OpenCV
import PIL
from PIL import Image
import numpy
# for log file
from datetime import datetime as dt
# Read in the tree image jpg files
# Get the Pepper Tree images
SOURCE_DIR_PEPPER = "/home/kate/data/trees-raw-data/california-pepper-tree/"
image_files_pepper = glob2.glob("/home/kate/data/trees-raw-data/california-pepper-tree/*.jpg")
# Get the Weeping Willow tree image files
SOURCE_DIR_WILLOW = "/home/kate/data/trees-raw-data/Lovely-trees-weeping-willow/"
image_files_willow = glob2.glob("/home/kate/data/trees-raw-data/Lovely-trees-weeping-willow/*.jpg")
# Where to put the flipped images:
OUTPUT_DIR_PEPPER = "/home/kate/data/trees-processed/pepper-trees/"
OUTPUT_DIR_WILLOW = "/home/kate/data/trees-processed/weeping-willow-trees/"
def flip_all_images(image_files, SOURCE_DIR, OUTPUT_DIR):
number_of_photos = len(image_files)
for filename in image_files:
img = Image.open(filename)
img_flip = img.transpose(PIL.Image.FLIP_LEFT_RIGHT)
# Determine how many characters in the source directory
len_source = len(SOURCE_DIR)
# Put the input directory path in, strip out the source directory path from the new filename
newfilename = OUTPUT_DIR + filename[len_source:-4] + "_flip" + ".jpg"
# print(newfilename)
img_flip.save(newfilename)
#create a log file to also put in the output directory
log_date = dt(dt.now().year, dt.now().month, dt.now().day, dt.now().hour, dt.now().minute)
line0 = "Created by function flip_all_images. Date/Time of log file: " + str(log_date)
line1 = "Done flipping and saving " + str(number_of_photos) +" photos."
line2 = "From photos in input directory " + SOURCE_DIR
line3 = "Flipping and saving those photos to output directory: " + OUTPUT_DIR
log_file_name = OUTPUT_DIR + "000_flip_all_images.log"
log_file_name = open(log_file_name, "w")
log_file_name.write(line0 + "\n")
log_file_name.write(line1 + "\n")
log_file_name.write(line2 + "\n")
log_file_name.write(line3 + "\n")
log_file_name.close()
print(line1)
print(line2)
print(line3)
print("")
# Now run the flipping function on both tree photo sources
flip_all_images(image_files_pepper, SOURCE_DIR_PEPPER, OUTPUT_DIR_PEPPER)
flip_all_images(image_files_willow, SOURCE_DIR_WILLOW, OUTPUT_DIR_WILLOW)
# ~~~~~~~~~~~~~~~~~~~ old stuff for reference ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# image_files = glob2.glob("*.jpg")
# for filename in image_files:
# img = cv2.imread(filename, 1)
# img64x64 = cv2.resize(img, (64, 64))
# newfilename = filename[:-4] + "64x64" + ".jpg"
# cv2.imshow(newfilename, img100x100)
# cv2.waitKey(2000)
# cv2.imwrite(newfilename, img100x100)
# import PIL
# from PIL import Image
#
# #read the image
# im = Image.open("sample-image.png")
#
# #flip image
# out = im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
# out.save('transpose-output.png')
|
4bdccf30ae69caf40fb1ff617f3ad93a5beb28d6 | XUSushi/Group-project_First-Version | /01_语音识别/语音识别_配置_陈思明/CHEN_only bing_test.py | 1,123 | 3.5625 | 4 | #!/usr/bin/env python3
import speech_recognition as sr
# obtain path to "english.wav" in the same folder as this script
# .wav的音频和本脚本应放在同一目录下
from os import path
AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "test.wav")
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "french.aiff")
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "chinese.flac")
# use the audio file as the audio source
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio = r.record(source) # read the entire audio file
# recognize speech using Microsoft Bing Voice Recognition
BING_KEY = "0a6b1eeea32840ea99e871099ef98556" # Microsoft Bing Voice Recognition API keys 32-character lowercase hexadecimal strings
try:
print("Microsoft Bing Voice Recognition thinks you said " + r.recognize_bing(audio, key=BING_KEY))
except sr.UnknownValueError:
print("Microsoft Bing Voice Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Microsoft Bing Voice Recognition service; {0}".format(e))
|
d8f46ed26fba8b3b860572edc034cff1646b6cb3 | Ahmed-Abdelhak/Problem-Solving | /Leetcode.30.contest/4. Move Zeros.py | 1,427 | 3.953125 | 4 |
# Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
# Example:
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# Note:
# You must do this in-place without making a copy of the array.
# Minimize the total number of operations.
class Solution:
def moveZeroes(self, nums) -> None:
i = 0 # a pointer for non zero Elements
# j is considered as a pointer that iterates the array
# I am shifting the "non Zero" elemnts to the left
for j in range(len(nums)):
if nums[j] != 0:
nums[i] = nums[j]
i = i+1
# now, I will trigger the free places at the array, to put zeros in them till the end
for k in range(i, len(nums)):
nums[k] = 0
print(nums)
print(Solution().moveZeroes([0,1,0,3,12]))
# C# solution
# public class Solution {
# public void MoveZeroes(int[] nums) {
# int i = 0;
# // Shifting all nonZero elements to the left
# for (int j = 0; j < nums.Length; j++) {
# if (nums[j] != 0) {
# nums[i++] = nums[j];
# }
# }
# // put zeros starting from the index after shifting till the end
# for (int j = i; j < nums.Length; j++) {
# nums[j] = 0;
# }
# }
# }
|
4174c30174c5f16e8964a7daf080de38b5a898d8 | bhajojo/PythonTraining | /Python Training Code/Loops/ForNEstedLoop.py | 113 | 3.765625 | 4 | for x in range(10,20):
print "in outer For Loop"
for y in range(20, 30):
print y
print x |
12aa7c4e16851c9d3fe720ada29bf322040ca422 | pubkraal/Advent | /2018/08/parsetree.py | 1,627 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
from functools import reduce
class Node:
def __init__(self, child_nodes=0, metadata=0):
self.num_nodes = child_nodes
self.num_metadata = metadata
self.child_nodes = []
self.metadata = []
def add_node(self, node):
self.child_nodes.add(node)
def add_nodes(self, nodes):
self.child_nodes += nodes
def add_metadata(self, data):
self.metadata.add(data)
def add_metadatas(self, datas):
self.metadata += datas
def parse_tree(data, nodes, expect_nodes=1):
# Nodes are:
# Number of childnodes
# Number of metadata
# <Childnodes>
# <metadata>
# So we go recursive, woop.
# We parse every node at this level and return a list
metadata = data[1]
childnodes = data[0]
print(metadata, childnodes)
n = Node(childnodes, metadata)
nodes.append(n)
moved = 0
if childnodes > 0:
cnodes, cursor_moved = parse_tree(data[2:], nodes, childnodes)
start = cursor_moved + 2
n.add_nodes(cnodes)
n.add_metadatas(data[start:start + metadata])
moved = start + metadata
else:
n.add_metadatas(data[2:2 + metadata])
moved = 2 + metadata
return [n, moved]
def main(inputfile):
nodes = []
with open(inputfile, 'r') as rd:
data = list(map(int, rd.read().split()))
rootnodes = parse_tree(data, nodes)
print(rootnodes)
print("Total sum:", sum(reduce(lambda a, b: a+b,
[n.metadata for n in nodes])))
if __name__ == "__main__":
main(sys.argv[1])
|
887cb4782c8e446160ccf1c570faa8596c8daf67 | rglusic/prg105 | /chapter 5/AutomobileCosts.py | 1,665 | 4.375 | 4 | """
Write a program that asks the user to enter the monthly costs for the following expenses incurred from operating his
or her automobile: loan payment, insurance, gas, and maintenance. The program should then display the total monthly
cost of these expenses, and the total annual cost of these expenses.
Assign meaningful names to your functions and variables. Every function also needs a comment explaining
what it does and what other function it works with.
"""
"""
Calls the other functions. Passes total monthly cost to yearly cost.
"""
def main():
total = monthly()
yearly(total)
"""
Asks the user how much they spend monthly on their loan, insurance and gas for their car.
Adds the values up into a total and prints it, finally returning it in order to use it
in another function.
"""
def monthly():
loan = float(input("How much do you pay for your car loan each month? "))
insurance = float(input("How much do you pay for your car insurance each month? "))
gas = float(input("How much do you spend on gas each month? "))
maintenance = float(input("How much do you spend on the maintenance of your car a month? "))
total = loan + insurance + gas + maintenance
print("You pay a total of $" + format(total, ",.2f") + " on your car each month.")
return total
"""
Calculates the total price annually by passing in the price monthly. Prints out the price spent each year.
"""
def yearly(monthly_total):
yearly_total = monthly_total * 12
print("You pay a total of $" + format(yearly_total, ",.2f") + " on your car each year")
"""
Runs the program.
"""
main()
|
6d38b2f91ad2aeeb89d25e2d49988b3d102ade90 | tonygomo/instilled-code-challenge | /test.py | 1,904 | 3.59375 | 4 | import unittest
from main import InvalidInputError, parse_fragments, calculate_uvt
class TestParseFragments(unittest.TestCase):
def test_parse_strings(self):
"""It should parse correctly formatted strings."""
parsed = parse_fragments('0-1000', '1500-2000')
self.assertEqual(parsed, [(0, 1000), (1500, 2000)])
def test_invalid_input(self):
"""It should raise an exception if input is invalid."""
with self.assertRaises(InvalidInputError):
parse_fragments('0-1000', '1500-twoThousand')
class TestCalculateUvt(unittest.TestCase):
def test_addition(self):
"""It should add together all given fragments."""
uvt = calculate_uvt((0, 1000), (1000, 2000), (2000, 3000))
self.assertEqual(uvt, 3000)
def test_unsorted(self):
"""It should handle fragments being passed out-of-order."""
uvt = calculate_uvt((1000, 2000), (2000, 3000), (0, 1000))
self.assertEqual(uvt, 3000)
def test_overlaps(self):
"""It should handle overlapping fragments without double counting."""
uvt = calculate_uvt((0, 1000), (1000, 2000), (1500, 3000))
self.assertEqual(uvt, 3000)
def test_non_contiguous_fragments(self):
"""It should handle non-contiguous fragments."""
uvt = calculate_uvt((0, 1000), (2000, 2500), (3000, 4000))
self.assertEqual(uvt, 2500)
def test_duplicates(self):
"""It should not double count duplicate fragments."""
uvt = calculate_uvt((0, 1000), (0, 1000))
self.assertEqual(uvt, 1000)
def test_contained_fragments(self):
"""It should handle fragments contained within other fragments."""
uvt = calculate_uvt((0, 1000), (200, 800))
self.assertEqual(uvt, 1000)
if __name__ == '__main__':
unittest.main() |
95ae6598375d7cebdb7bdf80fd42877c751dbb51 | hoanghuyen98/fundamental-c4e19 | /Session04/homeword/turtle_1.py | 344 | 3.90625 | 4 | from turtle import*
import random
colors = ['blue', 'orange', 'purple', 'white','yellow','red','pink','green']
shape("turtle")
speed(-1)
bgcolor("black")
for i in range(24):
for j in range(4):
color(random.choice(colors))
forward(100)
left(90)
left(15)
color(random.choice(colors))
# end_fill()
mainloop() |
34b88de508d78da511a34bd26e032e2de052d420 | samhithaaaa/Array-4 | /maxsubarraysum.py | 290 | 3.53125 | 4 | #time complexity is o(n)
#space complexity is o(1)
class Solution:
def maxSubArray(self,nums):
local =nums[0]
globall=nums[0]
for i in range(1,len(nums)):
local=max(local+nums[i],nums[i])
globall=max(globall,local)
return globall
|
e2805f4cd166d256f6e05b1279e6af7ae781a7bc | MitalAshok/semantics2021_toy_languages | /semantics2021_toy_languages/L1.py | 43,696 | 3.8125 | 4 | """An implementation of L1
Values:
𝑏 ∈ 𝔹 = { true, false }
𝑛 ∈ ℤ = { ..., -1, 0, 1, ... }
𝑙 ∈ 𝕃 = { l, l0, l1, l2, ... }
Operations:
op ∈ { +, ≥ }
Grammar:
(Quoted strings are literal, spaces (U+0020) do not matter between tokens,
including integer digits, but they do matter in literal tokens)
𝑒 ::= 𝑒 ";" 𝑒
| 𝑏
| 𝑛
| 𝑒 op 𝑒
| "if" 𝑒 "then" 𝑒 "else" 𝑒
| 𝑙 ":=" 𝑒
| "!" 𝑙
| 𝑙
| "skip"
| "while" 𝑒 "do" 𝑒
| "(" 𝑒 ")"
𝑏 ::= "true" | "false"
digit_non_zero ::= "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
digit ::= digit_non_zero | "0"
digits ::= digit digits
positive_integer = digit_non_zero digits | digit_non_zero
non_negative_integer = positive_integer | "0"
𝑛 ::= non_negative_integer | "-" positive_integer
op ::= "+" | "≥"
As an extension, allow
op ::= "+" | "≥" | ">="
𝑙 ::= "l" | "l" non_negative_integer
Where a greedy algorithm is employed to parse this grammar, so every
rule is left-to-right associative when parsing tokens
As an extension to the language, if the first line starts with "#!",
it is ignored up to the first \n.
Then, a list of initial states can be specified in the form of:
initial_states = 𝑙 "->" 𝑒 "," initial_states | ""
Where 𝑒 will be evaluated with all the mappings given so far, and it
is an error for the same mapping to appear multiple times.
Semantics:
TODO: Complete Semantics section
"""
# TODO: Allow more error conditions rather than just generic errors
import abc
import re
import enum
import typing
__all__ = (
'Options', 'State', 'Type',
'Expression',
'Seq', 'Boolean', 'Integer', 'Operation',
'Conditional', 'Assignment', 'Dereference',
'Location', 'Skip', 'WhileLoop', 'Parenthesised',
'to_ml', 'to_java'
)
SPACE = '[ \\r\\n]'
S = SPACE + '*' # Any amount of space
SPACE_PATTERN = re.compile(S)
POSITIVE_INTEGER_PATTERN = re.compile(f'{S}[1-9]{S}(?:[0-9]{S})*')
NON_NEGATIVE_INTEGER_PATTERN = re.compile(f'{POSITIVE_INTEGER_PATTERN.pattern}|{S}0{S}')
INTEGER_PATTERN = re.compile(f'{NON_NEGATIVE_INTEGER_PATTERN.pattern}|{S}-{POSITIVE_INTEGER_PATTERN.pattern}')
LOCATION_PATTERN = re.compile(f'{S}l{S}({NON_NEGATIVE_INTEGER_PATTERN.pattern}|)')
BOOLEAN_PATTERN = re.compile(f'{S}(?:true|false){S}')
_SPACE_TO_NONE_TRANSLATION = str.maketrans(dict.fromkeys(' \n\r', None))
def _matches_pattern(pattern, string):
return bool(pattern.fullmatch(string))
def _purge_spaces(s):
return s.translate(_SPACE_TO_NONE_TRANSLATION)
def _skip_spaces(source, index):
return SPACE_PATTERN.match(source, index).end(0)
def integer_token_to_integer(integer_token):
if not _matches_pattern(INTEGER_PATTERN, integer_token):
raise ValueError(f'Invalid integer token: {integer_token!r}')
return int(_purge_spaces(integer_token))
def integer_to_integer_token(integer):
return str(integer)
def location_token_to_index(location_token):
match = LOCATION_PATTERN.match(location_token)
if not match:
raise ValueError(f'Invalid location token: {location_token!r}')
index = _purge_spaces(match.group(1))
if not index:
return None
return int(index)
def index_to_location_token(index):
if index is None:
return 'l'
else:
return f'l{index}'
class Options:
"""A collection of options when interpreting an L1 program
L1b_mode (default: False)
If True, use L1b instead of L1, by evaluating the right
of operators first (Use (op1b) and (op2b) instead of (op1) and (op2)
Only effects stepping / running
allow_non_integer_programs (default: True)
If False, the only expression allowed as a complete program
must have type INTEGER
allow_two_character_ge (default: True)
Allow the usage of ">=" instead of "≥" during parsing.
Only affects parse() and create()
assign_returns_new_value (default: False)
If True, the type of an assignment expression is INTEGER, and the
value is the value that was assigned. It changes the rule (assign1)
to (assign'1), so that ⟨l := n, {l ↦ x}⟩ -> ⟨n, {l ↦ n}⟩.
Should set seq_allows_non_unit to True if this is True
seq_allows_non_unit (default: False)
If True, allows the left side of a sequence to be of non-unit type,
by changing the rule (seq1) to (seq1')
all_locations_implicitly_zero (default: False)
If True, when trying to dereference a location not in the store,
0 will be returned, and assignment is allowed to locations not in
the store.
Adds two rules:
⟨𝑙 := 𝑒, s⟩ -> ⟨𝑙 := 𝑒, s ∪ {𝑙 ↦ 0}⟩ if 𝑙 ∉ dom(s) (assign')
⟨!𝑙, s⟩ -> ⟨!𝑙, s ∪ {𝑙 ↦ 0}⟩ if 𝑙 ∉ dom(s) (deref')
And type checks under the assumption of dom(Γ) = 𝕃
allow_conditional_locations (default: False)
Allows the body of conditionals to have locations
"""
__slots__ = (
'L1b_mode',
'allow_two_character_ge', 'allow_non_integer_programs',
'assign_returns_new_value', 'seq_allows_non_unit',
'all_locations_implicitly_zero',
'allow_conditional_locations'
)
def __init__(self, other=None):
if isinstance(other, Options):
self.L1b_mode = other.L1b_mode
self.allow_two_character_ge = other.allow_two_character_ge
self.allow_non_integer_programs = other.allow_non_integer_programs
self.assign_returns_new_value = other.assign_returns_new_value
self.all_locations_implicitly_zero = other.all_locations_implicitly_zero
self.seq_allows_non_unit = other.seq_allows_non_unit
self.allow_conditional_locations = other.allow_conditional_locations
return
self.L1b_mode = False
self.allow_two_character_ge = True
self.allow_non_integer_programs = True
self.assign_returns_new_value = False
self.all_locations_implicitly_zero = False
self.seq_allows_non_unit = False
self.allow_conditional_locations = False
class State:
__slots__ = 'mappings',
def __init__(self, mappings=None, **extra_mappings):
if isinstance(mappings, State):
self.mappings = dict(mappings.mappings)
return
normalised_mapping = {}
for m in (mappings, extra_mappings):
for k, v in (m.items() if isinstance(m, dict) else () if m is None else m):
if k is not None:
if isinstance(k, int):
k = int(k)
else:
k = location_token_to_index(k)
if k in normalised_mapping:
raise ValueError(f'Duplicate location when initialising environment: {index_to_location_token(k)}')
if isinstance(v, int):
v = int(v)
else:
v = integer_token_to_integer(v)
normalised_mapping[k] = v
self.mappings = normalised_mapping
def __getitem__(self, item):
try:
return self.mappings[item]
except KeyError:
raise ValueError(f'Tried to access (read) location {index_to_location_token(item)} when there is no such location') from None
def __setitem__(self, item, value):
if item not in self.mappings:
raise ValueError(f'Tried to access (write {value}) location {index_to_location_token(item)} when there is no such location') from None
self.mappings[item] = value
def __contains__(self, item):
return item in self.mappings
def copy(self):
return State(self)
def __add__(self, other):
if isinstance(other, tuple) and len(other) == 2:
index, new_value = other
if (index is None or isinstance(index, int)) and isinstance(new_value, int):
if index is not None:
index = int(index)
new_value = int(new_value)
copy = self.copy()
copy[index] = new_value
return copy
return NotImplemented
def __repr__(self):
return f'State({self.mappings!r})'
def sorted_keys(self):
return sorted(self.mappings.keys(), key=(lambda n: -1 if n is None else n))
def __str__(self):
keys = self.sorted_keys()
m = self.mappings
mappings = ', '.join(f'{index_to_location_token(k)} ↦ {m[k]}' for k in keys)
return f'{{{mappings}}}'
def ml_repr(self):
keys = self.sorted_keys()
m = self.mappings
pairs = ', '.join(f'("{index_to_location_token(k)}", {m[k]!s})' for k in keys)
return f'[{pairs}]'
def java_repr(self):
keys = self.sorted_keys()
if not keys:
return 'new State()'
m = self.mappings
pairs = '; '.join(f'this.add({index_to_location_token(k)}, new Int({m[k]}))' for k in keys) + ';'
return f'new State(){{{{ {pairs} }}}}'
class Type(enum.Enum):
UNIT = 0
INTEGER = 1
BOOLEAN = 2
LOCATION = 3
class Expression(abc.ABC):
__slots__ = 'options',
def __init__(self, options):
self.options = options
@abc.abstractmethod
def step(self, s: State) -> typing.Tuple['Expression', State]:
"""
Throws an error if this expression cannot be stepped, otherwise
a pair (e, s), where e is a new expression, and
"""
raise NotImplementedError()
@staticmethod
def create(source: str, options : Options = Options()) -> 'Expression':
"""
Parses an Expression and returns the result
source is a string of the source code
If allow_any_type is True, allow the expression to have any type
This is an extension if this expression is the whole program, and
should have the following results printed:
UNIT: The entire state at the end of the program
INTEGER: The integer value
BOOLEAN: true or false, the boolean value
LOCATION: The value at the location in the state
Without this extension, only INTEGER types are allowed as a top-level
expression
"""
e = Expression.parse(source, 0, None, None if options.allow_non_integer_programs else {Type.INTEGER}, options)
if e is None:
raise ValueError(f'Could not parse {source!r} as an expression')
e, index = e
if index != len(source):
raise ValueError(f'Extraneous data after expression')
return e
@classmethod
@abc.abstractmethod
def parse(cls, source: str, start_index: int, except_, allow_types, options: Options) -> typing.Optional[typing.Tuple['Expression', int]]:
"""
Returns (e, new_index) where e was parsed from
source[start_index: new_index]. If not possible, returns None
If except_ is a set, will not try to parse those types
If allow_types is a set, will try to only parse expressions with those
types
"""
if except_ is None:
except_ = frozenset()
if allow_types is None:
allow_types = frozenset(Type.__members__.values())
if not allow_types:
return None # No allowed types
for subclass in Expression._subclasses:
if subclass in except_:
continue
result = subclass.parse(source, start_index, except_ | {subclass}, allow_types, options)
if result is not None:
return result
@abc.abstractmethod
def __repr__(self) -> str:
"""repr(self)"""
return object.__repr__(self)
@abc.abstractmethod
def __str__(self) -> str:
"""str(self)"""
return repr(self)
@abc.abstractmethod
def ml_repr(self):
raise NotImplementedError()
@abc.abstractmethod
def java_repr(self):
raise NotImplementedError()
@abc.abstractmethod
def get_type(self) -> Type:
"""Returns the type of this expression (A value from Type)"""
raise NotImplementedError()
_subclasses = ()
@classmethod
def __init_subclass__(cls, **kwargs):
Expression._subclasses += cls,
def __ne__(self, other):
eq = self.__eq__(other)
if eq is NotImplemented:
return NotImplemented
return not eq
@abc.abstractmethod
def __eq__(self, other):
if not isinstance(self, Expression) or not isinstance(other, Expression):
return NotImplemented
return type(self) == type(other)
def step_all(self, s: State) -> typing.Tuple[typing.Union['Boolean', 'Integer', 'Location', 'Skip'], State]:
finish_types = frozenset({Boolean, Integer, Location, Skip})
e = self
while type(e) not in finish_types:
e, s = e.step(s)
return e, s
def evaluate(self, s):
e, s = self.step_all(s)
if type(e) is Skip:
return s
if type(e) is Location:
return s[e.value]
return e.value
def print_steps(self, s: State):
finish_types = frozenset({Boolean, Integer, Location, Skip})
e = self
first = True
while type(e) not in finish_types:
if first:
first = False
else:
print('->')
print(f'⟨{e}, {s}⟩')
e, s = e.step(s)
print(f'⟨{e}, {s}⟩')
def visit(self, f):
f(self)
@abc.abstractmethod
def type_check(self, s: State) -> typing.Optional[Type]:
"""Like get_type() but also checks if this progam will type check, and returns None otherwise"""
raise NotImplementedError()
class Seq(Expression):
__slots__ = 'left', 'right'
def __init__(self, left: Expression, right: Expression, options: Options):
super().__init__(options)
if not options.seq_allows_non_unit and left.get_type() is not Type.UNIT:
raise ValueError(f'Seq left ({self.left!r}; right) should be of type UNIT')
self.left = left
self.right = right
def step(self, s):
if type(self.left) is Skip:
return self.right, s # (seq1)
if type(self.left) in (Integer, Boolean, Location):
if self.options.seq_allows_non_unit:
return self.right, s # (seq1')
else:
raise RuntimeError(f'Seq left ({self.left!r}; right) should be of type UNIT')
e, s = self.left.step(s)
return Seq(e, self.right, self.options), s # (seq2)
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
left = Expression.parse(source, start_index, except_, None if options.seq_allows_non_unit else {Type.UNIT}, options)
if left is None:
return None
left, start_index = left
if source[start_index: start_index + 1] != ';':
return None
right = Expression.parse(source, start_index + 1, None, allow_types, options)
if right is None:
return None
right, start_index = right
return Seq(left, right, options), start_index
def __repr__(self):
return f'Seq({self.left!r}, {self.right!r})'
def __str__(self):
return f'{self.left}; {self.right}'
def ml_repr(self):
return f'Seq ({self.left.ml_repr()}, {self.right.ml_repr()})'
def java_repr(self):
return f'new Seq({self.left.java_repr()}, {self.right.java_repr()})'
def get_type(self):
return self.right.get_type()
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.left == other.left and self.right == other.right
return eq
def visit(self, f):
super().visit(f)
self.left.visit(f)
self.right.visit(f)
def type_check(self, s):
left_type = self.left.type_check(s)
if not self.options.seq_allows_non_unit and left_type is not Type.UNIT:
return None
return self.right.type_check(s)
class Boolean(Expression):
__slots__ = 'value'
def __init__(self, value: bool, options: Options):
super().__init__(options)
if not isinstance(value, bool):
raise TypeError(f'Boolean(value) should be bool; got {type(value).__name__}')
self.value = bool(value)
def step(self, s):
# Stuck
raise RuntimeError(f'Tried to step a {self!r}')
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.BOOLEAN not in allow_types:
return None
m = BOOLEAN_PATTERN.match(source, start_index)
if m is None:
return None
return Boolean('t' in m.group(0), options), m.end(0)
def __repr__(self):
return f'Boolean({self.value})'
def __str__(self):
return str(self.value).lower()
def ml_repr(self):
return f'Boolean {str(self.value).lower()}'
def java_repr(self):
return f'new Bool({str(self.value).lower()})'
def get_type(self):
return Type.BOOLEAN
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.value is other.value
return eq
def type_check(self, s):
return Type.BOOLEAN
class Integer(Expression):
__slots__ = 'value'
def __init__(self, value: int, options: Options):
super().__init__(options)
if not isinstance(value, int):
raise TypeError(f'Integer(value) should be int; got {type(value).__name__}')
self.value = int(value)
def step(self, s):
# Stuck
raise RuntimeError(f'Tried to step a {self!r}')
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.INTEGER not in allow_types:
return None
m = INTEGER_PATTERN.match(source, start_index)
if m is None:
return None
return Integer(integer_token_to_integer(m.group(0)), options), m.end(0)
def __repr__(self):
return f'Integer({self.value})'
def __str__(self):
return str(self.value)
def ml_repr(self):
return f'Integer {self.value}'
def java_repr(self):
return f'new Int({self.value})'
def get_type(self):
return Type.INTEGER
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.value is other.value
return eq
def type_check(self, s):
return Type.INTEGER
class Operation(Expression):
__slots__ = 'left', 'op', 'right'
class Operations(enum.Enum):
ge = 0
plus = 1
def __repr__(self):
if self is Operation.Operations.ge:
return 'Operation.Operations.ge'
return 'Operation.Operations.plus'
def __init__(self, left: Expression, op: Operations, right: Expression, options: Options):
super().__init__(options)
if op is not Operation.Operations.ge and op is not Operation.Operations.plus:
raise TypeError(f'Operation(left, op, right): op should be Operation.Operations.plus; got {type(op).__name__}')
if left.get_type() is not Type.INTEGER:
raise TypeError(f'Operation left ({left!r} op right) should be of type INTEGER')
if right.get_type() is not Type.INTEGER:
raise TypeError(f'Operation left (left op {right!r}) should be of type INTEGER')
self.left = left
self.op = op
self.right = right
def step(self, s):
left = self.left
op = self.op
right = self.right
if self.options.L1b_mode:
# Reverse the order of evaluation: Step right first
if type(right) is not Integer:
right, s = right.step(s)
return Operation(left, op, right, self.options), s # (op1b)
if type(left) is not Integer:
left, s = left.step(s)
return Operation(left, op, right, self.options), s # (op1) or (op2b)
if type(right) is not Integer:
right, s = right.step(s)
return Operation(left, op, right, self.options), s # (op2)
if op is Operation.Operations.ge:
return Boolean(left.value >= right.value, self.options), s # (op>=)
elif op is Operation.Operations.plus:
return Integer(left.value + right.value, self.options), s # (op+)
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.BOOLEAN not in allow_types and Type.INTEGER not in allow_types:
return None
left = Expression.parse(source, start_index, except_, {Type.INTEGER}, options)
if left is None:
return None
left, start_index = left
if source[start_index: start_index + 1] == '+':
op = Operation.Operations.plus
start_index += 1
elif source[start_index: start_index + 1] == '≥':
op = Operation.Operations.ge
start_index += 1
elif source[start_index: start_index + 2] == '>=' and options.allow_two_character_ge:
op = Operation.Operations.ge
start_index += 2
else:
return None
if op is Operation.Operations.plus:
if Type.INTEGER not in allow_types:
return None
elif op is Operation.Operations.ge:
if Type.BOOLEAN not in allow_types:
return None
right = Expression.parse(source, start_index, None, {Type.INTEGER}, options)
if right is None:
return None
right, start_index = right
return Operation(left, op, right, options), start_index
def __repr__(self):
return f'Operation({self.left!r}, {self.op!r}, {self.right!r})'
def ml_repr(self):
op = 'Plus' if self.op is Operation.Operations.plus else 'GTEQ'
return f'Op ({self.left.ml_repr()}, {op}, {self.right.ml_repr()})'
def java_repr(self):
op = 'Plus' if self.op is Operation.Operations.plus else 'GTeq'
return f'new {op}({self.left.java_repr()}, {self.right.java_repr()})'
def __str__(self):
op = '+' if self.op is Operation.Operations.plus else '≥'
return f'{self.left} {op} {self.right}'
def get_type(self):
op = self.op
if op is Operation.Operations.ge:
return Type.BOOLEAN
elif op is Operation.Operations.plus:
return Type.INTEGER
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.op is other.op and self.left == other.left and self.right == other.right
return eq
def visit(self, f):
super().visit(f)
self.left.visit(f)
self.right.visit(f)
def type_check(self, s):
if self.left.type_check(s) is not Type.INTEGER or self.right.type_check(s) is not Type.INTEGER:
return None
return Type.INTEGER if self.op is Operation.Operations.plus else Type.BOOLEAN
class Conditional(Expression):
__slots__ = 'condition', 'if_true', 'if_false'
def __init__(self, condition: Expression, if_true: Expression, if_false: Expression, options: Options):
super().__init__(options)
if condition.get_type() is not Type.BOOLEAN:
raise TypeError(f'Conditional condition (if {condition!r} then if_true else if_false) should be of type BOOLEAN')
if if_true.get_type() is not if_false.get_type():
raise TypeError(f'Conditional if_true and if_false (if condition then {if_true!r} else {if_false!r}) should be of the same type')
self.condition = condition
self.if_true = if_true
self.if_false = if_false
def step(self, s):
condition = self.condition
if type(condition) is Boolean:
if condition.value:
return self.if_true, s # (if1)
return self.if_false, s # (if2)
condition, s = condition.step(s)
return Conditional(condition, self.if_true, self.if_false, self.options), s # (if3)
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
start_index = _skip_spaces(source, start_index)
if source[start_index: start_index + 2] != 'if':
return None
condition = Expression.parse(source, start_index + 2, None, {Type.BOOLEAN}, options)
if condition is None:
return None
condition, start_index = condition
if source[start_index: start_index + 4] != 'then':
return None
if_true = Expression.parse(source, start_index + 4, None, allow_types, options)
if if_true is None:
return None
if_true, start_index = if_true
if source[start_index: start_index + 4] != 'else':
return None
if_false = Expression.parse(source, start_index + 4, None, {if_true.get_type()}, options)
if if_false is None:
return None
if_false, start_index = if_false
return Conditional(condition, if_true, if_false, options), start_index
def __repr__(self):
return f'Conditional({self.condition!r}, {self.if_true!r}, {self.if_false!r})'
def ml_repr(self):
return f'If ({self.condition.ml_repr()}, {self.if_true.ml_repr()}, {self.if_false.ml_repr()})'
def java_repr(self):
return f'new IfThenElse({self.condition.java_repr()}, {self.if_true.java_repr()}, {self.if_false.java_repr()})'
def __str__(self):
return f'if {self.condition} then {self.if_true} else {self.if_false}'
def get_type(self):
return self.if_true.get_type()
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.condition == other.condition and self.if_true == other.if_true and self.if_false == other.if_false
return eq
def visit(self, f):
super().visit(f)
self.condition.visit(f)
self.if_true.visit(f)
self.if_false.visit(f)
def type_check(self, s):
if self.condition.type_check(s) is not Type.BOOLEAN:
return None
true_type = self.if_true.type_check(s)
if not self.options.allow_conditional_locations and true_type is Type.LOCATION:
return None
if true_type is not self.if_false.type_check(s):
return None
return true_type
class Assignment(Expression):
__slots__ = 'location', 'value'
def __init__(self, location: Expression, value: Expression, options: Options):
super().__init__(options)
if location.get_type() is not Type.LOCATION:
raise TypeError(f'Assignment location ({location!r} := value) should be of type LOCATION')
if value.get_type() is not Type.INTEGER:
raise TypeError(f'Assignment value (location := {value!r}) should be of type INTEGER')
self.location = location
self.value = value
def step(self, s):
location = self.location
value = self.value
if type(location) is not Location:
# Extension rule: Using new type Location, which can be
# in (if ... then l1 else l2) if options.allow_conditional_locations
location, s = location.step(s)
return Assignment(location, value, self.options), s
if type(value) is not Integer:
value, s = value.step(s)
return Assignment(location, value, self.options), s # (assign2)
l = location.value
if l not in s:
if not self.options.all_locations_implicitly_zero:
s[l] = value.value # Throw error
assert False
s = s.copy()
s.mappings[l] = 0
return self, s # (assign')
return Skip(self.options), s + (l, value.value) # (assign1)
@staticmethod
def _type_from_options(options):
return Type.INTEGER if options.assign_returns_new_value else Type.UNIT
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
T = Assignment._type_from_options(options)
if T not in allow_types:
return None
location = Expression.parse(source, start_index, except_, {Type.LOCATION}, options)
if location is None:
return None
location, start_index = location
if source[start_index: start_index+2] != ':=':
return None
value = Expression.parse(source, start_index + 2, None, {T}, options)
if value is None:
return None
value, start_index = value
return Assignment(location, value, options), start_index
def __repr__(self):
return f'Assignment({self.location!r}, {self.value!r})'
def ml_repr(self):
if type(self.location) is not Location:
raise ValueError('Using extension where expressions can be (indirect) locations; Cannot convert to ML')
return f'Assign ("{index_to_location_token(self.location.value)}", {self.value.ml_repr()})'
def java_repr(self):
if type(self.location) is not Location:
raise ValueError('Using extension where expressions can be (indirect) locations; Cannot convert to ML')
return f'new Assign({index_to_location_token(self.location.value)}, {self.value.java_repr()})'
def __str__(self):
return f'{self.location} := {self.value}'
def get_type(self):
return Assignment._type_from_options(self.options)
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.location == other.location and self.value == other.value
return eq
def visit(self, f):
super().visit(f)
self.location.visit(f)
self.value.visit(f)
def type_check(self, s):
if self.location.type_check(s) is not Type.LOCATION:
return None
if self.value.type_check(s) is not Type.INTEGER:
return None
return self.get_type()
class Dereference(Expression):
__slots__ = 'location',
def __init__(self, location: Expression, options: Options):
super().__init__(options)
self.location = location
def step(self, s):
location = self.location
if type(location) is not Location:
# Only happens if options.allow_conditional_locations
location, s = location.step(s)
return Dereference(location, self.options), s
l = location.value
if self.options.all_locations_implicitly_zero and l not in s:
s = s.copy()
s.mappings[l] = 0
return self, s # (deref')
return Integer(s[l], self.options), s # (deref)
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.INTEGER not in allow_types:
return None
start_index = _skip_spaces(source, start_index)
if source[start_index:start_index + 1] != '!':
return None
location = Expression.parse(source, start_index + 1, None, {Type.LOCATION}, options)
if location is None:
return None
location, start_index = location
return Dereference(location, options), start_index
def __repr__(self):
return f'Dereference({self.location!r})'
def ml_repr(self):
if type(self.location) is not Location:
raise ValueError('Using extension where expressions can be (indirect) locations; Cannot convert to ML')
return f'Deref "{index_to_location_token(self.location.value)}"'
def java_repr(self):
if type(self.location) is not Location:
raise ValueError('Using extension where expressions can be (indirect) locations; Cannot convert to ML')
return f'new Deref({index_to_location_token(self.location.value)})'
def __str__(self):
return f'!{self.location}'
def get_type(self):
return Type.INTEGER
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.location == other.location
return eq
def visit(self, f):
super().visit(f)
self.location.visit(f)
def type_check(self, s):
if self.location.type_check(s) is not Type.LOCATION:
return None
return Type.INTEGER
class Location(Expression):
__slots__ = 'value',
def __init__(self, value: typing.Optional[int], options: Options):
super().__init__(options)
if value is not None:
if not isinstance(value, int):
raise TypeError(f'Location(value) should be None or int; got {type(value).__name__}')
value = int(value)
self.value = value
def step(self, s):
# stuck
raise RuntimeError(f'Tried to step a {self!r}')
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.LOCATION not in allow_types:
return None
m = LOCATION_PATTERN.match(source, start_index)
if m is None:
return None
return Location(location_token_to_index(m.group(0)), options), m.end(0)
def __repr__(self):
return f'Location({self.value!r})'
def ml_repr(self):
raise ValueError('Should never have to get the ml_repr of a Location')
def java_repr(self):
raise ValueError('Should never have to get the java_repr of a Location')
def __str__(self):
return index_to_location_token(self.value)
def get_type(self):
return Type.LOCATION
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.value == other.value
return eq
def type_check(self, s):
if not self.options.all_locations_implicitly_zero and self.value not in s:
return None
return Type.LOCATION
class Skip(Expression):
__slots__ = ()
def __init__(self, options):
super().__init__(options)
def step(self, s):
# stuck
raise RuntimeError(f'Tried to step a {self!r}')
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.UNIT not in allow_types:
return None
start_index = _skip_spaces(source, start_index)
if source[start_index: start_index + 4] != 'skip':
return None
return Skip(options), _skip_spaces(source, start_index + 4)
def __repr__(self):
return 'Skip()'
def ml_repr(self):
return 'Skip'
def java_repr(self):
return 'new Skip()'
def __str__(self):
return f'skip'
def get_type(self):
return Type.UNIT
def __eq__(self, other):
return super().__eq__(other)
def type_check(self, s):
return Type.UNIT
class WhileLoop(Expression):
__slots__ = 'condition', 'body'
def __init__(self, condition: Expression, body: Expression, options: Options):
super().__init__(options)
if condition.get_type() is not Type.BOOLEAN:
raise TypeError(f'WhileLoop condition (while {condition!r} do body) should be of type BOOLEAN')
if body.get_type() is not Type.UNIT:
raise TypeError(f'WhileLoop body (while condition do {body!r}) should be of type UNIT')
self.condition = condition
self.body = body
def step(self, s):
condition = self.condition
body = self.body
options = self.options
return Conditional(condition, Parenthesised(Seq(body, WhileLoop(condition, body, options), options), options), Skip(options), options), s # (while)
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
if Type.UNIT not in allow_types:
return None
start_index = _skip_spaces(source, start_index)
if source[start_index: start_index + 5] != 'while':
return None
condition = Expression.parse(source, start_index + 5, None, {Type.BOOLEAN}, options)
if condition is None:
return None
condition, start_index = condition
if source[start_index: start_index + 2] != 'do':
return None
body = Expression.parse(source, start_index + 2, {Seq}, {Type.UNIT}, options)
if body is None:
return None
body, start_index = body
return WhileLoop(condition, body, options), start_index
def __repr__(self):
return f'WhileLoop({self.condition!r}, {self.body!r})'
def ml_repr(self):
return f'While ({self.condition.ml_repr()}, {self.body.ml_repr()})'
def java_repr(self):
return f'new While({self.condition.java_repr()}, {self.body.java_repr()})'
def __str__(self):
return f'while {self.condition} do {self.body}'
def get_type(self):
return Type.UNIT
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.condition == other.condition and self.body == other.body
return eq
def visit(self, f):
super().visit(f)
self.condition.visit(f)
self.body.visit(f)
def type_check(self, s):
if self.condition.type_check(s) is not Type.BOOLEAN:
return None
if self.body.type_check(s) is not Type.UNIT:
return None
class Parenthesised(Expression):
__slots__ = 'expression',
def __init__(self, expression: Expression, options: Options):
super().__init__(options)
self.expression = expression
def step(self, s):
return self.expression, s
@classmethod
def parse(cls, source, start_index, except_, allow_types, options):
start_index = _skip_spaces(source, start_index)
if source[start_index: start_index + 1] != '(':
return None
expression = Expression.parse(source, start_index + 1, None, allow_types, options)
if expression is None:
return None
expression, start_index = expression
if source[start_index: start_index + 1] != ')':
return None
return Parenthesised(expression, options), _skip_spaces(source, start_index + 1)
def __repr__(self):
return f'Parenthesised({self.expression!r})'
def ml_repr(self):
return self.expression.ml_repr()
def java_repr(self):
return self.expression.java_repr()
def __str__(self):
return f'({self.expression})'
def get_type(self):
return self.expression.get_type()
def __eq__(self, other):
eq = super().__eq__(other)
if eq is True:
return self.expression == other.expression
return eq
def visit(self, f):
super().visit(f)
self.expression.visit(f)
def type_check(self, s):
return self.expression.type_check(s)
def parse_source(source: str, options=Options()):
if source[0: 2] == '#!':
try:
source = source[source.index('\n') + 1:]
except ValueError:
pass
next_line = None
try:
next_line = source.index('\n')
except ValueError:
pass
s = State()
if next_line is not None:
possible_initial_mapping = source[: next_line]
pairs = []
i = 0
first = True
while i != len(possible_initial_mapping):
if first:
first = False
else:
if possible_initial_mapping[i: i + 1] != ',':
i = 0
break
i += 1
location = Expression.parse(possible_initial_mapping, i, set(), {Type.LOCATION}, options)
if location is None:
i = 0
break
location, i = location
if type(location) is Location:
location = location.value
else:
try:
location, _ = location.step_all(State(pairs))
except ValueError:
i = 0
break
if any(l == location for (l, _) in pairs):
i = 0
break
if possible_initial_mapping[i: i + 2] != '->':
i = 0
break
value = Expression.parse(possible_initial_mapping, i + 2, set(), {Type.INTEGER}, options)
if value is None:
i = 0
break
value, i = value
if type(value) is Integer:
value = value.value
else:
try:
value, _ = value.step_all(State(pairs))
except ValueError:
i = 0
break
pairs.append((location, value))
if i == len(possible_initial_mapping):
try:
s = State(pairs)
except ValueError:
i = 0
if i == len(possible_initial_mapping):
source = source[next_line + 1: ]
e = Expression.create(source, options=options)
return e, s
def to_ml(e: Expression, s: State):
return f'prettyreduce ({e.ml_repr()}, {s.ml_repr()})'
def to_java(e: Expression, s: State):
sorted_keys = s.sorted_keys()
l_names = tuple(map(index_to_location_token, sorted_keys))
lines = [
'// Matthew Parkinson, 1/2004',
'',
'public class L1 {',
'',
' public static void main(String[] args) {'
]
lines.extend([f' Location {l} = new Location("{l}");' for l in l_names])
lines.extend([
'',
' State s = ' + s.java_repr() + ';',
'',
' Environment env = new Environment()',
' ' + ''.join(f'.add({l})' for l in l_names) + ';',
'',
' Expression e =',
' ' + e.java_repr(),
' ;',
'',
' try {',
' // Type check',
' Type t = e.typeCheck(env);',
' System.out.println("Program has type: " + t);',
'',
' // Evaluate the program',
' System.out.printf("%s%n%n", e);',
' while (!(e instanceof Value)) {',
' e = e.smallStep(s);',
' // Display each step of reduction',
' System.out.printf("%s%n%n", e);',
' }',
'',
' // Give some output',
' System.out.println("Program has type: " + t);',
' System.out.println("Result has type: " + e.typeCheck(env));',
' System.out.println("Result: " + e);',
' System.out.println("Terminating State: " + s);',
' } catch (TypeError te) {',
' System.out.printf("Error:%n%s", te);',
' System.out.printf("From code:%n%s", e);',
' } catch (CanNotReduce cnr) {',
' System.out.println("Caught Following exception" + cnr);',
' System.out.printf("While trying to execute:%n%s", e);',
' System.out.printf("In state:%n%s", s);',
' }',
' }',
'',
'}',
''
])
return '\n'.join(lines)
|
b61a4fee235835f980841354bbc07e1703b37f17 | gasgustavo/pacman_search_agent | /pacman/search/hanoitower.py | 4,242 | 3.90625 | 4 |
from copy import deepcopy
import search
import random
# Module Classes
class HanoiTowerSearchProblem(search.SearchProblem):
"""
Implementation of a SearchProblem for the Hanoi Tower problem
Each state is represented by an instance of an Hanoi Tower.
"""
def __init__(self, hanoi_size, slot_size):
"Creates a new Hanoi Tower which stores search information."
self.hanoi_size = hanoi_size
self.slot_size = slot_size
self.hanoi_tower = createRandomHanoiTower(self.hanoi_size, self.slot_size)
def getStartState(self):
"""
Returns the start state for the search problem.
"""
return self.hanoi_tower
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state.
"""
condition_1 = sum([len(i) > 0 for i in state]) == 1 # all objects are in same space
condition_2 = [i == sorted(i, reverse=True) for i in state if len(i) > 0][0] # ordered objects
return condition_1 and condition_2
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost' is
the incremental cost of expanding to that successor.
"""
successors = []
for leaving_position in range(self.slot_size):
for arriving_position in range(self.slot_size):
leaving_stack = state[leaving_position]
if state[leaving_position]:
arriving_stack = state[arriving_position]
if arriving_stack:
if leaving_stack[-1] < arriving_stack[-1]:
successor = deepcopy(state)
successor[arriving_position].append(successor[leaving_position].pop())
successors.append((successor, [leaving_position, arriving_position], 1))
else:
successor = deepcopy(state)
successor[arriving_position].append(successor[leaving_position].pop())
successors.append((successor, [leaving_position, arriving_position], 1))
return successors
def draw_hanoi_tower(state):
max_columns = max([max(i) for i in state if len(i)])
max_rows = max_columns#max([len(i) for i in state])
draw = ['#' for i in range(max_rows)]
for slot in state:
slot_size = len(slot)
for row in range(max_rows):
if slot_size < (row+1):
draw[row] += ' '*max_columns
else:
draw[row] += '-' * slot[row]
draw[row] += ' '*(max_columns - slot[row])
draw[row] += '#'
draw = ['#'*((max_columns+1)*len(state)+1)] + draw
draw.reverse()
for i in draw:
print(i)
def createRandomHanoiTower(hanoi_size, slot_size):
"""
hanoi_size: de maximum size of a hanoi piece
slot_size: number of slots that you can put your hanoi pieces
Creates a random hanoi tower
"""
hanoi_tower = [[] for _ in range(slot_size)]
for i in range(1, hanoi_size + 1):
random_position = random.randint(0, slot_size - 1)
hanoi_tower[random_position].append(i)
for sublist in hanoi_tower:
random.shuffle(sublist)
return hanoi_tower
if __name__ == '__main__':
problem = HanoiTowerSearchProblem(hanoi_size=6, slot_size=3)
hanoi_tower = problem.getStartState()
print('A random hanoi tower: {}'.format('--'.join([str(i) for i in hanoi_tower])))
draw_hanoi_tower(hanoi_tower)
path = search.breadthFirstSearch(problem)
print('BFS found a path of %d moves: %s' % (len(path), str(path)))
i = 1
for action in path:
input("Press return for the next state...") # wait for key stroke
hanoi_tower[action[1]].append(hanoi_tower[action[0]].pop())
print('new configuration: {}'.format('--'.join([str(i) for i in hanoi_tower])))
draw_hanoi_tower(hanoi_tower)
|
1f0ea88bb9cf7996cfed17129e2c4402e70dc5c8 | ailunz/CIS2001-Winter2018 | /FirstWeek/Hello.py | 4,866 | 4.1875 | 4 | import math
# first_name = input("Enter your first name: ")
# last_name = input("Enter your last name: ")
#
# print('Hello ' + first_name + ' ' + last_name + '!')
# #anything after this gets ignored by python
#
# #using int will only work with integers, no decimal places
# hourly_wage = int(input("How much do you earn per hour?"))
#
# hourly_wage = float(input("How much do you earn per hour?"))
# print('You make: ', hourly_wage * 40 , 'per week' )
#
# #() for tuples, [] for lists, {} for dictionaries
# students_names = [ 'Mohamed', 'Jenny', 'Allen', 'Christie', 'Shafali' ]
#
# for student in students_names:
# print(student)
#
# for index in range( len(students_names) ):
# print(students_names[index])
#
# students_names.insert(2, "Bob")
# students_names.remove('Jenny')
# print(students_names)
#
# if 'Eric' in students_names:
# print("Eric is here")
# elif 'Jenny' in students_names:
# print("Jenny is here and Eric is not")
# else:
# print("Eric and Jenny have left the building")
#
# grades = {
# 'Mohamed' : 'A',
# 'Jenny' : 'A',
# 'Allen' : 'A',
# 'Christie' : 'A',
# 'Shafali' : 'A'
# }
#
# if 'Mohamed' in grades:
# print(grades['Mohamed'])
# else:
# print("Not an A student")
#
# sorted_names = sorted(list(grades.keys()))
#
# for student in sorted_names:
# print(student, ' grade: ', grades[student])
#
# for student, grade in grades.items():
# print(student, grade)
#
# favorite_number = int(input("What is your favorite number?"))
#
# if favorite_number == 42:
# print("You have the answer")
# else:
# print("go read hitch hikers guide to the galaxy")
#
# print( 5 % 2 )
#
# primes = []
#
# for number in range(2,1000):
# is_prime = True
# divisor = 2
# while is_prime and divisor < number:
# if number % divisor == 0:
# is_prime = False
# divisor += 1
# # divisor = divisor + 1
# if is_prime:
# print(number)
# primes.append(number)
#
# # list/string slicing
# print(primes[::-1])
#
# alphabet = 'abcdefghijklmnopqrstuvwsxyz'
# print( alphabet[::2])
#
# start of 1/18
def find_largest( list_to_search ):
largest = list_to_search[0]
for index in range(1,len(list_to_search)):
if list_to_search[index] > largest:
largest = list_to_search[index]
return largest
def find_smallest( list_to_search ):
smallest = list_to_search[0]
for index in range(1,len(list_to_search)):
if list_to_search[index] < smallest:
smallest = list_to_search[index]
return smallest
def find_average( list_to_average ):
return sum(list_to_average) / len(list_to_average)
def find_median( list_to_find_median ):
sorted_list = sorted(list_to_find_median)
# even length
if len(sorted_list) % 2 == 0:
middle_index_right_side = len(sorted_list) // 2
middle_index_left_side = middle_index_right_side - 1
# slow way
return( sorted_list[middle_index_left_side] + sorted_list[middle_index_right_side] ) / 2
else: # must be odd
middle_index = len(sorted_list) // 2
return sorted_list[middle_index], 10
def find_population_standard_deviation( list_to_find ):
average = find_average(list_to_find)
running_total_variance = 0
for value in list_to_find:
# same as ( running_total_variance = running_total_variance + (value - average)**2 )
# ** is to the power of
running_total_variance += (value - average)**2
variance = running_total_variance / len(list_to_find)
return math.sqrt(variance)
favorite_numbers_list = [ 13, 7, 9, 3, 8, 6 ]
print(find_largest(favorite_numbers_list))
print(find_smallest(favorite_numbers_list))
print( find_average(favorite_numbers_list) )
print( find_median( favorite_numbers_list))
def add_and_subtract( first_value, second_value ):
add = first_value + second_value
subtract = first_value - second_value
return add, subtract
#addition_result, subtraction_result = add_and_subtract( 10, 15 )
#print("10 + 15 =", addition_result)
#print("10 - 15 =", subtraction_result)
result = add_and_subtract( 10, 15 )
print("10 + 15 =", result[0])
print("10 - 15 =", result[1])
add_and_subtract( second_value=15, first_value=10)
# default arguments
def print_the_date( month, day, year="2018"):
month = "Jan"
print(month + "/" + day + "/" + year)
month = "01"
print_the_date(month, "18")
print_the_date(month, "18", "2017")
print(month)
place_to_eat = ""
hungry_for_thai_food = True
if hungry_for_thai_food:
place_to_eat = "Hang's Bistro"
else:
place_to_eat = "McDonalds"
place_to_eat = "Hang's Bistro" if hungry_for_thai_food else "McDonalds"
evens = [number for number in favorite_numbers_list if number % 2 == 0]
squares = [number**2 for number in favorite_numbers_list ]
print(evens)
print(squares) |
6cb77ec39c118f9ae536315a1e35cbd156946369 | liaochengyu/Data-Visualization | /code/Legends, Titles, and Labels with Matplotlib.py | 416 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# url: https://pythonprogramming.net/matplotlib-intro-tutorial/
import matplotlib.pyplot as plt
x=[1,2,3]
y=[5,7,4]
x2=[1,2,3]
y2=[10,14,12]
plt.plot(x,y,label='first line')
plt.plot(x2,y2,label='second line')
plt.legend()
plt.xlabel('plot number')
plt.ylabel('important var')
plt.title('interesting graph \n check it out')
plt.show()
# if __name__=='__main__':
|
323a60561d12c2f1a84226fc31b2d518bad64466 | Andrewlearning/Leetcoding | /leetcode/LinkedList/删除/1171. 从链表中删去总和值为零的连续节点(前缀和+两数之和).py | 1,426 | 3.65625 | 4 | """
Given the head of a linked list, we repeatedly delete consecutive sequences of
nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list.
You may return any such answer.
Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.
"""
class Solution(object):
def removeZeroSumSublists(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
preFix = 0
dummy = ListNode(0)
dummy.next = head
m = {}
cur = dummy
# 每次都把当前的(前缀合, 对应的节点) 存在map里
while cur:
preFix += cur.val
m[preFix] = cur # 相同的preFixSumn只保留最后一个
cur = cur.next
preFix = 0
cur = dummy
while cur:
preFix += cur.val
# 假如我们找到两个前缀和一样的节点,说明这两个节点之间的节点和为0
# 应该直接跳过
# list: [1,2,-3,3,1]
# prefix: [1,3, 0,3,1]
# 我们可以发现在[-3,3]应该被剔除,所以应该把 [1,2, 1]连起来
cur.next = m[preFix].next
cur = cur.next
return dummy.next
"""
古城算法 16:22
https://www.bilibili.com/video/BV1e5411c7JR/?spm_id_from=333.999.0.0&vd_source=b81616a45fd239becaebfee25e0dbd35
""" |
5ff45c3cab06347efd5686f8a5a4d106f1e696fa | garymale/python_learn | /python_oneline.py | 2,579 | 3.890625 | 4 | # _*_ coding: utf-8 _*_
# 一行代码启动一个Web服务
# python -m SimpleHTTPServer 8080
# python3 -m http.server 8080
# # 一行代码实现变量值互换
# a, b = 1, 2; a, b = b, a;
#
#
# # 一行代码解决FizzBuzz问题: 打印数字1到100, 3的倍数打印“Fizz”来替换这个数, 5的倍数打印“Buzz”, 既是3又是5的倍数的打印“FizzBuzz”
# print(' '.join(["fizz"[x % 3 * 4:]+"buzz"[x % 5 * 4:] or str(x) for x in range(1, 101)]))
#
#
# # 一行代码输出特定字符"Love"拼成的心形
# print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))
#
#
# # 一行代码输出Mandelbrot图像: Mandelbrot图像中的每个位置都对应于公式N=x+y*i中的一个复数
# print('\n'.join([''.join(['*'if abs((lambda a: lambda z, c, n: a(a, z, c, n))(lambda s, z, c, n: z if n == 0 else s(s, z*z+c, c, n-1))(0, 0.02*x+0.05j*y, 40)) < 2 else ' ' for x in range(-80, 20)]) for y in range(-20, 20)]))
#
#
# # 一行代码打印九九乘法表
# print('\n'.join([' '.join(['%s*%s=%-2s' % (y, x, x*y) for y in range(1, x+1)]) for x in range(1, 10)]))
#
#
# # 一行代码计算出1-100之间的素数(两个版本)
# print(' '.join([str(item) for item in filter(lambda x: not [x % i for i in range(2, x) if x % i == 0], range(2, 101))]))
# print(' '.join([str(item) for item in filter(lambda x: all(map(lambda p: x % p != 0, range(2, x))), range(2, 101))]))
#
#
# # 一行代码输出斐波那契数列
# print([x[0] for x in [(a[i][0], a.append([a[i][1], a[i][0]+a[i][1]])) for a in ([[1, 1]], ) for i in range(30)]])
#
#
# # 一行代码实现快排算法
# qsort = lambda arr: len(arr) > 1 and qsort(list(filter(lambda x: x <= arr[0], arr[1:]))) + arr[0:1] + qsort(list(filter(lambda x: x > arr[0], arr[1:]))) or arr
#
#
# # 一行代码解决八皇后问题
# [__import__('sys').stdout.write('\n'.join('.' * i + 'Q' + '.' * (8-i-1) for i in vec) + "\n========\n") for vec in __import__('itertools').permutations(range(8)) if 8 == len(set(vec[i]+i for i in range(8))) == len(set(vec[i]-i for i in range(8)))]
#
#
# # 一行代码实现数组的flatten功能: 将多维数组转化为一维
# flatten = lambda x: [y for l in x for y in flatten(l)] if isinstance(x, list) else [x]
#
#
# # 一行代码实现list, 有点类似与上个功能的反功能
# array = lambda x: [x[i:i+3] for i in range(0, len(x), 3)]
#
#
# # 一行代码实现求解2的1000次方的各位数之和
# print(sum(map(int, str(2**1000))))
|
aa60f672ccd0187013e6c80883dae6672839e209 | ivan-ver/Guess_the_number | /main.py | 2,810 | 3.75 | 4 | import numpy as np
def guess_the_number(target_number: int, max_number: int) -> int:
"""Функция подбора загаданного числа
Args:
target_number (int): Загаданное число
max_number (int): Верхняя граница диапазона "угадывания" числа
Returns:
int: Количество попыток
"""
min_number = 1 # Нижняя граница диапазона в первой итерации
generated_number = np.random.randint(min_number, max_number) # Первое сгенерированое число
count = 1 # Количество попыток
# print(f'Target number: {target_number}')
while generated_number != target_number: # Запускается цикл генерации числа, работающий до тех пор, пока сгенериованное число не будет равно загаданному
# print(f'Generated number: {generated_number}')
count += 1 # Инкрементация значения количества попыток
if generated_number > target_number: # Если сгенерированное число больше загаданного
max_number = generated_number # Верхняя граница диапазона смещается "вниз", до значения сгенерированного числа
else: # Если сгенерированное число меньше загаданного
min_number = generated_number # Нижняя граница диапазона смещается "вверх", до значения сгенерированного числа
generated_number = np.random.randint(min_number, max_number) # Генерация числа с новыми границами диапазона
# print(f'Number of attempts: {count}')
return count
def get_statistics(function, count) -> int:
"""Функция статистики, считает среднее число попыток
Args:
function ([type]): Исследуемая функция
count ([type]): Общее число тестов
Returns:
int: среднее число попыток
"""
counts_list = [
function(target_number=np.random.randint(1, 101), max_number=101) for _ in range(count)
] # Список результатов теста
return f"Среднее число попыток: {np.mean(counts_list)}, при количестве тестов - {count}"
if __name__ == "__main__":
# guess_the_number(target_number=np.random.randint(1, 101), max_number=101)
print(get_statistics(function=guess_the_number, count=1000)) |
e2cbab0232b1b4e53a1cf6f1c91c1bbeb25d6cdc | emark1/Assignment-1 | /yourname.py | 269 | 4.5 | 4 | #String Interpolation
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
print("Thanks! Your name is " + first_name + " " + last_name)
full_name = (f"Or, interpolated, your name is {first_name} {last_name}")
print(full_name) |
0e8265bde58646f2f2eebc70229c891971314c55 | MatthewMing11/TriMat | /gmath.py | 897 | 3.625 | 4 | import math
from display import *
def magnitude(vector):
return math.sqrt(math.pow(vector[0],2)+math.pow(vector[1],2)+math.pow(vector[2],2))
#vector functions
#normalize vector, should modify the parameter
def normalize(vector):
print(vector)
length = magnitude(vector)
if length==0:
return vector
else:
vector[0]/=length
vector[1]/=length
vector[2]/=length
return vector
#Return the dot porduct of a . b
def dot_product(a, b):
return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]
#Calculate the surface normal for the triangle whose first
#point is located at index i in polygons
def calculate_normal(polygons, i):
p0=polygons[i]
p1=polygons[i+1]
p2=polygons[i+2]
a=[p1[0]-p0[0],p1[1]-p0[1],p1[2]-p0[2]]
b=[p2[0]-p0[0],p2[1]-p0[1],p2[2]-p0[2]]
n=[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]]
return n
|
d76297c540142657072e2abd2327529776fbb155 | abr-98/FADACS_Parking_Prediction | /models/adda_models/callback.py | 2,475 | 3.578125 | 4 | class Callback(object):
"""
Abstract base class used to build new callbacks.
"""
def __init__(self):
pass
def set_params(self, params):
self.params = params
def set_trainer(self, model):
self.trainer = model
def on_epoch_begin(self, epoch, loss):
pass
def on_epoch_end(self, epoch, loss):
pass
def on_batch_begin(self, batch, loss):
pass
def on_batch_end(self, batch, loss):
pass
def on_train_begin(self):
pass
def on_train_end(self):
pass
class EarlyStopping(Callback):
"""
Early Stopping to terminate training early under certain conditions
"""
def __init__(self, min_delta=0, patience=10):
"""
EarlyStopping callback to exit the training loop if training or
validation loss does not improve by a certain amount for a certain
number of epochs
Arguments
---------
monitor : string in {'val_loss', 'loss'}
whether to monitor train or val loss
min_delta : float
minimum change in monitored value to qualify as improvement.
This number should be positive.
patience : integer
number of epochs to wait for improvment before terminating.
the counter be reset after each improvment
"""
self.min_delta = min_delta
self.patience = patience
self.wait = 0
self.best_loss = 1e-15
self.best_epoch = 0
self.stopped_epoch = 0
self.stop_flag = False
super(EarlyStopping, self).__init__()
def on_train_begin(self):
self.wait = 0
self.best_loss = 1e15
def on_epoch_end(self, epoch, loss):
current_loss = loss
if current_loss is None:
pass
else:
if (current_loss - self.best_loss) < -self.min_delta:
self.best_loss = current_loss
self.best_epoch = epoch
self.wait = 1
else:
if self.wait >= self.patience:
self.stopped_epoch = epoch + 1
self.stop_flag = True
self.wait += 1
def on_train_end(self):
if self.stopped_epoch > 0:
print('\nTerminated Training for Early Stopping at Epoch %04i' %
(self.stopped_epoch)) |
db56d84911eac1cae9be782fd2ebb047c625fce2 | pranaychandekar/dsa | /src/sorting/bubble_sort.py | 1,488 | 4.46875 | 4 | import time
class BubbleSort:
"""
This class is a python implementation of the problem discussed in this
video by mycodeschool - https://www.youtube.com/watch?v=Jdtq5uKz-w4
:Authors: pranaychandekar
"""
@staticmethod
def bubble_sort(unsorted_list: list):
"""
This method sorts a given list in ascending order using Bubble Sort algorithm.
:param unsorted_list: The list which needs to be sorted.
:type unsorted_list: list
"""
unsorted_list_size = len(unsorted_list)
for i in range(unsorted_list_size - 1):
all_sorted = True
for j in range(unsorted_list_size - i - 1):
if unsorted_list[j] > unsorted_list[j + 1]:
temp = unsorted_list[j]
unsorted_list[j] = unsorted_list[j + 1]
unsorted_list[j + 1] = temp
all_sorted = False
if all_sorted:
break
if __name__ == "__main__":
tic = time.time()
print("\nYou are currently running Bubble Sort test case.")
unsorted_list = [2, 7, 4, 1, 5, 3]
print("\nUnsorted List: ")
for element in unsorted_list:
print(str(element), end=", ")
print()
BubbleSort.bubble_sort(unsorted_list)
print("\nSorted List: ")
for element in unsorted_list:
print(str(element), end=", ")
print()
toc = time.time()
print("\nTotal time taken:", toc - tic, "seconds.")
|
efb0aa150fb9eb13c889ca0dccefd5ba65c9bc44 | raviolliii/PythonMinis | /sudoku/sudoku.py | 1,220 | 3.546875 | 4 |
def printBoard(board):
for row in board:
for c in row:
print(c, end = " ")
print()
def getZeroPositions(board):
posList = []
for r in range(len(board)):
for c in range(len(board[r])):
if not board[r][c]:
posList.append((r, c))
return posList
def getSquarePossibilites(board, pos):
startx = 6 if pos[0] > 5 else 3 if pos[0] > 2 else 0
starty = 6 if pos[1] > 5 else 3 if pos[1] > 2 else 0
res = []
for r in range(3):
for c in range(3):
n = board[startx + r][starty + c]
if n:
res.append(n)
return res
def solveBoard(board, zeroPosList):
if not zeroPosList:
printBoard(board)
return
for pos in zeroPosList:
r, c = pos[0], pos[1]
row = board[r]
col = [row[c] for row in board]
nums = range(1, 10)
nums = list(filter(lambda x: (x not in row) and (x not in col) and (x not in getSquarePossibilites(board, pos)), nums))
if len(nums) == 1:
board[r][c] = nums[0]
zeroPosList.remove(pos)
break
solveBoard(board, zeroPosList)
def initBoard():
file = open("board.txt", "r")
board = []
for line in file:
l = line.strip()
row = [int(x) for x in l.split(" ")]
board.append(row)
return board
board = initBoard()
solveBoard(board, getZeroPositions(board))
|
efba9f428cc0e30431bd5694046c072513990cf6 | nlucero-sg/AdventOfCode | /day13.py | 3,999 | 3.578125 | 4 | class Node:
def __init__(self, x, y):
self.x = x
self.y = y
class Edge:
def __init__(self, node_1, node_2):
self.nodes = frozenset([node_1, node_2])
class Map:
def __init__(self):
self.nodes = set()
self.edges = set()
def add_node(self, node):
self.nodes.add(node)
def add_edge(self, edge):
self.edges.add(edge)
def get_edges(self, node):
if node not in self.nodes:
raise IndexError('{} not in map nodes'.format(node))
return frozenset([e.nodes for e in self.edges if node in e.nodes])
def get_neighbors(self, node):
node_set = set()
for edge in self.get_edges(node):
for n in edge:
node_set.add(n)
node_set.remove(node)
return node_set
def get_node(self, x, y):
try:
return [node for node in self.nodes if node.x == x and node.y == y][0]
except:
return None
@staticmethod
def heuristic_cost_estimate(neighbor, goal):
return abs(neighbor.x - goal.x) + abs(neighbor.y - goal.y)
class Game:
def __init__(self, start_node, end_node, map):
self.map = map
self.start_node = start_node
self.end_node = end_node
def a_star(graph, start_node, goal_node):
closed_set = set()
open_set = set([start_node])
came_from = {}
g_score = dict([(node, 100000) for node in graph.nodes])
g_score[start_node] = 0
f_score = dict([(node, 100000) for node in graph.nodes])
f_score[start_node] = Map.heuristic_cost_estimate(start_node, goal_node)
while len(open_set) > 0:
current = min(open_set, key=(lambda key: f_score[key]))
if current == goal_node:
return reconstruct_path(came_from, current)
open_set.remove(current)
closed_set.add(current)
for neighbor in graph.get_neighbors(current):
if neighbor in closed_set:
continue
tentative_g_score = g_score[current] + 1
if neighbor not in open_set:
open_set.add(neighbor)
elif tentative_g_score >= g_score[neighbor]:
continue
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = g_score[neighbor] + Map.heuristic_cost_estimate(neighbor, goal_node)
return -1
def reconstruct_path(came_from, current):
total_path = [current]
while current in came_from.keys():
current = came_from[current]
total_path.append(current)
return total_path
def is_open(node, dnum):
x, y = node.x, node.y
n = ((x * x) + (3 * x) + (2 * x * y) + y + (y * y)) + dnum
return sum(int(i) for i in "{0:b}".format(n)) % 2 == 0
def build_game(width, height, dnum, start_tuple, goal_tuple):
m = Map()
grid = {}
for y in range(height):
grid[y] = {}
for x in range(width):
n = Node(x, y)
if is_open(n, dnum):
grid[y][x] = n
m.add_node(n)
for y in range(height):
for x in range(width):
if not (y in grid and x in grid[y]):
continue
if y-1 in grid:
if x in grid[y-1]:
m.add_edge(Edge(grid[y][x], grid[y-1][x]))
if y+1 in grid:
if x in grid[y+1]:
m.add_edge(Edge(grid[y][x], grid[y+1][x]))
if x-1 in grid[y]:
m.add_edge(Edge(grid[y][x], grid[y][x-1]))
if x+1 in grid[y]:
m.add_edge(Edge(grid[y][x], grid[y][x+1]))
sx, sy = start_tuple
gx, gy = goal_tuple
return Game(m.get_node(sx, sy), m.get_node(gx, gy), m)
g = build_game(10, 10, 10, (1, 1), (7, 4))
a = a_star(g.map, g.start_node, g.end_node)
print(a)
print(len(a)-1)
g2 = build_game(1000,1000,1350, (1, 1), (31, 39))
a2 = a_star(g2.map, g2.start_node, g2.end_node)
print(a2)
print(len(a2)-1) |
06d3202cc7b26472e7f324264c8940510e0c555d | KruKuma/attendanceRecord | /moduleAttendanceRecords.py | 10,717 | 4 | 4 | # moduleAttendanceRecords.py
# Author: Naphatsakorn Khotsombat
# Description: The Module Attendance Records programme will allow a lecturer do the following tasks for any
# module that they teach.
import numpy as np # Added numpy to improve array
def writeLine():
"""
Function for printing out lines
:return:
"""
print("-" * 35)
def checkForNum(prompt):
"""
Using a value as a prompt from one of the option to verified if its an int or not
:parameter prompt (int)
:returns (int)
"""
while True:
try:
number = int(input(prompt))
break
except ValueError:
print("Must be numeric...")
return number
def loginScreen():
"""
Print out the login screen for the user to input name and password to verified if the name or password
is in the database or not
"""
while True:
name = input("Name: ")
password = input("Password: ")
userData = open('loginData.txt', 'r')
data = userData.read().splitlines()
userName, userPass = data[:2]
if name == userName and password == userPass:
print("Welcome Anna")
break
else:
print("Module Record System - Login Failed")
def loadModules():
"""
This function will read the modules.txt file, it will turn the contents of the file into a list and then return
the list to be use in other function
:return: (String)
"""
moduleInfo = open('modules.txt', 'r')
moduleCodeList = []
moduleNameList = []
# Use while loop to make the list of module code and name
while True:
line = moduleInfo.readline().strip()
if line == "":
break # Stop the loop if there's no other line in the file
lineData = line.split(', ')
moduleCodeList.append(lineData[0])
moduleNameList.append(lineData[1])
moduleInfo.close()
# print(moduleCodeList)
# print(moduleNameList)
return moduleCodeList, moduleNameList
def mainMenuScreen():
"""
This function will display the main menu screen for the use to choose an option then return that option
:return: (String)
"""
print("Module Record System - Options")
writeLine()
while True:
userOption = checkForNum("1. Record Attendance"
"\n2. Generate Statistics"
"\n3. Exit"
"\n>>")
if 0 < userOption <= 3:
break
else:
print("Invalid input! Must be a number between 1 to 3")
if userOption == 1:
userOption = 1
if userOption == 2:
userOption = 2
if userOption == 3:
exit()
return userOption
def recordAttendanceMainScreen(moduleCodeList):
"""
Take in the mode code list and display it as an option for the user to pick from then will return the code of the
module to be use later.
:parameter moduleCodeList(String)
:return: (String)
"""
print("Module Record System(Attendance) - Choose a Module")
writeLine()
while True:
userOption = checkForNum(f"1. {moduleCodeList[0]}"
f"\n2. {moduleCodeList[1]}"
"\n>>>")
if userOption == 1:
moduleCode = "SOFT_6017"
break
elif userOption == 2:
moduleCode = "SOFT_6018"
break
else:
print("Invalid input! Must be a number between 1 to 2")
return moduleCode
def getClassAttendance(moduleCode):
"""
Will take in the module code and use the code to open the file of the specified module and read it to created
the list of names, presents, absents and excuses. To be return for future use
:param moduleCode:
:return: (list)
"""
classData = open(f"{moduleCode}.txt", 'r')
studentNameList = []
presentList = []
absentList = []
excuseList = []
while True:
line = classData.readline().strip()
if line == "":
break
lineData = line.split(',')
studentNameList.append(lineData[0])
presentList.append(int(lineData[1]))
absentList.append(int(lineData[2]))
excuseList.append(int(lineData[3]))
classData.close()
# print(presentList)
# print(absentList)
# print(excuseList)
return studentNameList, presentList, absentList, excuseList
def takeClassAttendance(moduleCode, studentNameList, presentList, absentList, excuseList):
"""
Use the module code to be print out in the top of the menu and use the list generated before to take attendance
for the class then send the list to be update.
:param moduleCode:
:param studentNameList:
:param presentList:
:param absentList:
:param excuseList:
"""
print(f"Module Record System(Attendance) - {moduleCode}")
writeLine()
print(f"There are {len(studentNameList)} students enrolled.")
for i, student in enumerate(studentNameList):
attendance = int(input(f"Student #{i + 1}: {studentNameList[i]}\n"
f"1. Present\n"
f"2. Absent\n"
f"3. Excused\n> "))
if attendance == 1:
presentList[i] += 1
if attendance == 2:
absentList[i] += 1
if attendance == 3:
excuseList[i] += 1
updateClassDate(moduleCode, studentNameList, presentList, absentList, excuseList)
def updateClassDate(moduleCode, studentNameList, presentList, absentList, excuseList):
"""
Take in the updated list to be writen into the module file to updated it. The function opens the file and updated
it accordingly.
:param moduleCode:
:param studentNameList:
:param presentList:
:param absentList:
:param excuseList:
"""
classData = open(f"{moduleCode}.txt", "w")
for x in range(len(studentNameList)):
print(f"{studentNameList[x]},{presentList[x]},{absentList[x]},{excuseList[x]}", file=classData)
print(f"{moduleCode}.txt updated with latest attendance records")
classData.close()
writeLine()
def genStatScreen(moduleCodeList):
"""
Use the module code list to display the option for the user to pick from then returns the module code in string
to be used in the other function.
:param moduleCodeList:
:return: (String)
"""
print("Module Record System(Statistics) - Choose a Module")
writeLine()
while True:
userOption = checkForNum(f"1. {moduleCodeList[0]}"
f"\n2. {moduleCodeList[1]}"
"\n>>")
if userOption == 1:
moduleCode = "SOFT_6017"
break
elif userOption == 2:
moduleCode = "SOFT_6018"
break
else:
print("Invalid input! Must be a number between 1 to 2")
return moduleCode
def generateAndSaveStats(moduleCode, studentNameList, presentList, absentList, excuseList):
"""
Use the module code to be display and use the other to calculate different number then display it in other output
:param moduleCode:
:param studentNameList:
:param presentList:
:param absentList:
:param excuseList:
:return:
"""
totalClasses = calTotalDays(presentList, absentList, excuseList)
attendanceRateList = calAttendanceRate(presentList, absentList, excuseList)
numStudent = len(studentNameList)
avgAttendance = sum(presentList) / len(presentList)
names = np.array(studentNameList) # Declare a numpy list for names from the list of student name
values = np.array(attendanceRateList) # Declare a numpy list for values from the attendances rate
# Use numpy to get a list of student names that have less then 70% attendances rate
lowAttendanceRateName = names[np.where(values < 70)]
# Use numpy to get a list of student names that have less then 0 attendances rate
nonAttenderName = names[np.where(values == 0)]
# Use numpy to get a list of student name that have the best attendances rate
bestAttenderName = names[np.where(values == max(values))[0]]
print(f"Module: {moduleCode}"
f"\nNumber of students: {numStudent}"
f"\nNumber of Classes: {totalClasses}"
f"\nAverage Attendance: {avgAttendance}")
print("Low Attender(s):")
for names in lowAttendanceRateName: # Use a for loop to print out the name of low attendance rate students
print(f"\t\t{names}")
print("None Attender(s):")
for names in nonAttenderName: # Use a for loop to print out the name of students that don't attend
print(f"\t\t{names}")
print("Best Attender(s):")
for names in bestAttenderName: # Use a for loop to print out the name of students with best attendance
print(f"\t\t{names}")
writeLine()
def calTotalDays(presentList, absentList, excuseList):
"""
Use present, absent and excuse list to calculate the total amount of days since the class began
:param presentList:
:param absentList:
:param excuseList:
:return: (int)
"""
totalDays = presentList[1] + absentList[1] + excuseList[1]
return totalDays
def calAttendanceRate(presentList, absentList, excuseList):
"""
Use present, absent and excuse list to calculate the attendances rate of each student and return the list of it
:param presentList:
:param absentList:
:param excuseList:
:return: (list)
"""
attendanceRateList = []
# Use a for loop to get the attendance rate for each student and put it into a list
for i in range(len(presentList)):
rate = ((presentList[i] / (presentList[i] + absentList[i] + excuseList[i])) * 100)
attendanceRateList.append(rate)
return attendanceRateList
def main():
loginScreen()
moduleCodeList, moduleNameList = loadModules()
while True:
mainMenuChoice = mainMenuScreen()
if mainMenuChoice == 1:
moduleCode = recordAttendanceMainScreen(moduleCodeList)
studentNameList, presentList, absentList, excuseList = getClassAttendance(moduleCode)
takeClassAttendance(moduleCode, studentNameList, presentList, absentList, excuseList)
if mainMenuChoice == 2:
moduleCode = genStatScreen(moduleCodeList)
studentNameList, presentList, absentList, excuseList = getClassAttendance(moduleCode)
generateAndSaveStats(moduleCode, studentNameList, presentList, absentList, excuseList)
main()
|
f71a6d1b7f131057c5721642272ca7ce9c24f18b | yilinmiao/movie_trailer_website | /media.py | 725 | 3.703125 | 4 | import webbrowser
class Movie():
""" This class provides a way to store movie related information
Args:
movie_title (str)
box_art (str): Movies' Posters.
trailer_link (str): Youtube Links.
Attributes:
movie_title (str)
box_art (str): Movies' Posters.
trailer_link (str): Youtube Links.
"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
# define constructor/initialization method for class movie
# constructor contains parameters: movie_title, box_art, trailer_link.
def __init__(self, movie_title, box_art, trailer_link):
self.title = movie_title
self.poster_image_url = box_art
self.trailer_youtube_url = trailer_link
|
e2aa6452df5ca62c12a065ceedda14b00bad2f8a | jaewon-jun9/rpa | /excel/old/excelrange.py | 1,109 | 3.8125 | 4 | def excelNum(string):
num=0
for i,j in enumerate(string):
if ord(j)>57:
num=num+(ord(j.upper())-64)*(26**(len(string)-i-1))
else:
num=num+int(j)*10**(len(string)-i-1)
return num
def excelString(string):
row=excelNum(list(filter(str.isalpha,string)))
col=excelNum(list(filter(str.isdigit,string)))
return ([row,col])
def cellRange(startCell,endCell):
start=excelString(startCell)
end=excelString(endCell)
if start[0]>end[0] or start[1]>end[1]:
print("error range")
return "error range"
else:
return (start+end)
def readCell(addList):
import openpyxl
all_values=[]
for row in range(addList[1],addList[3]+1): #row 단위로 읽기
row_value=[] #row 마다 셀의 값을 저장
for cell in range(addList[0],addList[2]+1): #row 마다 cell 단위로 데이터 읽기
row_value.append(load_ws.cell(row,cell).value) #row_value에 cell의 내용을 넣어주어 row를 완성
all_values.append(row_value) #row를 전체 리스트에 추가
return all_values |
db3c761c7af7b7428950d5850d0b05c984a036f8 | JJong0416/Algorithm | /Programmers/2Level/SummerWinterCoding/an_intact_square_62048/choboman.py | 381 | 3.53125 | 4 | # w : 가로, h : 세로
def solution(w, h):
total_paper = w * h
temp_paper = w + h
answer = 0
if w > h:
pass
else:
w, h = h, w
# w가 최대공약수로 변환되어 나옴
# 유클리드 호제법
while h > 0:
w, h = h, w % h
answer = total_paper - temp_paper + w
return answer
print(solution(8, 12))
|
cecb39bc407023869dd40c694c6657ebedc1ae56 | mgcarbonell/30-Days-of-Python | /15_comprehension.py | 4,655 | 4.8125 | 5 | # there are many types of comprehrension in python, but most commonly used is list comprehension.
# List comprehension is used to create a new list from some other iterable. It might be another list or even a zip object.
names = ["mary", "Richard", "Noah", "KATE"]
# Take a look at the names list and notice that they're not consistent.
# When can this happen? Grabbing data from a user.
# Let's make it all title case, we can interate over and create a new list.
processed_names = []
for name in names:
processed_names.append(name.title())
# we would expect back a list of title case names: Mary, Richard, Noah, Kate
# While there's nothing wrong with this approach per se, we do create a new list and we can't simply get rid of our old list.
# It's potentially unncessary as well because we can just comprehension syntax!
processed_names = [name.title() for name in names]
# or we can just use... names
names = [name.title() for name in names]
# let's dissect this:
# In the above example the VALUE we want to ADD is name.title()
# The loop we have defined is `for name in names`
# Think of it like this: "Put name.title() in the new list for every name in names."
# Another example. We can have code like this:
names = ("mary", "Richard", "Noah", "KATE")
ages = (36, 21, 40, 28)
people = []
for name, age in zip(names, ages):
person_data = (name.title(), age)
people.append(person_data)
# OR we can rewrite this using COMPREHENSION
names = ("mary", "Richard", "Noah", "KATE")
ages = (36, 21, 40, 28)
people = [(name.title(), age) for name, age in zip(names, ages)]
# whew that looks cleaner.
# We would end up with: [('Mary', 36), ('Richard', 21), ('Noah', 40), ('Kate', 28)]
# SET COMPREHENSION
# This works just like list comprehesnion but produces a set rather than a list
names = ["mary", "Richard", "Noah", "KATE"]
names = {name.title() for name in names}
# => {'Mary', 'Richard', 'Noah', 'Kate'}
# DICTIONARY COMPREHENSION
# Like set comprehension, dictionary comprehensions are surrounded by curly bois {}
# Dict comprehension are a little different from list and set because dicts need both a key & a value. The syntax we use for the key value pair is the same as when we define a dictionary normally. First we have the key, followed by a ':' and then the value.
# Let's take a look. We used to do this:
student_ids = (112343, 134555, 113826, 124888)
names = ("mary", "Richard", "Noah", "KATE")
students = {}
for student_id, name in zip(student_ids, names):
student = {student_id: name.title()}
students.update(student)
# => {112343: 'Mary', 134555: 'Richard', 113826: 'Noah', 124888: 'Kate'}
# OR we can produce the SAME dictionary when we do this:
student_ids = (112343, 134555, 113826, 124888)
names = ("mary", "Richard", "Noah", "KATE")
students = {
student_id: name.title()
for student_id, name in zip(student_ids, names)
}
# => {112343: 'Mary', 134555: 'Richard', 113826: 'Noah', 124888: 'Kate'}
# So to walk through: We have the value we want to add to our dictionary, our key value pair which is: student_id: name.title()
# This is followed by the loop definition which determines where the original values are comign from: for student_id, name in zip(student_ids, names)
# All of this is then placed within curly braces to indicate that we're using dictionary comprehension.
# COMPREHENSION AND SCOPE
# How does the scope work in comprehension?
names = ["Mary", "Richard", "Noah", "Kate"]
names_lower = []
for name in names:
names_lower.append(name.lower())
print(name) # This refers to the name variable we defined in the loop
# our output from the print statement is "Kate"
# If we tried to do this with name comprehension we would get a NameError because name is not defined. So what's going on here?
# Comprensions are actually just functions. When we define names_lower[name.lower() for name in names] we're actually writing something like follows:
def temp():
new_list = []
for name in names:
new_list.append(name.lower())
return new_list
# EXERCISES!
# 1) Convert the following for loop into a comprehension:
# numbers = [1, 2, 3, 4, 5]
# squares = []
# for number in numbers:
# squares.append(number ** 2)
numbers = [1, 2, 3, 4, 5]
numbers = [num ** 2 for num in numbers]
print(numbers)
# 2) Use a dictionary comprehension to create a new dictionary from the dictionary below, where each of the values is title case.
movie = {
"title": "thor: ragnarok",
"director": "taika waititi",
"producer": "kevin feige",
"production_company": "marvel studios"
}
movie = {
meta: info.title() for meta, info in movie.items()
}
print(movie)
|
adec65f0c1d2daffbf7f1e12dfdd1c32f02d6b30 | bibinjose/hackerrank | /week challenge/revisedRussianRoulette.py | 587 | 3.609375 | 4 | #https://www.hackerrank.com/contests/w36/challenges/revised-russian-roulette
#!/bin/python3
import sys
def revisedRussianRoulette(doors):
min=0
counter=0
max=(doors.count(1))
for door in doors:
if door==1:
counter+=1
if counter==2:
counter=0
min+=1
else:
counter=0
return max-min,max
if __name__ == "__main__":
n = int(input().strip())
doors = list(map(int, input().strip().split(' ')))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))
|
4fcb1e9201edb4458edfbcfb1125f692d3387a7b | Veraph/Python-Note | /tutorial/guest.py | 200 | 3.9375 | 4 | # create a file and let user write
filename = 'guest.txt'
name = input("please give me your name: \n")
with open(filename, 'a') as file_object:
file_object.write(name)
file_object.write('\n')
|
63971f4a58abca6542113cafd1741d8c7f65f6b9 | eastdog/4fun | /mooc/Algorithmic thinking/module1/application1.py | 3,054 | 3.53125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'victor'
"""
for application number 1
"""
import random
import matplotlib.pyplot as plt
from project1 import in_degree_distribution
from project1 import make_complete_graph
from math import log
class DPATrial:
"""
Simple class to encapsulate optimized trials for DPA algorithm
Maintains a list of node numbers with multiple instances of each number.
The number of instances of each node number are
in the same proportion as the desired probabilities
Uses random.choice() to select a node number from this list for each trial.
"""
def __init__(self, num_nodes):
"""
Initialize a DPATrial object corresponding to a
complete graph with num_nodes nodes
Note the initial list of node numbers has num_nodes copies of
each node number
"""
self._num_nodes = num_nodes
self._node_numbers = [node for node in range(num_nodes) for dummy_idx in range(num_nodes)]
def run_trial(self, num_nodes):
"""
Conduct num_node trials using by applying random.choice()
to the list of node numbers
Updates the list of node numbers so that the number of instances of
each node number is in the same ratio as the desired probabilities
Returns:
Set of nodes
"""
# compute the neighbors for the newly-created node
new_node_neighbors = set()
for dummy_idx in range(num_nodes):
new_node_neighbors.add(random.choice(self._node_numbers))
# update the list of node numbers so that each node number
# appears in the correct ratio
self._node_numbers.append(self._num_nodes)
self._node_numbers.extend(list(new_node_neighbors))
#update the number of nodes
self._num_nodes += 1
return new_node_neighbors
def load_graph(path):
"""
load the graph from file path
:param path
:return:a graph
"""
graph = {}
with open(path) as f:
for line in f:
graph[int(line.split()[0])] = set(map(int, line.strip().split()[1:]))
return graph
def question1():
graph = in_degree_distribution(load_graph('alg_phys-cite.txt'))
del graph[0]
plot(graph)
def plot(graph):
total = sum(graph.values())
X, Y = [], []
for k,v in graph.iteritems():
X.append(k)
Y.append(float(v)/total)
plt.loglog(X, Y, 'ro')
plt.grid(True)
plt.title('log/log plot of in-degree distribution')
plt.xlabel('in-degree')
plt.ylabel('count')
plt.show()
def generate_DPA(m, n):
graph = make_complete_graph(m)
dpatrail = DPATrial(m)
for i in xrange(m, n):
graph[i] = dpatrail.run_trial(m)
return graph
def question4():
graph = in_degree_distribution(generate_DPA(12, 27770))
del graph[0]
plot(graph)
if __name__ == '__main__':
# graph = load_graph('alg_phys-cite.txt')
# print len(graph.keys()), sum(map(lambda x:len(x), graph.values()))/len(graph.keys())
question4() |
2e9cdf371db5840a21196a7fb44ffe424f5c6827 | Holi0317/duty-notify | /utils/cache.py | 903 | 3.609375 | 4 | import os
CACHE_DIR = 'cache'
def make_cache(name, content):
"""
Create cache with given content.
:param str name -- Name, or key of the cache.
:param str content -- Content of the cache
:return bool -- If True, the content is changed with previously cached
content. I.E. should process the updated content.
"""
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR)
path = os.path.join(CACHE_DIR, name)
if not os.path.exists(path):
return _write_cache(name, content)
with open(path, 'r') as file:
read = file.read()
if content == read:
return False
else:
return _write_cache(name, content)
def _write_cache(name, content):
"""
Write content into cache.
:return bool -- True.
"""
with open(os.path.join(CACHE_DIR, name), 'w') as file:
file.write(content)
return True
|
d7acd1d3336f73d4022a3d2f7a3006888c1e13d0 | kyokagong/leetcode | /surroundedRegion.py | 1,508 | 3.875 | 4 | #-*-coding:utf-8-*-#
# 利用bfs 对搜索到的o点进行 广度搜索,搜索这个点的下和右的o点
# 虽然是 accept了,但是本地运行会报 'str' object does not support item assignment 错误
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def fill(x, y):
if x < 0 or y < 0 or x >= m or y >= n or board[x][y] == 'D' or board[x][y] == 'X':
return
board[x][y] = 'D'
queue.append((x, y))
def bfs(x, y):
if board[x][y] == 'O':
fill(x, y)
while queue:
cur_x, cur_y = queue.pop(0)
fill(cur_x + 1, cur_y)
fill(cur_x, cur_y + 1)
fill(cur_x - 1, cur_y)
fill(cur_x, cur_y - 1)
m = len(board)
if m == 0:
return None
n = len(board[0])
queue = []
for i in range(n):
bfs(0, i)
bfs(m - 1, i)
for i in range(m):
bfs(i, 0)
bfs(i, n - 1)
for i in range(m):
for j in range(n):
if board[i][j] == 'D':
board[i][j] = 'O'
elif board[i][j] == 'O':
board[i][j] = 'X'
if __name__ == '__main__':
s = Solution()
board = ["XXXX","XOOX","XXOX","XOXX"]
print(s.solve(board))
|
357e54c2ff5b3ea34c59687e699a22818e0d584e | EdgarRamirezFuentes/Python | /Fundamentos/21.herencia.py | 1,282 | 4.0625 | 4 | class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
## Getters
def getName(self):
return self.__name
def getAge(self):
return self.__age
## Setters
def setName(self, name):
self.__name = name
def setAge (self, age):
self.__age = age
def __str__(self):
return "Name: " + self.__name + " Age: " + str(self.__age)
class Employee(Person): ## Entre paréntesis se indica la clase de la que hereda.
def __init__(self, name, age, salary):
super().__init__(name, age) ## Inicializa los valores de la clase padre
self.__salary = salary
## Getters
def getName(self):
return super().getName()
def getAge(self):
return super().getAge()
## Setters
def setName(self, name):
super().setName(name)
def setAge(self, age):
super().setAge(age)
def setSalary(self, salary):
self.__salary = salary
def __str__(self):
return super().__str__() + " Salary: " + str(self.__salary)
employee = Employee("Edgar Ramírez Fuentes", 21, 20500.00)
employee.setName("Edgar Alejandro Ramírez Fuentes")
print(employee.__str__())
|
7abd554f57038331f50493564ad9f38177345a73 | kimsyversen/Ruter-workflow-for-Alfred | /src/Route.py | 1,131 | 3.5625 | 4 | # encoding: utf-8
class Route(object):
def __init__(self, from_place_id, to_place_id, from_place_name,
to_place_name, arrival_time, departure_time, travel_time, line,
number_of_changes_required, current_time, from_place_district,to_place_district,
deviations):
self.from_place_id = from_place_id
self.to_place_id = to_place_id
self.from_place_name = from_place_name
self.to_place_name = to_place_name
self.arrival_time = arrival_time
self.departure_time = departure_time
self.travel_time = travel_time
self.line = line
self.number_of_changes_required = number_of_changes_required
self.current_time = current_time
self.from_place_district = from_place_district
self.to_place_district = to_place_district
self.deviations = deviations
def is_bad(self):
if self.deviations or self.number_of_changes_required >= 1:
return True
return False
def is_horrible(self):
if self.deviations and self.number_of_changes_required >= 1:
return True
return False |
28fb330fd0cdbf2060b8b9fe8812bcf20209edce | paulosalvatore/ProjetoPython | /reverse.py | 66 | 3.671875 | 4 | lista = [1, 2, 3, 4, 5]
print(lista)
lista.reverse()
print(lista)
|
b5dfeba63547bfb16dc8b4d5eba9f26087b8bdf2 | tjr226/Algorithms | /knapsack/knapsack.py | 2,760 | 4.0625 | 4 | #!/usr/bin/python
import sys
from collections import namedtuple
Item = namedtuple('Item', ['index', 'size', 'value'])
def knapsack_solver(items, capacity):
knapsack_matrix = [[0 for column in range(capacity + 1)] for row in range(len(items) + 1)]
'''
This function uses the format (rows, columns)
'''
rows = len(knapsack_matrix)
columns = len(knapsack_matrix[0])
for row in range(1, rows):
'''
row is current item index
start with 1 to have row of zeros initially
need to access items index of (row - 1) because Items input is a zero indexed list
next line - confirming all items being accessed
'''
for column in range(1, columns):
current_item = items[row - 1]
''' first option - choose value in previous column '''
top_option = knapsack_matrix[row - 1][column]
''' second option - use current item, plus value in previous row (less current item size)'''
item_and_previous_option = 0
''' add current item if it fits '''
if current_item.size <= column:
item_and_previous_option += current_item.value
''' add previous value if it also fits '''
if column - current_item.size >= 0:
item_and_previous_option += knapsack_matrix[row - 1][column - current_item.size]
''' pick higher value - immediately above, or current row item and any values from previous row that fit '''
knapsack_matrix[row][column] = max(top_option, item_and_previous_option)
''' find out which ones were chosen '''
row_index = rows - 1
column_index = columns - 1
used_items = []
while row_index > 0:
if knapsack_matrix[row_index][column_index] == knapsack_matrix[row_index - 1][column_index]:
# do nothing if current value matches value in next row (remember, we're decrementing)
pass
else:
# add item to the used_items list. decrement size available (column_index) by size of the current object
used_items.append(row_index)
column_index -= items[row_index - 1].size
# decrement the row index
row_index -= 1
# tests expect a dictionary with a sorted list
used_items.sort()
dict_to_return = {}
dict_to_return['Value'] = knapsack_matrix[-1][-1]
dict_to_return['Chosen'] = used_items
return dict_to_return
if __name__ == '__main__':
if len(sys.argv) > 1:
capacity = int(sys.argv[2])
file_location = sys.argv[1].strip()
file_contents = open(file_location, 'r')
items = []
for line in file_contents.readlines():
data = line.rstrip().split()
items.append(Item(int(data[0]), int(data[1]), int(data[2])))
file_contents.close()
print(knapsack_solver(items, capacity))
else:
print('Usage: knapsack.py [filename] [capacity]') |
ebf210a9748154f00c213e00e0cfbb17adc9efbd | agrim123/algo-ds | /Algorithms/Pattern Searching/KMP (Knuth Morris Pratt) Pattern Searching/kmp.py | 1,383 | 3.5625 | 4 | """ KMP (Knuth Morris Pratt) Pattern Searching
- Worst case complexity is O(n)
"""
def KMPSearch(pattern, text):
M = len(pattern)
N = len(text)
# create lps[] that will hold the longest prefix suffix
# values for pattern
lps = [0]*M
j = 0 # index for pattern[]
# Preprocess the pattern (calculate lps[] array)
compute_LPS_Array(pattern, M, lps)
i = 0 # index for text[]
while i < N:
if pattern[j] == text[i]:
i += 1
j += 1
if j == M:
print "Found pattern at index " + str(i-j)
j = lps[j-1]
# mismatch after j matches
elif i < N and pattern[j] != text[i]:
# Do not match lps[0..lps[j-1]] characters, they will match anyway
if j != 0:
j = lps[j-1]
else:
i += 1
def compute_LPS_Array(pattern, M, lps):
len = 0 # length of the previous longest prefix suffix
lps[0] # lps[0] is always 0
i = 1
# the loop calculates lps[i] for i = 1 to M-1
while i < M:
if pattern[i] == pattern[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
text = "ABABDABACDABABCABAB"
pattern = "ABABCABAB"
KMPSearch(pattern, text)
|
7ec493228168143a0f7b00df0f09424d7a51db8e | vashist99/ds-and-algo | /Search - Linear/Python3/linearSearch.py | 531 | 3.890625 | 4 | # Author: Vishal Gaur
# Created: 03-01-2021 22:21:11
# function to search an element using linear seaching
def linearSearch(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
# Driver Code to test above function
arr = [45, 76, 12, 19, 43, 48, 56, 67]
x = 18
res = linearSearch(arr, x)
if res >= 0:
print(x, "found at index", res)
else:
print(x, "not found!")
x = 43
res = linearSearch(arr, x)
if res >= 0:
print(x, "found at index", res)
else:
print(x, "not found!")
|
87a2a552723f7ccd1171539c8e2615ae8723ac1f | A7madNasser/DataCamp | /Statistical Thinking in Python -Part 1/03 - Thinking probabilistically-- Discrete variables.py | 13,728 | 4.59375 | 5 | '''
1. Generating random numbers using the np.random module
We will be hammering the np.random module for the rest of this course and its sequel. Actually, you will probably call functions from this module more than any other while wearing your hacker statistician hat. Let's start by taking its simplest function, np.random.random() for a test spin. The function returns a random number between zero and one. Call np.random.random() a few times in the IPython shell. You should see numbers jumping around between zero and one.
In this exercise, we'll generate lots of random numbers between zero and one, and then plot a histogram of the results. If the numbers are truly random, all bars in the histogram should be of (close to) equal height.
You may have noticed that, in the video, Justin generated 4 random numbers by passing the keyword argument size=4 to np.random.random(). Such an approach is more efficient than a for loop: in this exercise, however, you will write a for loop to experience hacker statistics as the practice of repeating an experiment over and over again.
INSTRUCTIONS
100 XP
INSTRUCTIONS
100 XP
Seed the random number generator using the seed 42.
Initialize an empty array, random_numbers, of 100,000 entries to store the random numbers. Make sure you use np.empty(100000) to do this.
Write a for loop to draw 100,000 random numbers using np.random.random(), storing them in the random_numbers array. To do so, loop over range(100000).
Plot a histogram of random_numbers. It is not necessary to label the axes in this case because we are just checking the random number generator. Hit 'Submit Answer' to show your plot.
'''
# Seed the random number generator
np.random.seed(42)
# Initialize random numbers: random_numbers
random_numbers = np.empty(100000)
# Generate random numbers by looping over range(100000)
for i in range(100000):
random_numbers[i] = np.random.random()
print(random_numbers[i])
# Plot a histogram
_ = plt.hist(random_numbers)
# Show the plot
plt.show()
'''
2. The np.random module and Bernoulli trials
You can think of a Bernoulli trial as a flip of a possibly biased coin. Specifically, each coin flip has a probability p of landing heads (success) and probability 1−p of landing tails (failure). In this exercise, you will write a function to perform n Bernoulli trials, perform_bernoulli_trials(n, p), which returns the number of successes out of n Bernoulli trials, each of which has probability p of success. To perform each Bernoulli trial, use the np.random.random() function, which returns a random number between zero and one.
INSTRUCTIONS
100 XP
INSTRUCTIONS
100 XP
Define a function with signature perform_bernoulli_trials(n, p).
Initialize to zero a variable n_success the counter of Trues, which are Bernoulli trial successes.
Write a for loop where you perform a Bernoulli trial in each iteration and increment the number of success if the result is True. Perform n iterations by looping over range(n).
To perform a Bernoulli trial, choose a random number between zero and one using np.random.random(). If the number you chose is less than p, increment n_success (use the += 1 operator to achieve this).
The function returns the number of successes n_success.
'''
def perform_bernoulli_trials(n, p):
"""Perform n Bernoulli trials with success probability p
and return number of successes."""
# Initialize number of successes: n_success
n_success = 0
# Perform trials
for i in range(n):
# Choose random number between zero and one: random_number
random_number = np.random.random()
# If less than p, it's a success so add one to n_success
if random_number < p:
n_success += 1
return n_success
print(perform_bernoulli_trials(10000,0.65))
'''
3. How many defaults might we expect?
Let's say a bank made 100 mortgage loans. It is possible that anywhere between 0 and 100 of the loans will be defaulted upon. You would like to know the probability of getting a given number of defaults, given that the probability of a default is p = 0.05. To investigate this, you will do a simulation. You will perform 100 Bernoulli trials using the perform_bernoulli_trials() function you wrote in the previous exercise and record how many defaults we get. Here, a success is a default. (Remember that the word "success" just means that the Bernoulli trial evaluates to True, i.e., did the loan recipient default?) You will do this for another 100 Bernoulli trials. And again and again until we have tried it 1000 times. Then, you will plot a histogram describing the probability of the number of defaults.
INSTRUCTIONS
100 XP
INSTRUCTIONS
100 XP
Seed the random number generator to 42.
Initialize n_defaults, an empty array, using np.empty(). It should contain 1000 entries, since we are doing 1000 simulations.
Write a for loop with 1000 iterations to compute the number of defaults per 100 loans using the perform_bernoulli_trials() function. It accepts two arguments: the number of trials n - in this case 100 - and the probability of success p - in this case the probability of a default, which is 0.05. On each iteration of the loop store the result in an entry of n_defaults.
Plot a histogram of n_defaults. Include the normed=True keyword argument so that the height of the bars of the histogram indicate the probability.
Show your plot.
'''
# Seed random number generator
np.random.seed(42)
# Initialize the number of defaults: n_defaults
n_defaults = np.empty(1000)
# Compute the number of defaults
for i in range(1000):
n_defaults[i] = perform_bernoulli_trials(100,0.05)
# Plot the histogram with default number of bins; label your axes
_ = plt.hist(n_defaults, normed = True)
_ = plt.xlabel('number of defaults out of 100 loans')
_ = plt.ylabel('probability')
# Show the plot
plt.show()
'''
4. Will the bank fail?
Plot the number of defaults you got from the previous exercise, in your namespace as n_defaults, as a CDF. The ecdf() function you wrote in the first chapter is available.
If interest rates are such that the bank will lose money if 10 or more of its loans are defaulted upon, what is the probability that the bank will lose money?
INSTRUCTIONS
100 XP
INSTRUCTIONS
100 XP
Compute the x and y values for the ECDF of n_defaults.
Plot the ECDF, making sure to label the axes. Remember to include marker = '.' and linestyle = 'none' in addition to x and y in your call plt.plot().
Show the plot.
Compute the total number of entries in your n_defaults array that were greater than or equal to 10. To do so, compute a boolean array that tells you whether a given entry of n_defaults is >= 10. Then sum all the entries in this array using np.sum(). For example, np.sum(n_defaults <= 5) would compute the number of defaults with 5 or fewer defaults.
The probability that the bank loses money is the fraction of n_defaults that are greater than or equal to 10. Print this result by hitting 'Submit Answer'!
'''
# Compute ECDF: x, y
x,y = ecdf(n_defaults)
# Plot the ECDF with labeled axes
_ = plt.plot(x,y, marker = '.', linestyle = 'none')
_ = plt.xlabel('x')
_ = plt.ylabel('y')
# Show the plot
plt.show()
# Compute the number of 100-loan simulations with 10 or more defaults: n_lose_money
n_lose_money = np.sum(n_defaults >= 10)
# Compute and print probability of losing money
print('Probability of losing money =', n_lose_money / len(n_defaults))
'''
5. Sampling out of the Binomial distribution
Compute the probability mass function for the number of defaults we would expect for 100 loans as in the last section, but instead of simulating all of the Bernoulli trials, perform the sampling using np.random.binomial(). This is identical to the calculation you did in the last set of exercises using your custom-written perform_bernoulli_trials() function, but far more computationally efficient. Given this extra efficiency, we will take 10,000 samples instead of 1000. After taking the samples, plot the CDF as last time. This CDF that you are plotting is that of the Binomial distribution.
Note: For this exercise and all going forward, the random number generator is pre-seeded for you (with np.random.seed(42)) to save you typing that each time.
INSTRUCTIONS
100 XP
INSTRUCTIONS
100 XP
Draw samples out of the Binomial distribution using np.random.binomial(). You should use parameters n = 100 and p = 0.05, and set the size keyword argument to 10000.
Compute the CDF using your previously-written ecdf() function.
Plot the CDF with axis labels. The x-axis here is the number of defaults out of 100 loans, while the y-axis is the CDF.
Show the plot.
'''
# Take 10,000 samples out of the binomial distribution: n_defaults
n_defaults = np.random.binomial(n=100, p=0.05, size=10000)
# Compute CDF: x, y
x, y = ecdf(n_defaults)
# Plot the CDF with axis labels
_ = plt.plot(x, y, marker='.', linestyle='none')
_ = plt.xlabel('Defaults out of 100')
_ = plt.ylabel('CDF')
# Show the plot
plt.show()
'''
6. Plotting the Binomial PMF
As mentioned in the video, plotting a nice looking PMF requires a bit of matplotlib trickery that we will not go into here. Instead, we will plot the PMF of the Binomial distribution as a histogram with skills you have already learned. The trick is setting up the edges of the bins to pass to plt.hist() via the bins keyword argument. We want the bins centered on the integers. So, the edges of the bins should be -0.5, 0.5, 1.5, 2.5, ... up to max(n_defaults) + 1.5. You can generate an array like this using np.arange() and then subtracting 0.5 from the array.
You have already sampled out of the Binomial distribution during your exercises on loan defaults, and the resulting samples are in the NumPy array n_defaults.
INSTRUCTIONS
100 XP
Using np.arange(), compute the bin edges such that the bins are centered on the integers. Store the resulting array in the variable bins.
Use plt.hist() to plot the histogram of n_defaults with the normed=True and bins=bins keyword arguments.
Show the plot.
'''
# Compute bin edges: bins
bins = np.arange(min(n_defaults), max(n_defaults) + 1.5) - 0.5
# Generate histogram
_ = plt.hist(n_defaults, normed=True, bins=bins)
# Label axes
_ = plt.xlabel('x')
_ = plt.ylabel('y')
# Show the plot
plt.show()
'''
7. Relationship between Binomial and Poisson distributions
You just heard that the Poisson distribution is a limit of the Binomial distribution for rare events. This makes sense if you think about the stories. Say we do a Bernoulli trial every minute for an hour, each with a success probability of 0.1. We would do 60 trials, and the number of successes is Binomially distributed, and we would expect to get about 6 successes. This is just like the Poisson story we discussed in the video, where we get on average 6 hits on a website per hour. So, the Poisson distribution with arrival rate equal to np approximates a Binomial distribution for n Bernoulli trials with probability p of success (with n large and p small). Importantly, the Poisson distribution is often simpler to work with because it has only one parameter instead of two for the Binomial distribution.
Let's explore these two distributions computationally. You will compute the mean and standard deviation of samples from a Poisson distribution with an arrival rate of 10. Then, you will compute the mean and standard deviation of samples from a Binomial distribution with parameters n and p such that np=10.
INSTRUCTIONS
100 XP
INSTRUCTIONS
100 XP
Using the np.random.poisson() function, draw 10000 samples from a Poisson distribution with a mean of 10.
Make a list of the n and p values to consider for the Binomial distribution. Choose n = [20, 100, 1000] and p = [0.5, 0.1, 0.01] so that np is always 10.
Using np.random.binomial() inside the provided for loop, draw 10000 samples from a Binomial distribution with each n, p pair and print the mean and standard deviation of the samples. There are 3 n, p pairs: 20, 0.5, 100, 0.1, and 1000, 0.01. These can be accessed inside the loop as n[i], p[i].
'''
# Draw 10,000 samples out of Poisson distribution: samples_poisson
samples_poisson = np.random.poisson(10, size=10000)
# Print the mean and standard deviation
print('Poisson: ', np.mean(samples_poisson),
np.std(samples_poisson))
# Specify values of n and p to consider for Binomial: n, p
n = [20, 100, 1000]
p = [0.5, 0.1, 0.01]
# Draw 10,000 samples for each n,p pair: samples_binomial
for i in range(3):
samples_binomial = np.random.binomial(n[i], p[i], 10000)
# Print results
print('n =', n[i], 'Binom:', np.mean(samples_binomial),
np.std(samples_binomial))
'''
8. Was 2015 anomalous?
1990 and 2015 featured the most no-hitters of any season of baseball (there were seven). Given that there are on average 251/115 no-hitters per season, what is the probability of having seven or more in a season?
INSTRUCTIONS
100 XP
Draw 10000 samples from a Poisson distribution with a mean of 251/115 and assign to n_nohitters.
Determine how many of your samples had a result greater than or equal to 7 and assign to n_large.
Compute the probability, p_large, of having 7 or more no-hitters by dividing n_large by the total number of samples (10000).
Hit 'Submit Answer' to print the probability that you calculated.
'''
# Draw 10,000 samples out of Poisson distribution: n_nohitters
n_nohitters = np.random.poisson((251 / 115), size=10000)
# Compute number of samples that are seven or greater: n_large
n_large = np.sum(n_nohitters >= 7)
# Compute probability of getting seven or more: p_large
p_large = n_large / 10000
# Print the result
print('Probability of seven or more no-hitters:', p_large)
|
9d242e04fe2d2ef1617701b751a2760bb6d87f45 | nivedha1998/nivedha | /H124.py | 164 | 3.625 | 4 | I=int(input())
while(I>0):
j=0
while(j<I):
if (j==(I-1)):
print("1")
else:
print("1",end=" ")
j+=1
I-=1
|
be825daaab69cf112ecc4486321f21363fc147c4 | dezson/leetcoding-july | /word_search.py | 855 | 3.5625 | 4 | class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(board,x,y,word,i):
if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]) or i >= len(word):
return False
if board[x][y] == word[i]:
temp = board[x][y]
board[x][y] = ""
if i == len(word)-1:
return True
b = dfs(board,x+1,y,word,i+1) or dfs(board,x-1,y,word,i+1) or dfs(board,x,y+1,word,i+1) or dfs(board,x,y-1,word,i+1)
board[x][y] = temp
return b
for x in range(len(board)):
for y in range(len(board[0])):
z = board
if board[x][y] == word[0] and dfs(board,x,y,word,0):
return True
return False
|
7a191b28da2dde5b7b854789b6ff4a298e7f67de | Aasthaengg/IBMdataset | /Python_codes/p02273/s840823588.py | 947 | 3.65625 | 4 | import math
def make_3_points(p1, p2):
"""p1, p2 を分割する3点を作成する。
p1, p2 を両端の点とする線分を3等分する2点 s, t を
頂点とする正三角形の頂点 (s, u, t) のタプルを返す。
"""
s = ((2 * p1[0] + p2[0]) / 3, (2 * p1[1] + p2[1]) / 3)
t = ((p1[0] + 2 * p2[0]) / 3, (p1[1] + 2 * p2[1]) / 3)
theta = math.radians(60)
x = t[0] - s[0]
y = t[1] - s[1]
u = (math.cos(theta) * x - math.sin(theta) * y, math.sin(theta) * x + math.cos(theta) * y)
u = (u[0] + s[0], u[1] + s[1])
return (s, u, t)
def make_koch(n, pl):
if n == 0:
return pl
next_pl = [pl[0]]
for i in range(1, len(pl)):
s, u, t = make_3_points(next_pl[-1], pl[i])
next_pl += [s, u, t, pl[i]]
pl = None
return make_koch(n - 1, next_pl)
n = int(input())
rl = make_koch(n, [(0, 0), (100, 0)])
for p1, p2 in rl:
print(p1, p2)
|
92a1483e1cb03480feac8829374b13a9ae5a92bd | kapil87/LeetCode | /buySellStocksPeakValley.py | 380 | 3.578125 | 4 | def maxProit(prices):
i = 0
maxprofit = 0
while i < (len(prices) -1):
while (i < len(prices)-1 and prices[i] >= prices[i+1]):
i +=1
valley = prices[i]
while (i < len(prices)-1 and prices[i] <= prices[i+1]):
i +=1
peak = prices[i]
#print peak, valley
maxprofit += peak-valley
return maxprofit
|
3be62500739d20bf9fbd49b5fbeffe26628dbbad | windard/ModernCryptography | /cryptopals/quiz5.py | 641 | 3.609375 | 4 | # coding=utf-8
def repeatxor(strings,key):
result = ""
for i,x in enumerate(strings):
result += hex(ord(x) ^ ord(key[(i % len(key))]))[2:] if len(hex(ord(x) ^ ord(key[(i % len(key))]))[2:]) == 2 else "0"+hex(ord(x) ^ ord(key[(i % len(key))]))[2:]
return result
def decode_xorvigenere(ciphertext,key):
return "".join([chr(ord(x) ^ ord(key[i%len(key)])) for i,x in enumerate(ciphertext)])
strings = """Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal"""
key = "ICE"
print repeatxor(strings,key)
print len(repeatxor(strings,key))
print decode_xorvigenere(repeatxor(strings,key).decode("hex"),key)
# 0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f
|
534eaef921f513d64d04c11b75204f0bb861832c | jhassinger/Python_Hard_Way | /ex16.py | 1,002 | 4.3125 | 4 | # import argv
from sys import argv
# assign arguments to variables script and filename
script, filename = argv
# printing instructions to user
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
# wait for user to hit enter or escape
raw_input("?")
# open the file in write mode
print "Opening the file..."
target = open(filename, 'w')
# truncate the file to erase it
#print "Truncating the file. Goodbye!"
#target.truncate()
print "Now I'm going to ask you for three lines."
# read in 3 new lines from the user
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
# write the read in lines to the file
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
#target.write("\n")
#target.write(line2)
#target.write("\n")
#target.write(line3)
#target.write("\n")
# close the file
print "And finally, we close it."
target.close() |
86bba1089ce109d812667c92ce692c3fc90d9441 | p23he/oiler | /ProjectEuler/Problem 35.py | 737 | 3.6875 | 4 | #The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
#There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
#How many circular primes are there below one million?
import math
def is_prime(n):
upp = math.floor(math.sqrt(n))
for i in range(2, upp + 1):
if n % i == 0:
return False
return True
def is_circ(p):
temp = str(p)[1:len(str(p))] + str(p)[0:1]
for i in range(1, len(temp)):
if not is_prime(int(temp)):
return False
temp = temp[1:len(temp)] + temp[0:1]
return True
total = 0
for i in range(2, 1000000):
if is_prime(i) and is_circ(i):
total += 1
print(total)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.