blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
525d6a69c5a2ea74e78e43af87a899e39d598f57 | lborg019/py-netcentric | /hw2/http-server/HTTPServer.py | 5,190 | 3.828125 | 4 | ##########################################################################
""" HTTPServer.py
HTTPServer in Python
[STUDENTS FILL IN THE ITEMS BELOW]
STUDENT: Lukas Borges
COURSE NAME: [CNT4713] Netcentric Computing
SEMESTER: Spring 2016
DATE 02/15/2016
DESCRIPTION: This is an HTTP server in Python.
"""
'''
send:
Last-Modified: Sun Feb 28 07:42:30 2016 GMT
receive / parse:
If-Modified-Since: Sun Feb 28 00:34:45 2016
according to python's doc, datetime:
%c = Tue Aug 16 21:30:00 1988
'''
from socket import *
import os, time
from datetime import datetime as dt
# HTTP servers run on port 80
serverPort = 80
# create TCP welcoming socket
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(("",serverPort))
# server begins listening for incoming TCP requests
serverSocket.listen(1)
# the following variables are going to have to be changed according to test env.:
path = ("/home/luke/Desktop/Bobadilla/py-netcentric/hw2/Server/web/")
cacheHeader = ("If-Modified-Since:")
fileList = os.listdir(path)
print(fileList)
# output to console that server is listening
print ("Magic happens on port 80... ")
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
print ("Received From Client: ", sentence)
if(sentence[0:5]=="GET /"):
print("user sent a GET\n")
fileName = sentence[5:-2] # trim GET
fileName = fileName.partition(" ")[0] # GET file name (index.html)
print("fileName:", fileName)
else:
# rest of the code might be dependent on this
print("Server rejected HTTP method")
# compare this with the dir file list:
if fileName in fileList:
print("file found")
# check for caching:
if(cacheHeader in sentence):
print("Page is cached, perform check:")
# trim 'If-Modified-Since' date:
cacheIndex = sentence.find(cacheHeader, 0, len(sentence))
cacheDate = sentence[cacheIndex:]
cacheDate = cacheDate[19:]
cacheDate = cacheDate.partition(" GMT")[0]
print("CacheDate: ", cacheDate)
# element in list where file is at
i = fileList.index(fileName)
# full path with file name
filePath = (path+fileList[i])
# calculate last modified:
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filePath)
print("FileDate: ", time.ctime(mtime))
# compare the two dates:
# convert both strings back to time:
# convCacheDate = datetime.strptime(cacheDate, "%c")
a = dt.strptime(cacheDate, "%c")
b = dt.strptime(time.ctime(mtime), "%c")
if(b > a):
print("Cache is outdated, resend!")
# calculate last modified, send
i = fileList.index(fileName)
filePath = (path+fileList[i])
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filePath)
# send the file with Last-Modified header information:
connectionSocket.send('HTTP/1.1 200 OK\nContent-Type: text/html\nLast-Modified: %s GMT\n\n' % time.ctime(mtime))
webFile = open(path+fileList[i], 'rb')
l = webFile.read(1024)
print(l)
while(l):
print 'Sending...'
connectionSocket.send(l)
l = webFile.read(1024)
webFile.close()
else:
print("Cache is current, return 304")
connectionSocket.send('HTTP/1.1 304\n')
else:
print("Page not cached, send anyway")
# calculate last modified, send
i = fileList.index(fileName)
filePath = (path+fileList[i])
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filePath)
# send the file with Last-Modified header information:
connectionSocket.send('HTTP/1.1 200 OK\nContent-Type: text/html\nLast-Modified: %s GMT\n\n' % time.ctime(mtime))
webFile = open(path+fileList[i], 'rb')
l = webFile.read(1024)
print(l)
while(l):
print 'Sending...'
connectionSocket.send(l)
l = webFile.read(1024)
webFile.close()
# connectionSocket.shutdown(socket.SHUT_WR)
else:
print("file not found")
# send a 404
connectionSocket.send('\n404 Not Found\n');
# connectionSocket.send('HTTP/1.1 404 Not Found\nContent-Type: text/html\n\n')
# send the file
# connectionSocket.send(sentence)
# output to console the sentence sent back to the client
# print ("Sent back to Client: ", capitalizedSentence)
# close the TCP connection; the welcoming socket continues
connectionSocket.close()
##########################################################################
|
9b8271faadd33f72f8123ed7dcf2a1d4388507a3 | TheAragont97/Python | /Actividades/Relacion 2/ejercicio 9/ejercicio_9.py | 544 | 4.15625 | 4 | diccionario={}
carac=input("Ingrese el dato nuevo para el diccionario: ")
dato=input("Ingrese el valor del dato: ")
diccionario[carac]=dato
print(diccionario)
op=input("¿Quiere seguir añadiendo datos? S/N :").upper()
if op=="S" or op=="N":
while op=="S":
carac=input("Ingrese el dato nuevo para el diccionario: ")
dato=input("Ingrese el valor del dato: ")
diccionario[carac]=dato
print(diccionario)
op=input("¿Quiere seguir añadiendo datos? S/N :").upper()
else:
print("Opción incorrecta")
|
ded07d00c939c506517453cd9dd0d663ea836a01 | robintecho/Python | /Co1/14nmultiple.py | 52 | 3.6875 | 4 | n = int(input('Enter n: '))
s=n+n*n+n*n*n
print(s)
|
c9a6308bb58449d081812657c641f8285cd625b2 | hnmahamud/Unix-Problem-Solving | /Python/Code/5/main.py | 1,241 | 4 | 4 | # Dictionary of 10 elements
std_dic = {
'sayeed': 75,
'sakib': 70,
'shaon': 90,
'pranto': 38,
'hasib': 79,
'anik': 80,
'evan': 35,
'rafi': 82,
'pial': 83,
'masud': 40
}
# Extract the value of key contains from std_dic and append to num_list
# Then sort the num_list with Ascending Order
num_list = []
for key in std_dic:
num_list.append(std_dic[key])
num_list.sort()
print('Output:')
# Reverse the num_list for get the largest value from 0 position
# Then we find the highest mark with name from std_dic
num_list.reverse()
for i in std_dic:
if std_dic[i] == num_list[0]:
print('Highest Mark:',i,'(',std_dic[i],')')
# Again reverse the num_list for get the lowest value from 0 position
# Then we find the lowest mark with name from std_dic
num_list.reverse()
for j in std_dic:
if std_dic[j] == num_list[0]:
print('Lowest Mark:',j,'(',std_dic[j],')')
# Percentage Calculation
n = 0
m = 0
for i in std_dic:
if std_dic[i] >= 80:
n = n + 1
if std_dic[i] < 40:
m = m + 1
plus_cal = int((100 * n) / 10)
fail_cal = int((100 * m) / 10)
print(str(plus_cal) + '%' + ' students achieved 80 or more')
print(str(fail_cal) + '%' + ' students are failed') |
f16bbb16a231b27b0b793f10f33cffed079928e3 | mgokani/RH | /test_printpairs.py | 678 | 3.609375 | 4 | """@author: Mirav Gokani
Unit tests for print_pairs.py
"""
import print_pairs as ps
import unittest
class TestPairs(unittest.TestCase):
def test_negativenumbers(self):
"""Test a combination of positive and negative numbers"""
result = ps.pairs([-4, 4, 0, -2, 0], 0)
self.assertEqual(result[0, 0], -4)
self.assertEqual(result[0, 1], 4)
self.assertEqual(result[1, 0], 0)
self.assertEqual(result[1, 1], 0)
def test_exception(self):
"""Test if exception is raised when no pairs are found"""
with self.assertRaises(Exception):
ps.pairs([1, 1, 1, 2], 5)
if __name__ == "__main__":
unittest.main()
|
f009cfa22ca6d4034c7bdb0f15dda19e66480b96 | sheilsarda/CV_Fundamentals | /spring20_Solutions/hw2-sols/Part_2/line_intersection.py | 657 | 4 | 4 | import numpy as np
def line_intersection(l1, l2):
"""
Compute the intersection of two line
Input:
l1: array of size (3,) representing a line in homogenous coordinate
l2: array of size (3,) representing another line in homogenous coordinate
Returns:
pt: array of size (3,) representing the intersection of two lines in
homogenous coordinate. Remeber to normalize it so its last coordinate
is either 1 or 0.
"""
##### STUDENT CODE START #####
pt = np.cross(l1, l2)
if np.abs(pt[2]) > 1e-6:
pt = pt / pt[2]
##### STUDENT CODE END #####
return pt |
eed2adcdf014261a4888ea6041dfa4ebb248ae77 | Alicho220/python_practice | /python practice/set.py | 453 | 3.96875 | 4 | # collection with no duplicate..
# if you have a list and want no duplicate of element just convert to a set
# we cannot index a set
numbers = [1,1,1, 2,2,2,4,5,6,7,6]
numbers1 = set(numbers)
numbers2 = {1,4,10,50}
print(numbers1)
# you can add, remove
# numbers1.add()
# numbers1.remove()
# len(numbers1)
# union of two set
union = numbers1 | numbers2
print(union)
intersection = numbers1 & numbers2
print(intersection)
print(numbers2 - numbers1) |
e8bc86da72d39b2f73eb6971ebfe5899553a1c37 | tmtmaj/PYTHON | /SECTION_03/set2.py | 288 | 4.125 | 4 | s1 = set([1,2,3])
s2 = {1, 2, 3}
print(s1) # {1, 2, 3}
print(s2) # {1, 2, 3}
# 특징 1. 중복을 허용하지 않고, 순서를 유지 하지 않는다.
s1 = set('Hello')
print(s1)
# 특징 2. 배열 연산자를 사용해서 요소 접근 안됨
print(s1[0])
|
fd9e589c78389a84e8c7e32a3cf446d80854fb67 | tmngomez/DBN-Campus-Workshops-codebase- | /Lambda/calculator_test.py | 2,747 | 3.90625 | 4 | import calculator
import unittest
from unittest.mock import patch
from io import StringIO
import sys
class TestCalculator(unittest.TestCase):
@patch("sys.stdin", StringIO("not numbers\nsome 1 or 2 numbers\n1,2,3,4,5,6\n2,2\n"))
def test_get_input(self):
""" this checks that if if any item in the list is non numeric the loop asks
for input until only numbers are entered by the user"""
self.assertEqual(calculator.get_input(), [2,2])
def test_get_only_two_numbers(self):
"""this checks that we receive exactly 2 numbers from user, no more or less"""
self.assertTrue(calculator.only_two_numbers("1,2,3") ==False)
self.assertTrue(calculator.only_two_numbers("1") == False)
self.assertTrue(calculator.only_two_numbers("2,2") == True)
def test_valid_list(self):
""" this checks that our validator will only approve a list of numbers and reject it
if there is a non numeric"""
self.assertTrue(calculator.is_valid("1,2,3,4,5"),True)
self.assertTrue(calculator.is_valid("1,2,3,me,4,5") == False)
@patch("sys.stdin", StringIO("%\n+\n"))
def test_get_operator(self):
""" this checks that the loop will continue to ask for an operator until we get a valid
operator for our calculator"""
self.assertTrue(calculator.get_operator(),'+')
def test_calculate(self):
""""checks that given each operation we get the result expected"""
sys_orig = sys.stdout
my_file = StringIO()
sys.stdout = my_file #Just to ensure that tests do not print anything out
self.assertTrue(calculator.calculate([1,2],'+') == 3)
self.assertTrue(calculator.calculate([2,2],'-') == 0)
self.assertTrue(calculator.calculate([3,3],'/') == 1)
self.assertTrue(calculator.calculate([4,4],'*') == 16)
@patch("sys.stdin", StringIO("4,4\n*\noff\n"))
def test_output_for_all_right_inputs(self):
"""this captures the program output and tests that the program gives the exact output
we expect when perfectly valid input is entered
"""
sys_orig = sys.stdout
my_file = StringIO()
sys.stdout = my_file
calculator.run()
out_put = my_file.getvalue() #actually capturing the output so that we can test it
self.assertEqual("""Welcome friend ! lets go !\n Please enter 2 numbers seperated by a comma :\nPlease choose and operator : + ,- ,/ ,* :\nThe result is : 16\n Please enter 2 numbers seperated by a comma :\n""",out_put)
sys.stdout = sys_orig
if __name__=="__main__":
unittest.main() |
9679d2046e09fd33ea53daa11879b85b24cbca4b | ralic/aws_hack_collection | /101-AWS-S3-Hacks/searchabucket_casesensitive.py | 429 | 3.59375 | 4 | #!/usr/bin/python
"""
- Author : Nag m
- Hack : Search for a bucket with bucket name which is case sensitive
- Info : Search for a bucket named
* 101-S3-aws
"""
import boto
from boto.s3.connection import OrdinaryCallingFormat
def searchabucket():
bucket = conn.get_bucket("101-S3-aws")
print bucket
if __name__ == "__main__":
conn = boto.connect_s3(calling_format=OrdinaryCallingFormat())
searchabucket()
|
ed5d20adf680bcacc1ecddc6886d87edb22d369e | WSU-RAS/ras2 | /src/adl_error_detection/src/adl/robot_sensor_translation/convert_points.py | 2,262 | 3.578125 | 4 | #!/usr/bin/env python
import math
from typing import Tuple, List
a_default = 0.999198
b_default = -0.052252
c_default = 1.056307
d_default = 0.080343
e_default = 1.005433
f_default = 1.052456
def convert_point(point, a=a_default, b=b_default, c=c_default,
d=d_default, e=e_default, f=f_default):
"""
Convert an (x,y) point from robot space to sensor map space.
Conversion uses formulas:
x' = ax + by + c
y' = dx + ey + f
where a, b, c, d, e, and f are constants determined from training points. Default constants have been calculated
from 15 pairs of training points.
:param point: (x,y) coordinate from robot space to be converted
:param a: Uses default if not provided
:param b: Uses default if not provided
:param c: Uses default if not provided
:param d: Uses default if not provided
:param e: Uses default if not provided
:param f: Uses default if not provided
:return: The converted point (x',y') in sensor map space
"""
calculated_xp = a * point[0] + b * point[1] + c
calculated_yp = d * point[0] + e * point[1] + f
return calculated_xp, calculated_yp
convert_point.__annotations__ = {
'point': Tuple[float, float], 'a': float, 'b': float, 'c': float,
'd': float, 'e': float, 'f': float, 'return': Tuple[float, float]}
def calculate_errors(points, a, b, c, d, e, f):
x_avg_error = 0
y_avg_error = 0
avg_euclidean_error = 0
for index, pair in enumerate(points):
output_point = pair[1]
x_calc, y_calc = convert_point(pair[0], a, b, c, d, e, f)
x_error = abs(x_calc - output_point[0])
y_error = abs(y_calc - output_point[1])
x_avg_error += x_error
y_avg_error += y_error
avg_euclidean_error += math.sqrt(x_error ** 2 + y_error ** 2)
x_avg_error = x_avg_error / len(points)
y_avg_error = y_avg_error / len(points)
avg_euclidean_error = avg_euclidean_error / len(points)
return x_avg_error, y_avg_error, avg_euclidean_error
calculate_errors.__annotations__ = {
'point': List[Tuple[Tuple[float, float], Tuple[float, float]]],
'a': float, 'b': float, 'c': float, 'd': float, 'e': float, 'f': float,
'return': Tuple[float, float, float]}
|
a0fff79398db5b6fe912bb2f692b4141b8dd3f47 | carlosalbferreira/curso-Udemy-Python-iniciante-ao-avancado | /Salario15%aumento.py | 154 | 3.703125 | 4 | s =float(input('Digite o seu salario: R$'))
s1 = s*15/100
print('O salário com 15% de aumento será de R${}'.format(s+s1))
# Salário com aumento de 15%
|
b5a3d6a0da987102df1b77bf1fe5483b3640e1b3 | ginajoerger/Data-Structures | /Assignment 3 - Recursion/Question6_tree.py | 837 | 4.46875 | 4 | import turtle
def draw_tree(branchLen,t):
'''
@branchLen: Length of this branch. Should reduce every recursion. Starting length is 100.
@t: Instance of turtle module. We can call turtle functions on this parameter.
Figure out the tree pattern, and display the recursion tree.
You may have to play/tune with angles/lengths to draw a pretty tree.
@return: Nothing to return
'''
if branchLen > 5:
t.forward(branchLen)
t.right(20)
draw_tree(branchLen-15,t)
t.left(40)
draw_tree(branchLen-15,t)
t.right(20)
t.backward(branchLen)
t.pos()
def main():
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
t.backward(100)
t.color("green")
draw_tree(100,t)
myWin.exitonclick()
#main()
|
6c0ddd37baccbc7255632fe58f0ff72e92d94bf3 | xylover/BS- | /BS代码示例-8.py | 740 | 4.03125 | 4 | html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html , 'lxml')
print('Next Sibling',soup.a.next_sibling)
print('Prev Sibling',soup.a.previous_sibling)
print('Next Siblings',list(enumerate(soup.a.next_siblings)))
print('Prev Siblings',list(enumerate(soup.a.previous_siblings))) |
ead8e665a225ac64b916cc2ea3e0743813289dcb | tberhanu/elts-of-coding | /BST/closest_entries_in_3_sorted_arrays.py | 1,405 | 3.828125 | 4 | def find_closest_entries_in_three_sorted_arrays(sorted_arrays):
"""
Tess Strategy:
Time: O(N) w/r N is the maximum array length of the three arrays
Page 211 uses bintrees.RBTree(), check it out.
"""
a, b, c = sorted_arrays[0], sorted_arrays[1], sorted_arrays[2]
smallest_gap = float("inf")
collector = []
while a and b and c:
diff = sum([abs(a[0] - b[0]), abs(a[0] - c[0]), abs(b[0] - c[0])])
if diff < smallest_gap:
smallest_gap = diff
collector = []
collector.append([a[0], b[0], c[0]])
if diff == smallest_gap:
collector.append([a[0], b[0], c[0]])
e = min(a[0], b[0], c[0])
if e in a:
a.remove(e)
elif e in b:
b.remove(e)
else:
c.remove(e)
return collector
if __name__ == "__main__":
sorted_arrays = [[5, 10, 15], [3, 6, 9, 12, 15], [8, 16, 24]]
result = find_closest_entries_in_three_sorted_arrays(sorted_arrays)
print(result) # 15, 15, 16
sorted_arrays = [[5, 10, 15, 20], [3, 6, 9, 12, 15, 16], [8, 15, 16, 24]]
result = find_closest_entries_in_three_sorted_arrays(sorted_arrays)
print(result) # 15, 15, 15
sorted_arrays = [[5, 10, 15, 20], [3, 6, 9, 12, 15], [6, 8, 16, 24]]
result = find_closest_entries_in_three_sorted_arrays(sorted_arrays)
print(result) # 15, 15, 16
|
b318f7a181f487bf6abbea2bfeff5a9477952100 | HimaniSoni/CtCI | /8.3 Magic Index.py | 595 | 3.609375 | 4 | def magicIndex(arr):
first = 0
last = len(arr)-1
while first <= last:
mid = (first+last)//2
if arr[mid] == mid:
return mid
elif arr[mid] > mid:
last = mid-1
else:
first = mid+1
return False
print(magicIndex([1, 2, 2, 3, 6, 9, 15, 21]))
def magicIndex2(arr, min, max):
mid = (min + max) // 2
if arr[mid] == mid:
return mid
elif arr[mid] > mid:
return magicIndex2(arr, min, mid-1)
else:
return magicIndex2(arr, min+1, max)
print(magicIndex([1, 2, 2, 3, 6, 9, 15, 21])) |
f9d25b58defcfd01ef54cfa8687f1ff3d72ad1a1 | aaveter/curs_2016_b | /7/gens.py | 676 | 3.8125 | 4 |
# Генераторы
lst = range(1000000) # создает список в python 2
lst = list(range(1000000)) # создадим список в python 3
lst[100] = 'hi!'
gen = range(1000000) # создает генератор в python 3
#lst = [0, 1, 2 ...., 999999]
#gen[100] = 'hi'
for a in gen:
print( a )
# - не создают массив в памяти, а вычисляют новое значение в нужный момент
lst = [a for a in range(10) if a < 5] # генератор списка
gen = (a for a in range(10) if a < 5) # генератор, краткая запись
for a in gen:
print( a )
#print( gen[1] ) |
e748645915206c4067d83d0c749133b46a4c7968 | jxie0755/Learning_Python | /LeetCode/LC238_product_of_array_except_self.py | 2,489 | 3.515625 | 4 | # LC238 Product of Array Except Self
# Medium
# Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
# Note: Please solve it without division and in O(n).
# Follow up:
# Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
from typing import *
class Solution(object):
# Version A, O(N) time, O(1) space
# 4 differnt situations:
# no zero
# 1 zero
# >= 2 zeros
def productExceptSelf(self, nums: List[int]) -> List[int]:
total_product = 1
zerofound = 0
for i in nums:
if i == 0:
zerofound += 1
else:
total_product *= i
k = 0
result = []
if zerofound == 0: # no zero
while k != len(nums):
result.append(total_product // nums[k])
k += 1
elif zerofound == 1: # 1 zero, everything else is 0 except the i where nums[i] == 0
for i in nums:
if i == 0:
result.append(total_product)
else:
result.append(0)
else: # >= 2 zero, everything is zero
total_product = 0
for i in nums:
result.append(total_product)
return result
class Solution(object):
# Version B, O(N) time, No Division (不使用除法)
# space O(2n)
# 从左往右, 记录到每个数之前的乘积, 再从右往左, 然后把左侧的乘积乘以右侧的乘积
# 可以更加省空间到O(N), 使用右侧扫描时结果直接乘到left里面去
def productExceptSelf(self, nums: List[int]) -> List[int]:
N = len(nums)
left, right = [1] * N, [1] * N
i = 1
pd = 1
while i != N:
pd *= nums[i - 1]
left[i] = pd
i += 1
i = N - 2
pd = 1
while i >= 0:
pd *= nums[i + 1]
right[i] = pd
i -= 1
return [left[i] * right[i] for i in range(len(left))]
if __name__ == "__main__":
assert Solution().productExceptSelf([1, 2, 3, 4]) == [24, 12, 8, 6], "Example"
assert Solution().productExceptSelf([0, 0]) == [0, 0], "Additional 1"
assert Solution().productExceptSelf([1, 0, 1]) == [0, 1, 0], "Additional 2"
print("All passed")
|
eb68d005b874156194a759e152563ec368dbf35e | RawandKurdy/snippets | /22_hashcode_pizzza/pizzza.py | 1,948 | 3.8125 | 4 | import os
# More Pizza
# Google Hash Code 2020
# Practice Problem
# In Python
def fileOperation(fileName, flag):
path, op = "", ""
if flag == "a":
path = f"./output/{fileName}.out"
op = "Writing To"
elif flag == "r":
path = f"./input/{fileName}.in"
op = "Reading From"
print(f"{op} {path}")
return open(path, flag, 1, "UTF8", None, "\n")
# Used to read the file
def readFile(fileName):
return fileOperation(fileName, "r")
# Used to write the file
def writeFile(fileName, array=[]):
f = fileOperation(fileName, "a")
if f.writable():
f.write(f"{len(array)} \n") # Header
f.write(" ".join(array))
else:
print("File not writable")
f.close()
# Gets the file name
fileNameEnv = os.getenv("p_file")
fileName = fileNameEnv if fileNameEnv != None else input("Enter File Name:\n")
# Starts Reading file from source
file = readFile(fileName)
header = file.readline()
data = file.readline()
file.close()
# Problem Variables
maxSlice, numOftypes = [int(x) for x in header.split(" ")]
array = data.split(" ")
numOfImpTypes = len(array)
print(f"""Maximum Number of Slices: {maxSlice}
Number of Available Types: {numOftypes}""")
print(f"Number of Imported Types: {numOfImpTypes}")
usedTypes = [] # Pizza Type Keys (index)
slices = 0 # Points (Slices)
for i in range(0, numOfImpTypes): # Processing the data
v = int(array[numOfImpTypes-1-i])
if v <= maxSlice:
usedTypes.append(str(numOfImpTypes-1-i))
maxSlice -= v
slices += v
print(f"\r Processing Types {i+1}/{numOfImpTypes} ", end="")
print("\n Done!")
noTypesUsed = len(usedTypes)
print(f"Grabbed {noTypesUsed} Pizza Types")
print(f"Which is {slices} slices in total")
# Writing the output (Solution)
writeFile(fileName, sorted(usedTypes))
# Optional (Extra)
# Writes Output Extra Info
writeFile(fileName + "_details",
[str(noTypesUsed), str(slices)])
|
10cd9181b7bdbb9c5e898401099350e7a319ec19 | ShukurDev/Algorithms | /python_algorithms/#1 - Task/max.py | 281 | 3.734375 | 4 | a,b,c = map(int,input().split())
if a>b:
if a>c:
print(f"{a} eng katta son.")
else:
print(f"{c} eng katta son.")
elif a<b:
if b>c:
print(f"{b} eng katta son.")
else:
print(f"{c} eng katta son.")
else:
print(f"{c} eng katta son.") |
8e656ae9c9e7be5c01b244129d12f848b0b422f2 | maguedon/codingup | /2016/desamorcage_explosif.py | 234 | 3.6875 | 4 | #python3.6.3
# numSerie = '317010'
numSerie = '449149'
middle = int(len(numSerie)/2)
u = numSerie[0:middle]
n = numSerie[middle:len(numSerie)]
u = int(u)
n = int(n)
for i in range(n):
u *= 13
u = str(u)[-3:]
u = int(u)
print(u) |
8a75540b3347022ab3ebac5c8f6b9e39bd7b6907 | theemilyzhang/15-112_TP | /Player.py | 3,036 | 3.953125 | 4 | import Balloon
import Tower
from mathFunctions import *
import random
class Player(object):
def __init__(self):
self.hp = 20
self.coins = 150
self.towers = []
self.bullets = []
self.cacti = []
self.placingTower = None
self.placingCactus = None
self.illegallyPlacedItem = False
self.cantAfford = False
self.offBalloons = self.createBalloons()
self.onBalloons = []
def createBalloons(self, difficulty="easy"):
balloons = []
balloons.append(Balloon.DisappearingBalloon())
maxScore = 75
score = 0
if difficulty == "hard":
maxScore = 125
balloons.append(Balloon.Blimp())
#indexes:
#0: Balloon
#1: BlueBalloon
#2: GreenBalloon
#3: YellowBalloon
#4: PinkBalloon
#5: DisappearingBalloon
while score < maxScore:
index = random.randint(0, 5)
if index == 0:
balloons.append(Balloon.Balloon())
elif index == 1:
balloons.append(Balloon.BlueBalloon())
elif index == 2:
balloons.append(Balloon.GreenBalloon())
elif index == 3:
balloons.append(Balloon.YellowBalloon())
elif index == 4:
balloons.append(Balloon.PinkBalloon())
elif index == 5:
balloons.append(Balloon.DisappearingBalloon())
if index == 5:
score += 3
else:
score += (index+1)
return balloons
def moveBalloonOn(self, board):
#moves a balloon from offBalloons to onBalloons and changes its position to the start of the path
balloon = self.offBalloons.pop()
#question: should i be calling a specific Board here^?
balloon.position = (0, board.startY)
self.onBalloons.append(balloon)
def addTower(self, x, y):
newTower = Tower.Tower((x, y))
self.towers.append(newTower)
def canPlaceItemHere(self, x, y, towerRadius, width, height):
#return False if:
#1: overlap with tower
#2: overlap with cactus
#3: overlap with balloon
#4: too close to balloon exit/entrance
#1
for tower in self.towers:
if itemsOverlap(x, y, tower.location[0], tower.location[1], towerRadius, tower.radius):
return False
#2
for cactus in self.cacti:
if itemsOverlap(x, y, cactus.location[0], cactus.location[1], towerRadius, cactus.radius):
return False
#3
for balloon in self.onBalloons:
if itemsOverlap(x, y, balloon.position[0], balloon.position[1], towerRadius, balloon.radius):
return False
#4
if getDistance(0, 0, x, y) < 4 * towerRadius:
return False
elif getDistance(x, y, width, height) < 4 * towerRadius:
return False
return True
|
b70882e118f3c2706f4562bef5f19dff03242d41 | jose-m-marrero/MDTanaliza | /MDTa_interface.py | 78,655 | 3.59375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
import sys
from Tkinter import *
from Tkinter import Tk, Frame, BOTH
import Tkconstants, tkFileDialog
from tkMessageBox import showerror, showinfo, askyesno
import numbers
"""
* Copyright (C) 2009-2017 Jose M. Marrero <[email protected]> and Ramon Ortiz <[email protected]>
* You may use, distribute and modify this code under the terms of the MIT License.
* The authors will not be held responsible for any damage or losses or for any implications
* whatsoever resulting from downloading, copying, compiling, using or otherwise handling this
* source code or the program compiled.
Code name: MDTanaliza GUI
Version: 2.1-2018-04-06
Execute command line: ./MDTa_interface.py
Authors: Jose M. Marrero (1) R. Ortiz Ramis (2)
Affiliation 1: REPENSAR
Affiliation 1: IGEO-CSIC
"""
'''
x = StringVar() # Holds a string; default value ""
x = IntVar() # Holds an integer; default value 0
x = DoubleVar() # Holds a float; default value 0.0
x = BooleanVar() # Holds a boolean, returns 0 for False and 1 for True
To read the current value of such a variable, call the method get(). The value of such a variable can be changed with the set() method.
'''
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.ntipe = 0
self.LAN = 2
if self.LAN < 1 or self.LAN > 2:
print "Atencion, el numero asignado al lenguage debe estar entre 1 o 2"
sys.exit()
self.initUI()
#CHAGE LANGUAGE
def chalangen2sp(self):
if (self.LAN == 2):
self.LAN = 1
self.initUI()
def chalangsp2en(self):
if (self.LAN == 1):
self.LAN = 2
self.initUI()
#UPDATE DISABLE-NORMAL----------------------------------------------
def update_chk(self):
"""Change status according to weather some buttons are pressed or not."""
#MODIFICA MDT
if self.newz.get():
self.fase1.config(state=NORMAL)
self.fase2.config(state=NORMAL)
if self.nfase.get() == 1:
self.dirma.delete(0,END)
self.dirma.config(state=NORMAL)
self.nwz.delete(0,END)
self.nwz.config(state=DISABLED)
self.maskButton.config(state=NORMAL)
self.newButton.config(state=DISABLED)
self.masktipe.set(0)
self.maskradb.config(state=NORMAL)
self.maskrada.config(state=NORMAL)
if self.nfase.get() == 2:
self.dirma.delete(0,END)
self.dirma.config(state=DISABLED)
self.nwz.delete(0,END)
self.nwz.config(state=NORMAL)
self.maskButton.config(state=DISABLED)
self.newButton.config(state=NORMAL)
self.masktipe.set(0)
self.maskradb.config(state=DISABLED)
self.maskrada.config(state=DISABLED)
if self.newz.get() == 0:
self.nfase.set(0)
self.fase1.config(state=DISABLED)
self.fase2.config(state=DISABLED)
self.masktipe.set(0)
self.maskradb.config(state=DISABLED)
self.maskrada.config(state=DISABLED)
self.dirma.delete(0,END)
self.dirma.config(state=DISABLED)
self.maskButton.config(state=DISABLED)
self.nwz.delete(0,END)
self.nwz.config(state=DISABLED)
self.newButton.config(state=DISABLED)
#RECORTE
if self.recor.get():
self.xmin.config(state=NORMAL)
self.xmax.config(state=NORMAL)
self.ymin.config(state=NORMAL)
self.ymax.config(state=NORMAL)
self.resx.config(state=NORMAL)
self.resy.config(state=NORMAL)
if (self.recor.get() == 0):
self.xmin.delete(0,END)
self.xmin.config(state=DISABLED)
self.xmax.delete(0,END)
self.xmax.config(state=DISABLED)
self.ymin.delete(0,END)
self.ymin.config(state=DISABLED)
self.ymax.delete(0,END)
self.ymax.config(state=DISABLED)
self.resx.delete(0,END)
self.resx.config(state=DISABLED)
self.resy.delete(0,END)
self.resy.config(state=DISABLED)
#PROCESADO
#sink -----------------------------
valsik = int(self.sikvar.get())
if valsik == 0:
self.siklab.config(bg="#d9d9d9", foreground="black", text=self.txtchk9)
if valsik == 1:
self.siklab.config(bg="yellow", foreground="blue", text=self.txtchk9a)
if valsik == 2:
self.siklab.config(bg="yellow", foreground="blue", text=self.txtchk9b)
#aspcet ----------------------------
valasp = int(self.aspvar.get())
if valasp == 0:
self.asplab.config(bg="#d9d9d9", foreground="black", text=self.txtchk10)
if valasp == 1:
self.asplab.config(bg="yellow", foreground="blue", text=self.txtchk10a)
if valasp == 2:
self.asplab.config(bg="yellow", foreground="blue", text=self.txtchk10b)
#slope -----------------------------
valslo = int(self.slopvar.get())
if valslo == 0:
self.sloplab.config(bg="#d9d9d9", foreground="black", text=self.txtchk11)
if valslo == 1:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11a)
if valslo == 2:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11b)
if valslo == 3:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11c)
if valslo == 4:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11d)
if valslo == 5:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11e)
if valslo == 6:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11f)
if valslo == 7:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11g)
if valslo == 8:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11h)
if valslo == 9:
self.sloplab.config(bg="yellow", foreground="blue", text=self.txtchk11i)
#TRAYECTO
#algor = int(self.npt.get())
algor = int(self.tratip.get())
if(algor == 0):
self.dismax.delete(0,END)
self.dismax.config(state=DISABLED)
self.altmax.delete(0,END)
self.altmax.config(state=DISABLED)
self.rad.delete(0,END)
self.rad.config(state=DISABLED)
self.incre.delete(0,END)
self.incre.config(state=DISABLED)
self.force.set("0") #<-------------
self.forceval.config(state=DISABLED) #<-------------
self.itera.delete(0,END)
self.itera.config(state=DISABLED)
self.npt.delete(0,END)
self.npt.config(state=DISABLED)
self.T.delete("0.0",'end')
self.T.config(state=DISABLED)
self.loadnpt.config(state=DISABLED)
self.labalgtyp.config(text=self.txtlab18)
self.mod.set("0") #<-------------
self.modval.config(state=DISABLED) #<-------------
#self.mod.delete(0,END)
#self.mod.config(state=DISABLED)
self.huso.config(state=DISABLED)
self.labhemis.config(bg="#d9d9d9", foreground="black", text=self.txtlab19) #<-------------
self.hemis.set("0") #<-------------
self.hemisval.config(state=DISABLED) #<-------------
#self.hemis.config(state=DISABLED) #<-------------
#activado
if(algor > 0):
self.dismax.config(state=NORMAL)
self.altmax.config(state=NORMAL)
self.npt.config(state=NORMAL)
self.T.config(state=NORMAL)
self.loadnpt.config(state=NORMAL)
#self.mod.config(state=NORMAL)
self.modval.config(state="readonly") #<-------------
self.huso.config(state=NORMAL)
self.hemisval.config(state="readonly")
typhem = int(self.hemis.get()) #<-------------
if(typhem == 0): #<-------------
self.labhemis.config(bg="yellow", foreground="blue", text=self.txtlab19a) #<-------------
if(typhem == 1): #<-------------
self.labhemis.config(bg="yellow", foreground="blue",text=self.txtlab19b) #<-------------
#self.hemis.config(state=NORMAL) #<-------------
if(algor == 1 or algor == 2):
self.incre.config(state=NORMAL)
self.forceval.config(state="readonly") #<-------------
self.rad.delete(0,END)
self.rad.config(state=DISABLED)
self.itera.delete(0,END)
self.itera.config(state=DISABLED)
if(algor == 1):
self.labalgtyp.config(text=self.txtlab18a)
if(algor == 2):
self.labalgtyp.config(text=self.txtlab18b)
if(algor == 3):
self.incre.config(state=NORMAL)
self.forceval.config(state="readonly") #<-------------
self.itera.config(state=NORMAL)
self.rad.delete(0,END)
self.rad.config(state=DISABLED)
self.labalgtyp.config(text=self.txtlab18c)
if(algor == 4):
self.rad.config(state=NORMAL)
self.incre.delete(0,END)
self.incre.config(state=DISABLED)
self.force.set("0") #<-------------
self.forceval.config(state=DISABLED) #<-------------
self.itera.delete(0,END)
self.itera.config(state=DISABLED)
self.labalgtyp.config(text=self.txtlab18d)
#CHECK INTEGRITY----------------------------------------------------
def checkseq(self):
"""Secuencia de chequeo de informacion"""
#check integrity sequence---------------------------------------
self.totfall = 0
#directorios
dirdat = self.checkdirectories()
#modifica
if(self.newz.get() == 1):
mod = self.checkmodifica()
if(self.newz.get() == 0):
msg2 = "Modifica no elegido -2-\n"
self.txtout.insert("0.0", msg2)
print msg2
mod = 1
#datos mdt
data = self.checkdatosdtm()
#recorte
if(self.recor.get() == 1):
rec = self.checkrecorte()
if(self.recor.get() == 0):
msg2 = "Recorte no elegido -4-\n"
self.txtout.insert("0.0", msg2)
print msg2
rec = 1
#procesa
valsik = int(self.sikvar.get())
valasp = int(self.aspvar.get())
valslo = int(self.slopvar.get())
if (valsik > 0 or valasp > 0 or valslo > 0):
pros = self.checkprocesados()
else:
msg2 = "Procesados no elegido -5-\n"
self.txtout.insert("0.0", msg2)
print msg2
pros = 1
#trayec
if len(self.npt.get()) > 0:
val = int(self.npt.get())
if(val > 0):
tra = self.checktrayectorias()
if(val == 0):
msg2 = "Trayectorias no elegidas -6-\n"
self.txtout.insert("0.0", msg2)
print msg2
tra = 1
if len(self.npt.get()) == 0:
msg2 = "Trayectorias no elegidas -6-\n"
self.txtout.insert("0.0", msg2)
print msg2
tra = 1
glob = dirdat + mod + data + rec + pros + tra
if glob == 6: #ok
return 1
if glob != 6: #errores
return 0
def checkdirectories(self):
self.demButton.configure(bg="#d9d9d9")
self.outButton.configure(bg="#d9d9d9")
fallos = 0
#**********************************MDT
self.valtx = self.dirin.get()
self.texlab = "MDT"
if not self.dirin.get(): #no esta relleno
self.is_filled()
self.demButton.configure(bg="red")
fallos +=1
if self.dirin.get(): #si esta relleno
resul = self.is_filexist() #existe ruta
if(resul == 0): #no existe
self.demButton.configure(bg="red")
fallos +=1
if(resul == 1): #si existe
if self.num < 2000:
self.ntipe = self.is_binary() #es binario
self.valnum = self.demtipe.get()
if self.ntipe: #si es
coin = self.binasc_ok() #coincide tipo
if coin == 1: #no coincide
self.labdtipe.configure(bg="red")
self.demButton.configure(bg="red")
fallos +=1
if not self.ntipe: #si no es
coin = self.binasc_ok() #coincide tipo
if coin == 2: #no coincide
self.labdtipe.configure(bg="red")
self.demButton.configure(bg="red")
fallos +=1
#*************************
self.valtx = self.dirout.get()
self.texlab = "Dirout"
if not self.dirout.get(): #no esta relleno
self.is_filled()
self.outButton.configure(bg="red")
fallos +=1
if self.dirout.get(): #si esta relleno
resul = self.is_pathxist() #existe ruta
if(resul == 0): #no existe
self.outButton.configure(bg="red")
fallos +=1
#****************
if fallos > 0:
msg2 = ("Rutas con %i fallos\n" % fallos)
self.txtout.insert("0.0", msg2)
print msg2
self.totfall += fallos
return 0
if fallos == 0:
msg2 = "Rutas correctas -1-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
def checkmodifica(self):
self.maskButton.configure(bg="#d9d9d9")
self.newButton.configure(bg="#d9d9d9")
self.newbut.configure(bg="#d9d9d9")
self.labmasktipe.configure(bg="#d9d9d9")
#new xyz----------------------------------------------------
fallos = 0
if(self.newz.get() == 1):
val = self.nfase.get()
if val == 0:
textmsg = "Atencion, no se ha elegido la fase"
msg = showerror(title = "Error", message = textmsg)
self.newbut.configure(bg="red")
msg2 = "Error en archivo, falta el archivo XYZ\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos +=1
#****************************************mascara
if val == 1:
self.valtx = self.dirma.get()
self.texlab = "Mascara"
if not self.dirma.get(): #no esta relleno
self.is_filled()
self.newbut.configure(bg="red")
self.maskButton.configure(bg="red")
fallos +=1
if self.dirma.get(): #si esta relleno
resul = self.is_filexist() #existe ruta
if(resul == 0): #no existe
self.maskButton.configure(bg="red")
fallos +=1
if(resul == 1): #si existe
self.ntipe = self.is_binary() #es binario
if self.ntipe: #si es
self.valnum = self.masktipe.get()
coin = self.binasc_ok() #coincide tipo
if coin == 1: #no coincide
self.newbut.configure(bg="red")
self.labmasktipe.configure(bg="red")
fallos +=1
if not self.ntipe: #si no es
self.valnum = self.masktipe.get()
coin = self.binasc_ok() #coincide tipo
if coin == 2: #no coincide
self.newbut.configure(bg="red")
self.labmasktipe.configure(bg="red")
fallos +=1
#****************************************newxyz
if val == 2:
self.valtx = self.nwz.get()
self.texlab = "NewXYZ"
if not self.nwz.get():
self.is_filled()
self.newbut.configure(bg="red")
self.newButton.configure(bg="red")
fallos +=1
if self.nwz.get():
resul = self.is_filexist()
if(resul == 0): #no existe
self.newbut.configure(bg="red")
self.newButton.configure(bg="red")
fallos +=1
#****************
if fallos > 0:
msg2 = ("Modifica con %i fallos\n" % fallos)
self.txtout.insert("0.0", msg2)
print msg2
self.totfall += fallos
return 0
if fallos == 0:
msg2 = "Modifica correcto -2-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
#**************
if(self.newz.get() == 0):
msg2 = "Modifica no elegido -2-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
def checkdatosdtm(self):
self.labdmax.configure(bg="#d9d9d9")
self.labdmin.configure(bg="#d9d9d9")
self.labdnull.configure(bg="#d9d9d9")
#Valores DTM----------------------------------------------------
fallos = 0
#***********************************Maxval
totresp = 0
self.valtx = self.maxval.get()
self.texlab = "Maxval"
if len(self.maxval.get()) == 0:
self.labdmax.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.maxval.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_decimal()
totresp = resp1 + resp2
if(totresp > 0):
self.labdmax.configure(bg="red")
fallos += totresp
#***********************************Minval
totresp = 0
self.valtx = self.minval.get()
self.texlab = "Minimo"
if len(self.minval.get()) == 0:
self.labdmin.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.minval.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_decimal()
totresp = resp1 + resp2
if(totresp > 0):
self.labdmin.configure(bg="red")
fallos += totresp
#***********************************Nullval
totresp = 0
self.valtx = self.nullval.get()
self.texlab = "Nullval"
if len(self.nullval.get()) == 0:
self.labdnull.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.nullval.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_entero()
if(resp1 == 1 or resp2 == 1):
self.labdnull.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
if(resp1 == 0 and resp2 == 0):
self.valnum = int(self.nullval.get())
#****************
if fallos > 0:
msg2 = ("MDT con %i fallos\n" % fallos)
self.txtout.insert("0.0", msg2)
print msg2
self.totfall += fallos
return 0
if fallos == 0:
msg2 = "Valores MDT correctos -3-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
def checkrecorte(self):
self.labdxmin.configure(bg="#d9d9d9")
self.labdxmax.configure(bg="#d9d9d9")
self.labdymin.configure(bg="#d9d9d9")
self.labdymax.configure(bg="#d9d9d9")
self.labdrex.configure(bg="#d9d9d9")
self.labdrey.configure(bg="#d9d9d9")
#recorte--------------------------------------------------------
fallos = 0
if(self.recor.get() == 1):
#************************************Xmin
totresp = 0
self.valtx = self.xmin.get()
self.texlab = "Xmin"
if len(self.xmin.get()) == 0:
self.labdxmin.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.xmin.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.xmin.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdxmin.configure(bg="red")
fallos += totresp
#************************************Xmax
totresp = 0
self.valtx = self.xmax.get()
self.texlab = "Xmax"
if len(self.xmax.get()) == 0:
self.labdxmax.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.xmax.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.xmax.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdxmax.configure(bg="red")
fallos += totresp
#************************************Ymin
totresp = 0
self.valtx = self.ymin.get()
self.texlab = "Ymin"
if len(self.ymin.get()) == 0:
self.labdymin.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.ymin.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.ymin.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdymin.configure(bg="red")
fallos += totresp
#*************************************Ymax
totresp = 0
self.valtx = self.ymax.get()
self.texlab = "Ymax"
if len(self.ymax.get()) == 0:
self.labdymax.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.ymax.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.ymax.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdymax.configure(bg="red")
fallos += totresp
#***************************************resx
totresp = 0
self.valtx = self.resx.get()
self.texlab = "Resx"
if len(self.resx.get()) == 0:
self.labdrex.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.resx.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.resx.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdrex.configure(bg="red")
fallos += totresp
#****************************************resy
totresp = 0
self.valtx = self.resy.get()
self.texlab = "Resy"
if len(self.resy.get()) == 0:
self.labdrey.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.resy.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.resy.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdrey.configure(bg="red")
fallos += totresp
#****************
if fallos > 0:
msg2 = ("Recorte con %i fallos\n" % fallos)
self.txtout.insert("0.0", msg2)
print msg2
self.totfall += fallos
return 0
if fallos == 0:
msg2 = "Recorte correcto -4-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
'''
if(self.recor.get() == 0):
msg2 = "Recorte no elegido -4-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
'''
def checkprocesados(self):
#PROCESADO DTM----------------------------------------------
fallos = 0
used = 0
#****************************************sink
self.valtx = self.sikvar.get()
self.texlab = self.txtchk9
valsik = int(self.sikvar.get())
if valsik > 0:
used = 1
if valsik < 0 or valsik >2:
textmsg = "Atencion, el valor debe estar entre 1-2"
self.siklab.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = ("Error, valor fuera de rango en %s\n" % self.txtchk9)
self.txtout.insert("0.0", msg2)
print msg2
fallos +=1
#****************************************aspect
self.valtx = self.aspvar.get()
self.texlab = self.txtchk10
valasp = int(self.aspvar.get())
if valasp > 0:
used = 1
if valasp < 0 or valasp >2:
textmsg = "Atencion, el valor debe estar entre 1-2"
self.asplab.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = ("Error, valor fuera de rango en %s\n" % self.txtchk10)
self.txtout.insert("0.0", msg2)
print msg2
fallos +=1
#****************************************slope
self.valtx = self.slopval.get()
self.texlab = self.txtchk11
valslo = int(self.slopvar.get())
if valslo > 0:
used = 1
if valslo < 0 or valslo >9:
textmsg = "Atencion, el valor debe estar entre 1-9"
self.sloplab.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = ("Error, valor fuera de rango en slope\n" % self.txtchk11)
self.txtout.insert("0.0", msg2)
print msg2
fallos +=1
#****************
if used == 1:
if fallos > 0:
msg2 = ("Procesados con %i fallos\n" % fallos)
self.txtout.insert("0.0", msg2)
self.totfall += fallos
print msg2
return 0
if fallos == 0:
msg2 = "Procesados correctos -5-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if used == 0:
if (self.aspec.get() == 0):
msg2 = "Procesados no elegido -5-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
def checktrayectorias(self):
"""check integrity in the GUI"""
wkdir = os.getcwd()
self.labdminlabdmax.configure(bg="#d9d9d9")
self.labdminlabalt.configure(bg="#d9d9d9")
self.labdminlabrad.configure(bg="#d9d9d9")
self.labdminlabinc.configure(bg="#d9d9d9")
self.labdminlabfor.configure(bg="#d9d9d9") #<-------------
self.labdminlabnpt.configure(bg="#d9d9d9")
self.labdminlabite.configure(bg="#d9d9d9")
self.T.configure(bg="white")
#TRAYECTORIAS DTM-------------------------------------------
fallos = 0
elegido = 0
algor = int(self.tratip.get()) #tipo algoritmo
#Para cualquier situacion donde se active la opcion trayect
if(algor > 0):
#************************************DistMax
elegido = 1
self.valtx = self.dismax.get()
self.texlab = "Dismax"
if len(self.dismax.get()) == 0:
self.labdminlabdmax.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.dismax.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.dismax.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdminlabdmax.configure(bg="red")
fallos += totresp
#************************************AlstMax
self.valtx = self.altmax.get()
self.texlab = "Altmax"
if len(self.altmax.get()) == 0:
self.labdminlabalt.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.altmax.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.altmax.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdminlabalt.configure(bg="red")
fallos += totresp
#************************************npt
if len(self.npt.get()) == 0:
textmsg = "Atencion, faltan los puntos para evaluar trayectorias"
self.labdminlabnpt.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en trayectorias, falta el algoritmo\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
#***********************************XYZpt
if len(self.npt.get()) > 0:
puntos = int(self.npt.get()) #puntos
content = self.T.get("1.0", END)
totlineas = int(self.T.index('end-1c').split('.')[0])
if len(content) <= 1:
textmsg = "Atencion, faltan los puntos con coordenadas\n"
self.T.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en trayectorias, falta los puntos con coordenadas\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
if totlineas < puntos:
textmsg = "Atencion, el numero de coordenadas es menor que el indicado\n"
self.labdminlabnpt.configure(bg="red")
self.T.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en trayectorias, faltan puntos con coordenadas\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
#***********************************MODE
self.valtx = self.mod.get()
self.texlab = "Mode"
if len(self.mod.get()) == 0:
self.labdminlabmod.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.mod.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_entero()
if(resp1 == 1 or resp2 == 1):
self.labdminlabmod.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
var = int(self.mod.get())
if var < 0 or var > 1:
textmsg = "Atencion, MODE debe estar entre 0 y 1\n"
self.labdminlabmod.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en mode\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
#***********************************HUSO
self.valtx = self.huso.get()
self.texlab = "Huso"
if len(self.huso.get()) == 0:
self.labhuso.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.huso.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_entero()
if(resp1 == 1 or resp2 == 1):
self.labhuso.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
var = int(self.huso.get())
if var < 0 or var > 60:
textmsg = "Atencion, el uso debe estar entre 0 y 60\n"
self.labhuso.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en huso\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
#***********************************hemis
self.valtx = self.hemis.get()
self.texlab = "Hemisferio"
if len(self.hemis.get()) == 0:
self.labhemis.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.hemis.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_entero()
if(resp1 == 1 or resp2 == 1):
self.labhemis.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
var = int(self.hemis.get())
if var < 0 or var > 1:
textmsg = "Atencion, el hemisferio es 0 norte y 1 sur\n"
self.labhemis.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en huso\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
#************************************RadBus
if(algor == 4):
self.valtx = self.rad.get()
self.texlab = "RadBus-Rest"
if len(self.rad.get()) == 0:
self.labdminlabrad.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.rad.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_decimal()
if(resp1 == 1 or resp2 == 1):
self.labdminlabrad.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
#************************************IncAlt
if(algor == 1 or algor == 2 or algor == 3):
self.valtx = self.incre.get()
self.texlab = "IncAlt"
if len(self.incre.get()) == 0:
self.labdminlabinc.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.incre.get()) > 0:
resp3 = 0
resp1 = self.is_punto()
resp2 = self.is_decimal()
if((resp1 + resp2) == 0):
self.valnum = float(self.incre.get())
resp3 = self.is_positivo()
totresp = resp1 + resp2 + resp3
if(totresp > 0):
self.labdminlabinc.configure(bg="red")
fallos += totresp
#***********************************FORCE
if(algor == 1 or algor == 2 or algor == 3):
self.valtx = self.force.get()
self.texlab = "Force"
if len(self.force.get()) == 0:
self.labdminlabfor.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.force.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_entero()
if(resp1 == 1 or resp2 == 1):
self.labdminlabfor.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
var = int(self.force.get())
print var
if var < 0 or var > 1:
textmsg = "Atencion, FORCE debe estar entre 0 y 1\n"
self.labdminlabfor.configure(bg="red")
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en mode\n"
self.txtout.insert("0.0", msg2)
print msg2
fallos += 1
#************************************Itera
if(algor == 3):
self.valtx = self.itera.get()
self.texlab = "Itera"
if len(self.itera.get()) == 0:
self.labdminlabite.configure(bg="red")
self.is_filled()
fallos +=1
if len(self.rad.get()) > 0:
resp1 = self.is_punto()
resp2 = self.is_entero()
if(resp1 == 1 or resp2 == 1):
self.labdminlabite.configure(bg="red")
if(resp1 == 1):
fallos += 1
if(resp2 == 1):
fallos += 1
#************************************
if(elegido == 1):
if fallos > 0:
msg2 = ("Encontrados %i fallos\n" % fallos)
self.txtout.insert("0.0", msg2)
print msg2
self.totfall += fallos
return 0
if fallos == 0:
msg2 = "Trayectorias correctas -6-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if(elegido == 0):
msg2 = "Trayectorias no elegidas -6-\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
#CHECK BINARY - TYPE NUMBER-----------------------------------------
def is_binary(self):
filename = self.valtx
fin = open(filename, 'rb')
try:
CHUNKSIZE = 1024
while 1:
chunk = fin.read(CHUNKSIZE)
if '\0' in chunk: # found null byte
return True #es binario
if len(chunk) < CHUNKSIZE:
break # done
finally:
fin.close()
return False #es ascii
def binasc_ok(self):
formerror = 0
if self.ntipe: #es bin
if (self.valnum != 1 ):
formerror = 1
if not self.ntipe: #es asc
if (self.valnum != 2):
formerror = 1
if formerror == 1:
textmsg = "Atencion, el tipo (bin-ascii) no coincide con el archivo mascara"
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en tipo de archivo\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if formerror == 0:
return 0
def is_filled(self):
textmsg = ("Atencion, falta el valor %s" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en recorte, falta valor ymax\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
def is_punto(self):
if ',' in self.valtx:
textmsg = "Atencion, debe utilizar un punto para el separador decimal"
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en valor, punto para decimal\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if not ',' in self.valtx:
return 0
def is_decimal(self):
if not '.' in self.valtx:
if self.ndectype == 0:
textmsg = ("Atencion, el valor %s debe ser decimal" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en valor, debe ser decimal\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if self.ndectype == 1:
msg2 = "Archivo con cabecera\n"
self.txtout.insert("0.0", msg2)
self.ndectype = 0
return 1
if '.' in self.valtx:
self.ndectype = 0
return 0
def is_entero(self):
if '.' in self.valtx:
if self.ndectype == 0:
textmsg = ("Atencion, el valor %s debe ser entero" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en valor, debe ser entero\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if self.ndectype == 1:
self.ndectype = 0
return 1
if not '.' in self.valtx:
self.ndectype = 0
return 0
def is_positivo(self):
if(self.valnum < 0):
textmsg = ("Atencion, %s debe ser positivo" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en valor, debe ser postivio\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if(self.valnum >= 0):
return 0
def is_negativo(self):
if(self.valnum >= 0):
textmsg = ("Atencion, %s debe ser positivo" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en valor, debe ser postivio\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if(self.valnum < 0):
return 0
def is_filexist(self):
filename = self.valtx
#si es archivo
if not os.path.isfile(filename):
textmsg = ("Atencion, el archivo o la ruta a %s no existe" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en ruta al archivo\n"
self.txtout.insert("0.0", msg2)
print msg2
return 0
if os.path.isfile(filename):
file_info = os.stat(filename)
self.num = file_info.st_size
#self.convert_bytes()
return 1
def is_pathxist(self):
filename = self.valtx
self.color = 0
#si es archivo
if not os.path.exists(filename):
textmsg = (u"Atencion, la ruta a %s no existe, ¿desea crearla?" % self.texlab)
msg = askyesno(title = "Error", message = textmsg)
if msg == True:
try:
os.makedirs(filename)
return 1
except OSError as exception:
if exception.errno != errno.EEXIST:
return 0
if msg == False:
textmsg = (u"La ruta a %s no a sido creada" % self.texlab)
msg = showerror(title = "Error", message = textmsg)
msg2 = "La ruta no a sido creada\n"
self.txtout.insert("0.0", msg2)
print msg2
return 0
if os.path.exists(filename):
return 1
def convert_bytes(self):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if self.num < 1024.0:
return "%3.1f %s" % (self.num, x)
self.num /= 1024.0
#CLEAN GUI----------------------------------------------------------
def cleangui(self):
self.demButton.configure(bg="#d9d9d9")
self.outButton.configure(bg="#d9d9d9")
self.maskButton.configure(bg="#d9d9d9")
self.newButton.configure(bg="#d9d9d9")
self.newbut.configure(bg="#d9d9d9")
self.labdmax.configure(bg="#d9d9d9")
self.labdmin.configure(bg="#d9d9d9")
self.labdnull.configure(bg="#d9d9d9")
self.labdxmin.configure(bg="#d9d9d9")
self.labdxmax.configure(bg="#d9d9d9")
self.labdymin.configure(bg="#d9d9d9")
self.labdymax.configure(bg="#d9d9d9")
self.labdrex.configure(bg="#d9d9d9")
self.labdrey.configure(bg="#d9d9d9")
#---
self.siklab.config(bg="#d9d9d9", foreground="black", text=self.txtchk9)
self.asplab.config(bg="#d9d9d9", foreground="black", text=self.txtchk10)
self.sloplab.config(bg="#d9d9d9", foreground="black", text=self.txtchk11)
#---
#self.labdminlabtray.configure(bg="#d9d9d9")
self.labdminlabdmax.configure(bg="#d9d9d9")
self.labdminlabalt.configure(bg="#d9d9d9")
self.labdminlabrad.configure(bg="#d9d9d9")
self.labdminlabinc.configure(bg="#d9d9d9")
self.labdminlabmod.configure(bg="#d9d9d9")
self.labdminlabnpt.configure(bg="#d9d9d9")
self.T.configure(bg="white")
self.labhuso.configure(bg="#d9d9d9")
self.labhemis.configure(bg="#d9d9d9")
self.dirin.delete(0,END)
self.dirout.delete(0,END)
self.newz.set(0)
self.nfase.set(0)
self.dirma.delete(0,END)
self.dirma.config(state=DISABLED)
self.nwz.delete(0,END)
self.nwz.config(state=DISABLED)
self.newButton.config(state=DISABLED)
self.maskButton.config(state=DISABLED)
self.demtipe.set(0)
#self.demradb.config(state=DISABLED)
#self.demrada.config(state=DISABLED)
self.maxval.delete(0,END)
self.minval.delete(0,END)
self.nullval.delete(0,END)
self.recor.set(0)
self.xmin.delete(0,END)
self.xmin.config(state=DISABLED)
self.xmax.delete(0,END)
self.xmax.config(state=DISABLED)
self.ymin.delete(0,END)
self.ymin.config(state=DISABLED)
self.ymax.delete(0,END)
self.ymax.config(state=DISABLED)
self.resx.delete(0,END)
self.resx.config(state=DISABLED)
self.resy.delete(0,END)
self.resy.config(state=DISABLED)
self.sikvar.set('0')
self.aspvar.set('0')
self.slopvar.set('0')
self.tratip.set(0)
self.dismax.delete(0,END)
self.altmax.delete(0,END)
self.rad.delete(0,END)
self.force.set("0")
self.incre.delete(0,END)
self.mod.set('0')
self.npt.delete(0,END)
self.npt.insert( INSERT, "0" )
self.T.delete("0.0",'end')
self.huso.delete(0,END)
self.huso.config(state=DISABLED)
self.hemisval.delete(0,END)
self.hemisval.config(state=DISABLED)
#OPEN FILE----------------------------------------------------------
def dtmfile(self):
"""Returns a selected directoryname."""
self.demButton.configure(bg="#d9d9d9")
wkdir = os.getcwd()
#txtdir = tkFileDialog.askdirectory(parent=self,title='Directorio entrada DTM')
#comdir = txtdir + "/"
filename = tkFileDialog.askopenfilename(parent=self,title='Nombre MDT')
if filename:
self.txtout.insert("0.0", filename)
#print os.path.commonprefix([wkdir, filename])
finalfile = '/' + os.path.relpath(filename, wkdir)
print finalfile
print filename
self.valtx = filename
self.dirin.delete(0,END)
self.dirin.insert(INSERT, filename)
self.ntipe = 1
tipe = self.is_binary()
if tipe:
self.demtipe.set(1)
else:
self.demtipe.set(2)
if not filename:
print "Accion cancelada\n"
def direout(self):
"""Returns a selected directoryname."""
self.outButton.configure(bg="#d9d9d9")
txtdir = tkFileDialog.askdirectory(parent=self,title='Directorio de Salida')
if txtdir:
comdir = txtdir + "/"
self.txtout.insert("0.0", comdir)
self.dirout.delete(0,END)
self.dirout.insert(INSERT, comdir)
if not txtdir:
print "Accion cancelada\n"
def maskfile(self):
"""Returns a selected directoryname."""
self.maskButton.configure(bg="#d9d9d9")
self.labmasktipe.configure(bg="#d9d9d9")
#txtdir = tkFileDialog.askdirectory(parent=self,title='Directorio entrada DTM')
#comdir = txtdir + "/"
filename = tkFileDialog.askopenfilename(parent=self,title='Nombre Mascara')
if filename:
self.txtout.insert("0.0", filename)
print filename
self.dirma.delete(0,END)
self.dirma.insert(INSERT, filename)
self.ntipe = 2
self.valtx = filename
tipe = self.is_binary()
if tipe:
self.masktipe.set(1)
else:
self.masktipe.set(2)
if not filename:
print "Accion cancelada\n"
def newopenfile(self):
"""Returns a new xyz file name to modify the DEM."""
self.newButton.configure(bg="#d9d9d9")
self.newbut.configure(bg="#d9d9d9")
filename = tkFileDialog.askopenfilename(parent=self,title='Archivo xyz nuevo')
if filename:
print filename
#name = os.path.basename(filename)
self.txtout.insert("0.0", filename)
self.nwz.delete(0,END)
self.nwz.insert(INSERT, filename)
if not filename:
print "Accion cancelada\n"
def openhelp(self):
ostype = sys.platform
if ostype == 'linux2':
ejecutac = 'evince MDTa_help.pdf'
if ostype == 'darwin':
"open -a Preview.app MDTa_help.pdf"
if ostype == "win32":
print "windows"
print ostype
os.system(ejecutac)
return 1
#SAVE LOAD FILE-----------------------------------------------------
def savefile(self):
"""Save file, create a new file."""
#check integrity--------------------------------------------
valchk = self.checkseq()
print(valchk)
if valchk == 1:
#escribe un fichero de salida
self.cfgfile = tkFileDialog.asksaveasfilename(parent=self,filetypes=[('Config file','*.cfg')] ,title="Save configfile as...")
if self.cfgfile:
self.txtfile =open(self.cfgfile,"w")
self.writefile()
return 1
if valchk == 0:
textmsg = ("Atencion, imposible guardar archivo, se encontraron %s errores" % self.totfall)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error, imposible guardar\n"
self.txtout.insert("0.0", msg2)
print msg2
def savedefault(self):
"""Save default file, create a new file."""
#check integrity--------------------------------------------
valchk = self.checkseq()
if valchk == 1:
#escribe un fichero de salida
self.cfgfile = "MDTA_default.cfg"
if self.cfgfile:
self.txtfile =open(self.cfgfile,"w")
self.writefile()
return 1
if valchk == 0:
textmsg = ("Atencion, imposible ejecutar aplicacion, se encontraron %s errores" % self.totfall)
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error, imposible ejecutar\n"
self.txtout.insert("0.0", msg2)
print msg2
def writefile(self):
"""Write the new created file with the GUI content."""
#Corta las direcciones
wkdir = os.getcwd()
filename = self.dirin.get()
finaldir = '/' + os.path.relpath(filename, wkdir)
filename = self.dirout.get()
finalout = '/' + os.path.relpath(filename, wkdir) + '/'
#txtfile = open(self.cfgfile,"w")
self.txtfile.writelines("VERSION %s\n" % self.currentv)
self.txtfile.writelines("%s %s\n" % (self.txtout1, finaldir))
self.txtfile.writelines("DIR_OUT %s\n" % finalout)
#---------------------------------------------------------------
self.txtfile.writelines("[%s]\n" % self.txtout2)
if(self.newz.get() == 0):
self.txtfile.writelines("NEWZ 0\n")
self.txtfile.writelines("%s 0\n" % self.txtout3)
self.txtfile.writelines("%s 0\n" % self.txtout4)
self.txtfile.writelines("%s /masknamefile.grd\n" % self.txtout5)
self.txtfile.writelines("%s /xyzznamefile.txt\n" % self.txtout6)
if(self.newz.get() == 1):
self.txtfile.writelines("NEWZ 1\n")
self.txtfile.writelines("%s %i\n" % (self.txtout3, self.nfase.get()))
if self.nfase.get() == 1:
filename = self.dirma.get()
finalmask = '/' + os.path.relpath(filename, wkdir)
self.txtfile.writelines("%s %i\n" % (self.txtout4, self.masktipe.get()))
self.txtfile.writelines("%s %s\n" % (self.txtout5, finalmask))
self.txtfile.writelines("%s /xyzznamefile.txt\n" % self.txtout6)
if self.nfase.get() == 2:
filename = self.nwz.get()
finalxyz = '/' + os.path.relpath(filename, wkdir)
self.txtfile.writelines("%s 0\n" % self.txtout4)
self.txtfile.writelines("%s /masknamefile.grd\n" % self.txtout5)
self.txtfile.writelines("%s %s\n" % (self.txtout6, finalxyz))
#---------------------------------------------------------------
self.txtfile.writelines("[%s]\n" % self.txtout7)
#self.txtfile.writelines("DEM_NAME %s\n" % self.demname.get())
self.txtfile.writelines("%s %i\n" % (self.txtout8, self.demtipe.get()))
self.txtfile.writelines("MAX_ZVAL %s\n" % self.maxval.get())
self.txtfile.writelines("MIN_ZVAL %s\n" % self.minval.get())
self.txtfile.writelines("NULL_VAL %i\n" % int(self.nullval.get()))
if(self.recor.get() == 0):
self.txtfile.writelines("%s 0\n" % self.txtout9)
self.txtfile.writelines("X_MIN 0.0\n")
self.txtfile.writelines("X_MAX 0.0\n")
self.txtfile.writelines("Y_MIN 0.0\n")
self.txtfile.writelines("Y_MAX 0.0\n")
self.txtfile.writelines("RESX 0.0\n")
self.txtfile.writelines("RESY 0.0\n")
if(self.recor.get() == 1):
self.txtfile.writelines("%s 1\n" % self.txtout9)
self.txtfile.writelines("X_MIN %s\n" % self.xmin.get())
self.txtfile.writelines("X_MAX %s\n" % self.xmax.get())
self.txtfile.writelines("Y_MIN %s\n" % self.ymin.get())
self.txtfile.writelines("Y_MAX %s\n" % self.ymax.get())
self.txtfile.writelines("RESX %s\n" % self.resx.get())
self.txtfile.writelines("RESY %s\n" % self.resy.get())
#---------------------------------------------------------------
self.txtfile.writelines("[%s]\n" % self.txtout10)
valsik = int(self.sikvar.get())
self.txtfile.writelines("%s %i\n" % (self.txtout11, valsik))
#aspcet ----------------------------
valasp = int(self.aspvar.get())
self.txtfile.writelines("%s %i\n" % (self.txtout12, valasp))
#slope -----------------------------
valslo = int(self.slopvar.get())
self.txtfile.writelines("%s %i\n" % (self.txtout13, valslo))
#---------------------------------------------------------------
self.txtfile.writelines("[%s]\n" % self.txtout14)
algo = int(self.tratip.get())
if ( algo == 0):
self.txtfile.writelines("%s 0\n" % self.txtout15)
self.txtfile.writelines("DIST_MAX 0.0\n")
self.txtfile.writelines("%s 0.0\n" % self.txtout16)
self.txtfile.writelines("%s 0\n" % self.txtout17)
self.txtfile.writelines("%s 0.0\n" % self.txtout18)
self.txtfile.writelines("%s 0\n" % self.txtout19)
self.txtfile.writelines("%s 0\n" % self.txtout22) #<--------------
self.txtfile.writelines("UTMZONE 0\n")
self.txtfile.writelines("HEMIS 0\n")
self.txtfile.writelines("[SEC_POINTS]\n")
self.txtfile.writelines("N_CENTROS 0\n")
self.txtfile.writelines("[X_Y_JERAR_RIO]\n")
if ( algo > 0):
self.txtfile.writelines("%s %s\n" % (self.txtout15, self.tratip.get()))
self.txtfile.writelines("DIST_MAX %s\n" % self.dismax.get())
self.txtfile.writelines("%s %s\n" % (self.txtout16, self.altmax.get()))
if ( algo == 1 or algo == 2):
self.txtfile.writelines("%s 0\n" % self.txtout17)
self.txtfile.writelines("%s %s\n" % (self.txtout18, self.incre.get()))
self.txtfile.writelines("%s %s\n" % (self.txtout23, self.force.get()))
self.txtfile.writelines("%s 0\n" % self.txtout19)
if ( algo == 3):
self.txtfile.writelines("%s 0\n" % self.txtout17)
self.txtfile.writelines("%s %s\n" % (self.txtout18, self.incre.get()))
self.txtfile.writelines("%s %s\n" % (self.txtout23, self.force.get()))
self.txtfile.writelines("%s %s\n" % (self.txtout19, self.itera.get()))
if ( algo == 4):
self.txtfile.writelines("%s %s\n" % (self.txtout17, self.rad.get()))
self.txtfile.writelines("%s 0.0\n" % self.txtout18)
self.txtfile.writelines("%s 0\n" % self.txtout23)
self.txtfile.writelines("%s 0\n" % self.txtout19)
self.txtfile.writelines("WRITE_MOD %s\n" % self.mod.get())
self.txtfile.writelines("UTMZONE %s\n" % self.huso.get())
self.txtfile.writelines("HEMIS %s\n" % self.hemis.get())
self.txtfile.writelines("[SEC_POINTS]\n")
self.txtfile.writelines("%s %s\n" % (self.txtout20, self.npt.get()))
self.txtfile.writelines("[%s]\n" % self.txtout21)
line = self.T.get("0.0", END)
self.txtfile.writelines(line)
self.txtfile.close()
msg2 = "End save file\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
#LOAD FILE----------------------------------------------------------
def loadfile(self):
#carga un fichero
self.calload = 1
"""Load an existed file in the GUI."""
wkdir = os.getcwd()
archivo = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a cfg file')
#archivo = tkFileDialog.askopenfilename(parent=self,title='Choose a cfg file')
if archivo != None:
self.txtout.delete("0.0",END)
name = archivo.name
cfgname = os.path.basename(name)
textmsg = ("Leyendo archivo %s\n" % cfgname)
self.txtout.insert("0.0", textmsg)
self.cleangui()
lines = archivo.readlines()
lines = [line.rstrip('\n') for line in lines]
#sec dir 0--------------------------------------------------
val = lines[0].split(" ")
vers = val[1]
print self.currentv, vers
if(self.currentv != vers):
textmsg = ("Atencion, la version de archivo de configuracion no coincide")
msg = showerror(title = "Error", message = textmsg)
msg2 = ("Error en cfg\n")
self.txtout.insert("0.0", msg2)
print msg2
else:
val = lines[1].split(" ")
finaldir = wkdir + val[1]
self.dirin.delete(0,END)
self.dirin.insert(INSERT, finaldir)
val = lines[2].split(" ")
finalout = wkdir + val[1]
self.dirout.delete(0,END)
self.dirout.insert(INSERT, finalout)
#sec modifica dem 3 ----------------------------------------
val = lines[4].split(" ") #new dem
dat = int(val[1])
if(dat == 1):
self.newz.set(1)
self.update_chk()#----------CHECK
val = lines[5].split(" ") #fase
dat2 = int(val[1])
if(dat2 == 1):
self.nfase.set(1)
if(dat2 == 2):
self.nfase.set(2)
self.update_chk()#----------CHECK
val = lines[6].split(" ")#tipo mascara
dat = int(val[1])
self.masktipe.set(dat)
val = lines[7].split(" ")#mascara
finalmask = wkdir + val[1]
self.dirma.delete(0,END)
self.dirma.insert(INSERT, finalmask)
val = lines[8].split(" ")#xyzfile
finalxyz = wkdir + val[1]
self.nwz.delete(0,END)
self.nwz.insert(INSERT, finalxyz)
#val = lines[4].split(" ")
#self.demname.delete(0,END)
#self.demname.insert(INSERT, val[1])
#secdem 9---------------------------------------------------
val = lines[10].split(" ") #dem tipe
dat = int(val[1])
if(dat == 1):
self.demtipe.set(1)
if(dat == 2):
self.demtipe.set(2)
val = lines[11].split(" ") #max val
self.maxval.delete(0,END)
self.maxval.insert(INSERT, val[1])
val = lines[12].split(" ") #min val
self.minval.delete(0,END)
self.minval.insert(INSERT, val[1])
val = lines[13].split(" ") #nul val
self.nullval.delete(0,END)
self.nullval.insert(INSERT, val[1])
#recorte----------------------------
val = lines[14].split(" ") #recorte
dat = int(val[1])
if(dat == 1):
self.recor.set(1)
self.update_chk()#----------CHECK
val = lines[15].split(" ") #xmin
self.xmin.delete(0,END)
self.xmin.insert(INSERT, val[1])
val = lines[16].split(" ") #xmax
self.xmax.delete(0,END)
self.xmax.insert(INSERT, val[1])
val = lines[17].split(" ") #ymin
self.ymin.delete(0,END)
self.ymin.insert(INSERT, val[1])
val = lines[18].split(" ") #ymax
self.ymax.delete(0,END)
self.ymax.insert(INSERT, val[1])
val = lines[19].split(" ") #resx
self.resx.delete(0,END)
self.resx.insert(INSERT, val[1])
val = lines[20].split(" ") #resy
self.resy.delete(0,END)
self.resy.insert(INSERT, val[1])
#procesado 21-----------------------------------------------
val = lines[22].split(" ") #sink
dat = int(val[1])
if dat > 0 and dat < 3:
self.sikvar.set(str(dat))
self.update_chk()#----------CHECK
if dat <= 0 or dat >= 3:
self.sikvar.set('0')
self.update_chk()#----------CHECK
val = lines[23].split(" ") #asp
dat = int(val[1])
if dat > 0 and dat < 3:
self.aspvar.set(str(dat))
self.update_chk()#----------CHECK
if dat <= 0 or dat >= 3:
self.aspvar.set('0')
self.update_chk()#----------CHECK
val = lines[24].split(" ") #slope
dat = int(val[1])
if dat > 0 and dat < 10:
self.slopvar.set(str(dat))
self.update_chk()#----------CHECK
if dat <= 0 or dat >= 10:
self.slopvar.set('0')
self.update_chk()#----------CHECK
#trayec 26--------------------------------------------------
val = lines[26].split(" ") #algoritmos
self.tratip.set(val[1])
alg = int(val[1])
if(alg > 0):
self.update_chk()#----------CHECK
val = lines[27].split(" ") #distmax
self.dismax.delete(0,END)
self.dismax.insert(INSERT, val[1])
val = lines[28].split(" ") #altmax
self.altmax.delete(0,END)
self.altmax.insert(INSERT, val[1])
val = lines[33].split(" ") #mod
self.modval.delete(0,END)
self.mod.set(val[1])
val = lines[34].split(" ") #huso
self.huso.delete(0,END)
self.huso.insert(INSERT, val[1])
val = lines[35].split(" ") #hemis
self.hemisval.delete(0,END)
self.hemis.set(val[1]) #<--------------
#self.hemisval.insert(INSERT, val[1])
val = lines[37].split(" ") #npt
self.npt.delete(0,END)
self.npt.insert(INSERT, val[1])
npt = int(val[1])
if(npt > 0):
j=1;
for i in xrange(39, npt+39): #puntos xy
if(i == 39):
self.T.delete("0.0",'end')
self.T.insert("0.0", lines[i] + '\n')
if(i > 39 and i < npt+39-1):
self.T.insert(str(j)+".0", lines[i] + '\n')
if(i == npt+39-1):
self.T.insert(str(j)+".0", lines[i])
j +=1;
if(npt == 0):
self.npt.delete(0,END)
self.npt.insert(INSERT, "0")
self.update_chk()#----------CHECK
if(alg == 1 or alg == 2):
val = lines[30].split(" ") #incremento
self.incre.delete(0,END)
self.incre.insert(INSERT, val[1])
val = lines[31].split(" ") #force
self.forceval.delete(0,END)
self.force.set(val[1])
self.rad.delete(0,END)
self.rad.insert(INSERT, "0.0")
self.itera.delete(0,END)
self.itera.insert(INSERT, "0.0")
if(alg == 3):
val = lines[30].split(" ") #incremento
self.incre.delete(0,END)
self.incre.insert(INSERT, val[1])
val = lines[31].split(" ") #force
self.forceval.delete(0,END)
self.force.set(val[1])
val = lines[32].split(" ") #itera
self.itera.delete(0,END)
self.itera.insert(INSERT, val[1])
self.rad.delete(0,END)
self.rad.insert(INSERT, "0.0")
#self.incre.delete(0,END)
#self.incre.insert(INSERT, "0.0")
if(alg == 4):
val = lines[29].split(" ") #radbus
self.rad.delete(0,END)
self.rad.insert(INSERT, val[1])
self.incre.delete(0,END)
self.incre.insert(INSERT, "0.0")
self.itera.delete(0,END)
self.itera.insert(INSERT, "0.0")
#----------------------
archivo.close()
msg2 = "End load file\n"
self.txtout.insert("0.0", msg2)
print msg2
#check integrity--------------------------------------------
msg2 = "Checking file\n"
self.txtout.insert("0.0", msg2)
print msg2
valchk = self.checkseq()
if valchk == 0:
textmsg = ("Atencion, se encontraron %s errores en la carga del archivo" % self.totfall)
msg = showerror(title = "Error", message = textmsg)
msg2 = ("%s Errores econtrados\n" % self.totfall)
self.txtout.insert("0.0", msg2)
print msg2
if valchk == 1:
textmsg = "Archivo cargado correctamente\n"
self.txtout.insert("0.0", textmsg)
print msg2
def loadnpt(self):
#carga un fichero
"""Load an xyz file in the GUI."""
wkdir = os.getcwd()
archivo = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a txt file')
if archivo != None:
self.txtout.delete("0.0",END)
name = archivo.name
cfgname = os.path.basename(name)
textmsg = ("Leyendo archivo %s\n" % cfgname)
self.txtout.insert("0.0", textmsg)
#self.cleangui()
self.T.delete("0.0",'end')
lines = archivo.readlines()
lines = [line.rstrip('\n') for line in lines]
nlin = len(lines)
#---
val = lines[0].split()
nval = len(val)
if nval != 2:
textmsg = "Atencion, el archivo debe tener 2 columnas - X Y - separadas por espacios"
msg = showerror(title = "Error", message = textmsg)
msg2 = "Error en estructura del archivo\n"
self.txtout.insert("0.0", msg2)
print msg2
return 1
if nval == 2:
#check si hay cabecera
self.valtx = val[0]
self.ndectype = 1
resp1 = self.is_decimal()
if(resp1 == 0):
print "sin cabecera"
ncab = 0
if(resp1 == 1):
print "Con cabecera, saltamos linea"
val = lines[1].split()
ncab = 1
self.valtx = val[0]
self.ndectype = 1
resp1 = self.is_decimal()
self.valtx = val[1]
self.ndectype = 1
resp2 = self.is_decimal()
#self.valtx = val[2]
#self.ndectype = 1
#resp3 = self.is_entero()
#self.valtx = val[3]
#self.ndectype = 1
#resp4 = self.is_entero()
#if resp1 == 0 and resp2 == 0 and resp3 == 0 and resp4 == 0:
if resp1 == 0 and resp2 == 0:
msg2 = "Estructura correcta, leyendo archivo\n"
self.txtout.insert("0.0", msg2)
print msg2
j=0;
for i in xrange(0, nlin):
if(i == 0):
if(ncab == 0):
self.T.delete("0.0",'end')
self.T.insert("1.0", lines[i] + '\n')
j=2;
if(ncab == 1):
j=1;
if(i > 0):
if(i < nlin-1):
self.T.insert(str(j)+".0", lines[i] + '\n')
if(i == nlin-1):
self.T.insert(str(j)+".0", lines[i])
j +=1;
if ncab == 1:
nlin = nlin - 1
self.npt.delete(0,END)
self.npt.insert( INSERT, str(nlin) )
return 0
else:
textmsg = "Error en estructura, el archivo debe tener 2 columnas - X Y - separadas por espacios\n"
msg = showerror(title = "Error", message = textmsg)
self.txtout.insert("0.0", textmsg)
print msg
return 1
#RUN MODEL----------------------------------------------------------
def runmdt(self):
savefile = self.savedefault()
devuelve = 0
if savefile != 1:
msg = "ATENCION, ocurrio un error, revise los datos e intentelo de nuevo\n"
self.txtout.insert("0.0", msg)
print msg
if savefile == 1:
ejecutac = "./MDTanaliza MDTA_default.cfg"
msg2 = "Inicio simulacion\n"
self.txtout.insert("0.0", msg2)
print msg2
os.system(ejecutac)
devuelve = 1
return 1
if devuelve == 1:
msg2 = "Finalizacion simulacion\n"
self.txtout.insert("0.0", msg2)
print msg2
#LANGUAJE GUI
def lanGUI(self):
#Language
if (self.LAN == 1):
self.txtbu0 = "Opciones"
self.txtbu1 = "Cargar archivo cfg"
self.txtbu2 = "Salvar archivo cfg"
self.txtbu3 = "Ejecutar MDTanaliza"
self.txtbu4 = "Ayuda"
self.txtbu5 = "Salir"
self.txtbu6 = "Change Lang Eng"
self.txtgen1 = "DIRECTORIOS Y FICHEROS DE ENTRADA-SALIDA"
self.txtgen2 = u"MODIFICACIÓN MDT"
self.txtgen3 = u"PARÁMETROS MDT"
self.txtgen4 = u"MORFOMETRÍA"
self.txtgen5 = "TRAYECTORIA DE FLUJOS GRAVITACIONALES"
self.txtgen6 = "PANEL INFORMATIVO"
self.txtlab1 = "Formato MDT"
self.txtlab2 = "Formato Mascara"
self.txtlab3 = "Valor Z Max. del MDT (m)"
self.txtlab4 = "Valor Z Min. del MDT (m)"
self.txtlab5 = "Valor Nulo interno"
self.txtlab6 = "X coordenada Min."
self.txtlab7 = "X coordenada Max."
self.txtlab8 = "Y coordenada Min."
self.txtlab9 = "Y coordenada Max."
self.txtlab10 = u"Resolución en X"
self.txtlab11 = u"Resolución en Y"
self.txtlab12 = u"Distancia máxima (m)"
self.txtlab13 = u"Altura crítica (m)"
self.txtlab14 = "Restric. Multiflow (%)"
self.txtlab15 = "Incremento relleno (m)"
self.txtlab16 = u"Iteraciones totales"
self.txtlab17 = "Punto inicio totales"
self.txtlab18 = "Tipo de algoritmo"
self.txtlab18a = "Unidireccional Min.Top."
self.txtlab18b = "Unidireccional Max.Pen."
self.txtlab18c = "Montecarlo Random"
self.txtlab18d = "Multidireccional Min.Top."
self.txtlab19 = "Hemisferio"
self.txtlab19a = "Hemisferio Norte"
self.txtlab19b = "Hemisferio Sur"
self.txtlab20 = "Modo Esc. Raster"
self.txtlab21 = "Forzar Interacc."
self.txtchk1 = "MDT modifica"
self.txtchk2 = "Fase I"
self.txtchk3 = "Fase II"
self.txtchk4 = "Binario"
self.txtchk5 = "ASCII "
self.txtchk6 = "Binario"
self.txtchk7 = "ASCII "
self.txtchk8 = "Recorte - UTM (m)"
self.txtchk9 = "Superficie sin salida"
self.txtchk9a = u"S.S. Detección"
self.txtchk9b = u"S.S. Modificación"
self.txtchk10 = u"Pendiente-Orientación"
self.txtchk10a = "P-O. Min.Top."
self.txtchk10b = "P-O. Max.Pen."
self.txtchk11 = "Pendiente-Gradiente"
self.txtchk11a = "S-G Burrough and McDonell, 1998" #1
self.txtchk11b = "S-G Fleming and Hoffer, 1979" #2
self.txtchk11c = "S-G Unwin, 1981" #3
self.txtchk11d = "S-G Sharpnack et al, 1969" #4
self.txtchk11e = "S-G Horn, 1981"
self.txtchk11f = "S-G Chu and Tsai, 1995"
self.txtchk11g = "S-G Travis etal 1975, EPPL7, 1987"
self.txtchk11h = "S-G Jones, 1998"
self.txtchk11i = "S-G Wood, 1996"
self.txtbut1 = "Archivo MDT"
self.txtbut2 = "Directorio Salida"
self.txtbut3 = u"Máscara"
self.txtbut4 = "XYZ file"
self.txtout1 = "MDT_IN"
self.txtout2 = "SEC_MDT_MOD"
self.txtout3 = "FASE"
self.txtout4 = "FORMATO_MASCARA"
self.txtout5 = "NOMBRE_MASCARA"
self.txtout6 = "NOMBRE_XYZZ"
self.txtout7 = "SEC_MDT"
self.txtout8 = "FORMATO_MDT"
self.txtout9 = "RECORTE"
self.txtout10 = "MORFOMETRIA"
self.txtout11 = "SIN_SALIDA"
self.txtout12 = "PEND_ORIENT"
self.txtout13 = "PEND_GRAD"
self.txtout14 = "TRAY_FLUJOS"
self.txtout15 = "ALGOR_TIPO"
self.txtout16 = "CRIT_ALTURA"
self.txtout17 = "REST_MULTIFLOW"
self.txtout18 = "INCRE_RELLENO"
self.txtout19 = "INTERACIONES"
self.txtout20 = "PUNTOS_TOTALES"
self.txtout21 = "PUNTOS_DATOS"
self.txtout22 = "ESCRIB_MODO"
self.txtout23 = "FORZAR_INTER"
if (self.LAN == 2):
self.txtbu0 = "Options"
self.txtbu1 = "Load cfg file"
self.txtbu2 = "Save cfg file"
self.txtbu3 = "Run MDTanaliza"
self.txtbu4 = "Help"
self.txtbu5 = "Exit"
self.txtbu6 = "Cambiar idioma Spa"
self.txtgen1 = "INPUT-OUTPUT FILES AND DIRECTORIES"
self.txtgen2 = "DEM MODIFICATION"
self.txtgen3 = "DEM PARAMETERS"
self.txtgen4 = "MORPHOMETRY"
self.txtgen5 = "GRAVITY FLOW PAHTS"
self.txtgen6 = "INFO PANEL"
self.txtlab1 = "DEM Format"
self.txtlab2 = "Mask Format"
self.txtlab3 = "DEM Z Max. Value (m)"
self.txtlab4 = "DEM Z Min. Value (m)"
self.txtlab5 = "Internal Null value"
self.txtlab6 = "X Min. coordenate"
self.txtlab7 = "X Max. coordenate"
self.txtlab8 = "Y Min. coordenate"
self.txtlab9 = "Y Max. coordenate"
self.txtlab10 = "X Resolution"
self.txtlab11 = "Y Resolution"
self.txtlab12 = "Maximum Distance (m)"
self.txtlab13 = "Critical height (m)"
self.txtlab14 = "Restric. Multiflow (%)"
self.txtlab15 = "Fill increase (m)"
self.txtlab16 = "Total Iterations"
self.txtlab17 = "Total init. points"
self.txtlab18 = "Algorithm type"
self.txtlab18a = "Single Path LHM"
self.txtlab18b = "Single Path SSM"
self.txtlab18c = "Montecarlo Random"
self.txtlab18d = "Multiple Path. LHM"
self.txtlab19 = "Hemisphere"
self.txtlab19a = "Northern Hemisphere"
self.txtlab19b = "Southern Hemisphere"
self.txtlab20 = "W. Raster Mode"
self.txtlab21 = "Force Interacc."
self.txtchk1 = "Modified DEM"
self.txtchk2 = "Step I"
self.txtchk3 = "Step II"
self.txtchk4 = "Binary"
self.txtchk5 = "ASCII "
self.txtchk6 = "Binary"
self.txtchk7 = "ASCII "
self.txtchk8 = "Clip - UTM (m)"
self.txtchk9 = "Surface Depression"
self.txtchk9a = "S.D. Detection"
self.txtchk9b = "S.D. Modification"
self.txtchk10 = "Slope-Aspect"
self.txtchk10a = "S-A. LHM"
self.txtchk10b = "S-A. SSM"
self.txtchk11 = "Slope-Gradient"
self.txtchk11a = "S-G Burrough and McDonell, 1998" #1
self.txtchk11b = "S-G Fleming and Hoffer, 1979" #2
self.txtchk11c = "S-G Unwin, 1981" #3
self.txtchk11d = "S-G Sharpnack et al, 1969" #4
self.txtchk11e = "S-G Horn, 1981"
self.txtchk11f = "S-G Chu and Tsai, 1995"
self.txtchk11g = "S-G Travis etal 1975, EPPL7, 1987"
self.txtchk11h = "S-G Jones, 1998"
self.txtchk11i = "S-G Wood, 1996"
self.txtbut1 = "DEM File"
self.txtbut2 = "Output directory"
self.txtbut3 = "Raster Mask"
self.txtbut4 = "XYZ file"
self.txtout1 = "DEM_IN"
self.txtout2 = "SEC_MOD_DEM"
self.txtout3 = "PHASE"
self.txtout4 = "MASK_FORMAT"
self.txtout5 = "MASK_FILENAME"
self.txtout6 = "XYZZ_FILENAME"
self.txtout7 = "SEC_DEM"
self.txtout8 = "DEM_FORMAT"
self.txtout9 = "CLIP"
self.txtout10 = "MORPHOMETRY"
self.txtout11 = "SURF_DEPRESSION"
self.txtout12 = "SLOPE_ASPECT"
self.txtout13 = "SLOPE_GRAD"
self.txtout14 = "FLOW_PATH"
self.txtout15 = "ALGOR_TYPE"
self.txtout16 = "CRIT_HEIGHT"
self.txtout17 = "REST_MULTIFLOW"
self.txtout18 = "FILL_INCRE"
self.txtout19 = "ITERATIONS"
self.txtout20 = "TOTAL_POINTS"
self.txtout21 = "POINT_DATA"
self.txtout22 = "WRITE_MOD"
self.txtout23 = "FORCE_INTER"
#GRAFIC GUI---------------------------------------------------------
def initUI(self):
self.ndectype = 0
self.ntipe = 0
self.parent.title("MDTanaliza v. 2.1-2018-04-06")
self.currentv = '1.2'
self.pack(fill=BOTH, expand=1)
self.lanGUI()
#***************************************************************
#MENU BAR-------------------------------------------------------
self.menubar = Menu(self)
menu = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label=self.txtbu0, menu=menu)
if (self.LAN == 2):menu.add_command(label=self.txtbu6, comman=self.chalangen2sp)
if (self.LAN == 1):menu.add_command(label=self.txtbu6, comman=self.chalangsp2en)
menu.add_command(label=self.txtbu1, comman=self.loadfile)
menu.add_command(label=self.txtbu2, comman=self.savefile)
menu.add_command(label=self.txtbu3, comman=self.runmdt)
menu.add_command(label=self.txtbu4, comman=self.openhelp)
menu.add_command(label=self.txtbu5, command=self.quit)
try:
self.master.config(menu=self.menubar)
except AttributeError:
# master is a toplevel window (Python 1.4/Tkinter 1.63)
self.master.tk.call(master, "config", "-menu", self.menubar)
#***************************************************************
#SECCION DIRECTORIOS directorios--------------------------------
#labels
labdirgen = Label(self, text=self.txtgen1, fg = "red")
labdirgen.grid(row=0, columnspan=4, sticky=W+E)
labnwz = Label(self, text=self.txtgen2, fg = "red")
labnwz.grid(row=3, columnspan=4, sticky=W+E)
#campos
self.dirin = Entry(self)
self.dirin.grid(row=1, column=1, columnspan=2, sticky=W+E)
self.dirout = Entry(self)
self.dirout.grid(row=2, column=1, columnspan=2, sticky=W+E)
#---
self.newz = BooleanVar()
self.newbut = Checkbutton(self, text=self.txtchk1, variable=self.newz, command = self.update_chk)
self.newbut.grid(row=3, column=3)
self.dirma = Entry(self, state=DISABLED)
self.dirma.grid(row=4, column=1, columnspan=2, sticky=W+E)
#botones
self.demButton = Button(self, text=self.txtbut1, command=self.dtmfile, width=20)
self.demButton.grid(row=1)
self.outButton = Button(self, text=self.txtbut2, command=self.direout, width=20)
self.outButton.grid(row=2)
#---
self.maskButton = Button(self, text=self.txtbut3, width=20, state=DISABLED, command=self.maskfile)
self.maskButton.grid(row=4)
self.newButton = Button(self, text=self.txtbut4, command=self.newopenfile, state=DISABLED, width=20)
self.newButton.grid(row=5)
self.nwz = Entry(self, justify=LEFT, width=25, state=DISABLED)
self.nwz.grid(row=5, column=1, columnspan=2, sticky=W+E)
self.nfase = IntVar()
self.fase1 = Radiobutton(self,
text=self.txtchk2,
#padx = 20,
justify=LEFT,
variable=self.nfase,
width=25,
value=1,
state=DISABLED, command = self.update_chk)
self.fase1.grid(row=4, column=3)
self.fase2 = Radiobutton(self,
text=self.txtchk3,
justify=LEFT,
#padx = 20,
variable=self.nfase,
width=25,
value=2,
state=DISABLED, command = self.update_chk)
self.fase2.grid(row=5, column=3)
logo = PhotoImage(file="MDTanaliza_ico.gif",)
labimg = Label(self, image=logo, relief=RIDGE, height=65, width=65)
labimg.logo = logo
labimg.grid(row=0, column=3, rowspan=3)
#***************************************************************
#SECCION DATOS DTM----------------------------------------------
#labels EMPIEZA EN 6 - 24
labdemgen = Label(self, text=self.txtgen3, fg = "red", width=25).grid(row=6, columnspan=2, sticky=W+E)
self.labdtipe = Label(self, justify=LEFT, text=self.txtlab1)
self.labdtipe.grid(row=7)
self.labmasktipe = Label(self, justify=LEFT, text=self.txtlab2)
self.labmasktipe.grid(row=7, column=1)
self.labdmax = Label(self, justify=LEFT, text=self.txtlab3, relief=RIDGE, width=25)
self.labdmax.grid(row=10)
self.labdmin = Label(self, justify=LEFT, text=self.txtlab4, relief=RIDGE, width=25)
self.labdmin.grid(row=11)
self.labdnull = Label(self, justify=LEFT, text=self.txtlab5, relief=RIDGE, width=25)
self.labdnull.grid(row=12)
self.labdxmin = Label(self, justify=LEFT, text=self.txtlab6, relief=RIDGE, width=25)
self.labdxmin.grid(row=14)
self.labdxmax = Label(self, justify=LEFT, text=self.txtlab7, relief=RIDGE, width=25)
self.labdxmax.grid(row=14, column=1)
self.labdymin = Label(self, justify=LEFT, text=self.txtlab8, relief=RIDGE, width=25)
self.labdymin.grid(row=16)
self.labdymax = Label(self, justify=LEFT, text=self.txtlab9, relief=RIDGE, width=25)
self.labdymax.grid(row=16, column=1)
self.labdrex = Label(self, justify=LEFT, text=self.txtlab10, relief=RIDGE, width=25)
self.labdrex.grid(row=18)
self.labdrey = Label(self, justify=LEFT, text=self.txtlab11, relief=RIDGE, width=25)
self.labdrey.grid(row=18, column=1)
#campos
self.demtipe = IntVar()
self.demradb = Radiobutton(self, text=self.txtchk4, justify=LEFT, variable=self.demtipe, command = self.checkdirectories, width=25, value=1)
self.demradb.grid(row=8)
self.demrada = Radiobutton(self, text=self.txtchk5, justify=LEFT, variable=self.demtipe, command = self.checkdirectories, width=25, value=2)
self.demrada.grid(row=9)
self.masktipe = IntVar()
self.maskradb = Radiobutton(self, text=self.txtchk6, justify=LEFT, variable=self.masktipe, command = self.checkdirectories, state=DISABLED, width=25, value=1)
self.maskradb.grid(row=8, column=1)
self.maskrada = Radiobutton(self, text=self.txtchk7, justify=LEFT, variable=self.masktipe, command = self.checkdirectories, state=DISABLED, width=25, value=2)
self.maskrada.grid(row=9, column=1)
self.maxval = Entry(self, justify=RIGHT, width=25)
self.maxval.grid(row=10, column=1)
self.minval = Entry(self, justify=RIGHT, width=25)
self.minval.grid(row=11, column=1)
self.nullval = Entry(self, justify=RIGHT, width=25)
self.nullval.grid(row=12, column=1)
self.nullval.insert(INSERT, "-9999")
self.recor = BooleanVar()
self.recorbut = Checkbutton(self, text=self.txtchk8, variable=self.recor, command = self.update_chk)
self.recorbut.grid(row=13, sticky=W)
self.xmin = Entry(self, justify=RIGHT, width=25, state=DISABLED)
self.xmax = Entry(self, justify=RIGHT, width=25, state=DISABLED)
self.ymin = Entry(self, justify=RIGHT, width=25, state=DISABLED)
self.ymax = Entry(self, justify=RIGHT, width=25, state=DISABLED)
self.resx = Entry(self, justify=RIGHT, width=25, state=DISABLED)
self.resy = Entry(self, justify=RIGHT, width=25, state=DISABLED)
self.xmin.grid(row=15)
self.xmax.grid(row=15, column=1)
self.ymin.grid(row=17)
self.ymax.grid(row=17, column=1)
self.resx.grid(row=19)
self.resy.grid(row=19, column=1)
#***************************************************************
#SECCION OPCIONES PROCESADO DTM---------------------------------
#labels EMPIEZA EN 20
labprogen = Label(self, text=self.txtgen4, fg = "red", width=25).grid(row=20, columnspan=2, sticky=W+E)
#campos
#SINK
self.siklab = Label(self, justify=LEFT, text=self.txtchk9, relief=RIDGE, width=27)
self.siklab.grid(row=21)
self.sikvar = StringVar()
self.sikval = Spinbox(self, from_=0, to=2, textvariable=self.sikvar, command = self.update_chk, state="readonly")
self.sikval.grid(row=21, column=1, sticky=W+E)
#ASPECT
self.asplab = Label(self, justify=LEFT, text=self.txtchk10, relief=RIDGE, width=27)
self.asplab.grid(row=22)
self.aspvar = StringVar()
self.aspval = Spinbox(self, from_=0, to=2, textvariable=self.aspvar, command = self.update_chk, state="readonly")
self.aspval.grid(row=22, column=1, sticky=W+E)
#SLOPE
self.sloplab = Label(self, justify=LEFT, text=self.txtchk11, relief=RIDGE, width=27)
self.sloplab.grid(row=23)
self.slopvar = StringVar()
self.slopval = Spinbox(self, from_=0, to=9, textvariable=self.slopvar, command = self.update_chk, state="readonly")
self.slopval.grid(row=23, column=1, sticky=W+E)
#***************************************************************
#SECCION TRAYECTORIAS-------------------------------------------
#labels EMPIEZA EN 6
self.labdminlabtragen = Label(self, text=self.txtgen5, fg = "red", width=25)
self.labdminlabtragen.grid(row=6, column=2, columnspan=2, sticky=W+E)
self.labalgtyp = Label(self,text=self.txtlab18, background='yellow', foreground="blue", relief=RIDGE, width=25)
self.labalgtyp.grid(row=7, column=2)
self.labdminlabdmax = Label(self, justify=LEFT, text=self.txtlab12, relief=RIDGE, width=25)
self.labdminlabdmax.grid(row=8,column=2)
self.labdminlabalt = Label(self, justify=LEFT, text=self.txtlab13, relief=RIDGE, width=25)
self.labdminlabalt.grid(row=9,column=2)
self.labdminlabrad = Label(self, justify=LEFT, text=self.txtlab14, relief=RIDGE, width=25)
self.labdminlabrad.grid(row=10,column=2)
self.labdminlabinc = Label(self, justify=LEFT, text=self.txtlab15, relief=RIDGE, width=25)
self.labdminlabinc.grid(row=11,column=2)
self.labdminlabfor = Label(self, justify=LEFT, text=self.txtlab21, relief=RIDGE, width=25) #<---------------
self.labdminlabfor.grid(row=12,column=2)
self.labdminlabite = Label(self, justify=LEFT, text=self.txtlab16, relief=RIDGE, width=25)
self.labdminlabite.grid(row=13,column=2)
self.labdminlabmod = Label(self, justify=LEFT, text=self.txtlab20, relief=RIDGE, width=25) #<---------------
self.labdminlabmod.grid(row=14,column=2)
self.labdminlabnpt = Label(self, justify=LEFT, text=self.txtlab17, relief=RIDGE, width=25)
self.labdminlabnpt.grid(row=15,column=2)
#campos
self.tratip = StringVar()
self.trayval = Spinbox(self, from_=0, to=4, textvariable=self.tratip, width=20, command = self.update_chk, state="readonly")
self.dismax = Entry(self, justify=RIGHT, width=20, state=DISABLED)
self.altmax = Entry(self, justify=RIGHT, width=20, state=DISABLED)
self.rad = Entry(self, justify=RIGHT, width=20, state=DISABLED)
self.incre = Entry(self, justify=RIGHT, width=20, state=DISABLED)
#self.force = Entry(self, justify=RIGHT, width=20, state=DISABLED) #<---------------
self.force = StringVar()
self.forceval = Spinbox(self, from_=0, to=1, textvariable=self.force, width=20, command = self.update_chk, state=DISABLED)
self.itera = Entry(self, justify=RIGHT, width=20, state=DISABLED)
#self.mod = Entry(self, justify=RIGHT, width=20, state=DISABLED) #<---------------
self.mod = StringVar()
self.modval = Spinbox(self, from_=0, to=1, textvariable=self.mod, width=20, command = self.update_chk, state=DISABLED)
self.npt = Entry(self, justify=RIGHT, width=20)
self.npt.delete(0,END)
self.npt.insert( INSERT, "0" )
self.trayval.grid(row=7,column=3)
self.dismax.grid(row=8, column=3)
self.altmax.grid(row=9, column=3)
self.rad.grid(row=10, column=3)
self.incre.grid(row=11, column=3)
self.forceval.grid(row=12, column=3) #<---------------
self.itera.grid(row=13, column=3)
self.modval.grid(row=14, column=3) #<---------------
self.npt.grid(row=15, column=3) #de 13 a 14
#LOAD XY VENTS
self.S = Scrollbar(self)
self.T = Text(self, height=4, width=27, state=DISABLED)
self.S.grid(row=15, column=3, rowspan=5, sticky=N+S+E)
#self.T.grid(row=14, column=3, rowspan=5, columnspan=1, pady=3, sticky=W)
self.T.grid(row=15, column=3, rowspan=5)
self.S.config(command=self.T.yview)
self.T.config(yscrollcommand=self.S.set)
self.loadnpt = Button(self, text="Load xy file", width=20, comman=self.loadnpt, state=DISABLED)
self.loadnpt.grid(row=16, column=2,)
#--
self.labhuso = Label(self, justify=LEFT, text="UTM ZONE", relief=RIDGE, width=20)
self.labhuso.grid(row=20,column=3)
self.huso = Entry(self, justify=RIGHT, width=20, state=DISABLED)
self.huso.grid(row=21, column=3,)
self.labhemis = Label(self, justify=LEFT, text=self.txtlab19, relief=RIDGE, width=20)
self.labhemis.grid(row=22,column=3)
#self.hemis = Entry(self, justify=RIGHT, width=20, state=DISABLED)
#self.hemis.grid(row=23, column=3,)
self.hemis = StringVar()
self.hemisval = Spinbox(self, from_=0, to=1, textvariable=self.hemis, width=20, command = self.update_chk, state=DISABLED)
self.hemisval.grid(row=23, column=3,)
#Salida de mensajes---------------------------------------------
self.labpanel = Label(self, text=self.txtgen6, fg = "red", width=25)
self.labpanel.grid(row=17,column=2)
self.scr = Scrollbar(self)
self.txtout = Text(self, height=8, width=26)
self.scr.grid(row=18, column=2, rowspan=6, sticky=N+S+E)
self.txtout.grid(row=18, column=2, rowspan=6, sticky=W)
self.scr.config(command=self.txtout.yview)
self.txtout.config(yscrollcommand=self.scr.set)
def main():
root = Tk()
root.geometry("920x550+300+300")
#root.state('zoomed')
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
|
81ac2f9c4c26d2305517baa4a160a6ec5157543b | PatrickNyrud/projects | /other/test.py | 870 | 3.53125 | 4 | import lyricwikia
import re
from PyDictionary import PyDictionary
import enchant
dictionary=PyDictionary()
# name = "Barack (of Washington)"
# name = re.sub('[\(\)\{\}<>]', '', name)
# print(name)
artist = "Lil pump"
song = "Gucci gang"
def run():
lyrics = lyricwikia.get_lyrics(artist, song)
d = enchant.Dict("en_US")
word_list = []
for x in lyrics.split():
word = x
word = re.sub("""[\(\)\{\}<>?,":.!'-]""", '', word)
if word.lower() not in word_list:
try:
check_if_word = d.check(word.lower())
except Exception as e:
pass
if check_if_word:
word_list.append(word.lower())
else:
pass
else:
pass
i = 0
for x in word_list:
try:
print x
except:
pass
i += 1
print "\n" + artist + ", " + song
print str(i) + " ord!"
run()
# d = enchant.Dict("en_US")
# print d.check("hello")
#(dictionary.meaning(word.lower())) |
6ed1b150d53e200047c99a0103894feaca812702 | gb08/30-Day-LeetCoding-Challenge | /binary_tree_diameter.py | 1,158 | 4.25 | 4 | """
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def depth(root):
nonlocal maxDiameter
if not root:
return 0
left = depth(root.left)
right = depth(root.right)
#get the no of edges in both children
currentDiameter = left + right
#track max diameter
maxDiameter = max(maxDiameter, currentDiameter)
#we can only return one of the children
#we add a one to represent the edge
#between node and parent above
return max(left, right) + 1
maxDiameter = 0
depth(root)
return maxDiameter
|
91b969c1eeff25b086293bc8217938794567808a | InduPriya-pokuri/Python_Advance_Topics | /Python Advanced Workshop/files/list_comprehension.py | 449 | 3.96875 | 4 | '''n=int(input("Enter range:"))
li=[]
for i in range(1,n+1):
num=int(input("Enter number:"))
li.append(num)
print(li)
print("minimum elemnent ", min(li))
print("max element :", max(li))
s=0
for ele in li:
s+=ele
print("sum value is ",s)
print("sum of the list ",sum(li))
if li.sort()!=None:
li=li.sort()
print("sorted list :",li)
if li.reverse()!=None:
li=li.reverse()
print("Reversed list :",li) '''
|
e6b52b09c2bebe8304b27f5f2c9f077ba14e8039 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2333/60602/261884.py | 1,250 | 3.71875 | 4 | def quickSort(list):
if(len(list)>1):
count=1;
x=list[0];
leftList=[];
rightList=[];
while(count<len(list)):
if(int(list[count])>=int(x)):
rightList.append(list[count]);
else:
leftList.append(list[count]);
count+=1;
leftList.append(x);
return quickSort(leftList)+quickSort(rightList);
else:
return list;
def boundList(x,y,bound):
temp=0;
ans=[];
while(temp<=bound):
i=0;
j=0;
while(x**i+y**j<=temp):
if(x**i+y**j==temp):
if(ans==[]):
ans.append(temp)
elif(temp!=ans[len(ans)-1]):
ans.append(temp);
else:
while(x**i+y**j<=temp):
if (x ** i + y ** j == temp):
if (ans == []):
ans.append(temp)
elif (temp != ans[len(ans) - 1]):
ans.append(temp);
j+=1;
j=0;
i+=1;
temp+=1;
ans=quickSort(ans);
print(ans);
x=int(input());
y=int(input());
bound=int(input());
boundList(x,y,bound); |
f4fd2c67348e172ae83a40e0c8ced65e0deec606 | LokiGadd/Python | /26.py | 2,204 | 4.09375 | 4 | # Problem 26
'''
My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest.
I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits.
For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?
Example:
"56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99"
When two numbers have the same "weight", let us class them as if they were strings (alphabetical ordering) and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9), it comes before as a string.
All numbers in the list are positive numbers and the list can be empty.
'''
def order_weight(strng):
if strng == "":
return strng
number = list(map(int, strng.split(" ")))
l = len(number)
num = [0]*l
dig = 0
n=0
i=0
for i in range(l):
num[i] = number[i]
tot=0
n=num[i]
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
num[i] = tot
i=l-1
j=0
temp=0
while i>=1:
j=i-1
while j>=0:
if (num[j]>num[i]):
temp = num[j]
num[j] = num[i]
num[i] = temp
temp = number[j]
number[j] = number[i]
number[i] = temp
elif (num[j] == num[i] and str(number[j]) > str(number[i])):
temp = number[j]
number[j] = number[i]
number[i] = temp
j -= 1
i -= 1
for i in range(l):
number[i] = str(number[i])
return " ".join(number)
print(order_weight("56 65 74 100 99 68 86 180 90"))
# Done |
d695275eeaab7e4e737567704ed466460a357eb3 | zcl0405/vip10test | /面向对象/1.py | 1,914 | 3.96875 | 4 | # class washer():#定义类
# def wash(self):
# print('我会洗衣服')
# haier1=washer()#创建对象
# print(haier1)
# haier1.wash()#haier对象调用实例方法,创建对象的过程也叫实例化对象
# class washer():
# def print_info(self):
#类的里面获取实例属性
# print(f'haire1洗衣机的宽度是{self.width}')
# haier1 = washer()#创建对象
# haier1.width = 500#添加实例属性
# haier2=washer()
# haier2.width=600
#
#
# haier1.print_info()
# haier2.print_info()
# class washer():
# def __init__(self):#魔法方法初始化方法
# self.width=500
# self.height=800
# def print_info(self):
# print(f'洗衣机的宽度是{self.width}')
# print(f'洗衣机的高度是{self.height}')
# haier1=washer()
# haier1.print_info()
class Washer():
def __init__(self,width,height):
self.width=width
self.height=height
def print_info(self):
print(f'洗衣机的宽度是{self.width}')
print(f'洗衣机的高度是{self.height}')
haier1=Washer(10,20)
haier1.print_info()
#
# haier2=Washer(30,40)
# haier2.print_info()
'''
定义一个老师类,
老师的属性有:姓名.性别,教的课程
方法:可以教学
'''
# class Teacher():
# def tea_math(self):
# teacher1.
# class Furniture():
# def __init__(self,name,area):
# self.name=name
# self.area=area
# class Home():
# def __init__(self,address,area):
# self.address=address
# self.area=area
# self.free_area=area
# self.furniture=[]
# def __str__(self):
# return f'房子坐落于{self.address},占地面积{self.area},剩余面积{self.free_area},家具有{self.furniture}'
# def add_furniture(self,item):
# if self.free_area>=item.area:
# self.furniture.append(item.name)
# self.free_area=self.free_area-
|
ceb203c13a3fe912077532290b4a8c27c1707855 | Oceavos/PythonCourses | /Korean_ver/2_Datatypes/Step_9_Dictionary_functions.py | 1,060 | 3.53125 | 4 | 이번에는 딕셔너리 자료형에서 사용하는 함수들에 대해 알아보자.
- 딕셔너리의 Key만 모아서 리스트로 리턴 (keys)
>>> dic = {'name' : 'SeongJin-Hong', 'gender' : 'male'}
>>> dic.keys()
dict_keys(['name', 'gender']) # dict_keys 란 이름의 객체를 리턴해줌
- 딕셔너리의 Value만 모아서 리스트로 리턴 (values)
>>> dic = {'name' : 'SeongJin-Hong', 'gender' : 'male'}
>>> dic.values()
dict_values(['SeongJin-Hong', 'male']) # dict_values 란 이름의 객체를 리턴
- Key를 이용한 Value값 얻기 (get)
>>> dic = {'name' : 'SeongJin-Hong', 'gender' : 'male'}
>>> dic.get('name')
'SeongJin-Hong'
>>> dic.get('gender')
'male'
- 딕셔너리 초기화 (clear)
>>> dic = {'name' : 'SeongJin-Hong', 'gender' : 'male'}
>>> dic.clear() # 딕셔너리 값 초기화
{}
- Key, Value 쌍 얻기 (items)
>>> dic = {'name' : 'SeongJin-Hong', 'gender' : 'male'}
>>> dic.items()
dict_items([('name', 'SeongJin-Hong'), ('getnder', 'male')]) # dict_items 라는 객체로 리턴함
|
583d2d49508b5cd2cd18f6e791e3e6f13fb0a434 | osmaoguzhan/topSort | /topSort.py | 1,157 | 3.6875 | 4 | #Code has been taken from Geeksforgeeks and updated
from collections import defaultdict
import time
class myGraph:
def __init__(self,verts):
self.graph = defaultdict(list)
self.V = verts
def edge(self,u,v): # adding an edge
self.graph[u].append(v)
def topSortSub(self,v,visited,queue):
visited[v] = True #set v's index as visited
for i in self.graph[v]: # Recursion for all the v's adjacent to this vertex
if visited[i] == False:
self.topSortSub(i,visited,queue)
time.sleep(2)
#Pushing current vertex to queue
queue.insert(0,v)
print("\rCurrent Queue: " + str(queue), end='')
def topsort(self):
visited = [False]*self.V #setting all visited nodes False
queue =[]
for i in range(self.V):
if visited[i] == False:#if the node isn't visited yet
self.topSortSub(i,visited,queue) #run topSortSub func.
print("\rResult: "+str(queue))
graph = myGraph(5)
graph.edge(0, 1);
graph.edge(0, 4);
graph.edge(1, 2);
graph.edge(3, 1);
graph.edge(3, 2);
graph.edge(4, 1);
graph.edge(4, 3);
print("-------------------------")
print("Sorted")
print("-------------------------")
graph.topsort()
|
10f91a0fd19d2eddb344b5a7028683a2dfe0b42c | maubarrerag/python-exercises | /advanced-python-concepts/Demos/sorting_sort_method.py | 973 | 4.5625 | 5 | # Simple sort() method:
colors = ['red', 'blue', 'green', 'orange']
colors.sort()
print('Colors sorted', colors, '-'*70, sep='\n')
# The reverse argument:
colors.sort(reverse=True)
print('Colors sorted in reverse order', colors, '-'*70, sep='\n')
# The key argument:
colors.sort(key=len)
print('Colors sorted by length', colors, '-'*70, sep='\n')
# The key argument with named function:
def get_lastname(name):
return name.split()[-1]
people = ['George Washington', 'John Adams', 'Thomas Jefferson',
'John Quincy Adams']
people.sort(key=get_lastname)
print('People sorted by last name using named function',
people, '-'*70, sep='\n')
# The key argument with lambda function
people = ['George Washington', 'John Adams', 'Thomas Jefferson',
'John Quincy Adams']
people.sort(key=lambda name: name.split()[-1])
print('People sorted by last name using lambda function',
people, '-'*70, sep='\n')
# Combining key and reverse
colors.sort(key=len, reverse=True)
print('Colors sorted by length and reversed',
colors, '-'*70, sep='\n') |
1c4b1c09a147479aff3412ba352579e88d8c1bda | erickapsilva1/desafios-python3-cev | /Desafios/066.py | 373 | 3.828125 | 4 | # programa que leia vários n. inteiros, só vai parar com 999
# ao final, tem que mostrar a soma desconsiderando a flag
n = int(input('Digite um número: '))
cont = 0
soma = 0
while n != 999:
cont += 1
n = int(input('Digite um número: '))
if n == 999:
break
soma += n
print('Saindo...')
print('A soma dos {} valores foi {}: '.format(cont, soma)) |
829d335cfa700d8900ddacee56b0b84e4d1ce94b | gsk120/ibk_python_progrmming | /mycode/3_string/yesterday_count.py | 658 | 3.9375 | 4 | """
yesterday.txt 파일을 읽어서
yesterday 단어가 몇번 나오는지을 count 해보기
open mode
r : read, w: write
rb : read binary, wb: write binary
a : append
"""
def file_read(file_name):
with open(file_name, "r", encoding='utf-8') as file:
lyric = file.read()
return lyric
read = file_read("yesterday.txt")
print(read)
n_of_YESTERDAY = read.upper().count("YESTERDAY")
print(f'Number of a word YESTERDAY {n_of_YESTERDAY}')
n_of_Yesterday = read.count('Yesterday')
print(f'Number of a word Yesterday {n_of_Yesterday}')
n_of_yesterday = read.lower().count('yesterday')
print(f'Number of a word yesterday {n_of_yesterday}')
|
0cfa47b60866d55a896ebb31b34882a141d17f61 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mjlkhw001/question4.py | 2,263 | 4.09375 | 4 | # Palindromic Primes
# Khwezi Majola
# MJLKHW001
# 04 May 2014
import question1 #Import for use of palindrome checker
import math #Import for limiting the checking of prime numbers
import sys #Import to increase recursion limit
sys.setrecursionlimit (30000) #Increase recursion limit
def palin_primes(n, m):
global i #Makes i a global variable
i = 2 #Resets i to 2
count = 0 #Counter of factors
if n == m: #End case for recursion
if prime(n, i, count) == 0: #Checks if the factor count is 0
if question1.palin(str(n)): #Checks if it is a palindrome
if n != 1 and n != 0: #Excludes 0 and 1 from printing
print(n) #Prints
return #End the recursion
return #Above
return #Above
else:
if prime(n, i, count) == 0: #Same as above
if question1.palin(str(n)): #Same as above
if n != 1 and n != 0: #Same as above
print(n) #Same as above
return palin_primes(n+1, m) #Recursion occurs using n + 1
else: return palin_primes(n+1, m) #Above
else: return palin_primes(n+1, m) #Above
def prime(j, i, count): #Checks if a number is prime. Takes in "j" - the number to check, "i" - the factor & "count" - the number of factor which produce whole number
if i <= math.ceil(j/2): #Stops the loop if "i" exceeds halfway of "j"
if j%i == 0: #Checks if "i" is a factor
count += 1 #Increases thus increase the factors
i += 1 #Increases thus getting a new factor
return prime(j, i, count) #Recursion occurs using the changed "count", "i"
else:
i += 1 #Same as above
return prime(j, i, count) #Recursion occurs using the changed "i"
else:
return count #Returns count. Count is zero when prime as 1 isn't included in division nor is "j"/the number being checked
def main(): #Input output function
n = eval(input('Enter the starting point N:\n'))
m = eval(input('Enter the ending point M:\n'))
if n != '' and m != '': #Ensures actual values are inputted
print('The palindromic primes are:')
palin_primes(n, m)
main() |
a1dc16f3dbaa17143808c998fc3690ff159fcee8 | rodcoelho/flask-chatbot | /createdb.py | 387 | 3.75 | 4 | import sqlite3
connection = sqlite3.connect('db/entries.db')
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE users(
pk INTEGER,
name VARCHAR(32),
PRIMARY KEY(pk))
;""")
cursor.execute("""
CREATE TABLE tweets(
pk INTEGER,
userID INTEGER,
tweet VARCHAR,
response VARCHAR,
FOREIGN KEY(userID) REFERENCES users(pk),
PRIMARY KEY(pk))
;""")
connection.commit()
cursor.close()
|
52bed69c128d6d6e9348ea29abdfbed8521255f2 | nagireddy96666/Interview_-python | /practice/prepare/dict/dictswaap.py | 165 | 4.03125 | 4 | def swap(d):
k = d.keys()
v = d.values()
z = zip(v,k)
print dict(z)
z1 = zip(k,v)
print dict(z1)
d = input("enter the dict values:")
swap(d)
|
f126a0c0d3bce18bb99ae77ba4d0223fb6d82372 | adiraj47/Python_Udemy | /List_Range_Tuple_Section_5/more_tuples.py | 154 | 4 | 4 | even = [2, 4, 6, 8, 10]
odd = [1, 3, 5, 7, 9]
numbers = [even , odd]
print(numbers)
for i in numbers:
print(i)
for j in i:
print(j) |
35d965366fa0333abbe2f0ec526b76006413e5ab | kantegory/studying | /Multimedia-Tech/03. jpeg-python/huffman.py | 1,591 | 3.8125 | 4 | import heapq
from collections import Counter, namedtuple
class Node(namedtuple("Node", ["left", "right"])):
def walk(self, code, acc):
self.left.walk(code, acc + "0")
self.right.walk(code, acc + "1")
class Leaf(namedtuple("Leaf", ["char"])):
def walk(self, code, acc):
code[self.char] = acc or "0"
def huffman_encode(string):
queue = []
for char, freq in Counter(string).items():
queue.append((freq, len(queue), Leaf(char)))
heapq.heapify(queue)
count = len(queue)
while len(queue) > 1:
freq1, _count1, left = heapq.heappop(queue)
freq2, _count2, right = heapq.heappop(queue)
heapq.heappush(queue, (freq1 + freq2, count, Node(left, right)))
count += 1
code = {}
if queue:
[(_freq, count, root)] = queue
root.walk(code, "")
return code
def huffman_decode(string, code):
chars_list = [char for char in string]
decoded_string = ""
while chars_list:
if chars_list[0] in code.values():
for l, cod in code.items():
if cod == chars_list[0]: decoded_string += l
del chars_list[0]
else:
chars_list[0] = (chars_list[0]) + (chars_list[1])
del chars_list[1]
return decoded_string
def main():
string = input()
code = huffman_encode(string)
encoded = "".join(code[char] for char in string)
print(len(code), len(encoded))
for char in sorted(code):
print("{}: {}".format(char, code[char]))
print(encoded)
if __name__ == "__main__":
main()
|
075c3abd77cead11df004ca7b5e73967f9352a83 | sotojcr/100DaysOfCode | /PythonLearningStep1/05function.py | 1,002 | 3.953125 | 4 | #function
# def helloFun():
# # print('Hello Function!')
# # print('Hi')
# return 'Hello Funciton'
# def fun2(greeting, name ='You'):
# return '{}, {}'.format(greeting, name)
# print(helloFun())
# print(fun2('Hi'))
#allowing us to accept an arbitary number of positional keyword arguments # def fun3(*args, **kwargs):
# print(args) #tuple
# print(kwargs) #dictionary
# # fun3('Math', 'art', name='John', age = 22)
# courses = ['math','art']
# info = {'name':'Pk', 'age':22}
# # fun3(courses, info)
# fun3(*courses, **info) #unpack the tuple and dict
monthDays = [0,31,28,31,30,31,30,31,31,30,31,30,31]
def isLeap(year):
"""Return true for leap years,
flase for non leap years"""
return year % 4 ==0 and(year%100 !=0 or year % 400 ==0)
def daysInMonth(year, month):
"""return number of days in a month"""
if not 1 <=month <=12:
return 'invalid month'
if month ==2 and isLeap(year):
return 29
return monthDays[month]
# print(isLeap(2020))
print(daysInMonth(2016,2)) |
a69ac4a9cab9db8ced8f9a84ca9be7d454e7c590 | haley-harris/csc221 | /hw5/part3/password.py | 722 | 3.9375 | 4 | import re
def get_user_password():
password = input('Type a password: ')
return password
def test_password_strength():
password = get_user_password()
# matches at least one lowercase letter, uppercase letter, digit, and special char
password_regex = re.compile(r'(?=^.{8,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W])[0-9a-zA-Z\W]*$')
if password_regex.fullmatch(password):
print('strong password')
else:
print('''
password must be a minimum of 8 characters and must
contain at least one lowercase letter, uppercase letter,
digit, and special character.
''')
password = test_password_strength()
test_password_strength()
|
e52a0417b800f71bb95e8b870778ac1d9fb90ffd | copperstick6/Python-Projects | /Python-Projects/messingWithFunctions.py | 593 | 3.84375 | 4 | def function1():
print("I like turtles")
function1()
#print statement tries to print the return, but there is none, so it prints
#none
print function1()
#not invoking the function with the parenthesis prints the
#memory location of the object, as all functions are stored
#as an object wihin python
print function1
#functions can be stored as variables
x = function1
x()
#note that + in java is the same as , in python.
def function2(x,y):
print x, " ", y
function2(3,4)
print function2(3,4)
#return functions
def cubed(x):
return x*x*x
print cubed(3)
a = cubed(3)
print(a)
|
8e94057e6cb452cfb8117eb5c7146c70546324a7 | madeibao/PythonAlgorithm | /PartB/py是否由重复的子字符串构成.py | 696 | 4.15625 | 4 |
给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。
示例 1:
输入: "abab"
输出: True
解释: 可由子字符串 "ab" 重复两次构成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/repeated-substring-pattern
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return s in (s+s)[1:-1]
if __name__ == "__main__":
s = Solution()
str2 ="abcabc"
print(s.repeatedSubstringPattern(str2))
|
aacbe90159a43d06fa50edd42d3c1dc50f6ded95 | Isthares/Small-Python-Projects | /Conversion-Calculator/screen.py | 8,407 | 4.0625 | 4 | # File Name: screen.py
# Author: Esther Heralta Espinosa
# Date: 02/20/19
# Description of the program: Conversion Calculator
# This class contains functions that are related to displaying something on the screen
# or asking the user to enter some kind of data
# ---------------------------------- Libraries ----------------------------------
import validate #module
# -------------------------------------------------------------------------------
class Screen():
""" displaying something on the screen or gathering data from the user """
# -------------------------------- Main Menu Functions ---------------------------------
#display the main menu on the screen
def mainMenu(self):
""" Display main menu on the screen """
print("\n")
print(" ----------- CONVERSION CALCULATOR MENU ----------- \n")
print(" 1. Temperature ")
print(" 2. Weight ")
print(" 3. Time ")
print(" 4. Exit ")
#print("\n")
print(" -------------------------------------------------- ")
def getMenuOption(self):
""" prompt the user to choose an option of the main menu """
print("\n")
option = int(input(" Enter an option: "))
#print(option, type(option))
return (option)
def displayInvalidOptionMessage(self):
""" display a message telling the user that the option entered is not valid """
print("\n")
print(" Invalid choice. Please, choose a valid one.")
def getValidMainMenuOption(self, optionChosen):
vd = validate.ValidateData()
""" prompts the user for an option and checks whether is valid or not """
while (vd.isValidMainMenuOption(optionChosen) == False):
self.displayInvalidOptionMessage()
self.mainMenu() #display the main menu on the screen
optionChosen = self.getMenuOption()
# --------------------------------------------------------------------------------------
# ------------------------------------ Exit Option -------------------------------------
def exitMessage(self):
""" display exit message """
print("\n")
print(" You have exit the Conversion Calculator.\n")
# --------------------------------------------------------------------------------------
# -------------------------------- Temperature Options ----------------------------------
def temperatureMenu(self):
""" Display temperatura menu on the screen """
print("\n")
print(" ---------------- TEMPERATURE MENU --------------- \n")
print(" 1. Convert Celsius to Fahrenheit ")
print(" 2. Convert Celsius to Kelvin ")
print(" 3. Convert Fahrenheit to Celsius ")
print(" 4. Convert Fahrenheit to Kelvin ")
print(" 5. Convert Kelvin to Celsius ")
print(" 6. Convert Kelvin to Fahrenheit ")
print(" 7. Exit ")
#print("\n")
print(" -------------------------------------------------- ")
def getValidTemperatureMenuOption(self, optionChosen):
""" prompts the user for an option and checks whether is valid or not """
vd = validate.ValidateData()
while (vd.isValidSubMenuOption(optionChosen) == False):
self.displayInvalidOptionMessage()
self.temperatureMenu() #display the temperature menu on the screen
optionChosen = self.getMenuOption()
def getValueToConvert(self):
""" prompt the user to enter the value that is going to be converted """
#print("\n")
option = float(input(" Enter the value to convert: "))
return (option)
def displayTemperatureConversionMessage(self, optionChosen, dataToConvert, dataConverted):
""" display a message telling the user the result of the conversion chosen """
print("\n")
if (optionChosen == 1):
print(" {0} C = {1:.2f} F ".format(dataToConvert, dataConverted))
elif (optionChosen == 2):
print(" {0} C = {1:.2f} K ".format(dataToConvert, dataConverted))
elif (optionChosen == 3):
print(" {0} F = {1:.2f} C ".format(dataToConvert, dataConverted))
elif (optionChosen == 4):
print(" {0} F = {1:.2f} K ".format(dataToConvert, dataConverted))
elif (optionChosen == 5):
print(" {0} K = {1:.2f} C ".format(dataToConvert, dataConverted))
elif (optionChosen == 6):
print(" {0} K = {1:.2f} F ".format(dataToConvert, dataConverted))
# --------------------------------------------------------------------------------------
# ---------------------------------- Weight Options ------------------------------------
def weightMenu(self):
""" Display weight menu on the screen """
print("\n")
print(" ------------------- WEIGHT MENU ----------------- \n")
print(" 1. Convert Gram to Ounce ")
print(" 2. Convert Gram to Pound ")
print(" 3. Convert Ounce to Gram ")
print(" 4. Convert Ounce to Pound ")
print(" 5. Convert Pound to Gram ")
print(" 6. Convert Pound to Ounce ")
print(" 7. Exit ")
#print("\n")
print(" -------------------------------------------------- ")
def getValidWeightMenuOption(self, optionChosen):
""" prompts the user for an option and checks whether is valid or not """
vd = validate.ValidateData()
while (vd.isValidSubMenuOption(optionChosen) == False):
self.displayInvalidOptionMessage()
self.weightMenu() #display the weight menu on the screen
optionChosen = self.getMenuOption()
def displayWeightConversionMessage(self, optionChosen, dataToConvert, dataConverted):
""" display a message telling the user the result of the conversion chosen """
print("\n")
if (optionChosen == 1):
print(" {0} grams = {1:.3f} ounces ".format(dataToConvert, dataConverted))
elif (optionChosen == 2):
print(" {0} grams = {1:.3f} pounds ".format(dataToConvert, dataConverted))
elif (optionChosen == 3):
print(" {0} ounces = {1:.3f} grams ".format(dataToConvert, dataConverted))
elif (optionChosen == 4):
print(" {0} ounces = {1:.3f} pounds ".format(dataToConvert, dataConverted))
elif (optionChosen == 5):
print(" {0} pounds = {1:.3f} grams ".format(dataToConvert, dataConverted))
elif (optionChosen == 6):
print(" {0} pounds = {1:.3f} ounces ".format(dataToConvert, dataConverted))
# --------------------------------------------------------------------------------------
# ----------------------------------- Time Options -------------------------------------
def timeMenu(self):
""" Display time menu on the screen """
print("\n")
print(" -------------------- TIME MENU ------------------- \n")
print(" 1. Convert hours to minutes ")
print(" 2. Convert hours to seconds ")
print(" 3. Convert minutes to hours ")
print(" 4. Convert minutes to seconds ")
print(" 5. Convert seconds to hours ")
print(" 6. Convert seconds to minutes ")
print(" 7. Convert days to hours ")
print(" 8. Convert days to minutes ")
print(" 9. Convert days to seconds ")
print(" 0. Exit ")
#print("\n")
print(" -------------------------------------------------- ")
def getValidTimeMenuOption(self, optionChosen):
""" prompts the user for an option and checks whether is valid or not """
vd = validate.ValidateData()
while (vd.isValidTimeMenuOption(optionChosen) == False):
self.displayInvalidOptionMessage()
self.timeMenu() #display the time menu on the screen
optionChosen = self.getMenuOption()
def displayTimeConversionMessage(self, optionChosen, dataToConvert, dataConverted):
""" display a message telling the user the result of the conversion chosen """
print("\n")
if (optionChosen == 1):
print(" {0} hours = {1:.3f} minutes ".format(dataToConvert, dataConverted))
elif (optionChosen == 2):
print(" {0} hours = {1:.3f} seconds ".format(dataToConvert, dataConverted))
elif (optionChosen == 3):
print(" {0} minutes = {1:.3f} hours ".format(dataToConvert, dataConverted))
elif (optionChosen == 4):
print(" {0} minutes = {1:.3f} seconds ".format(dataToConvert, dataConverted))
elif (optionChosen == 5):
print(" {0} seconds = {1:.5f} hours ".format(dataToConvert, dataConverted))
elif (optionChosen == 6):
print(" {0} seconds = {1:.5f} minutes ".format(dataToConvert, dataConverted))
elif (optionChosen == 7):
print(" {0} days = {1:.3f} hours ".format(dataToConvert, dataConverted))
elif (optionChosen == 8):
print(" {0} days = {1:.3f} minutes ".format(dataToConvert, dataConverted))
elif (optionChosen == 9):
print(" {0} days = {1:.3f} seconds ".format(dataToConvert, dataConverted))
# --------------------------------------------------------------------------------------
|
7827351c66f94086305a2fd91812d320bfdca6e5 | abhi55555/dsPrograms | /Dynamic Programming/ugly_numbers.py | 364 | 3.921875 | 4 | # program to find ugly numbers(numbers with only prime factors 2,3,5) upto n.
def reduce(num, x):
while(num % x == 0):
num = num / x
return num
def ugly(n):
count = 1
for i in range(2, n):
i = reduce(i, 2)
i = reduce(i, 3)
i = reduce(i, 5)
if i == 1:
count += 1
print(count)
ugly(11)
|
f4157ba7c8485c7abaa719e71c87ba3389750dad | pah-dev/curso_python | /funciones/decoradores.py | 757 | 3.75 | 4 |
# a, b, c
# a(b) -> c formula de decoradores
# formula a recibe a funcion b y retorna funcion c
def decorador(funcion):
def nueva_funcion():
print("Podemos agregar codigo antes")
funcion()
print("Podemos agregar codigo despues")
return nueva_funcion
@decorador
def funcion_a_decorar():
print("Esta es una funcion a decorar")
funcion_a_decorar()
def decorador(funcion):
def nueva_funcion(*args,**kwargs):
print("Podemos agregar codigo antes")
resultado = funcion(*args,**kwargs)
print("Podemos agregar codigo despues")
return resultado
return nueva_funcion
@decorador
def suma(val1,val2):
return val1+val2
funcion_a_decorar()
resultado = suma(10,20)
print(resultado) |
c388abd56e6d66944bfcdf93d322b9788536e3ae | mcguiremw/prime_check | /src/is_prime.py | 1,620 | 4.40625 | 4 | import argparse
from math import sqrt
import sys
def check(n):
"""Check if a number is prime, return True if it is False otherwise.
Args:
n -- the number to check for primeness
"""
if n == 1:
return True
elif (n % 2 == 0) and (n != 2):
return False
else:
for x in range(3, (int(sqrt(n)) + 1)):
if n % x == 0:
return False
return True
def build_matrix(size):
"""Given the amount of prime numbers to find, build a two dimensional array with the prime
numbers as the indices for the rows and columns. Each cell will be the product of their
respective row and column indices, return the resulting matrix.
Args:
size -- the amount of prime numbers to find, starting with 1
"""
indices = []
for i in range(sys.maxsize):
if check(i):
indices.append(i)
if len(indices) == size:
break
return [[x*y for x in indices] for y in indices]
def print_matrix(size):
"""Print a multiplication table with prime numbers as the Row and Column Indeces.
Args:
size -- the amount of prime numbers to find, starting with 1
"""
matrix = build_matrix(size)
for x in matrix:
print(*x, sep="\t")
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Print a Multiplication Table of Primary Numbers')
parser.add_argument(
'--primes', nargs='?', const=1, default=10, type=int,
help='How many primes would you like to build the multiplication table with?')
print_matrix(parser.parse_args().primes)
|
7caed6af61f104a3e0832a8fadc0f4a75778eb15 | lan-tianyu/python3 | /CookBook-Learning/code/chapter3/test-3-2.py | 441 | 3.515625 | 4 | a = 4.2
b = 2.1
print(a + b)
import math
from decimal import Decimal, localcontext
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b, a + b == Decimal('6.3'))
print('-' * 50)
a = Decimal(1.7)
b = Decimal(1.2)
print(a / b)
with localcontext() as ctx:
ctx.prec = 3
print(a / b)
with localcontext() as ctx:
ctx.prec = 50
print(a / b)
print('-' * 50)
nums = [1.23e+18, -1.23e+18]
print(sum(nums))
print(math.fsum(nums))
|
5b7d0f3f62e4cc590c7db46f10c071e2814d4149 | MSharique/competitive_codes | /TWOVSTEN.py | 162 | 3.6875 | 4 | t = int(input())
while t>0:
t-=1
num = int(input())%10
if num==0:
print("0")
elif num==5:
print("1")
else:
print("-1") |
fa26018430388028041567a0138e795f6cedd18f | qkreltms/problem-solvings | /BOJ/괄호의값/3회차-stack.py | 1,108 | 3.5625 | 4 | def f():
stack=[]
for c in s:
if c==')':
r=0
if not stack:
return 0
while True:
t=stack.pop()
if t=='(':
if r:
stack.append(2*r)
else:
stack.append(2)
break
elif not stack or t=='[':
return 0
else:
r+=t
elif c==']':
r=0
if not stack:
return 0
while True:
t=stack.pop()
if t=='[':
if r:
stack.append(3*r)
else:
stack.append(3)
break
elif not stack or t=='(':
return 0
else:
r+=t
else:
stack.append(c)
ans=0
for c in stack:
if not isinstance(c, int):
return 0
ans+=c
return ans
s=input()
print(f()) |
b52a116f8990e6d083f19a4ca6ba2f119efc63de | jwlauer/MS5803_Logger | /pressure.py | 4,695 | 3.875 | 4 | def MS5803(i2c, power_pin=None, ground_pin=None):
""" A micropython function for reading pressure and temperature from an MS5803 sensor.
The function assumes that the MS5803 is hooked up according to instructions at
the `cave pearl project <https://thecavepearlproject.org/2014/03/27/adding-a-ms5803-02-high-resolution-pressure-sensor/>`_.
Power and ground should be connected through a 100 nf (104) decoupling capacitor, and CSB
should be pulled high using a 10 kOhm resistor. Tested with MS5803_BA.
Code modified from code originally developed for raspberry pi at the `control everything community <https://github.com/ControlEverythingCommunity/MS5803-05BA/blob/master/Python/MS5803_05BA.py>`_.
Parameters
----------
i2c : :obj:'machine.I2C'
An I2C bus object
power_pin : :obj:'machine.PIN', optional
Pin object representing the pin used to power the MS5803
ground_pin : :obj:'machine.PIN', optional
Pin object representing the pin used to ground the MS5803 (optional)
Returns
-------
pressure : float
Pressure in hPa.
temperature : float
Temperature in degrees C.
Example
-------
>>> from machine import I2C, Pin
>>> import pressure
>>> i2c = I2C(scl='X9', sda='X10', freq = 100000)
>>> power_pin = Pin('Y7', Pin.OUT_PP)
>>> ground_pin = Pin('Y8', Pin.OUT_PP)
>>> [pres, ctemp] = pressure.MS5803(i2c, power_pin, ground_pin)
"""
import time
#turn on power and turn off ground if necessary
if not(power_pin is None):
power_pin.value(1)
if not(ground_pin is None):
ground_pin.value(0)
#check if device is connected--should be at address 118
#i2c.scan()
# MS5803_05BA address, 0x76(118)
# 0x1E(30) Reset command
reset_command = bytearray([0x1E])
i2c.writeto(0x76, reset_command)
time.sleep(0.5)
# Read 12 bytes of calibration data
# Read pressure sensitivity
data = bytearray(2)
data = i2c.readfrom_mem(0x76, 0xA2, 2)
C1 = data[0] * 256 + data[1]
# Read pressure offset
data = i2c.readfrom_mem(0x76, 0xA4, 2)
C2 = data[0] * 256 + data[1]
# Read temperature coefficient of pressure sensitivity
data = i2c.readfrom_mem(0x76, 0xA6, 2)
C3 = data[0] * 256 + data[1]
# Read temperature coefficient of pressure offset
data = i2c.readfrom_mem(0x76, 0xA8, 2)
C4 = data[0] * 256 + data[1]
# Read reference temperature
data = i2c.readfrom_mem(0x76, 0xAA, 2)
C5 = data[0] * 256 + data[1]
# Read temperature coefficient of the temperature
data = i2c.readfrom_mem(0x76, 0xAC, 2)
C6 = data[0] * 256 + data[1]
# MS5803_05BA address, 0x76(118)
# 0x40(64) Pressure conversion(OSR = 256) command
pressure_command = bytearray([0x40])
i2c.writeto(0x76, pressure_command)
time.sleep(0.5)
# Read digital pressure value
# Read data back from 0x00(0), 3 bytes
# D1 MSB2, D1 MSB1, D1 LSB
value = bytearray(3)
value = i2c.readfrom_mem(0x76, 0x00, 3)
D1 = value[0] * 65536 + value[1] * 256 + value[2]
# MS5803_05BA address, 0x76(118)
# 0x50(64) Temperature conversion(OSR = 256) command
temperature_command = bytearray([0x50])
i2c.writeto(0x76, temperature_command)
time.sleep(0.5)
# Read digital temperature value
# Read data back from 0x00(0), 3 bytes
# D2 MSB2, D2 MSB1, D2 LSB
value = i2c.readfrom_mem(0x76, 0x00, 3)
D2 = value[0] * 65536 + value[1] * 256 + value[2]
dT = D2 - C5 * 256
TEMP = 2000 + dT * C6 / 8388608
OFF = C2 * 262144 + (C4 * dT) / 32
SENS = C1 * 131072 + (C3 * dT ) / 128
T2 = 0
OFF2 = 0
SENS2 = 0
if TEMP > 2000 :
T2 = 0
OFF2 = 0
SENS2 = 0
elif TEMP < 2000 :
T2 = 3 * (dT * dT) / 8589934592
OFF2 = 3 * ((TEMP - 2000) * (TEMP - 2000)) / 8
SENS2 = 7 * ((TEMP - 2000) * (TEMP - 2000)) / 8
if TEMP < -1500 :
SENS2 = SENS2 + 3 * ((TEMP + 1500) * (TEMP +1500))
TEMP = TEMP - T2
OFF = OFF - OFF2
SENS = SENS - SENS2
pressure = ((((D1 * SENS) / 2097152) - OFF) / 32768.0) / 100.0
cTemp = TEMP / 100.0
fTemp = cTemp * 1.8 + 32
# Output data to screen
print("Pressure : %.2f mbar" %pressure)
print("Temperature in Celsius : %.2f C" %cTemp)
print("Temperature in Fahrenheit : %.2f F" %fTemp)
if not(power_pin is None):
power_pin.value(0)
return([pressure, cTemp]) |
48a124c129dcd782fcc4d47f189decb740fbfde2 | liqian7979/algorithm016 | /Week_07/Trie.py | 1,655 | 4.125 | 4 | # @Author : debian-liqian
# @Email : [email protected]
# @Time : 20-10-29 下午3:55
# @File : Trie.py
# @Software : PyCharm
"""
208. 实现Trie (前缀树)
实现一个Trie (前缀树),包含 insert, search 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
· 你可以假设所有的输入都是由小写字母 a-z 构成的
· 保证所有输入均为非空字符串
"""
class Trie(object):
def __init__(self):
self.root = {}
self.end_of_word = "#"
def insert(self, word):
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end_of_word] = self.end_of_word
def search(self, word):
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return self.end_of_word in node
def startsWith(self, prefix):
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
if __name__ == '__main__':
trie = Trie()
trie.insert('apple')
sea1 = trie.search('apple')
print(sea1)
sea2 = trie.search('app')
print(sea2)
stw = trie.startsWith('app')
print(stw)
trie.insert('app')
sea3 = trie.search('app')
print(sea3)
sea4 = trie.search('apple')
print(sea4) |
8a20ee352924876b8b7685ecbd96d5fa4b1bfb1a | Navuzasshu/Act_3 | /Act_3.py | 3,089 | 4.125 | 4 | #This is a program that gives the user a limited breakfast selection.
delivMes='It will be delivered shortly. Enjoy!'
#delivMes = delivery message. Will be used repeatedly, therefore it was stored in a variable.
rejectMes='Your choice is not available at the moment. If you want a special order, please visit the counter.'
#rejectMes = rejection message, when the input is not one of the presented choices. Will be used repeatedly, therefore it was stored in a variable.
print("> Please select your breakfast choice!")
mMenu=["Bacon and Eggs", "Toast/Pandesal", "Rice", "Pancakes"]
#mMenu= main menu
print("1. Bacon and Eggs")
print("2. Toast/Pandesal")
print("3. Rice")
print("4. Pancakes")
primsel=int(input("> Your choice: "))
#primsel = primary selection
if (primsel==1):
print("You've selected Bacon and Eggs! {}".format(delivMes))
elif (primsel==2):
filling=["Hotdog", "Sunny Side Egg", "Sandwich Spread", "Cheese"]
print("1. Hotdog (Hotdog Bun)")
print("2. Sunny Side Egg")
print("3. Sandwhich Spread")
print("4. Cheese")
subsel1=int(input("> Please select filling: "))
#subsel = sub selection 1
if (subsel1==1):
print("You've selected {}, with {} filling. {}".format(mMenu[1],filling[0],delivMes))
elif (subsel1==2):
print("You've selected {}, with {} filling. {}".format(mMenu[1],filling[1],delivMes))
elif (subsel1==3):
print("You've selected {}, with {} filling. {}".format(mMenu[1],filling[2],delivMes))
elif (subsel1==4):
print("You've selected {}, with {} filling. {}".format(mMenu[1],filling[3],delivMes))
else:
print(rejectMes)
elif (primsel==3):
viand=["Hotdog", "Ham", "Bacon", "Scrambled Egg", "Sunny Side Egg"]
print("1. Hotdog")
print("2. Ham")
print("3. Bacon")
print("4. Scrambled Egg")
print("5. Sunny Side Egg")
subsel2=int(input("> Please select viand: "))
if (subsel2==1):
print("You've selected {} with {}. {}".format(mMenu[2],viand[0],delivMes))
elif (subsel2==2):
print("You've selected {} with {}. {}".format(mMenu[2],viand[1],delivMes))
elif (subsel2==3):
print("You've selected {} with {}. {}".format(mMenu[2],viand[2],delivMes))
elif (subsel2==4):
print("You've selected {} with {}. {}".format(mMenu[2],viand[3],delivMes))
elif (subsel2==5):
print("You've selected {} with {}. {}".format(mMenu[2],viand[4],delivMes))
else:
print(rejectMes)
elif (primsel==4):
toppings=["Syrup","Honey","Fruit"]
print("1. Syrup")
print("2. Honey")
print("3. Fruit")
subsel3=int(input("> Please select topping: "))
if (subsel3==1):
print("You've selected {}, with {} topping. {}".format(mMenu[3],toppings[0],delivMes))
elif (subsel3==2):
print("You've selected {}, with {} topping. {}".format(mMenu[3],toppings[1],delivMes))
elif (subsel3==3):
print("You've selected {}, with {} topping. {}".format(mMenu[3],toppings[2],delivMes))
else:
print(rejectMes)
else:
print(rejectMes)
|
88a778f6ac35154a4a09c337d586e17d7aac4359 | swapnil-tiwari/programming | /printsubsetsum.py | 676 | 3.609375 | 4 | stack=[]
def printsubsetsum(sets,sub,n,sum):
# print(elem)
if(sum==0):
for each in sub:
print (each, end=" ")
print()
return
if(n==0):
return
# res = (printsubsetsum(sets,n-1,sum) or (stack.append(sets[n-1]) and printsubsetsum(sets,n-1,sum-sets[n-1])))
res1=printsubsetsum(sets,sub,n-1,sum)
sub1=sub
print(sub,sub1)
sub1.append(sets[n-1])
res2=printsubsetsum(sets,sub1,n-1,sum-sets[n-1])
# def main(len):
# sets=[2, 3, 5, 6, 8, 10]
# print(printsubsetsum(sets,len,10))
print(printsubsetsum([2,3,5,6,8,10],[],6,10))
# print(stack)
# print(list(map(main,[6,5,4,3,2,1])))
|
576c0552b68614b8eb12440fb228a56aab204a02 | vitorAmorims/python | /dicionario_loop.py | 546 | 4.5 | 4 |
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
# Imprima todos os valores do dicionário, um por um:
for x in thisdict:
print(thisdict[x])
# Você também pode usar o values()método para retornar valores de um dicionário:
for x in thisdict.values():
print(x)
# Você pode usar o keys()método para retornar as chaves de um dicionário:
for x in thisdict.keys():
print(x)
# Loop através de chaves e valores , usando o items()método:
for x, y in thisdict.items():
print(x, y)
|
58aea3f621bd062cce83316ed654d980b48bbcc7 | lowrybg/SoftuniPythonFund | /dictionaries/student_academy.py | 446 | 3.53125 | 4 | n = int(input())
my_dict = {}
for _ in range(n):
name = input()
grade = float(input())
if name not in my_dict:
my_dict[name] = []
my_dict[name].append(grade)
filtered = {}
for key, value in my_dict.items():
av_grade = sum(value)/len(value)
if av_grade >= 4.5:
filtered[key] = av_grade
for key, value in sorted(filtered.items(), key=lambda x: x[1], reverse=True):
print(f'{key} -> {value:.2f}')
|
df2f36e15e49ee1196837e9a28d150efeac030b8 | linika/Python-Program | /code43.py | 309 | 4 | 4 | # count the vowel in each number
vowel="aeiou"
ip_str=input("Enter the string")
ip_str=ip_str.casefold()
count={}.fromkeys(vowel,0)
# here in fromkeys we are constructing new dictinary where all the vowels are keys and intialize value as 0
for char in ip_str:
if char in count:
count[char]+=1
print(count)
|
147e08b938d321076b9f43711c8194566a5a4671 | harishtallam/Learning-Python | /Learn_Python_by_Udemy_Navin/3_Math/5_assignment.py | 591 | 4.3125 | 4 | ## List any 5 funtions from math module and how it works?
import math
print(math.sqrt(4))
print(math.floor(3.2))
print(math.ceil(3.2))
print(math.degrees(1)) # converts radians to degrees
print(math.fabs(2.13)) # returns absolute value of the float
"""
Write a code to find the cube of the number. Take input from the user using input() and also using command line
"""
# Solution 1
import math
print(math.pow(3,3))
# Solution 2
x = int(input("Enter the number: "))
print(math.pow(x,3))
# Solution 3
# Need run like --> py filename.py
import sys
y = int(sys.argv[1])
print(math.pow(y,3)) |
b018f5a27cd18418bd8c4570f8267e6eff5be0cf | njenga5/python-problems-and-solutions | /Solutions/problem92.py | 295 | 4.125 | 4 | '''
Question 92:
By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].
Hints:
Use list's remove method to delete a value.
'''
values = [12, 24, 35, 24, 88, 120, 155]
values = [x for x in values if x != 24]
print(values)
|
5499110ab50d4a11ed5463f011178055aecc1502 | linag99/Proyecto | /cris.py | 940 | 3.53125 | 4 | #MiPong#
from tkinter import*
def pad1Arriba(r):
c.move(pad1, 0, -10)
def pad1Abajo(r):
c.move(pad1, 0, 10)
def pad2Arriba(e):
c.move(pad2, 0, -10)
def pad2Abajo(e):
c.move(pad2, 0, 10)
def moverBall():
x1, y1, x2, y2 = c.coords(ball["obj"])
x = (x1+x2)//2
y = (y1+y2)//2
dx = 4
if x<10 or x>390:
ball["dx"]*=-1
if y<10 or y>390:
ball["dy"]*=-1
c.move(ball["obj"], ball["dx"], ball["dy"])
ventana.after(50, moverBall)
ventana = Tk()
c = Canvas(ventana, width = 400, height=400)
c.pack()
c.create_line(200, 0, 200, 400)
pad1 = c.create_rectangle(10, 25, 20, 75, fill= "red")
pad2 = c.create_rectangle(380, 325, 390, 375, fill= "blue")
ball = {"dx": 5, "dy":5, "obj":c.create_oval(190, 190, 210, 210, fill= "black")}
ventana.bind("w", pad1Arriba)
ventana.bind("s", pad1Abajo)
ventana.bind("8", pad2Arriba)
ventana.bind("2", pad2Abajo)
ventana.after(10, moverBall)
|
ab510abcf925e780b8ec8b0867419f3a59ebeb16 | Padma-Dhar/Python_assignments | /black_jack/black_jack.py | 3,343 | 3.671875 | 4 | # from art import logo
# import random
# class blackjack_player:
# def __init__(self):
# self.blackjack_cards_drawn = []
# self.end_game_parameter=0
# self.lost=0
# self.sum_of_card_value=0
# self.card_value={"J":10,"Q":10,"K":10,"A":11}
# for i in range(1,11):
# self.card_value[i]=int(i)
# def draw_card(self):
# card=random.choice([2,3,4,5,6,7,8,9,10,"J","Q","K","A"])
# self.blackjack_cards_drawn.append(card)
# self.check_if_lost()
# def end_game(self):# return 1 if the player has end the game
# self.end_game_parameter = 1
# def reveal_card(self):
# for i in self.blackjack_cards_drawn:
# if(i==1):
# print(" A ", end="")
# else:
# print(" "+str(i)+' ',end="")
# print()
# def count_score(self):
# self.sum_of_card_value=0
# for card in self.blackjack_cards_drawn:
# self.sum_of_card_value+=self.card_value[card]
# if(self.sum_of_card_value>21):
# for location, card in enumerate(self.blackjack_cards_drawn):
# print(self.card_value)
# print(self.blackjack_cards_drawn)
# try:
# print(self.card_value[card])
# except:
# print("probelme")
# print(card,location)
# if(self.card_value[card] == 11):
# self.blackjack_cards_drawn[location]=1
# self.sum_of_card_value-=10
# break
# def check_if_lost(self):# goes over 21
# self.count_score()
# if(self.sum_of_card_value>21):
# self.lost=1
# player = blackjack_player()
# computer = blackjack_player()
# while(input("Play a game of blackjack")=="y"):
# player.draw_card()
# player.draw_card()
# player.reveal_card()
# computer.draw_card()
# computer.reveal_card()
# computer.draw_card()
# while(input("Draw a card") == "y"):
# player.draw_card()
# player.reveal_card()
# if(player.lost==1):
# break
# player.end_game()
# computer.reveal_card()
# while(computer.sum_of_card_value<player.sum_of_card_value and computer.lost==0 and computer.end_game_parameter != 1 and player.lost==0):
# computer.count_score()
# score_left=21-computer.sum_of_card_value
# if(score_left>10):
# computer.draw_card()
# computer.reveal_card()
# elif(score_left<=10):
# choice_by_computer = random.choices([0,1], weights=[(10-score_left)/10, score_left/10], cum_weights=None, k=1)
# if(choice_by_computer == 1):
# #pick a card
# computer.draw_card()
# computer.reveal_card()
# else:
# computer.end_game()
# print("Your cards", player.reveal_card())
# print("Computers Cards", computer.reveal_card())
# if(computer.lost==1 or (computer.sum_of_card_value<player.sum_of_card_value and player.lost==0)):
# print("You Win")
# elif((computer.lost==0 and computer.sum_of_card_value>player.sum_of_card_value) or player.lost == 1):
# print("You lose")
# else:
# print("Draw") |
a545d73cfd2e26f29484b2a7e611986da2ba0b03 | turanbulutt/ThirdClassAssignments | /Scripting/ServerAndClientCoding/server.py | 3,796 | 3.640625 | 4 | import datetime
import socket
import threading
threadLock = threading.RLock()
class ClientThread(threading.Thread): # custom class extending the Thread class
def __init__(self, clientAddr, clientsock): # constructor for ClientThread
threading.Thread.__init__(self) # calling base class constructor Thread class
self.csocket = clientsock # setting socket
self.caddr = clientAddr # setting address
print("New connection from {}".format(self.caddr)) # displaying the address of the client in the console
def run(self): # running client thread
msg = "Connection Established".encode() # message for client
self.csocket.send(msg) # send message
threadLock.acquire() # defining the borders of critical section
while True: # continue listening (receiving packages)
self.data = self.csocket.recv(1024).decode() # receiving package from client
if self.data == 'bye': # if client terminates the program
self.csocket.send("bye".encode())
break # break the while True loop
myData = self.data.split(";")
print(myData)
customerNo = myData[0].split(" ")[1]
meal = myData[1].split(" ")[2]
cakes = myData[2].split(":")[1]
print(cakes)
price = 0
if meal == "Burger(25TL)":
print("burger")
price = price + 25
else:
print("pizza")
price = price + 30
if cakes == " Chocolate Cake":
print("choco")
price = price + 20
elif cakes == " Chocolate Cake,Strawberry Cake":
print("both")
price = price + 38
elif cakes == " Strawberry Cake":
print("straw")
price = price + 18
now = datetime.datetime.now() # stores the date, when the button was pressed
file = open("orders.txt", "r") # open users.txt for reading
count = 0
for x in file: # for each line in users.txt
xList = x.split(";") # split users.txt based on the ';' char and stores string in list
if xList[0].split(" ")[1] == customerNo:
count = count + 1
file.close() # close the users.txt file
if count > 10:
price = price * 90 / 100
newData = self.data + ";Price: " + str(price) + ";" + str(now.day) + "/" + str(now.month) + "/" + str(
now.year) + " " + str(now.hour) + ":" + str(now.second)
file = open("orders.txt", "a") # open a sales.txt for appending
file.write(newData+"\n") # append data from the client to the sales.txt file as a new line
file.close() # close the sales.txt
self.csocket.send(str(price).encode()) # send the report to the client.
threadLock.release()
print("Client is disconnected")
self.csocket.close() # close the server side socket
HOST = "127.0.0.1" # localhost
PORT = 5000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # setting server to support multithreading
server.bind((HOST, PORT)) # binding server to the address and port provided above
print("Server is started")
print("Waiting for client requests")
while True: # Main loop to run the server and accept client packages.
server.listen() # listener for client
clientsock, clientAddr = server.accept() # accepting packages from client
newthread = ClientThread(clientAddr, clientsock) # creating new thread for client
newthread.start() # running the newly created thread
|
8b2f0ce3c46f80ccdb65d434383860445ad28187 | Juan-Chen-BNUZ/algorithm-study | /Test/test-29.py | 568 | 3.625 | 4 | # -*- coding:utf-8 -*-
"""
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
"""
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
if k > len(tinput):
return []
tin = sorted(tinput)
res = list()
for i in range(0, k):
res.append(tin[i])
return res
if __name__ == '__main__':
A = [4, 5, 1, 6, 2, 7, 3, 8]
B = 4
print(Solution().GetLeastNumbers_Solution(A,B))
# write code here
|
56e9ac27af978ad10077a35c7af6aadbd960f1e0 | wangyendt/LeetCode | /Easy/14. Longest Common Prefix/Longest Common Prefix.py | 530 | 3.8125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# author: wang121ye
# datetime: 2019/8/28 22:38
# software: PyCharm
class Solution:
def longestCommonPrefix(self, strs: list) -> str:
if not strs: return ''
ret = strs[0]
while strs:
s = strs.pop()
for i in range(min(len(s), len(ret))):
if s[i] != ret[i]:
ret = ret[:i]
break
return ret
so = Solution()
print(so.longestCommonPrefix(["flower", "flow", "flight"]))
|
170b03b10232c13c78943636cefbacafe4cda4be | Yuehchang/Python-practice-files | /Introducing_Python/Chap2_numstrvar.py | 2,501 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 30 21:57:41 2017
@author: changyueh
"""
type() #瞭解()的物件類型
# / 浮點除法 => 7/2 => 3.5
# // 整數除法 => 7/2 => 3 (捨去)
# % 餘數 => 7/2 => 1
a -= 3 <==> a = a - 3 #兩個式子是一樣的
a += 3 <==> a = a + 3
a *= 3 <==> a = a * 3
divmod() #可以回傳商及餘數 page 25
#基數 二進位 0b/0B // 八進位 0o/0O // 十六進位 0x/0X
0b10 #2
0o10 #8
0x10 #16
#類型轉換 page 27
# 整數
int() #轉變成整數,捨棄小數
int(True) #轉變成 1
int(False) #轉變成 0
int('-99') #轉換只含數字的字串
int('99.89') #無法處理有小數的字串
#Boolean與數字相加時會自動變成 0 or 1
True + 1 # = 2
#浮點數
float() #()裡面中如是整數,會自動變成增加“點零”
#用str()轉換資料類型 page 33
str() #數值轉變成字串
# \ => 轉義
palinedrome = 'A man, \nA plan, \nA canal, \nPanama.'
print(palinedrome)
# \n 代表換行
print('\tabc')
print('a\tbc')
# \t 代表對齊
testimony = "\"I did noting!\" he said. \"Not that either! Or the other thing.\""
print(testimony)
# \' or \" 代表引號
fact = "The world's largest rubber duck was 54'2\" by 65'7\" by 105'" # 必須利用\"代替,不然字串會斷掉
#需要反斜線就打兩次 \\
# 用*來複製
strat = 'Na' * 4 + '\n'
middle = 'Hey' * 3 + '\n'
end = 'Goodbye.'
print(strat + strat + middle + end)
#Slice的使用
[:] #從開始到結束
[start :] #從start到結束
[: end] #從頭到(end-1)
[start : end] #從start到(end-1)
[start : end : step]
#如果沒有指定start or end就會從0開始,-1結束
#把玩字串 page 40-41
len()
startswith() #找出字串的開頭,括號內輸入“值”
endswith() #與上述相反
find() #找出括號內的值,第一次出現的位移植
rfind() #最後一次的位移植
count()
isalnum()
#大小寫與對齊 page 41
strip("char") #可以移除內容
capitalize() #第一個字改為大寫
title() #全部字的第一個字改為大寫
upper() #全部大寫
lower() #全部小寫
swapcase() #大小寫對掉
center(30) #在30個字元中對齊,數值可隨時替換
ljust(number) #靠左對齊
rjust(number) #靠右對齊
# replace()做簡單替換
replace('char1', 'char2') #用char2替換char1,但是只會替換第一個
replace('char1', 'char2', 100) #等同效果,替換100個
"""
如果要替換全部的字,或複雜的替換,需使用“正規表達式”,第七章會介紹
"""
|
fccba4e01ad566e184e5d163f52d2bcb7839174c | Vith-MCB/Phyton---Curso-em-Video | /Cursoemvideo/Exercícios/exer36 - Empréstimo.py | 314 | 3.859375 | 4 | valcasa = float(input('Valor da casa: '))
sal = float(input('Salário: '))
anos = float(input('Quantidade de anos: '))
prest = valcasa/(anos * 12)
if prest > sal * 1.3:
print('Empréstimo negado!')
elif prest == sal * 1.3:
print('Empréstimo aprovado NA TRAAAAVE!')
else:
print('Emprestimo liberado!')
|
0ac93e2bc791451ccd9c104718498da651e186f2 | DmitryIvanov10/MetodyNumeryczneI | /Tasks/Lista10/task2.py | 482 | 3.890625 | 4 | # Lesson10, Task2
# import cos
from math import cos
# import own module
import numerical_methods as num
# set initial data
a = -1
b = 1
def f(_x):
return cos(2 * cos(_x)**(-1))
# calculate and print results
integral = num.simpson(f, a, b, 3)
print("I = {} for n = 3".format(integral))
print ()
integral = num.simpson(f, a, b, 5)
print("I = {} for n = 5".format(integral))
print ()
integral = num.simpson(f, a, b, 7)
print("I = {} for n = 7".format(integral))
print ()
|
12a1792b0510f40f52988688b2179788e2b8d949 | PrimoWW/mooc | /add_digits.py | 610 | 4.21875 | 4 | """
Given a non-negative integer num,
repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38,
the process is like: 3 + 8 = 11,
1 + 1 = 2. Since 2 has only one digit, return it.
"""
def add_digits(num):
"""
:param num: int
:return: int
"""
next_num = num
while True:
print(next_num)
list_num = list(str(next_num))
next_num = 0
for i in list_num:
next_num += int(i)
if next_num < 10:
break
return next_num
if __name__ == '__main__':
num = 38
print(add_digits(num))
|
afc337ddb683636cd770fa48fa88213a8e5bd6a9 | SamratAdhikari/Ethical-Hacking-Python | /Password cracker/Password Cracker.py | 1,485 | 3.90625 | 4 | # Password Cracker
import hashlib, pyperclip
def main():
myPass = str(input("Enter the password/passhash: "))
pass_mode = str(input("[E]ncrypt or [D]ecrypt: "))
if pass_mode.upper().startswith("E"):
encryptHash(myPass)
elif pass_mode.upper().startswith("D"):
decryptHash(myPass)
else:
print("Invalid Input...")
def encryptHash(msg):
pass_hash = hashlib.md5(str.encode(msg)).hexdigest()
with open("wordlist.txt", "a") as f:
f.write("\n" + msg.strip())
print("\nEncrypted Password is: " + pass_hash)
print("Copied the PassHash to the clipboard")
pyperclip.copy(pass_hash)
def decryptHash(msg):
pass_file = open("wordlist.txt", "r")
flag = 0
for word in pass_file:
encode_word = word.encode("utf-8")
digest = hashlib.md5(encode_word.strip()).hexdigest()
if digest == msg:
print("Password has been found !\nPassword : " + word)
# return "Password has been found !\nPassword : " + word
flag = 1
print("Copied the PassWord to the clipboard")
pyperclip.copy(word)
break
if flag == 0:
print("\nPassword/Passphase is not in the list...")
ask = input("\nDo you know the Decrypted Password?(y/n) ")
if ask == "y":
ask_pass = input("Type the Password: ")
with open("wordlist.txt", "a") as f:
f.write(ask_pass.strip())
if __name__ == '__main__':
run = True
while run:
main()
play = input("\nRun the Program again?(y/n) ")
if play != "y":
run = False
|
5a2284a34993b18ea278047eca702c643ee98b43 | sufyjakate/Mario-Princess | /princess_save.py | 694 | 3.703125 | 4 | def PrincessPath(n, grid):
for idx, row in enumerate(grid):
if 'p' in row:
princess = (idx, row.index('p'))
if 'm' in row:
mario = (idx, row.index('m'))
# negative row difference implies UP
# negative col difference implies LEFT
drows = princess[0] - mario[0]
dcols = princess[1] - mario[1]
final = ''.join([
'UP\t' * abs(drows) if drows < 0 else 'DOWN\t' * drows,
'LEFT\t' * abs(dcols) if dcols < 0 else 'RIGHT\t' * dcols])
return final
if __name__ == "__main__":
n = int(input('Enter N'))
grid = [input('grid').strip() for _ in range(n)]
print(PrincessPath(n, grid))
|
00fe8b198e8cf153a2ada8b8236033e9f801856b | mradoychovski/Python | /PAYING OFF CREDIT CARD DEBT/bisection_search.py | 863 | 4.25 | 4 | # Uses bisection search to find the fixed minimum monthly payment needed
# to finish paying off credit card debt within a year
balance = float(raw_input("Enter the outstanding balance on your credit card: "))
annualInterestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
monthlyInteretRate = annualInterestRate/12.0
high =(balance * (1 + monthlyInteretRate)**12)/12
total = 0
tempBalance = balance
while tempBalance > 0:
month = 0
while month < 12:
interest = (tempBalance - high) * monthlyInteretRate
tempBalance = (tempBalance - high) + interest
total += high
finalbalance = tempBalance - total
month += 1
if tempBalance < -0.01 or tempBalance > 0.01:
high += tempBalance / 12.0
tempBalance = balance
else:
break
total=0
print('Lowest Payment: %.2f' % high)
|
0fde2f9f07c9997cef61ab99b9ff03140a373f28 | OctavioThomsen/LexerParser | /LexerParser/Automata_numeros.py | 1,847 | 3.875 | 4 | #Variables auxiliares
TRAP_STATE = -1
RESULT_TRAP = "RESULT_TRAP"
RESULT_ACCEPTED = "ACCEPTED"
RESULT_NOT_ACCEPTED = "NOT ACCEPTED"
numeros = ["0","1","2","3","4","5","6","7","8","9"]
#Función transición
def delta(state, caracter):
#{q0, ["0",...,"9"], q1f}
if state == 0 and caracter in numeros:
return 1
#{q1f, ["0",...,"9"], q1f}
if state == 1 and caracter in numeros:
return 1
#{q1f, ".", q2}
if state == 1 and caracter == ".":
return 2
#{q2, ["0",...,"9"], q3f}
if state == 2 and caracter in numeros:
return 3
#{q3, ["0",...,"9"], q3f}
if state == 3 and caracter in numeros:
return 3
return TRAP_STATE
#Automata numeros
def automata_num(input):
state = 0
final = [1,3]
for caracter in input:
next_state = delta(state, caracter)
#print(("transicion", state, caracter, next_state))
state = next_state
if state in final:
#print( input, "pertenece al lenguaje")
return RESULT_ACCEPTED
if state != TRAP_STATE:
#print( input, "aún no pertenece al lenguaje")
return RESULT_NOT_ACCEPTED
#print(input, "no pertenece al lenguaje")
return RESULT_TRAP
#Tests
#assert(automata_num("222222")== RESULT_ACCEPTED)
#print (" ")
#assert(automata_num("124712986") == RESULT_ACCEPTED)
#print(" ")
#assert(automata_num("412.6171.6717")== RESULT_TRAP)
#print(" ")
#assert(automata_num("42069")== RESULT_ACCEPTED)
#print (" ")
#assert(automata_num("23432,234") == RESULT_TRAP)
#print(" ")
#assert(automata_num("24.76")== RESULT_ACCEPTED)
#print(" ")
#assert(automata_num("xdxdxdxd") == RESULT_TRAP)
#print(" ")
#assert(automata_num("87.") == RESULT_NOT_ACCEPTED) |
4663f2a44681e3730212682b1d30fc87e12a2183 | allenwhc/Algorithm | /Company/Facebook/IncreasingTripletSequence(M).py | 1,141 | 3.78125 | 4 | class Solution(object):
"""
Brute force solution
Time complexity: O(nk), n is length of nums, k is length of subset whose best case is O(1) and worst case is O(n)
Extra space: O(1)
"""
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums)<3: return False
for i in range(1,len(nums)-1):
less,greater=False,False
for j in range(i-1,-1,-1):
if nums[i]>nums[j]:
less=True
break
for j in range(i+1,len(nums)):
if nums[i]<nums[j]:
greater=True
break
if less and greater: return True
return False
"""
Two pointer solution
Time complexity: O(n), n is length of nums
Extra space: O(1)
"""
def increasingTriplet2(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums)<3: return False
l,r=float('inf'),float('inf')
for i in range(len(nums)):
if nums[i]<=l:
l=nums[i]
elif nums[i]<=r:
r=nums[i]
else:
return True
return False
nums=[15,12,0,1,10,-10]
sol=Solution()
print nums,"exists" if sol.increasingTriplet2(nums) else "doesn't exist",'increasing triplet sequence' |
334f482ea6e98d0b7de665fa89eef7601b9b3f22 | lealobanov/Year3-COMP3487-Bioinformatics | /bio_expectation_maximization.py | 12,898 | 3.796875 | 4 | import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
pd.set_option("display.max_rows", None, "display.max_columns", None)
#Run-time instructions and output formatting
#The command line prompt accepts 3 arguments: alphabet length, number of states, and an observed input sequence
#The parameters are initialized randomly
#The program can be invoked by calling: python3 cssg28_bio_em.py alphabet_length num_states observed_sequence
#An example use case with an alphabet length of 3, 5 states, and an input sequence 0,1,2,1,0 would appear as:
#python3 cssg28_bio_em.py 3 5 0,1,2,1,0
#An alphabet length of n suggests that the input sequence can consist of integer 0 to n-1
#E.g. with alphabet length 5, the observed input sequence can contain values 0,1,2,3,4
#The input sequence must be delimited using commas to ensure that tokens with more than one digit (e.g. 10+) are accomodated
#If the input sequence contains invalid values (e.g. alphabet length 5 and you supply a value of 7 in the input sequence), an error will be returned
#While the algorithm is running, progress (current iteration) is reflected on the screen every 10 iterations
#Once the algorithm exceeds the set number of iterations (by default 1000) or the termination condition is met (log(forward probability) does not improve for 5 consecutive iterations), the model parameters are returned
#Max number of iterations may be updated on line 247
#The initial probabilities, transition and emission matrices will print to the screen
#Implementation of Baum-Welch Expectation-Maximization (EM) algorithm to estimate HMM model parameters
#Given a sequence of observed letters and number of states k
#Normalize a vector (row in Numpy matrix)
def normalize(v):
norm = np.sum(v)
v = v/norm
return (v, norm)
def forward(observed_sequence, tp, ep, ip):
normalization_constants = []
#Matrix dimensions: sequence length x number of states
alpha = np.zeros((len(observed_sequence), len(tp[0])))
#Populate the first row
alpha[0, :] = ip[0:,] * ep[:, int(observed_sequence[0])]
#Normalize first row - using Rabiner scaling (https://stats.stackexchange.com/questions/274175/scaling-step-in-baum-welch-algorithm)
normalized = normalize(alpha[0])
#Normalized alpha value
alpha[0] = normalized[0]
#Normalization constant
norm = normalized[1]
normalization_constants.append(norm)
probs_sum = []
#Use dynamic programming to populate the rest of alpha matrix
for letter in range(1, len(observed_sequence)):
for j in range(len(tp[0])):
#Derivation of forward algorithm - http://www.adeveloperdiary.com/data-science/machine-learning/forward-and-backward-algorithm-in-hidden-markov-model/
alpha[letter, j] = alpha[letter - 1].dot(tp[:, j]) * ep[j, int(observed_sequence[letter])]
normalized = normalize(alpha[letter])
alpha[letter] = normalized[0]
norm = normalized[1]
normalization_constants.append(norm)
#Compute log(forward probability) to assess convergence
logP = sum([math.log(c) for c in normalization_constants])
print("LOGP", logP)
return alpha, normalization_constants, logP
def backward(observed_sequence, tp, ep, norm_constants):
#Intialize matrix for beta values
beta = np.zeros((len(observed_sequence), len(tp[0])))
#Populate the last row with 1 - working backwards by dynamic programming
beta[len(observed_sequence) - 1] = np.ones((len(tp[0])))
#Normalize matrix row using corresponding normalization constant from alpha timestep
beta[len(observed_sequence) - 1] = beta[len(observed_sequence) - 1]/norm_constants[len(observed_sequence) - 1]
#Populate matrix
for letter in range(len(observed_sequence) - 2, -1, -1):
for j in range(len(tp[0])):
#Calculation based on - http://www.adeveloperdiary.com/data-science/machine-learning/forward-and-backward-algorithm-in-hidden-markov-model/
beta[letter, j] = (beta[letter + 1] * ep[:, int(observed_sequence[letter+1])]).dot(tp[j, :])
#Normalize row using alpha normalization constant for corresponding timestep
beta[letter] = beta[letter] / norm_constants[letter]
return beta
#Format output of estimated model parameters to screen
def format_ouput(tp, ep, ip, alphabet, num_states):
print("")
print("_________________________________")
print("")
print("Alphabet: ", alphabet)
print("Number of states: ", num_states)
print("* Initial, transition, and emission probabilities intialized randomly")
print("")
print("INITIAL PROBABILITIES")
print("* column labels denote states")
print("")
ip_df = pd.DataFrame(ip)
ip_df = ip_df.rename({0: "Initial Probabilities: "}, axis='index')
print(ip_df)
print("")
print("TRANSITION PROBABILITIES")
print("* row and column labels denote states")
print("")
tp_df = pd.DataFrame(tp)
print(tp_df)
print("")
print("EMISSION PROBABILITIES")
print("* row labels denote states, column labels denote alphabet entries")
print("")
ep_df = pd.DataFrame(ep)
print(ep_df)
print("")
return 1
#Update model parameters - return updated transition and emission probabilities
def update_params(tp, ep, gamma, xi, observed_sequence):
#Update to transition and emission probability matrices; http://www.adeveloperdiary.com/data-science/machine-learning/derivation-and-implementation-of-baum-welch-algorithm-for-hidden-markov-model/
#Updated transition probabilities = sum of all x_i / sum of all gamma up to time n-1
tp = np.sum(xi, 2) / np.sum(gamma, axis=1).reshape((-1, 1))
#Populate gamma at the last time step
gamma = np.hstack((gamma, np.sum(xi[:, :, len(observed_sequence) - 2], axis=0).reshape((-1, 1))))
#Convert observed sequence to a list of ints, then to a numpy array
observed_sequence = list(map(int, observed_sequence))
arr = np.array(observed_sequence)
#Update emission probabilities matrix
#Denominator is the sum over all gamma to time n (including last row)
denominator = np.sum(gamma, axis=1)
#Compute numerator values
for l in range(len(ep[0])):
ep[:, l] = np.sum(gamma[:, arr == l], axis=1)
#Divide all matrix entries by denominator
ep = np.divide(ep, denominator.reshape((-1, 1)))
return tp, ep
#Parse the input observed sequence and check that it comprises only the specified alphabet
def parse_observed(observed_sequence, alphabet):
#Split on commas
split_on_comma = observed_sequence.split(",")
#Convert all list entries to strings
parsed_seq = [str(i) for i in split_on_comma]
#Check validity of tokens - must come from the alphabet
for entry in split_on_comma:
if entry not in alphabet:
print("Invalid token in observed sequence - must be contained in specified alphabet. For a supplied alphabet size n, the alphabet comprises {0,1,...n-1}. Check for duplicate commas in your input.")
return 0
return parsed_seq
#Randomize initial model parameters
def randomize_initial_params(tp, ep, ip, num_states, alphabet_length):
i = 0
for row in tp:
#Probabilities must sum to 1
rand_states = np.random.dirichlet(np.ones(num_states),size=1)
tp[i] = rand_states
i +=1
i = 0
for row in ep :
rand_alphabet = np.random.dirichlet(np.ones(alphabet_length),size=1)
ep[i] = rand_alphabet
i +=1
rand_states = np.random.dirichlet(np.ones(num_states),size=1)
ip = rand_states
return tp, ep, ip
#Plotting convergence
def plot(data):
iters = []
probs = []
for entry in data:
iters.append(entry[0])
probs.append(entry[1])
plt.plot(iters,probs)
plt.title('Convergence Plot')
plt.xlabel('Time Step')
plt.ylabel('Log(Forward Probability)')
plt.show()
#Main function
def main():
#Parse command line arguments
try:
alphabet_length = sys.argv[1]
num_states = sys.argv[2]
observed_sequence = sys.argv[3]
except:
print("Missing input parameters - 3 arguments must be specified.")
return 0
#Check alphabet length is an int, and initialize the alphabet
try:
alphabet_length = int(alphabet_length)
#Must be non-zero and positive
if int(alphabet_length) <= 0:
print("Alphabet length must be a positive integer.")
return 0
#Generate alphabet
alphabet = []
for i in range(alphabet_length):
alphabet.append(str(i))
except:
print("Specified invalid alphabet length - must be an integer.")
return 0
#Check num states is an int
try:
num_states = int(num_states)
#Must be non-zero and positive
if int(num_states) <= 0:
print("Number of states must be a positive integer.")
return 0
except:
print("Specified invalid number of states - must be an integer.")
return 0
#Check observed sequence is non empty
if len(observed_sequence) == 0:
print("Observed sequence must be non-empty.")
return "Error"
#Check observed sequence only contains the alphabet
#For now assuming the observed sequence is a string separated by commas ***CLARIFY
parsed_seq = parse_observed(observed_sequence, alphabet)
if parsed_seq == 0:
return "Error"
#Parameter intialization - random probabilities (ensuring that they sum to 1)
tp = np.zeros((num_states,num_states))
ep = np.zeros((num_states,len(alphabet)))
ip = np.zeros((num_states))
tp, ep, ip = randomize_initial_params(tp, ep, ip, num_states, len(alphabet))
#Termination condition - max iterations reached or change in forward probability does not improve in 5 iterations
max_iters = 1000
termination_check = 0
prev_check = False
prev_probs = float('-inf')
current_iter = 0
plotting = []
while True:
#Log progress on the screen when many states/long seqeunce and the computation may be slow
if current_iter > 1 and current_iter % 10 == 0:
print("Current progress: timestep = " + str(current_iter))
#1. Expectation step
#Forward algorithm
alpha, norm_constants,probs = forward(parsed_seq, tp, ep, ip)
probs_ = probs
plotting.append((current_iter, probs))
#Compute the difference in forward probability as a metric of convergence
diff = np.abs(probs_ - prev_probs)
#Check if the model is improving, else add to the termination condition
if probs_ > prev_probs:
prev_probs = probs_
prev_check = False
termination_check = 0
else:
if prev_check == True:
termination_check += 1
else:
prev_check == True
termination_check += 1
#Backward algorithm
beta = backward(parsed_seq, tp, ep, norm_constants)
#Re-estimate x_i and gamma
xi = np.zeros((num_states, num_states, len(parsed_seq)-1))
for t in range(len(parsed_seq)-1):
#Xi computation derived from http://www.adeveloperdiary.com/data-science/machine-learning/derivation-and-implementation-of-baum-welch-algorithm-for-hidden-markov-model/
#Denominator = sum over all i, j (alpha_i at t * transition probability from i to j * emission probability that j emits some k * beta_j at time t+1)
denominator = np.dot(np.dot(alpha[t, :].T, tp) * ep[:, int(parsed_seq[t + 1])].T, beta[t + 1, :])
for i in range(num_states):
#Numerator = alpha_i at t * transition probability from i to j * emission probability that j emits some k * beta_j at time t+1
numerator = alpha[t, i] * tp[i, :] * ep[:, int(parsed_seq[t + 1])].T * beta[t + 1, :].T
xi[i, :, t] = numerator / denominator
#Gamma can be computed as the sum of xi values
gamma = np.sum(xi, axis=1)
#2. Maximization step
#Calculate and update new model parameters (tp, ep) using gamma, xi
tp, ep = update_params(tp, ep, gamma, xi, parsed_seq)
#Termination condition
if current_iter > max_iters or termination_check == 5:
#Format output and return the initial probabilities, the transition probabilities and the emission probabilities
format_ouput(tp, ep, ip, alphabet, num_states)
#Plotting convergence to demonstrate correctness
#plot(plotting)
break
current_iter += 1
return ip, tp, ep
if __name__ == "__main__":
main()
|
8a9ef66ca67a9f251ccd5f5340545c84adf755ef | DarMorar/Dawson_Python_Programming | /Chapter6/6.1.py | 736 | 3.9375 | 4 | """
Доработайте функцию ask_number() так, чтобы ее можно было вызывать
еще с одним параметром - кратностью (величиной шага). Сделайте шаг
по умолчанию равным 1.
"""
def ask_number(question, low, high, multiplicity=1):
"""Функция просит ввести число из диапазона"""
response = None
while response not in range(low, high, multiplicity):
response = int(input(question))
return response
low = 1
high = 20
multiplicity = 3
question = f"Введите число от {low} до {high} с шагом {multiplicity}: "
ask_number(question, low, high, multiplicity)
|
7869fa76162c6b7ffa31256edfd0393f85968bdf | Knoxxx-404/amanirshad.github.io | /sum_of_array.py | 382 | 4.25 | 4 | # Python 3 code to find sum
# of elements in given array
def _sum(arr,n):
# return sum using sum
# inbuilt sum() function
return(sum(arr))
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr,n)
# display sum
print ('Sum of the array is ', ans)
# This code is contributed by Himanshu Ranjan
|
400422f4dcf4b8edebffabc10b2932cdff485986 | carlos1134/python | /programa de calculo.py | 1,396 | 4.09375 | 4 | '''Escribir un programa para calcular
f(x) = ((x^2 + 1)^0.5) − 1
g(x) = x^2/[((x^2 + 1)^0.5) + 1]
para la sucesion 8^−1, 8^−2, 8^−3. . . , 8^−10.
Aunque f = g la computadora produce resultados distintos,cual es m´as confiable?
'''
import math
def f(x):
return math.sqrt(math.pow(x, 2)+1)-1
def g(x):
return (math.pow(x, 2))/(math.sqrt(math.pow(x, 2)+1)+1)
def evaluar_sucesion_en_ambas_funciones():
numero = 8
salida_f = []
salida_g = []
errores = []
for i in range(1, 8):
salida_f.append(f(math.pow(numero, -i)))
salida_g.append(g(math.pow(numero, -i)))
errores.append(abs(salida_f[i-1]-salida_g[i-1]))
return salida_f, salida_g, errores
def mostrar_comparaciones(salida_f, salida_g, errores):
for i in range(len(salida_f)):
print('Termino',(i+1))
print('Salida con f:', (salida_f[i]))
print('Salida con g:',(salida_g[i]))
print('Error: ', (errores[i]))
print('\n')
if __name__ == '__main__':
salida = evaluar_sucesion_en_ambas_funciones()
mostrar_comparaciones(salida[0], salida[1], salida[2])
'''Para la suce4sion 8^-1, ... 8^⁻10, a medida que crece el n, el termino se aproxima mas a cero, y la raiz se
aproxima mas a 1. En f, estoy restando numeros parecidos. En cambio, en g los estoy sumando.
Es mas confiable el resultado que produce g'''
|
0c1d632857c90962088ba0a44729684a85e4ee1d | nkbhan/Spectral_Runner | /main/Obstacle.py | 1,650 | 3.703125 | 4 | """
Obstacle.py
contains the class for the obstacles in the game
"""
import pygame
import Colors
class Obstacle(pygame.sprite.Sprite):
@staticmethod
def init():
Obstacle.size = 75
Obstacle.vy = 7
Obstacle.pinkImage = pygame.image.load("Images/pinkObstacle.png").convert_alpha()
Obstacle.tealImage = pygame.image.load("Images/tealObstacle.png").convert_alpha()
Obstacle.yellowImage = pygame.image.load("Images/yellowObstacle.png").convert_alpha()
Obstacle.baseImages = [Obstacle.pinkImage,
Obstacle.tealImage,
Obstacle.yellowImage]
def __init__(self, lane, data):
super().__init__()
self.lane = lane
self.size = Obstacle.size
self.y = -self.size
self.updateXPos(data)
self.image = pygame.Surface((Obstacle.size, Obstacle.size))
self.image = self.baseImages[self.lane]
self.rect = self.get_rect()
def get_rect(self):
left = self.x - self.size/2
top = self.y - self.size/2
return pygame.Rect(left, top, self.size, self.size)
def updateXPos(self, data):
self.x = data.width/4 + data.width/2 * (1/6 + 2*self.lane/6)
self.rect = self.get_rect()
def updateYPos(self):
self.y += self.vy
self.rect = self.get_rect()
def update(self, data):
self.updateYPos()
if self.y > data.height + self.size/2:
# if the obstacle is off the screen, the player missed it
# so break the scoring streak
data.score.breakStreak()
self.kill()
|
2ecc063dcd86afbe46d49d5e85e4512c4ae7fa3f | adamvh/caesar-cipher | /decrypt-message.py | 1,476 | 3.796875 | 4 | """
Name: Adam Hudson
Date: 2018-07-12
Program Name: decrypt-message.py
Description: This program will receive a text file and decrypt the message using the
caesar-cypher method. The decrypted message will output to the terminal.
"""
# Declair imports
import fileinput
from string import punctuation
# Shift length. Default: 3
shift = 3
# list for letter translation
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
# List of inputs from the file
data = []
# Get user's file from command line
with fileinput.input() as fileObject:
for line in fileObject:
l = list(line)
data.append(l)
for line in data:
for char in line:
# Check for special characters because are not encrypted
if char == ' ' or char == '\n' or char in set(punctuation):
print(char, end='')
else:
# This is the decryption logic
newIndex = alphabet.index(char) + shift
# If the decryption leaves the scope of the array, continue at the start of the array
if newIndex > (len(alphabet) - 1):
newIndex = newIndex - len(alphabet)
# Print the decryped character
print(alphabet[newIndex], end='')
|
0702888c98fc07cc48a6f74bd9cbf708bfccfdde | boknowswiki/mytraning | /lc/python/0067_add_binary.py | 926 | 3.5 | 4 | # string
# time O(n)
# space O(n)
class Solution:
def addBinary(self, a, b) -> str:
x, y = int(a, 2), int(b, 2)
while y:
x, y = x ^ y, (x & y) << 1
return bin(x)[2:]
class Solution:
def addBinary(self, a: str, b: str) -> str:
a_len = len(a)
b_len = len(b)
if a_len == 0:
return b
if b_len == 0:
return a
new_a = a[::-1]
new_b = b[::-1]
ret = []
c = 0
cur = 0
while cur < max(a_len, b_len):
val_a = ord(new_a[cur]) - ord("0") if cur < a_len else 0
val_b = ord(new_b[cur]) - ord("0") if cur < b_len else 0
val = (val_a + val_b + c)%2
c = (val_a + val_b + c)//2
ret.append(str(val))
cur += 1
if c:
ret.append(str(c))
#print(f"ret {ret}")
return "".join(ret[::-1])
|
d16ad5c898122f21fe43fcce9801fb08c3cf056e | amolsmarathe/python_programs_and_solutions | /2-Basic_NextConceptsAndNumpy/3-Functions_Basics.py | 2,481 | 4.4375 | 4 | # Functions can be created to perform certain tasks
# Functions can return nothing, or may return single or multiple values
# Function is to be DEFINED and then CALLED
# Types of arg- Formal (defined in function) and Actual (given while calling a function)
# Types of Actual arg- Position, keyword, default, variable length
def add_sub(x, y):
c = x + y
d = x - y
return c, d
result1, result2 = add_sub(10, 15)
print(result1, result2)
print(add_sub(30, 20)) # this prints the tupple of the function output
# Position and Keywordarguments- the function always considers the default sequence of definition and accepts values
# only in that order while calling the function. If you do not know the order, simply define the the values along with
# the name of arg while calling the function
def person(name, age):
print('\n Name is-', name)
print('\n Age is- ', age)
person('Amol', 28) # This works if you know the exact position of the arguments
person(age=28, name='Amol') # this works when you dont know the exact position of the arguments
def person2(name, age=18): # This way, you can define the default value of the argument
print('\n Name is-', name)
print('\n Age is- ', age)
person2('Amol') # In this way, only one argument is sufficient, for the others it takes default value
def sum1(a, *b): # *b now is a variable which is a 'tuple' to be spcific and user can pass any # of args
for n in b:
a = a + n
print('\n Sum1 is- ', a)
sum1(2, 4, 5, 6)
sum1(5, 9)
sum1(10, 20, 30)
def sum2(*b): # *b is now a tuple again. This time only one arg would also work. just note that
# the function definition will change a little bit (we define initial value of a as 0)
a = 0
for n in b:
a = a + n
print('\n Sum2 is- ', a)
sum2(5)
sum2(2, 5)
sum2(2, 4, 7, 9)
def person2(name, *data): # this time again *data can have any number of arg which will form a tuple
print('\n', name) # Problem with this is, we do not know what is the data coming in as args
print(data) # this will print only argument values, we do not know what are they
person2('Amol', 29, 'Pune', 8983495022)
def person3(name, **data): # Now, **data can take 'key=value' pair in the argument and print in the same way
print('\n', name)
print(data) # This will print argument values, along with the key which is passed while calling function
person3('Amol', age=28, city='Pune', mobile=8983495022)
|
5474fc354fe6537e9aee3955705de44462ddcc07 | jsm209/lugmere-s-loss | /encounterGroup.py | 369 | 3.609375 | 4 | # EncounterGroup keeps track of a group of encounters. It is able to store encounters,
# and retrieve random encounters.
import random
class encounterGroup:
def __init__(self):
self.encounters = []
def add(self, encounter):
self.encounters.append(encounter)
def get_random_encounter(self):
return random.choice(self.encounters) |
0f02f68206617afb2655ed694a1d247dd6a3b91c | JamesNgai/qtbot | /utils/dict_manip.py | 1,054 | 3.5 | 4 | import json
from nltk.metrics import edit_distance as ed
def get_closest(word_dict, word):
""" returns the key which matches most closely to 'word' """
# stores keys and their edit distance values
distance_dict = {}
for key in word_dict:
distance_dict[key] = ed(key, word)
# return key w/ least edits
return min(distance_dict, key=distance_dict.get)
def key_with_max_value(d):
"""
a) create a list of the dict's keys and values;
b) return the key with the max value
Shamelessly taken from:
http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary
"""
v = list(d.values())
k = list(d.keys())
return k[v.index(max(v))]
def key_with_min_value(d):
"""
a) create a list of the dict's keys and values;
b) return the key with the max value
Shamelessly taken from:
http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary
"""
v = list(d.values())
k = list(d.keys())
return k[v.index(min(v))]
|
56f6e82e3db7ae91ffe0ad09a56e363ff8d80948 | mozzherina/cherimoya | /event.py | 1,172 | 3.640625 | 4 | from abc import ABC, abstractmethod
from typing import List
from constants import *
class Event(ABC):
"""
Event is base class providing an interface for all subsequent
(inherited) events, that will trigger further events in the
trading infrastructure.
"""
def __init__(self, event_type: Event) -> None:
self._event_type = event_type
@property
def event_type(self) -> Event:
return self._event_type
@abstractmethod
def __str__(self) -> str:
raise NotImplementedError("Should implement __str__()")
class MarketEvent(Event):
"""
Handles the event of receiving a new market update
(new bars become available)
"""
def __init__(self, symbols: List[str], datetime: tpDateTime) -> None:
"""
Parameters:
symbols - List of ticker symbols that have new data.
datetime - The timestamp at which the signal was generated.
"""
super().__init__(EVENT_MARKET)
self._symbols = symbols
self._datetime = datetime
def __str__(self) -> str:
return "MARKET {} at {}".format(self._symbols, self._datetime) |
a2e152e09ee76827469dd796f819987373bd4473 | JoshRU13/Project-105 | /105.py | 460 | 3.765625 | 4 | import math
import csv
with open('data.csv',newline='')as f:
reader=csv.reader(f)
data1=list(reader)
data=data1[0]
def mean(data):
m=len(data)
total=0
for x in data:
total=total+int(x)
mean=total/m
return mean
square=[]
for i in data:
a = int(i)-mean(data)
a= a **2
square.append(a)
some=0
for i in square:
some=some+i
result = some/(len(data)-1)
final=math.sqrt(result)
print(final)
|
7c12bdf3a21e9d2cdc759b91e28b5dad68170bda | MurluKrishna4352/Python-Learning | /palindrome_check def function.py | 418 | 4.03125 | 4 | # def p[alindrome
def palindrome_check(word):
if word == word[::-1]:
return 1
else:
return 0
input_list_no= int(input("Enter number of elements you want in your list : "))
list_1 = []
for i in range(input_list_no + 1):
list_elements = input("Enter element" , str(i + 1) , " : ")
list_1.append(list_elements)
print(list_1)
print(palindrome_check(list_1))
|
8efde4beb616e355b7f191139120cdd8e9458b68 | pewosas/DuongHieu-C4T6 | /list-intro.py | 230 | 4 | 4 | color_list = ["red", "purple", "blue", "orange", "teal"]
while True:
new_color = input("New_color?")
color_list.append(new_color)
print("* " * 10)
for color in color_list:
print(color)
print("* " * 10) |
0435975b01e1a9698ee0f37c11e900055f0da990 | cyang812/leetcode | /20-isValid.py | 1,351 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Author: cyang
# @Date: 2020-09-22 19:49:00
# @Last Modified by: cyang
# @Last Modified time: 2020-09-22 20:47:44
def isValid(s):
c1 = s.count('(')
c2 = s.count(')')
c3 = s.count('[')
c4 = s.count(']')
c5 = s.count('{')
c6 = s.count('}')
print(c1, c2, c3, c4, c5, c6)
if c1 != c2 or c3 != c4 or c5 != c6:
return False
stack = []
size_1 = size_2 = size_3 = 0
for idx in range(len(s)):
temp = s[idx]
if temp == '(' or temp == '[' or temp == '{':
if temp == '(':
size_1 = size_1 + 1
stack.append('(')
elif temp == '[':
size_2 = size_2 + 1
stack.append('[')
elif temp == '{':
size_3 = size_3 + 1
stack.append('{')
elif len(stack):
if temp == ')' and '(' == stack[len(stack) - 1]:
size_1 = size_1 - 1
del stack[len(stack) - 1]
elif temp == ']' and '[' == stack[len(stack) - 1]:
size_2 = size_2 - 1
del stack[len(stack) - 1]
elif temp == '}' and '{' == stack[len(stack) - 1]:
size_3 = size_3 - 1
del stack[len(stack) - 1]
else:
return False
# if len(stack) == 0:
# return True
# else:
# return False
# print(stack)
if size_1 == 0 and size_2 == 0 and size_3 == 0:
return True
else:
return False
if __name__ == '__main__':
testStr = "()"
result = isValid(testStr)
print(result)
|
62daebb185af4bfeb27d0d85bc3ec13c9f52b27b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2068/60654/253820.py | 95 | 3.75 | 4 | a= int(input())
b = int(input())
if a*b >0:
print(a//b)
else:
print(a//b + 1)
|
ccaf5123dc1613be15a4e8d46109bcda85efe318 | MichelleZ/leetcode | /algorithms/python/minimumInitialEnergytoFinishTasks/minimumInitialEnergytoFinishTasks.py | 495 | 3.546875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/
# Author: Miao Zhang
# Date: 2021-05-26
class Solution:
def minimumEffort(self, tasks: List[List[int]]) -> int:
n = len(tasks)
tasks.sort(key = lambda x: (x[1] - x[0]), reverse=True)
res = 0
actual = 0
for act, threshold in tasks:
res = max(res, actual + threshold)
actual += act
return res
|
7c4c593bb4dd93be1ad42d83d0eb38bc3a3a3fed | ordinary-developer/education | /py/m_lutz-programming_python-4_ed/code/ch_03/10-redirecting_streams_to_python_objects/teststreams.py | 372 | 3.5625 | 4 | "read numbers till oef and show squares"
def interact():
print('Hello stream world')
while True:
try:
reply = input('Enter a number>')
except EOFError:
break
else:
num = int(reply)
print("{} squared is {}".format(num, num ** 2))
print('Bye')
if __name__ == '__main__':
interact()
|
813cef8156751c1c858ef39f7f93e2f030904dcb | govardhananprabhu/DS-task- | /Extra.py | 1,230 | 4.09375 | 4 | """
H-5
Given two sorted arrays. There is only 1 difference between the arrays. The first array has one element extra added in between. Find the index of the extra element.
Explanation: The first array has an extra element 9.
The extra element is present at index 4.
In des
First line contain two space integers N,M,size of arrays.
Second line contain N space separated integers,denotes the arr1 elements.
Second line contain M space separated integers,denotes the arr2 elements.
Ot des
print the extra element's index.
Hin
The basic method is to iterate through the whole second array and check element by element if they are different. As the array is sorted, checking the adjacent position of two arrays should be similar until and unless the missing element is found.
T-1500
1 1
3 5 7 9 11 13
3 5 7 11 13
3
7 6
2 4 6 8 9 10 12
2 4 6 8 10 12
4
4 2
1 3 6 8
1 3 4
2
1 1
1
2
0
3 2
1 2 3
1 3
1
"""
def findExtra(arr1, arr2, n) :
for i in range(0, n) :
if (arr1[i] != arr2[i]) :
return i
return n
N,M=map(int,input().split())
arr1 = list(map(int,input().split()))
arr2 = list(map(int,input().split()))
n = len(arr2)
print(findExtra(arr1, arr2, n))
|
e5f1a7c0d33100f373dd67b9668b1252293e661a | Leownhart/My_Course_of_python | /Exercicios/ex067.py | 552 | 4.0625 | 4 | '''67 - Faça um programa que mostre a tabuada de vários números,
um de cada vez, para cada valor digitado pelo usuário.
O programa será interrompido quando o número solicitado for
negativo.'''
cont = 0
while True:
n = int(input('Quer ver a tabuada de qual valor? '))
print('\033[34m=\033[m'*35)
if n <= 0:
break
while cont < 10:
cont += 1
print(f'\033[33m{n:.0f}\033[m x \033[32m{cont:.0f}\033[m= '
f'\033[31m{n*cont:.0f}\033[m')
cont = 0
print('\033[34m=\033[m'*35)
print('Acabou')
|
5705e7444c6d33f95a82d3bfb76500e980eb2ef1 | mike-jolliffe/Learning | /leet_268.py | 560 | 3.78125 | 4 | class Solution(object):
def missingNumber(self, nums):
"""Find number missing from array
:type nums: List[int]
:rtype: int
"""
# Generate a set for reference, from 0 to n
ref_set = set(range(0, len(nums) + 1))
# Return the diff of the sets
return list(ref_set - set(nums))[0]
if __name__ == '__main__':
sol = Solution()
print(sol.missingNumber([0,1,2,4,5])) # 3
print(sol.missingNumber([0,1])) # 2
print(sol.missingNumber([0])) # 1
print(sol.missingNumber([1])) # 0
|
98b4343b21d76144aa82b4745b046c91b61af09c | aatherton/project4 | /py_output.py | 5,322 | 3.5 | 4 |
# coding: utf-8
# In[1]:
# import modules
import pandas
# In[2]:
# declare variables
data = pandas.read_json("purchase_data.json")
data.append(pandas.read_json("purchase_data2.json"))
data.head()
# # Playercount
# In[3]:
print("Total Players: " + str(len(data["SN"].value_counts())))
# # purchasing analysis (total)
# In[4]:
result = pandas.DataFrame({"Number of Unique Items": len(data.drop_duplicates("Item ID")),
"Average Price": data.drop_duplicates("Item ID")["Price"].mean(),
"Number of Purchases": len(data),
"Total Revenue": data["Price"].sum()
}, index = [0])
result["Total Revenue"] = result["Total Revenue"].apply("${:,.2f}".format)
result["Average Price"] = result["Average Price"].apply("${:,.2f}".format)
result
# # Gender Demographics
# In[5]:
result = pandas.DataFrame(data["Gender"].value_counts())
result["Percentage of Players"] = (result["Gender"] / len(data) * 100)
result = result.rename(columns = {"Gender":"Total Count"})
result
# # Purchasing Analysis (Gender)
# In[14]:
result = pandas.DataFrame({"Male": {
"Purchase Count": len(data.loc[data["Gender"] == "Male"]),
"Average Purchase Price": data.loc[data["Gender"] == "Male"]["Price"].mean(),
"Total Purchase Value": data.loc[data["Gender"] == "Male"]["Price"].sum()
}, "Female": {
"Purchase Count": len(data.loc[data["Gender"] == "Female"]),
"Average Purchase Price": data.loc[data["Gender"] == "Female"]["Price"].mean(),
"Total Purchase Value": data.loc[data["Gender"] == "Female"]["Price"].sum()
}, "Other / Non-Disclosed": {
"Purchase Count": len(data.loc[data["Gender"] == "Other / Non-Disclosed"]),
"Average Purchase Price": data.loc[data["Gender"] == "Other / Non-Disclosed"]["Price"].mean(),
"Total Purchase Value": data.loc[data["Gender"] == "Other / Non-Disclosed"]["Price"].sum()}})
result = result.transpose()
result["Average Purchase Price"] = result["Average Purchase Price"].apply("${:,.2f}".format)
result["Total Purchase Value"] = result["Total Purchase Value"].apply("${:,.2f}".format)
result
# # Age Demographics
# In[13]:
result = pandas.DataFrame({"Total Count": {"<10": len(data.loc[data["Age"] < 10])}})
ball = data.drop(data.loc[data["Age"] < 10].index)
for each in range(14, 40, 5):
result = result.append(pandas.Series(data = {"Total Count": len(ball.loc[ball["Age"] <= each])}, name = str(each-4) + "-" + str(each)))
ball = ball.drop(ball.loc[ball["Age"] <= each].index)
result = result.append(pandas.Series(data = {"Total Count": len(ball)}, name = "40+"))
result["Percentage of Players"] = round((result["Total Count"] / len(data)) * 100, 2)
result["Percentage of Players"] = result["Percentage of Players"].apply("{:,.2f}%".format)
result
# # Purchasing Analysis (Age)
# In[8]:
ball = [0,0]
ball[0] = data.loc[data["Age"] < 10]["Price"]
result = pandas.DataFrame({"Purchase Count": {"<10": len(ball[0])}, "Total Purchase Value": {"<10": ball[0].sum()}})
ball[1] = data.drop(ball[0].index)
for each in range(14, 40, 5):
ball[0] = ball[1].loc[ball[1]["Age"] <= each]["Price"]
result = result.append(pandas.Series(data = {"Purchase Count": len(ball[0]), "Total Purchase Value": ball[0].sum()}, name = str(each-4) + "-" + str(each)))
ball[1] = ball[1].drop(ball[0].index)
result = result.append(pandas.Series(data = {"Purchase Count": len(ball[1]), "Total Purchase Value": ball[1]["Price"].sum()}, name = "40+"))
result["Average Purchase Price"] = result["Total Purchase Value"] / result["Purchase Count"]
result["Total Purchase Value"] = result["Total Purchase Value"].apply("${:,.2f}".format)
result["Average Purchase Price"] = result["Average Purchase Price"].apply("${:,.2f}".format)
result
# In[9]:
ball = [0,0]
ball[0] = data["SN"].drop_duplicates()
result = pandas.DataFrame(columns = ["Purchase Count", "Total Purchase Value"])
for each in ball[0]:
ball[1] = data.loc[data["SN"] == each]["Price"]
result = result.append(pandas.Series(data = {"Purchase Count": len(ball[1]), "Total Purchase Value": ball[1].sum()}, name = each))
result = result.sort_values("Total Purchase Value", ascending = False).head(5)
result["Average Purchase Price"] = result["Total Purchase Value"] / result["Purchase Count"]
result["Total Purchase Value"] = result["Total Purchase Value"].apply("${:,.2f}".format)
result["Average Purchase Price"] = result["Average Purchase Price"].apply("${:,.2f}".format)
result
# In[10]:
result = pandas.DataFrame(columns = ["Item ID", "Item Name", "Purchase Count", "Item Price"])
for each in data["Item ID"].drop_duplicates():
ball = data.loc[data["Item ID"] == each]
result = result.append(pandas.Series(data = {"Item ID": each, "Item Name": ball["Item Name"][ball.index[0]], "Purchase Count": len(ball), "Item Price": ball["Price"][ball.index[0]]}), ignore_index = True)
result["Total Purchase Value"] = result["Purchase Count"] * result["Item Price"]
ball = result.sort_values("Total Purchase Value", ascending = False).head(5)
ball["Item Price"] = ball["Item Price"].apply("${:,.2f}".format)
ball["Total Purchase Value"] = ball["Total Purchase Value"].apply("${:,.2f}".format)
ball
# In[12]:
result = ball.sort_values("Purchase Count", ascending = False).head(5)
result
|
bde4780839b308dddbf4b73d94e1220078c7e32c | kristophercasey/Ransomware | /payload/generator/message.py | 3,274 | 3.6875 | 4 | from tkinter import *
TITLE_MESSAGE = "Your files have been encrypted!"
INFO_MESSAGE = "Your files have been encrypted. If you wish to recover them, you need to pay {}$ worth of Bitcoin "\
"and follow the payment instructions. If you don't pay the ransom within {} hours the access to your files " \
"will be permanently lost. Click 'Show files' button to review which files are encrypted."
PAYMENT_MESSAGE = "Your ID: {}\nBitcoin address: {}\nEmail: {}\n\nPay the ransom to the given bitcoin address and send"\
" the transaction alongside with your id to the email address."
DECRYPTION_MESSAGE = "Once the payment is received you will get your decryption key. Insert the key into the box and click 'Decrypt'."
WARNING_MESSAGE = "Do not attempt to decrypt the files yourself! It may cause permanent data loss.\n" \
"Do not rename your files, as it would prevent the decryptor from accessing them.\n"\
"Do not remove this program. You need it for decrypting your files. Otherwise " \
"you will have to redownload it."
def concatenate_message():
return \
TITLE_MESSAGE + "\n" + INFO_MESSAGE + "\n" + PAYMENT_MESSAGE + "\n" + DECRYPTION_MESSAGE + "\n" + WARNING_MESSAGE + "\n"
def generate_default(_id, payment, payment_details, time_limit, contact):
info = INFO_MESSAGE.format(payment, time_limit)
pay = PAYMENT_MESSAGE.format(_id,payment_details,contact)
return TITLE_MESSAGE + "\n" + info + "\n" + pay + "\n" + DECRYPTION_MESSAGE + "\n" + WARNING_MESSAGE + "\n"
class UserMessage(Toplevel):
def __init__(self, _id, time_limit, payment, payment_details, contact, current_message=None):
Toplevel.__init__(self)
self.id = _id
self.time_limit =time_limit
self.payment = payment
self.payment_details = payment_details
self.contact = contact
self.message = current_message if current_message else self.__default_message()
self.geometry('590x450')
self.title("User message generator")
self.resizable(False, False)
self.message_box = Text(self, wrap=WORD, height=25, width=70)
self.message_box.place(x=10, y=10)
self.message_box.insert(INSERT, self.message)
Button(self, text="Save", command=self.__save_message).place(x=200, y=420)
Button(self, text="Clear", command=self.__clear_text).place(x=250, y=420)
Button(self, text="Default", command=self.__generate_default).place(x=300, y=420)
self.message_box.bind("<Return>", self.__save_message)
self.grab_set()
def run(self):
self.wm_deiconify()
self.message_box.focus_force()
self.wait_window()
return self.message
def __default_message(self):
return generate_default(self.id, self.payment, self.payment_details, self.time_limit, self.contact)
def __generate_default(self):
self.message = self.__default_message()
self.__clear_text()
self.message_box.insert(INSERT, self.message)
def __save_message(self):
self.message = self.message_box.get("1.0", "end-1c")
self.destroy()
def __clear_text(self):
self.message_box.delete('1.0', END)
|
69d955821edadda5fa188e2507f894ff6ff119e0 | AndrejusAnto/tvwatch | /series.py | 12,267 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
from threading import Thread
from datetime import datetime
from typing import Union
import imdb
import json
import os
import copy
import sys
import logging
tod = datetime.today()
listtod = [tod.year, tod.month, tod.day]
ia = imdb.IMDb()
convertmonths = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December",
}
"""testuoju static typing dėl hint'ų
Union[list, str] reiškia, kad funkcija convert_dates gali priimti tiek list'ą,
tiek string'ą ir taip grąžinti tiek list'ą, tiek string'ą"""
def convert_dates(dates: Union[list, str]) -> Union[list, str]:
if type(dates) == list:
if len(dates) != 1:
dates[1] = convertmonths[dates[1]]
return " ".join([str(x) for x in dates])
else:
return str(dates[0])
elif type(dates) == str:
ndates = dates.split()
if len(ndates) != 1:
nconvertmonths = {value: key for (key, value) in convertmonths.items()}
ndates[1] = nconvertmonths[ndates[1]]
nd = [int(x) for x in ndates]
return nd
else:
nd = [int(x) for x in ndates]
return nd
watchseries = [
"Attack on Titan",
"Better Call Saul",
"Black Mirror",
"Brooklyn Nine-Nine",
"Killing Eve",
"Lucifer",
"One Punch Man",
"Star Trek: Picard",
"Stranger Things",
"The Blacklist",
"The Good Doctor",
"The Grand Tour",
"The Mandalorian",
"The Orville",
# "The Witcher",
# "Westworld",
# "Goliath",
# "Doom Patrol",
# "F Is for Family",
# "The Boys",
# "The Expanse",
# "The Umbrella Academy",
# "Curb Your Enthusiasm",
# "His Dark Materials",
# "Warrior",
# "Avenue 5",
# "Superman and Lois",
# "The Falcon and the Winter Soldier",
# "Dexter",
# "Invincible",
# "Loki",
# nepamirsti kad daugiau nei 29 mes errora
]
dictseries = {}
def pirmasal(tod, ed):
if ed != {}:
pirmasalis = list(ed.keys())[0]
data = convert_dates(ed[pirmasalis])
return data
else:
return ed
def getrd(rd):
countrydate = {}
for reldate in rd['raw release dates']:
dates = list(reversed(reldate["date"].split()))
sdates = " ".join(dates)
countryname = reldate['country'].rstrip("\n")
if countryname == "USA":
countryname = "United States"
if countryname == "UK":
countryname = "United Kingdom"
countrydate[countryname] = sdates
for k, v in countrydate.items():
countrydate[k] = convert_dates(v)
sortedcd = dict(sorted(countrydate.items(), key=lambda x: x[1]))
return sortedcd
def sorted_dates(cntr, cd, sic):
sortedcountries = dict(sorted(cntr.items(), key=lambda x: x[1]))
pirmasalis = list(sortedcountries.values())[0]
for country, date in cd.copy().items():
if date < pirmasalis:
del cd[country]
cd_tuples = list(cd.items())
for country, date in cd.items():
if country in sic:
if date <= cd_tuples[0][1]:
cd_tuples.remove((country, date))
cd_tuples.insert(0, (country, date))
sortedcdn = dict(cd_tuples)
return sortedcdn
def collect_series(tv, d):
try:
seriesdict = {}
ifserie = True
tvseries = ia.search_movie(tv)
for serie in tvseries:
if ifserie:
seriesid = serie.movieID
serieinfo = ia.get_movie(seriesid)
serieyear = serieinfo["series years"]
if ("tv" and "series") in serieinfo['kind'] and tv == serieinfo['title']:
ifserie = False
pavad = f'{serieinfo["title"]} | {serieyear} | ID{seriesid}'
print(pavad)
seriesdict[pavad] = {}
ia.update(serieinfo, 'episodes')
seasonlist = [s for s in sorted(serieinfo['episodes'].keys()) if s > 0]
for s in seasonlist:
sstring = f"S{s}"
seriesdict[pavad][sstring] = {}
print("episodes number", len(serieinfo['episodes'][s]))
for e in serieinfo['episodes'][s]:
estring = f"E{e}"
episodeid = serieinfo['episodes'][s][e].movieID
seriesdict[pavad][sstring][estring] = {}
releasedate = ia.get_movie_release_dates(episodeid)['data']
if releasedate:
sortedcd = getrd(releasedate)
countries = {k: v for (k, v) in sortedcd.items() if k in serieinfo['countries']}
if countries:
sortedcdn = sorted_dates(countries, sortedcd, serieinfo['countries'])
for k, v in sortedcdn.items():
sortedcdn[k] = convert_dates(v)
seriesdict[pavad][sstring][estring][serieinfo['episodes'][s][e]['title']] = sortedcdn
d.update(seriesdict)
else:
for k, v in sortedcd.items():
sortedcd[k] = convert_dates(v)
seriesdict[pavad][sstring][estring][serieinfo['episodes'][s][e]['title']] = sortedcd
d.update(seriesdict)
else:
seriesdict[pavad][sstring][estring][serieinfo['episodes'][s][e]['title']] = {}
d.update(seriesdict)
else:
continue
except KeyError:
pass
def add_new(sie, d, sk, sa, series):
atjsez = [s for s in sa if s not in sk]
epzsk = [len(sie['episodes'][x]) for x in atjsez]
for s, e in zip(atjsez, epzsk):
laikepz = {}
laiksez = {}
for ee in range(1, e + 1):
laikdata = {}
episodeid = sie['episodes'][s][ee].movieID
epzname = sie['episodes'][s][ee]['title']
releasedate = ia.get_movie_release_dates(episodeid)['data']
sstring = f"S{s}"
estring = f"E{ee}"
if releasedate:
sortedcd = getrd(releasedate)
countries = {k: v for (k, v) in sortedcd.items() if k in sie['countries']}
if countries:
sortedcdn = sorted_dates(countries, sortedcd, sie['countries'])
for k, v in sortedcdn.items():
sortedcdn[k] = convert_dates(v)
laikdata = {epzname: sortedcdn}
laikepz[estring] = laikdata
laiksez[sstring] = laikepz
d[series].update(laiksez)
else:
for k, v in sortedcd.items():
sortedcd[k] = convert_dates(v)
laikdata = {epzname: sortedcd}
laikepz[estring] = laikdata
laiksez[sstring] = laikepz
d[series].update(laiksez)
else:
laikdata = {epzname: {}}
laikepz[estring] = laikdata
laiksez[sstring] = laikepz
d[series].update(laiksez)
def update_old(d, series, s, e, ep, sei):
episodeid = sei['episodes'][int(s[1:])][int(e[1:])].movieID
epzname = sei['episodes'][int(s[1:])][int(e[1:])]['title']
releasedate = ia.get_movie_release_dates(episodeid)['data']
if releasedate:
if epzname != ep:
d[series][s][e][epzname] = d[series][s][e].pop(ep)
sortedcd = getrd(releasedate)
countries = {k: v for (k, v) in sortedcd.items() if k in sei['countries']}
if countries:
sortedcdn = sorted_dates(countries, sortedcd, sei['countries'])
for k, v in sortedcdn.items():
sortedcdn[k] = convert_dates(v)
d[series][s][e].update({epzname: sortedcdn})
else:
for k, v in sortedcd.items():
sortedcd[k] = convert_dates(v)
d[series][s][e].update({epzname: sortedcd})
def update_series(series, data):
seriesinfo = copy.deepcopy(data[series])
seriesy = [i.strip() for i in series.split("|")][1]
seriesy = [i for i in seriesy.split("-") if i.isdigit()]
if len(seriesy) < 2:
aratn = True
serieinfo = True
sezatn = []
seriesid = [i.strip() for i in series.split("|")][-1]
seriesid = "".join([i for i in seriesid if i.isdigit()])
sezsk = [int(x[1:]) for x in seriesinfo.keys()]
for sezonas, sezonoi in seriesinfo.items():
for epizodas, epizodoi in sezonoi.items():
for epizodopavad, epizododatos in epizodoi.items():
atr = pirmasal(listtod, epizododatos)
if "Episode #" in epizodopavad:
if (len(atr) == 0) or (len(atr) == 3):
if aratn:
print(series)
aratn = False
print("Atnaujinama")
serieinfo = ia.get_movie(seriesid)
ia.update(serieinfo, 'episodes')
sezatn = [s for s in sorted(serieinfo['episodes'].keys()) if s > 0]
if sezsk != sezatn:
add_new(serieinfo, data, sezsk, sezatn, series)
else:
# if sezsk != sezatn
# if (len(atr) == 0) or (len(atr) == 3)
update_old(data, series, sezonas, epizodas, epizodopavad, serieinfo)
else:
# if (len(atr) == 0) or (len(atr) == 3) salyga
if (listtod[0] == atr[0]) and (listtod > atr):
if aratn:
print(series)
aratn = False
print("Atnaujinama")
serieinfo = ia.get_movie(seriesid)
ia.update(serieinfo, 'episodes')
sezatn = [s for s in sorted(serieinfo['episodes'].keys()) if s > 0]
if sezsk != sezatn:
add_new(serieinfo, data, sezsk, sezatn, series)
else:
update_old(data, series, sezonas, epizodas, epizodopavad, serieinfo)
else:
# if "Episode #" in epizodopavad salyga
if int(sezonas[1:]) == sezsk[-1]:
if len(atr) == 0 or (listtod >= atr):
if aratn:
print(series)
aratn = False
print("Atnaujinama")
serieinfo = ia.get_movie(seriesid)
ia.update(serieinfo, 'episodes')
sezatn = [s for s in sorted(serieinfo['episodes'].keys()) if s > 0]
if sezsk != sezatn:
add_new(serieinfo, data, sezsk, sezatn, series)
else:
# if sezsk != sezatn salyga
update_old(data, series, sezonas, epizodas, epizodopavad, serieinfo)
else:
# if int(sezonas[1:]) == sezsk[-1] salyga
continue
def atvaizdavimas(d):
dictser = {}
max_l = []
ll = []
stdout_fileno = sys.stdout
# Redirect sys.stdout to the file
sys.stdout = open(f'{tod.year}_{tod.month}_{tod.day}.txt', 'wt')
for serie, info in d.items():
for sez, sezi in info.items():
for epz, epzi in sezi.items():
for epzpav, epzd in epzi.items():
laikdate = {}
for sal, dt in epzd.items():
ndt = convert_dates(dt)
if (len(ndt) == 3) and ndt >= listtod:
laikdate.update({sal: ndt})
dictser.update({serie + ">" + sez + ">" + epz + ">" + epzpav: laikdate})
lent = len(sez + epz + epzpav) + 7 * 2
max_l.append(lent)
sort_orders = dict(sorted(dictser.items(), key=lambda x: list(x[1].values())))
max_v = max(max_l)
for s, d in sort_orders.items():
serie, sez, epz, epzname = s.split(">")
lines = "-" * max_v
ifpop = "true" if len(ll) == 1 else "false"
ll.append(serie)
if (len(ll) == 1) or (ll[0] != ll[1]):
sys.stdout.write(lines + '\n')
stdout_fileno.write(lines + '\n')
sys.stdout.write(serie + '\n')
stdout_fileno.write(serie + '\n')
sys.stdout.write(f"***** {sez} {epz} {epzname} *****\n")
stdout_fileno.write(f"***** {sez} {epz} {epzname} *****\n")
for sal, dat in d.items():
ndat = convert_dates(dat)
sys.stdout.write(f' {sal} {ndat}\n')
stdout_fileno.write(f' {sal} {ndat}\n')
if ifpop == "true":
ll.pop(0)
else:
sys.stdout.write(f"***** {sez} {epz} {epzname} *****\n")
stdout_fileno.write(f"***** {sez} {epz} {epzname} *****\n")
for sal, dat in d.items():
ndat = convert_dates(dat)
sys.stdout.write(f' {sal} {ndat}\n')
stdout_fileno.write(f' {sal} {ndat}\n')
ll.pop(0)
sys.stdout.write("-" * max_v + "\n")
stdout_fileno.write("-" * max_v + "\n")
# Close the file
sys.stdout.close()
# Restore sys.stdout to our old saved file handler
sys.stdout = stdout_fileno
def main():
if not os.path.isfile("data_file.json"):
threads = []
for tvserie in watchseries:
threads.append(Thread(target=collect_series, args=(tvserie, dictseries)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
atvaizdavimas(dictseries)
with open("data_file.json", "w") as write_file:
dictseriesn = dict(sorted(dictseries.items()))
json.dump(dictseriesn, write_file, ensure_ascii=False, indent=4)
else:
threads = []
with open("data_file.json", "r") as read_file:
data = json.load(read_file)
seriesn = {i.split(" | ")[0]: i for i in list(data.keys())}
for tvserie in watchseries:
if tvserie in list(seriesn.keys()):
threads.append(Thread(target=update_series, args=(seriesn[tvserie], data)))
else:
threads.append(Thread(target=collect_series, args=(tvserie, data)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
atvaizdavimas(data)
with open("data_file.json", "w") as write_file:
data = dict(sorted(data.items()))
json.dump(data, write_file, ensure_ascii=False, indent=4)
if __name__ == "__main__":
main()
|
cb7ec5a8c46a0546a2bcc121089208703be9f8ad | at-bradley/python_Main | /Sublime/TIY6b.py | 2,381 | 3.9375 | 4 | print ("\n") #6-3 p.102:
from pprint import pprint #Stackoverflow.
programming_words = {
'list': 'Items enclosed in [] brackets.',
'list_comprehension':'A simpler way to construct lists.',
'tuple':'A list of immutable objects, enclosed in () brackets.',
'pep 8':'Style guide for Python code.',
'slice':'A specific position to start, stop, increment. In lists/tuples.',
'key': 'First part of an item in a dictionary. Coupled with value.',
'value': 'Second part of an item in a dictionary. Coupled with key.',
'pprint': '"Pretty print". Nicely formats a list for output.',
}
pprint (programming_words)
#print "\nIndividual keys below:".title()
#print programming_words['list']
#print programming_words['list_comprehension']
#print programming_words['tuple']
#print programming_words['pep 8']
#print programming_words['slice']
print ("\n") #6-4 Glossary 2:
for key, value in programming_words.items():
print ("\nKey: " + key)
print ("Value: " + value)
print ("\n")
print ("\n") #6-5. Rivers:
major_rivers__countries = {
'nile': 'egypt',
'yangtze': 'china',
'amazon': 'south america', #brazil, peru, columbia.
}
pprint (major_rivers__countries)
for river, country in major_rivers__countries.items():
print (("The " + river + " flows through " + country + ".").title())
#for rivers in major_rivers__countries.items():
#print (river)
for river in major_rivers__countries.keys():
print (river.title())
#for countries in major_rivers__countries.items():
#print (country)
for country in major_rivers__countries.keys():
print (country.title())
print ("\n") #6-6. Polling:
favorite_languages = {
'marlon': 'java',
'stephen': 'sql',
'anthony':'python',
'marcus': 'c',
}
print (favorite_languages)
pollers = {'marlon', 'fernando', 'marcus', 'andrew', 'mike'}
for name in sorted(pollers):
if name in favorite_languages:
print ("Thank you for participating in our survey, "
+ name.title() + ".")
else:
print ("Please take our survey, " + name.title() + ".")
"""for name in pollers:
if name in pollers:
print (name + "Please take our survey.")
"""
"""for name, language in favorite_languages:
if name in favorite_languages:
print ("Thank you " + name + " for participating in our survey.")
if name not in favorite_languages:
print ("Please take our survey.")
""" |
4ac0cb071c5b70181f5d00fd568b6018a20f4d23 | juraj-kajaba/MITx_6_00_2x | /Item.py | 1,527 | 3.59375 | 4 | from functools import total_ordering
import sys
#I used decorators for getters and setter just to practise them. I know they should not have them as I can acess them directly in Python
@total_ordering
class Item:
def __init__(self, name, weight, value):
self._weight = weight
self._value = value
self._name = name
@property
def name(self):
return self._name
@property
def weight(self):
return self._weight
@property
def value(self):
return self._value
@name.setter
def name(self, name):
self._name = name
@weight.setter
def weight(self, weight):
self._weight = weight
@value.setter
def value(self, value):
self._value = value
# To get nicer output in print function
def __repr__(self):
return '{}: {} {} {}'.format(self.__class__.__name__,
self._name,
self._weight,
self._value)
def metric1(self):
try:
return self._value / self._weight
except ZeroDivisionError as e:
return sys.maxsize
def metric2(self):
return (-1)*self._weight
def metric3(self):
return self._value
# for @total_ordering decorator
def __eq__(self, other):
return self.metric() == other.metric()
# for @total_ordering decorator
def __lt__(self, other):
return self.metric() < other.metric()
|
ad9a1c16c133627450dee835fabb62830b9a823d | JakubKazimierski/PythonPortfolio | /AlgoExpert_algorithms/Hard/KnapsackProblem/test_KnapsackProblem.py | 915 | 3.84375 | 4 | '''
Unittests for KnapsackProblem.py
March 2021 Jakub Kazimierski
'''
import unittest
from KnapsackProblem import knapsackProblem
class test_KnapsackProblem(unittest.TestCase):
'''
Class with unittests for KnapsackProblem.py
'''
def setUp(self):
'''
Sets up input.
'''
self.input_items = [[1, 2], [4, 3], [5, 6], [6, 7]]
self.capacity = 10
self.output = [10, [1, 3]]
return self.input_items, self.capacity, self.output
# region Unittests
def test_user_input(self):
'''
Checks if method works properly.
'''
items, capacity, output = self.setUp()
output_method = knapsackProblem(items, capacity)
self.assertEqual(output, output_method)
# endregion
if __name__ == "__main__":
'''
Main method for test cases.
'''
unittest.main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.