blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f62937a59fc575cc074780bbf33d09be33edb0c4 | markfmccormick/ChessBaxter | /create_board_string.py | 4,776 | 3.71875 | 4 | """
Takes the 64 length array of board position piece classifications and
constructs the FEN notation for the board state
see: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
Example of results, the input to the function
results = ["rook","knight","bishop","queen","king","bishop","knight","rook",
"pawn","pawn","pawn","pawn","pawn","pawn","pawn","pawn",
"square","square","square","square","square","square","square","square",
"square","square","square","square","square","square","square","square",
"square","square","square","square","square","square","square","square",
"square","square","square","square","square","square","square","square",
"PAWN","PAWN","PAWN","PAWN","PAWN","PAWN","PAWN","PAWN",
"ROOK","KNIGHT","BISHOP","QUEEN","KING","BISHOP","KNIGHT","ROOK"]
"""
def create_board_string(results):
current_state_of_the_board = ""
consecutive_empty_square_counter = 0
for c in range(0,64):
if c%8 == 0:
if c != 0:
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "/"
if results[c] == "king":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "k"
elif results[c] == "KING":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "K"
elif results[c] == "queen":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "q"
elif results[c] == "QUEEN":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "Q"
elif results[c] == "knight":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "n"
elif results[c] == "KNIGHT":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "N"
elif results[c] == "bishop":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "b"
elif results[c] == "BISHOP":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "B"
elif results[c] == "pawn":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "p"
elif results[c] == "PAWN":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "P"
elif results[c] == "rook":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "r"
elif results[c] == "ROOK":
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
consecutive_empty_square_counter = 0
current_state_of_the_board += "R"
else:
consecutive_empty_square_counter += 1
if consecutive_empty_square_counter != 0:
current_state_of_the_board += str(consecutive_empty_square_counter)
return current_state_of_the_board
|
857b96d69fa3d39f3f86c8930522ffc29f57c2ec | yhyecho/Python3 | /day03/mapReduce.py | 1,597 | 4.3125 | 4 | # map/reduce
# Python内建了map()和reduce()函数
# 1. map
# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
L = list(r)
print(L)
# map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。
# 不需要map()函数,写一个循环,也可以计算出结果:
L2 = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
L2.append(f(n))
print(L2)
# 的确可以,但是,从上面的循环代码,能一眼看明白“把f(x)作用在list的每一个元素并把结果生成一个新的list”吗?
# 把这个list所有数字转为字符串:
L3 = list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(L3)
# reduce
# reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
# 比方说对一个序列求和,就可以用reduce实现:
from functools import reduce
def add(x, y):
return x + y
L4 = reduce(add, [1, 3, 5, 7, 9])
print(L4)
# 把序列[1, 3, 5, 7, 9]变换成整数13579,reduce就可以派上用场:
def fn(x, y):
return x * 10 + y
L5 = reduce(fn, [1, 3, 5, 7, 9])
print(L5)
# 假设Python没有提供int()函数,你完全可以自己写一个把字符串转化为整数的函数,而且只需要几行代码!
|
20744c39976f8aedf68bc5d90f1115d208a5f9b0 | standrewscollege2018/2021-year-11-classwork-Hellolightn3ss | /bidding auction.py | 710 | 4.0625 | 4 |
auction = input("what item is up for sale today?")
Reserve_price = input("what is the reserve price")
print("The auction for the", auction,"has begun with the reserve price of $",Reserve_price,)
name = input("whats your name?")
bid = int(input("what's your bid? input as interger"))
condition = 1
true = 1
admin =("admin")
while condition is true:
print("Highest bid so far is",name,"with $", bid)
name2 = input("whats your name?")
bid2 = int(input("what's your bid? input as interger"))
if bid2 > bid:
bid = bid2
name = name2
if bid2 == -1 and name2 == admin:
print("congradulations to", name,"for winning", auction,"for $",bid)
condition = 2
|
fef62cf65b04092023dfb0175155eaecc766cf9d | beatrizwang/advent_of_code_2020 | /day02/solution.py | 1,488 | 3.71875 | 4 | import re
import pprint
def get_lines():
with open('day02\input.txt', 'r') as input_file:
lines = [line.rstrip().split(':') for line in input_file]
return lines
def count_valid_passwords_by_letter_count(lines):
count_valid_pass = 0;
for line in lines:
required_letter = line[0][-1]
min_rep, max_rep = re.findall('\d+', line[0])
password = line[1]
count_required_letters = password.count(required_letter)
if count_required_letters <= int(max_rep) and count_required_letters >= int(min_rep):
count_valid_pass += 1
return count_valid_pass
def count_valid_passwords_by_letter_position(lines):
count_valid_pass = 0;
for line in lines:
required_letter = line[0][-1]
first_position, second_position = re.findall('\d+',line[0])
password = line[1]
first_letter = password.strip()[int(first_position) - 1]
second_letter = password.strip()[int(second_position) - 1]
if ((first_letter == required_letter and second_letter != required_letter) or
(first_letter != required_letter and second_letter == required_letter)):
count_valid_pass += 1
return count_valid_pass
def main():
lines = get_lines()
print('Solution to first puzzle: ' + str(count_valid_passwords_by_letter_count(lines)))
print('Solution to second puzzle: ' + str(count_valid_passwords_by_letter_position(lines)))
if __name__ == '__main__':
main()
|
60bd29af7047f6234d46cb0c53f9db39a18c636b | leihuagh/python-tutorials | /books/AutomateTheBoringStuffWithPython/Chapter03/PracticeProjects/P01_make_collatz_seq.py | 859 | 4.59375 | 5 | # This program makes a Collatz Sequence for a given number
# Write a function named collatz() that has one parameter named number.
# If number is even, then collatz() should print number // 2 and return this value.
# If number is odd, then collatz() should print and return 3 * number + 1.
# Then write a program that lets the user type in an integer and that keeps calling
# collatz() on that number until the function returns the value 1.
# Sample output:
# Enter number:
# 3
# 10
# 5
# 16
# 8
# 4
# 2
# 1
def collatz(number):
if not number % 2:
return number // 2
else:
return 3 * number + 1
def main():
n = int(input("Input a number: "))
while n != 1:
print(n)
n = collatz(n)
print(n) # When n == 1
# If program is run (instead of imported), call main():
if __name__ == "__main__":
main()
|
8761b9ea4862c5cb8801e75a560e171466bcc983 | SRKACDGLD/Assignment2.2 | /Assignment2.2.py | 1,110 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 14:56:07 2018
@author: krishna.i
Assignment 2.2: Create the below pattern using nested for loop in Python.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
starval= 5 # Initialization of starval variable to set max stars needed
if(starval > 0): # check if Starval is greater than zero
tempnum = 1 # taking tempnum varialble initialized with 1
while tempnum <= starval : #iterating till tempnum is less than or equal to starval
i=1 # taking another variable to start iterating till starval value
while i <=tempnum : # Iterating from one star till starval is reached
print("*",sep=' ',end=' ')
i=i+1
print("",end='\n')
tempnum = tempnum + 1
tempnum=tempnum - 2
while tempnum >=1:
j=tempnum
while j >=1: # Iterating from four stars till 1 star is printed
print("*",sep=' ',end=' ')
j=j-1
print("",end='\n')
tempnum=tempnum-1
|
73021ba5b35bac7ecabc89c2ae3d0d071efbf376 | cbass2404/bottega_classwork | /python/notes/conditionals.py | 2,723 | 3.859375 | 4 | # answer = False
#
# if answer == False:
# answer = True
#
# print(answer)
# def watermelonparty(watermelons):
# if watermelons > 50:
# print(True)
# else:
# print(False)
#
#
# watermelonparty(51)
# def kid(age):
# if age > 15:
# print('You can get a license')
# elif age == 15:
# print("You can get a permit, but can't get a license")
# else:
# print("You are not old enough for a permit or license.")
#
# kid(14)
# kid(15)
# kid(16)
# role = 'guest'
#
# auth = 'can access' if role == 'admin' else 'cannot access'
#
# # if role == 'admin':
# # auth = 'can access'
# # else:
# # auth = 'cannot access'
#
# print(auth)
# def ageverification(age):
# if age > 25:
# print('can rent a car')
# else:
# print("can't rent a car")
# def ageverification(age):
# print("Can rent a car") if age > 25 else print("Can't rent a car")
#
#
# ageverification(26)
# ageverification(25)
# checking if a value is in a string or list
# sentence = 'The quick brown fox jumped over the lazy Dog'
# word = 'dog'
#
# if word.lower() in sentence.lower():
# print('The word is in the sentence')
# else:
# print('The word is not in the sentence')
#
#
# nums = [1, 2, 3, 4]
#
# if 3 in nums:
# print('The number was found')
# else:
# print('The number was not found')
# sentence = 'Python is the best!'
#
# def word_finder(word, variable):
# if word in variable:
# print('The word is in the sentence')
# else:
# print('The word is not in the sentence')
#
#
# word_finder('Python', sentence)
# word_finder('Balloon', sentence)
# nums = [1, 2, 3, 4]
#
# def item_finder(num, list_name):
# if num in list_name:
# print(f"{num} found.")
# else:
# print(f"{num} not found")
#
#
# item_finder(2, nums)
# item_finder(0, nums)
# compound conditionals in python
# username = 'jonsnow'
# email = 'jon@snow.com'
# password = 'thenorth'
#
# if username == 'jonsnow' and password == 'thenorth':
# print('Access permitted')
# else:
# print('Not allowed')
#
#
# if (username == 'jonsnow' or email == 'jon@snow.com') and password == 'thenorth':
# print('Access permitted')
# else:
# print('Not allowed')
#
#
# if username == 'jonsnow' or password == 'thenorth':
# print('Access permitted')
# else:
# print('Not allowed')
#
#
# logged_in = True
# standard_user = False
#
# if logged_in and not standard_user:
# print('You can access the admin dashboard')
# else:
# print('You can only access the standard dashboard')
# a = 200
# b = 33
# c = 500
# if a > b and a < c:
# print("Both conditions are True")
#
# if a > b or a > c:
# print("At least one of the conditions are True")
|
250246634ba80001c733ece18989763e91ed69c3 | changdaeoh/Algorithm_study | /ch9_Stack_Queue/Q21_Remove_Duplicate_Letters.py | 2,753 | 3.6875 | 4 | '''
Given a string s, remove duplicate letters so that every letter appears once and only once.
You must make sure your result is the smallest in lexicographical order among all possible results.
Input: s = "bcabc"
Output: "abc"
Input: s = "cbacdcbc"
Output: "acdb"
Constraint
* 1 <= s.length <= 10^4
* s consists of lowercase English letters.
'''
# solution 1 - 재귀구조 이용
def remover(s:str)->str:
for char in sorted(set(s)):
suffix = s[s.index(char):]
# 전체집합과 접미사 집합이 일치할 때 분리 진행
if set(s) == set(suffix):
return char + remover(suffix.replace(char, ''))
return ''
'''
unique 문자들을 오름차순으로 저장하고 하나씩 원 문자열에서 검색
해당 unique 문자 인덱스부터 시작하여 문자열 끝까지를 대상으로 모든 다른 unique 문자 포함하면 check it
그 문자를 output에 추가. 나머지(뒤에나오는 동일문자) 전부제거
-반복-
(재귀 호출시 조건을 만족할때마다 하나의 문자는 전부 제거되므로
input되는 문자열에 포함되어있는 unique 문자수도 하나씩 줄어듬)
'''
# solution 2
def remover(s:str) -> str:
counter, seen, stack = collections.Counter(s), set(), []
for char in s:
counter[char] -= 1 # 순회될 때마다 count 1씩 감소
if char in seen: # 한번이라도 순회한 문자 만나면 일단 다음인덱스로 건너뜀
continue
# 조건 : stack에 문자가 있고, 새로 조회한 문자가 stack의 가장 위 문자보다 더 빠르며,
# 그 stack 가장 위의 문자가 뒤에 또 나온다면. 제거 쌉가능이다 이말이야
while stack and char < stack[-1] and counter[stack[-1]] > 0:
seen.remove(stack.pop()) # 해당 문자를 stack에서도 꺼내고 seen에서도 제거해버림
stack.append(char) # 별 일 없으면 문자 stack에 추가
seen.add(char) # 고유한 문자 seen 집합에 추가
return ''.join(stack)
'''
필요한 객체들
- cnt 사전 -> 순회시마다 횟수 (-). 남은 출현횟수 확인용
- seen -> stack에 고유한 문자만 저장하고, 불필요한 조건확인 줄이기 위해 집합자료형 만들기
- stack 순차적으로 쌓아가며 range 1범위 내에서 넣다뺐다가능. 최종출력 문자목록으로 사용
stack 업데이트 발동 조건 3개
- stack이 비어있지 않음
- stack에 쌓여있는 가장 마지막 문자보다 현재 순회중인 문자가 더 빨라야함
- stack에 쌓여있는 가장 마지막 문자가 남은 문자열에 또 있어야함 (cnt로 알 수 있음)
''' |
bd183d2c8eea7914e089146afa301d966cf9fd22 | arnabs542/Leetcode-18 | /199. Binary Tree Right Side View.py | 886 | 4.09375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
bfs = [root]
res = []
if not root:
return res
while bfs:
tmp_bfs = []
res.append(bfs[-1].val)
for node in bfs:
if node.left:
tmp_bfs.append(node.left)
if node.right:
tmp_bfs.append(node.right)
bfs = tmp_bfs
return res
'''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Solution: BFS, level, traversal
Time: O(n)
Space: O(n)
'''
|
b8ae7b6929a2bbb6a1ef194f03a6a9bb6330e271 | clemg/aoc2020 | /AdventofCode/08/8.py | 1,614 | 3.5 | 4 | with open("input", "r") as fi:
file = [line.strip() for line in fi]
# Part 1
def part1():
ptr = 0
acc = 0
already_done = []
while True:
if ptr not in already_done:
already_done.append(ptr)
value = int(file[ptr].split(" ")[1])
if file[ptr].startswith("nop"):
ptr += 1
elif file[ptr].startswith("acc"):
acc += value
ptr+=1
elif file[ptr].startswith("jmp"):
ptr += value
else:
break
return acc
# Part 2
def part2():
potentials = []
for instruction in range(len(file)):
if not file[instruction].startswith("acc"):
potentials.append(instruction)
for potential in potentials:
ptr = 0
acc = 0
already_done = []
while True:
if ptr in already_done:
break
already_done.append(ptr)
value = int(file[ptr].split(" ")[1])
if file[ptr].startswith("nop"):
if ptr != potential:
ptr += 1
else:
ptr += value
elif file[ptr].startswith("acc"):
acc += value
ptr += 1
elif file[ptr].startswith("jmp"):
if ptr == potential:
ptr += 1
else:
ptr += value
if ptr == len(file):
return acc
print(part1(), part2())
|
e5b87f47632b42e94468628729f7729e496acb0c | hhonasoge/ds_algos | /queue.py | 1,022 | 4.15625 | 4 | import linked_list
class Queue:
def __init__(self):
self.queue=linked_list.LinkedList()
self.last=None
self.first=None
def isEmpty(self):
return self.last==None
def enqueue(self, data):
node=linked_list.Node(data)
if self.isEmpty():
self.queue.add_node_by_obj(node)
self.last=node
self.first=node
return
self.last.next=node
self.last=node
def dequeue(self):
if self.isEmpty():
raise ValueError("queue is empty")
rv=self.queue.getFirstElement()
self.queue.remove_first_element()
return rv
def __str__(self):
return self.queue.__str__()
def length(self):
return self.queue.length()
if __name__=="__main__":
queue=Queue()
print(queue.isEmpty())
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue)
for i in range(queue.length()):
print(queue.dequeue())
print(queue.isEmpty())
|
49b6909079349350d03f13015472f4cc1eed8da5 | stenioaraujo/cracking-interview | /chapter1/008/main.py | 1,354 | 3.796875 | 4 | def main():
matrix = [
[1,1,1,1],
[2,2,0,2],
[3,0,3,3],
[4,4,4,4]
]
print_matrix(matrix)
matrix = [
[1,1,1],
[2,0,2],
[3,3,3]
]
print_matrix(matrix)
matrix = [
[1,1],
[2,0]
]
print_matrix(matrix)
matrix = [
[1]
]
print_matrix(matrix)
matrix = [
[]
]
print_matrix(matrix)
def zero(matrix):
if len(matrix) == 0:
return
num_lines = len(matrix)
num_cols = len(matrix[0])
lines = [False] * num_lines
columns = [False] * num_cols
for i in range(num_lines):
for j in range(num_cols):
if matrix[i][j] == 0:
lines[i] = True
columns[j] = True
for i, should_zero in enumerate(lines):
if should_zero:
zeroLine(matrix, i)
for j, should_zero in enumerate(columns):
if should_zero:
zeroColumn(matrix, j)
def zeroLine(matrix, i):
for j in range(len(matrix[0])):
matrix[i][j] = 0
def zeroColumn(matrix, j):
for i in range(len(matrix)):
matrix[i][j] = 0
def print_matrix(matrix):
for l in matrix:
print(l)
print("--------------------")
zero(matrix)
for l in matrix:
print(l)
print("===================+")
main() |
c5224b57e783016e44d505ddd8a1eb571c74cabf | Geethachundru/CS17B009_PYTHON99prolog | /99py6.py | 57 | 3.71875 | 4 | my_list=[1,2,3,8,1]
a=my_list[::-1]
print(a==my_list)
|
f963e5c3771e2ea201ad4594a371239a5e4fe27b | Feedmemorekurama/py_course_bernadska | /homework_bernadska/hw_1/task_3.py | 156 | 3.671875 | 4 | number = 567
nextnumber = (number +1)
lastnumber = (number -2)
print("Your number:" ,number, "your nextnumber:" ,nextnumber, 'your lastnumber:' ,lastnumber) |
9177ca1eb2409f43fe96a64588d70257c95a6c1e | joseruben123/EstructuraDatos | /S15-TAREA_4-Ejercicios_Clases/lista.py | 1,548 | 3.859375 | 4 | class lista:
def __init__(self,tamanio=3):
self.lista=[]
self.longitud=0
self.size=tamanio
def append(self,dato):
if self.longitud<self.size:
self.lsita +=[dato]
self.longitud+=1
else:
print("Lista esta llena")
def obtener(self,pos):
self.mostrar()
if pos <0 or pos >=self.longitud:
return None
else:
return self.lista[pos]
def obtenerEliminado(self,pos):
if pos <0 or pos >=self.longitud:
return None
else:
eliminado=self.lista[pos]
listaAux=[]
for ind in range(pos):
listaAux+=[self.lista[ind]]
for indice in range(pos+1,self.longitud):
listaAux+=[self.lista[indice]]
self.longitud-=1
self.lista=listaAux
return (self.lista,eliminado)
def mostrar(self):
print("{:2}{:9} {}".format("","lista","posicion"))
for pos,ele in enumerate(self.lista):
print("[{:10}] {:10}".format(ele,pos))
lista1=lista()
lista1.append("Daniel")
lista1.append(52)
lista1.append(True)
lista1.mostrar()
posicion=int(input("Ingrese posicion para optner el elemento: "))
resp=lista1.obtener(posicion)
if resp==None:
print("Posicion no valida, verifique la lista")
else:
print("EL ELEMENTO DE LA POSICION: {} es:{}".format(posicion,resp)) |
fe10ba25129da1bb8441e57c44aa20c49ce78eb3 | priyanka-111-droid/100daysofcode | /Day006/6-1.py | 547 | 3.984375 | 4 | ###<<<CHALLENGE>>>###
'''
To jump hurdles and carry Reborg from (x,y)=(1,1) to (13,1)
Basic level - use move() and turn_left()
Advanced level-define function named jump() and use that
#Please write the code below in Reeborg's world text editor !
'''
def turn_right():
turn_left()
turn_left()
turn_left()
def jump():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
#total 6 steps being repeated so (1,7) or (0,6) both are accepted
for robot in range(1,7):
jump()
|
bf3d001fbb03a8c20285b7c74e631545b25c6f66 | Monkey-Young/Python-Code-Practice | /force.py | 293 | 3.78125 | 4 | # coding:utf-8
'''
my first program.
filename: force.py
'''
import math
f1 = 20
f2 = 10
alpha = math.pi / 3
x_force = f1 + f2 * math.sin(alpha)
y_force = f2 * math.cos(alpha)
force = math.sqrt(x_force * x_force + y_force ** 2)
print('The result is: ', round(force, 2), 'N') |
1ab7cf0a1c953282abef7916779bc5706e90f1ae | sky-dream/LeetCodeProblemsStudy | /[0221][Medium][Maximal_Square]/Maximal_Square_5.py | 1,014 | 3.515625 | 4 | # https://leetcode.com/problems/maximal-square/discuss/61845/9-lines-Python-DP-solution-with-explaination
# leetcode time cost : 112 ms
# leetcode memory cost : 14.4 MB
class Solution(object):
def maximalSquare(self, matrix):
dp, maxLength = [[0 for _1_ in range(len(matrix[0]))] for ___ in range(len(matrix))], 0
for i in range(0, len(matrix)):
for j in range(0, len(matrix[0])):
if i == 0 or j == 0:
dp[i][j] = int(matrix[i][j])
elif int(matrix[i][j]) == 1:
dp[i][j] = min(dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]) + 1
maxLength = max(maxLength, dp[i][j])
return maxLength*maxLength
def main():
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] # expect is 4
Solution_obj = Solution()
result = Solution_obj.maximalSquare(matrix)
print("result value is ",result)
if __name__ =='__main__':
main() |
e9da45804fec6c0afb5d9887ec830d1b7d8a64de | benjaminek1337/dt179g_PythonProjects | /Laboration_2/assignment.py | 2,955 | 3.625 | 4 | #!/usr/bin/env python
""" DT179G - LAB ASSIGNMENT 2
"""
import argparse
import sys
__version__ = '1.0'
__desc__ = "A simple script used to authenticate spies!"
def main():
"""The main program execution. YOU MAY NOT MODIFY ANYTHING IN THIS FUNCTION!!"""
epilog = "DT0179G Assignment 2 v" + __version__
parser = argparse.ArgumentParser(description=__desc__, epilog=epilog, add_help=True)
parser.add_argument('credentials', metavar='credentials', type=str,
help="Username and password as string value")
args = parser.parse_args()
if not authenticate_user(args.credentials):
print("Authentication failed. Program exits...")
sys.exit()
print("Authentication successful. User may now access the system!")
def authenticate_user(credentials: str) -> bool:
"""Procedure for validating user credentials"""
username = 'Chevy_Chase' # Expected username. MAY NOT BE MODIFIED!!
password = 'i0J0u0j0u0J0Zys0r0{' # Expected password. MAY NOT BE MODIFIED!!
user_tmp = pass_tmp = str()
''' PSEUDO CODE
PARSE string value of 'credentials' into its components: username and password.
SEND username for FORMATTING by utilizing devoted function. Store return value in 'user_tmp'.
SEND password for decryption by utilizing devoted function. Store return value in 'pass_tmp'.
VALIDATE that both values corresponds to expected credentials.
RETURN outcome of validation as BOOLEAN VALUE.
'''
c = credentials.split()
user_tmp = format_username(f"{c[0]} {c[1]}")
pass_tmp = decrypt_password(c[2])
is_validated = user_tmp == username and pass_tmp == password
return is_validated
def format_username(username: str) -> str:
"""Procedure to format user provided username"""
''' PSEUDO CODE
FORMAT first letter of given name to be UPPERCASE.
FORMAT first letter of surname to be UPPERCASE.
REPLACE empty space between given name and surname with UNDERSCORE '_'
RETURN formatted username as string value.
'''
u = username.split()
return f"{u[0].capitalize()}_{u[1].capitalize()}"
def decrypt_password(password: str) -> str:
"""Procedure used to decrypt user provided password"""
rot7, rot9 = 7, 9 # Rotation values. MAY NOT BE MODIFIED!!
vowels = 'AEIOUaeiou' # MAY NOT BE MODIFIED!!
decrypted = str()
''' PSEUDO CODE
REPEAT {
DETERMINE if char IS VOWEL.
DETERMINE ROTATION KEY to use.
DETERMINE decryption value
ADD decrypted value to decrypted string
}
RETURN decrypted string value
'''
for i in range(len(password)):
is_vowel = vowels.find(password[i])
key = rot7 if i % 2 == 0 else rot9
decrypted_value = chr(ord(password[i]) + key) if is_vowel == -1 else f"0{chr(ord(password[i]) + key)}0"
decrypted += decrypted_value
return decrypted
if __name__ == "__main__":
main()
|
0c06aa2d5f72b1e8243819c07fee8fc6359178b2 | sake12/exercism.io | /python/rna-transcription/rna_transcription.py | 266 | 3.703125 | 4 | def to_rna(dna):
rna = []
transcript = {
"G": "C",
"C": "G",
"T": "A",
"A": "U"
}
for char in dna:
if char not in transcript:
return ''
rna.append(transcript[char])
return ''.join(rna)
|
3e4bc6c4ee76d5b629139bae0c6a258e46520be3 | AngelaPSerrano/ejerciciosPython | /hoja1/ex01.py | 172 | 3.71875 | 4 | base = int(input("Introduzca la base: "))
altura = int(input("Introduzca la altura: "))
area = base * (altura/2)
print("El área de su triángulo es ", area)
|
74bb078daf00d555275bcd3c7e7f329ff379149b | Sarbodaya/PythonGeeks | /Operator/Operator/SpecialOp.py | 676 | 4.03125 | 4 | # 1.Examples of Identity operators
# is : True if the operands are identical
# is not : True if the operands are not identical
a1 = 3
b1 = 3
a2 = 'GeeksforGeeks'
b2 = 'GeeksforGeeks'
a3 = [1, 2, 3]
b3 = [1, 2, 3]
print(a1 is not b1)
print(a2 is b2)
# Output is False, since lists are mutable.
print(a3 is b3)
# 2.MemberShip Operator
# in : True if value is found in the sequence
# not in : True if value is not found in the sequence
# Examples of Membership operator
x = 'Geeks for Geeks'
y = {3: 'a', 4: 'b'}
print('G' in x)
print('geeks' not in x)
print('Geeks' not in x)
print(3 in y)
print('b' in y) # False
|
da5721dfed38dea2fcc1f6b8cffe0ddf138e2803 | timpeng1991/Data_Structures_and_Algorithms | /Algorithmic_Toolbox/Introduction/Least_Common_Multiple.py | 254 | 4 | 4 | #Uses python3
def gcd(a, b):
if b == 0:
return a
else:
a_p = a % b
return gcd(b, a_p)
def lcm(a, b):
return (a * b) // gcd(a, b)
x, y = [int(x) for x in input("Enter two integers: ").split()]
print("LCM:", lcm(x, y)) |
b774f690386bdf0a7e9142c10e63f9c250963fb1 | raman20/next_date | /next_date.py | 1,238 | 4.25 | 4 | def generate_next_date(day,month,year):
#Start writing your code here
next_day = day
next_month = month
next_year = year
if month in [1,3,5,7,8,10,12]:
if day<31:
next_day=day+1
elif day==31:
next_day = 1
if month == 12:
next_year = year+1
next_month = 1
else:
next_month = month+1
elif month in [2,4,6,9,11]:
if month == 2:
if (year % 400 or year%4) ==0:
if day < 29:
next_day = day+1
elif day==29:
next_day = 1
next_month = month+1
else:
if day < 28:
next_day = day+1
elif day==28:
next_day = 1
next_month = month+1
else:
if day < 30:
next_day=day+1
elif day == 30:
next_day =1
next_month=month+1
print(next_day,"-",next_month,"-",next_year)
day = input('enter day: ')
month = input('enter month: ')
year = input('enter year: ')
generate_next_date(day,month,year)
|
4a1305f44a8424d7f5d018eccf1051bee955bb0f | lemonnader/LeetCode-Solution-Well-Formed | /backtracking/Python/0046.py | 593 | 3.625 | 4 | from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def dfs(nums, tmp):
print('-', nums, tmp, not nums)
if not nums:
res.append(tmp[:])
return
for i in range(len(nums)):
tmp = tmp + [nums[i]]
dfs(nums[:i] + nums[i + 1:], tmp)
tmp.pop()
dfs(nums, [])
return res
if __name__ == '__main__':
nums = [1, 2, 3]
solution = Solution()
res = solution.permute(nums)
print(res)
|
98427273cabbe338ee47cfa39fde2c69ec153cca | EmjayAhn/DailyAlgorithm | /04_30days_codechallenge/23_bst_level_order_traversal.py | 1,016 | 4 | 4 | # https://www.hackerrank.com/challenges/30-binary-trees/tutorial
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data <= root.data:
cur = self.insert(root.left, data)
root.left = cur
else:
cur = self.insert(root.right, data)
root.right = cur
return root
def levelOrder(self, root):
#Write your code here
queue = [root]
while queue:
current = queue.pop(0)
print(str(current.data) + ' ', end="")
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
|
d8c7320a83f537a902a7f9cbfa35a1655756e0ea | HaylsDpy/Python---Udacity | /2.3 - multiplyingbyscalar.py | 158 | 3.75 | 4 | # Example as to multiplying a vector by a scalar aka single number
# Expected output = array([3, 6, 9])
import numpy as mp
v1 = np.array([1, 2, 3])
v1 * 3
|
ebe20ade0b67d0b32da780641b3620f2a8662b03 | Eoghan-oconnor/CollatzEmergingTechLab | /collatz.py | 458 | 4.3125 | 4 | # The number we will perform the Collatz operation on
n = int(input("Enter a positive integer: "))
# keep looping until we reach 1.
# assuming the collatz conjecture is true
while n != 1:
# print current n value
print(n)
# see if n is even
if n % 2 == 0:
# if n is even divide by two
n = n / 2
else:
# if n is odd, multiply by three and add one
n = (3 * n) + 1
# print n value
print(n)
|
4b142da84eebf290c1f8e4eb2cbb5523105b622b | ilyarudyak/data_science | /python/oreilly_intermediate_python/unit4/jeopardy/clues.py | 345 | 3.546875 | 4 | import sqlite3
connection = sqlite3.connect('jeopardy.db')
cursor = connection.cursor()
cursor.execute("SELECT text, answer, value FROM clue LIMIT 10")
results = cursor.fetchall()
# TODO: process results
format_string = "[$%s]\n%s\n%s\n"
[print(format_string % (value, text, answer)) for (text, answer, value) in results]
connection.close()
|
d55c6fd20ebd8d69fdf6ad44bf642c78c9e9ccde | bsextion/CodingPractice_Py | /MS/DFS/path_sum.py | 801 | 4.03125 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def has_path(root, sum):
if root:
if root.val == sum and root.right is None and root.left is None:
return True
if sum < 0:
return False
return has_path(root.left, sum-root.val) or has_path(root.right, sum-root.val)
return False
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
print("Tree has path: " + str(has_path(root, 23)))
print("Tree has path: " + str(has_path(root, 16)))
# recursively call to traverse the left and right sub-tree
# return true if any of the two recursive call return true
|
a4aec1bbed4c05a2386a8c54ca9127e309fda13e | chezslice/A.I.-Personal-Assistant | /A.I. Personal Assistant/A.I._Personal_Assistant.py | 1,550 | 3.53125 | 4 | import speech_recognition as sr
from time import ctime
import time
import os
from gtts import gTTS
def speak(audio_response):
print(audio_response)
tts = gTTS(text=audio_response, lang="en")
tts.save("audio.mp3")
os.system("mpg321 audio.mp3")
def record():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say Something")
audio = r.listen(source)
# Google Speech Recognition in use.
data = ""
try:
data = r.recognize_google(audio)
print("You said: " + data)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return data
# Colin is name of the A.I.
def Colin(data):
# Different responses are taken from the data and fed thru Colin, and Colin will produce a response.
# Time, Location and to see how Colin is doing today.
if "how are you" in data:
speak("I am Good Thanks for asking")
if "what time is it" in data:
speak(ctime())
if "where is" in data:
data = data.split(" ")
location = data[2]
speak("Hold on Sir, I will show you where " + location + " is.")
os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&")
# Initialize function.
time.sleep(4)
speak("Hi Sir, what can I help do for you?")
while 1:
data = record()
Colin(data)
|
c38e62449fd9efdf488baee42e5923ca931dadb3 | hedychium/python_learning | /mapAndReduce.py | 1,436 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from functools import reduce
CHAR_TO_FLOAT = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'.': -1
}
def str2float(s):
nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
point = 0
def to_float(f, n):
nonlocal point
if n == -1:
point = 1
return f
if point == 0:
return f * 10 + n
else:
point = point * 10
return f + n / point
return reduce(to_float, nums, 0.0)
print(str2float('0'))
print(str2float('123.456'))
print(str2float('123.45600'))
print(str2float('0.1234'))
print(str2float('.1234'))
print(str2float('120.0034'))
from operator import itemgetter
L = ['bob', 'about', 'Zoo', 'Credit']
print(sorted(L))
print(sorted(L, key=str.lower))
students = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
print(sorted(students, key=itemgetter(0)))
print(sorted(students, key=lambda t: t[1]))
print(sorted(students, key=itemgetter(1), reverse=True))
def createCounter():
i=0
def counter():
nonlocal i
i+=1
return i
return counter
def c():
def num():
n=1
while True:
yield n
n+=1
g=num()
def g_num():
return next(g)
return g_num
A=createCounter()
print(A(),A(),A(),A())
B=c()
print(B(),B(),B(),B()) |
520c85458badb9b29eaba638f48d4e2ec304597f | myf-algorithm/Leetcode | /Leetcode/73.矩阵置零.py | 1,551 | 3.671875 | 4 | class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
O(m+n)额外空间
"""
row = len(matrix)
col = len(matrix[0])
row_zero = set()
col_zero = set()
for i in range(row):
for j in range(col):
if matrix[i][j] == 0:
row_zero.add(i)
col_zero.add(j)
for i in range(row):
for j in range(col):
if i in row_zero or j in col_zero:
matrix[i][j] = 0
def setZeroes1(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
O(1)额外空间
"""
flag_col = False
row = len(matrix)
col = len(matrix[0])
for i in range(row):
if matrix[i][0] == 0:
flag_col = True
for j in range(1, col):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in range(row - 1, -1, -1):
for j in range(col - 1, 0, -1):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
if flag_col == True:
matrix[i][0] = 0
if __name__ == '__main__':
S = Solution()
a = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
S.setZeroes(a)
print(a)
|
c199c4aff550e7a3b8dd83f386a5e69f8783ba8b | sm11/CodeJousts | /linkedLists.py | 1,129 | 3.953125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newData):
self.data = newData
def setNext (self, newNext):
self.next = newNext
class LinkedList(Node):
def __init__(self, data):
self.head = Node(data)
def isEmpty(self):
return self.head == None
def addFront (self, data):
temp = Node(data)
temp.setNext(self.head)
self.head = temp
def addEnd(self, data):
temp = Node(data)
curr = self.head
while (curr.next):
curr = curr.next
curr.setNext(temp)
def printList(self):
curr = self.head
while (curr.next):
print (str(curr.getData())+" -> ", end="")
curr = curr.next
print (curr.getData())
if __name__ == "__main__":
linked = LinkedList(5)
linked.printList()
linked.addFront(33)
linked.addFront(44)
linked.addEnd(11)
linked.printList()
|
1fcc99b1efb6f4003e20a9856acc6ba13d623e3f | zouwen198317/TensorflowPY36CPU | /_15_Crawler/showStrOperation.py | 3,096 | 3.78125 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
__author__ = 'hstking hstking@hotmail.com'
def strCase():
"字串大小寫轉換"
print (u'示範字串大小寫轉換')
print (u"示範字串S儲存值為:' ThIs is a PYTHON '")
S = ' ThIs is a PYTHON '
print (u"大寫轉換成小寫:\tS.lower() \t= %s"%(S.lower()))
print (u"小寫轉換成大寫:\tS.upper() \t= %s"%(S.upper()) )
print (u"大小寫轉換:\t\tS.swapcase() \t= %s"%(S.swapcase()) )
print (u"首字母大寫:\t\tS.title() \t= %s"%(S.title()) )
print (u'\n' )
def strFind():
"字串搜索、替換"
print (u"示範字串搜索、替換等" )
print (u"示範字串S儲存值為:' ThIs is a PYTHON '" )
S = ' ThIs is a PYTHON '
print (u"字串搜索:\t\tS.find('is') \t= %s"%(S.find('is')) )
print (u"字串統計:\t\tS.count('s') \t= %s"%(S.count('s')) )
print (u"字串替換:\t\tS.replace('Is','is') = %s"%(S.replace('Is','is')) )
print (u"去左右空格:\t\tS.strip() \t=#%s#"%(S.strip()) )
print (u"去左邊空格:\t\tS.lstrip() \t=#%s#"%(S.lstrip()) )
print (u"去右邊空格:\t\tS.rstrip() \t=#%s#"%(S.rstrip()) )
print (u'\n' )
def strTest():
"字串測試"
print (u"示範字串測試")
print (u"示範字串S儲存值為:'abcd'")
S1 = 'abcd'
print (u"測試S.isalpha() = %s"%(S1.isalpha()) )
print (u"測試S.isdigit() = %s"%(S1.isdigit()) )
print (u"測試S.isspace() = %s"%(S1.isspace()) )
print (u"測試S.islower() = %s"%(S1.islower()) )
print (u"測試S.isupper() = %s"%(S1.isupper()) )
print (u"測試S.istitle() = %s"%(S1.istitle()) )
def strSplit():
"字串分割、組合"
print (u"示範字串分割、組合" )
print (u"示範字串S儲存值為:' ThIs is a PYTHON '" )
S = ' ThIs is a PYTHON '
print (u"字串分割:\t\tS.split() \t= %s"%(S.split()) )
print (u"字串組合1: '#'.join(['this','is','a','python']) \t= %s"%('#'.join(['this','is','a','python'])) )
print (u"字串組合2: '$'.join(['this','is','a','python']) \t= %s"%('$'.join(['this','is','a','python'])) )
print (u"字串組合3: ' '.join(['this','is','a','python']) \t= %s"%(' '.join(['this','is','a','python'])) )
print (u'\n' )
def strCode():
"字串編碼、解碼"
print (u"示範字串編碼、解碼" )
print (u"示範字串S儲存值為:'編碼解碼測試'" )
S = '編碼解碼測試'
print (u"utf-8編碼的S \t = %s"%(S) )
print (u"utf-8編碼的S轉換unicode編碼" )
print (u"S.decode('utf-8')= %s"%(S.decode("utf-8")) )
print (u"utf-8編碼的S轉換成utf8" )
print (u"S.decode('utf-8').encode('utf8') = %s"%(S.decode("utf-8").encode("utf8")) )
print (u"注意:不管是編碼還是解碼針對的都是unicode字串編碼,\n所以要編碼或者解碼前必須先將源字串轉換成unicode編碼格式" )
print (u'\n')
if __name__ == '__main__':
strCase()
strFind()
strSplit()
strCode()
strTest()
|
75c8bd523df4378adf7cdb6840a871259ef3026a | AurelioLMF/PersonalProject | /ex023.py | 394 | 3.96875 | 4 | '''Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
Ex: Digite um número:
unidade: 4 dezena: 3 centena: 8 milhar: 1'''
num = int(input('Digite um número: '))
uni = num//1 %10
dez = num//10 %10
cen = num//100 %10
mil = num//1000 %10
print(f'Unidade: {uni}')
print(f'Dezena: {dez}')
print(f'Centena: {cen}')
print(f'Milhar: {mil}') |
bbc291f2c47ef52147214abdd530308f5f5298ef | ketika-292/-t2021-2-1 | /Program-2.py | 333 | 3.96875 | 4 | # Program to print an arithmetic series
def printAP(a,d,n):
# Printing AP by simply adding d
# to previous term.
curr_term
curr_term=a
for i in range(1,n+1):
print(curr_term, end=' ')
curr_term =curr_term + d
# Driver code
a = 2 # starting number
d = 1 # Common difference
n = 5 # N th term to be find
printAP(a, d, n)
|
2bea9176297ebfb94fe29b42155078abd0fb54ea | I-ABD-I/School | /ex4_6_2.py | 313 | 3.734375 | 4 | def format_list(my_list):
string = ""
print(str(my_list[:-1:2]).replace("[","").replace("]",""),"and",my_list[-1])
format_list(["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"])
def extend_list_x(list_x, list_y):
list_x[:0] = list_y
print(list_x)
extend_list_x([4,5,6],[1,2,3]) |
1db6be890daf7b41138064e558bda45238359c4a | danielamezcua/Programming-Practice | /LintCode/interval_minimum_coverage.py | 754 | 3.6875 | 4 | """
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param a: the array a
@return: return the minimal points number
"""
def getAns(self, a):
# write your code here
def take_first(elem):
return elem.end
n = len(a)
a.sort(key=take_first)
#the first interval will be the first reference, for which we need at least 1 point.
index_ref_interval = 0
number_points = 1
for i in range(1,n):
if a[i].start > a[index_ref_interval].end:
index_ref_interval = i
number_points+=1
return number_points |
5dae19f3cbb223ff86b4f2cd6d37980a810409b5 | Ruanfc/lista3_python_para_engenharia | /09/main.py | 1,109 | 4.0625 | 4 | #!/usr/bin/env python3
# mensalidade é a prestação
# atraso é o atraso em dias
def valorPagamento(mensalidade, atraso):
if atraso <= 0:
return mensalidade
else:
return 1.03*mensalidade + 0.001*atraso
info = []
while(True):
e = input("Prestação e atraso separados por espaço: ")
if e == "sair" or e == "quit" or e == "exit" or e=="0":
break
dados = e.split()
if len(dados) > 2:
print("Use apenas um espaço para inserir dados")
continue
try:
_setelement = (float(dados[0]), int(dados[1]))
info.append(_setelement)
except ValueError:
print("O valores deve ser float e int respectivamente")
except IndexError:
print("Use um espaço entre a prestação e o atraso")
print("-"*10)
print("Relatório do dia".center(24, "-"))
print("As prestação pagas no dia foram:")
count = 0
soma = 0
for prest, dias in info:
count = count + 1
valor = valorPagamento(prest,dias)
print("*** Prestação de R${:.2f};".format(valor))
soma = soma + valor
print("Totalizando R${:.2f}".format(soma))
|
8c5b4750a019d71b21bcea88eb403bb150203331 | thewchan/python_crash_course | /python_basic/userclass.py | 2,343 | 4.1875 | 4 | class User:
"""Simulate user info including first and last names."""
def __init__(self, first_name, last_name, age, gender):
"""Initiate user instance with first/last name, age, and gender"""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.gender = gender
self.login_attempts = 0
def describe_user(self):
"""Print summary of user information based on input."""
print("Here are the information according to your input:")
print(f"First name: {self.first_name.title()}")
print(f"Last name: {self.last_name.title()}")
print(f"Age: {self.age}")
print(f"Gender: {self.gender.title()}")
def greet_user(self):
"""Print greetings for user."""
print(f"Hello, {self.first_name.title()}, glad you are here with us!")
def increment_login_attempts(self):
"""Increment login_attempts by 1"""
self.login_attempts += 1
def reset_login_attempts(self):
"""Reset login_attempts to 0"""
self.login_attempts = 0
class Privileges:
"""Stores list of current admin privileges as attribute."""
def __init__(self, current_privileges = []):
self.current_privileges = current_privileges
def show_privileges(self):
"""Print summary of admin privileges."""
print(f"Hello, SysAdmin. Here are your current admin privileges: ")
for privilege in self.current_privileges:
print(f"- {privilege.capitalize()}")
class Admin(User):
"""A subclass of User that is an admin"""
def __init__(self, first_name, last_name, age, gender, privileges):
"""Initiate admin with the superclass User"""
super().__init__(first_name, last_name, age, gender)
self.privileges = Privileges(privileges)
matt = User('matt', 'chan', '34', 'male')
micaela = User('micaela', 'chan', '31', 'female')
rosalee = User('rosalee', 'chan', '29', 'female')
admin_privileges = ['can add post', 'can delete post', 'can ban user']
brian = Admin('brian', 'rodriguez', '37', 'male', admin_privileges)
matt.describe_user()
matt.greet_user()
micaela.describe_user()
micaela.greet_user()
rosalee.describe_user()
rosalee.greet_user()
brian.privileges.show_privileges()
|
dae81e040d70bbd06261ad6eed9694cc859614ad | YaniraHagstrom/PY-111-Intro_to_Python | /Example.py | 228 | 3.546875 | 4 | def add(x, y):
return x + y
def multipy(x, y):
return x * y
def substract(x, y):
return x - y
def divide(x, y):
return x / y
def mod(x, y):
if(x > y):
return x % y
else:
return y % x
|
545876341a5bc82abc601e99b210321f9f1fd6c7 | raghavddps2/Technical-Interview-Prep-1 | /UD_DSA/Course1/Trees/Tree.py | 3,188 | 4.375 | 4 | # this code makes the tree that we'll traverse
class Node(object):
def __init__(self,value = None):
self.value = value
self.left = None
self.right = None
self.is_visited_left = False
self.is_visited_right = False
def set_value(self,value):
self.value = value
def get_value(self):
return self.value
def set_left_child(self,left):
self.left = left
def set_right_child(self, right):
self.right = right
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left != None
def has_right_child(self):
return self.right != None
# define __repr_ to decide what a print statement displays for a Node object
def __repr__(self):
return f"Node({self.get_value()})"
def __str__(self):
return f"Node({self.get_value()})"
class Tree():
def __init__(self, value=None):
self.root = Node(value)
def get_root(self):
return self.root
# create a tree and add some nodes
tree = Tree("apple")
tree.get_root().set_left_child(Node("banana"))
tree.get_root().set_right_child(Node("cherry"))
tree.get_root().get_right_child().set_right_child(Node("Pulao"))
tree.get_root().get_left_child().set_left_child(Node("dates"))
# Let's define a stack to help keep track of the tree nodes
class Stack():
def __init__(self):
self.list = list()
def push(self,value):
self.list.append(value)
def pop(self):
return self.list.pop()
def top(self):
if len(self.list) > 0:
return self.list[-1]
else:
return None
def is_empty(self):
return len(self.list) == 0
def __repr__(self):
if len(self.list) > 0:
s = "<top of stack>\n_________________\n"
s += "\n_________________\n".join([str(item) for item in self.list[::-1]])
s += "\n_________________\n<bottom of stack>"
return s
else:
return "<stack is empty>"
def pre_order_with_stack(tree):
visit_order = list()
stack = Stack()
node = tree.get_root()
stack.push(node)
node = stack.top()
visit_order.append(node.get_value())
while(node):
if node.has_left_child() and (not node.is_visited_left):
node.is_visited_left = True
node = node.get_left_child()
stack.push(node)
node = stack.top()
visit_order.append(node.get_value())
elif node.has_right_child() and (not node.is_visited_right):
node.is_visited_right = True
node = node.get_right_child()
stack.push(node)
node = stack.top()
visit_order.append(node.get_value())
else:
stack.pop()
if not stack.is_empty():
node = stack.top()
else:
node = None
return visit_order
print(pre_order_with_stack(tree)) |
0bca363abf2580366e8bac016762dba373efb41d | DroneOmega/Random | /College/Python/Zig Zag KS4 Programs/Exercise1-NumberGame/original/q1-numGame.py | 1,333 | 4.03125 | 4 | import random
counter = 0
def guess():
try:
num = int(input("\u0332".join("Please enter your guess: ")))
val = int(num)
if num > 100:
print("The number you have entered is too large.")
print("Please try again.")
guess()
elif num < 1:
print("your number you have entered is too small.")
print("Please try again.")
guess()
else:
return num
except ValueError:
print("That's not an int!")
guess()
print("\u0332".join("Welcome to the number guessing game"))
print("The objective is to guess the number I'm thinking of.")
print("I will give you clues after your first guess.")
print("I have thought of a number from 1-100")
secretNumber = random.randint(1,100)
secretNumber = int(secretNumber)
numGuessed = guess()
while numGuessed != secretNumber:
if numGuessed < secretNumber:
print("Guess is too low, guess higher!")
counter += 1
numGuessed=guess()
elif numGuessed > secretNumber:
print("Guess is too high, guess lower!")
counter += 1
numGuessed=guess()
print("Correct! The number is {}".format(secretNumber))
counter += 1
print("It Took You {} Tries to Guess Correctly".format(counter))
|
e31b2398dba970c79f21e1fef69d437882bf177a | SherbazHashmi/HackathonServer | /arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/geometry/functions.py | 39,682 | 3.515625 | 4 | """
Functions which take geometric types as parameters and return geometric type results.
"""
import arcgis.env
# https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer.
def areas_and_lengths(polygons,
length_unit,
area_unit,
calculation_type,
spatial_ref=4326,
gis=None):
"""
The areas_and_lengths function calculates areas and perimeter lengths
for each polygon specified in the input array.
Inputs:
polygons - The array of polygons whose areas and lengths are
to be computed.
length_unit - The length unit in which the perimeters of
polygons will be calculated. If calculation_type
is planar, then length_unit can be any esriUnits
constant. If lengthUnit is not specified, the
units are derived from spatial_ref. If calculationType is
not planar, then lengthUnit must be a linear
esriUnits constant, such as esriSRUnit_Meter or
esriSRUnit_SurveyMile. If length_unit is not
specified, the units are meters. For a list of
valid units, see esriSRUnitType Constants and
esriSRUnit2Type Constant.
area_unit - The area unit in which areas of polygons will be
calculated. If calculation_type is planar, then
area_unit can be any esriUnits constant. If
area_unit is not specified, the units are derived
from spatial_ref. If calculation_type is not planar, then
area_unit must be a linear esriUnits constant such
as esriSRUnit_Meter or esriSRUnit_SurveyMile. If
area_unit is not specified, then the units are
meters. For a list of valid units, see
esriSRUnitType Constants and esriSRUnit2Type
constant.
The list of valid esriAreaUnits constants include,
esriSquareInches | esriSquareFeet |
esriSquareYards | esriAcres | esriSquareMiles |
esriSquareMillimeters | esriSquareCentimeters |
esriSquareDecimeters | esriSquareMeters | esriAres
| esriHectares | esriSquareKilometers.
calculation_type - The type defined for the area and length
calculation of the input geometries. The
type can be one of the following values:
planar - Planar measurements use 2D
Euclidean distance to calculate
area and length. Th- should
only be used if the area or
length needs to be calculated in
the given spatial reference.
Otherwise, use preserveShape.
geodesic - Use this type if you want to
calculate an area or length using
only the vertices of the polygon
and define the lines between the
points as geodesic segments
independent of the actual shape
of the polygon. A geodesic
segment is the shortest path
between two points on an ellipsoid.
preserveShape - This type calculates the
area or length of the geometry on
the surface of the Earth
ellipsoid. The shape of the
geometry in its coordinate system
is preserved.
Output:
JSON as dictionary
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.areas_and_lengths(
polygons,
length_unit,
area_unit,
calculation_type,
spatial_ref)
def auto_complete(polygons=None,
polylines=None,
spatial_ref=None,
gis=None):
"""
The auto_complete function simplifies the process of
constructing new polygons that are adjacent to other polygons.
It constructs polygons that fill in the gaps between existing
polygons and a set of polylines.
Inputs:
polygons -
array of Polygon objects
polylines -
list of Polyline objects
spatial_ref -
spatial reference of the input geometries WKID
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.auto_complete(
polygons,
polylines,
spatial_ref)
def buffer(geometries,
in_sr,
distances,
unit,
out_sr=None,
buffer_sr=None,
union_results=None,
geodesic=None,
gis=None):
"""
The buffer function is performed on a geometry service resource
The result of this function is buffered polygons at the
specified distances for the input geometry array. Options are
available to union buffers and to use geodesic distance.
Inputs:
geometries -
The array of geometries to be buffered.
in_sr -
The well-known ID of the spatial reference or a spatial
reference JSON object for the input geometries.
distances -
The distances that each of the input geometries is
buffered.
unit - The units for calculating each buffer distance. If unit
is not specified, the units are derived from bufferSR. If
bufferSR is not specified, the units are derived from in_sr.
out_sr - The well-known ID of the spatial reference or a
spatial reference JSON object for the input geometries.
buffer_sr - The well-known ID of the spatial reference or a
spatial reference JSON object for the input geometries.
union_results - If true, all geometries buffered at a given
distance are unioned into a single (gis,possibly multipart)
polygon, and the unioned geometry is placed in the output
array. The default is false
geodesic - Set geodesic to true to buffer the input geometries
using geodesic distance. Geodesic distance is the shortest
path between two points along the ellipsoid of the earth. If
geodesic is set to false, the 2D Euclidean distance is used
to buffer the input geometries. The default value depends on
the geometry type, unit and bufferSR.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.buffer(
geometries,
in_sr,
distances,
unit,
out_sr,
buffer_sr,
union_results,
geodesic)
def convex_hull(geometries,
spatial_ref=None,
gis=None):
"""
The convex_hull function is performed on a geometry service
resource. It returns the convex hull of the input geometry. The
input geometry can be a point, multipoint, polyline, or polygon.
The convex hull is typically a polygon but can also be a polyline
or point in degenerate cases.
Inputs:
geometries - The geometries whose convex hull is to be created.
spatial_ref - The well-known ID or a spatial reference JSON object for
the output geometry.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.convex_hull(
geometries,
spatial_ref)
def cut(cutter,
target,
spatial_ref=None,
gis=None):
"""
The cut function is performed on a geometry service resource. This
function splits the target polyline or polygon where it's crossed
by the cutter polyline.
At 10.1 and later, this function calls simplify on the input
cutter and target geometries.
Inputs:
cutter - The polyline that will be used to divide the target
into pieces where it crosses the target.The spatial reference
of the polylines is specified by spatial_ref. The structure of the
polyline is the same as the structure of the JSON polyline
objects returned by the ArcGIS REST API.
target - The array of polylines/polygons to be cut. The
structure of the geometry is the same as the structure of the
JSON geometry objects returned by the ArcGIS REST API. The
spatial reference of the target geometry array is specified by
spatial_ref.
spatial_ref - The well-known ID or a spatial reference JSON object for
the output geometry.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.cut(
cutter,
target,
spatial_ref)
def densify(geometries,
spatial_ref,
max_segment_length,
length_unit,
geodesic=False,
gis=None):
"""
The densify function is performed using the GIS's geometry engine.
This function densifies geometries by plotting points between
existing vertices.
Inputs:
geometries - The array of geometries to be densified. The
structure of each geometry in the array is the same as the
structure of the JSON geometry objects returned by the ArcGIS
REST API.
spatial_ref - The well-known ID or a spatial reference JSON object for
the input polylines. For a list of valid WKID values, see
Projected coordinate systems and Geographic coordinate systems.
max_segment_length - All segments longer than maxSegmentLength are
replaced with sequences of lines no longer than
max_segment_length.
length_unit - The length unit of max_segment_length. If geodesic is
set to false, then the units are derived from spatial_ref, and
length_unit is ignored. If geodesic is set to true, then
length_unit must be a linear unit. In a case where length_unit is
not specified and spatial_ref is a PCS, the units are derived from spatial_ref.
In a case where length_unit is not specified and spatial_ref is a GCS,
then the units are meters.
geodesic - If geodesic is set to true, then geodesic distance is
used to calculate max_segment_length. Geodesic distance is the
shortest path between two points along the ellipsoid of the
earth. If geodesic is set to false, then 2D Euclidean distance
is used to calculate max_segment_length. The default is false.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.densify(
geometries,
spatial_ref,
max_segment_length,
length_unit,
geodesic)
def difference(geometries,
spatial_ref,
geometry,
gis=None):
"""
The difference function is performed on a geometry service
resource. This function constructs the set-theoretic difference
between each element of an array of geometries and another geometry
the so-called difference geometry. In other words, let B be the
difference geometry. For each geometry, A, in the input geometry
array, it constructs A-B.
Inputs:
geometries - An array of points, multipoints, polylines or
polygons. The structure of each geometry in the array is the
same as the structure of the JSON geometry objects returned by
the ArcGIS REST API.
geometry - A single geometry of any type and of a dimension equal
to or greater than the elements of geometries. The structure of
geometry is the same as the structure of the JSON geometry
objects returned by the ArcGIS REST API. The use of simple
syntax is not supported.
spatial_ref - The well-known ID of the spatial reference or a spatial
reference JSON object for the input geometries.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.difference(
geometries,
spatial_ref,
geometry)
def distance(spatial_ref,
geometry1,
geometry2,
distance_unit="",
geodesic=False,
gis=None):
"""
The distance function is performed on a geometry service resource.
It reports the 2D Euclidean or geodesic distance between the two
geometries.
Inputs:
spatial_ref - The well-known ID or a spatial reference JSON object for
input geometries.
geometry1 - The geometry from which the distance is to be
measured. The structure of the geometry is same as the structure
of the JSON geometry objects returned by the ArcGIS REST API.
geometry2 - The geometry from which the distance is to be
measured. The structure of the geometry is same as the structure
of the JSON geometry objects returned by the ArcGIS REST API.
distanceUnit - specifies the units for measuring distance between
the geometry1 and geometry2 geometries.
geodesic - If geodesic is set to true, then the geodesic distance
between the geometry1 and geometry2 geometries is returned.
Geodesic distance is the shortest path between two points along
the ellipsoid of the earth. If geodesic is set to false or not
specified, the planar distance is returned. The default value is
false.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.distance(
spatial_ref,
geometry1,
geometry2,
distance_unit,
geodesic)
def find_transformation(in_sr, out_sr, extent_of_interest=None, num_of_results=1, gis=None):
"""
The find_transformations function is performed on a geometry
service resource. This function returns a list of applicable
geographic transformations you should use when projecting
geometries from the input spatial reference to the output spatial
reference. The transformations are in JSON format and are returned
in order of most applicable to least applicable. Recall that a
geographic transformation is not needed when the input and output
spatial references have the same underlying geographic coordinate
systems. In this case, findTransformations returns an empty list.
Every returned geographic transformation is a forward
transformation meaning that it can be used as-is to project from
the input spatial reference to the output spatial reference. In the
case where a predefined transformation needs to be applied in the
reverse direction, it is returned as a forward composite
transformation containing one transformation and a transformForward
element with a value of false.
Inputs:
in_sr - The well-known ID (gis,WKID) of the spatial reference or a
spatial reference JSON object for the input geometries
out_sr - The well-known ID (gis,WKID) of the spatial reference or a
spatial reference JSON object for the input geometries
extent_of_interest - The bounding box of the area of interest
specified as a JSON envelope. If provided, the extent of
interest is used to return the most applicable geographic
transformations for the area. If a spatial reference is not
included in the JSON envelope, the in_sr is used for the
envelope.
num_of_results - The number of geographic transformations to
return. The default value is 1. If num_of_results has a value of
-1, all applicable transformations are returned.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.find_transformation(in_sr, out_sr,
extent_of_interest, num_of_results)
def from_geo_coordinate_string(spatial_ref, strings,
conversion_type, conversion_mode=None, gis=None):
"""
The from_geo_coordinate_string function is performed on a geometry
service resource. The function converts an array of well-known
strings into xy-coordinates based on the conversion type and
spatial reference supplied by the user. An optional conversion mode
parameter is available for some conversion types.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference json object.
strings - An array of strings formatted as specified by
conversion_type.
Syntax: [<string1>,...,<stringN>]
Example: ["01N AA 66021 00000","11S NT 00000 62155",
"31U BT 94071 65288"]
conversion_type - The conversion type of the input strings.
Valid conversion types are:
MGRS - Military Grid Reference System
USNG - United States National Grid
UTM - Universal Transverse Mercator
GeoRef - World Geographic Reference System
GARS - Global Area Reference System
DMS - Degree Minute Second
DDM - Degree Decimal Minute
DD - Decimal Degree
conversion_mode - Conversion options for MGRS, UTM and GARS
conversion types.
Conversion options for MGRS and UTM conversion types.
Valid conversion modes for MGRS are:
mgrsDefault - Default. Uses the spheroid from the given spatial
reference.
mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The
180 degree longitude falls into Zone 60.
mgrsOldStyle - Treats all spheroids as old, like Bessel 1841.
The 180 degree longitude falls into Zone 60.
mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180
degree longitude falls into Zone 01.
mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180
degree longitude falls into Zone 01.
Valid conversion modes for UTM are:
utmDefault - Default. No options.
utmNorthSouth - Uses north/south latitude indicators instead of
zone numbers. Non-standard. Default is recommended
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.from_geo_coordinate_string(spatial_ref, strings,
conversion_type, conversion_mode)
def generalize(spatial_ref,
geometries,
max_deviation,
deviation_unit,
gis=None):
"""
The generalize function is performed on a geometry service
resource. The generalize function simplifies the input geometries
using the Douglas-Peucker algorithm with a specified maximum
deviation distance. The output geometries will contain a subset of
the original input vertices.
Inputs:
spatial_ref - The well-known ID or a spatial reference JSON object for the
input geometries.
geometries - The array of geometries to be generalized.
max_deviation - max_deviation sets the maximum allowable offset,
which will determine the degree of simplification. This value
limits the distance the output geometry can differ from the input
geometry.
deviation_unit - A unit for maximum deviation. If a unit is not
specified, the units are derived from spatial_ref.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.generalize(
spatial_ref,
geometries,
max_deviation,
deviation_unit)
def intersect(spatial_ref,
geometries,
geometry,
gis=None):
"""
The intersect function is performed on a geometry service
resource. This function constructs the set-theoretic intersection
between an array of geometries and another geometry. The dimension
of each resultant geometry is the minimum dimension of the input
geometry in the geometries array and the other geometry specified
by the geometry parameter.
Inputs:
spatial_ref - The well-known ID or a spatial reference JSON object for the
input geometries.
geometries - An array of points, multipoints, polylines, or
polygons. The structure of each geometry in the array is the same
as the structure of the JSON geometry objects returned by the
ArcGIS REST API.
geometry - A single geometry of any type with a dimension equal to
or greater than the elements of geometries.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.intersect(spatial_ref,
geometries,
geometry)
def label_points(spatial_ref,
polygons,
gis=None):
"""
The label_points function is performed on a geometry service
resource. The labelPoints function calculates an interior point
for each polygon specified in the input array. These interior
points can be used by clients for labeling the polygons.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference JSON object for the input polygons.
polygons - The array of polygons whose label points are to be
computed. The spatial reference of the polygons is specified by
spatial_ref.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.label_points(spatial_ref, polygons)
def lengths(spatial_ref,
polylines,
length_unit,
calculation_type,
gis=None):
"""
The lengths function is performed on a geometry service resource.
This function calculates the 2D Euclidean or geodesic lengths of
each polyline specified in the input array.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference JSON object for the input polylines.
polylines - The array of polylines whose lengths are to be
computed.
length_unit - The unit in which lengths of polylines will be
calculated. If calculation_type is planar, then length_unit can be
any esriUnits constant. If calculation_type is planar and
length_unit is not specified, then the units are derived from spatial_ref.
If calculation_type is not planar, then length_unit must be a
linear esriUnits constant such as esriSRUnit_Meter or
esriSRUnit_SurveyMile. If calculation_type is not planar and
length_unit is not specified, then the units are meters.
calculation_type - calculation_type defines the length calculation
for the geometry. The type can be one of the following values:
planar - Planar measurements use 2D Euclidean distance to
calculate length. This type should only be used if the length
needs to be calculated in the given spatial reference.
Otherwise, use preserveShape.
geodesic - Use this type if you want to calculate a length
using only the vertices of the polygon and define the lines
between the vertices as geodesic segments independent of the
actual shape of the polyline. A geodesic segment is the
shortest path between two points on an earth ellipsoid.
preserveShape - This type calculates the length of the geometry
on the surface of the earth ellipsoid. The shape of the
geometry in its coordinate system is preserved.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.lengths(
spatial_ref,
polylines,
length_unit,
calculation_type)
def offset(geometries,
offset_distance,
offset_unit,
offset_how="esriGeometryOffsetRounded",
bevel_ratio=10,
simplify_result=False,
spatial_ref=None,
gis=None):
"""
The offset function is performed on a geometry service resource.
This function constructs geometries that are offset from the
given input geometries. If the offset parameter is positive, the
constructed offset will be on the right side of the geometry. Left
side offsets are constructed with negative parameters. Tracing the
geometry from its first vertex to the last will give you a
direction along the geometry. It is to the right and left
perspective of this direction that the positive and negative
parameters will dictate where the offset is constructed. In these
terms, it is simple to infer where the offset of even horizontal
geometries will be constructed.
Inputs:
geometries - The array of geometries to be offset.
offset_distance - Specifies the distance for constructing an offset
based on the input geometries. If the offset_distance parameter is
positive, the constructed offset will be on the right side of the
curve. Left-side offsets are constructed with negative values.
offset_unit - A unit for offset distance. If a unit is not
specified, the units are derived from spatial_ref.
offset_how - The offset_how parameter determines how outer corners
between segments are handled. The three options are as follows:
esriGeometryOffsetRounded - Rounds the corner between extended
offsets.
esriGeometryOffsetBevelled - Squares off the corner after a
given ratio distance.
esriGeometryOffsetMitered - Attempts to allow extended offsets
to naturally intersect, but if that intersection occurs too far
from the corner, the corner is eventually bevelled off at a
fixed distance.
bevel_ratio - bevel_ratio is multiplied by the offset distance, and
the result determines how far a mitered offset intersection can
be located before it is bevelled. When mitered is specified,
bevel_ratio is ignored and 10 is used internally. When bevelled is
specified, 1.1 will be used if bevel_ratio is not specified.
bevel_ratio is ignored for rounded offset.
simplify_result - if simplify_result is set to true, then self
intersecting loops will be removed from the result offset
geometries. The default is false.
spatial_ref - The well-known ID or a spatial reference JSON object for the
input geometries.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.offset(
geometries,
offset_distance,
offset_unit,
offset_how,
bevel_ratio,
simplify_result,
spatial_ref)
def project(geometries,
in_sr,
out_sr,
transformation="",
transform_forward=False,
gis=None):
"""
The project function is performed on a geometry service resource.
This function projects an array of input geometries from the input
spatial reference to the output spatial reference.
Inputs:
geometries - The list of geometries to be projected.
in_sr - The well-known ID (gis,WKID) of the spatial reference or a
spatial reference JSON object for the input geometries.
out_sr - The well-known ID (gis,WKID) of the spatial reference or a
spatial reference JSON object for the input geometries.
transformation - The WKID or a JSON object specifying the
geographic transformation (gis,also known as datum transformation) to
be applied to the projected geometries. Note that a
transformation is needed only if the output spatial reference
contains a different geographic coordinate system than the input
spatial reference.
transform_forward - A Boolean value indicating whether or not to
transform forward. The forward or reverse direction of
transformation is implied in the name of the transformation. If
transformation is specified, a value for the transformForward
parameter must also be specified. The default value is false.
Example:
input_geom = [{"x": -17568824.55, "y": 2428377.35}, {"x": -17568456.88, "y": 2428431.352}]
result = project(geometries = input_geom, in_sr = 3857, out_sr = 4326)
returns:
a list of geometries in the out_sr coordinate system, for instance:
[{"x": -157.82343617279275, "y": 21.305781607280093}, {"x": -157.8201333369876, "y": 21.306233559873714}]
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.project(
geometries,
in_sr,
out_sr,
transformation,
transform_forward)
def relation(geometries1,
geometries2,
spatial_ref,
spatial_relation="esriGeometryRelationIntersection",
relation_param="",
gis=None):
"""
The relation function is performed on a geometry service resource.
This function determines the pairs of geometries from the input
geometry arrays that participate in the specified spatial relation.
Both arrays are assumed to be in the spatial reference specified by
spatial_ref, which is a required parameter. Geometry types cannot be mixed
within an array. The relations are evaluated in 2D. In other words,
z coordinates are not used.
Inputs:
geometries1 - The first array of geometries used to compute the
relations.
geometries2 -The second array of geometries used to compute the
relations.
spatial_ref - The well-known ID of the spatial reference or a spatial
reference JSON object for the input geometries.
spatial_relation - The spatial relationship to be tested between the two
input geometry arrays.
Values: esriGeometryRelationCross | esriGeometryRelationDisjoint |
esriGeometryRelationIn | esriGeometryRelationInteriorIntersection |
esriGeometryRelationIntersection | esriGeometryRelationLineCoincidence |
esriGeometryRelationLineTouch | esriGeometryRelationOverlap |
esriGeometryRelationPointTouch | esriGeometryRelationTouch |
esriGeometryRelationWithin | esriGeometryRelationRelation
relation_param - The Shape Comparison Language string to be
evaluated.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.relation(
geometries1,
geometries2,
spatial_ref,
spatial_relation,
relation_param)
def reshape(spatial_ref,
target,
reshaper,
gis=None):
"""
The reshape function is performed on a geometry service resource.
It reshapes a polyline or polygon feature by constructing a
polyline over the feature. The feature takes the shape of the
reshaper polyline from the first place the reshaper intersects the
feature to the last.
Input:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference JSON object for the input geometries.
target - The polyline or polygon to be reshaped.
reshaper - The single-part polyline that does the reshaping.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.reshape(
spatial_ref,
target,
reshaper)
def simplify(spatial_ref,
geometries,
gis=None):
"""
The simplify function is performed on a geometry service resource.
Simplify permanently alters the input geometry so that the geometry
becomes topologically consistent. This resource applies the ArcGIS
simplify function to each geometry in the input array.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference JSON object for the input geometries.
geometries - The array of geometries to be simplified.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.simplify(spatial_ref, geometries)
def to_geo_coordinate_string(spatial_ref,
coordinates,
conversion_type,
conversion_mode="mgrsDefault",
num_of_digits=None,
rounding=True,
add_spaces=True,
gis=None):
"""
The to_geo_coordinate_string function is performed on a geometry
service resource. The function converts an array of
xy-coordinates into well-known strings based on the conversion type
and spatial reference supplied by the user. Optional parameters are
available for some conversion types. Note that if an optional
parameter is not applicable for a particular conversion type, but a
value is supplied for that parameter, the value will be ignored.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference json object.
coordinates - An array of xy-coordinates in JSON format to be
converted. Syntax: [[x1,y2],...[xN,yN]]
conversion_type - The conversion type of the input strings.
Allowed Values:
MGRS - Military Grid Reference System
USNG - United States National Grid
UTM - Universal Transverse Mercator
GeoRef - World Geographic Reference System
GARS - Global Area Reference System
DMS - Degree Minute Second
DDM - Degree Decimal Minute
DD - Decimal Degree
conversion_mode - Conversion options for MGRS and UTM conversion
types.
Valid conversion modes for MGRS are:
mgrsDefault - Default. Uses the spheroid from the given spatial
reference.
mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The
180 degree longitude falls into Zone 60.
mgrsOldStyle - Treats all spheroids as old, like Bessel 1841.
The 180 degree longitude falls into Zone 60.
mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180
degree longitude falls into Zone 01.
mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180
degree longitude falls into Zone 01.
Valid conversion modes for UTM are:
utmDefault - Default. No options.
utmNorthSouth - Uses north/south latitude indicators instead of
zone numbers. Non-standard. Default is recommended.
num_of_digits - The number of digits to output for each of the
numerical portions in the string. The default value for
num_of_digits varies depending on conversion_type.
rounding - If true, then numeric portions of the string are
rounded to the nearest whole magnitude as specified by
numOfDigits. Otherwise, numeric portions of the string are
truncated. The rounding parameter applies only to conversion
types MGRS, USNG and GeoRef. The default value is true.
addSpaces - If true, then spaces are added between components of
the string. The addSpaces parameter applies only to conversion
types MGRS, USNG and UTM. The default value for MGRS is false,
while the default value for both USNG and UTM is true.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.to_geo_coordinate_string(
spatial_ref,
coordinates,
conversion_type,
conversion_mode,
num_of_digits,
rounding,
add_spaces)
def trim_extend(spatial_ref,
polylines,
trim_extend_to,
extend_how=0,
gis=None):
"""
The trim_extend function is performed on a geometry service
resource. This function trims or extends each polyline specified
in the input array, using the user-specified guide polylines. When
trimming features, the part to the left of the oriented cutting
line is preserved in the output, and the other part is discarded.
An empty polyline is added to the output array if the corresponding
input polyline is neither cut nor extended.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference json object.
polylines - An array of polylines to be trimmed or extended.
trim_extend_to - A polyline that is used as a guide for trimming or
extending input polylines.
extend_how - A flag that is used along with the trimExtend
function.
0 - By default, an extension considers both ends of a path. The
old ends remain, and new points are added to the extended ends.
The new points have attributes that are extrapolated from
adjacent existing segments.
1 - If an extension is performed at an end, relocate the end
point to the new position instead of leaving the old point and
adding a new point at the new position.
2 - If an extension is performed at an end, do not extrapolate
the end-segment's attributes for the new point. Instead, make
its attributes the same as the current end. Incompatible with
esriNoAttributes.
4 - If an extension is performed at an end, do not extrapolate
the end-segment's attributes for the new point. Instead, make
its attributes empty. Incompatible with esriKeepAttributes.
8 - Do not extend the 'from' end of any path.
16 - Do not extend the 'to' end of any path.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.trim_extend(spatial_ref,
polylines,
trim_extend_to,
extend_how)
def union(spatial_ref,
geometries,
gis=None):
"""
The union function is performed on a geometry service resource.
This function constructs the set-theoretic union of the geometries
in the input array. All inputs must be of the same type.
Inputs:
spatial_ref - The well-known ID of the spatial reference or a spatial
reference json object.
geometries - The array of geometries to be unioned.
"""
if gis is None:
gis = arcgis.env.active_gis
return gis._tools.geometry.union(spatial_ref, geometries)
|
fdd4ae4830014b1b0523eacb288483b6f6dc8c31 | MatheusIshiyama/Sudoku-API | /src/services/sudoku/valid_Numbers.py | 2,605 | 4.3125 | 4 | from random import sample
def invalid_row_numbers(matrix: list, row: int, column_length: int) -> list:
# receives a [matrix] and a reference [row]
# return a list of invalid numbers in the row.
invalid_numbers = list()
for column in range(column_length):
# matrix[row][column] != 0 means that matrix[row][column] is an invalid
# number in the row.
if matrix[row][column]:
invalid_numbers.append(matrix[row][column])
return invalid_numbers
def invalid_column_numbers(matrix: list, column: int, row_length: int) -> list:
# receives a [matrix] and a reference [column]
# return a list of invalid numbers in the column.
invalid_numbers = list()
for row in range(row_length):
# matrix[row][column] != 0 means that matrix[row][column] is an invalid
# number in the column.
if matrix[row][column]:
invalid_numbers.append(matrix[row][column])
return invalid_numbers
def invalid_box_numbers(matrix: list, point: tuple) -> list:
# receives a [matrix] and a reference [point](column, row)
# return a list of invalid numbers in box.
# A box is a 3x3 matrix inside the main sudoku matrix,
# you can see a better definition at: https://en.wikipedia.org/wiki/Mathematics_of_Sudoku
invalid_numbers = list()
column = point[0]
row = point[1]
box = {
0: (0, 1, 2), # 0 <= [column || row] <= 2
1: (3, 4, 5), # 3 <= [column || row] <= 5
2: (6, 7, 8) # 6 <= [column || row] <= 8
}
for y in box[ int(row/3) ]:
for x in box[ int(column/3) ]:
# matrix[y][x] != 0 means that matrix[y][x]
# is an invalid number in the box (relative 3x3 matrix).
if matrix[y][x]:
invalid_numbers.append(matrix[y][x])
invalid_numbers = list(set(invalid_numbers))
return invalid_numbers
def valid_random_number(*invalid_numbers_rol: tuple) -> int:
# gets severals invalid numbers.
# A: return a random number, from 1 to 9, that is not in the row, column or box
# return 0 if it cant return A
invalid_numbers = list()
for numbers in invalid_numbers_rol:
invalid_numbers.extend(numbers)
invalid_numbers = set(invalid_numbers)
valid_numbers_list = list(range(1, 10))
for number in invalid_numbers:
valid_numbers_list.remove(number)
try:
# if length of valid_numbers_list is zero, raises an erro.
return sample(valid_numbers_list, 1)[0]
except:
return 0
|
fd4fcb75956f7d12200c923eeedf10773830b1a9 | adashtoyan/numpy-mnist-classifier | /classifier/nn.py | 7,911 | 3.890625 | 4 | import pickle
from typing import List, Tuple
import numpy as np
from . import activations
class NeuralNetwork():
"""Deep neural network using batch training.
Example::
>>> model = NeuralNetwork([784, 30, 10])
>>> model.train(training_data)
>>> model.test(test_data)
.. note::
To train the model for a number of epochs you should call
``model.train(training_data)`` multiple times
"""
def __init__(self,
layers_size: List[int],
learning_rate=0.01,
batch_size=10,
activation=activations.SIGMOID,
weights=None,
biaises=None):
self.learning_rate = learning_rate
self.layers_size = layers_size
self.number_layers = len(layers_size) - 1
self.batch_size = batch_size
self.activation = activation
self._generate_weights = _generate_random
self._activation = activations.find(activation)
self._activation_derivative = activations.find_derivative(activation)
self.weights = weights
self.biaises = biaises
if (self.weights is None):
self._initialize_weights(layers_size)
if (self.biaises is None):
self._initialize_biases(layers_size)
def train(self, data_set: List[Tuple[np.ndarray, np.ndarray]]):
"""Train the neural network on input data and adjust it weights ans biaises.
:param data_set: data used to train the neural network
"""
batch_gradients_w = self._initialize_batch(self.weights)
batch_gradients_b = self._initialize_batch(self.biaises)
X = data_set[0]
Y = data_set[1]
N = len(X)
for iteration in range(1, N + 1):
x = X[iteration - 1]
y = Y[iteration - 1]
z, a = self.forward_propagation(x)
gradients_w, gradients_b = self.backward_propagation(z, a, y)
self._update_batch(batch_gradients_w, gradients_w)
self._update_batch(batch_gradients_b, gradients_b)
if (iteration % self.batch_size == 0):
self._apply_gradients(batch_gradients_w, batch_gradients_b)
batch_gradients_w = self._initialize_batch(self.weights)
batch_gradients_b = self._initialize_batch(self.biaises)
def test(self, data_set: List[Tuple[np.ndarray, np.ndarray]]) -> Tuple[float, float]:
"""Test the neural network on the input data set.
:param data_set: The data that will be used to test the model
:return: Losses and accuracies
"""
misses = 0
total = 0
losses = 0.0
for x, y in zip(data_set[0], data_set[1]):
total += 1
_, a = self.forward_propagation(x)
losses += self._loss(a, y)
prediction = np.argmax(a[self.number_layers])
expected = np.argmax(y)
if (prediction != expected):
misses += 1
losses = losses / total
accuracy = 100 * (total - misses) / total
return losses, accuracy
def forward_propagation(self, data: np.ndarray):
"""Forward_propagation algorithms.
:param data: A numpy array containing input data such as an image
:return: (z, a) Each layer and activation
"""
z = _create_array(self.number_layers + 1)
a = _create_array(self.number_layers + 1)
a[0] = data
for k in range(1, self.number_layers + 1):
z[k] = np.dot(self.weights[k], a[k - 1]) + self.biaises[k]
a[k] = self._activation(z[k])
return z, a
def backward_propagation(self,
z: List[np.ndarray],
a: List[np.ndarray],
y: np.ndarray):
"""Backward_propagation algorothm.
:param z: An array containing each layer
:param a: An array containing activations of each layer
:param y: A numpy array containing data label
:return: (gradients_w, gradients_b) Computed weights and biaises gradients
"""
gradients = _create_array(self.number_layers + 1)
cost_derivative = self._error_derivative(a, y)
propagation = cost_derivative
for k in range(self.number_layers, 0, -1):
a_derivative = self._activation_derivative(z[k])
gradients[k] = propagation * a_derivative
propagation = np.dot(self.weights[k].T, gradients[k])
gradients_b = _create_array(self.number_layers)
gradients_w = _create_array(self.number_layers)
for k in range(self.number_layers, 0, -1):
gradients_b[k - 1] = gradients[k]
gradients_w[k - 1] = np.dot(gradients[k], a[k - 1].T)
return gradients_w, gradients_b
def _initialize_batch(self, numpy_arrays: List[np.ndarray]):
batch_gradients = []
for i in range(1, len(numpy_arrays)):
batch_gradients.append(np.zeros(numpy_arrays[i].shape))
return batch_gradients
def _initialize_weights(self, layers_size):
preview = layers_size[0]
self.weights = [None] # W_0 does not exist
for i in range(1, len(layers_size)):
layer = layers_size[i]
self.weights.append(self._generate_weights((layer, preview)))
preview = layer
def _initialize_biases(self, layers_size):
self.biaises = [None] # B_0 does not exist
for i in range(1, len(layers_size)):
layer = layers_size[i]
self.biaises.append(self._generate_weights((layer, 1)))
def _loss(self, a, y):
cost = self._error(a, y)
return np.sum(cost)
def _error(self, a, y):
prediction = a[self.number_layers]
error = (prediction - y)
return np.square(error)
def _error_derivative(self, a, y):
prediction = a[self.number_layers]
error = (prediction - y)
return 2 * error
def _update_batch(self, batch_gradients: List[np.ndarray],
gradients: List[np.ndarray]):
for batch_gradient, gradient in zip(batch_gradients, gradients):
batch_gradient += gradient
def _apply_gradients(self, gradients_w: np.ndarray,
gradients_b: np.ndarray):
for i in range(self.number_layers):
self.weights[i + 1] -= self.learning_rate * gradients_w[i]
self.biaises[i + 1] -= self.learning_rate * gradients_b[i]
def save(model: NeuralNetwork, file_name: str):
"""Save the input model using pickle.
:param model: The neural network to be saved
:param file_name: The path to pickle file
"""
parameters = {
'learning_rate': model.learning_rate,
'layers_size': model.layers_size,
'number_layers': model.number_layers,
'batch_size': model.batch_size,
'activation_function': model.activation,
'weights': model.weights,
'biases': model.biaises
}
with open(file_name, 'wb') as file:
pickle.dump(parameters, file)
def load(file_name: str) -> NeuralNetwork:
"""Load a neural network model.
:param file_name: The pickle file containing a saved neural networl
:return: The neural network already initialized or trained
"""
with open(file_name, 'rb') as file:
parameters = pickle.load(file)
return NeuralNetwork(
parameters['layers_size'],
learning_rate=parameters['learning_rate'],
batch_size=parameters['batch_size'],
activation=parameters['activation_function'],
weights=parameters['weights'],
biaises=parameters['biases'])
def _create_array(size):
return [None] * (size)
def _generate_random(shape) -> np.ndarray:
return 2 * np.random.random(shape) - 1
|
180cda553d9f955a107e239dbdb85dc95410cdcc | WisTiCeJEnT/204111-2021-TA | /Lab 07x: Repetition I (extra)/05 Count Vowel.py | 286 | 3.796875 | 4 | # NOT USING STRING.count()
s = input('Enter a string: ')
vo = 'aeiou'
no_of_vo = 0
d = {v: 0 for v in vo}
for c in s:
if c in vo:
d[c] += 1
no_of_vo += 1
for v in vo:
print(f"There are {d[v]} {v}'s.")
print(f'There are {len(s)-no_of_vo} non-vowels characters.') |
f264de16e07c4e44e3ac3032b38ac44a95f5fcf6 | 0alan0/Examples | /TaiChi.py | 2,771 | 3.75 | 4 | import turtle
r = 400 #半径
a =50 #边距
b = 14 #字体大小
x,y = 0,-r
turtle.setup(width=1200,height=1200, startx=500, starty=0)
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('white')
turtle.circle(r,-180)
turtle.circle(r/2,-180)
turtle.circle(-r/2,-180)
turtle.end_fill()
turtle.begin_fill()
turtle.fillcolor('black')
turtle.circle(-r,-180)
turtle.circle(-r/2,180)
turtle.circle(r/2,180)
turtle.end_fill()
turtle.penup()
turtle.goto(x,y+3*r/8)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('white')
turtle.circle(r/8)
turtle.end_fill()
turtle.penup()
turtle.goto(x,y+11*r/8)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('black')
turtle.circle(r/8)
turtle.end_fill()
# =================================================
turtle.penup()
turtle.goto(x,y+3*r/8)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('white')
turtle.circle(r/8,-180)
turtle.circle(r/16,-180)
turtle.circle(-r/16,-180)
turtle.end_fill()
turtle.begin_fill()
turtle.fillcolor('black')
turtle.circle(-r/8,-180)
turtle.circle(-r/16,180)
turtle.circle(r/16,180)
turtle.end_fill()
turtle.penup()
turtle.goto(x,y+27*r/64)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('white')
turtle.circle(r/64)
turtle.end_fill()
turtle.penup()
turtle.goto(x,y+35*r/64)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('black')
turtle.circle(r/64)
turtle.end_fill()
# =================================================
turtle.penup()
turtle.goto(x,y+11*r/8)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('white')
turtle.circle(r/8,-180)
turtle.circle(r/16,-180)
turtle.circle(-r/16,-180)
turtle.end_fill()
turtle.begin_fill()
turtle.fillcolor('black')
turtle.circle(-r/8,-180)
turtle.circle(-r/16,180)
turtle.circle(r/16,180)
turtle.end_fill()
turtle.penup()
turtle.goto(x,y+91*r/64)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('white')
turtle.circle(r/64)
turtle.end_fill()
turtle.penup()
turtle.goto(x,y+99*r/64)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('black')
turtle.circle(r/64)
turtle.end_fill()
#=================================================
turtle.penup()
turtle.goto(x,y-a)
turtle.pendown()
turtle.write("冬至", font=("微软雅黑", b, "normal"))
turtle.penup()
turtle.goto(x-r-a-2*b,y+r)
turtle.pendown()
turtle.write("春分", font=("微软雅黑", b, "normal"))
turtle.penup()
turtle.goto(x,y+2*r+a-b)
turtle.pendown()
turtle.write("夏至", font=("微软雅黑", b, "normal"))
turtle.penup()
turtle.goto(x+r+a,y+r)
turtle.pendown()
turtle.write("秋分", font=("微软雅黑", b, "normal"))
turtle.hideturtle()
turtle.mainloop();
|
11b35163432609cda937aec7064572508a416e06 | algorithm2020/Algorithm_CEK | /06_Stack과Queue/백준/10828_스택.py | 1,654 | 3.84375 | 4 | import sys
class Stack:
#비어있는 스택
def __init__(self):
self.stack=[]
self._top=-1
def push(self, val):
#val을 stack에 넣는다.
self.stack.append(val)
self._top+=1
# 맨위에 있는 정수를 출력
def top(self):
#스택이 비어있다.
if self.empty()==1:
return -1
else:
return self.stack[self._top]
def empty(self):
# 스택이 비어있다
if self._top==-1:
return 1
else:
return 0
def pop(self):
# 스택이 비어있지 않다
if self.empty()!=1:
self._top-=1
return self.stack.pop()
#스택이 비어있다
else:
return -1
#size: 스택이 들어있는 정수의 개수 출력
def size(self):
# 스택이 비어있다
if self.empty()==1:
return 0
#스택이 비어있지 않다면
else:
return len(self.stack)
def main():
s=Stack() #스택객체를 만든다.
N=int(sys.stdin.readline())
for _ in range(N):
commands=sys.stdin.readline().split()
if commands[0]=='push':
s.push(commands[1])
elif commands[0]=='top':
print(s.top())
elif commands[0]=='empty':
print(s.empty())
elif commands[0]=='pop':
print(s.pop())
elif commands[0]=='size':
print(s.size())
if __name__=='__main__':
main()
|
a0036df1e7c0d813c43bd087a2226b3c10a97dcc | niwza/PythonSummerfield | /chap01/average1_ans.py | 610 | 3.96875 | 4 | numbers = []
total = 0
lowest = None
highest = None
while True:
num = input("enter a number or Enter to finish: ")
if not num:
break
try:
i = int(num)
if lowest is None or i < lowest:
lowest = i
if highest is None or i > highest:
highest = i
numbers += [i]
total += i
except ValueError:
print("Please enter a valid integer.")
continue
count = len(numbers)
mean = total / count
print("numbers: ", numbers)
print("count =", count, "sum =", total, "lowest =", lowest, "highest =", highest, "mean =", mean)
|
6bc427081575807a867a5e0353969c50d719e211 | xiaojinghu/Leetcode | /Leetcode0106_Recursion&Hashmap.py | 1,390 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def build(self, inorder, inStart, inEnd, postorder, postStart, postEnd, indexMap):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
# print inStart, inEnd, postStart, postEnd
if inStart>inEnd or postStart>postEnd:
return None
root = TreeNode(postorder[postEnd])
rootIndex = indexMap[root.val]
leftInStart = inStart
leftInEnd = rootIndex-1
leftPostStart = postStart
leftPostEnd = rootIndex-inStart+postStart-1
root.left = self.build(inorder, leftInStart, leftInEnd, postorder, leftPostStart, leftPostEnd, indexMap)
rightInStart = rootIndex+1
rightInEnd = inEnd
rightPostStart = leftPostEnd+1
rightPostEnd = postEnd-1
root.right = self.build(inorder, rightInStart, rightInEnd, postorder, rightPostStart, rightPostEnd, indexMap)
return root
def buildTree(self, inorder, postorder):
indexMap = {}
for i in range(len(inorder)):
indexMap[inorder[i]] = i
return self.build(inorder, 0, len(inorder)-1, postorder, 0, len(inorder)-1, indexMap)
|
4669dcaa51b4239d5ff548cfd4623615715deac7 | T0N1R/Maquina-Turing | /maquina/automata.py | 3,525 | 3.546875 | 4 | """
Logica matematica
Proyecto Final - Maquina de Turing
20/11/2019
Gustavo de Leon #17085
Antonio Reyes #17273
"""
f = open("MT1.txt")
cinta_inicial = ""
for line in f:
cinta_inicial = cinta_inicial + line
def separar_zonas(cinta):
global contador
contador = 0
global separacion
separacion = ""
global previa_zona
previa_zona = 0
zonas = []
#print("la cinta que se ingresa es: ", len(cinta))
for i in range(0, len(cinta)):
if cinta[i] == "1":
contador += 1
if contador >= 6:
separacion = cinta[previa_zona:(i+1)]
#print(separacion)
zonas.append(separacion)
#evitamos que el siguiente sea 1
previa_zona = i + 1
contador = 0
return zonas
class Zona:
def __init__(self, estado1, letra1, estado2, letra2, movimiento):
self.estado1 = estado1
self.estado2 = estado2
self.letra1 = letra1
self.letra2 = letra2
self.movimiento = movimiento
def crear_objetos(lista_de_zonas):
#print("zonas")
lista_objetos = []
for i in range(0, len(lista_de_zonas)):
separaciones = lista_de_zonas[i].split('1')
#print(separaciones)
objeto = Zona(separaciones[0], separaciones[1], separaciones[2], separaciones[3], separaciones[4])
lista_objetos.append(objeto)
return lista_objetos
def separar_segmentos(cinta):
secuencia_inicial = ""
secuencia_2 = ""
secuencia_3 = ""
nueva_secuencia_2 = ""
for i in range(0, len(cinta)):
if cinta[i] == "1":
secuencia_inicial = cinta[ 0 : i ]
secuencia_2 = cinta[ ( i + 1 ) : len(cinta) ]
break
for i in range(0, len(cinta)):
if cinta[i] == "1":
if cinta[ i + 1 ] == "1":
if cinta[ i + 2 ] == "1":
secuencia_3 = cinta[ (i + 3) : len(cinta)]
for i in range(0, len(secuencia_2)):
if cinta[i] == "1":
if cinta[ i + 1 ] == "1":
if cinta[ i + 2 ] == "1":
nueva_secuencia_2 = secuencia_2[ 0 : (i - 1) ]
zonas = separar_zonas(nueva_secuencia_2)
zonas_establecidas = crear_objetos(zonas)
print("**************************************************")
print(" --- ESTADO INICIAL --- ")
print(secuencia_inicial)
print("**************************************************")
print(" --- CINTA CON ZONAS --- ")
print(nueva_secuencia_2)
print(" --- CINTA SEPARADA EN ZONAS --- ")
correcto_secuencia_2 = True
for x in zonas_establecidas:
print(x.estado1, x.letra1, x.estado2, x.letra2, x.movimiento)
for x in zonas_establecidas:
if "1" in x.estado1:
correcto_secuencia_2 = False
if "1" in x.letra1:
correcto_secuencia_2 = False
if "1" in x.estado2:
correcto_secuencia_2 = False
if "1" in x.letra2:
correcto_secuencia_2 = False
if len(x.movimiento) > 3:
correcto_secuencia_2 = False
print("")
print("[[ Validez de esta cadena: ", correcto_secuencia_2, " ]]")
print("**************************************************")
print(" --- CINTA CON LETRAS --- ")
print(secuencia_3)
correcto_secuencia_3 = True
if "11" in secuencia_3:
correcto_secuencia_3 = False
print("[[ Validez de esta cadena: ", correcto_secuencia_3, " ]]")
separar_segmentos(cinta_inicial)
|
56d4b1c0acc94a04fb84021e7ef02f469bcfe3cb | marineam/pycde | /pycde/textui.py | 823 | 3.5 | 4 | #
"""Text User Interface"""
import sys
class TextUI(object):
def choose(self, name, items, fmt=str):
if len(items) == 1:
print "Found %s: %s" % (name, fmt(items[0]))
return items[0]
else:
print '%ss:' % name
for i, item in enumerate(items):
formated = fmt(item).replace('\n', '\n ')
print ' %2d. %s' % (i+1, formated)
choice = int(raw_input('Choose %s: ' % name))
return items[choice - 1]
def status(self, text):
print text
def info(self, text):
print text
def error(self, text):
sys.stderr.write('%s\n' % text)
def yesno(self, prompt):
ok = raw_input('%s [Y/n] ' % prompt)
return not (ok and ok[0].lower() not in ('y', 't', '1'))
|
6276dd412a56ad4452b1acefce53b0605cdf3ef1 | reisthi/SimplePython | /evenorodd.py | 425 | 4.25 | 4 | """ This tests if a number is even or odd"""
print("***************")
print("EVEN or ODD?")
print("***************")
def evenoddtest():
number = int(input("Type a number: "))
remainder = number % 2
result = str(number)
if remainder == 1:
print(result + " is odd.")
else:
print(result + " is even.")
rerun = input("Type 1 to check again.")
if rerun == 1:
evenoddtest()
|
3714c6711965c550226509ba4558b4825f480756 | raviteja1117/sumanth_ketharaju | /keyword_variable.py | 156 | 3.71875 | 4 | def person(name, **data):
print(name)
for i,j in data.items():
print(i, j)
person("sunil",age=21, city="nellore",mob= "98488671452")
|
e860bb0f46bc24c9f4b3bcdcd7df0fc228e80349 | nikhiilll/Data-Structures-and-Algorithms-Prep | /Arrays/GeeksforGeeks/ArrayPairSum.py | 606 | 4.21875 | 4 | import array
"""
The array can be sorted at the start if not sorted and then this method can be used.
"""
def find_pair_sum(arr, sum):
n = len(arr)
left_ptr = 0
right_ptr = n - 1
while left_ptr < right_ptr:
if arr[left_ptr] + arr[right_ptr] > sum:
right_ptr -= 1
elif arr[left_ptr] + arr[right_ptr] < sum:
left_ptr += 1
else:
print("Sum found in: {} {}".format(arr[left_ptr], arr[right_ptr]))
break
else:
print("No sum found")
arr = array.array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
find_pair_sum(arr, 20) |
6cdfc0849816ac192410c7bcd3ecf43c2dcadc78 | O-Huslin/RSA-Encrytion-and-Database | /Sockets/Starter/PaillierClientSocket.py | 5,029 | 3.9375 | 4 | # Client to implement simplified 'secure' electronic voting algorithm
# and send votes to a server
# Author:
# Last modified: 2020-10-07
# Version: 0.1.1
#!/usr/bin/python3
import socket
import random
import math
import sys
class NumTheory:
@staticmethod
def expMod(b,n,m):
"""Computes the modular exponent of a number"""
"""returns (b^n mod m)"""
if n==0:
return 1
elif n%2==0:
return expMod((b*b)%m, n/2, m)
else:
return(b*expMod(b,n-1,m))%m
class PaillierClientSocket:
def __init__(self, host, port):
'''Initialise the host name and port to be used'''
self.host = host
self.port = port
print(host, port, "\n")
votes = [0,0]
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((host, port))
msg1 = "100 Hello"
clientSocket.send(msg1.encode())
msg2 = clientSocket.recv(1024) #receives the key message
print(msg2)
m = clientSocket.recv(1024).decode() #recieves the candidate names
msg = "The candidates voting information are: " + m
m = m.split()
print(msg)
clientSocket.send(msg.encode())
newMsg = clientSocket.recv(1024) #receives the list of candidates
print('The candidates are: ', newMsg.decode())
mg = clientSocket.recv(1024) # receives the 106 message of candidates
print(mg.decode())
#pmsg = clientSocket.recv(1024).decode() #receives polls open message
#print(psmg)
sen = str(input("Please type the name of the candidate you wish to vote for: "))
print(sen)
print(self.vote(sen, m, votes))
sen = sen.upper()
sen = str(sen)
print(sen + " 2")
if self.vote(sen, m, votes) == "Incorrect candidate name entered.":
print(self.vote(sen, m, votes))
print('Please try again')
sen_2 = input("Please type the name of the candidate you wish to vote for: ")
print(self.vote(sen_2, m, votes))
else:
print("Please restart and try again.")
print(votes)
clientSocket.close()
def ProcessMsgs(self):
"""Main event processing method"""
pass
def mysend(self, msg):
"""Accepts message into the socket"""
clientSocket.send(msg)
def myreceive(self):
"""Add code here to read data from the socket"""
newSen = clientSocket.recv(1024)
def vote(self, w, l_names, v_lst):
self.w = w
self.l_names = l_names
self.v_lst = v_lst
l_names += [1]
if w == l_names[0]:
v_lst[0] += 1
agn = input('Type Y is you would like to vote again or N if not.')
if agn == 'Y' or 'y':
v_again = input('Please type the name of the candidate:')
vote(v_again, l_names, v_lst)
else:
return 'Thank you for voting'
elif w == l_names[1]:
v_lst[1] += 1
agn_2 = input('Type Y is you would like to vote again or N if not.')
if agn_2 == 'Y' or 'y':
v_again2 = input('Please type the name of the candidate:')
vote(v_again2, l_names, v_lst)
else:
return 'Thank you for voting'
elif w != l_names[0] or l_names[1]:
return "Incorrect candidate name entered."
'''
This will be run if you run this script from the command line. You should not
change any of this; the grader may rely on the behavior here to test your
submission.
'''
if __name__ == "__main__":
args = sys.argv
if len(args) != 3:
print ("Please supply a server address and port.")
# sys.exit()
serverHost = str(args[1]) # The remote host
serverPort = int(args[2]) # The same port as used by the server
print(serverHost, serverPort)
print("Client of Orley M. Huslin")
c = PaillierClientSocket( serverHost, serverPort)
c.close()
|
f01342d67e3b41d818fdc27e9c6399de588bff87 | alineat/web-scraping | /33.funcao-compile-character-class.py | 1,333 | 4 | 4 | import re # módulo regular expression
# Expressão é compilada em bytecode e executada por um mecanismo de combinação escrito em C
# Usada para combinar caracteres, encontrar tags ou dados em uma árvore sintática
# Por ex. a expressão "abc" está na string "abcdef"
# Exceção: metacaracteres não dão "match"
# Lista de Metacaracteres: . ^ $ * + ? {} [] \ | ()
regex = re.compile('a') # retorna um objeto regex
print(regex.match('a')) # verifica se a expressão regex está na string.
regex = re.compile('ab')
print(regex.match('a')) # Retorna None se não encontrar
# character class: aceita qualquer caracter que esteja dentro do []
regex = re.compile('[abc]')
print(regex.match('a'))
print(regex.match('d')) # retorna None se colocar qualquer coisa que não seja os caracteres dessa classe
regex = re.compile('[a-f]') # posso escrever como intervalo
print(regex.match('e'))
regex = re.compile('[a-z]')
print(regex.match('C')) # case sensitive
regex = re.compile('[a-zA-Z]')
print(regex.match('C'))
# Complementar do conjunto a-zA-Z, ou seja, todos os caracteres que não estejam nessa classe de caracteres
regex = re.compile('[^a-zA-Z]')
print(regex.match('1'))
# Metacaracteres perdem o seu significado quando estão dentro de uma classe de caracteres
regex = re.compile('[+]')
print(regex.match('+'))
|
87e2503f1b69762e97395d1158495209bb27b1b1 | cmrad/Mini-Python-Programs | /madLibsGame.py | 8,943 | 4.5625 | 5 | '''
Let’s build an old, popular game: Mad Libs. We’ll start by getting input from the user, just like in a real Mad
Libs game, and use the user’s responses in our story. The starting version of this game has nothing to do with
lists, but once we build the base game, we’ll modify it to use lists.
'''
# MadLib (version 1)
while True:
name = input('Enter a name: ')
verb = input('Enter a verb: ')
adjective = input('Enter an adjective: ')
noun = input('Enter a noun: ')
sentence = name + ' ' + verb + ' through the forest, hoping to escape the ' + \
adjective + ' ' + noun + '.'
print()
print (sentence)
print()
# See if the user wants to quit or continue
answer = input('Type "q" to quit, or anything else (even Return/Enter) to continue:')
if answer == 'q':
break
print ('Bye')
'''
Now, we’ll change the program. Rather than having the user enter a name, we’ll build a pool of names and
select one randomly for the user. The pool of predetermined names will be built as a list. We could use any
names for our list, but to make our Mad Libs game fun, our list will look like this:
'''
namesList = ['Roberto Manrique', 'The Teenage Mutant Ninja Turtles', 'Carmen Villalobos', \
'The Stay Puft Marshmallow Man', 'Shrek', 'Sherlock Holmes', \
'The Beatles', 'Maluma', 'The Pillsbury Doughboy']
'''
Next, we want to choose a random name from this list. This particular list has nine elements in it.
In order to select a random element from the list, we need to generate a random index between 0 and 8
(remember, list indices start at zero).
'''
import random
##randomIndex = random.randrange (<lowerLimit>, <upToButNotIncluding>)
'''
Again, our goal is to select a random number to use as an index of an element in the list. With our list of
nine names, we would call random.randrange , passing in a 0 and a 9. It would return a random integer of 0
to 8 (up to but not including 9). The resulting program would look like this:
'''
# MadLib (version 2)
import random
namesList = ['Roberto Manrique', 'The Teenage Mutant Ninja Turtles', 'Carmen Villalobos', \
'The Stay Puft Marshmallow Man', 'Shrek', 'Sherlock Holmes', \
'The Beatles', 'Maluma', 'The Pillsbury Doughboy']
while True:
nameIndex = random.randrange(0, 9) # Choose a random index into the namesList
name = namesList[nameIndex] # Use the index to choose a random name
verb = input('Enter a verb: ')
adjective = input('Enter an adjective: ')
noun = input('Enter a noun: ')
sentence = name + ' ' + verb + ' through the forest, hoping to escape the ' + \
adjective + ' ' + noun + '.'
print()
print (sentence)
print()
# See if the user wants to quit or continue
answer = input('Type "q" to quit, or anything else (even Return/Enter) to continue: ')
if answer == 'q':
break
print ('Bye')
# MadLib (version 3)
import random
namesList = ['Roberto Manrique', 'The Teenage Mutant Ninja Turtles', 'Carmen Villalobos', \
'The Stay Puft Marshmallow Man', 'Shrek', 'Sherlock Holmes', \
'The Beatles', 'Maluma', 'The Pillsbury Doughboy', 'Ellen Degeneres']
nNames = len(namesList) # find out how many names are in the list of names
while True:
nameIndex = random.randrange(0, nNames) # Choose a random index into the namesList
name = namesList[nameIndex] # Use the index to choose a random name
verb = input('Enter a verb: ')
adjective = input('Enter an adjective: ')
noun = input('Enter a noun: ')
sentence = name + ' ' + verb + ' through the forest, hoping to escape the ' + \
adjective + ' ' + noun + '.'
print()
print (sentence)
print()
# See if the user wants to quit or continue
answer = input('Type "q" to quit, or anything else (even Return/Enter) to continue:')
if answer == 'q':
break
print ('Bye')
'''
Notice that in this version, we’ve added another name to our list of names. But we also used the len
function to set a variable, nNames , to the number of elements in our list of names. Finally, we used that
variable in our call to randrange . Using this approach, we can put as many names in our list as we wish, and
the code will adjust at runtime for us.
'''
'''
Similar to the modification to use a list of names, let’s modify the program to include a list of verbs, a list of
adjectives, and a list of nouns. The program should randomly choose a name, a verb, an adjective, and a
noun. You can put as many elements as you want into each list, and the program should create and print a
fully randomized Mad Lib.
'''
# MadLib (version 4)
import random
namesList = ['Roberto Manrique', 'The Teenage Mutant Ninja Turtles', 'Carmen Villalobos', \
'The Stay Puft Marshmallow Man', 'Shrek', 'Sherlock Holmes', \
'The Beatles', 'Maluma', 'The Pillsbury Doughboy', 'Ellen Degeneres']
nNames = len(namesList) # find out how many names are in the list of names
verbsList = ['screamed', 'burped', 'ran', 'galumphed', 'rolled', 'ate', 'laughed', \
'complained', 'whistled']
nVerbs = len(verbsList)
adjectivesList = ['purple', 'giant', 'lazy', 'curly-haired', 'wireless electric', \
'ten foot tall']
nAdjectives = len(adjectivesList)
nounsList = ['ogre', 'dinosaur', 'Frisbee', 'robot', 'staple gun', 'hot dog vendor', \
'tortoise', 'rodeo clown', 'unicorn', 'Santa hat', 'garbage can']
nNouns = len(nounsList)
while True:
nameIndex = random.randrange(0, nNames) # Choose a random index into the namesList
name = namesList[nameIndex] # Use the index to choose a random name
verbIndex = random.randrange(0, nVerbs)
verb = verbsList[verbIndex]
adjectiveIndex = random.randrange(0, nAdjectives)
adjective = adjectivesList[adjectiveIndex]
nounIndex = random.randrange(0, nNouns)
noun = nounsList[nounIndex]
sentence = name + ' ' + verb + ' through the forest, hoping to escape the ' + \
adjective + ' ' + noun + '.'
print()
print (sentence)
print()
# See if the user wants to quit or continue
answer = input('Type "q" to quit, or anything else (even Return/Enter) to continue:')
if answer == 'q':
break
print('bye')
'''
In the prior code, you may have noticed a pattern. For each of the four lists ( nounsList , verbsList ,
adjectivesList , and nounsList ), we have built essentially the same code. Whenever we wanted to select
a random element, we chose a random index, and then found the element at that index. While this clearly
works, whenever we see essentially the same code repeated, that is a signal that it is probably a good
candidate to turn into a function. In this case, rather than repeating the same set of operations four times,
we’ll build a single function to select a random element from a list and call it four times.
'''
# MadLib (version 5)
import random
def chooseRandomFromList(aList):
nItems = len(aList)
randomIndex = random.randrange(0, nItems)
randomElement = aList[randomIndex]
return randomElement
namesList = ['Roberto Manrique', 'The Teenage Mutant Ninja Turtles', 'Carmen Villalobos', \
'The Stay Puft Marshmallow Man', 'Shrek', 'Sherlock Holmes', \
'The Beatles', 'Maluma', 'The Pillsbury Doughboy', 'Ellen Degeneres']
verbsList = ['screamed', 'burped', 'ran', 'galumphed', 'rolled', 'ate', 'laughed', \
'complained', 'whistled']
adjectivesList = ['purple', 'giant', 'lazy', 'curly-haired', 'wireless electric', \
'ten foot tall']
nounsList = ['ogre', 'dinosaur', 'Frisbee', 'robot', 'staple gun', 'hot dog vendor', \
'tortoise', 'rodeo clown', 'unicorn', 'Santa hat', 'garbage can']
while True:
name = chooseRandomFromList(namesList)
verb = chooseRandomFromList(verbsList)
adjective = chooseRandomFromList(adjectivesList)
noun = chooseRandomFromList(nounsList)
sentence = name + ' ' + verb + ' through the forest, hoping to escape the ' + \
adjective + ' ' + noun + '.'
print()
print (sentence)
print()
# See if the user wants to quit or continue
answer = input('Type "q" to quit, or anything else (even Return/Enter) to continue:')
if answer == 'q':
break
print ('Bye')
'''
In this version, we’ve built a small function called chooseRandomFromList . It is designed to expect to
have one parameter passed in when it is called. It is expected to be passed in a list. The aList parameter
variable takes on the value of the list passed in. We used a very generic name here because we do not know
what the contents of the list are, and inside the function, we do not care. The function uses the len function
to see how many items are in the list, chooses a random index, finds the element at that index, and returns
that element. From the main code, we now call the function four times, passing in four different lists. This
version of the code generates the same type of Mad Libs sentences as the earlier version, but it is easier to
read and is less prone to errors.
'''
|
250f423e2e829cfb393d748bdd6e372fa9938c65 | dharunsri/Python_Journey | /User_Input.py | 742 | 4.25 | 4 | # To get input from user
# Method 1
x = int(input("Enter the 1st number ")) # input() gets input from user
y = int(input("Enter the 2nd number "))
z = x+y
print(z)
# Method 2 [passing arguments from cmd]
"""
import sys
a = int(sys.argv[1]) # argv - argument passes from the user. argv - present in the sys module
b = int(sys.argv[2])
c = a+b
print(c) """
# Method 3
# Get a char
# from user
# But python has string only not a char datatype
# But this made gets only one char as input and print even user gave a string
ch = input("Enter a character: ")[0]
print(ch)
# Another method to evaluate a expression
# Here we use a function called eval
exp = eval(input("Enter a expression: "))
print(exp) |
1612856b713552f32defccb865ee87d14b022aeb | 21eleven/leetcode-solutions | /python/1305_all_elements_in_two_binary_search_trees/bfs_n_sort.py | 1,201 | 3.9375 | 4 | """
1305. All Elements in Two Binary Search Trees
Medium
Given two binary search trees root1 and root2.
Return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]
Example 3:
Input: root1 = [], root2 = [5,1,7,0,2]
Output: [0,1,2,5,7]
Example 4:
Input: root1 = [0,-10,10], root2 = []
Output: [-10,0,10]
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
output = []
nodes = deque()
if root1:
nodes.append(root1)
if root2:
nodes.append(root2)
while nodes:
n = nodes.popleft()
output.append(n.val)
if l := n.left:
nodes.append(l)
if r := n.right:
nodes.append(r)
return sorted(output)
|
cca18a959fd5280d4fe815eb7fb04bbcdbff59a3 | hectorsum/python-exercises | /Sem01/formulario.py | 1,679 | 3.8125 | 4 | import tkinter as tk
from tkinter import ttk
#from tkinter.ttk import *
window = tk.Tk()#creando el formulario
window.title("Sistemas Inteligentes")# colocandole un titulo
window.geometry('500x200')# dandole dimension al formulario
lbl1 = tk.Label(window,text="Ingrese primer valor: ")#creando un etiqueta
lbl1.grid(column=0,row=0)# asignando posicion a esa etiqueta
txt1 = tk.Entry(window,width=10)
txt1.grid(column=1,row=0)# asignando posicion a esa txt1
def mifuncion():
lbl1.configure(text="Hola mundo "+txt1.get())#modificando un atributo del lbl
print("le has clicado al boton")
btn1 = tk.Button(window,text="Boton",command=mifuncion)#creando un boton
btn1.grid(column=2,row=0)# asignando posicion a esa boton
lbl2 = tk.Label(window,text="Ingrese segundo valor: ")#creando un etiqueta
lbl2.grid(column=0,row=1)# asignando posicion a esa etiqueta
txt2 = tk.Entry(window,width=10)
txt2.grid(column=1,row=1)# asignando posicion a esa txt1
def sumar(a,b):
return a+b
def mifuncion2():
a = int(txt1.get())
b = int(txt2.get())
lbl2.configure(text="la suma es: "+str(sumar(a,b)))#modificando un atributo del lbl
print("Has seleccionado: ",cbo1.get())
btn2 = tk.Button(window,text="Sumar",command=mifuncion2)#creando un boton
btn2.grid(column=2,row=1)# asignando posicion a esa boton
cbo1 = ttk.Combobox(window)
cbo1['values']=("sumar","restar","multiplicar","potencia")
cbo1.current(1)
cbo1.grid(column=1,row=2)
window.mainloop()#mostrar el formulario
# tarea seleccionar por combo o por radio button la operacion
# matematica que desea realizar (sumar, restar , multiplicar y potencia)
|
47ac9eea5e11dd2f5d5e59c088fdbd09605e37ee | BrandonDotson65/LeetCode | /plusOne.py | 749 | 4.03125 | 4 | # You are given a large integer represented as an integer array digits, where
# each digits[i] is the ith digit of the integer. The digits are ordered from
# most significant to least significant in left-to-right order. The large integer
# does not contain any leading 0's.
# Increment the large integer by one and return the resulting array of digits.
def plusOne(numberList):
if len(numberList) == 1 and numberList[0] == 9:
return [1, 0]
elif numberList[-1] != 9:
numberList[-1] += 1
return numberList
else:
numberList[-1] = 0
numberList[:-1] = plusOne(numberList[:-1])
return numberList
numList = [1, 2, 3]
numList2 = [4, 3, 2, 1]
numList3 = [7, 6, 2, 9]
print(plusOne(numList3)) |
d37a20f3c7d7298431deca22b793b2d6ca2b01e4 | liweicai990/learnpython | /Code/Basic/Basic07.py | 778 | 4.09375 | 4 | '''
功能:计算一元二次方程的实数根
重点:多分支结构if...elif...else...的用法
作者:薛景
最后修改于:2019/05/25
'''
a,b,c = input("请输入一元二次方程的系数a、b、c,用空格分开:").split()
a,b,c = float(a),float(b),float(c)
d = b**2 - (4 * a * c) # 两个星号“**”表示幂运算,即“b**2”等价于“b*b”
if d<0:
print("方程没有实数根")
elif d>0:
x1 = (-b + d**0.5)/(2 * a)
x2 = (-b - d**0.5)/(2 * a)
print("方程有两个实数根:%.2f和%.2f" % (x1,x2))
else:
x = (-b)/(2 * a)
print("方程只有一个实数根:%.2f" % x)
'''
思考题:编写程序输入三角形的三条边,判断三角形的类型(等边、等腰、直角、等腰直接、普通)
''' |
744f89ef0ea85bc653bc050d6efd1384217fc543 | bingx1/leetcode-solutions | /medium/46.py | 747 | 3.71875 | 4 |
class Solution:
"""
Level0: []
level1: [1] [2] [3]
level2: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2]
level3: [1,2,3] [1,3,2] [2,1,3][2,3,1] [3,1,2][3,2,1]
"""
def permute(self, nums: List[int]) -> List[List[int]]:
result = []
self.backtracking(result, [], nums)
return result
def backtracking(self, res, subset, nums):
if len(subset) == len(nums):
res.append(subset)
return
for num in nums:
if num in subset:
continue
self.backtracking(res, subset + [num], nums)
return
#warning: involves deep copying of subset - o(n * n!)
|
034628f2fa35b422caf812e58f66577e5086fbd3 | NachikethP/LOOPS | /posint.py | 158 | 3.71875 | 4 | list=eval(input("Input:"))
count=0
print("Output:",end=" ")
while count<len(list):
if list[count]>0:
print(list[count],end=" ")
count=count+1
|
17ce688c53d80bbaf1b70204e5401a4f777e899a | BansiddhaBirajdar/python | /assignment21/ass21Q1.py | 669 | 4.1875 | 4 | '''1. Accept N numbers from user and return difference between summation
of even elements and summation of odd elements.
Input : N : 6
Elements : 85 66 3 80 93 88
Output : 53 (234 - 181)'''
def diff(l):
even=0
odd=0
for i in range(len(l)):
if(l[i]%2==0):
even+=l[i]
else:
odd+=l[i]
return(even-odd)
def main():
ino=int(input("Enter the how you wanna insert :: "))
l=[]
for i in range(ino):
a=int(input(f"enter the l[{i+1}]:: "))
l.append(a)
ans=diff(l)
print(f"Summation of even elements and summation of odd elements differences {ans}")
if __name__ == '__main__':
main() |
575f8109d9c44edc63db3dcb1385acde17aff878 | atbba3000/python-learning | /remainder.py | 170 | 4.15625 | 4 | a=int(input("enter the 1st digit"))
b=int(input("enter the 2nd digit"))
quotient=a//b
remainder=a%b
print("quotient is:",quotient)
print("remainder is:",remainder)
|
5c5d41f8e78601f80c552a73bc77777fb69e377b | hot-graphs/hot-plots-gtk | /batch.py | 2,167 | 3.609375 | 4 | #!/usr/bin/env python3
import click
from data_source import get_temperature_data
from data_source import plot_temperature_data
@click.command()
@click.option("--altitude", default="", help="Select a comma-separated temperature range like \"200,300\"")
@click.option("--greenery", default="", help="Select a comma-separated greenery range like \"0.1,0.5\"")
@click.option("--month", default=-1, help="Select a month")
@click.option("--hour", default=-1, help="Select a one-hour slice of a day")
@click.option("--year", default=-1, help="Select a year")
@click.option("--id", default="", help="Select concrete ID of a sensor")
@click.option("--x", default="month", help="What should be displayed on horizontal axis")
@click.option("--y", default="temperature", help="What should be displayed on vertical axis")
@click.option("--address", default="", help="Address of sensors")
@click.option("--width", default=1024)
@click.option("--height", default=768)
@click.argument("output_path")
def batch(x, y, id, output_path, month, hour, year, altitude, greenery, width, height, address):
if not id:
id = None
if hour < 0:
hour = None
if month < 0:
month = None
if year < 0:
year = None
if altitude:
altitude=tuple((int(a) for a in altitude.split(",")))
if len(altitude) != 2:
print("Altitude must be set as two comma-separated values")
exit(-1)
else:
altitude=None
if greenery:
greenery=tuple((float(a) for a in greenery.split(",")))
if len(greenery) != 2:
print("Greenery must be set as two comma-separated values")
exit(-1)
else:
greenery=None
try:
data = get_temperature_data(id=id, hour=hour, month=month, year=year, altitude_range=altitude, greenery_range=greenery, axes=(x, y), address=address)
except RuntimeError as err:
print("Cannot read data.")
print(err)
exit(-1)
plot_temperature_data(data, output_path, width=width, height=height)
print("Output written to {0}.".format(output_path))
if __name__ == "__main__":
batch()
|
d05cfbecab6b0b581be6bca68b49b04e803259ff | keinen-lab/design-pattern-python | /FactoryMethodPattern.py | 1,077 | 3.828125 | 4 | class Pizza:
HAM_MUSHROOM_PIZZA_TYPE = 0
DELUXE_PIZZA_TYPE = 1
SEAFOOD_PIZZA_TYPE = 2
def __init__(self, price):
self.__price = price
def getPrice(self):
return self.__price
class HamAndMushroomPizza(Pizza):
def __init__(self):
super().__init__(8.50)
class DeluxePizza(Pizza):
def __init__(self):
super().__init__(10.50)
class SeafoodPizza(Pizza):
def __init__(self):
super().__init__(11.50)
class PizzaFactory:
def createPizza(pizzaType):
if pizzaType == Pizza.HAM_MUSHROOM_PIZZA_TYPE:
print("Ham Mushroom Pizza")
return HamAndMushroomPizza()
elif pizzaType == Pizza.DELUXE_PIZZA_TYPE:
print("Deluxe Pizza")
return DeluxePizza()
elif pizzaType == Pizza.SEAFOOD_PIZZA_TYPE:
print("Seafood Pizza")
return SeafoodPizza()
else:
return DeluxePizza()
if __name__ == '__main__':
pizzaPrice = PizzaFactory.createPizza(Pizza.SEAFOOD_PIZZA_TYPE).getPrice()
print(pizzaPrice)
|
e43bb5a7481a409719f4e631542bea027813ce12 | songjy6565/alg-py | /programmers/level4/A.17685.py | 1,639 | 3.546875 | 4 | def solution(words):
answer = 0
words = sorted(words)
length = len(words)
target = 'dummy'
index = 0
while True:
#print(index, length, answer, words)
if length <= 1:
if target == words[0][0]:
answer += 2
return answer
answer += 1
return answer
if index >= length:
index = 0
target = 'dummy'
continue
if target != words[index][0]:
if index != 0:
return answer+solution(words[0:index])+solution(words[index:])
if index == length-1:
answer += 1
words.pop(index)
length -= 1
continue
if words[index][0] == words[index+1][0]:
target = words[index][0]
if len(words[index]) != 1:
words[index] = words[index][1:]
answer += 1
index += 1
continue
else:
answer += 1
words.pop(index)
length -= 1
continue
else:
answer += 1
words.pop(index)
length -= 1
continue
else:
if len(words[index]) != 1:
words[index] = words[index][1:]
answer += 1
index += 1
continue
else:
answer += 1
words.pop(index)
length -= 1
continue
return answer |
9e15e5e76d325b2328a8e94b873408ec25e4dce7 | gurmeetkhehra/python-practice | /IfConditionPizza.py | 1,144 | 3.859375 | 4 | # pizza_topping = ['Olive', 'Mushroom', 'Tomato', 'Cheese', 'Pineapple']
# if 'Olive' in pizza_topping:
# print('Adding Olive')
# if 'Mushroom' in pizza_topping:
# print('Adding Mushroom')
# if 'Tomato' in pizza_topping:
# print('Adding Tomato')
# if 'Cheese' in pizza_topping:
# print('Adding Cheese')
# if 'Pineapple' in pizza_topping:
# print('Adding Pineapple')
# if 'Garlic' in pizza_topping:
# print('Adding Garlic')
# if 'Olive' in pizza_topping:
# print('Adding Olive')
# if 'Mushroom' in pizza_topping:
# print('Adding Mushroom')
# if 'Tomato' in pizza_topping:
# print('Adding Tomato')
# if 'Cheese' in pizza_topping:
# print('Adding Cheese')
# if 'Pineapple' in pizza_topping:
# print('Adding Pineapple')
pizza_topping = ['Pepperoni', 'Chicken', 'Pork', 'Cheese', 'Beef']
if 'Pepperoni' in pizza_topping:
print ('Put on the Pepperoni ')
if 'Chicken' in pizza_topping:
print ('Put on the Chicken')
if 'Pork' in pizza_topping:
print ('Put on the Pork')
if 'Cheese' in pizza_topping:
print ('Put on the Cheese')
if 'Beef' in pizza_topping:
print ('Put on the Beef')
|
f049637b7e58176677963ea36f5b4857bc2a3dcb | zVelto/Python-Basico | /aula22/aula22.py | 552 | 4.03125 | 4 | # texto = 'Python'
#
# for letra in texto:
# print(letra)
# for numero in range(20, 10, -2):
# print(numero)
#
# for numero in range(0, 100, 8):
# print(numero)
# for n in range(100):
# if n % 8 == 0:
# print(n)
# continue - pula para o próximo laço
# break - termina o laço
texto = 'python'
nova_string = ''
for letra in texto:
if letra == 't':
nova_string += letra.upper()
elif letra == 'h':
nova_string += letra.upper()
break
else:
nova_string += letra
print(nova_string)
|
a831bbe132c084e7949875490f7b80e3f19616db | sneharnair/Competitive-Coding-1 | /Problem1_missing_number_in_sorted.py | 4,183 | 3.921875 | 4 | # APPROACH:1 BRUTE FORCE SOLUTION
# Time Complexity : O(n^2) - n is the length of nums
# Space Complexity : O(n) - n is the size of set same as the length of nums
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None
# Your code here along with comments explaining your approach
# 1. Create a set and store all numbers from 0 to n in it.
# 2. For each element in set, check if the number exist in nums. (Can do other way - for each num in nums, check whether in set but need to keep track of which all numbers are seen)
# 3. Return that element which is not present in nums
class Solution:
def missingNumber(self, nums: List[int]) -> int:
if not nums:
return None
set_nums = set()
for num in range(0, len(nums) + 1):
set_nums.add(num)
for num in set_nums:
if num not in nums:
return num
# APPROACH:2 BRUTE FORCE SOLUTION / INTERMEDIATE one
# Time Complexity : O(n) - n is the length of nums
# Space Complexity : O(n) - n is the length of the list created which is passed to sum for total_sum
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None
# Your code here along with comments explaining your approach
# 1. Find the total sum ie., sum of list of all elements from 0 to n
# 2. Find the sum of given list - nums
# 3. Get the difference of above 2 sums and that's the missing element.
class Solution:
def missingNumber(self, nums: List[int]) -> int:
if not nums:
return None
total_sum = sum([i for i in range(len(nums) + 1)])
nums_sum = sum([i for i in nums])
return total_sum - nums_sum
# APPROACH:3 OPTIMAL SOLUTION
# Time Complexity : O(n lg n) actually. O(lg n) - n is the length of the sorted array (here I have sorted it as input is unsorted in leetcode)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes (need to sort the input)
# Any problem you faced while coding this : None
# Your code here along with comments explaining your approach
# 1. Initialize start to 0 and end to len(nums) - 1. Compute mid
# 2. If mid (index) not same as nums[mid] (array value) -> check its difference with it's left neighbor -> If 2, then found the missing element - nums[mid] - 1
# -> We have overshot the missing elment, need to go to the part before
# this element (left side of it)
# 3. If mid (index) not same as nums[mid] (array value) -> need to go right of it as all elements before this element are present as ind == arr[ind]
class Solution:
def missingNumber(self, nums: List[int]) -> int:
if not nums:
return None
nums.sort()
start, end = 0, len(nums) - 1
while start <= end:
mid = start + (end - start) // 2
if mid != nums[mid]:
if mid == 0 or nums[mid] - nums[mid - 1] == 2:
return nums[mid] - 1
else:
end = mid - 1
else:
start = mid + 1
return len(nums)
# ANOTHER WAY OF IMPLEMENTING
class Solution:
def missingNumber(self, nums: List[int]) -> int:
if nums is None:
return None
nums.sort()
if nums[0] != 0:
return 0
start, end = 0, len(nums) - 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] > mid:
if mid == 0 or nums[mid - 1] == mid - 1:
return mid
else:
end = mid - 1
elif nums[mid] == mid:
start = mid + 1
return len(nums)
|
79600d48b98302005c454310b459f38748fe019a | Edyta2801/Python-kurs-infoshareacademy | /code/Day_9/samochod.py | 812 | 3.578125 | 4 | class Samochod(object):
'''Definiuje atrybuty i metody samochodu'''
def __init__(self, marka, kolor):
'''Konstruktor, tworzy nowe instancje'''
self.producent = marka
self.kolor = kolor
self.czy_jedzie = None
self.silnik = None
def zatrab(self, intensywnosc):
'''
Trąbi w zależności od intensywności
:param intensywnosc: int, długość trąbienia w sekundach
:return: str, reprezentacja dźwięku klaksonu
'''
if intensywnosc > 10:
return 'PIIIIIIIIIIIIII'
else:
return ('p' + 'i' * intensywnosc)
def jedz(self):
'''Rzozpedza samochod'''
self.czy_jedzie = True
def zatrzymaj(self):
'''Zatrzymuje samochod'''
self.czy_jedzie = False
|
abe59f6662114fb011d1a351502b904aa72d443a | cravo123/LeetCode | /Algorithms/0034 Find First and Last Position of Element in Sorted Array.py | 1,208 | 3.703125 | 4 | import bisect
# Solution 1, implement bisect functions
class Solution:
def lower_bound(self, nums, target):
i, j = 0, len(nums) - 1
while i < j:
m = (i + j) // 2
if nums[m] < target:
i = m + 1
else:
j = m
return i if nums[i] == target else -1
def upper_bound(self, nums, target):
i, j = 0, len(nums)
while i < j:
m = (i + j) // 2
if nums[m] <= target:
i = m + 1
else:
j = m
return i - 1 if nums[i - 1] == target else -1
def searchRange(self, nums: List[int], target: int) -> List[int]:
if not nums:
return [-1, -1]
i, j = self.lower_bound(nums, target), self.upper_bound(nums, target)
return [i, j]
# Solution 2, use bisect directly
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
i = bisect.bisect_left(nums, target)
j = bisect.bisect_right(nums, target)
if i == len(nums) or nums[i] != target:
return [-1, -1]
return [i, j - 1] |
23040b54237942ab7555e1ecb9695633b608d08b | rodrigobn/Python | /Lista de exercicio 2 (print, input, tipos primitivos)/ex18.py | 289 | 3.65625 | 4 | #18. Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo
# que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) – 58.
altura = float(input("Altura em m = "))
pesoIdeal = (72.7 * altura) - 58
print("O seu peso ideal é: {:.2f}".format(pesoIdeal)) |
f02907f738abb86f7e9e72d522180aaaf4e25ff6 | cloudsecuritylabs/learningpython3 | /ch1/aksforage1.py | 371 | 4.1875 | 4 | print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
height = input()
print("what is your weight?", end=' ')
weight = input()
# Print using format
print('You are {} years old, {} inches tall and you weight {} lbs'.format(age, height, weight))
# Print using f
print(f'You are {age} years old, {height} inches tall and {weight} lbs heavy') |
ae4f2935775b02d388ab3840d84511d777ffed36 | WeikangChen/algorithm | /lintcode/180_binary-representation/binary-representation.py | 1,438 | 3.640625 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: chenweikang
@Problem: http://www.lintcode.com/problem/binary-representation
@Language: Python
@Datetime: 16-07-09 14:04
'''
class Solution:
#@param n: Given a decimal number that is passed in as a string
#@return: A string
def binaryRepresentation(self, n):
def parseIntegral(i):
if not i or i == "0":
return "0"
t = int(i)
integral = ""
while t:
integral = str(t % 2) + integral
t >>= 1
return integral
def parseFraction(f):
frac = float("0." + f)
fraction = ""
while frac:
if len(fraction) > 32:
return 'ERROR'
r = frac * 2
if r >= 1:
frac = r - 1
fraction += '1'
else:
frac = r
fraction += '0'
return fraction
if '.' not in n:
return parseIntegral(n)
else:
i, f = n.split('.')
integral = parseIntegral(i)
fraction = parseFraction(f)
if not fraction:
return integral
if fraction == "ERROR":
return "ERROR"
return integral + '.' + fraction |
80c25ea7a717874557d0d3365588b167a8e25fa3 | AnchanaK24/python | /Day11.py | 575 | 3.96875 | 4 | #ex1
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l = list(zip(l1, l2))
print(l)
#ex2
from itertools import zip_longest
numbers=[1,2,3,4,5,6,7,8]
letters=['a','b','c','d','e','f','g','h']
longest=range(1,9)
zipped=zip_longest(numbers,letters,longest,fillvalue='?')
l=list (zipped)
print(l)
#ex3
a=[6,8,5,7,2,3,4,1]
a.sort()
print(a)
#ex4
numbers = [1,2,6,7,13,14,12,17,16,53,67,34,75,48]
def even_numbers(num):
if(num%2 == 0):
return True
else:
return False
evenNums = filter(even_numbers, numbers)
print('Even Numbers are:')
for num in evenNums:
print(num)
|
d98c9cc6acac6fb41d1b086a5b18943cab0e4b88 | NITIN-ME/Python-Algorithms | /arraysum.py | 481 | 3.59375 | 4 | def summer(arr, start, end):
if(start == end):
return arr[start]
elif(start >= end):
return 0
else:
mid = (start + end)//2
return summer(arr, start, mid) + summer(arr, mid + 1, end)
def basic(arr):
sum = 0
for i in arr:
sum += i
return sum
def tailrec(arr, n):
if(n < 0):
return 0
else:
return arr[n] + tailrec(arr, n-1)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print(summer(arr, 0, len(arr) - 1))
print(basic(arr))
print(tailrec(arr, len(arr) - 1))
|
70f2450b01140a2f7273fe990f146b8d6a766a21 | johndrew/AirplaneBoardingSimulator | /models/passenger.py | 3,859 | 3.5 | 4 | import uuid
from random import uniform
from constants import time_to_pass_one_row as walking_speeds, \
time_to_load_carry_on as loading_speeds, \
time_to_install_in_seat as seating_speeds
class Passenger():
def __init__(self, env, seat, airplane):
"""
Represents a passenger boarding the airplane.
Passengers:
- walk to seat
- load carry on
- sit down
Variables:
- waiting in line
- loading carry on away from seat
- passenger has to unseat for this passenger to seat
"""
self.env = env
self.assigned_seat = seat
self.id = uuid.uuid4()
self.walking_speed = walking_speeds['maximum']
self.loading_speed = get_process_speed(loading_speeds)
self.seating_speed = get_process_speed(seating_speeds)
self.airplane = airplane
self.walk_process = None
self.current_row = None
self.is_seated = False
def walk_one_row(self):
"""
Simulates a passenger walking a single row.
"""
# print 'passenger %s is walking a row' % self.assigned_seat
self.env.total_time += self.walking_speed
return self.env.timeout(self.walking_speed)
def load_carry_on(self):
"""
Process of a passenger loading a carry on item.
It is assumed that each passenger has only 1 carry on and that no
passenger does not have a carry on.
Initially it is assumed that there is room for every passenger's
bags in the overhead compartment directly above th passenger's seat
"""
# print 'passenger %s is loading a carry on item' % self.assigned_seat
self.env.total_time += self.loading_speed
yield self.env.timeout(self.loading_speed)
def seat_self(self):
"""
Process of a passenger seating him or herself.
"""
# print 'passenger %s is now seating' % self.assigned_seat
self.env.total_time += self.seating_speed
return self.env.timeout(self.seating_speed)
def stop_walking(self):
# print "passenger %s stopped walking" % self.id
return self.interrupt()
def get_assigned_seat(self):
return self.assigned_seat
def get_row_number(self):
return self.assigned_seat.get_row_number()
def set_walk_process(self, walk_process):
self.walk_process = walk_process
def __str__(self):
return "Passenger(seat=%s%s)" % (self.assigned_seat.get_row_number(),
self.assigned_seat.get_position())
def get_process_speed(speed_dict):
"""
Returns a speed for the action that speed_dict represents.
Gets a random value between the min and max of speed_dict, and then
takes the average of this random value with the average of speed_dict.
Returns this value.
"""
random_speed = uniform(speed_dict['minimum'],
speed_dict['maximum'])
# below calculation gets a random value closer to the average
return (random_speed + speed_dict['average']) / 2
def get_seat_column(label, passengers):
"""
Returns all passengers with a seat in the given seat column.
A seat column is one of the position_labels in constants.py
"""
return [p for p in passengers if p.get_assigned_seat().get_position()
== label]
def get_even_row_passengers(passengers):
"""
Returns all passengers witch a seat in an even row.
"""
return [p for p in passengers if p.get_assigned_seat().get_row_number()
% 2 == 0]
def get_odd_row_passengers(passengers):
"""
Returns all passengers witch a seat in an even row.
"""
return [p for p in passengers if p.get_assigned_seat().get_row_number()
% 2 != 0] |
dde62d382e4cb1ba9ab4176ecadeab31e9b8063c | shahzorHossain/Diversity-Search-Engine | /q3.py | 681 | 3.53125 | 4 | def my_map(func,iterable):
if func is None:
return list(iterable)
else:
return [func(i) for i in iterable]
def my_reduce(func, iterable, start=None):
iterator = iter(iterable)
if start is None:
try:
start = iterator.next()
except StopIteration:
raise TypeError("my_reduce() of empty sequence with no initial value")
accum = start
for i in iterable:
accum = func(accum, i)
return accum
def my_filter(func, iterable):
if func is None:
result = [i for i in iterable if i]
else:
result = [i for i in iterable if func(i)]
if type(iterable) == tuple:
return tuple(result)
elif type(iterable) == str:
return ''.join(result)
return result
|
eb02c0abb17f0cea900344f8e81af40052414c64 | vishwanathsavai/Python | /brackets.py | 1,189 | 3.78125 | 4 | from itertools import permutations
def check(unique):
str1=[]
final=[]
for i in unique:
flag = 0
str1.extend([char for char in i])
print(str1)
for j in range(0,len(str1)):
if (str1[j]=='('):
flag+=1
else:
flag-=1
print(flag)
if(flag==-1):
break
else:
final.append(''.join(str1))
print("after{}" .format(flag))
str1=[]
print(final)
def print_brackets(list1):
unique_list = []
for j in list1:
if j not in unique_list:
unique_list.append(j)
#print(unique_list)
check(unique_list)
def brackets(list2):
perm = permutations(list2)
list1 = []
#print (perm)
for i in list(perm):
str = ''.join(i)
list1.append('('+str+')')
#print(list1)
print_brackets(list1)
def generate_brackets(n):
list2 = []
for i in range(1,n):
list2.append('(')
for i in range(1,n):
list2.append(')')
#print (list2)
brackets(list2)
n = int(input("Enter number:"))
generate_brackets(n) |
c22b6a46f7451be28b5b739ef36642fb9a5ee3ec | SenthilKumar009/100DaysOfCode-DataScience | /Python/Pattern/rightTraingle.py | 324 | 4 | 4 | line = int(input("Enter the total line to print:"))
#for x in range(1,line+1):
# print('* '*(x))
'''
for i in range(0, line+1):
for j in range(0, line-i+1):
print(' '*(j), end='')
print('*'*(i))
'''
for i in range(0,line+1):
for j in range(0, line-i):
print(' ', end='')
print('*'*(i)) |
e8caeb6eb6abea43082f05b8744fe7284ba7f561 | lxconfig/UbuntuCode_bak | /algorithm/牛客网/58-对称的二叉树.py | 2,627 | 3.703125 | 4 |
"""
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
"""
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetrical(self, pRoot):
"""求出原二叉树的前序遍历,及镜像二叉树的前序遍历
如果相等则说明是对称二叉树
注:不能用中序遍历,当二叉树中所有节点的值都相同时,中序遍历的结果都是一样的
"""
# 运行时间:25ms 占用内存:5736k
if not pRoot:
return True
ret1 = self.PreOrder([], pRoot)
root = self.Mirror(pRoot)
ret2 = self.PreOrder([], root)
return ret1 == ret2
# return self.helper(pRoot, root)
def Mirror(self, root):
if not root:
return None
root.left, root.right = root.right, root.left
self.Mirror(root.left)
self.Mirror(root.right)
return root
def PreOrder(self, ret, root):
"""对于没有左孩子或右孩子或叶子节点
需要补上没有的节点,防止所有节点值相等时,遍历没有效果
"""
if not root:
ret.append(-1)
return
ret.append(root.val)
self.PreOrder(ret, root.left)
self.PreOrder(ret, root.right)
return ret
def isSymmetrical2(self, pRoot):
"""递归比较法
左子树的左节点和右子树的右节点比较
左子树的右节点和右子树的左节点比较
"""
if not pRoot:
return True
return self.compare(pRoot.left, pRoot.right)
def compare(self, root1, root2):
if not root1 and not root2:
return True
if not root1 or not root2:
return False
if root1.val == root2.val:
if self.compare(root1.left, root2.right) and self.compare(root1.right, root2.left):
return True
return False
if __name__ == "__main__":
a = TreeLinkNode(5)
b = TreeLinkNode(5)
c = TreeLinkNode(5)
d = TreeLinkNode(5)
e = TreeLinkNode(5)
f = TreeLinkNode(5)
g = TreeLinkNode(5)
a.left = b
a.right = c
b.left = d
# b.right = e
# c.left = f
c.right = e
d.left = f
e.left = g
solution = Solution()
print(solution.isSymmetrical2(a)) |
ff092c1a6e3f7d5bd60497653c340729c2d8460b | nitin2149kumar/INFYTQ-Modules | /Data Structure/Day-4/Assignment-18.py | 721 | 3.984375 | 4 | #DSA-Assgn-18
def find_unknown_words(text,vocabulary):
#Remove pass and write your logic here
l=[]
status=0
text_list=text.split(" ")
for each_text in text_list:
if each_text not in vocabulary:
if "." in each_text:
each_text=each_text.replace(".","")
l.append(each_text)
status=1
if status:
return set(l)
else:
return -1
#Pass different values of text and vocabulary to the function and test your program
text="The sun rises in the east and sets in the west."
vocabulary = ["sun","in","rises","the","east"]
unknown_words=find_unknown_words(text,vocabulary)
print("The unknown words in the file are:",unknown_words)
|
2964cdc77617298fe7142df2827435c716e9f891 | Safat11/Admin | /25. Guessing Game.py | 619 | 4.15625 | 4 |
import random
guessNumber = int(input("Enter your guess between 1 to 5 : "))
randomNumber = random.randint(1,5)
if guessNumber == randomNumber :
print("You have won")
else :
print("you have lost")
print("Random number was : ",randomNumber)
###
# To be continue : for X in range(n,n) :
from random import randint
for X in range(1,6) :
guessNumber = int(input("Enter your guess between 1 to 9 : "))
randomNumber = randint(1,9)
if guessNumber == randomNumber :
print("You have won")
else :
print("you have lost")
print("Random number was : ",randomNumber)
|
6d9916e8566cee1733aaa5e10c14d95778f60d7b | dudnicp/compilateur_deca | /src/test/script/stack_overflow_generator.py | 444 | 3.609375 | 4 | #!usr/bin/python3
def main():
with open("test_stack_overflow.deca", 'w') as test_file:
test_file.write("// @result Error: Stack overflow\n")
test_file.write("{\n")
for char1 in range(97, 123):
for char2 in range(97, 123):
for char3 in range(97, 123):
test_file.write("int {}{}{} = 0;\n".format(chr(char1), chr(char2), chr(char3)))
test_file.write("}")
main() |
a59a44609827c0b29c219e7911b6ba8ef1b3fecf | amberrevans/pythonclass | /chapter 4 and 5 programs/temp_celcius.py | 792 | 4.3125 | 4 | #amber evans
#9/15/20
#program 4-2
#This program assists a technician in the process
#of checking a substances temperature.
#named constant to represent the maximum temperature
Max_temp = 102.5
#get the substances temperature
temperature= float(input('Enter the substances Celsius temperature: '))
#as long as necessary, instruct the user to
#adjust the thermostat
while temperature > Max_temp:
print('The temperature is too high.')
print('Turn the thermostate down and wait')
print('5 minutes. Then take the temperature')
print('again and enter it.')
temperature= float(input('Enter the new Celsius temperature: '))
#remind the user to check the temperature again
#in 15 minutes
print ('The temperature is acceptable.')
print ('Check it again in 15 minutes.')
|
4f2d4502ccf135f30f311c5fd24f0e9029031763 | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios alternativas/Ejercicio 14.py | 1,529 | 3.859375 | 4 |
#La asociación de vinicultores tiene como política fijar un precio inicial al kilo de uva, la cual se clasifica en tipos A y B, y además en tamaños 1 y 2.
#Cuando se realiza la venta del producto, ésta es de un solo tipo y tamaño,
#se requiere determinar cuánto recibirá un productor por la uva que entrega en un embarque, considerando lo siguiente: si es de tipo A,
#se le cargan 20 céntimos al precio inicial cuando es de tamaño 1;
#y 30 céntimos si es de tamaño 2. Si es de tipo B, se rebajan 30 céntimos cuando es de tamaño 1,
#y 50 céntimos cuando es de tamaño 2. Realice un algoritmo para determinar la ganancia obtenida.
kilo = int(input("Dime los kilos comprados:"))
precio = int(input("Dime el precio por kg:"))
tipo = input("Dime el tipo de uva (A o B):")
tam = int(input("Dime el tamaño de uva (1 o 2):"))
if tipo == "A" and tam == 1:
ganancia = kilo * 0.2
ganancia = ganancia * precio
print("La ganancia por la venta sería de",ganancia,"€.")
else:
if tipo == "A" and tam == 2:
ganancia = kilo * 0.3
ganancia = ganancia * precio
print("La ganancia por la venta sería de",ganancia,"€.")
if tipo == "B" and tam == 1:
ganancia = precio - 0.3
ganancia = ganancia * kilo
print("La ganancia por la venta sería de",ganancia,"€.")
else:
if tipo == "B" and tam == 2:
ganancia = precio - 0.5
ganancia = ganancia * kilo
print("La ganancia por la venta sería de",ganancia,"€.")
|
462d4299d7d74c4ef910666f324a1d19c5383d0a | gurkaran97/Offline-Dictionary-attack-tool | /run.py | 501 | 3.9375 | 4 | import hashlib
hashed_word = input('Enter the hashed word: ')
pass_file = input('Enter the password file: ')
try:
passfile = open(pass_file, "r")
except:
print("No file found, please check again")
for word in passfile:
enc_word = word.encode()
passfile_hashes = hashlib.md5(enc_word.strip()).hexdigest()
if passfile_hashes == hashed_word:
print('Password found. Password is ' + word)
break
else:
print("No password found")
break
|
4ff8f497ab114e2ba35e6800f0337dec3c434c4d | ProgFuncionalReactivaoct19-feb20/clase03-vysery98 | /ejercicio1.py | 376 | 3.890625 | 4 | """
@vysery98
Dado un conjunto de palabras, filtrar todas aquellas que sean
palíndromas
Palabras: "oro", "pais", "ojo", "oso", "radar", "sol", "seres"
"""
conjPalabras = ["oro", "pais", "ojo", "oso", "radar", "sol", "seres"]
# reversed similar a map, poner: "".join
palindromas = filter(lambda x: x == "".join(reversed(x)), conjPalabras)
print(list(palindromas))
|
78f8f95ca65d6ea231e88e1fdb822f169dba31bc | billkabb/learn_python | /MIT/L11_problem_4.py | 1,524 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 5 17:26:13 2016
@author: billkabb
"""
class Coordinate(object):
def __init__(self,x,y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better practice than just accessing an attribute directly
return self.x
def getY(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def __str__(self):
return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
def __eq__(self, other):
# First make sure `other` is of the same type
assert type(other) == type(self)
# Since `other` is the same type, test if coordinates are equal
return self.getX() == other.getX() and self.getY() == other.getY()
def __repr__(self):
return 'Coordinate(' + str(self.getX()) + ', ' + str(self.getY()) + ')'
class Point3D(object):
def __init__(self,a,b,c):
self.x = a
self.y = b
self.z = c
def __repr__(self):
return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
def __str__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print `my_point` # __repr__ gets called automatically
print my_point # __str__ gets called automatically
x = 123
y = 123
c = Coordinate(x,y)
c2=eval(repr(c))
print c
print `c`
print str(c)
print c2
print eval(`c`)
print c.__eq__(c2)
#print c |
55efa6a24697a6710f6de7baf605a382ac2316f3 | bupthl/Python | /Python从菜鸟到高手/chapter7/demo7.11.py | 1,146 | 4.3125 | 4 | '''
--------《Python从菜鸟到高手》源代码------------
欧瑞科技版权所有
作者:李宁
如有任何技术问题,请加QQ技术讨论群:264268059
或关注“极客起源”订阅号或“欧瑞科技”服务号或扫码关注订阅号和服务号,二维码在源代码根目录
如果QQ群已满,请访问https://geekori.com,在右侧查看最新的QQ群,同时可以扫码关注公众号
“欧瑞学院”是欧瑞科技旗下在线IT教育学院,包含大量IT前沿视频课程,
请访问http://geekori.com/edu或关注前面提到的订阅号和服务号,进入移动版的欧瑞学院
“极客题库”是欧瑞科技旗下在线题库,请扫描源代码根目录中的小程序码安装“极客题库”小程序
关于更多信息,请访问下面的页面
https://geekori.com/help/videocourse/readme.html
'''
def jc(n):
if n == 0 or n == 1:
return 1
else:
return n * jc(n - 1)
print(jc(10))
def fibonacci(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10)) |
f45b13cd1cdaf8bed6458c8bf9d9d27449692bf3 | huseyinyilmaz/datastructures | /python/mergesort.py | 2,609 | 3.90625 | 4 | """
Destructive merge sort algorithm.
Implements top down scheme
"""
import unittest
from hypothesis import given
from hypothesis import settings
# from hypothesis import Verbosity
from hypothesis.strategies import integers
from hypothesis.strategies import lists
from hypothesis.strategies import text
def merge(xs, ys):
"""Merge 2 lists into one"""
result = []
# create iterator to go over both lists
xi = iter(xs)
yi = iter(ys)
x = next(xi, None)
y = next(yi, None)
while x is not None and y is not None:
if x < y:
result.append(x)
x = next(xi, None)
else:
result.append(y)
y = next(yi, None)
# put left over element back to list
result.append(x if y is None else y)
# find out which list is longer
rest_iter = xi if y is None else yi
result.extend(rest_iter)
return result
def merge_sort(xs):
"""
Topdown merge sort implementation
"""
l = len(xs)
if l <= 1:
response = xs
else:
i = l//2
response = merge(merge_sort(xs[:i]), merge_sort(xs[i:]))
return response
def _merge_sort2(xss):
if len(xss) == 1:
return xss
else:
result = []
ys = None
for xs in xss:
if ys is None:
ys = xs
else:
result.append(merge(xs, ys))
ys = None
# Add left over element into result
if ys is not None:
result.append(ys)
return _merge_sort2(result)
def merge_sort2(xs):
"""
Bottom up merge sort implementation
"""
if xs:
response = _merge_sort2([[x] for x in xs])[0]
else:
response = xs
return response
class SortTestCase(unittest.TestCase):
@given(lists(elements=integers()))
@settings(max_examples=500)
def test_int_sort(self, ls):
self.assertListEqual(merge_sort(ls[:]), sorted(ls))
# verbosity=Verbosity.verbose)
@given(lists(elements=text()))
@settings(max_examples=500)
def test_text_sort(self, ls):
self.assertListEqual(merge_sort(ls[:]), sorted(ls))
class Sort2TestCase(unittest.TestCase):
@given(lists(elements=integers()))
@settings(max_examples=500)
def test_int_sort(self, ls):
self.assertListEqual(merge_sort2(ls[:]), sorted(ls))
# verbosity=Verbosity.verbose)
@given(lists(elements=text()))
@settings(max_examples=500)
def test_text_sort(self, ls):
self.assertListEqual(merge_sort2(ls[:]), sorted(ls))
if __name__ == '__main__':
unittest.main()
|
c88c26c524764cc71d73b0f16347905d064ef266 | 73fc/912_project | /5 操作系统/实验/ucore/ucore_lab/related_info/lab7/semaphore_condition/thr-ex7.py | 1,828 | 3.84375 | 4 | #coding=utf-8
import threading
import random
import time
class SemaphoreThread(threading.Thread):
"""classusing semaphore"""
availableTables=['A','B','C','D','E']
def __init__(self,threadName,semaphore):
"""initialize thread"""
threading.Thread.__init__(self,name=threadName)
self.sleepTime=random.randrange(1,6)
#set the semaphore as a data attribute of the class
self.threadSemaphore=semaphore
def run(self):
"""Print message and release semaphore"""
#acquire the semaphore
self.threadSemaphore.acquire()
#remove a table from the list
table=SemaphoreThread.availableTables.pop()
print "%s entered;seated at table %s." %(self.getName(),table),
print SemaphoreThread.availableTables
time.sleep(self.sleepTime)
#free a table
print " %s exiting;freeing table %s." %(self.getName(),table),
SemaphoreThread.availableTables.append(table)
print SemaphoreThread.availableTables
#release the semaphore after execution finishes
self.threadSemaphore.release()
threads=[] #list of threads
#semaphore allows five threads to enter critical section
threadSemaphore=threading.Semaphore(len(SemaphoreThread.availableTables))
#创建一个threading.Semaphore对象,他最多允许5个线程访问临界区。
#Semaphore类的一个对象用计数器跟踪获取和释放信号机的线程数量。
#create ten threads
for i in range(1,11):
threads.append(SemaphoreThread("thread"+str(i),threadSemaphore))
#创建一个列表,该列表由SemaphoreThread对象构成,start方法开始列表中的每个线程
#start each thread
for thread in threads:
thread.start()
|
38e670253d7e28f9dd96ab285c36cc45df1f80b2 | rudyekoprasetya/belajar-python | /3 percabangan/Main.py | 251 | 3.71875 | 4 | nilai = input('Masukan nilai ')
# if float(a) >= 75:
# print('Selamat Anda Lulus')
# else:
# print('Maaf Anda Belum Lulus')
if float(nilai) > 85:
print('Nilai Anda A')
elif float(nilai) >= 75:
print('Nilai Anda B')
else:
print('Nilai Anda C')
|
00644387e1193de60582ab41c1d9106c82e0a166 | mingsalt/START_UP_PYTHON | /6st/hw3.py | 227 | 3.78125 | 4 | #hw3 숫자의 약수 구하기 & 숫자 분류하기
num = int(input("숫자를 입력하세요 : "))
list_1=[]
for i in range(1,num):
if num%i==0 :
list_1.append(i)
print(f"{num}의 약수 :{list_1[0:]}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.