blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
cf564056ed656f9afdc5d4702234aefba996317d | emilnorman/euler | /problem012.py | 384 | 3.671875 | 4 | import math
def NumOfDivisors(num):
divisors = 0
s = round(math.sqrt(num))
for i in range(1, s + 1):
if num % i == 0:
divisors += 2
return divisors + 1
# Generate triangular numbers
triagNum = 0
current = 1
nod = 0
while(nod < 500):
triagNum += current
current += 1
nod = NumOfDivisors(triagNum)
print(current, triagNum, nod)
|
362732b4c04eb0b2a1a8530d9f501a8b707e5d20 | oktavianidewi/interactivepython | /recursion_reverseWord.py | 785 | 3.875 | 4 | # recursively
# write a function that takes string as parameter
# and returns a new string that is reverse of the old string
from stack import stack
rev = stack()
wordlist = []
reverseWord = ""
# reverse word tanpa recursion
def reverse(words):
# 4, 3, 2, 1, 0
iterasi = len(words)-1
while iterasi >= 0:
letter = words[iterasi]
rev.push(letter)
iterasi = iterasi - 1
sisa = words[:4]
return sisa
# reverse word dengan recursion
def reverseRefactor(words):
# 4, 3, 2, 1, 0
iterasi = len(words)-1
if iterasi >= 0:
wordlist.append(words[iterasi])
reverseRefactor(words[:iterasi])
reverseWord = "".join(wordlist)
return reverseWord
# return true/false kalo polindrome
print(reverseRefactor("fellow")) |
bf8c910710b9bb56557b41628f9fcaad53ade019 | excelkks/MachineLearning | /感知机/perceptron.py | 1,210 | 3.625 | 4 | class perceptron:
'''
perceptron class, use Stochastic Gradient Descent to training coefficient
'''
def __init__(self, x_train, y_train):
self.x_train = x_train
self.y_train = y_train
self.w = np.ones((len(x_train[0])))
self.b = np.ones((1))
def sign(self, x_input):
y = np.matmul(x_input, self.w.T) + self.b
y = np.array([-1 if v < 0 else 1 for v in y])
return y
def sgd(self,learn_rate = 0.01):
'''
Stochastic Gradient Descent training function
default learning rate learn_rate = 0.01
'''
stop_flag = False
while not stop_flag:
wrong_count = 0
y = self.sign(self.x_train)
for i in range(len(self.y_train)):
if y[i]*y_train[i] < 0:
self.w += learn_rate*x_train[i]*y_train[i]
self.b += learn_rate*y_train[i]
wrong_count += 1
if wrong_count == 0:
stop_flag = True
def loss_func(self):
loss = 0
y = self.sign(self.x_train)*self.y_train
for l in y:
if l < 0:
loss += l
return loss
|
c2aa268fac623483f54166ed94e01428e44df57c | CX-Bool/LeetCodeRecord | /Python/Array/88E. Merge Sorted Array.py | 768 | 3.953125 | 4 | # 执行用时: 44 ms, 在Merge Sorted Array的Python3提交中击败了99.73% 的用户
# 内存消耗: 6.5 MB, 在Merge Sorted Array的Python3提交中击败了86.92% 的用户
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
if not nums2:
return
j=m-1
k=n-1
i=m+n-1
while i>=0:
if j< 0 or nums2[k]>nums1[j] and k>=0:
nums1[i]=nums2[k]
i-=1
k-=1
else:
nums1[i] = nums1[j]
i-=1
j-=1 |
3e55840c6e1eda86ba8f8aa34e0d61a8c3564871 | voicezyxzyx/python | /Exercise/爬虫/yx_02_爬虫2.py | 151 | 3.75 | 4 | def sum_number(num):
if num == 1:
return 1
temp = sum_number(num - 1)
return num + temp
result = sum_number(1000)
print(result)
|
570bdffc7adc4f60b0e6301331cc630c1a644df4 | ishmam-hossain/problem-solving | /leetcode/222_count_complete_tree_nodes.py | 478 | 3.71875 | 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 countNodes(self, root: TreeNode) -> int:
self.total = 0
def count_nodes(head):
if head is None:
return
self.total += 1
count_nodes(head.left)
count_nodes(head.right)
count_nodes(root)
return self.total |
1c78419875a72333fe8f2f1954516c79ad8811a5 | ojasjoshi18/Ojas-Joshi | /Angstrom_number.py | 579 | 3.75 | 4 | #Name:Ojas Joshi
#Gr no:11810839
#roll no:23
#Division:M
def armstrong(n): #function to define armstrong number
sum=0
t=n
while t>0:
d=t%10 #Separating out the number into indiviual digits
sum=t**3 #cube of the digits is found out
t=t//10
return sum
n=int(input("Enter a number")) #user input number is taken
y=armstrong(n) #function is called
print(y)
|
b177ba463cc8d3a47178536520f1513bb0f38ceb | olliechick/instagram-unfollowers | /generate_dirs.py | 2,586 | 3.9375 | 4 | #!/usr/bin/python3
import errno
import os
from file_io import write_to_file
STORE_LOGIN_DATA_PROMPT = "Do you want to store you login data on this computer? " \
"Note that it will be stored in plaintext, so don't do this on a shared computer."
def get_boolean_response(prompt):
response = input(prompt + "\nType y/n: ").lower()
while len(response) > 0 and response[0] not in ['y', 'n']:
response = input("Sorry, that is not a valid response. Please type only one character, either 'y' or 'n': ")
return response[0] == 'y'
def ends_in_slash(string):
return len(string) > 0 and string[-1] in ['/', '\\']
def is_valid_dir(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
return False
return True
def is_valid_filepath(filepath):
directory = filepath[:filepath.rindex('/') + 1]
return is_valid_dir(directory)
def generate_dirs():
dirs = dict()
data_dir = input("Enter the directory where you want data to be stored: ")
good_dir = is_valid_dir(data_dir) and ends_in_slash(data_dir)
while not (good_dir):
if not ends_in_slash(data_dir):
data_dir = input("That is not a valid directory. Valid directories must end in a slash. Please try again: ")
else:
data_dir = input("That is not a directory you can create. Please try again: ")
good_dir = is_valid_dir(data_dir) and ends_in_slash(data_dir)
dirs['data'] = data_dir
wants_to_store_logins = get_boolean_response(STORE_LOGIN_DATA_PROMPT)
if wants_to_store_logins:
logins_dir = input("Enter the location of the text file where you store your logins: ")
while not (is_valid_filepath(data_dir)):
logins_dir = input("That is not a file you can create. Please try again: ")
dirs['logins'] = logins_dir
# Save dirs.txt
write_to_file('dirs.txt', str(dirs))
# Get login details
if wants_to_store_logins:
print("Now enter the user details you want to save. To finish, enter * as a username:")
logins = dict()
username = input("Username: ").strip()
keep_going = username != '*'
while keep_going:
password = input("Password: ").strip()
logins[username] = password
username = input("Username: ").strip()
keep_going = username != '*'
# Save logins file
write_to_file(logins_dir, str(logins))
def main():
generate_dirs()
if __name__ == "__main__":
main()
|
d78b72fd2c95c43ab76a2e97c17263c485de7ea4 | pndx/learn-to-use-python | /PythonQuickTips2.py | 421 | 3.78125 | 4 | # Python Splat/Unpack Operator - Python Quick Tips
my_list = ["hello", 'world', 4, 5]
my_dict = {"apple": 1, "pear": 2, "orange": 3}
function_args = {"name": "world", "age": 6}
def test1(name, age):
print(name, age)
def test2(**kwargs):
print(kwargs)
def test3(*args):
print(args)
print(*my_list)
print(*my_dict)
test1(**function_args)
test2(name="tim", height=100, tim="cool")
test3("tim", 5, True)
|
5fc94675c4e94ebf87deca5648b813f4c3fcddc0 | eopr12/pythonmine | /st01.Python기초/py09예외문/py09_01_Error.py | 1,388 | 3.59375 | 4 |
# 교재 222-228페이지
# 숫자가 아닌 것을 정수로 변환하려고 할 때
# 숫자가 아닌 것을 실수로 변환 할 때
# 소수점이 있는 숫자 형식의 문자열을 int() 함수로 변환하려고 할 때
# IndexError
입력값 = int(input("숫자를 입력하세요.")) # 입력값 = "abc"이면 에러 발생
try:
입력값 = int(input("숫자를 입력하세요.")) # 입력값 = "abc"이면 에러 발생
입력값 = float(input("숫자를 입력하세요.")) # 입력값 = "abc"이면 에러 발생
입력값 = int(input("숫자를 입력하세요.")) # 입력값 = "12.3"이면 에러 발생
except TypeError as ex:
print("TypeError", ex)
except ZeroDivisionError as ex:
print("ZeroDivisionError", ex)
except Exception as ex: # TypeError도 아니고 아무것도 아니면 무조건 Exception에 넣어야 됨 > 무조건 마지막줄에 넣어야 됨
print("Exception", ex)
# 테스트 방법
# 테스트1: abc입력
# 테스트2: 숫자0입력
# 테스트3: 숫자12.5입력
# 테스트4: 숫자12입력
# 함수코드를 try - except 구문 코드로 감싼다
# 오류 종류:컴파일 오류(구문 에러), 실행 오류(run-time error), 논리오류(logical error)
# Unhandled Exception : 0으로 나누는 경우 / 원격 데이터 접속시 연결 안되는 경우 / 파일 열었는데 삭제된 경우
|
2fc4acecfc788f5ad519829bc9ebd381355202ae | wakkpu/algorithm-study | /20 Summer Study/command-and-conquer/binary_search.py | 867 | 4.1875 | 4 | def binary_search(A, left, right, k):
# A is list to input
# left is the most left index
# right is the most right index
# k is the number we try to find
# it cannot be reversed
if left > right:
return None
# mid is the middle index
mid = (left + right) // 2
# if the middle one is what we try to find, return it (base case)
if k == A[mid]:
return mid
# recursive case
else:
# find the left half
if k < mid:
return binary_search(A, left, mid-1, k)
# find the right half
else:
return binary_search(A, mid+1, right, k)
if __name__ == "__main__":
A = [1, 2, 3, 0, 5, 6, 8, 9, 4, 7]
# binary search works iff list to input is sorted
A = sorted(A)
print(binary_search(A, 0, len(A), 3))
print(binary_search(A, 0, len(A), -1))
|
39bed9e7ea3fc2ba7d9788c5a1206fa8606b183b | therachelbentley/algorithms | /python-playground/mathlib/math_lib.py | 3,071 | 3.984375 | 4 |
def _gcd(a, b):
"""Returns the greatest common divisor
of two numbers.
Params:
a (int)
b (int)
"""
a = abs(a)
b = abs(b)
if(a < b):
a, b = b, a
r = a % b
if r == 0:
return b
else:
return _gcd(b, r)
def _lcm(a, b):
"""Returns the lowest common multiple
of two numbers.
Params:
a (int)
b (int)
"""
return abs((a * b)/_gcd(a, b))
def _base_expansion(n, b):
"""Returns the base b expansion of
a base ten number n.
Params:
n (int): Base ten number
b (int): Base expansion
"""
_remainders = []
q, r = divmod(n, b)
if q == 0:
_remainders.append(r)
while q > 0:
_remainders = [r] + _remainders
q, r = divmod(q, b)
if q == 0:
_remainders = [r] + _remainders
return int("".join(str(x) for x in _remainders))
def _base_ten(n, b):
"""Returns n as a base 10 number.
Params:
n (int)
b (int): Base of n
"""
n = str(n)
k = 0
for i in n:
i = int(i)
k = b * k + i
return(k)
# TODO: identical objects
def _permutation(n, r, repetition=False):
"""Return the number of permutations.
Params:
n (int): Number of objects in a set
r (int): Number of objects being chosen
repetition (boolean): Specifies if repeats are allowed
"""
if repetition is True:
return n**r
permutation = 1
for i in range(r):
permutation *= n - i
return permutation
def _combination(n, r, repetition=False):
"""Return the number of combinations.
Params:
n (int): Number of objects in a set
r (int): Number of objects being chosen
repetition (boolean): Specifies if repeats are allowed
"""
numerator = 1
denominator = 1
if repetition is True:
c = n - 1
p = r + c
for i in range(p):
numerator *= p - i
if i < r:
denominator *= r - i
if i < c:
denominator *= c - i
else:
for i in range(r):
numerator *= n - i
denominator *= r - i
return numerator // denominator
### GCD Tests ###
assert _gcd(34, 6) == 2
assert _gcd(360,39736) == 8
assert _gcd(-6, 34) == 2
### LCM Tests ###
assert _lcm(65, 10) == 130
assert _lcm(60, 3350) == 20100
assert _lcm(3350, -60) == 20100
### BaseExpansion Tests ###
assert _base_expansion(8, 2) == 1000
assert _base_expansion(2, 5) == 2
assert _base_expansion(16, 16) == 10
### BaseTen Tests ###
assert _base_ten(1000, 2) == 8
assert _base_ten(16, 16) == 22
assert _base_ten(2, 15) == 2
### Permutation Tests ###
assert _permutation(20, 3, repetition=False) == 6840
assert _permutation(20, 3, repetition=True) == 8000
### Combination Tests ###
assert _combination(20, 3, repetition=False) == 1140
assert _combination(20, 3, repetition=True) == 1540
|
14334e83989e0302c99bbdf517bffaf2de6e2356 | LoralieFlint/learning-python | /Lists.py | 647 | 4.0625 | 4 | # lists in python are arrays in javascript
friends = ["Jess", "Jess", "Jess", "Hope", "Lexi", "Tattoo Girl"]
# lists can hold stings numbers and booleans
friends2 = ["Jess", 1, True]
# index starts at 0 just like javascript
print(friends[0])
# targeting index by negative numbers
# starts at the last index of list
# returnsTattoo Girl
print(friends[-1])
# accessing portions of a list
# this will return index of 1 and the rest of the list
print(friends[1:])
# accessing a range of items in a list
# returns names from index 1 and two stops at 3 not returning it
print(friends[1:3])
# modify an item in A list
friends[1] = "Hopey"
print(friends) |
8bb4930f77abe42a728d62a21c17690bd5985a34 | LeandroBP/Python | /HandsOn/Aula03/funcoes.py | 2,054 | 3.734375 | 4 | #!/usr/bin/python
import sys
import json
usuarios = []
def exibeMenu():
print "\n1 - Para cadastrar usuarios"
print "2 - Para listar todos os usuarios"
print "3 - Para deletar um usuario"
print "4 - Para autenticar um usuario"
print "5 - Sair"
def cadastraUsuario(usuarios):
with open("banco.txt","r") as f:
arquivo = json.loads(f.read())
novo_usuario = {"login":"","senha":""}
novo_usuario["login"] = raw_input("\nDigite o nome do usuario: ")
novo_usuario["senha"] = raw_input("\nDigite a senha de usuario: ")
arquivo["usuarios"].append(novo_usuario)
with open("banco.txt","w") as f:
f.write(json.dumps(arquivo))
print "\nUsuario cadastrado com sucesso!"
###############################################################################
def listarUsuario(usuarios):
with open("banco.txt","r") as f:
conteudo = f.read()
print conteudo
def deletarUsuarios():
print "Deletar usuarios"
##############################################################################
def autenticaUsuario(usuarios):
with open("banco.txt","r") as f:
arquivo = json.loads(f.read())
login = raw_input("\nDigite o login do usuario: ")
senha = raw_input("\nDigite a senha do usuario: ")
for usuario in arquivo.get("usuarios"):
if usuario["login"]== login and usuario.get("senha")== senha:
print "\nUsuario autenticado!\n"
break
else:
print "\nVoce nao tem permissao para acessar este sistema!\n"
############################################################################
def sairMenu(usuarios):
sys.exit()
def switch(opcao,usuarios):
try:
dic = {1:cadastraUsuario,
2:listarUsuario,
3:deletarUsuarios,
4:autenticaUsuario,
5:sairMenu}
dic[opcao](usuarios)
except Exception as e:
print "Voce digitou uma opcao invalida",e
while True:
try:
exibeMenu()
opcao = input("\nInsira a opcao desejada: ")
switch(opcao,usuarios)
except Exception as e:
print "Voce digitou uma opcao invalida",e
|
e101d0202251923a727abc9cacd09359db7386cf | chanathivat/Python | /050264.py | 3,851 | 3.65625 | 4 | ############################################################5.1####################################################################################################
class nisit:
def __init__(self,name,province,year,department,sex):
self.name = name
self.province = province
self.year = year
self.department = department
self.sex = sex
def show(self):
if self.sex == 'ชาย':
print('สวัสดีครับ ผมชื่อ '+self.name +' มาจากจังหวัด'+self.province+' เพศ'+self.sex+ ' นักศึกษาชั้นปีที่ '+self.year + ' สาขา '+self.department)
elif self.sex == 'หญิง':
print('สวัสดีค่ะ ฉันชื่อ'+self.name +' มาจากจังหวัด'+self.province+' เพศ'+self.sex+ ' นักศึกษาชั้นปีที่ '+self.year + ' สาขา '+self.department)
else:
print('ERROR!')
@classmethod
def info(self):
print('-'*15,'แนะนำตัว','-'*15)
#print('ชื่อ-สกุล:เพศ:ชั้นปี:สาขาวิชา:')
name = input('ชื่อ : ')
province = input('จังหวัด : ')
year = input('ชั้นปี : ')
department = input('สาขา : ')
sex = input('เพศ : ')
return self(name,province,year,department,sex)
x = nisit.info()
x.show()
###################################################################5.2##########################################################################################
import os
name_list = ['แมว','สุนัข','หมีแพนด้า','สิงโต']
price_list = [8,6,9,8]
class market :
def list_def(self):
for x in range(0,len(name_list)):
print(x+1,name_list[x],price_list[x],'บาท')
def choose(self):
print('*'*10,'','*'*10)
print('\tแสดงรายการสินค้า [a]\n\tเพิ่มรายการสินค้า [s]\n\tออกจากระบบ [x]')
def input_choise(self):
global choise
choise = input('กรุณาเลือกคำสั่ง: \t')
def add_list(self):
while True:
print('เพิ่มรายการสินค้า หากต้องการกรอก exit')
add_name = input('เพิ่มชื่อสินค้า: ')
if add_name == 'exit':
break
else :
add_price = input('เพิ่มราคาสินค้า: ')
name_list.append(add_name)
price_list.append(add_price)
add = input ('ต้องการเพิ่มสินค้าอีกหรือไม่ [y/n]: ')
if add == 'n' :
break
elif add == 'y' :
os.system('cls')
while True:
x = market()
x.choose()
x.input_choise()
if choise == 'a' :
os.system('cls')
print('กรุณาเลือกคำสั่ง:\t',choise)
x.list_def()
if choise == 's' :
os.system('cls')
print('กรุณาเลือกคำสั่ง:\t',choise)
x.add_list()
if choise == 'x' :
os.system('cls')
print('กรุณาเลือกคำสั่ง:\t',choise)
close = input('ต้องการออกจากระบบหรือไม่ [y/n] : ')
if close == 'n' :
os.system('cls')
if close == 'y' :
os.system('cls')
print('ออกจากระบบเรียบร้อยแล้ว')
break |
61497cccfc7d401400ef0a24a3cebf59ae1bbfce | optimus1810/crackingTheCodingIntPython | /binary_search_tree.py | 3,731 | 3.890625 | 4 | from Queue import Queue
__author__ = 'Gaurav'
class BSTNode:
def __init__(self, content):
self.content = content
self.left = None
self.right = None
def insert(root, node):
if root == None:
root = node
else:
if root.content > node.content:
if root.left is None:
root.left = node
else:
insert(root.left, node)
else:
if root.right is None:
root.right = node
else:
insert(root.right, node)
def delete(root, node):
if root is None:
return
elif root.content < node.content:
root.right = delete(root.right, node)
elif root.content > node.content:
root.left = delete(root.left, node)
# Now we have found the node to be deleted
elif root.left is None and root.right is None:
del root
return root
elif root.left is None:
root = root.right
del root.right
return root
elif root.right is None:
root = root.left
del root.left
return root
elif root.left is not None and root.right is not None:
root = min_node(root.right)
root.right = delete(root.right, node)
return root
def min_node(root):
if root is None:
return
min = root
if root.left is not None:
min = min_node(root.left)
return min
def search(root, node):
if root == node:
return root
else:
if root.content < node.content:
if root.right == node:
return root.right
else:
search(root.right, node)
if root.content > node.content:
if root.left == node:
return root.left
else:
search(root.left, node)
def breadth_first(root):
queue = Queue()
queue.put(root)
while queue:
node = queue.get()
print node.content
if node.left is not None:
queue.put(node.left)
if node.right is not None:
queue.put(node.right)
return
def breadth_first_level_wise(root):
this_level = [root]
while this_level:
new_level = []
for n in this_level:
print n.content,
if n.left:
new_level.append(n.left)
if n.right:
new_level.append(n.right)
print
this_level = new_level
def preOrder(root):
if not root:
return
print root.content
preOrder(root.left)
preOrder(root.right)
def InOrder(root):
if not root:
return
InOrder(root.left)
print root.content
InOrder(root.right)
def PostOrder(root):
if not root:
return
PostOrder(root.left)
PostOrder(root.right)
print root.content
def main():
node_one = BSTNode(2)
node_two = BSTNode(3)
node_three = BSTNode(7)
node_four = BSTNode(8)
node_five = BSTNode(1)
node_six = BSTNode(11)
node_seven = BSTNode(6)
root = BSTNode(5)
insert(root, node_one)
insert(root, node_two)
insert(root, node_three)
insert(root, node_four)
insert(root, node_five)
insert(root, node_six)
insert(root, node_seven)
print "PreOrder:"
preOrder(root)
print "InOrder:"
InOrder(root)
print "PostOrder:"
PostOrder(root)
# value = search(root, node_seven).content
# print "found"
min = min_node(root)
print min.content
# deleted_node = delete(root, node_four)
# print "After deleting:"
# preOrder(root)
# print "BFS:"
# breadth_first(root)
print "Level_wise:"
breadth_first_level_wise(root)
if __name__ == '__main__':
main() |
2d1a783822cf5778895eb3c98fc113e79160eb0a | siddharthcurious/Pythonic3-Feel | /Data-Structures/Graph/topological_sorting/topological_sorting.py | 1,231 | 3.75 | 4 | class Topological:
def __init__(self, v, graph):
self.v = v
self.total_nodes = set(range(self.v))
self.graph = graph
def print_nodes(self):
print(self.total_nodes)
def indegree_zero(self):
child_nodes = []
for k, v in self.graph.items():
child_nodes.extend(v)
indegree_nodes = set(child_nodes)
return self.total_nodes - indegree_nodes
def outdegree_zero(self):
parent_nodes = graph.keys()
return self.total_nodes - parent_nodes
def indegree(self):
pass
def outdegree(self):
pass
def topological_sorting(self):
topological_order = []
indegree_zero_nodes = self.indegree_zero()
for node in indegree_zero_nodes:
self.graph.pop(node)
print(self.graph)
if __name__ == "__main__":
graph = {
0: [1, 2, 3],
1: [4],
2: [5],
3: [1, 4, 5, 7, 8],
4: [8],
5: [6],
6: [7, 10],
7: [8, 9],
8: [9],
10: [9, 11]
}
v = 12
obj = Topological(v, graph)
obj.topological_sorting()
obj.print_nodes()
print(obj.indegree_zero())
print(obj.outdegree_zero()) |
dbd6172f19f90bedfa2f942c0133efa1900151c4 | JArmour416/python-challenge | /PyPoll/main.py | 3,098 | 3.5625 | 4 | import os
import csv
election_csv = os.path.join("Documents", "GitHub", "python-challenge", "PyPoll", "election_data.csv")
# Set variables
total_votes = 0
khan_votes = 0
correy_votes = 0
li_votes = 0
otooley_votes = 0
# with open(election_csv, newline="", encoding='utf-8') as csvfile:
with open(election_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the header
header = next(csvreader)
# Iterate through each row
for row in csvreader:
# Set a variable of total_votes to count the votes by ID
total_votes += 1
# Seperate the values by candidates
if row[2] == "Khan":
khan_votes += 1
elif row[2] == "Correy":
correy_votes += 1
elif row[2] == "Li":
li_votes += 1
elif row[2] == "O'Tooley":
otooley_votes += 1
# Create a dictionary for the candidates and votes
candidates = ["Khan", "Correy", "Li", "O'Tooley"]
votes = [khan_votes, correy_votes, li_votes, otooley_votes]
# Zip lists together
candidates_votes_dict = dict(zip(candidates,votes))
key = max(candidates_votes_dict, key = candidates_votes_dict.get)
# Find the percentage of votes
khan_percent = (khan_votes/total_votes) * 100
correy_percent = (correy_votes/total_votes) * 100
li_percent = (li_votes/total_votes) * 100
otooley_percent = (otooley_votes/total_votes) * 100
# Print the analysis
print(f"Election Results")
print(f"--------------------------")
print(f"Total Votes: {total_votes}")
print(f"--------------------------")
print(f"Khan: {khan_percent:.5}% ({khan_votes})")
print(f"Correy: {correy_percent:.5}% ({correy_votes})")
print(f"Li: {li_percent:.5}% ({li_votes})")
print(f"O'Tooley: {otooley_percent:.4}% ({otooley_votes})")
print(f"--------------------------")
print(f"Winner: {key}")
print(f"--------------------------")
# Set variable for the output file
output_file = os.path.join("election_results.csv")
# Open the output file
with open(output_file, "w", newline="") as datafile:
# Write the analysis
datafile.write(f"Election Results")
datafile.write("\n")
datafile.write(f"--------------------------")
datafile.write("\n")
datafile.write(f"Total Votes: {total_votes}")
datafile.write("\n")
datafile.write(f"--------------------------")
datafile.write("\n")
datafile.write(f"Khan: {khan_percent:.5}% ({khan_votes})")
datafile.write("\n")
datafile.write(f"Correy: {correy_percent:.5}% ({correy_votes})")
datafile.write("\n")
datafile.write(f"Li: {li_percent:.5}% ({li_votes})")
datafile.write("\n")
datafile.write(f"O'Tooley: {otooley_percent:.4}% ({otooley_votes})")
datafile.write("\n")
datafile.write(f"--------------------------")
datafile.write("\n")
datafile.write(f"Winner: {key}")
datafile.write("\n")
datafile.write(f"--------------------------") |
de2c9e343c4ef9c735a3582f012e41e4146f157e | lucassilva-2003/Cursoemvideo_Python_100exs | /ex019.py | 270 | 3.6875 | 4 | # sorteio de alunos
from random import choice
a1 = input('Digite o 1 nome: ')
a2 = input('Digite o 2 nome: ')
a3 = input('Digite o 3 nome: ')
a4 = input('Digite o 4 nome: ')
escolha = (a1, a2, a3, a4)
print('O aluno sorteado foi {}'.format(choice(escolha)))
|
1274ea5cab74389e68915793408c37b85b5274a3 | devdutt-dikshit/furnish | /problems.py | 910 | 3.5625 | 4 | # solution 1 and 2
# https://github.com/hemanthmalik/furnish.git
print('Solution for problem 1 and 2 are updated at https://github.com/hemanthmalik/furnish.git')
# endpoints /register and /login for respective apis along with a token secured testapi for security validation
# haven't added cors and allowed hosts as it is meant to be a test app.
# solution 3
print(" ".join(input("Enter string to be reversed --> ").split(" ")[::-1]))
# solution 4
from random import randrange
def pick_all_randoms(arr): # T(n)=O(n) S(n)=O(1)
curr_index = 0
arr_size = len(arr)
while curr_index < arr_size:
random_index = randrange(curr_index, arr_size)
random_item = arr[random_index]
print(random_item)
arr[curr_index], arr[random_index] = arr[random_index], arr[curr_index]
curr_index += 1
mylist = [1, 2, 3, 4, 5, 6, 7 ,8,9,10]
pick_all_randoms(mylist)
|
37732912b9a5ec2c63c511cb4223d688404b409c | gaurav-dalvi/codeninja | /python/matrix_diagonal_print.py | 1,321 | 4.4375 | 4 | # https://www.ideserve.co.in/learn/print-matrix-diagonally#algorithmVisualization
# Key points to remember:
# 1: to understand what was the exact order of printing, had to watch video. Ask interviewer
# 2: these two loops are very tricky
# 3: understand to split this problem into two separate pair of for loops is the big idea here.
def print_matrix_digonally(matrix):
if matrix is None:
raise Exception("Invalid input")
row_count = len(matrix)
col_cont = len(matrix[0])
# First half
for i in xrange(row_count):
row_index = i
for j in xrange(i+1):
print matrix[row_index][j],
if row_index == 0:
break
else:
row_index = row_index - 1
print ""
# second half
for i in xrange(1,col_cont):
col_index = i
for j in xrange(row_count-1,-1,-1):
print matrix[j][col_index],
col_index = col_index + 1
if col_index >= col_cont:
break
print ""
if __name__ == '__main__':
# matrix = [[1,2,3,4,5],
# [6,7,8,9,10],
# [11,12,13,14,15],
# [16,17,18,19,20]
# ]
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
print_matrix_digonally(matrix)
|
d0c9ee11d96f4eb2cf9f98de4891a439f6f895eb | nyxtom/fbpuzzles | /puzzles/liarliar.py | 3,415 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
colors = dict(red="\033[1;31m", nc="\033[0m")
def print_error(message):
"""
Prints the appropriate error message to the user
in full red color as it should be.
"""
print '%s%s%s' % (colors['red'], message, colors['nc'])
class Puzzle(object):
"""
Defines the liar liar puzzle implementation.
"""
def run(self, lines):
"""
Runs through the given input to create
an aggregate result of liars/non-liars.
"""
success, result = self.is_valid(lines)
if not success:
print_error(result)
return
graph, start = self.build_graph(result)
groups = [len(g) for g in self.bfs(graph, start)]
groups.reverse()
print '%s %s' % (groups[0], groups[1])
def is_valid(self, lines):
"""
Ensures that the given input is validated and
if not, then the appropriate error message
result will be displayed to the user.
"""
if not lines:
return False, 'You must provide a valid input file'
if not lines[0].strip().isdigit():
return False, 'The first line in the input should be the count'
lines = [line.strip() for line in lines]
matches = []
for line in lines[1:]:
m = re.match(r'(?P<name>[A-Za-z]+)(\s+(?P<count>\d+))?', line)
if not m:
return False, 'All lines must contain a valid name and/or count match'
else:
matches.append(m.groupdict('0'))
return True, matches
def build_graph(self, matches):
"""
Builds an undirected connected graph using the matching input.
"""
names = set([m['name'] for m in matches])
graph = {}
for n in names:
graph[n] = {}
i = 0
while i < len(matches):
count, n = matches[i].values()
start = n
for l in xrange(int(count)):
ln = matches[i + 1]['name']
graph[n][ln] = graph[ln][n] = True
i = i + 1
i = i + 1
return graph, start
def bfs(self, graph, start):
"""
Groups vertices into two groups using a FIFO queue for traversal.
http://en.wikipedia.org/wiki/Adjacency_matrix
http://en.wikipedia.org/wiki/Breadth-first_search
"""
visited = {start: True}
group1 = {start: True}
group2 = {}
import Queue
queue = Queue.Queue()
queue.put(start)
while not queue.empty():
n = queue.get()
for k in graph[n].keys():
if k in visited:
continue
visited[k] = True
if group2.get(n):
group1[k] = True
if group1.get(n):
group2[k] = True
queue.put(k)
return [group1, group2]
# Puzzle runner boilerplate
if __name__ == "__main__":
if not len(sys.argv) > 1:
print_error('You must provide an input filename')
else:
try:
with open(sys.argv[1]) as input_file:
input = input_file.readlines()
runner = Puzzle()
runner.run(input)
except IOError as e:
print_error(e)
|
2e92f456a5d3cf5ea78039b88453c2b260afbbc8 | liemlyquan/project-euler | /p4.py | 635 | 3.765625 | 4 | '''
Problem 4:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
https://projecteuler.net/problem=4
'''
first_number = 999
second_number = 999
array_of_result = []
def palindrome(int):
return str(int) == str(int)[::-1]
for first_counter in range(first_number,100,-1):
for second_counter in range(second_number, 100, -1):
prod = first_counter * second_counter
if (palindrome(prod)):
array_of_result.append(prod)
print(max(array_of_result))
|
fe1fe83467d0cb87fc08d7ad78422a8d164150f9 | neelamy/Leetcode | /Graph/140_WordBreakII.py | 1,368 | 3.53125 | 4 | # Source : https://leetcode.com/problems/word-break-ii/description/
# Algo/DS : Graph, DFS
# Complexity : O()
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
wordDict = set(wordDict)
d = {}
return self.check( s,wordDict, d)
def check(self,s,wordDict, d):
# if s has been processed then return its result
if s in d:
return d[s]
# return empty list if not s
if not s :
return []
res = []
for i in range(len(s)):
# check all possible prefix of s
if s[:i+1] in wordDict:
# if prefix in wordDict and no remanining char left then
# append it to dict
if i == len(s) -1: res.append(s[:i+1])
else:
# else get the result of remaining chars
remaining = self.check( s[i+1:],wordDict, d)
# append current word to each result
for string in remaining:
string = s[:i+1] + " " + string
res.append(string)
# update dict
d[s] = res
return res
|
65f06134a80f78a3ddcbef8529544fdb790abe1e | dianaparr/holbertonschool-higher_level_programming | /0x03-python-data_structures/8-multiple_returns.py | 264 | 3.84375 | 4 | #!/usr/bin/python3
def multiple_returns(sentence):
if sentence == "":
tuple_two = (len(sentence), None)
else:
# other form represents position 0 of the string with splice
tuple_two = len(sentence), sentence[:1]
return tuple_two
|
9e735698ecb205e83968bbee384732a132b1cb47 | usac201602491/Proyectos980 | /Ejemplos/Pogramacion Basica/Ejemplo3.py | 194 | 3.671875 | 4 | def esPar(num):
if(num%2>0):
return False
else:
return True
for i in range(10):
if(esPar(i)):
print("Es par : ",i)
else:
print("Es impar : ",i) |
56048abbfee557932a9dd38e3273addc907fd9e0 | snowan/interviews | /2021/python/20.valid-parentheses.py | 1,244 | 4 | 4 | """
20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
"""
"""
Solution: using stack, left put into stack, when current is right, check whether stack top left matches with current right, if stack empty or not match, return false. otherwise pop stack top, continue.
"""
def isValid(s: str) -> bool:
if not s:
return True
size = len(s)
if size % 2 != 0:
return False
maps = {')': '(', ']': '[', '}': '{'}
sets = {'(', '[', '{'}
stack = []
for idx in range(size):
curr = s[idx]
if curr in sets:
stack.append(curr)
else:
if not stack or maps[curr] != stack.pop():
return False
return len(stack) == 0
|
21b277478a5a1c7862ab8ddfee98b8d81126affe | serdarayalp/my-python-2 | /MoneyInWallet.py | 596 | 4 | 4 | # Use raw_input to get info from the user
nOnes = raw_input('How many ones do you have? ')
nFives = raw_input('How many fives do you have? ')
nTens = raw_input('How many tens do you have? ')
nTwenties = raw_input('How many twenties do you have? ')
# Use int to convert the inputted strings to integer values before multiplying
total = int(nOnes) + (int(nFives) * 5) + (int(nTens) * 10) + (int(nTwenties) * 20)
# Use str to convert to a string, then concatenate on a decimal point and zeros
totalAsString = str(total) + '.00'
# Concatentate strings and print
print 'You have $' + totalAsString
|
c2e76e612150284541fb33ad2e3bd4792fd4a02a | raufmca/pythonCodes | /FileOperations2.py | 1,139 | 4.34375 | 4 |
"""
Uses Python's file class to store data to and retrieve data from
a text file.
"""
def read_data(filename):
""" Print the elements stored in the text file named filename. """
with open(filename) as f:
for line in f:
print(int(line) , end = ' ')
def write_data(filename):
""" Allows the user to store data to the text file named filename. """
with open(filename, 'w') as f:
number = 0
while number != 999:
number = int ( input ( ' Enter the number = ' ))
if number != 999:
f.write(str(number)+'\n')
else:
break
def main():
""" Interactive function that allows the user to
create or consume files of numbers. """
stop = False
while not stop:
cmd = input (' W)rite , \n R)ead , \n Q)uit = ' )
if cmd == 'W' or cmd == 'w':
write_data(input ('Enter the filename = ' ))
elif cmd == 'R' or cmd == 'r':
read_data(input ('Enter the filename = ' ))
elif cmd == 'Q' or cmd == 'q':
stop = True
main()
|
3be0bf00a1d82d9a144b7a6f90a3dea5ccb66c71 | liucheng2912/py | /leecode/数据结构/二叉树/先序遍历-迭代.py | 2,387 | 3.75 | 4 | '''
算法1:将根节点入栈,然后弹出栈顶元素,将值追加到res末尾,然后将右子节点和左子节点一次入栈,因为左子节点要先出栈,所以先入栈右子节点
算法2:cur指向root根节点,将值追加到末尾,将根节点入栈
然后让cur指向cur.left 继续上述操作
当cur为None时,弹出根节点,让cur指向cur.right 继续上述操作
算法3:父节点遍历后不入栈,将右子节点入栈
'''
class Solution:
# 前序遍历
def pre_order(self, root):
stack = []
# 将根节点入栈
stack.append(root)
res = []
while stack:
# 将栈顶元素弹出,将值存入到res中
cur = stack.pop()
res.append(cur.val)
# 需要先弹出左子节点,所以右子节点先入栈
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return res
def pre_order1(self, root):
cur = root
stack = []
res = []
while stack or cur:
if cur:
res.append(cur.val)
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
cur = cur.right
def pre_order2(self, root):
cur = root
res = []
stack = []
while stack or cur:
if cur:
res.append(cur.val)
if cur.right:
stack.append(cur.right)
cur = cur.left
else:
cur = stack.pop()
def pre_order(self,root):
if not root:return []
res=[]
stack=[root]
while stack:
cur=stack.pop()
if cur.right:
stack.append(cur.right)
if cur.right:
stack.append(cur.left)
return res
#标记法迭代,在栈中存放一个标记位
def pre_order(self,root):
stack=[(0,root)]
res=[]
while stack:
flag,cur=stack.pop()
if not cur:continue
if flag==0:
stack.append(0,cur.right)
stack.append(0,cur.left)
stack.append(1,cur)
else:
res.append(cur.val)
return res
|
35432eb5027ad1056bae19d52e9a9e01ef692c14 | Owhab/Python-Codes | /StringFormating.py | 293 | 4.1875 | 4 | while True:
print("Enter 'x' for exit.")
string = input('Please Enter any string: ')
if string == 'x':
break
else:
new_string = string.replace(" ","")
print("\n New String after removing all spaces: ")
print(new_string, '\n')
|
b873739e464141263e4f399836e5b668bd5e3943 | amy243/wallbreakers_week1 | /stringmanipulation_q9.py | 366 | 4 | 4 |
'''
Write a function that reverses a string.
link:https://leetcode.com/problems/reverse-string
'''
class Solution:
def reverseString(self, s: List[str]) -> None:
def revv(start, stop, st):
if start<stop:
st[start],st[stop]=st[stop],st[start]
revv(start+1,stop-1,st)
revv(0,len(s)-1,s)
|
80850428c02381c7461ace01f3ab4e05b72f510d | Bob-CHEN26/IBI1_2019-20 | /Practical5/Exercise 7/powersof2.py | 617 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 10:32:44 2020
@author: 10139
"""
# Get the function ceil
from math import ceil
# Give x is a value
x=1750
# Add a string variable
s=str(x)+" is "
# Find n which makes 2^n is closest number to x and smaller than x.
for n in range (0, ceil(x**0.5)+1) :
if (2**n < x)==True and (2**(n+1) > x)==True:
break
# The primitive number minus 2^n, write the string
x=x-2**n
s=s+"2**"+str(n)
# Find the sum of powers of 2
while x!=0 and n>0:
n=n-1
if (2**n < x)==True:
x=x-2**n
s=s+" +2**"+str(n)
# Print the outcome
print (s)
|
d04a9ff0572d8ed9364260823eb1c300922deb0d | NiCrook/Edabit_Exercises | /30-39/35.py | 491 | 3.859375 | 4 | # https://edabit.com/challenge/gbWDtMHtZARm7sdNA
# Python has a logical operator "and".
# The "and" operator takes two boolean values, and returns True if both values are True.
def and_(bool1: bool, bool2: bool) -> bool:
try:
if bool1 and bool2:
return True
else:
return False
except TypeError as err:
print(f"Error: {err}")
print(and_(True, False))
print(and_(True, True))
print(and_(False, False))
print(and_(False, True))
|
1e8e9ac6fc2290b6f7a0ca32802d8d8779f59ca7 | peddroy/my-road-to-Python | /venv/Scripts/09_secao/53_listcomprehension.py | 3,291 | 4.46875 | 4 | """
LIST COMPREHENSION - PARTE 1
Utilizando List Comprehension podemos podemos gerar novas listas com dados processados a partir de outro iteravel.
Sintaxe de List Comprehension
[dado for dado in interavel]
numeros = [1, 2, 3, 4]
res = [numero * 10 for numero in numeros]
print(res)
def quadrado(valor):
return valor * valor
res = [quadrado(numero) for numero in numeros] # utilizando função
print(res)
Para entender melhor o que está acontecendo devemos dividir a expressão em duas partes:
1. Primeira parte: for numero in numeros
2. Segunda parte: numero * 10
# List Comprehensions versus Loop
# Exemplo com Loop
numero_dobrado = []
for numero in [1, 2, 3, 4]:
numero_dobrado.append(numero * 2)
print(numero_dobrado)
# List Comprehension
print([numero * 2 for numero in [1, 2, 3, 4]])
nome = 'Pedro Araujo'
print([letra.upper() for letra in nome])
def caixa_alta(nome):
nome = nome.replace(nome[0], nome[0].upper())
return nome
amigas = ['jessica', 'samara', 'suellen', 'jennifer']
print([caixa_alta(nome) for nome in amigas])
print([numero * 3 for numero in range(1, 10)])
print([bool(valor) for valor in [0, [], '', True, 1, 2, 3]])
print([str(num) for num in [1, 2, 3, 4]])
////////// LIST COMPREHENSION - PARTE 2 //////////
Podemos adicionar estruturas condicionais às lists comprehensions
numeros = [1, 2, 3, 4, 5, 6]
pares = [numero for numero in numeros if numero % 2 == 0]
impares = [numero for numero in numeros if numero % 2 != 0]
print(pares)
print(impares)
# refatorar
# Qualquer numero par modulo de 2 é 0 e 0 em Python é False. not False = True
pares = [numero for numero in numeros if not numero % 2]
# Qualquer numero impar modulo de 2 é 1 e 1 em Python é True.
impares = [numero for numero in numeros if numero % 2]
# estudo a parte if e if not
par = 2
impar = 3
if impar % 2:
print(par)
# Outro exemplo:
numeros = [1, 2, 3, 4, 5, 6]
res = [numero * 2 if numero % 2 == 0 else numero / 2 for numero in numeros]
print(res)
/// YOUTUBE
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ex1 = [(v * 2, v2) for v in l1 for v2 in range(3)]
l2 = ['Luiz', 'Marta', 'Maumau']
ex2 = [letra.replace('a', '@') for letra in l2]
ex3 = [letra.replace('a', '@').upper() for letra in l2]
print(ex3)
tupla = (
('chave', 'valor'),
('chave2', 'valor2')
)
exe4 = [(y, x) for x, y in tupla]
exe5 = dict(exe4)
print(exe5)
l3 = list(range(100))
exe6 = [v for v in l3 if v % 3 == 0 if v % 8 == 0]
print(exe6)
exe7 = [v if v % 3 == 0 else 'Não é' for v in l3]
exe8 = [v if v % 3 == 0 and v % 8 == 0 else 0 for v in l3]
print(exe7)
linhas_colunas = [
(x, y)
if y != 2 else (x, y * 100)
for x in range(1, 6)
for y in range(1,4)
if x != 2
]
print(linhas_colunas)
# String
string = 'Pedro Araujo'
numero_letras = 5
nova_string = '.'.join([
string[indice:indice + numero_letras]
for indice in range(0, len(string), numero_letras)
])
print(nova_string)
"""
nomes = ['luiz', 'maria', 'jose', 'carmelita', 'suavita']
novos_nomes = [f'{nome[:-1].lower()}'f'{nome[-1].upper()}' for nome in nomes]
print(novos_nomes)
numeros = [[numero, numero **2] for numero in range(10)]
print(numeros)
numeros = [[numero, numero **2] for numero in range(10)]
flat = [y for x in numeros for y in x]
print(flat)
|
d31a1550ba1f32cb1f60c4e0bafbd01189764546 | juliaheisler/CSE-231 | /proj08.py | 8,740 | 3.828125 | 4 | ###############################################################################
# Computer Project 8
#
# Algorithm
#
# Program uses 7 functions to take information provided in .csv file and\
# user's region input to create organized table and scatter plot.
#
# open_file: attempts opening file if it exists
#
# read_file: reads through file and creates dictionary depending on region\
# user inputs - returns dictionary and user input.
#
# max_min: determines maxs/mins of dictionary's values - returns maxs/mins\
# as well as states associated with them.
#
# display_info: displays stats and maxs/mins for states in specified region\
# plot_regression: draws line of best fit between plotted points.
#
# plot: using x and y provided by user, creates scatter plot.
#
# main: main function of program, calls each function and asks user if\
# graph should be plotted.
###############################################################################
#import sys
#def input( prompt=None ):
# if prompt != None:
# print( prompt, end="" )
# aaa_str = sys.stdin.readline()
# aaa_str = aaa_str.rstrip( "\n" )
# print( aaa_str )
# return aaa_str
import pylab
REGION_LIST = ['far_west',
'great_lakes',
'mideast',
'new_england',
'plains',
'rocky_Mountain',
'southeast',
'southwest',
'all']
VALUES_LIST = ['pop', 'gdp', 'pi', 'sub', 'ce', 'tpi', 'gdpp', 'pip']
VALUES_NAMES = ['State', 'Population(m)','GDP(b)','Income(b)','Subsidies(m)',\
'Compensation(b)','Taxes(b)','GDP per capita','Income per capita']
PROMPT1 = "\nSpecify a region from this list -- far_west,great_lakes,"\
"mideast,new_england,plains,rocky_mountain,southeast,southwest,all: "
PROMPT2 = "\nSpecify x and y values, space separated from Pop, GDP, PI,"\
" Sub, CE, TPI, GDPp, PIp: "
def open_file():
'''
Using user's input, attempts to open file (try/except).
Returns file pointer.
'''
# driver loop for user's file input #
while True:
file_input = input("Enter a filename: ")
try:
# while file exists, attempt opening #
fp = open(file_input)
# return file pointer #
return fp
# if file does not exist, prints error statement #
except FileNotFoundError:
print("\nError: File does not exist! Please try again.\n")
def read_file(fp):
'''
Using opened file and user input, reads file and creates dictionary of\
of states associated with inputed region.
Returns dictionary and user's input.
'''
# skips over first line #
fp.readline()
# creates empty dictionary #
D = {}
user_input = ''
counter=1
# loop fot error checking #
while user_input.lower() not in REGION_LIST:
if counter>1:
print("Error in region name. Please try again.")
# prompt and user input for region #
user_input = input(PROMPT1)
counter += 1
# if statement for region in list or all #
if user_input.lower() in REGION_LIST or user_input.lower() == 'all':
# loop iterating through file #
for line in fp:
# strips and splits each word from file and creates list #
line = line.strip()
L1 = line.split(',')
# associates indexes with specific variables #
state = L1[0]
region = L1[1]
# converts strings in list to floats #
for i in range(2,8):
L1[i] = float(L1[i])
# appends GDP per capita and Income per capita #
L1.append(L1[3]/L1[2]*1000)
L1.append(L1[4]/L1[2]*1000)
# adds state as a key to dictionary and floats of list as values #
if user_input.lower() == region.lower():
D[state] = L1[1:]
if user_input.lower() == 'all':
D[state] = L1[1:]
# returns dictionary and user input #
return D, user_input
def max_min(D):
'''
Iterates through dictionary values, finding min/max of GDP per capita\
and income per capita.
Returns max/mins and states associated with them.
'''
# maxs/mins assigned exaggerated values #
g_max=0
g_min=1000000000000000000000000000
i_max=0
i_min=1000000000000000000000000000
#loop iterates through dictionary finding max/mins and associated states#
for k,v in D.items():
if v[7] > g_max:
g_max = v[7]
state_g_max = k
if v[7] < g_min:
g_min = v[7]
state_g_min = k
if v[8] > i_max:
i_max = v[8]
state_i_max = k
if v[8] < i_min:
i_min = v[8]
state_i_min = k
# returns maxs/mins and associated states #
return g_max,state_g_max,g_min,state_g_min,i_max,state_i_max,\
i_min,state_i_min
def display_info(D,g_max,state_g_max,g_min,state_g_min,i_max,state_i_max,\
i_min,state_i_min,user_input):
'''
Displays max/min information and states with their stats in table format.
'''
# defines region inputed as first index in value list #
for k,v in D.items():
reg_input = v[0]
break
# if user's input is 'all', this becomes region input #
if user_input.lower() == 'all':
reg_input = 'All'
# prints maxs and mins for states in inputed region#
print("\nData for the", reg_input, "region:\n")
print(state_g_max, "has the highest GDP per capita at","${:,.2f}"\
.format(g_max))
print(state_g_min, "has the lowest GDP per capita at","${:,.2f}"\
.format(g_min),"\n")
print(state_i_max, "has the highest income per capita at","${:,.2f}"\
.format(i_max))
print(state_i_min, "has the lowest income per capita at","${:,.2f}"\
.format(i_min))
print("\nData for all states in the", reg_input, "region:\n")
print("{:<14s}{:>14s}{:>11s}{:>11s}{:>15s}{:>17s}{:>12s}{:>18s}{:>19s}"\
.format('State', 'Population(m)','GDP(b)','Income(b)','Subsidies(m)'\
,'Compensation(b)','Taxes(b)','GDP per capita',\
'Income per capita'))
# prints stats for each state in organized table #
for k,v in sorted(D.items()):
print("{:<14s}{:>14,.2f}{:>11,.2f}{:>11,.2f}"\
"{:>15,.2f}{:>17,.2f}{:>12,.2f}{:>18,.2f}{:>19,.2f}"\
.format(k,v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8]))
def plot_regression(x,y):
'''Draws a regression line for values in lists x and y.
x and y must be the same length.'''
xarr = pylab.array(x) #numpy array
yarr = pylab.array(y) #numpy arry
#creates line, only takes numpy arrays#
m,b = pylab.polyfit(xarr,yarr, deg = 1)
#as parameters
pylab.plot(xarr,m*xarr + b, '-') #plotting the regression line
def plot(D):
'''
Using dictionary and user's choice of x and y, creates scatter plot.
'''
# initializes variables #
state_list = []
x = []
y = []
a = ''
b = ''
# loop for error checking #
while a.lower() not in VALUES_LIST or b.lower() not in VALUES_LIST:
while True:
try:
X_Y=input(PROMPT2)
a,b = X_Y.split()
break
except ValueError:
print("Error")
# associates x and y indexes with indexes in values list #
x_index = VALUES_LIST.index(a.lower())
y_index = VALUES_LIST.index(b.lower())
# appends values from dictionary to list #
for k, v in D.items():
state_list.append(k)
x.append(v[x_index+1])
y.append(v[y_index+1])
# title of graph #
pylab.title(VALUES_NAMES[x_index+1]+' vs. '+VALUES_NAMES[y_index+1])
# label of x axis #
pylab.xlabel(VALUES_NAMES[x_index+1])
# label of y axis #
pylab.ylabel(VALUES_NAMES[y_index+1])
# plots points #
pylab.scatter(x,y)
# labels points with state names #
for i, txt in enumerate(state_list):
pylab.annotate(txt, (x[i],y[i]))
# plots line of best fit #
plot_regression(x,y)
# displays graph #
pylab.savefig("plot.png")
def main():
# calls each function #
fp = open_file()
D, user_input = read_file(fp)
g_max,state_g_max,g_min,state_g_min,i_max,state_i_max,i_min,state_i_min\
= max_min(D)
display_info(D,g_max,state_g_max,g_min,state_g_min,i_max,state_i_max,\
i_min,state_i_min,user_input)
plot_str =input("\nDo you want to create a plot? (yes or no) ")
# if user inputs 'yes' plot graph #
if plot_str.lower() == "yes":
plot(D)
if __name__ == "__main__":
main()
#Questions
#Q1: 7
#Q2: 7
#Q3: 5
#Q4: 5
#Q5: 7
|
2bb8dc9ee323c494bcee41020ca3939f10170a07 | Erfan021/Implement_OOP_Python | /venv/Abstraction_and_Encapsulation.py | 1,851 | 4.03125 | 4 | class Library:
def __init__(self, listOfBooks):
self.availableBooks = listOfBooks
def displayBooks(self):
print() # Encapsulation being done
print("Books in Library:")
for books in self.availableBooks:
print(books)
def lendBook(self, requestedBook):
if requestedBook in self.availableBooks: # Encapsulation being done
self.availableBooks.remove(requestedBook)
print("Book borrowed")
else:
print("Sorry, requested book is not available.")
def addBook(self, returnedBook):
self.availableBooks.append(returnedBook) # Encapsulation being done
print("Book returned to the library.")
class Customer:
def requestBook(self): # Encapsulation being done
print("Enter the name of book to borrow: ")
self.book = input()
return self.book
def returnBook(self): # Encapsulation being done
print("Enter name of book to return: ")
self.book = input()
return self.book
customer = Customer()
library = Library(['Life of Pie', 'Matilda', 'Boy', 'Narnia'])
while True:
print('Enter 1 to display books available in library: ')
print('Enter 2 to borrow the book: ')
print('Enter 3 to return the book: ')
print('Enter 4 to quit: ')
userInput = int(input())
if userInput is 1:
library.displayBooks() # Layer of abstraction performed
elif userInput is 2:
requestedBook = customer.requestBook() # Layer of abstraction performed
library.lendBook(requestedBook)
elif userInput is 3:
returnedBook = customer.returnBook() # Layer of abstraction performed
library.addBook(returnedBook)
elif userInput is 4:
quit()
else:
print("Enter right option!")
print("Finally GIT implemented")
|
24037d09430d35a666678c9639bd5ad12eb0a96b | bluepine/topcoder | /algortihms_challenges-master/general/odd_man.py | 433 | 3.953125 | 4 | """
In an unsorted array of integers each except one appear twice
Find the element that appears once
Idea: Do xor on array and the one that is left as a result is element
that appears once
"""
def odd_man(array):
if array is None or len(array) < 1:
return False
if len(array) == 1:
return array[0]
return reduce(lambda x, y: x ^ y, array)
array = [1, 3, 4, 3, 2, 5, 2, 5, 4]
print odd_man(array)
|
bbcbbeac8350810bd6e2c1cc3252d0448b173c24 | ARSimmons/IntroToPython | /Students/apklock/session02/sum_series.py | 189 | 3.609375 | 4 | def sum_series(l,m,n): # return the 'lth' place in the series with starting values of m and n
if l == 1:
return m
if l == 2:
return n
return sum_series(l-2,m,n) + sum_series(l-1,m,n) |
47a743a5f6b8b6c160db272423892512fb8273bb | linzhulz/CLRS | /chapter10_ElementaryDataStructure/chapter10.1-4.py | 1,526 | 3.875 | 4 | #!/usr/bin/env python
# coding=utf-8
class Queue:
def __init__(self, size):
self.q = [0 for _ in xrange(size)]
self.head = 0
self.tail = 0
self.size = size
def enqueue(self, x):
if (self.tail + 1) % self.size == self.head:
raise Exception('overflow')
self.q[self.tail] = x
# print 'q.tail before enqueue', q.tail
self.tail += 1
if self.tail == self.size:
self.tail = 0
# print 'q.tail after enqueue', q.tail
# print '###'
def dequeue(self):
if self.head == self.tail:
raise Exception('underflow')
x = self.q[self.head]
# print 'q.head before dequeue', q.head
self.head += 1
if self.head == self.size:
self.head = 0
# print 'q.head after dequeue', q.head
# print '###'
return x
class Stack:
def __init__(self, size):
self.s = [-1 for _ in xrange(size)]
self.top = -1
self.size = size
def push(self, x):
if self.top + 1 == self.size:
raise Exception('overflow')
# print 'top before push', self.top
self.top += 1
self.s[self.top] = x
# print 'top after push', self.top
def pop(self):
if self.top == 0:
raise Exception('underflow')
# print 'top before pop', self.top
x = self.s[self.top]
self.top -= 1
# print 'top after pop', self.top
# return x
|
f993d49c0192e37c9f35b05d4f624bc80c3cd096 | hky5401/MyAlgorithm | /Baekjoon Algorithm/Step/3_1차원 배열/7_4344_평균은 넘겠지_실수 자릿수 출력.py | 432 | 3.546875 | 4 | num = int(input())
result = []
for i in range(num):
num_list = list(map(int, input().split()))
people = len(num_list) - 1
avg = sum(num_list)-num_list[0]
avg /= people
count = 0
for j in range(1, len(num_list)):
if(num_list[j] > avg):
count += 1
re = count / people
re *= 100
result.append(re)
for i in range(len(result)):
print('%.3f' % result[i],end='')
print('%') |
21fee9082c166ae353507fc4c81024baf00b3d98 | pingwindyktator/AdventOfCode | /2019/day_6/part_2_dijkstra.py | 1,059 | 3.78125 | 4 | def find_shortest_path(start, end, neighbours):
import sys
vertices = list(neighbours.keys())
distances = {v: sys.maxsize for v in vertices}
distances[start] = 0
while vertices:
current = min(vertices, key=lambda v: distances[v])
if distances[current] == sys.maxsize: break
for n in neighbours[current]:
new_route = distances[current] + 1
if new_route < distances[n]:
distances[n] = new_route
vertices.remove(current)
return distances[end]
if __name__ == '__main__':
neighbours = {}
for object, orbits_around in list(map(lambda x: [x.strip() for x in x.split(')')], open('input').readlines())):
if orbits_around not in neighbours: neighbours[orbits_around] = []
if object not in neighbours: neighbours[object] = []
neighbours[orbits_around].append(object)
neighbours[object].append(orbits_around)
start = neighbours['YOU'][0]
end = neighbours['SAN'][0]
print(find_shortest_path(start, end, neighbours))
|
ea90e3cf5a5e1d34a7f806dd4018b9c88ae6248c | anasvassia/Riddle-Maze | /maze_game.py | 2,482 | 4.0625 | 4 | # http://www.101computing.net/creating-sprites-using-pygame/
# http://www.101computing.net/pygame-how-to-control-your-sprite/
# https://stackoverflow.com/questions/28098738/changing-size-of-image
# https://stackoverflow.com/questions/31570527/how-to-get-the-color-value-of-a-pixel-in-pygame
# a maze game where in order to get through the end, the player must answer riddles
# at the moment, there is only one riddle per game
from starter import *
from riddles import *
import pygame
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
SPRITEWIDTH = 20
SPRITEHEIGHT = 20
SCREENWIDTH = 600
SCREENHEIGHT = 600
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Riddle Maze")
# allowing for randomization of mazes
mazes = ["maze.png", "kidmaze.png", "coding maze"]
ranmaze = randint(0, len(mazes)-1)
# game starts
game = Starter(mazes[ranmaze], RED, SPRITEWIDTH, SPRITEHEIGHT)
game.resizeBG(SCREENWIDTH, SCREENHEIGHT)
game.resizeSprite(SPRITEWIDTH, SPRITEHEIGHT)
# at the moment, only one riddle is created
ranx = randint(0, SCREENWIDTH)
rany = randint(0, SCREENHEIGHT)
riddle = Riddle(GREEN, SPRITEWIDTH, SPRITEHEIGHT, ranx, rany)
riddle.resize(SPRITEWIDTH, SPRITEHEIGHT)
done = False
riddleSolved = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_x: # Pressing the x Key will quit the game
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
game.moveRight(1)
if keys[pygame.K_LEFT]:
game.moveLeft(1)
if keys[pygame.K_DOWN]:
game.moveDown(1)
if keys[pygame.K_UP]:
game.moveUp(1)
screen.fill(WHITE)
game.drawBG(screen)
game.drawSprite(screen)
riddle.draw(screen)
# if the user is on top of the riddle, then the riddle box opens
if game.urect.x == ranx and game.urect.y == rany:
riddle.start()
if riddle.check() == True:
riddle.color = GREY
else:
riddle.start()
# the game ends when the user reaches the lower right corner of the screen
if game.urect.x == SCREENWIDTH - 2 and game.urect.y == SCREENHEIGHT - 2:
done = True
pygame.quit()
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
0a77930e31eefbc949d6d6983b518bc8094632f3 | mattmakesmaps/python-algorithms-data-structures | /recursion/turtle_fractal.py | 1,037 | 4.125 | 4 | import turtle
import itertools
colors = ['tan', 'yellow', 'tomato', 'violet', 'blue', 'LemonChiffon']
colorPicker = itertools.cycle(colors)
def tree(branchLen, t):
# Base case, branchLen less then 5
if branchLen > 5:
t.color(colorPicker.next())
t.forward(branchLen)
t.right(40)
# at the deepest level (branchLen == 15),
# tree(15-15, t) will do nothing, allowing the
# line after, `t.left(80)` to execute.
tree(branchLen-15, t)
t.left(80)
tree(branchLen-15, t)
t.right(40)
# t.backward is required to reset the position
# of the turtle for the previous tree() instance on outer frame.
# NOTE: the same turtle is being used in every frame;
# separate turtles are not created per frame.
t.backward(branchLen)
if __name__ == '__main__':
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("green")
tree(75, t)
myWin.exitonclick() |
746546a9118acd00262870fe6b5341eaf95932c2 | alisen39/algorithm | /algorithms/sword_offer/25_mergeTwoLists.py | 1,077 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# author: Alisen
# time: 2022/7/22 20:36
# desc:
""" 剑指 Offer 25. 合并两个排序的链表
https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(-1)
pre = head
while l1 and l2:
if l1.val > l2.val:
pre.next = l2
l2 = l2.next
else:
pre.next = l1
l1 = l1.next
pre = pre.next
if l1 is None:
pre.next = l2
if l2 is None:
pre.next = l1
pre = pre.next
return head.next
if __name__ == '__main__':
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(7)
l1.next = l2
l2.next = l3
l11 = ListNode(1)
l22 = ListNode(3)
l33 = ListNode(6)
l11.next = l22
l22.next = l33
Solution().mergeTwoLists(l1, l11)
|
83943d7da7860592c34b57ec9ee3df26d3f01de0 | dhbandler/Projects | /HangmanGraphics.py | 4,572 | 3.6875 | 4 | #Daniel Bandler
#4/4/18
#HangmanGraphics.py --- makes a hangman game graphically
from ggame import *
from random import randint
def pickWord(): #Selects the word
num = randint(0,1)
choices = ["praetor", "purgatory", "perestroika","airport","realpolitik","beelzebub","fraternal","schadenfreude","intelligentsia","incendiary","dachshund","petroleum","electroencephalograph","antidisestablishmentarianism" "carthage"]
return choices[num]
def charact(): #Prints lines under letters for guess
charcount = len(data["word"])
z = 350
for i in range(1,charcount+1):
Sprite(wordunderline, (z, 450))
z += 25
def wordComplete(): #Finishes game if you get it correct
for ch in data["word"]:
if ch not in data["lettersGuessed"]:
data["gameOver"] = False
return False
data["gameOver"] = True
return True
def keyPress(event): #Deals with what happens when you hit a key
if data["gameOver"] == False:
if event.key not in data["lettersGuessed"]:
text = TextAsset(event.key, fill=black,style= "bold 30pt Georgia")
Sprite(text, (data["guessed boxx"],data["guessed boxy"]))
data["guessed boxx"] += 40
if data["guessed boxx"] >= 900:
data["guessed boxy"] += 40
data["guessed boxx"] = 450
data["lettersGuessed"] += event.key
if wordComplete():
Sprite((TextAsset("YOU SAVED THE CONVICTED MURDERER!!", fill=green,style= "bold 75pt Georgia")), (75, 50))
z = 350 #Sprites letters if correct
for ch in data["word"]:
if ch == event.key:
Sprite(TextAsset(event.key, fill=black,style= "bold 30pt Georgia"), (z, 410))
z += 25
if event.key not in data["word"]: #Deals with the "What if?"'s of getting it wrong
data["incorrect guesses"] += 1
if data["incorrect guesses"] == 1:
Sprite(head, (200,140))
elif data["incorrect guesses"] == 2:
Sprite(body, (235,220))
elif data["incorrect guesses"] == 3:
Sprite(limbs, (225,295))
elif data["incorrect guesses"] == 4:
Sprite(limbs, (245,295))
elif data["incorrect guesses"] == 5:
Sprite(blackLine, (230, 220))
elif data["incorrect guesses"] == 6:
Sprite(blackLine2, (190, 220))
Sprite((TextAsset("YOU DIED!!", fill=red,style= "bold 100pt Georgia")), (150, 100))
data["gameOver"] = True
if __name__ == '__main__':
data = {} #These are for storing number of correct and incorrect guesses
data["incorrect guesses"] = 0
data["guessed boxx"] = 450
data["guessed boxy"] = 250
data["word"] = pickWord()
data["gameOver"] = False
data["lettersGuessed"] = str()
#Colors:
black = Color(0x000000,1) #color black
white = Color(0xFFFFFF,1) #color white
woodbrown = Color(0x8B4513,1) #Color brown
lightbrown = Color(0xD2691E,1)#light brown
red = Color(0xFF0000,1) #red
green = Color(0x008000,1) #green
blackOutline = LineStyle(5,black) #Outline
blackOutline2 = LineStyle(1,black) #Outline
#Shape Design:
wood1 = RectangleAsset(50,400, blackOutline2, woodbrown)
wood2 = RectangleAsset(200,25, blackOutline2, woodbrown)
rope1 = RectangleAsset(5,75,blackOutline2,lightbrown)
rope2 = EllipseAsset(15,30,blackOutline2,lightbrown)
ropespace = EllipseAsset(12,27,blackOutline2,white)
head = CircleAsset(40,blackOutline,white)
body = RectangleAsset(5,75, blackOutline, white)
limbs = RectangleAsset(5,50, blackOutline, white)
blackLine = LineAsset(50,50, blackOutline)
blackLine2 = LineAsset(-50,50, blackOutline)
wordunderline = RectangleAsset(15,5, blackOutline, black)
#Sprites constants
Sprite(wood1, (50,50))
Sprite(wood2, (50,50))
Sprite(wood2, (0,450))
Sprite(rope1, (240,75))
Sprite(rope2, (228,150))
Sprite(ropespace, (231, 153))
charact() #creates the correct number of underlines for the word
for i in str("abcdefghijklmnopqrstuvwxyz"): #listens for keyboard event
App().listenKeyEvent("keydown", i, keyPress)
App().run(pickWord)
|
cf065520b4994e10a80c17c62aa81c53535600a7 | Niguwa/848iPython | /digits.py | 201 | 4.0625 | 4 | string=input("enter string: ")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("the number of digits is: ")
print(count1)
|
1ca45414208e908aed7078974e28a13c69564583 | thenerdpoint60/Sem_5 | /SEM_5/AI/BFS.py | 421 | 3.734375 | 4 | g={'A':{'B','C'},
'B':{'A','D','E'},
'C':{'A','C'},
'D':{'B','G'}}
def bfs(g,s,goal):
explored=[]
queue=[s]
while queue:
node = queue.pop(0)
if node not in explored:
explored.append(node)
neis=g[node]
for nei in neis:
queue.append(nei)
if goal==node:
break
return explored
print (bfs(g,'A','C'))
|
626475ef01013ce2bc88fedac15798b9ce21ad8b | JagadeeshVarri/learnPython | /Basics/prob_12.py | 233 | 4.28125 | 4 | # Write a Python program to print the calendar of a given month and year.
import calendar
year = int(input("Enter the year : "))
month = int(input("Enter the month : "))
print(" month calender : ")
print(calendar.month(year, month)) |
05aeeacd3bfa9f1e67b61f67d83e000fe28ccf01 | neethucmohan/solutions | /chapter2/reverseline.py | 155 | 3.671875 | 4 | #Problem 18
def reverse(fname):
l=open(fname).readlines()
r=map(lambda line:line.strip()[::-1],l)
print '\n'.join(r)
import sys
reverse(sys.argv[1])
|
97d1219305140306d90c7356e7475ea2a81bb54c | Khalaf57/ml17kfma | /Python Scripts/Final_Model/agentframework.py | 4,905 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 14:31:00 2018
@author: ml17kfma
"""
import random # random is a library contains many featurs and now it is imported
# a classification of an agent characteristic and behavior that can move and eat and share with other agents within the environment given
class Agent():
# initialise and define the variables that will be used in the model
def __init__(self, name, environment, randomSeed, probabilityMove, printlevel):
random.seed(randomSeed) # this implimented to generlise the resulte of the model each time it will be run
self.x = random.randint(0, 299)
# The x coordinate value it can be obtained from a web page but here it is random number from 0 to 299 to be inside the environment boundaries
self.y = random.randint(0, 299)
# The y coordinate value it can be obtained from a web page but here it is random number from 0 to 299 to be inside the environment boundaries
self.name = name # the id of each agent
self.environment = environment # The space that evrey agent will move in and eat from.
self.store = 0 # The value of each agent store which could be a basket and it is zero here.
self.probabilityMove = probabilityMove
# this variable will be used in defining the ability of agents to move into different place within the environment
self.printlevel = printlevel # this implemented to orgenise printing the values and textual contents
pass
# This function will give every agent a specific name, location and store after running the model and it return all these values into the agents
def __str__(self):
return "Agent " + str(self.name) + ": Location x=" + str(self.x) + "; y=" + str(self.y) + " Store=" + str(self.store)
# describe the movement ability of agents whether they move or stay from their current locations to different direction
def move0(self, xory):
if random.random() < self.probabilityMove:
if random.random() < 0.5:
xory = (xory + 1) % 300
else:
xory = (xory - 1) % 300
return xory
# define agent locations befor and after any new move for each iteration
def move(self):
self.print1("Before move:" + self.__str__())
self.y = self.move0(self.y)
self.x = self.move0(self.x)
self.print1("After move:" + self.__str__())
# describe the amount of eating of agents from the environment and decrease that from values of pixles
def eat(self):
amount = random.randint(0,10) # the amount of an agent eating will change randomly in each iteration
#amount = 2
self.print1("Amount eaten " + str(amount)) # show the value of amount eaten
if self.environment[self.y][self.x] > amount: # condition if the amount below the value of environment they can eat
self.environment[self.y][self.x] -= amount # take the value from environment
self.store += amount # add the value to the store
# share the with other agents using the condition inside the loop if distance between agents is below the neighbourhood
def share(self,neighbourhood,agents,j):
# Go through agents
for i in range(j + 1, len(agents)):
d = self.distance(agents[i]) # set d variable as a distance of an agent
self.print1("I am Agent " + str(self.name) + " do I share with Agent" + str(i) + "?")
#a textual message cantains agents id with a quastion that asked if they share or not
self.print1("The distance between us is " + str(d)) # the distance will appear
if (d < neighbourhood):
self.print1("Yes, we share.") # if the above condition is true the agents will share otherwise they will not share
self.print1("I have store " + str(self.store)) # show the value of an agent store
self.print1("You have store " + str(agents[i].store)) # idicate the other agent store
amount = (self.store + agents[i].store) / 2 # every agent share half of their store
self.store = amount
agents[i].store = amount
self.print1("We end up sharing " + str(amount)) # sum the amount of sharing
else:
self.print1("No, we are too far away to share.")
# calculate the distance between agents according to their locations using x and y coordinate values
def distance(self, agent):
return (((self.y - agent.y)**2) +
((self.x - agent.x)**2))**0.5
# define the print function which is described previously
def print1(self, s):
if (self.printlevel > 1):
print(s) |
f19956ce276a8e493f5c8b5399732a092b41cd1c | qlhai/Algorithms | /程序员面试金典/01.03.py | 884 | 3.5 | 4 | """
面试题 01.03. URL化
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例2:
输入:" ", 5
输出:"%20%20%20%20%20"
提示:
字符串长度在[0, 500000]范围内。
"""
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
return S[:length].replace(' ', '%20')
def replace_spaces_naive(self, s: str, length: int) -> str:
res = [''] * length
for i in range(length):
if s[i] == ' ':
res[i] = '%20'
else:
res[i] = s[i]
return ''.join(res)
|
62b75d82820bfe588b7404cf61f0561d976eaba1 | jarvisi71729/Mega-Movie-Fundraiser | /01_Name_Not_Blank.py | 309 | 3.8125 | 4 | # Functions go here
def not_blank(question):
valid = False
while not valid:
response = input(question)
if response != "":
return response
else:
print("Sorry - this can't be blank")
# Main routine goes here
name = not_blank("What's your name? ") |
307177ce185b797061df03cc0b2f94277832e762 | xzmbghmf/Hacktoberfest_Event | /Make a Wish.py | 1,393 | 3.890625 | 4 |
# Import the modules
import sys
import random
ans = True
while ans:
question = raw_input("Ask if your wish will be granted: (press enter to quit) ")
answers = random.randint(1,7)
if question == "":
sys.exit()
elif answers == 1:
print "Congratulations! The odds are in your favour and your wish will surely be granted!"
elif answers == 2:
print "There is a high chance your wish will come true,but you need to put in the effort."
elif answers == 3:
print "Your wish will not come true easily, so do work hard to achieve your dreams!"
elif answers == 4:
print "If you really want this wish to come true,you must work really hard or it won't come true. But I believe that hard work pays off! "
elif answers == 5:
print "I'm sorry,but the chances of this wish coming tre are really slim."
elif answers == 6:
print "I'm really sorry but this wish doesn't seem to have a chance of coming true. It's okay, I believe that you can still be happy.Be positive!"
elif answers == 7:
print "Hmm, the chances of your wish coming true are really 50/50. Press enter again to get another result!"
print "Thank you for making your wish! Whether your result be positive or not, I wish you all the best! And that wish shall come true! :D"
|
a253720337c9cab846961c31293e3d140a320225 | SiddhantBhardwaj2018/ISTA-350 | /lab10_solutions.py | 11,161 | 3.828125 | 4 | from bs4 import BeautifulSoup
import json
def make_soup(fname):
"""
This function takes a string as its only parameter.
The string REPRESENTS the name of an html file.
Your task is to CREATE and RETURN a BeautifulSoup object from the
string parameter.
"""
return BeautifulSoup(open(fname), "lxml")
def make_table(fname):
"""
This function takes a string as its only parameter. The string, fname,
REPRESENTS the name of an html file.
First task:
Use your make_soup function to create a soup object from fname.
The BeautifulSoup object that is returned from the first task, contains
an html parse tree that describes a table of data. If you refer back to
index_lab9.html file you can see that the table is filled with
"@}>-'-,--" (thorny roses), and "(8>/--<" (creepy aliens).
Second task:
EXTRACT the data from the parse tree and store it into a list of lists.
Each inner list within your list of lists should contain the data from a
respective row in the HTML table.
Once you are finished extracting the data from the table RETURN the
list of lists.
"""
soup = make_soup(fname)
primary_list = []
for tr in soup.find_all('tr'):
sub_list = []
for td in tr.find_all('td'):
sub_list.append(td.get_text())
primary_list.append(sub_list)
return primary_list
def remove_thorns(data):
"""
This function takes a list of lists. The list of lists contains either
alien "(8>/--<" or thorny rose "@}>-'-,--" emoticons.
As you can see the rose emoticons contain virtual thorns. Your task is to
remove the thorns on the roses. Return a NEW list of lists in which
thorny roses "@}>-'-,--" are de-thorned "@}>----" , leave the aliens alone
for now.
Restriction:
- You can not alter the originality list of lists.
"""
new_data = data.copy()
for r in range(len(data)):
for c in range(len(data[0])):
if data[r][c] == "@}>-'-,--":
new_data[r][c] = "@}>----"
return new_data
def translate_data(data, original=True, english=True):
'''
This function take as list of lists as its first parameter, and two
booleans for the second and third parameters. The list of lists contains
either alien "(8>/--<" or DE-THORNED rose "@}>----" emoticons.
Your task is to translate emoticon text to English and vise versa.
-First, check if the second parameter, original, is True. If that
is the case raise a RuntimeError with the message:
"Cannot alter source, aborting mission!"
Otherwise do the next step below.
-If the third parameter, english, is True you will translate
"@}>----" to "ROSE" and "(8>/--<" to "ALIEN". If the english parameter
is False you will translate "ROSE" to "@}>----" and "ALIEN" to "(8>/--<".
-This function returns None.
Example:
data = [['@}>----', '@}>----'], [['ROSE', 'ROSE'],
['(8>/--<', '@}>----'], <=> ['ALIEN', 'ROSE'],
['@}>----', '(8>/--<']] ['ROSE', 'ALIEN']]
'''
if original:
raise RuntimeError("Cannot alter source, aborting mission!")
else:
if english:
for r in range(len(data)):
for c in range(len(data[0])):
if data[r][c] == '@}>----':
data[r][c] = 'ROSE'
else:
data[r][c] = 'ALIEN'
else:
for r in range(len(data)):
for c in range(len(data[0])):
if data[r][c] == 'ROSE':
data[r][c] = '@}>----'
else:
data[r][c] = '(8>/--<'
def process_data(data):
"""
This function takes a list of lists. The list of lists contains either
alien "(8>/--<" or thorny rose "@}>-'-,--" emoticons.
Your task is as followed:
- Remove the thorns form the thorny roses. What function does this?
Remember the function that you will use will return a new list of
lists. Never alter original data.
- Next, translate the list of list that was return from the previous
step. Make sure to pass in the proper arguments. You want to translate
form emoticon to English. Remember you already coded a function that
does this!
NOTE: After translating your list your elements are "ROSE" and "ALIEN"
not the emoticon text version.
- Then, for each row in the list you want to place all the roses before
aliens.
Example:
[['ALIEN', "ROSE", "ROSE", "ROSE", "ROSE", "ROSE", 'ALIEN'], ...]
will now be
[["ROSE", "ROSE", "ROSE", "ROSE", "ROSE", 'ALIEN', 'ALIEN'], ...]
- Finally, translate the list of lists back from English to emoticon text.
Make sure to pass in the proper arguments in the function call.
Return the translated list of lists.
"""
data_copy = remove_thorns(data)
translate_data(data_copy, False)
data_copy2 = data_copy.copy()
for row in data_copy2:
aliens, roses = [], []
for item in row:
if item == "ALIEN":
aliens.append(item)
else:
roses.append(item)
data_copy.pop(0)
sub_list = roses + aliens
data_copy.append(sub_list)
translate_data(data_copy, False, False)
return data_copy
def verify_ratio(data, ratio_dict = {}):
"""
This function takes a list of lists. The list of lists contains either
alien "(8>/--<" or DE-THORNED rose "@}>----" emoticons.
Your task it to CREATE and RETURN a dictionary that maps the alien (8>/--<
and de-thorned rose @}>---- emoticons to the number of times it appear
in the list of lists.
Example:
data = [['@}>----', '@}>----'],
['(8>/--<', '@}>----'],
['@}>----', '(8>/--<']]
Dictionary returned:
stats = {'@}>----':4, '(8>/--<':2}
"""
for r in range(len(data)):
for c in range(len(data[0])):
if data[r][c] not in ratio_stats:
ratio_dict[data[r][c]] = 0
ratio_dict[data[r][c]] += 1
return ratio_dict
def encrypt_and_file(data, encryptionKey_dict):
"""
This function takes a list of lists as its first parameter. The list
of lists contains either alien "(8>/--<" or de-thorned rose "@}>-'-,--"
emoticons. The second parameter is a dictionary that maps a character to
a string integer.
Example:
encryptionKey_dict = {'A': '121', 'L': '050', 'I': '932',
'E': '13', 'N': '87', 'R': '11',
'O': '430', 'S': '553'}
Your task is to encrypt the data in the list of lists. Your
encryptionKey_dict can only encrypt English alphabet characters so you
must first translate the data from emoticon text to English.
-You MUST translate the original data don't make a copy of it. Recall
that translate_data will raise a RuntimeError if you indicate that
you are translating the original data. Call the function with the
appropriate arguments to bypass raising an Error.
-After translating, you need to encrypt, use the dictionary,
encryptionKey_dict, to do this. For each character in the strings
"ALIEN" or "ROSE" you will replace with values in the encryptionKey_dict.
Remember you are going through a lists of lists. Make sure that the
encrypted data is transformed to an integer, see example below!
Example:
[["ROSE", "ROSE", "ALIEN"],...]
Will become:
[[1143055313, 1143055313, 1210509321387],...] #NOTE: no longer
strings!
-Finally save the encrypted data in json format. Name the file
"AlienMission.json". You must write each row on separate lines.
-Function returns None.
"""
translate_data(data,False)
for r in range(len(data)):
for c in range(len(data[r])):
item = data[r][c]
expand_item = list(item)
for i, item in enumerate(expand_item):
expand_item[i] = encryptionKey_dict[item]
data[r][c] = int(''.join(expand_item))
out_file = open("AlienMission.json",'w')
json.dump(data, out_file)
out_file.close()
def peace_or_nuke(data, encrypt_key):
"""
This function takes a list of lists as its first parameter. The list of
lists contains either alien "(8>/--<" or thorny rose "@}>-'-,--" emoticons.
The second parameter is a dictionary that maps a character to a string
integer.
Example:
encrypt_key = {'A': '121', 'L': '050', 'I': '932',
'E': '13', 'N': '87', 'R': '11',
'O': '430', 'S': '553'}
Your task is verify if there are enough roses to give the aliens. If one
alien is left without a rose then they will nuke Earth. Unless we
nuke their mother ship first. Since we prefer peace over war you can't just
nuke the mother ship. Following the steps below before can proceed with
Mission Nuke.
- call process_data() on the data argument store it to a variable, info
- call verify_ratio() passing info as an argument.
- set a variable, flag, to True
- You need to verify if the dictionary returned from verify_ratio()
contains more aliens or flowers. If there are more flowers than aliens
print the following message:
"All missiles down, ceasefire! Mission Nuke aborted."
and set flag to False.
Otherwise print the following message:
"Nuke the Mother Ship!! BOOOOM BOOOOOOOM ... POW!!!"
- call encrypt_and_file(), pass info and encrypt_key as arguments.
- Finally, return flag.
"""
info = process_data(data)
stats = verify_ratio(info)
print(stats)
# print(stats)
flag = True
if stats["(8>/--<"] < stats["@}>----"]:
print("All missiles down, ceasefire! Mission Nuke aborted.")
flag = False
else:
print("Nuke the Mother Ship!! BOOOOM BOOOOOOOM ... POW!!!")
encrypt_and_file(info, encrypt_key)
return flag
def main():
t = make_table('index_lab11.html')
# orig = \
# [['(8>/--<', "@}>-'-,--", "@}>-'-,--", "@}>-'-,--", "@}>-'-,--", "@}>-'-,--", '(8>/--<'],
# ['(8>/--<', "@}>-'-,--", '(8>/--<', '(8>/--<', '(8>/--<', "@}>-'-,--", '(8>/--<']]
# print(verify_ratio(process_data(t)))
encrypt = {'A': '121', 'L': '050', 'I': '932', 'E': '13', 'N': '87', 'R': '11', 'O': '430', 'S': '553'}
peace_or_nuke(t, encrypt)
if __name__ == '__main__':
main() |
a65eecd4c8e3354758a741b09b49fe3525256c8d | wx1653265/my-summer | /cat.py | 195 | 3.984375 | 4 | cats=input("how many cats?")
cats=float(cats)
dogs=30
if cats<dogs:
print"more dogs than cats."
elif dogs<cats:
print"more cats than dogs."
else:
print"same number of cats and dogs."
|
948dee36334fa4111d24ca0c287ebff399ed34ef | SemieZX/myleetcode | /q110.py | 960 | 3.59375 | 4 | class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(root):
if root == None:
return 0
return max(height(root.left),height(root.right)) + 1
if root == None:
return True
return abs(height(root.left),height(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def dfsheight(root):
if root == None:
return 0
lh = dfsheight(root.left)
if (lh == -1):
return -1
rh = dfsheight(root.right)
if (rh == -1):
return -1
if abs(lh-rh) > 1:
return -1
return max(lh,rh) + 1
return dfsheight(root) != -1
|
7dc531f436fa15ea57909b1c9a25ee08ba611332 | KleinTong/Daily-Coding-Problem-Solution | /min_sum_level/main.py | 973 | 3.640625 | 4 | from binary_tree import BTree
from node import Node
def level_split(root):
def helper(node, level):
if not node:
return
if level not in level_dict:
level_dict[level] = [node]
else:
level_dict[level].append(node)
helper(node.left, level+1)
helper(node.right, level+1)
level_dict = {}
helper(root, 0)
final_result = float('inf')
level = None
for value in level_dict.values():
result = 0
for node in value:
result += node.data
if final_result > result:
final_result = result
level = value
print(final_result)
return value
if __name__ == '__main__':
tree = BTree()
node_1 = Node(50)
node_2 = Node(102)
node_3 = Node(40)
node_4 = Node(1)
tree.insert(node_1)
tree.insert(node_2)
tree.insert(node_3)
tree.insert(node_4)
tree.show()
print(level_split(tree.root))
|
cc4277de50313db57e219522193830190d42e6f1 | L3onet/AlgoritmosOrdenamiento2019 | /quicksort.py | 821 | 3.71875 | 4 | class QuickSort:
def intercambia(self, A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
def Particionar(self, A, p, r):
x = A[r]
i = p - 1
for j in range(p, r):
if (A[j] <= x):
i = i + 1
self.intercambia (A, i, j)
self.intercambia(A, i+1, r)
return i + 1
def QuickSort(self, A, p, r):
if (p < r):
q = self.Particionar(A, p, r)
#print (A[p:r])
self.QuickSort(A, p, q-1)
self.QuickSort(A, q+1, r)
return A
def ordenar(self, A):
p = 0
r = len(A) - 1
q = int((p + r) / 2)
return self.QuickSort(A, p, r)
def main():
a = [78, 67, 34, 35, 89, 56]
print (a)
b = QuickSort()
print (b.ordenar(a)) |
8bb7db942185415f2c881b1c879d9960413520f1 | pranaysathu/pythonTraining | /prime.py | 165 | 3.53125 | 4 | r = 1
while(r < 100):
r = r+1
i = 0
con = 0
while(i <= r):
i = i+1
if(r%i == 0):
con=con+1
if(con ==2):
print(r,end=" ") |
a6373872488a3865d22117a7d5e26712311b0775 | yangyuxiang1996/leetcode | /53.最大子序和.py | 1,081 | 3.5625 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-04-26 08:02:36
LastEditors: yangyuxiang
LastEditTime: 2021-07-05 23:17:38
FilePath: /leetcode/53.最大子序和.py
'''
#
# @lc app=leetcode.cn id=53 lang=python
#
# [53] 最大子序和
#
# @lc code=start
class Solution(object):
def maxSubArray0(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
maxsum = -float('inf')
sum = 0
for i in range(len(nums)):
sum = max(sum+nums[i], nums[i])
maxsum = max(maxsum, sum)
return maxsum
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
解法:动态规划
"""
dp = [0] * len(nums)
dp[0] = nums[0]
maxSum = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1]+nums[i], nums[i])
if dp[i] > maxSum:
maxSum = dp[i]
return maxSum
# @lc code=end
|
c294096eb6375db7ccb306a15563ce555cfd55d3 | dev2404/Babber_List | /kadanes.py | 293 | 3.5 | 4 | #code
def subarray(arr):
currmax = maxi = arr[0]
for i in arr[1:]:
currmax = max(currmax+i, i)
maxi = max(currmax, maxi)
return maxi
t = int(input())
for i in range(t):
size = int(input())
arr = list(map(int, input().split()))
print(subarray(arr))
|
eff1c1689f3411e6df31bf4d8c1cee219053eaab | rawnoob25/Optimization | /genBagCombinations.py | 1,144 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 25 22:53:01 2017
"""
def gen1BagCombo(L):
for i in range(2**len(L)):
out=[]
for j in range(len(L)):
if (i//(2**j))%2==1:
out.append(L[j])
yield out
def gen2BagCombo(L):
for i in range(3**len(L)):
out1, out2 = [], []
for j in range(len(L)):
if (i//(3**j))%3==1:
out1.append(L[j])
elif (i//(3**j))%3==2:
out2.append(L[j])
else:
continue
yield (out1,out2)
def testGen1BagCombo():
l=[chr(x) for x in range(97,101)]
comboGen = gen1BagCombo(l)
for i in range(16):
try:
print(comboGen.__next__())
except StopIteration as e:
print("Don't have "+str(i)+"th element")
def testGen2BagCombo():
l = [chr(x) for x in range(97,101)]
comboGen = gen2BagCombo(l)
for i in range(100):
try:
print(i, comboGen.__next__())
except StopIteration as e:
print("Don't have "+str(i)+"th element")
testGen2BagCombo()
#testGen1BagCombo()
|
c5ea220c6a17d5539cd0a75e11be05f9daa59ced | sora1441/4883-Programming-Techniques | /Assignments/A04/binary tree style 1.py | 485 | 4.09375 | 4 | from binarytree import Node
root = Node(3)
root.left = Node(6)
root.right = Node(8)
# Getting binary tree
print('Binary tree :', root)
# Getting list of nodes
print('List of nodes :', list(root))
# Getting inorder of nodes
print('Inorder of nodes :', root.inorder)
# Checking tree properties
print('Size of tree :', root.size)
print('Height of tree :', root.height)
# Get all properties at once
print('Properties of tree : \n', root.properties)
|
699aaa2417bfdf6a6895d0caacb21c5be1571d6c | sahilg50/Python_DSA | /Sorting/InsertionSortRecursion.py | 996 | 4.28125 | 4 | # Insertion Sort Using Recursion
class InsertionSort:
def __init__(self, array):
self.array = array
self.length = len(array)
def __str__(self):
return " ".join([str(item) for item in self.array])
def insertionSortRecursive(self, i=1):
# Base Case
if i == self.length:
return
key = self.array[i]
a = i-1
while(a >= 0 and key < self.array[a]):
self.array[a+1] = self.array[a]
a -= 1
self.array[a+1] = key
self.insertionSortRecursive(i=i+1)
def main():
# INtialize the array
try:
array = []
while(True):
array.append(int(input("Enter the Element: ")))
except ValueError:
print(array)
# Initialize the object and then call the recursive sort function
sort = InsertionSort(array=array)
sort.insertionSortRecursive()
print('The sorted array is :\n', sort)
if __name__ == '__main__':
main()
|
759a3f376576c86a90301fa2633afb0c3da4f6b3 | WhoisBsa/Curso-de-Python | /1 - Fundamentos/Calculadora.py | 1,000 | 3.734375 | 4 | from tkinter import *
janela = Tk()
def soma_click():
num1 = float(ed.get())
num2 = float(ed2.get())
lb["text"] = num1 + num2
def sub_click():
num1 = float(ed.get())
num2 = float(ed2.get())
lb["text"] = num1 - num2
def multi_click():
num1 = float(ed.get())
num2 = float(ed2.get())
lb["text"] = num1 * num2
def divi_click():
num1 = float(ed.get())
num2 = float(ed2.get())
lb["text"] = num1 / num2
ed = Entry(janela)
ed.place(x=50, y = 60)
ed2 = Entry(janela)
ed2.place(x=50, y=100)
bl = Button(janela, width=20, text="+", command=soma_click)
bl.place(x=180, y=60)
b2 = Button(janela, width=20, text="-", command=sub_click)
b2.place(x=180, y=100)
b3 = Button(janela, width=20, text="*", command=multi_click)
b3.place(x=180, y=140)
b4 = Button(janela, width=20, text="/", command=divi_click)
b4.place(x=180, y=180)
lb = Label(janela, text="")
lb.place(x=50, y=180)
janela.title("calculadora")
janela.geometry("400x400")
janela.mainloop() |
c3eb2b00c074ad73d6c617ea60dfd75bf7523254 | mandulaj/Python-Tests | /Python/test.py | 340 | 3.78125 | 4 | class Animal(object):
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = 2*c
def add(self,add):
self.b += add
c = Animal("ahoj",3,6)
b = Animal("AHOJ",2,8)
print (c.b)
c.add(6)
print (c.b)
class Dog(Animal):
def ADD(self):
return 4
dog = Dog("Jakub",5,6)
print (dog.a)
|
f2d55a138648d26e2dc9406674f0d47036b0eccc | lexruee/learning-python | /basics/zip.py | 143 | 4.09375 | 4 | #!/usr/bin/env python3
a, b, c = range(0, 10), range(10, 21), range(20, 31)
zipped = zip(a, b, c)
for a, b, c in zipped:
print(a, b, c)
|
3760a35e73774c2b7814b13a2900bcf5198f7671 | luciano-mendes-jr/Exercicios_Python3 | /ex070.py | 815 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 12 10:44:25 2021
@author: luciano
"""
total = totmil = menor = cont = 0
barato = ' '
while True:
produto = str(input('Nome do produto: '))
valor = float(input('Preço: R$ '))
cont += 1
total += valor
if valor > 1000:
totmil += 1
if cont == 1 or valor < menor:
menor = valor
barato = produto
resp = ' '
while resp not in 'SN':
resp = str(input('Quer continuar ? [S/N] ')).strip().upper()[0]
if resp == 'N':
break
print('{:-^40}'.format(' FIM DO PROGRAMA '))
print(f'O total da compra foi R$ {total:.2f}')
print(f'Temos {totmil} produtos que custam mais de R$ 1000.00')
print(f'O produto mais barato foi {barato} que custa R$ {menor:.2f}.')
#### final #### |
52a9a0aca34130e853048c3ddf0ce2c1239d486e | nelss95/Analisis1semestre2015 | /Tarea1/InsertionSor/InsertionSort.py | 373 | 3.953125 | 4 | __author__ = 'nelson'
def insertionSort(lista):
for i in range(1, len(lista)):
ValorActual = lista[i]
position = i
while position >0 and lista[position-1] > ValorActual:
lista[position] = lista[position-1]
position = position-1
lista[position] = ValorActual
lista = [54,26,93,17,77,31,44,55,20]
insertionSort(lista)
print(lista) |
f0785a73e11b3e04c2d28214aeeca6c74479a777 | jinseok9338/Sudoku | /sudoku_board.py | 11,084 | 3.734375 | 4 | import turtle
from random import randint, shuffle
class Board:
numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
counter = 0
def __init__(self):
self.board = [[0 for _ in range(9)] for _ in range(9)]
self.myPen = turtle.Turtle()
self.myPen.speed(0)
self.myPen.color("#000000")
self.myPen.hideturtle()
self.topLeft_x = -150
self.topLeft_y = 150
def __str__(self):
ceiling = "-------------------------\n"
line = "|{num1} {num2} {num3}|{num4} {num5} {num6}|{num7} {num8} {num9}|\n"
lines_list =[]
for a in (0,3,6):
for b in (0,3,6):
lines = line.format(num1 =self.board[a][b] ,num2 =self.board[a][b+1],num3=self.board[a][b+2],num4=self.board[a+1][b],num5=self.board[a+1][b+1],num6=self.board[a+1][b+2],num7=self.board[a+2][b],num8=self.board[a+2][b+1],num9=self.board[a+2][b+2])
lines_list.append(lines)
board = ceiling+lines_list[0]+lines_list[1]+lines_list[2]+ceiling+lines_list[3]+lines_list[4]+lines_list[5]+ceiling+lines_list[6]+lines_list[7]+lines_list[8]+ceiling
return board
def text(self,message, x, y, size):
FONT = ('Arial', size, 'normal')
self.myPen.penup()
self.myPen.goto(x, y)
self.myPen.write(message, align="left", font=FONT)
# A procedure to draw the grid on screen using Python Turtle
def drawGrid(self):
intDim = 35
for row in range(0, 10):
if (row % 3) == 0:
self.myPen.pensize(3)
else:
self.myPen.pensize(1)
self.myPen.penup()
self.myPen.goto(self.topLeft_x, self.topLeft_y - row * intDim)
self.myPen.pendown()
self.myPen.goto(self.topLeft_x + 9 * intDim, self.topLeft_y - row * intDim)
for col in range(0, 10):
if (col % 3) == 0:
self.myPen.pensize(3)
else:
self.myPen.pensize(1)
self.myPen.penup()
self.myPen.goto(self.topLeft_x + col * intDim, self.topLeft_y)
self.myPen.pendown()
self.myPen.goto(self.topLeft_x + col * intDim, self.topLeft_y - 9 * intDim)
for row in range(0, 9):
for col in range(0, 9):
if self.board[row][col] != 0:
self.text(self.board[row][col], self.topLeft_x + col * intDim + 9, self.topLeft_y - row * intDim - intDim + 8, 18)
# A function to check if the grid is full
def checkGrid(self):
for row in range(0, 9):
for col in range(0, 9):
if self.board[row][col] == 0:
return False
# We have a complete grid!
return True
def fillGrid(self):
# Find next empty cell
for i in range(0, 81):
row = i // 9 #this method is kind of clever
col = i % 9
if self.board[row][col] == 0:
shuffle(self.numberList)
for value in self.numberList:
# Check that this value has not already be used on this row
if not (value in self.board[row]):
# Check that this value has not already be used on this column
if not value in (self.board[0][col], self.board[1][col], self.board[2][col], self.board[3][col], self.board[4][col], self.board[5][col],self.board[6][col], self.board[7][col], self.board[8][col]):
# Identify which of the 9 squares we are working on
square = []
if row < 3:
if col < 3:
square = [self.board[i][0:3] for i in range(0, 3)]
elif col < 6:
square = [self.board[i][3:6] for i in range(0, 3)]
else:
square = [self.board[i][6:9] for i in range(0, 3)]
elif row < 6:
if col < 3:
square = [self.board[i][0:3] for i in range(3, 6)]
elif col < 6:
square = [self.board[i][3:6] for i in range(3, 6)]
else:
square = [self.board[i][6:9] for i in range(3, 6)]
else:
if col < 3:
square = [self.board[i][0:3] for i in range(6, 9)]
elif col < 6:
square = [self.board[i][3:6] for i in range(6, 9)]
else:
square = [self.board[i][6:9] for i in range(6, 9)]
# Check that this value has not already be used on this 3x3 square
if not value in (square[0] + square[1] + square[2]):
self.board[row][col] = value
if self.checkGrid():
return True
else:
if self.fillGrid():
return True
break
self.board[row][col] = 0
# A backtracking/recursive function to check all possible combinations of numbers until a solution is found
def solveGrid(self,grid):
# Find next empty cell
for i in range(0, 81):
row = i // 9
col = i % 9
if grid[row][col] == 0:
for value in range(1, 10):
# Check that this value has not already be used on this row
if not (value in grid[row]):
# Check that this value has not already be used on this column
if not value in (
grid[0][col], grid[1][col], grid[2][col], grid[3][col], grid[4][col], grid[5][col],
grid[6][col], grid[7][col], grid[8][col]):
# Identify which of the 9 squares we are working on
square = []
if row < 3:
if col < 3:
square = [grid[i][0:3] for i in range(0, 3)]
elif col < 6:
square = [grid[i][3:6] for i in range(0, 3)]
else:
square = [grid[i][6:9] for i in range(0, 3)]
elif row < 6:
if col < 3:
square = [grid[i][0:3] for i in range(3, 6)]
elif col < 6:
square = [grid[i][3:6] for i in range(3, 6)]
else:
square = [grid[i][6:9] for i in range(3, 6)]
else:
if col < 3:
square = [grid[i][0:3] for i in range(6, 9)]
elif col < 6:
square = [grid[i][3:6] for i in range(6, 9)]
else:
square = [grid[i][6:9] for i in range(6, 9)]
# Check that this value has not already be used on this 3x3 square
if not value in (square[0] + square[1] + square[2]):
grid[row][col] = value
if self.checkGrid():
self.counter += 1
break
else:
if self.solveGrid(self.board):
return True
break
grid[row][col] = 0
def remove_number_one_by_one(self):
# Start Removing Numbers one by one
# A higher number of attempts will end up removing more numbers from the grid
# Potentially resulting in more difficiult grids to solve!
attempts = 5
self.counter = 1
while attempts > 0:
# Select a random cell that is not already empty
row = randint(0, 8)
col = randint(0, 8)
while self.board[row][col] == 0:
row = randint(0, 8)
col = randint(0, 8)
# Remember its cell value in case we need to put it back
backup = self.board[row][col]
self.board[row][col] = 0
# Take a full copy of the grid
copyGrid = []
for r in range(0, 9):
copyGrid.append([])
for c in range(0, 9):
copyGrid[r].append(self.board[r][c])
# Count the number of solutions that this grid has (using a backtracking approach implemented in the solveGrid() function)
self.counter = 0
self.solveGrid(copyGrid)
# If the number of solution is different from 1 then we need to cancel the change by putting the value we took away back in the grid
if self.counter != 1:
self.board[row][col] = backup
# We could stop here, but we can also have another attempt with a different cell just to try to remove more numbers
attempts -= 1
def findNextCellToFill(self, i, j):
for x in range(i, 9):
for y in range(j, 9):
if self.board[x][y] == 0:
return x, y
for x in range(0, 9):
for y in range(0, 9):
if self.board[x][y] == 0:
return x, y
return -1, -1
def isValid(self, i, j, e):
rowOk = all([e != self.board[i][x] for x in range(9)])
if rowOk:
columnOk = all([e != self.board[x][j] for x in range(9)])
if columnOk:
# finding the top left x,y co-ordinates of the section containing the i,j cell
secTopX, secTopY = 3 * (i // 3), 3 * (j // 3) # floored quotient should be used here.
for x in range(secTopX, secTopX + 3):
for y in range(secTopY, secTopY + 3):
if self.board[x][y] == e:
return False
return True
return False
def solveSudoku(self, i=0, j=0):
i, j = self.findNextCellToFill( i, j)
if i == -1:
return True
for e in range(1, 10):
if self.isValid(i, j, e):
self.board[i][j] = e
if self.solveSudoku( i, j):
return True
# Undo the current cell for backtracking
self.board[i][j] = 0
return False
|
ec04637919058dc2b4675994f1d069963f18e0eb | enigmatic-cipher/basic_practice_program | /Q69) WAP to sort three integers without using conditional statements and loops.py | 261 | 3.859375 | 4 | n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
n3 = int(input("Enter third number: "))
n4 = int(input("Enter forth number: "))
n5 = int(input("Enter fifth number: "))
list = [n1, n2, n3, n4, n5]
arr = sorted(list)
print(arr)
|
12cb33d0a76f4bfbf97603afece6c20a55fe3da9 | DiOsTvE/Python | /34 - ejer34.py | 944 | 4.125 | 4 | """
Introducir dos cadenas, decir si tienen la misma cantidad de
caracteres, decir si no son iguales y cual es la más grande en
longitud
"""
def pedir_cadena():
texto = input("Introduce la cadena: ")
return texto
def cuenta_caracteres(cadena1, cadena2):
longitud1 = len(cadena1)
longitud2 = len(cadena2)
if longitud1 == longitud2:
tamanio = 0
return tamanio
else:
if longitud1 > longitud2:
tamanio = 1
return tamanio
else:
tamanio = 2
return tamanio
def solucion(tamanio):
if tamanio == 0:
print("Las cadenas son iguales.")
elif tamanio == 1:
print("Las cadenas son distintas. La cadena1 es más grande.")
elif tamanio == 2:
print("Las cadenas son distintas. La cadena2 es más grande.")
cadena1 = pedir_cadena()
cadena2 = pedir_cadena()
tamanio = cuenta_caracteres(cadena1, cadena2)
solucion(tamanio) |
e849edd9d6ecd6e932508136cc2f20e34217997e | asmakhanam54/EDM | /output.py | 252 | 3.578125 | 4 | dictOfList = {
'Boys':[72,68,70,69,74],
'Girls':[63,65,69,62,61]
}
listOfDict = []
len = len(dictOfList['Boys'])
for i in range(0, len):
listOfDict.append({'Boys': dictOfList['Boys'][i],'Girls': dictOfList['Girls'][i]})
print(listOfDict) |
39e50504afb73da995e5f49ed5ff5cda3987d322 | amoghrajesh/Coding | /extra_candies.py | 182 | 3.546875 | 4 | candies = [4,2,1,1,2]
extraCandies = 1
m = max(candies)
ans = []
for i in candies:
if i+extraCandies>=m:
ans.append(True)
else:
ans.append(False)
print(ans)
|
d0d0910fc08e7934257fd32b3ba01fe94ccaface | ArkusNavrey/ADVENTURE | /NAGGAFLAGGA.py | 1,689 | 3.84375 | 4 | from Room import Room
from inventory import Inventory
from inventory import Stick
print ' _____ __ __ __\n / ___// /__________ _____ ____/ /__ ____/ /\n \__ \/ __/ ' \
'___/ __ `/ __ \/ __ / _ \/ __ / \n ___/ / /_/ / / /_/ / / / / /_/ / __/ /_/ / \n/____/\__/_/ \__,' \
'_/_/ /_/\__,_/\___/\__,_/ \n '
House = Room('House', "You find yourself in a large Victorian home at the base of a green valley"
"Out the window to your left from where you stand inside of a small kitchen"
"You can see a large tower ominously hanging over the valley in the distance", 1)
stop = Room('Dining Room', 'You walk through the door in front of you to find'
'a beautifully set dining room', 2)
hallway = Room('hallway', 'you are in the hallway', 3)
hallway2 = Room('upstairs hallway', "You are in the upstairs hallway", 4)
bedroom = Room('bedroom', 'you are in the bedroom', 5)
bedroom2 = Room('bedroom', 'You are in the bedroom', 6)
bedroom3 = Room('bedroom', 'You are in the bedroom', 7)
living = Room('living room', 'you are in the living room', 8)
inventory = Inventory()
current_room = House
House.add_item(Stick('Stick', 'This is a quest!'))
while True:
current_room.enter_room()
command = raw_input("What do you want to do?\n")
print
if command == 'x':
break
result = current_room.process_command(command, inventory)
if isinstance(result, Room):
current_room = result
result.enter_room()
continue
elif isinstance(result, str):
print result
continue
else:
print 'Quit Action \n' |
028a0a3763cccdffe42e3b9cecebc1f3a8965c4b | MariaAndJava/PythonBoringStuff | /StopLight.py | 552 | 3.5 | 4 |
berthaVonSuttner = {'belderberg_Ampeln':'green', 'platz_Ampeln':'red'}
def switchLights(intersection):
for key in intersection.keys():
light = intersection[key]
if light == 'green':
intersection[key] = 'yellow'
elif light == 'yellow':
intersection[key] = 'red'
elif light == 'red':
intersection[key] = 'green'
assert 'red' in intersection.values(), 'Neither light is red!' + str(intersection)
print(berthaVonSuttner)
switchLights(berthaVonSuttner)
print(berthaVonSuttner)
|
54999660a6b7f518bcdefb9528f5fc0b12b25b58 | msw1535540/ml_learn | /05_The_use_of_math_libraries/01_example.py | 303 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import numpy as np
# 数据生成
# (列)reshape((-1, 1)): 1:一列,-1,算出来是多少就是多少行。
# (行)np.arange(6):在当前行数子上再加0,1,2,3,4,5(做一个广播)
a = np.arange(0, 60, 10).reshape((-1, 1)) + np.arange(6)
print(a)
|
5ad37a359ac19049a519faad582945bca70c4d6e | ophusdev/advent-of-code_2020 | /2/day_2.py | 2,363 | 3.515625 | 4 |
class DayTwo():
lines = []
valid_password = 0
valid_position = 0
def __init__(self):
self.read_list()
def read_list(self):
with open('./_data/data_2.txt') as f:
self.lines = [line.rstrip() for line in f]
def part_one(self):
for line in self.lines:
occurence_string = line.split(":")
occurence_values = occurence_string[0].split(" ")
min_value = int(occurence_values[0].split("-")[0])
max_value = int(occurence_values[0].split("-")[1])
char_to_find = occurence_values[1]
string_to_evaluate = occurence_string[1].strip()
if self.is_valid_count(string_to_evaluate, char_to_find,
min_value, max_value):
self.valid_password += 1
def is_valid_count(self, string_to_evaluate, char_to_find,
min_value, max_value):
if string_to_evaluate.count(char_to_find) >= min_value and \
string_to_evaluate.count(char_to_find) <= max_value:
return True
return False
def part_two(self):
for line in self.lines:
occurence_string = line.split(":")
occurence_values = occurence_string[0].split(" ")
position_one = int(occurence_values[0].split("-")[0])
position_two = int(occurence_values[0].split("-")[1])
char_to_find = occurence_values[1]
string_to_evaluate = occurence_string[1].strip()
if self.is_valid_position(string_to_evaluate, char_to_find,
position_one, position_two):
self.valid_position += 1
def is_valid_position(self, string_to_evaluate, char_to_find,
position_one, position_two):
only_one_occurrence = 0
if string_to_evaluate[position_one-1] == char_to_find:
only_one_occurrence += 1
if string_to_evaluate[position_two-1] == char_to_find:
only_one_occurrence += 1
return True if only_one_occurrence == 1 else False
day_two = DayTwo()
day_two.part_one()
print("Number valid password:")
print(day_two.valid_password)
print("=======================")
print("Number valid password with new policy:")
day_two.part_two()
print(day_two.valid_position)
|
561bb0fd2c100544f8bce245ef9dbb548c7c9b8b | amirtha4501/PythonExercises | /altersorting.py | 382 | 3.984375 | 4 | import itertools
a = []
n = int(input("Enter numeber of elements: "))
for i in range(0, n):
ele = int(input("Element: "))
a.append(ele)
a.sort()
b = a.copy()
b.sort(reverse=True)
# Using zip we can access multiple lists simultaneously
for (i, j) in zip(a, b):
if i == j:
print(i, end=" ")
break
if i == j+1:
break
print(j, i, end=" ") |
b8682f7ba7118640a6f67c16984dc44154ffdbc0 | jmwalls/iverplot | /iverpy/plots/base.py | 792 | 3.515625 | 4 | """
Plot interface class definition
"""
class Plot_object (object):
"""
Plot_object represents the interface class for a specific plot, e.g., a
time series that plots both depth and altitude, or rph values
plot object knows how to draw the specific plot including labels, legend,
etc.
Parameters
-----------
Notes
------
"""
def __init__ (self, uvclog, lcmlog):
self.uvclog = uvclog
self.lcmlog = lcmlog
def plot (self, ax, xmin, xmax):
ax.clear ()
if self.uvclog:
ax.plot (self.uvclog.utime, self.uvclog.dfs_depth, 'r')
else:
ax.plot ()
self.set_limits (ax, xmin, xmax)
def set_limits (self, ax, xmin, xmax):
if xmin and xmax: ax.set_xlim (xmin,xmax)
|
229520867623f5ba4a49424ac0b583dfe9bba43c | zihaoy/cis472project | /perceptron.py | 3,550 | 3.5625 | 4 | import sys
import re
from math import log
from math import exp
#Some code use the homework code provided by Daniel Lowd <lowd@cs.uoregon.edu>
MAX_ITERS = 100
# Load data from a file
def read_data(filename):
f = open(filename, 'r')
p = re.compile(',')
data = []
header = f.readline().strip()
varnames = p.split(header)
namehash = {}
for k in f.readlines():
temp = []
if filename == "test.csv":
temp += ["test"]+k.strip().split(",")
elif filename == "gender_submission.csv":
temp += k.strip().split(",") + ["1"]*8
else:
temp += k.strip().split(",")
#not include Name and Passenger ID (useless)
#add Pclass in array
array = [temp[2]]
#append sex as male = 0, female = 1
if temp[-8] == "male":
array.append(1)
else:
array.append(2)
#add age, sibsp and parch in array
l = temp[-7]
#if l != "":
# array.append(abs(float(l)-18))
#else:
# array.append(l)
array.append(l)
array.append(temp[-6])
array.append(temp[-5])
#not include ticket number(useless)
#add Fare
array.append(temp[-3])
#not include cabin since a lot of passenger not have.
#add Embarked as S = 0, C = 1, Q = 2
if temp[-1] == "S":
array.append(0)
elif temp[-1] == "C":
array.append(1)
else:
array.append(2)
if temp[1] == "0":
data.append((array,-1))
else:
data.append((array,1))
#for l in f:
# example = [int(x) for x in p.split(l.strip())]
# x = example[0:-1]
# y = example[-1]
# Each example is a tuple containing both x (vector) and y (int)
# data.append( (x,y) )
return (data, varnames)
# Learn weights using the perceptron algorithm
def train_perceptron(data):
max = 0;
# Initialize weight vector and bias
numvars = len(data[0][0])
w = [0.0] * numvars
b = 0.0
#
# YOUR CODE HERE!
#
passes = MAX_ITERS
for i in xrange(0,passes):
for (x,y) in data:
a = b
for j in xrange(0,numvars):
if x[j] != "":
a += w[j] * float(x[j])
if y * a <= 0:
for k in xrange(0,numvars):
if x[k] != "":
w[k] = w[k]+y*float(x[k])
b = b + y
if (allcorr(data,(w,b))>= len(data)):
break
return (w,b)
def allcorr(test,model):
correct = 0
for (x,y) in test:
activation = predict_perceptron( model, x )
if activation * y > 0:
correct += 1
return correct
# Compute the activation for input x.
# (NOTE: This should be a real-valued number, not simply +1/-1.)
def predict_perceptron(model, x):
(w,b) = model
#
# YOUR CODE HERE!
#
a = b
for i in xrange(len(x)):
if x[i] != "":
a += w[i]*float(x[i])
return a
# Load train and test data. Learn model. Report accuracy.
def main(argv):
# Process command line arguments.
# (You shouldn't need to change this.)
if (len(argv) != 3):
print('Usage: perceptron.py <train> <test> <gender_sub>')
sys.exit(2)
(train, varnames) = read_data(argv[0])
(test, testvarnames) = read_data(argv[1])
(gen, genvarnames) = read_data(argv[2])
model = train_perceptron(train)
print allcorr(train,model)/float(len(train))
correct = 0
for i in xrange(len(test)):
x = test[i][0]
y = gen[i][1]
activation = predict_perceptron( model, x )
if activation * y > 0:
correct += 1
print correct/float(len(test))
print model
if __name__ == "__main__":
main(sys.argv[1:])
|
f2b2ba62b5b3e412cda386df385d9db2e81f9ec5 | kareemawad2/python-For-beginners- | /Dictionary.py | 591 | 3.703125 | 4 | def main():
#student={'name':"wifi",'age':"15",'wepset':"https://www.youtube.com/",'slary':"2515.1,",'id':"1515615165"}
student=dict(name="wifi",age="15",wepset="https://www.youtube.com/",slary="6515.1",id=51515456545)
student['name']="kareem awad"
del student["id"]
print(student,type(student))
print("name= kareem awad\n")
print("age= 15\n")
print("wepset= https://www.youtube.com/\n")
print("slary= 6515.1\n")
print("id= 51515456545\n")
student.clear()
print(student,type(student))
print("kareem")
if __name__ == "__main__":main()
|
8956e4d15be3616e2fe8040a1938a8ef0c97e71d | chrisliatas/py4e_code | /py4e_ex_02_03.py | 99 | 3.828125 | 4 | hours = input("Enter Hours: ")
rate = input("Enter Rate: ")
print("Pay:",float(hours)*float(rate))
|
959e70a1dd7d1d54cfe8edebd62821dccfbb9284 | vishvapatel/Python | /pytohn GUI/login App/Loginpage.py | 1,148 | 3.53125 | 4 | from tkinter import *
from tkinter import ttk
from tkinter import messagebox
layout = Tk()
layout.resizable(False,False)
layout.title("Login")
def BUclick():
if( (userentry.get())=="admin" and (passwentry.get())=="1234"):
messagebox.showinfo(title="Login Info",message="Welcome! to Python app")
userentry.delete(0, END)
passwentry.delete(0, END)
else:
messagebox.showinfo(title="Login Info",message="Invalid Username or Password")
username=Label(layout,text="Username").grid(row=0,column=0,padx=5,pady=5,sticky="E")
password=Label(layout,text="Password").grid(row=1,column=0,padx=5,pady=5,sticky="E")
userentry=ttk.Entry(layout,background="#000000",foreground="#00cc00")
userentry.grid(row=0,column=1,padx=2,ipadx=2)
passwentry=ttk.Entry(layout,background="#000000",foreground="#00cc00")
passwentry.grid(row=1,column=1,padx=2,ipadx=2)
passwentry.config(show="*")
check= ttk.Checkbutton(layout,text="Keep me logged in")
check.grid(row=2,column=1,padx=2,pady=2,sticky="ew")
loginbut=ttk.Button(layout,text="Login",command=BUclick)
loginbut.grid(row=3,column=1)
layout.mainloop()
|
caa34864905e6f2e9384faeda4c3a3c8cd8f10c3 | jinlxz/CommandArgsParser | /cmd_arg_parser.py | 3,559 | 3.6875 | 4 | import sys
class cmd_arg_parser(object):
def __init__(self,cmd_args):
self.index=1
"""dictionary to store all command line arguments after parsing the command line successfully.
the dictionary stores switch-styled options, key-value pair options, list of positional arguments.
you can refer to all the command line options by referring to this variable as follows:
cmd_arg_parser.real_cmd_options[option1]
cmd_arg_parser.real_cmd_options[option2]
cmd_arg_parser.real_cmd_options["position_arg_list"]
the option1,option2 keys are defined by devepers in self.cmd_args_list, refer to self.cmd_args_list for more information.
the value for position_arg_list key is a list of all positional arguments.
switch-styled options have the value True or False
"""
self.real_cmd_options={}
#the original list of command line arguments.
self.cmd_args_list=cmd_args
"""dictionary to represent all valid command line options, developer can add user-defined options here to add the options to the application.
adding a switch-styled option refer to the following format.
<option_name_cmd>:(self.process_bool_option,"<option_name_internal>")
adding a option of key-value pair refer to the following format.
<option_name_cmd>:(self.process_keyvalue_option,"<option_name_internal>")
option_name_cmd is the name of the option used in command line, type string.
option_name_internal is the name of the option as a key to stored in the self.real_cmd_options dictionary, type string.
"""
self.cmd_args_map={
"--help":(self.display_help,"help"),
"-h":(self.display_help,"help"),
"--version":(self.display_version,"version"),
"-ver":(self.display_version,"version"),
"--openfile":(self.process_keyvalue_option,"openfile"),
"--enable-smp":(self.process_bool_option,"enable-smp"),
"--":(self.process_option_separator,"separator")
}
def get_cmd_function(self,arg):
if self.cmd_args_map.get(arg) is not None:
return self.cmd_args_map.get(arg)
else:
if arg.startswith("-"):
print "invalid option {0}".format(arg)
return (self.display_help,"help")
else:
return (self.get_position_arg_list,"position_arg_list")
def process_bool_option(self,name):
self.real_cmd_options[name]=True;
self.index+=1
def process_keyvalue_option(self,name):
self.index+=1
self.real_cmd_options[name]=self.cmd_args_list[self.index]
self.index+=1
def display_help(self,name):
print "help information"
sys.exit(0)
def display_version(self,name):
print "version 1.0"
sys.exit(0)
def get_position_arg_list(self,name):
self.real_cmd_options[name]=self.cmd_args_list[self.index:]
self.index=len(self.cmd_args_list)
def process_option_separator(self,name):
self.index+=1
self.get_position_arg_list(name)
def parse_cmd_args(self):
while self.index<len(self.cmd_args_list):
p_arg = self.cmd_args_list[self.index]
arg_process_func,arg_name=self.get_cmd_function(p_arg)
arg_process_func(arg_name)
if __name__=="__main__":
cmd_parser=cmd_arg_parser(sys.argv)
cmd_parser.parse_cmd_args()
print cmd_parser.real_cmd_options |
9875adbc48cbacdcb17d3971db3a65f9e374e43f | vaish28/Python-Programming | /JOC-Python/numpy_2-d.py | 398 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 3 07:18:11 2021
@author: User
"""
'''
List slicing
'''
import numpy as np
array = np.zeros([2,4,3],dtype=np.uint8)
print('Original array is: \n ',array, '\n')
array[:,:2] = [5,5,5]
print('After filling array by 5 array is : \n ',array,'\n')
array[:,2:] = [1,1,1]
print('After filling array by 1 array is : \n ',array,'\n')
|
0b6957524d1212085a50ef2b5ef628636820d6ce | sameen964/python | /quadrant.py | 451 | 4.21875 | 4 | """
wap to get x and y coordinates from the user and print which quadrant it is in.
"""
x = int(input("Enter x coordinate "))
y = int(input("Enter y coordinate "))
print ("(x,y) = ({0}, {1})".format(x,y))
if ((x > 0) and (y > 0)):
print ("Coordinate in Quadrant 1")
elif ((x > 0) and (y < 0)):
print ("Coordinate in Quadrant 4")
elif ((x < 0) and (y > 0)):
print ("Coordinate in Quadrant 2")
else:
print ("Coordinate in Quadrant 3") |
db66a5a2ac714441f0bca4913e4e9422763af4ab | sssvip/LeetCode | /python/num485.py | 1,092 | 3.859375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: David
@contact: tangwei@newrank.cn
@file: num485.py
@time: 2017/11/10 10:41
@description:
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
"""
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
>>> print Solution().findMaxConsecutiveOnes([1,1,0,1,1,1])
3
"""
max_sum = 0
temp_sum = 0
for x in nums:
if x == 0:
max_sum = max(max_sum, temp_sum)
temp_sum = 0
else:
temp_sum += 1
return max(max_sum, temp_sum)
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
|
8101eafb4e1a296d814255993c74072d1cf7f7d5 | vasilikikrem/pythonToSubmit | /ask7.py | 428 | 3.8125 | 4 | print "dwste tis lexeis xwrismenes me keno"
# oles oi lexeis mazi
words = raw_input()
seperated = words.split(" ") # array kai se ka8e cell mia lexh ths eisodou
maxLen = len(seperated[0]) # max len to mhkos ths prwths lexhs
longestWord = ""
for i in range (len(seperated)):
if maxLen <= len(seperated[i]): # an einai to maxlen <= ths current lexis
longestWord = seperated[i]
maxLen = len(longestWord)
print longestWord
|
808ffaa12922572f7312deaa29bb7d3af0325c71 | edabrito7/sudoku-solver | /Soduku_solver.py | 1,786 | 3.6875 | 4 | # Sudoku solver
sudoku = [
[0,6,3,0,8,0,4,0,0],
[0,9,0,0,0,4,0,0,7],
[4,0,0,0,2,0,0,0,0],
[0,0,7,2,0,3,0,5,8],
[0,5,0,0,4,0,0,0,0],
[0,0,8,0,0,0,2,0,4],
[6,0,0,0,0,0,7,0,0],
[0,0,5,0,3,6,0,0,0],
[0,3,0,8,7,0,0,2,6]
]
def regla_1(sudoku,fila, num):
#Chequea numeros por fila
if num in sudoku[fila]:
return False
return True
def regla_2(sudoku,fila,columna,num):
#Chequea numeros por columna
for numero in range(len(sudoku)):
if sudoku[numero][columna] == num:
return False
return True
def regla_3(sudoku,fila,columna,num):
# Chequea recuadro 3x3
box_x = fila // 3
box_y = columna // 3
for i in range(box_x*3, box_x*3 + 3):
for j in range(box_y*3, box_y*3 + 3):
if sudoku[i][j] == num and (i,j) != (fila,columna):
return False
return True
def funciona(sudoku, fila, columna):
# Chequeando condiciones
for numero in range(1,10):
condicion1 = regla_1(sudoku,fila, numero)
condicion2 = regla_2(sudoku,fila,columna,numero)
condicion3 = regla_3(sudoku,fila,columna,numero)
if condicion1==True and condicion2==True and condicion3==True:
sudoku[fila][columna] = numero
if main(sudoku):
return True
sudoku[fila][columna]= 0
return False
def vacio(sudoku):
# Chequeando si el numero esta vacio
for i in range(len(sudoku)):
for j in range(len(sudoku[0])):
if sudoku[i][j] == 0:
return (i, j) # fila, columna
return None
def main(sudoku):
esvacio = vacio(sudoku)
if not esvacio:
return True
else:
fila,columna = esvacio
if funciona(sudoku,fila,columna):
return True
return False
print("Sudoku antes de resolver: ")
for col in sudoku:
print (col)
print(" ")
main(sudoku)
print("Sudoku despues de resolver: ")
for col in sudoku:
print(col)
|
b3226581b74cf1a67e821110a869093ea1c96130 | kononeddiesto/Skillbox-work | /Module24/01_fight/main.py | 1,118 | 3.640625 | 4 | import random
class Unit:
def __init__(self, name, health):
self.name = name
self.health = health
def fight(self, enemy):
print('Атакует {}'.format(self.name))
enemy.protection()
print('У {} осталось {} здоровья. У {} осталось {} здоровья\n'.format(
self.name, self.health, enemy.name, enemy.health
))
def protection(self):
defenced = random.randint(1, 2)
if defenced == 1:
print('Противник не смог защититься!')
self.health -= 20
else:
print('Противник смог защититься.')
warrior_1 = Unit('Воин 1', 100)
warrior_2 = Unit('Воин 2', 100)
while warrior_1.health > 1 or warrior_2.health > 1:
warrior_1.fight(warrior_2)
warrior_2.fight(warrior_1)
if warrior_1.health <= 1:
print('Победу одержал Воин 2!')
break
elif warrior_2.health <= 1:
print('Победу одержал Воин 1!')
break
else:
continue |
e483415cd8e57415c7c6c0c5a88492b4d36e6a06 | nophar16-meet/MEET-YL1 | /OOP.py | 574 | 3.71875 | 4 | class Animal:
def __init__ (self,name,age,color,size):
self.name=name
self.age=age
self.color=color
self.size=size
def print_all(self):
print(self.size)
print(self.name)
print(self.age)
print(self.color)
def eat(self,food):
print("The animal "+self.name+" is eating "+food+" !")
def sleep(self,hours):
print("The animal "+self.name+" is sleeping "+str(hours)+" !")
dog=Animal("guy",15,"pink","tiny")
lion=Animal("nofar",18,"orange","big")
dog.print_all()
lion.print_all()
dog.eat("pizza")
dog.sleep(8)
lion.eat("Everthing")
lion.sleep(23)
|
32a271ec4070c5567a4e02955b9100b9d3920f0b | bologno/SimpleFastFood | /store_user_register.py | 3,083 | 3.5 | 4 | import tkinter
from store_user_login import StoreLogin
from user_class import User
from tkinter import messagebox
class StoreRegClass():
'''
This class models the Register and LOgin for store system users.
'''
def __init__(self):
pass
# self.name = ''
# self.lastName = ''
# self.phone = ''
# self.address = ''
def getProfile(self, entryList):
# this method saves Wnrey values from user to a local variable,
# After, is called a method for saving new user information on DB
#userParms = [str(entryList[0]), str(entryList[1]), int(entryList[2]), str(entryList[3])]
userParms = []
for i in entryList:
userParms.append(i.get())
userLogic = User(userParms)
userLogic.setUserDb()
profTab = tkinter.Tk()
profTab.title('User Info shuld be saved on DB')
nameLabel = tkinter.Label(profTab, text='Name '+str(userLogic.name))
nameLabel.pack()
profTab.mainloop
def showRegister(self, mainForm):
# This methos displays form, validates data security
# and sends the data to be saved on DB.
loginTab = tkinter.Toplevel(mainForm)
loginTab.after(1, lambda: loginTab.focus_force())
loginTab.title('Provide user info')
nameEntry = tkinter.Entry(loginTab) # add 'command
nameLabel = tkinter.Label(loginTab, text='Enter Name')
lastNEntry = tkinter.Entry(loginTab) # add 'command
lastNLabel = tkinter.Label(loginTab, text='Enter Last Name')
userEntry = tkinter.Entry(loginTab) # add 'command
userLabel = tkinter.Label(loginTab, text='Enter user')
pswdEntry = tkinter.Entry(loginTab) # add '
pswdLabel = tkinter.Label(loginTab, text='Enter password')
pswd2Entry = tkinter.Entry(loginTab) # add 'comman
pswd2Label = tkinter.Label(loginTab, text='Repeat password')
emailEntry = tkinter.Entry(loginTab)
emailLabel = tkinter.Label(loginTab, text='Enter email ')
listParms = [nameEntry, lastNEntry, userEntry, pswdEntry, emailEntry]
registerBtn = tkinter.Button(loginTab, text='Save ',
command=lambda: self.getProfile(listParms))
#aself.name = tkinter.Entry(registerTab, text = 'Name')#add 'command
nameEntry.pack()
nameLabel.pack()
lastNEntry.pack()
lastNLabel.pack()
userEntry.pack()
userLabel.pack()
pswdEntry.pack()
pswdLabel.pack()
pswd2Entry.pack()
pswd2Label.pack()
emailEntry.pack()
emailLabel.pack()
registerBtn.pack()
return (loginTab)
def setProfile(self, loginTab, mainForm):
# This method should validate for security and then.
# add store user name and password.
# into store user Database. And then open login menu.
messagebox.showinfo('Registered', 'Check email')
loginTab.destroy()
mainMenuForm = StoreLogin().loginForm(mainForm)
mainMenuForm.grab_set()
|
333c33030655e8bd627bdc8681c585fe17fe77f9 | BrandonTrapp88/Practice.py | /months2.py | 493 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 15 22:52:36 2021
@author: brandontrapp
"""
# a program to print the month abbreviation, giving its number:
def main():
#months is a list used as a lookup table
months = ["Jan", "Feb", "Mar", "Apr", "May","Jun","Jul","Aug","Sep"
,"Oct","Nov","Dec"]
n = int(input("Enter a month number (1-12): "))
print("The month abbreviation is", months[n-1] + ". ")
main() |
47ecdc1eb31038eaee1e697013e0b5eb0efd9275 | ftczohaib/python_Assignments | /Assignment_3/Assignment3_3.py | 596 | 3.9375 | 4 | def AcceptData():
size = int(input("Enter The Number of Elements to Accept: "));
arr = list();
print("Enter the Numbers: ")
for i in range(0,size,1):
print("Enter the ",i+1," value: ");
arr.append(int(input()));
return arr;
def GetMinimum(arr):
min = arr[0];
for i in range(1,len(arr),1):
if(min > arr[i]):
min = arr[i];
return min;
def main():
listData = AcceptData();
print("Entered Data is: ",listData);
print("Maximum Number of Entered Data is : ",GetMinimum(listData));
if __name__ == "__main__":
main(); |
7cfcad3c3365639d5b749d91c8b7881686104f23 | yg42/iptutorials | /TB_IPR/TUT.IMG.stereology/python/section_spheres.py | 2,054 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 4 09:50:35 2016
@author: Yann GAVET @ Mines Saint-Etienne
"""
import numpy as np
import numpy.matlib as ml
import matplotlib.pyplot as plt
def generatePointsOnSphere(nb_points, R):
"""
Generate points on a sphere
@param nb_points: number of points
@return n: array of size nb_points x 3
"""
n = np.random.randn(nb_points, 3)
mynorm = np.linalg.norm(n, axis=1)
n = R * n / np.transpose(ml.repmat(mynorm, 3, 1))
return n
def dot(A, B, ax=1):
""" dot product for arrays
"""
return np.sum(A.conj()*B, axis=ax)
h = plt.figure()
N = 10000000
R = 1
nBins = 1000
# first simulation method: random radius
d = R * np.random.rand(int(N))
radii = np.sqrt(R**2 - d**2)
probaSimu = np.histogram(radii, bins=nBins)
plt.plot(probaSimu[1][:-1], probaSimu[0]/N, linewidth=2)
# second simulation
# choose 3 endpoints to define a plane,
# then, compute the distance from the origin to this plane
n1 = generatePointsOnSphere(N, R)
n2 = generatePointsOnSphere(N, R)
n3 = generatePointsOnSphere(N, R)
# u and v belong to the plane
u = n2-n1
v = n3-n1
# n: normal vector to the plane
n = np.cross(u, v)
x = dot(n, n1) / np.linalg.norm(n, axis=1)
# distance from the origin to the plane:
r = np.sqrt(R**2 - x**2)
probaSimu = np.histogram(r, bins=nBins)
plt.plot(probaSimu[1][:-1], probaSimu[0]/N, linewidth=2)
# 3rd case:
# 2 endpoints on the sphere and distance between them
n1 = generatePointsOnSphere(N, R)
n2 = generatePointsOnSphere(N, R)
r = 1./2 * np.linalg.norm(n1-n2, axis=1)
probaSimu = np.histogram(r, bins=nBins)
plt.plot(probaSimu[1][:-1], probaSimu[0]/N, linewidth=2)
# analytical values
step = .05
r2 = np.arange(0, R, step)
probaReal = 1./R * r2 / np.sqrt(R**2-r2**2)
probaReal = probaReal * R / nBins # approximation of the integral
plt.scatter(r2, probaReal, 50)
# display
plt.legend(["random radius", "random plane by 3 endpoints",
"2 endpoints", "Analytical values"])
plt.title("Random chords of a sphere")
plt.show()
h.savefig("sections_sphere.pdf")
|
18de3a14d402badd31b0be2feae55894e725c3e2 | lgigek/alura | /python3/games/games.py | 233 | 3.578125 | 4 | import hangman
import guess
print("*************")
print("Choose a game")
print("*************")
print("(1) Hangman \n(2) Guess")
game = int(input("Which game: "))
if game == 1:
hangman.play()
elif game == 2:
guess.play()
|
54db042a8c6808f0f85a364e9a7adda32183a693 | bittu1990/python_code | /greedy_algo/min_non_increasing_sub_sequence.py | 1,097 | 3.84375 | 4 | """Given the array nums, obtain a subsequence of the array whose sum of
elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there
still exist multiple solutions, return the subsequence with the maximum total sum of
all its elements. A subsequence of an array can be obtained by erasing some (possibly zero)
elements from the array.
Input: nums = [4,3,10,9,8]
Output: [10,9]
Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their
elements is strictly greater than the sum of elements not included,
however, the subsequence [10,9] has the maximum total sum of its elements.
"""
nums = [4,3,10,8,9]
#nums = [4,4,7,6,7]
def minSubsequence(nums):
nums.sort()
total = sum(nums)
i = 0
currSum = 0
while i < len(nums):
currSum += nums[i]
if currSum < total - currSum:
i += 1
else:
break
print(i)
res = nums[i:]
return res[::-1]
print(minSubsequence(nums))
|
3c4a20b233860d202814087a9c658bc4d88aea54 | critian-90/python-course | /Anidamiento_estructural.py/ciclo_for.py | 656 | 3.953125 | 4 | ''' repetitiva_desde_1.py
script e python que muestre los números enteros
desde el 0 hasta el 13 usando un ciclo for
'''
print ('Programa que muestra los numeros del 0 al 13 con for')
for numero in range(14):
print (f'{numero}')
print('Fin del programa')
print('Imprima los números pares desde el 2 al 20')
print('\nMetodo 1', sep=(''))
for par in range (1, 11):
print (f'{par*2}')
print('*'*20)
print('\nmetodo 2')
for par in range(2, 21):
if par % 2 == 0:
print (f'par: {par}')
print('Fin del segundo programa')
print('*'*20)
print('\nmetodo 2')
for par in range(2, 21, 2):
print('Los números par son:' + str(par))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.