blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
ab65f0304d4408675e7ce7baac0f66415c859afc | joshyou/comp_bio | /hmm.py | 8,189 | 3.5625 | 4 | import math
import random
import re
import sys
'''
This class implements the Viterbi algorithm for finding the best state path of a
Hidden Markov Model. find_prob recursively computes the probability that
the sequence up to the given index ended in a given state. This updates the
table state_probs storing these results, which find_best_path can use to
reconstruct the best path to the end of the sequence.
'''
class HMM:
def __init__(self, sequence, states, state_matrix, output_matrix, begin_matrix):
self.sequence = sequence
self.states = states
#contains transition probabilities between each pair of states
self.state_matrix = state_matrix
#contains initial probability that the sequence will begin in any state
self.begin_matrix = begin_matrix
#contains probabilities that each output will result from each state
self.output_matrix = output_matrix
#Dynamic programming table which, for each state, stores
#the probability of the optimal state-path ending at that state
#and each index, as well as the preceding state
#Each entry in the dictionary is a list of pairs [probability, last state]
self.state_probs = {}
#this initialization makes it so the indices start at 1
for state in self.states:
self.state_probs[state] = [[0, "begin"]]
def find_best_path(self):
best_k = self.states[0]
#finds the state with the most probable path to the end of the sequence
for k in self.states:
if self.state_probs[k][-1][0] > self.state_probs[best_k][-1][0]:
best_k = k
best_path = [best_k]
#uses backpointers to reconstruct the state path
index = 1
current_state = best_k
while len(best_path) < len(self.sequence):
current_state = self.state_probs[current_state][-1 * index][1]
best_path.append(current_state)
index += 1
#reverses the state path
reversed = []
for i in range(1, len(best_path)+1):
reversed.append(best_path[-i])
return reversed
#returns probability of the best path ending at that index
def find_best_prob(self, index):
if index > len(self.sequence):
return None
if index == 0:
return 1
best_prob = -float("inf")
for state in self.states:
state_prob = self.find_prob(state, index)
if state_prob > best_prob:
best_prob = state_prob
return best_prob
#Recursively computes and returns probability of best path ending in given
#state and index. Indices start at 1, so index = 1 means looking at the first
#character in the sequence
def find_prob(self, state, index):
#if the probability of a given state and index have already been
#computed, return the stored value
if len(self.state_probs[state]) > index:
return self.state_probs[state][index][0]
best_prob = -float("inf")
out = self.prob_output(self.sequence[index-1], state)
best_k = state
#loop through states and find the most likely preceding state
for k in self.states:
#change_prob is probability k will transition to state
#for first index, look at begin_matrix since it is transitioning from
#the "begin" state to state
if index == 1:
change_prob = self.begin_matrix[state]
else:
change_prob = self.prob_state_change(k, state)
#state_prob is probability of best path ending in k and index - 1
if index < 2:
state_prob = 0
else:
state_prob = self.find_prob(k, index - 1)
#state_prob * change_prob is probability the HMM followed the most likely path
#ending at state k at index - 1 and then transitioned to state
#probabilities are logarithms so they are added instead of multiplied
if change_prob + state_prob > best_prob:
best_prob = change_prob + state_prob
best_k = k
best_prob += self.prob_output(self.sequence[index-1], state)
#update dictionary
self.state_probs[state].append([best_prob, best_k])
return best_prob
#probability that state 1 transitions to state 2
def prob_state_change(self, state1, state2):
return self.state_matrix[state1][state2]
#probability that a state produces a given output
def prob_output(self, output, state):
return self.output_matrix[state][output]
def get_state_probs(self):
return self.state_probs
def ln(n):
return math.log(n)
def find_CGI(sequence):
CPG_states = ["A+", "C+", "G+", "T+", "A-", "C-", "G-", "T-"]
CPG_begin_matrix = {"A-": ln(.2465), "C-": ln(.2465), "G-": ln(.2465), "T-": ln(.2465),
"A+": ln(.0035), "C+": ln(.0035), "G+": ln(.0035), "T+": ln(.0035)}
CPG_state_matrix = {"A+": {"A+": ln(0.176), "C+": ln(.268), "G+": ln(.417), "T+": ln(.117), "A-": ln(.0037), "C-": ln(.0056), "G-": ln(.0086), "T-": ln(.0025)},
"C+": {"A+": ln(.167), "C+":ln(.36), "G+":ln(.268), "T+":ln(.184), "A-":ln(.00354), "C-":ln(.00747), "G-":ln(.00559), "T-":ln(.00387)},
"G+": {"A+": ln(.157), "C+":ln(.332), "G+":ln(.367), "T+":ln(.112), "A-":ln(.0034), "C-":ln(.0069), "G-":ln(.0076), "T-":ln(.0026)},
"T+": {"A+": ln(.077), "C+":ln(.348), "G+":ln(.376), "T+":ln(.178), "A-":ln(.0017), "C-":ln(.0072), "G-":ln(.0078), "T-":ln(.00376)},
"A-": {"A+": ln(.00042), "C+":ln(.00033), "G+":ln(.000408), "T+":ln(.00033), "A-":ln(.299), "C-":ln(.2047), "G-":ln(.285), "T-":ln(.2097)},
"C-": {"A+": ln(.000447), "C+":ln(.00042), "G+":ln(.0002), "T+":ln(.000427), "A-":ln(.321), "C-":ln(.2975), "G-":ln(.078), "T-":ln(.301)},
"G-": {"A+": ln(.0003), "C+":ln(.00036), "G+":ln(.000417), "T+":ln(.000417), "A-":ln(.177), "C-":ln(.239), "G-":ln(.2915), "T-":ln(.2915)},
"T-": {"A+": ln(.000372), "C+":ln(.00037), "G+":ln(.000423), "T+":ln(.00033), "A-":ln(.2476), "C-":ln(.2456), "G-":ln(.2975), "T-":ln(.2077)}
}
CPG_output_matrix = {"A+": {"A":0, "C":-float("inf"), "G":-float("inf"), "T":-float("inf")},
"C+": {"A":-float("inf"), "C":0, "G":-float("inf"), "T":-float("inf")},
"G+": {"A":-float("inf"), "C":-float("inf"), "G":0, "T":-float("inf")},
"T+": {"A":-float("inf"), "C":-float("inf"), "G":-float("inf"), "T":0},
"A-": {"A":0, "C":-float("inf"), "G":-float("inf"), "T":-float("inf")},
"C-": {"A":-float("inf"), "C":0, "G":-float("inf"), "T":-float("inf")},
"G-": {"A":-float("inf"), "C":-float("inf"), "G":0, "T":-float("inf")},
"T-": {"A":-float("inf"), "C":-float("inf"), "G":-float("inf"), "T":0},
}
CPG_hmm = HMM(sequence, CPG_states, CPG_state_matrix, CPG_output_matrix, CPG_begin_matrix)
CPG_hmm.find_best_prob(len(sequence))
path = CPG_hmm.find_best_path()
#once the path is found, the start and endpoints of CG islands are located
#'+' states are in CGI islands, so search for sequences of + states
index = 0
islands = []
for k in path:
#beginning of CGI
if "+" in k and (index == 0 or "-" in path[index-1]):
new_island = [index]
islands.append(new_island)
elif "-" in k:
if index > 0 and "+" in path[index-1]:
islands[-1].append(index)
if (index == len(path) - 1) and len(islands) > 0 and len(islands[-1]) < 2:
islands[-1].append(index)
index += 1
for island in islands:
print island
if len(islands) == 0:
print "no CGIs detected"
return islands
def main():
filename = sys.argv[1]
f = open(filename, 'r')
sequence = ""
for line in f:
#removes characters that aren't A, G, C, or T
line = re.sub(r'[^ACGT]', "", line)
line = line.replace("\n", "")
sequence += line
sys.setrecursionlimit(10000)
find_CGI(sequence)
if __name__ == "__main__":
main() |
6fc969b1a196b6998b130b39631f6bb82f02a123 | srikantviswanath/Algo-Practice | /subsets/find_subsets.py | 657 | 3.78125 | 4 | import copy
def find_subsets_iterative(nums):
all_subsets = [[]]
for num in nums:
next_level = copy.deepcopy(all_subsets)
for subset in all_subsets:
subset.append(num)
next_level.append(subset)
all_subsets = next_level
return all_subsets
def find_subsets_recursive(nums):
if not nums:
return [[]]
prev_layer = find_subsets_recursive(nums[1:])
curr_layer = copy.deepcopy(prev_layer)
return curr_layer + [subset + [nums[0]] for subset in prev_layer]
if __name__ == '__main__':
print(find_subsets_iterative([1, 5, 3]))
print(find_subsets_recursive([1, 5, 3]))
|
431eb71f33427378078c1b847980b372619c76de | ksayee/programming_assignments | /python/CodingExercises/PrintLeafNodesLeftToRightBinaryTree.py | 1,759 | 3.984375 | 4 | # Sum of all elements in a binary tree
class Node(object):
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class BinaryTree(object):
def __init__(self,root):
self.root=Node(root)
def preorder(self,start,traversal):
if start!=None:
traversal=traversal+ (str(start.value)+ '-')
traversal=self.preorder(start.left,traversal)
traversal = self.preorder(start.right, traversal)
return traversal
def print_tree(self,traversal_type):
if traversal_type=='preorder':
return self.preorder(self.root,'')
elif traversal_type=='inorder':
return self.inorder(self.root,'')
elif traversal_type=='postorder':
return self.postorder(self.root,'')
def LeafNodesLefttoRight(self,start,tmp):
if start is None:
return
if start.left is None and start.right is None:
tmp.append(start.value)
self.LeafNodesLefttoRight(start.left,tmp)
self.LeafNodesLefttoRight(start.right,tmp)
def PrintLeafNodesLeftToRightBinaryTree(self):
start=self.root
tmp=[]
self.LeafNodesLefttoRight(start,tmp)
return tmp
def main():
tree1=BinaryTree(1)
tree1.root.left=Node(2)
tree1.root.right=Node(3)
tree1.root.left.left=Node(4)
tree1.root.right.left=Node(5)
tree1.root.right.left.left = Node(6)
tree1.root.right.left.right = Node(7)
tree1.root.right.right = Node(8)
tree1.root.right.right.left = Node(9)
tree1.root.right.right.right = Node(10)
print(tree1.print_tree('preorder'))
print(tree1.PrintLeafNodesLeftToRightBinaryTree())
if __name__=='__main__':
main() |
a6d1b0f41f8357652b78543f6ad0d81871b22a0d | GAYATHRIalagar/PythonProgramming | /Other Programs/greater.py | 141 | 3.984375 | 4 | x=input()
y=input()
z=input()
if(x>y and x>z):
print("x is greater")
elif(y>x and y>z):
print("y is greater")
else:
print("z is greater")
|
d55c5bff63d9d915bf765d8f9d3f640175ce1112 | alexp01/trainings | /Python/5_Advance_buily_in_functions/502_Iterator_class_example/prime_number_example_2.py | 1,394 | 4.125 | 4 |
# https://www.udemy.com/course/the-complete-python-course/learn/quiz/4902698#questions
class GenPrime:
def __init__(self, bound):
self.number = 3
self.bound = bound
def __next__(self):
if self.number < self.bound:
for y in range(2, self.number):
if self.number % y == 0:
self.number += 1
break
else:
self.number += 1
return self.number-1
var_prime = GenPrime(20)
for x in range(20):
a= next(var_prime)
if a != None:
print (a)
# trainer solution
# class PrimeGenerator:
# def __init__(self, stop):
# self.stop = stop
# self.start = 2
#
# def __next__(self):
# for n in range(self.start, self.stop): # always search from current start (inclusive) to stop (exclusive)
# for x in range(2, n):
# if n % x == 0: # not prime
# break
# else: # n is prime, because we've gone through the entire loop without having a non-prime situation
# self.start = n + 1 # next time we need to start from n + 1, otherwise we will be trapped on n
# return n # return n for this round
# raise StopIteration() # this is what tells Python we've reached the end of the generator |
7c7b86d658fb8d30f44bf793a5d41bda8bcc084f | AlvarocJesus/Exercicios_Python | /AulaTeorica/exerciciosModulos/exercicio4/verificaSenha.py | 728 | 3.640625 | 4 | # Pelo menos 8 caracteres
def tamanhoMin(senha):
if len(senha) >= 8:
return True
else:
return False
# Pelo menos uma letra maiúscula
def letraMaiuscula(senha):
maiuscula = 0
for i in range(len(senha)):
if senha[i].isupper():
maiuscula+=1
if maiuscula >= 1:
return True
else:
return False
# Pelo menos uma letra minúscula
def letraMinuscula(senha):
minuscula = 0
for i in range(len(senha)):
if senha[i].islower():
minuscula+=1
if minuscula >= 1:
return True
else:
return False
# Pelo menos um número
def umNum(senha):
num = 0
for i in range(len(senha)):
if senha[i].isdigit():
num+=1
if num >= 1:
return True
else:
return False
|
e65fe7919f53dcd5a457a96837b83dc4bf4154b4 | Cationiz3r/C4T-Summer | /Session-6 [Absent]/dictionary/listDict.py | 913 | 3.859375 | 4 |
book = {
"name": "The Deventure of The Normie",
"pubyear": "20XX",
"characters": ["Stephen", "Dan", "Zane"],
}
book["manufactor"]= "Xapploie"
book["country"]= "The Publica of Boardein"
for k, v in book.items():
print(k, "-", v)
print()
# Update List
book["characters"]= ["Anne", "Bran", "Cessi"]
# Create item in list
book["characters"].append("Dantey")
# Delete first item in list
book["characters"].pop(0)
# Print second in list
print(book["characters"][1])
print()
# Print each character
for char in book["characters"]:
print(char)
print()
# Print All
for key, value in book.items():
if key != "characters":
print(key, end="")
print(":", value)
else:
print(key, end=": ")
for index in range(len(value)):
if index < len(value) -1:
print(value[index], end=", ")
else:
print(value[index]) |
1abcf6a38374157fe012025d151a506fe32b5d6f | NewAwesome/Fundamental-algorithms | /LeetCode/80. 删除有序数组中的重复项 II/Solution.py | 1,002 | 3.6875 | 4 | from typing import List
class Solution:
# 条件:
# 1、数组 2、原地修改 ————> 双指针
# 双指针:
# slow 指向本次要放置元素的位置
# fast 向后遍历所有元素
def removeDuplicates(self, nums: List[int]) -> int:
slow = 0
for fast in range(len(nums)):
if slow < 2 or nums[fast] != nums[slow - 2]:
nums[slow] = nums[fast]
slow += 1
return slow
# 通用 删除有序数组重复项,仅保留x个相同元素
def removeDuplicatesCommon(self, nums: List[int], x) -> int:
slow = 0
for fast in range(len(nums)):
if slow < x or nums[fast] != nums[slow - x]:
nums[slow] = nums[fast]
slow += 1
return slow
print(Solution().removeDuplicates([1, 1, 1, 2, 2, 3]))
print(Solution().removeDuplicatesCommon([1, 1, 1, 2, 2, 3],1))
print(Solution().removeDuplicates([0, 0, 1, 1, 1, 1, 2, 3, 3]))
|
c9a16a1c85e1473d6737fb16f1f307e9a425e6a8 | garima0106/Python-basics | /conversation-simulator.py | 266 | 4 | 4 | from random import choice
questions =["Why is it a holiday?", "Why is it so hot?", "Why are you mad at me?"]
question=choice(questions)
answer=input(question).strip().lower()
while answer!='just because':
answer=input("why?: ").strip().lower()
print("Oh ok..")
|
b265199e5dee4234474949e3baa14a34df57cd73 | 8Gitbrix/Coding_Problems | /IIT_cs331_fall2015_mps/03/sort_algs.py | 1,303 | 4.34375 | 4 | def insertion_sort(vals):
"""Insertion sort implementation"""
for j in range(1, len(vals)):
to_insert = vals[j]
i = j - 1
while i >= 0 and vals[i] > to_insert:
vals[i+1] = vals[i]
i -= 1
vals[i+1] = to_insert
def merge(l1, l2):
"""Merges two sorted lists into a single sorted list, which is returned"""
res = []
while l1 and l2:
if l1[0] < l2[0]:
res.append(l1.pop(0))
else:
res.append(l2.pop(0))
res.extend(l1 if l1 else l2)
return res
def divide_sort(l):
"""Splits list in two, insertion sorts each half, then merges"""
c = len(l) // 2
l1 = l[:c]
l2 = l[c:]
insertion_sort(l1)
insertion_sort(l2)
return merge(l1, l2)
def merge_sort(vals):
"""Recursive mergesort implementation"""
if len(vals) <= 1:
return vals
c = len(vals) // 2
return merge(merge_sort(vals[0:c]), merge_sort(vals[c:len(vals)]))
### Add your sort algorithm(s) below! ##########################################
def selection_sort(vals):
for x in range(len(vals)-1,0,-1):
Max = 0
for y in range(1,x):
if vals[y]>vals[Max]:
Max = y
temp = vals[x]
vals[x] = vals[Max]
vals[Max] = temp
|
98bfea8df835689bcf55cb01152696d3f1edd672 | brk9009/superchargedPython | /chapter1/forLoops.py | 443 | 3.84375 | 4 | # my_lst doesn't get affected by for loop
my_lst = [10,15,25]
for thing in my_lst:
thing *= 2
#print(thing)
print("Unaffected list: " + str(my_lst))
# double each element in list
my_lst = [10,15,25]
for i in [0, 1, 2]:
my_lst[i] *= 2
print("Affected list: " + str(my_lst))
# Best way to double list
my_lst = [100, 102, 50, 25, 72]
for i in range(len(my_lst)):
my_lst[i] *= 2
print("Best way to double list: " + str(my_lst))
|
ec35ddacf8dd14315f4500c340ad9eebecfa1c42 | BJV-git/leetcode | /string/count_binary_substr.py | 732 | 3.703125 | 4 | # logic: the counting starts at 01 or 10
def count_binary_packed(s):
slen=len(s)
count=0
if slen < 2:
return 0
i=0
while i < slen-1:
if (s[i] == '0' and s[i+1]=='1') or (s[i] == '1' and s[i+1]=='0'):
count+=1
start = i-1
end = i+2
if s[i]=='0':
left, right = '0','1'
else:
left, right = '1','0'
while start>=0 and end < slen:
if not(s[start]==left and s[end]==right):
i = end-2
break
count += 1
start-=1
end+=1
i+=1
return count
print(count_binary_packed('11111110')) |
6a290dac0a2dd84f53464d15297bc289bf99fd14 | cbuffalow/BookStore | /BookStoreList.py | 6,190 | 3.84375 | 4 | def main():
import pickle
run = True
cashBalance = 1000
bookstore = titles, authors, prices = [], [], []
while run:
mainmenu = input('''What would you like to do?
A. Add Book
S. Sell Book
R. Reduce book prices across the board by 2%
I. Increase book prices across the board by 2%
V. Display inventory
P. Save current inventory
O. Open and load an inventory
Q. Quit
: ''')
if mainmenu.upper() == "A": # add book
title = input("What is the title of the book you are adding: ")
author = input("What is the book's author: ")
cost = input("What is the cost of the book: ")
if title.isalpha():
if author.isalpha():
if cost.isdigit():
if int(cost) > 0: # cost cant be non zero
if cashBalance - int(cost) >= 0: # have enough cash
cashBalance -= (int(cost) * .90) # reduce cash
if author != "":
if title != "": # add author and title to appropriate lines
titles.append(title)
authors.append(author)
prices.append((int(cost) * .90))
else:
print("The title was blank")
else:
print("Author was blank")
else:
print("Insufficient funds.")
else:
print("Cost was zero which is invalid")
else:
print("Invalid Cost")
else:
print("Invalid author")
else:
print("Invalid Title")
elif mainmenu.upper() == "S": # sell book (increases cash bal) deletes book from inv
bookToSell = input("What book would you like to sell (just press enter to return to main menu): ")
if bookToSell != "\n": # enter was not pressed
okayToSell = False # initialized boolean to fasle until all checks passed
index = None
for i in range(len(titles)):
if titles[i] == bookToSell:
index = i
okayToSell = True
break
else:
print("Book does not exist.")
if okayToSell:
# remove book from database
del authors[index]
del titles[index]
priceToAdd = prices.pop(index) # pop gives item and removes it at the same time
cashBalance = cashBalance + int(priceToAdd) # add cash from selling book
print("Sale successful!")
else:
print("Exiting to main menu...")
elif mainmenu.upper() == "R": # reduce cost by 2%
for i in range(len(prices)):
prices[i] *= .98
elif mainmenu.upper() == "I": # increase cost by 2%
for i in range(len(prices)):
prices[i] *= 1.02
elif mainmenu.upper() == "V": # displays inventory
"""
Title:
Author:
Our Cost (current cost):
Anticipated selling price (current cost X 1.1):
Anticipated profit (selling price X .10):
...
Cash Balance:
"""
for i in range(len(prices)):
tempTitle = titles[i]
tempAuthor = authors[i]
tempPrice = prices[i]
sellingPrice = tempPrice * 1.1
profit = sellingPrice * .1
print(tempTitle + " by " + tempAuthor + " at cost of us: $ " + str(format(tempPrice, '.2f')))
print("Anticipated selling price: " + str(format(sellingPrice, '.2f')))
print("Anticipated profit/revenue: " + str(format(profit, '.2f')))
print("Current cash balance: " + str(cashBalance))
elif mainmenu.upper() == "P": #pickles list and clears current inv
savename = input("What would you like to call the file you will save the inventory too: ")
pickle_out = open(savename, "wb")
titles_obj = titles
authors_obj = authors
prices_obj = prices
pickle.dump(titles_obj, pickle_out)
pickle.dump(authors_obj, pickle_out)
pickle.dump(prices_obj, pickle_out)
pickle_out.close()
del titles[:]
del authors[:]
del prices[:]
print(bookstore)
elif mainmenu.upper() == "O":
readfile = input("What is the file name you of the inventory you would like to open: ")
pickle_in = open(readfile, "rb")
titles_obj = pickle.load(pickle_in)
authors_obj = pickle.load(pickle_in)
prices_obj = pickle.load(pickle_in)
titles = titles_obj
authors = authors_obj
prices = prices_obj
elif mainmenu.upper() == "Q":
print("Exiting...")
run = False
if __name__ == '__main__':
main()
|
6f141c34a8c3696f527075633f2d667618f810d6 | slaash/scripts | /python/fp/prime.py | 546 | 3.53125 | 4 | #!/usr/bin/python
import math, sys
#def get_divisors(x):
# return filter(lambda j: x % j == 0, range(2, int(math.sqrt(x)+1)))
#def is_prime(x):
# if len(get_divisors(x)) == 0:
# if len(filter(lambda j: x % j == 0, range(2, int(math.sqrt(x)+1)))) == 0:
# return True
#def get_primes(min, max):
# return filter(is_prime, range(min, max))
#print get_primes(1, 100)
#print filter(is_prime, range(1, 100))
print filter(lambda x: len(filter(lambda j: x % j == 0, range(2, int(math.sqrt(x)+1)))) == 0, range(int(sys.argv[1]), int(sys.argv[2])))
|
b31d2e0e5f2b2de480fdf48643dba1c9509931e8 | bugagashenki666/lesson11p | /procvesses_class.py | 851 | 3.515625 | 4 | from multiprocessing import Lock, Process
import os
from time import sleep
class MyProcess(Process):
def __init__(self, begin, end, timeout, lock):
super().__init__()
self.begin = begin
self.end = end
self.timeout = timeout
self.lock = lock
def run(self):
while self.begin < self.end:
with self.lock:
print(f"Process '{os.getpid()}' : {self.begin}")
self.begin += 1
sleep(self.timeout)
if __name__ == "__main__":
lock = Lock()
t1 = MyProcess(begin=3, end=10, timeout=1, lock=lock)
t2 = MyProcess(begin=5, end=15, timeout=0.5, lock=lock)
t1.start()
t2.start()
for i in range(5):
with lock:
print(f"Process '{os.getpid()}': ", i)
sleep(0.5)
t1.join()
t2.join()
print("END")
|
47529d43606dd9d7acf5c721fed6efdf837b15d1 | evasu9582/python | /countofday.py | 228 | 3.671875 | 4 |
def countofdays(trips):
cou=[]
for i in trips:
a,b=i
count=0
for k in range(a,b+1):
count+=1
cou.append(count)
return sum(cou)
a=countofdays([[10,15],[35,45]])
print(a) |
cee8559b41b47adfdb45345e37173388d4c191b9 | knittingarch/Zelle-Practice | /Exercises/3-1.py | 363 | 4.28125 | 4 | '''
A program that calculates the volume and surface area of a sphere
by Sarah Dawson
'''
import math
def main():
print "This program will caluclate the volume and surface area of a sphere with your help!"
r = eval(raw_input("Please enter the radius of your sphere: "))
volume = 4.0/3.0 * math.pi * r**3
area = 4 * math.pi * r**2
print volume
print area
main() |
12a816ec8c784e2960a1c9837aa599f7d44f7945 | zdenek-nemec/sandbox | /binec/tools/get_longest_line.py | 721 | 3.96875 | 4 | #!/usr/bin/env python3
import argparse
DEFAULT_FILENAME = "get_longest_line.py"
def main():
parser = argparse.ArgumentParser(prog="get_longest_line")
parser.add_argument('--filename', '-f', default=DEFAULT_FILENAME)
filename = parser.parse_args().filename
with open(filename, "r") as input_file:
longest_length = 0
longest_line = ""
for line in input_file:
current_length = len(line) - 1
if current_length > longest_length:
longest_length = current_length
longest_line = line[:-1]
input_file.close()
print("Length %d, line \"%s\"" % (longest_length, longest_line))
if __name__ == "__main__":
main()
|
d589fc75b266c420a3f94939e0cfe35cc97f9ee5 | RioterTrov97/Audio-Chatbot | /Source Code/calc.py | 6,248 | 3.796875 | 4 | def calculate(q):
import main
import speaker
data_length = main.voice_data.split(" ")
length = len(data_length)
if length > 3:
opr = main.voice_data.split()[-2]
ppr = main.voice_data.split()[-4]
if opr == '+' or opr == 'plus' or ppr == 'add':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
adding = first_num + second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " plus " + str(second_num)+ " is " + str(adding) + "\n")
speaker.speech_output(str(first_num) + " plus " + str(second_num)+ " is " + str(adding))
elif opr == '-' or opr == 'minus' or ppr == 'subtract':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
subtracting = first_num - second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " minus " + str(second_num)+ " is " + str(subtracting) + "\n")
speaker.speech_output(str(first_num) + " minus " + str(second_num)+ " is " + str(subtracting))
elif opr == 'x' or ppr == 'multiply':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
multiplying = first_num * second_num
q.put(main.asis_obj.name + ": " + "Multiplication of " + str(first_num) + " and " + str(second_num)+ " is " + str(multiplying) + "\n")
speaker.speech_output("Multiplication of " + str(first_num) + " and " + str(second_num)+ " is " + str(multiplying))
elif opr == '/' or ppr == 'divide':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
dividing = first_num / second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " divided by " + str(second_num)+ " is " + str(dividing) + "\n")
speaker.speech_output(str(first_num) + " divided by " + str(second_num)+ " is " + str(dividing))
elif opr == 'power':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
powering = first_num ** second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " to the power of " + str(second_num)+ " is " + str(powering) + "\n")
speaker.speech_output(str(first_num) + " to the power of " + str(second_num)+ " is " + str(powering))
else:
q.put(main.asis_obj.name + ": " + "Sorry, I cannot understand the way you ask. For instance, you can ask 'what is 5 + 2?' Or say 'add 5 and 2'" + "\n")
speaker.speech_output("Sorry, I cannot understand the way you ask. For instance, you can ask 'what is 5 + 2?' Or say 'add 5 and 2'")
elif length == 3:
opr = main.voice_data.split()[-2]
ppr = main.voice_data.split()[-3]
if opr == '+' or opr == 'plus' or ppr == 'add':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
adding = first_num + second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " plus " + str(second_num)+ " is " + str(adding) + "\n")
speaker.speech_output(str(first_num) + " plus " + str(second_num)+ " is " + str(adding))
elif opr == '-' or opr == 'minus' or ppr == 'subtract':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
subtracting = first_num - second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " minus " + str(second_num)+ " is " + str(subtracting) + "\n")
speaker.speech_output(str(first_num) + " minus " + str(second_num)+ " is " + str(subtracting))
elif opr == 'x' or ppr == 'multiply':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
multiplying = first_num * second_num
q.put(main.asis_obj.name + ": " + "Multiplication of " + str(first_num) + " and " + str(second_num)+ " is " + str(multiplying) + "\n")
speaker.speech_output("Multiplication of " + str(first_num) + " and " + str(second_num)+ " is " + str(multiplying))
elif opr == '/' or ppr == 'divide':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
dividing = first_num / second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " divided by " + str(second_num)+ " is " + str(dividing) + "\n")
speaker.speech_output(str(first_num) + " divided by " + str(second_num)+ " is " + str(dividing))
elif opr == 'power':
first_num = int(main.voice_data.split()[-3])
second_num = int(main.voice_data.split()[-1])
powering = first_num ** second_num
q.put(main.asis_obj.name + ": " + str(first_num) + " to the power of " + str(second_num)+ " is " + str(powering) + "\n")
speaker.speech_output(str(first_num) + " to the power of " + str(second_num)+ " is " + str(powering))
else:
q.put(main.asis_obj.name + ": " + "Sorry, I cannot understand the way you ask. For instance, you can ask 'what is 5 + 2?' Or say 'add 5 and 2'" + "\n")
speaker.speech_output("Sorry, I cannot understand the way you ask. For instance, you can ask 'what is 5 + 2?' Or say 'add 5 and 2'")
else:
q.put(main.asis_obj.name + ": " + "Sorry, I cannot understand the way you ask. For instance, you can ask 'what is 5 + 2?' Or say 'add 5 and 2'" + "\n")
speaker.speech_output("Sorry, I cannot understand the way you ask. For instance, you can ask 'what is 5 + 2?' Or say 'add 5 and 2'")
|
92109a5e3f6767cc208605736f17b0771c0629f3 | sgnn7/sandbox | /fizzbuzz/fizzbuzz.py | 884 | 4 | 4 | #!/usr/bin/env python3
# Fun solution - list comprehension
# print('\n'.join(["FizzBuzz" if not (num % 3 or num % 5)
# else "Buzz" if not num % 5
# else "Fizz" if not num % 3
# else str(num) for num in range(1,101)]))
# Fun solution2 - zipping
list_range = range (1,101)
mod_3_list = ['' if num % 3 else "Fizz" for num in list_range]
mod_5_list = ['' if num % 5 else "Buzz" for num in list_range]
numbers = [str(num) if num % 3 and num % 5 else '' for num in list_range]
for items in zip(numbers, mod_3_list, mod_5_list):
print('%s%s%s' % items)
# Maintainable solution
# for index in range (1, 101):
# if index % 3 == 0 and index % 5 == 0:
# print("FizzBuzz")
# elif index % 3 == 0:
# print("Fizz")
# elif index % 5 == 0:
# print("Buzz")
# else:
# print(index)
|
98f29fc1c4d236ccef650d9a24a2f9d7afc2e5b8 | krishnx/codes | /crud_tree.py | 2,686 | 3.859375 | 4 | class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
class Tree:
def __init__(self, root):
self.root = root
def insert_node(self, data):
if not self.root:
self.root = Node(data)
else:
tmp = self.root
while tmp:
if tmp.data <= data:
if tmp.right:
tmp = tmp.right
else:
tmp.right = Node(data)
break
elif tmp.data > data:
if tmp.left:
tmp = tmp.left
else:
tmp.left = Node(data)
break
def inorder_traversal(self):
if not self.root:
return
tmp = self.root
stack = []
res = []
while True:
if tmp:
stack.append(tmp)
elif stack:
tmp = stack.pop()
res.append(tmp.data)
tmp = tmp.right
else:
break
return res
def search_node(self, data):
if not self.root:
return None
tmp = self.root
while tmp:
if tmp.data > data:
tmp = tmp.left
elif tmp.data <= data:
tmp = tmp.right
else:
return tmp
def min_key(self, node):
if not node:
return None
while node.left:
node = node.left
return node
def delete_node(self, data):
curr = self.root
parent = None
while curr and curr.data != data:
parent = curr
if curr.data < data:
curr = curr.right
else:
curr = curr.left
if not curr:
return None
if not (curr.left and curr.right):
if curr != self.root:
if parent.left == curr:
parent.left = None
else:
parent.right = None
else:
self.root = None
del curr
elif curr.left and curr.right:
successor = self.min_key(curr)
val = successor.data
self.delete_node(val)
curr.data = val
else:
child = curr.left or curr.right
if curr != self.root:
if curr == parent.left:
parent.left = child
else:
parent.right = child
else:
self.root = child
|
a978d4b39fe70c81ebd35d2160e4744d3713a2fe | andybloke/python4everyone | /Chp_3/Chp_3_ex_1_pay.py | 253 | 4.125 | 4 | hours = input("Enter hours: ")
rate = input("Enter rate: ")
hours = float(hours)
rate = float(rate)
if hours > 40.0:
extra = hours - 40
pay = (hours - extra) * rate + extra * 1.5 * rate
print("Pay:", pay)
else:
pay = hours * rate
print("Pay:", pay) |
2078a44d9b08b9ba3c8ed8c486feb78d5d0ff8dc | greenfox-zerda-lasers/t2botond | /week-03/day-1/11.py | 113 | 3.75 | 4 | k = 1521
# tell if k is dividable by 3 or 5
if k%3==0 or k%5==0:
print("True")
print(k%3)
print(k%5)
|
c09ffa3c43618e25c9c23dd3455ded95d207f6f2 | Ashutosh-gupt/HackerRankAlgorithms | /Funny String.py | 1,179 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Problem Statement
Suppose you have a string S which has length N and is indexed from 0 to N−1. String R is the reverse of the string S.
The string S is funny if the condition |Si−Si−1|=|Ri−Ri−1| is true for every i from 1 to N−1.
(Note: Given a string str, stri denotes the ascii value of the ith character (0-indexed) of str. |x| denotes the
absolute value of an integer x)
"""
__author__ = 'Danyang'
class Solution(object):
def solve(self, cipher):
"""
main solution function
:param cipher: the cipher
"""
s = cipher
r = s[::-1]
s = map(ord, list(s))
r = map(ord, list(r))
for i in xrange(1, len(s)):
if abs(s[i] - s[i - 1]) != abs(r[i] - r[i - 1]):
return "Not Funny"
return "Funny"
if __name__ == "__main__":
import sys
f = open("0.in", "r")
# f = sys.stdin
solution = Solution()
testcases = int(f.readline().strip())
for t in xrange(testcases):
# construct cipher
cipher = f.readline().strip()
# solve
s = "%s\n" % (solution.solve(cipher))
print s,
|
d1130c50efbab250fbe60c3532679e05d30b5651 | harshidkoladara/Python_Projects | /Project Modules-20200331T061028Z-001/Project Modules/demo.py | 777 | 3.71875 | 4 | from tkinter import Tk,Text,Label
from tkinter import ttk
from PIL import ImageTk,Image
t = Tk()
t.title('EVA')
t.geometry('500x300')
img1 = ImageTk.PhotoImage(Image.open('YOU.png'))
img2 = ImageTk.PhotoImage(Image.open('EVA.png'))
you_tn = Label(t,image = img1)
eva_tn = Label(t,image = img2)
you_txt = Label(t,text = 'hello how are you? this is a tkinter program for dummy content please bear with me', background = 'grey', height = 7, width = 50, wraplength = 250)
eva_txt = Label(t, background = 'grey', height = 7, width = 50)
mic_active = Label(t, text = 'Sound Not Detected!')
mic_active.grid(column = 1, row = 0)
you_tn.grid(column = 0, row = 1)
eva_tn.grid(column = 2, row = 2)
you_txt.grid(column = 1, row = 1)
eva_txt.grid(column = 1, row = 2, pady = 1)
t.mainloop() |
b43bbe0238176fd2b95a5da61dc00f0186a4e2c6 | AK-1121/code_extraction | /python/python_28698.py | 258 | 4.125 | 4 | # How can I delete the letter that occurs in the two strings using python?
def revers_e(s1, s2):
print(*[i for i in s1 if i in s2]) # Print all characters to be deleted from s1
s1 = ''.join([i for i in s1 if i not in s2]) # Delete them from s1
|
b2f3cd7eac1231bc837001bce73b3d56ce4590f9 | Jadouille/Kithub | /GithubSearch/process_files.py | 8,671 | 3.546875 | 4 | import json
import os
import yaml
import argparse
import javalang
def process_file(filepath):
"""
Process the code file and extract the parsed tree and tokens
:return the parsed tree, tokens, lines and comments
"""
with open(filepath, 'r') as f:
content = f.read()
with open(filepath, 'r') as f:
lines = f.readlines()
javatok = javalang.tokenizer.JavaTokenizer(content)
tok = javatok.tokenize()
tokens = list(tok)
comments = javatok.comments
tree = javalang.parser.Parser(tokens).parse()
return tree, tokens, lines, comments
def get_end_line_tokens(start_line, tokens, abstract):
"""
Given tokens and the starting line number of the function/class in the file
:return the ending line number of that function and all the tokens present in the function
"""
count = 0
line = -1
tlist = []
for i in range(len(tokens)):
token = tokens[i]
line = token.position[0]
if line >= start_line:
tlist.append(token.value)
if token.__class__.__name__ == 'Separator' and token.value == '{':
count += 1
if token.__class__.__name__ == 'Separator' and token.value == '}':
count -= 1
if count == 0:
return line, set(tlist)
if count < 0:
if abstract:
line = start_line
else:
print("Error in format....")
print(start_line, line)
raise ValueError
return line, set(tlist)
def get_attached_functions(comments, functions):
"""
Get the functions attached to the comments
:param comments: list of comments
:param functions: list of functions
:return: the functions attached to the comments
"""
function_track = 0
function_comments = {}
for line in comments:
for i in range(function_track, len(functions)):
if i == 0:
if line < functions[0]['start_line']:
function_comments[functions[0]['name']] = comments[line]
function_track += 1
else:
if functions[i - 1]['end_line'] < line < functions[i]['start_line']:
function_comments[functions[i]['name']] = comments[line]
function_track += 1
return function_comments
def process_tree(tree, tokens, lines):
"""
Process the tree and retrieves the functions and classes
:return
classes the list of classes retrieved
functions the list of functions retrieved
"""
interface = False
abstract = False
classes = []
functions = []
for _, node in tree:
cdict = {}
fdict = {}
if str(node) == "ClassDeclaration":
cdict["name"] = node.name
cdict["start_line"] = node.position[0]
cdict["end_line"], _ = get_end_line_tokens(node.position[0], tokens, abstract)
classes.append(cdict)
if 'abstract' in node.modifiers:
abstract = True
cdict['input_type'] = ''
cdict['modifiers'] = ''
cdict['content'] = ""
cdict['javadoc'] = ''
cdict['return_type'] = ''
if str(node) == 'InterfaceDeclaration':
if str(node) == "InterfaceDeclaration":
interface = True
if str(node) == "MethodDeclaration":
if interface:
fdict["end_line"] = node.position[0]
else:
fdict["end_line"], _ = get_end_line_tokens(node.position[0], tokens, abstract)
fdict["name"] = node.name
fdict["start_line"] = node.position[0]
if str(node) != "InterfaceDeclaration":
fdict["input_type"] = [i.type.name for i in node.parameters]
else:
fdict['input_type'] = ''
fdict["modifiers"] = [i for i in node.modifiers]
fdict["content"] = "".join(lines[fdict["start_line"] - 1:fdict["end_line"]])
"""
if node.documentation is None:
fdict["comments"] = set()
else:
fdict["comments"] = set(node.documentation.split()) ## change to list if count and order is important
"""
if str(node) == "MethodDeclaration":
if node.return_type is None:
fdict["return_type"] = "void"
else:
fdict["return_type"] = node.return_type.name
else:
fdict['return_type'] = ''
functions.append(fdict)
return classes, functions
def get_class(function, classes):
"""
Clean the data and get the class of the function
:return name the name of the class
"""
name = 'interface'
for clas in classes:
end = clas['end_line']
begin = clas['start_line']
if begin <= function['start_line'] < end:
name = clas['name']
return name
def iterate_list(liste, function_comment, metadata, classes, repo, url, complete_json, repo_id):
"""
Iterate through the list of functions and store the indexed information
:return
complete_json the function information
repo_id the id of the repository
"""
for i in range(0, len(liste)):
dic = liste[i]
# discard all empty functions
if dic['start_line'] == dic['end_line']:
continue
if dic['name'] in function_comment:
dic['javadoc'] = function_comment[dic['name']]
else:
dic['javadoc'] = ''
dic['content'] = dic['content']
dic['github_url'] = url
dic['stars'] = metadata['stars']
dic['forks'] = metadata['forks']
dic['watchers'] = metadata['watchers']
if 'input_type' in dic:
dic['variables'] = dic['input_type']
dic.pop('input_type', None)
else:
dic['variables'] = ''
if 'modifiers' not in dic:
dic['modifiers'] = ''
if 'return_type' not in dic:
dic['return_type'] = ''
dic['class_name'] = get_class(dic, classes)
dic['repo_name'] = repo
complete_json[repo_id] = dic
repo_id += 1
return complete_json, repo_id
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--code', type=str, dest="code")
args = parser.parse_args()
example_path = args.code
paths_not_found = []
paths_404 = 0
repo_id = 0
complete_json = {}
for subdir, dirs, files in os.walk(example_path):
for ymlfile in files:
if ymlfile.split('.')[-1] == 'yml' and ymlfile != 'repositories.yml':
path = os.path.join(subdir, ymlfile).replace('\\', '/').replace('\\', '/')
with open(path, 'r') as fp:
metadata = yaml.load(fp)
repo_name = path.split('/')[10] + '/' + path.split('/')[11]
print('Repository:', repo_name, 'at index', repo_id)
for file in metadata['files']:
java_file = os.path.join(subdir, file).replace('\\', '/')
try:
tree, tokens, lines, comments = process_file(java_file)
classes, functions = process_tree(tree, tokens, lines)
function_comment = get_attached_functions(comments, functions)
url = metadata['files'][file]
complete_json, repo_id = iterate_list(functions, function_comment, metadata, classes, repo_name,
url, complete_json, repo_id)
except javalang.parser.JavaSyntaxError:
print('Java syntax error, cannot parse file', file)
except FileNotFoundError:
print("File not found", file)
paths_404 += 1
paths_not_found.append(java_file)
except UnicodeDecodeError:
print('Could not decode', java_file)
except javalang.tokenizer.LexerError:
print('Could not decode', java_file)
except ValueError:
print("Submitted non working file", java_file)
with open('./records.json', 'w') as fp:
json.dump(complete_json, fp)
with open('./not_found.json', 'w') as fp:
json.dump(paths_not_found, fp)
if __name__ == '__main__':
main()
|
383f2948699888210ba5031e9b77dcf1009435cd | erjan/coding_exercises | /maximum_value_after_insertion.py | 2,075 | 3.953125 | 4 | '''
You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.
You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.
For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.
If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.
Return a string representing the maximum value of n after the insertion.
'''
If the number is greater than 0 we will iterate from index 0 if the target is greater than the current element we will add it before that.
Else if the number is less than 0 we will iterate from index 0 if target is less than the current we will replace add it there.
We will also keep a flag to check if we have placed the taget number or not if the flag was not striked in the end we will simply add the target number in the end.
class Solution:
def maxValue(self, n: str, x: int) -> str:
if int(n)>0:
ans = ""
flag = False
for i in range(len(n)):
if int(n[i])>=x:
ans += n[i]
else:
a = n[:i]
b = n[i:]
ans = a+str(x)+b
flag = True
break
if not flag:
ans += str(x)
else:
n = n[1:]
ans = ""
flag = False
for i in range(len(n)):
if int(n[i])<=x:
ans += n[i]
else:
a = n[:i]
b = n[i:]
ans = a+str(x)+b
flag = True
break
if not flag:
ans += str(x)
ans = "-"+ans
return ans
|
6257674866e32bf4412641715edd26bfe07c551d | zachfeld/data-structures-algorithms | /Assignment-1/MaxSubarray.py | 1,501 | 4.125 | 4 | # A python program for finding the largest sum in an array of values
def maxSubarray(arr):
#working set of variables and finalized set of variables
currentMax = float('-inf')
startIndex = 0
endIndex = 0
maxStart = 0
maxEnd = 0
workingMax = float('-inf')
for i in range (len(arr)):
#if the current array position is better than the next one added
#set the index to where you currently are
if(arr[i] > arr[i] + workingMax):
workingMax = arr[i]
startIndex = i
endIndex = i
else:
#append the next value to the working maximum
workingMax = workingMax + arr[i]
endIndex = i
#if max that I currently have is better than what I had before
#turn all variables to what I have now
if (workingMax > currentMax):
currentMax = workingMax
maxStart = startIndex
maxEnd = endIndex
print ("Starting index: " + str(maxStart) + " Ending index: " + str(maxEnd))
print ("The max subarray is: " + str(currentMax) + "\n")
#Test for random number input
arr = [-2, -3, 4, -1, -2, 1, 5, -3]
maxSubarray(arr)
#Test for all positive numbers
arr = [10, 12, 13, 15, 10, 40, 33]
maxSubarray(arr)
#Test for all negative numbers
arr = [-10, -12, -13, -15, -10, -40, -33]
maxSubarray(arr)
#Test for all negative numbers last number should drown them out
arr = [-10, -12, -13, -15, -10, -40, 100]
maxSubarray(arr) |
21c0d2942d3c03711ce6373d59e82013c060594e | MaxDunsmore/Prac08 | /blockBuilding.py | 480 | 3.921875 | 4 | """ CP1404 Prac 08 - Recursion"""
def main():
number_of_blocks = int(input("Please enter the number of rows: "))
pyramid_block_builder(number_of_blocks)
def pyramid_block_builder(number_of_blocks):
total_blocks = 0
if number_of_blocks == 0:
print(total_blocks)
return
if number_of_blocks != 0:
total_blocks += number_of_blocks
pyramid_block_builder(number_of_blocks-1)
main()
# Unsure how to add the data to a list each time,
|
63c31b426d7c5d4bea5a801cd9e67afd07bb194d | 224nth/leetcode | /apple/reverse_linked_list.py | 735 | 4 | 4 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from common.linked_list import build_linked_list_with_ListNode, ListNode
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
stack = []
while head:
stack.append(head)
head = head.next
newhead = ListNode(-1)
last = newhead
while stack:
current =stack.pop()
last.next = current
current.next = None
last = current
return newhead.next
node =build_linked_list_with_ListNode([1,2,3,4,5])
a =Solution().reverseList(node)
print('done') |
bdc856dc28bf7988bbadcfe149fa3d3906eda2f2 | SelahittinSaytas/IntroToPythonProgramming | /Sentdex/PythonFundamentals/Basics/28-ListManipulation/tut.py | 462 | 4.0625 | 4 |
x = [1,2,3,4,5,6,7,8,9,10,11]
y = ["Janet","Jessy","Kelly","Alice","Joe","Bob"]
x.append(13)
x.insert(11,12)
x.remove(x[5])
print(x)
print(x[11])
print(x[2:5]) #Slicing - to access a slice
print(x[-1]) #To access the lass element of the list
print(x.index(1)) #To find the index number of a list item
print(x.count(13)) #To find how many same elements there are
x.sort() #To sort numerically or alphabetically
print(x)
y.sort()
print(y)
y.reverse()
print(y)
|
b16627179e29d0922468169526f511e67fb160a0 | swikot/DatabaseProject | /ProjectFile.py | 6,062 | 3.875 | 4 | __author__ = 'swikot'
# delete the existing database and CSV file and run program again
import sqlite3
import csv
from datetime import date, datetime
db_connection=sqlite3.connect("FLAPPY.db",detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
db_cursor=db_connection.cursor()
print("WELCOME TO OUR COURIER SERVIECE")
try:
db_connection.execute("CREATE TABLE IF NOT EXISTS Client(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,Client_name TEXT,Phone TEXT,Email TEXT )")
db_connection.commit()
#print("table created")
except sqlite3.OperationalError:
print(" Client table not created")
try:
db_connection.execute("CREATE TABLE IF NOT EXISTS Orders(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,Client_id INTEGER NOT NULL,Product TEXT ,Weight INTEGER,date_time DATE)")
db_connection.commit()
#print("table created")
except sqlite3.OperationalError:
print("order table not created")
def mail_serviece():
pass
def Client_create():
try:
print("client details")
names=input("name:")
phone=input("phone:")
email=input("email:")
# db_connection.execute("INSERT INTO Client VALUES (?, ?, ?);",(names, phone,email))
db_connection.execute("INSERT INTO Client(Client_name,Phone,Email) VALUES (?,?,?);",(names,phone,email))
db_connection.commit()
result=db_cursor.execute("SELECT ID FROM Client WHERE Email=(?);",(email,))
for i in result:
print("Welcome to our courier company. Client Id is {{",list(i)[0] ," }}" )
print(" Client Created")
except sqlite3.OperationalError:
print("No Client Created")
menu()
def Client_list():
try:
c_list= db_cursor.execute("SELECT * FROM Client ORDER BY Client_name")
print("-----clientlist------")
print("-id--name---------phone------------email")
for i in c_list:
# print(i[0]," ",i[1]," ",i[2]," ",i[3])
print(list(i))
print("------------------------------------")
except sqlite3.OperationalError:
print("Client list not created")
menu()
def Order_create():
try:
ids=int(input("Give a Client's ID:"))
id_finding=db_cursor.execute("SELECT ID FROM Client WHERE ID=(?)",(ids,))
# print(tuple(id_finding)!=())
pk=tuple(id_finding)
if pk!=():
print(" client is in our db,give order's details")
try:
product=input("ProductName:")
weight=int(input("Weight:"))
today=date.today()
db_connection.execute("INSERT INTO Orders(Client_id,Product,Weight,date_time) VALUES (?,?,?,?);",(ids,product,weight,today))
db_connection.commit()
print("order placed")
except sqlite3.OperationalError:
print("Not placed the order")
else:
print("client is not in our db,give client's details")
try:
names=input("name:")
phone=input("phone:")
email=input("email:")
# db_connection.execute("INSERT INTO Client VALUES (?, ?, ?);",(names, phone,email))
db_connection.execute("INSERT INTO Client(ID,Client_name,Phone,Email) VALUES (?,?,?,?);",(ids,names,phone,email))
db_connection.commit()
result=db_cursor.execute("SELECT ID FROM Client WHERE Email=(?);",(email,))
for i in result:
print("Welcome to our courier company. Client Id is {{",list(i)[0] ," }}" )
print("-----now make the order---")
product=input("ProductName:")
weight=int(input("Weight:"))
today=date.today()
try:
db_connection.execute("INSERT INTO Orders(Client_id,Product,Weight,date_time) VALUES (?,?,?,?);",(ids,product,weight,today))
db_connection.commit()
print("\n \n \n order placed for missing id")
except sqlite3.OperationalError:
print("Not placed the order for missing id")
except sqlite3.OperationalError:
print("Something inside else is not good")
except sqlite3.OperationalError:
print("problems")
menu()
def Order_list():
try:
c_list= db_cursor.execute("SELECT * FROM Orders ORDER BY date_time DESC")
print("orderlist")
print("OID-CID-product-weight-date")
for i in c_list:
print(i[0]," ",i[1]," ",i[2]," ",i[3]," ",i[4])
print("-----------------------------------")
except sqlite3.OperationalError:
print("Order list not created")
menu()
def Export():
#to export as csv file
# with open("wub.csv", "wb") as write_file:
#
# for row in db_cursor.execute("SELECT * FROM Orders "):
# writeRow = " ".join([str(i) for i in row])
# write_file.write(writeRow.encode())
#
# print("File Created")
data=db_cursor.execute("SELECT * FROM Orders")
with open('output.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Id','Client_id','Product_Name','Weight','Date'])
writer.writerows(data)
print("Exported CSV file Created")
menu()
def menu():
print()
print()
print("-------Menu-------")
print("1:Client Creating")
print("2:Client List")
print("3:Order Create")
print("4:Order List")
print("5:Export Order")
print("press 1-5 for selecting an option")
print()
print()
p=int(input("Press the number:"))
if p==1:
Client_create()
elif p==2:
Client_list()
elif p==3:
Order_create()
elif p==4:
Order_list()
elif p==5:
Export()
else:
db_cursor.close()
db_connection.close()
menu()
|
3b9bb0b6d61b23c6663e8b22e1cb2a3278273871 | tonyfrancis1997/Lane_detection | /exp_01_28_lane_detection.py | 2,205 | 3.53125 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
# LOading the image
img = cv2.imread('road1.jpg')
# Converting to RBG format to display in pyplot
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Finding height and width
height = img.shape[0]
width = img.shape[1]
# defining variables for region of interest
roi_vertices = [
(0,height),
(width/2.5,height/2),
(width,height-100)
]
# Creating a mask
def roi_mask(img,vertices):
mask = np.zeros_like(img)
# channel_count = img.shape[2]
# match_mask_color = (255,)* channel_count #this is for matching the mask color
match_mask_color = 255 #this is done becaz we are passing gray scale image which has only one color so that is why we are not detecting the channel count also
cv2.fillPoly(mask,vertices,match_mask_color) # this is for filling the polygon the colours in the image and storing it in mask
masked_image = cv2.bitwise_and(img,mask)
return masked_image
# Converting to gray scale
gray_crop = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
# Canny edge detection
edge = cv2.Canny(gray_crop,100,200,apertureSize=3)
# Here we would crop the image to dimension which is only necesary for us
cropped_image = roi_mask(edge,np.array([roi_vertices],np.int32))
# Using this cropped image we would execute the lane detection algorithm using prob_hough
# adding the first two steps before region of interest mask to avoid detecting mask edges( it is from line 27 to 30)
#Finding lines using Prob_HOugh
lines = cv2.HoughLinesP(cropped_image,rho=6,theta=np.pi/60,threshold=160,lines=np.array([]),minLineLength=40,maxLineGap=25)
# Iterating through the lines
def draw_lines(img1,lines1):
img1 = np.copy(img1)
blank_img = np.zeros((img1.shape[0],img1.shape[1],3),dtype=np.uint8)
for line in lines1:
#Finding the coordinates to plot the line
for x1,y1,x2,y2 in line:
#Drawing the line
cv2.line(blank_img,(x1,y1),(x2,y2),(0,255,0),5)
img1 = cv2.addWeighted(img1,0.8,blank_img,1,0.0)
return img1
img_with_lines = draw_lines(img,lines)
plt.imshow(img_with_lines)
plt.show()
cv2.destroyAllWindows()
|
dd4cb7464a53868b9e6488a83248818a6d5eaf14 | emirarditi/IEEEPythonDersleri | /Lecture3/FirstCalculator.py | 840 | 3.859375 | 4 | while True:
deniz = input("Lütfen bir işlem girin: ")
if deniz == "-1":
print("Goodbye!!!")
break
karakterler = deniz.split(" ")
ilk_sayi = float(karakterler[0])
ikinci_sayi = float(karakterler[2])
islem = karakterler[1]
result = None
if islem == "+":
result = ilk_sayi + ikinci_sayi
elif islem == "-":
result = ilk_sayi - ikinci_sayi
elif islem in ["*", "x", "X"]:
result = ilk_sayi * ikinci_sayi
elif islem in ["**", "^"]:
result = ilk_sayi ** ikinci_sayi
elif islem == "/":
if ikinci_sayi == 0:
print("Bölmede payda 0 olamaz!")
continue
result = ilk_sayi / ikinci_sayi
else:
print("Girdiğiniz işlem hatalı, lütfen tekrar deneyiniz!")
if result is not None:
print(result) |
18cfb77c6446b34575ea92d962e26fa5e461c7f0 | ashwani8958/Python | /PyQT and SQLite/M3 - Basics of Programming in Python/program/function/5_global_vs_local_variable.py | 441 | 3.78125 | 4 | age = 7
def a():
print("Global varible 'age': ", globals()['age'])
#now modifying the GLOBAL varible 'age' INSIDE the function.
globals()['age']=27
print("Global variable 'age' modified INSIDE the function: ", globals()['age'])
#now creating a LOCAL variable, 'age' INSIDE the function.
age = 11
print("local variable 'age': ", age)
return
a()
print("Checking global variable OUTSIDE the function: ", age)
|
446114f7f8bf7a2627b3d075d8d8e1b3f33726d0 | trunghieu11/PythonAlgorithm | /Contest/CodeFights/LCM.py | 289 | 3.640625 | 4 | __author__ = 'trunghieu11'
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def LCM(n):
answer = n
for i in range(1, n + 1):
answer = answer * i / gcd(answer, i)
return answer
if __name__ == '__main__':
n = int(raw_input())
print LCM(n) |
8789bf4a1396c91a40ae8b8ba1b577ea14dc149a | AMFeoktistov/infa_2019_ivanov | /Turtle/11.py | 283 | 3.625 | 4 | import turtle
import math
turtle.shape('turtle')
turtle.rt(90)
def two_circles():
for i in range(60):
turtle.fd(step)
turtle.rt(6)
for i in range(60):
turtle.fd(step)
turtle.lt(6)
step = 5
for i in range(10):
two_circles()
step += 1 |
19839565401520cf2a2dac8b1ba04fb854215962 | 17766475597/Python | /part1.py | 1,273 | 4.34375 | 4 | #字符串
car = ['Honda','Toyota','Benz','BMW']; #列表方括号
car.insert(1,'Hyundai'); #插入元素
print(car);
car.append("append"); #追加元素
print(car);
del car[0]; #删除元素
print(car);
pop_ele = car.pop(); #弹出最后一个元素
print(car);
print(pop_ele);
pop_eler = car.pop(0); #弹出任意位置元素(下标从0开始)
print(car);
print(pop_eler);
car.remove('Benz'); #根据值删除元素
print(car);
a = len(car); #列表长度
print(a);
car.sort(reverse=True); #反向排序
print(car);
#for循环
for car_ele in car: #遍历car列表
print(car_ele);
for value in range(1,5): #打印1-5
print(value);
for value in range(0,len(car)):
print(car[value]);
digits = [1,2,3,4,5,6,7,8,9,0];
print("min = "+ str(min(digits)));
print("min = "+ str(max(digits)));
print("min = "+ str(sum(digits)));
print(digits[1:4]); #index from 1 to 4
print(digits[:4]); #index from start to 4
print(digits[4:]); #index from 3 to end
print(digits[-3:]); #Last 3
print(digits[:]) #ALL
digits_1 = digits[:]; #copy digits to digits_1xd
print(digits_1[:]); |
e29c7453fa68601fb48ff06a5a910866888901f6 | bphillab/Five_Thirty_Eight_Riddler | /Riddler_17_12_22/Riddler_classic.py | 1,054 | 3.59375 | 4 | import numpy.random as random
def __initialize_game(num_players, num_dollars):
return [num_dollars for i in range(num_players)]
def __eliminate_dead_players(players):
return [i for i in players if i > 0]
def __pass_dollars(players):
players = __eliminate_dead_players(players)
for i in range(len(players)):
players[i] = players[i] - 1
what_happens = random.choice(range(3))
if what_happens == 0:
players[(i-1)%len(players)] += 1
if what_happens == 1:
players[(i+1)%len(players)] += 1
return __eliminate_dead_players(players)
def play_a_game(num_players, num_dollars):
players = __initialize_game(num_players,num_dollars)
num_rounds = 0
while(len(players)>1):
players = __pass_dollars(players)
num_rounds+=1
return num_rounds
def simulate_mult_games(num_games, num_players, num_dollars):
num_rounds = []
for i in range(num_games):
num_rounds = num_rounds + [play_a_game(num_players, num_dollars)]
return num_rounds
|
f513399fc4a9705588a25d10044b631a6282d1a1 | mcgettin/ditOldProgramming | /yr2/sem1/euler/eu3.py | 490 | 3.671875 | 4 | #euler3: prime factors of 600,851,475,143
def isPrime(num):
for i in range(2,int(num/2)+1):
if not num%i:
return False
return True
def getNextFactor(fac,num):
for i in range(int(fac)+1,int(num/2)+1):
if (not num%i):
return i
return int(num/2)+1
num=600851475143
fac=1
while(fac<(num/2)):
fac=getNextFactor(fac,num)
print(".",fac,".")
if (isPrime(fac)): print("Prime factor of ",num,": ",fac,)
|
df9b4835f76dc671b7c6742dc531114bf56bf85f | razzaksr/SasiPython | /basics/SeriesFibo.py | 224 | 4.21875 | 4 | # Fibonacci series: 0 1 1 2 3 5 8 13 21 ,,,,,
num1=0
num2=1
print(num1,num2,end=" ")
for temp in range(2,int(input("Tell us count of fibonacci: "))):
sum = num1 + num2
num1=num2
num2=sum
print(num2,end=" ") |
1a26e81cf9d4be8f32592f62c09fddbb4aff2469 | ohentony/Aprendendo-python | /Funções em python/ex003.py | 1,234 | 4 | 4 | # Faça um programa que tenha uma função chamada contador(), que receba três
# parâmetros: início, fim e passo. Seu programa tem que realizar três contagens
# através da função criada:
# a) de 1 até 10, de 1 em 1
# b) de 10 até 0, de 2 em 2
# c) uma contagem personalizada
from time import sleep
def contador(início, fim, passo):
if passo == 0:
passo = 1
if fim < início and passo > 0:
passo *= -1
print(f'Contagem de {início} até {fim} de {passo} em {passo}:')
fim -= 1
elif fim > início and passo < 0:
passo *= -1
print(f'Contagem de {início} até {fim} de {passo} em {passo}:')
fim += 1
elif passo < 0:
print(f'Contagem de {início} até {fim} de {passo} em {passo}:')
fim -= 1
else:
print(f'Contagem de {início} até {fim} de {passo} em {passo}:')
fim += 1
for num in range(início,fim,passo):
sleep(0.5)
print(num,end=' ',flush = True)
print('FIM!')
print(50*'=')
contador(1,10,1)
print(50*'=')
contador(10,0,2)
print(50*'=')
print('Agora é a sua vez de personalizar a contagem!')
contador(int(input('Início: ')),int(input('Fim: ')),int(input('Passo: ')))
print(50*'=')
|
9fba7032b14e2da452a67c948352348fe63cab79 | StephanJon/Interpolation | /src/SeqADT.py | 2,806 | 3.984375 | 4 | ## @file SeqADT.py
# @author Stephanus Jonatan
# @date January 21, 2018
## @brief SeqT is a class that creates an empty list/sequence.
# @details SeqT has a constructor, and a few accessors and mutators.
class SeqT(object):
## @brief Initializes an empty Sequence.
def __init__(self):
self.Seq = []
## @brief add(i, v) inserts an element into a list (mutator).
# @details It either appends or inserts at a specific position in the list.
# @param i is the index of the list to which the user wants to add a value to.
# @param v is the value the user wants to add to the list.
# @return An updated list is returned.
def add(self, i, v):
# Checks if sequence is empty
if self.Seq == 0:
return self.Seq.append(v)
# Checks if index i exists
elif i >= len(self.Seq):
return self.Seq.append(v)
else:
return self.Seq.insert(i, v)
## @brief Removes an element from a list (mutator).
# @param i is the index of the element that the user wants to remove.
# @return An updated list is returned.
def rm(self, i):
return self.Seq.pop(i)
## @brief Modifies an element in a list (mutator).
# @param i is the index of the element that the user wants to modify.
# @param v is the value that the user wishes to replace the old value with.
# @return An updated list is returned.
def set(self, i, v):
# Checks if index i exists
if i >= len(self.Seq):
# prints error message when index doesn't exists
print("Index does not exists. Nothing to modify")
else:
self.Seq[i] = v
return self.Seq
## @brief Accesses an index of a list (accessor).
# @param i is the index that is being accessed.
# @return Returns the value at the index i.
def get(self, i):
# Checks if index i exists
if i >= len(self.Seq):
# prints error message when index doesn't exists
print("Index does not exists")
else:
return self.Seq[i]
## @brief Checks for the size of a list.
# @returns the the size of a list.
def size(self):
return len(self.Seq)
## @brief Finds the approximate position for a value in a sorted list (accessor).
# @details The value does not have to exist in the list, but has to be >= than the first element and <= the last element of the list.
# @param v is the value being searched for in the list.
# @return Returns the approximate index of the value v.
def indexInSeq(self, v):
for i in range(0, self.size()):
if (self.get(i) <= v) and (v <= self.get(i + 1)):
return i
|
3a802048836cd531f75a30f45370fd1aa6690336 | buhuipao/LeetCode | /2017/tree/Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py | 1,632 | 4 | 4 | # _*_ coding: utf-8 _*_
'''
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root = TreeNode(preorder[0])
mid = inorder.index(preorder[0])
# 左子树位于preorder以及inorder的区间
l = self.buildTree(preorder[1:mid+1], inorder[:mid])
# 右子树位于的区间
r = self.buildTree(preorder[mid+1:], inorder[mid+1:])
root.left, root.right = l, r
return root
class Solution1(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root = TreeNode(preorder[0])
stack = [root]
i, j = 1, 0
while i < len(preorder):
temp = None
cur = TreeNode(preorder[i])
while stack and stack[-1].val == inorder[j]:
temp = stack.pop()
j += 1
if temp:
temp.right = cur
else:
stack[-1].left = cur
stack.append(cur)
i += 1
return root
|
9d7bb54a0ec3a35509948b0c0e7bc23830207d72 | asset311/leetcode | /linked lists/merge_two_sorted_lists.py | 1,863 | 3.984375 | 4 | '''
21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
'''
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Approach 1: create a new linked list
# Time is O(m+n) where m, n are list lengths
# Space is O(m+n) since we create a new list
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
p = l1
q = l2
dummy_head = ListNode(0)
curr = dummy_head
while p or q:
if not p:
curr.next = ListNode(q.val)
q = q.next
elif not q:
curr.next = ListNode(p.val)
p = p.next
else:
if p.val < q.val:
curr.next = ListNode(p.val)
p = p.next
else:
curr.next = ListNode(q.val)
q = q.next
curr = curr.next
return dummy_head.next
# Approach 2: update one of the lists in-place - very similar logic to Approach 1, but in-place
# Time is O(m+n) where m, n are list lengths
# Space is O(1) we only created one additional node
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
# maintain an unchanging reference to node ahead of the return node.
prehead = ListNode(-1)
#prev always points to the previous node
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1 if l1 else l2
# exactly one of l1 and l2 can be non-null at this point, so connect
# the non-null list to the end of the merged list.
return prehead.next
|
22be27924e29e5c616bd06534db8680c70eb861c | wmm98/homework1 | /7章之后刷题/9章/有理数加法.py | 773 | 4.0625 | 4 | '''【问题描述】
定义有理数类,定义计算两个有理数的和的方法。程序输入两个有理数,输出它们的和。
【输入形式】
输入在一行中按照a1/b1 a2/b2的格式给出两个分数形式的有理数,其中分子和分母全是正整数。
【输出形式】
在一行中按照a/b的格式输出两个有理数的和。注意必须是该有理数的最简分数形式,若分母为1,则只输出分子。
【样例输入】
1/3 1/6
【样例输出】
1/2'''
from fractions import Fraction
class yl_shu:
# def __init__(self, x, y):
# self.x = x
# self.y = y
def sum(self, x, y):
return x + y
n, m = input().split()
n = Fraction(n)
m = Fraction(m)
result = yl_shu()
print(result.sum(n, m))
|
60d9b1aafb2cba74dca0478679f6ae9c5c860081 | chenxu0602/LeetCode | /1793.maximum-score-of-a-good-subarray.py | 1,558 | 3.65625 | 4 | #
# @lc app=leetcode id=1793 lang=python3
#
# [1793] Maximum Score of a Good Subarray
#
# https://leetcode.com/problems/maximum-score-of-a-good-subarray/description/
#
# algorithms
# Hard (46.06%)
# Likes: 220
# Dislikes: 14
# Total Accepted: 5.6K
# Total Submissions: 12.2K
# Testcase Example: '[1,4,3,7,4,5]\n3'
#
# You are given an array of integers nums (0-indexed) and an integer k.
#
# The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ...,
# nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
#
# Return the maximum possible score of a good subarray.
#
#
# Example 1:
#
#
# Input: nums = [1,4,3,7,4,5], k = 3
# Output: 15
# Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) *
# (5-1+1) = 3 * 5 = 15.
#
#
# Example 2:
#
#
# Input: nums = [5,5,4,5,4,1,1,1], k = 0
# Output: 20
# Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) *
# (4-0+1) = 4 * 5 = 20.
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^5
# 1 <= nums[i] <= 2 * 10^4
# 0 <= k < nums.length
#
#
#
# @lc code=start
class Solution:
def maximumScore(self, nums: List[int], k: int) -> int:
res = mini = nums[k]
i, j, n = k, k, len(nums)
while i > 0 or j < n - 1:
if (nums[i - 1] if i else 0) < (nums[j + 1] if j < n - 1 else 0):
j += 1
else:
i -= 1
mini = min(mini, nums[i], nums[j])
res = max(res, mini * (j - i + 1))
return res
# @lc code=end
|
af74640d6908675f7991c40401a9f4045ca4c6bb | hkpcmit/AlgThink | /proj2.py | 1,502 | 3.765625 | 4 | """Algorithm Thinking: Project 2."""
from collections import deque
import copy
def bfs_visited(ugraph, start_node):
"""Return set of nodes visited from start_node."""
visited = set([start_node])
queue = deque([start_node])
while queue:
node = queue.popleft()
for neighbor in ugraph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return visited
def cc_visited(ugraph):
"""Return list of set of connected components."""
remain = set(ugraph.keys())
conn_comp = []
while remain:
node = remain.pop()
visited = bfs_visited(ugraph, node)
conn_comp.append(visited)
remain = remain.difference(visited)
return conn_comp
def largest_cc_size(ugraph):
"""Return size of largest connected connected components."""
if not ugraph:
return 0
return max(len(cc) for cc in cc_visited(ugraph))
def remove_node_from_graph(ugraph, node):
"""Remove the given node from the graph."""
neighbors = ugraph[node]
for neighbor in neighbors:
ugraph[neighbor].remove(node)
ugraph.pop(node)
return ugraph
def compute_resilience(ugraph, attack_order):
"""Return resilience of the graph."""
graph = copy.deepcopy(ugraph)
result = [largest_cc_size(graph)]
for node in attack_order:
graph = remove_node_from_graph(graph, node)
result.append(largest_cc_size(graph))
return result
|
1e59d9d806484bc213cd02ab062d37174f07e6a1 | Samyuktha-ch/Assignment-6 | /assignment 6.py | 771 | 3.96875 | 4 | #Greatest Common Divisor
t=0
gcd=0
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
x=a
y=b
while b!=0:
t=b
b=a%b
a=t
gcd=a
print("The GCD of",x,"and",y,"is:",gcd)
#Reverse a string by input from user
def reverse(s):
str=" "
for i in s:
str=i+str
return str
s=str(input("Enter the string:"))
print("The original string is:",s)
print("The reversed string is:",reverse(s))
#Even or Odd
n=(101,45,24,27,97,5,3,61,46)
codd=0
ceven=0
for i in n:
if not i%2:
ceven=ceven+1
else:
codd=codd+1
print("Number of even numbers :",ceven)
print("Number of odd numbers :",codd)
#Numbers from 0-6 except 3 and 6
n=(0,1,2,3,4,5,6)
print(0)
for i in n:
if i%3!=0:
print(i) |
23ad38b6cb2464d076b0bd96f03b9bb7ccbdcfdd | ccc013/DataStructe-Algorithms_Study | /Python/Leetcodes/linked_list/jianzhi_offer_25_mergeTwoLists.py | 1,230 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2021/2/10 6:18 下午
@Author : luocai
@file : jianzhi_offer_25_mergeTwoLists.py
@concat : [email protected]
@site :
@software: PyCharm Community Edition
@desc :
剑指 Offer 25. 合并两个排序的链表
https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
new_head = cur = l1
l1 = l1.next
else:
new_head = cur = l2
l2 = l2.next
while l1 or l2:
if l1 is None:
cur.next = l2
return new_head
if l2 is None:
cur.next = l1
return new_head
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
return new_head
|
a92d8a5558ddd2a3e32b90745acf4ce82b4037ed | tng10/sitemap-generator | /parsers.py | 1,216 | 3.640625 | 4 | from urlparse import urlparse
from HTMLParser import HTMLParser
class URLParser(object):
def __init__(self, url):
self.url = url
self.parsed_url = urlparse(self.url)
def get_domain(self):
"""
Extracted domain from the URL (e.g berlin.de)
"""
return self.parsed_url.netloc
def get_prefix(self):
"""
Basically it will return either HTTP or HTTPS
"""
return self.parsed_url.scheme
def get_path(self):
"""
Return path from the URL (e.g /blog/post/die-welt/)
"""
return self.parsed_url.path
class AnchorHTMLParser(HTMLParser):
"""
Responsible for parsing anchor tags (<a>) and grab its attributes
On this particular case we are interested on href attribute
https://docs.python.org/2/library/htmlparser.html#HTMLParser.HTMLParser.handle_starttag
"""
tag = {'name': 'a', 'attribute': 'href'}
links = set()
def handle_starttag(self, tag, attrs):
if tag == self.tag['name']:
link = dict(attrs).get(self.tag.get('attribute'))
if link:
self.links.add(link)
def get_links(self):
return self.links
|
971b9d6d5f2c486c8a87183b2e61bfa05bc25ca3 | AbelNyc/Desktop-Database-Application | /table.py | 3,199 | 4.125 | 4 | """
The database can store book information
Title, Year ,Author , ISBN
User can :
Add a book,
View all books in the database
Search for a book,
Update a book info,
Delete a book,
Close
"""
import tkinter as tk
import storage
from tkinter import *
from tkinter import ttk
def lookup():
lst.delete(0,END)
for row in storage.view_data("MyBooks.db"):
lst.insert(END,row)
def searchup():
lst.delete(0,END)
for row in storage.search_data("MyBooks.db",title_input.get(), author_input.get(),year_input.get(),ISBN_input.get()):
lst.insert(END,row)
def add_Data():
lst.delete(0,END)
for row in storage.insert_data(title_input.get(), author_input.get(),year_input.get(),ISBN_input.get(),"MyBooks.db"):
lst.insert(END,row)
def choose_item(event): #retuns type of data
global tuplee
tuplee = lst.get(lst.curselection()[0])
#return tuplee
Title_bar.delete(0,END)
Title_bar.insert(END,tuplee[1])
year_bar.delete(0,END)
year_bar.insert(END,tuplee[3])
Author_bar.delete(0,END)
Author_bar.insert(END,tuplee[2])
ISBN_bar.delete(0,END)
ISBN_bar.insert(END,tuplee[4])
def remove():
storage.delete_data("MyBooks.db",tuplee[0])
def update_():
storage.update_data("MyBooks.db",tuplee[0],title_input.get(), author_input.get(),year_input.get(),ISBN_input.get())
screen = tk.Tk()
screen.title("Book Database")
screen.config(bg='gray')
tk.Label(screen, text="Title").grid(row=0)
tk.Label(screen, text="Year").grid(row=1)
tk.Label(screen, text = "Author").grid(row=0,column=2)
tk.Label(screen,text = "ISBN").grid(row=1,column=2)
title_input = StringVar()
Title_bar = tk.Entry(screen,text=title_input, bg = 'orange')
Title_bar.grid(row=0, column=1)
year_input = StringVar()
year_bar = tk.Entry(screen,text=year_input , bg = 'orange')
year_bar.grid(row=1, column=1)
author_input = StringVar()
Author_bar = tk.Entry(screen,text=author_input, bg = 'orange')
Author_bar.grid(row=0, column=4)
ISBN_input= StringVar()
ISBN_bar = tk.Entry(screen,text=ISBN_input, bg = 'orange')
ISBN_bar.grid(row=1, column=4)
tk.Button(screen, text = 'Add',width = 15,command = add_Data , bg = 'yellow').grid(row = 2, column = 1,sticky='n')
tk.Button(screen, text = 'Update',width = 15,command = update_, bg = 'yellow').grid(row = 3, column = 1,sticky='n')
tk.Button(screen, text = 'Delete',width = 15,command = remove, bg = 'yellow').grid(row = 4,column = 1,sticky='n')
tk.Button(screen, text = 'View',width = 15,command = lookup, bg = 'yellow').grid(row = 5, column = 1,sticky='n')
tk.Button(screen, text = 'Search',width = 15,command = searchup, bg = 'yellow').grid(row = 6, column = 1,sticky='n')
tk.Button(screen, text = 'Close',width = 15,command =screen.destroy, bg = 'yellow').grid(row = 7,column = 1,sticky='n')
lst = Listbox(screen, width = 35, height = 10, bg = 'white')
lst.grid(row = 2, column = 2, columnspan = 5,rowspan=10)
lst.bind("<<ListboxSelect>>",choose_item)
scrolll = tk.Scrollbar(screen)
scrolll.grid(row = 2, column = 7,columnspan = 1,rowspan=8)
#attach Listbox to scrollbar
lst.configure(yscrollcommand = scrolll.set)
scrolll.configure(command = lst.yview)
screen.mainloop() |
a390a8e4c203b5fa01979ee8fd3dcca586d0f9e0 | toddlerya/Core-Python-Programming-Homework | /Chapter_2/2-11.py | 1,475 | 3.9375 | 4 | #! /usr/bin/env python
#coding: utf-8
"""
带 文本菜 单 的程序 写一个 带 文本菜 单 的程序,菜 单项 如下(1)取五个数的和 (2) 取五个
数的平均 值 ....(X)退出。由用 户 做一个 选择 ,然后 执 行相 应 的功能。当用 户选择 退出 时 程序
结 束。 这 个 程序的有用之 处 在于用 户 在功能之 间 切 换 不需要一遍一遍的重新启 动 你 的脚本。
( 这
对 开 发 人 员测试 自己的程序也会大有用 处 )
"""
while True:
usr_choice = raw_input("请输入你的选项:\n (1)计算五个数字的加和\n (2)计算五个数字的平均值\n (x)退出\n")
#print usr_choice == 1,type(usr_choice),
print "你的选择:(%s)" % usr_choice
if usr_choice == 'x':
print "退出程序"
break
elif int(usr_choice) == 1:
new_list = []
new_swap = 0
new_sum = 0
for l in range(5):
new_swap = raw_input('请输入一个数:')
new_list.append(new_swap)
new_sum += long(new_list[l])
print "五个数加和结果是:", new_sum
elif int(usr_choice) == 2:
new_list = []
new_swap = 0
new_sum = 0
for l in range(5):
new_swap = raw_input('请输入一个数:')
new_list.append(new_swap)
new_sum += long(new_list[l])
avg = new_sum / len(new_list)
print "五个输入数字的平均值是:", avg
|
a5bd29992170419773ac00968c7d95e1313ab7b5 | 18965050/python-advanced | /finalgenerator/generator101.py | 238 | 3.796875 | 4 | def countdown(n):
while n > 0:
yield n
n -= 1
if __name__=='__main__':
for x in countdown(10):
print('T-minus', x)
c = countdown(3)
next(c)
next(c)
c.__next__()
# next(c)
# next(c) |
f9b8b19065cb6458f17e6f0803965775c3895d09 | JeanneBM/Python | /Owoce Programowania/R07/09. Insert_list.py | 489 | 4.25 | 4 | # Ten program pokazuje przykład użycia metody insert().
def main():
# Utworzenie listy wraz z przykładowymi imionami.
names = ['Jakub', 'Katarzyna', 'Bartosz']
# Wyświetlenie listy.
print('Lista przed wstawieniem nowego elementu:')
print(names)
# Wstawienie nowego elementu w indeksie 0.
names.insert(0, 'Janusz')
# Ponowne wyświetlenie listy.
print('Lista po wstawieniu nowego elementu:')
print(names)
# Wywołanie funkcji main().
main()
|
003e664680cd3395c78e2f4e04a8a8047cc826f4 | BelenSolorzano/UNEMI---POO | /CicloFor.py | 3,604 | 3.640625 | 4 | class For:
def __init__(self):
pass
# ciclo repetitivo de incrementos o decrementos se ejecuta por verdadero (mientras tengo valores)
def usoFor(self):
nombre = " Marcos"
datos = ["Marcos", 28 , True]
numeros = (2,5.6,4,1)
docente = {'Nombre': 'Marcos', 'Edad':28 , 'Fac': 'Faci'}
listNotas = [(40,40),(35,40),(50,45)]
listAlumnos = [{"Nombre":"Alex","Nota":80},{"Nombre":"Luci","Nota":75},{"Nombre":"Felix","Nota":95}]
#? range([inicio = 0, limite,[inc/dec = 1].Genere un rango de valores desde un valor inicial a un valor final])
#! se ejecuta desde inicio hasta el limite
# for i in range(5): # rango (0,1,2,3,4)
# print("i={}".format(i))
# for i in range(2,10): # rango (2,3,4,5,6,7,8,9)
# print("i={}".format(i))
# for i in range(4,10,2): # rango (4,6,8,)
# print("i = {}".format(i), end = " ")
# for i in range(12,3,-3): # rango (4,6,8,)
# print("i={}".format(i), end = " ")
# longitud = len (datos) #len funciona en lista, tuplas y diccionarios
# print(datos[0])
# print(datos[1])
# print(datos[2])
# for i in range(longitud-1,-1,-1):
# print("for", datos[i])
# for i , dato in enumerate(datos): #aplicables solo para lsita y tuplas
# print("for",i, dato)
#Dato Toma cada elemento de la coleccion numeros ( cadena , lista , tupla)
# for dato in numeros:
# print(dato)
# for dato in ["H","o","l","a","que","tal"]:
# print(dato)
# print("\nDcicionario de nota")
# # for clave , valor in docente,items():
# # print(clave;":", valor,end = " ")
# for docente in listAlumnos:
# for clave , valor in docente.items():
# print(clave,":", valor,end = " ")
# Sacar primedios por cada alumno
# listNotas = [(40,40),(35,40,60),(50,45,34,45,40)]
# acum = 0
# long = 0
# for notas in listNotas: #ciclos anidados
# # print(notas)
# acuParcial = 0
# for nota in notas:
# print(nota)
# long=long + 1
# acum = acum + nota
# acuParcial = acuParcial + nota
# promParcial = acuParcial /len(notas)
# print("Notas Parciales = {} Pormedio Parcial = {}".format(acuParcial,promParcial))
# prom = acum/long
# print("Total notas = {} - #Notas = {} :Promedio = {} ".format(acum,long,prom))
# listAlumnos = [{"Nombre":"Alex","Nota":80},{"Nombre":"Luci","Nota":75},{"Nombre":"Felix","Nota":95}]
# #Sacar promedio general de un grupo de alumnos
# acum = 0
# cont = 0
# for alumnos in listAlumnos:
# print(alumnos)
# cont += 1
# for i, va in alumnos.items():
# print(i," : ", va , end= " ")
# if i == "Nota": acum = acum + va
# print (acum / cont)
# palabra = " Bienvenido a mi cumpleaños"
# #presentar poor lista las vocales
# vocales = []
# for carac in palabra:
# if carac in ("a","e","i","o","u"):
# vocales.append(carac)
# print(vocales)
#segunda forma
print ([carac for carac in " Bienvenido a mi cumpleaños" if carac in ("a","e","i","o","u") ]) #comprension
bucle1 = For()
bucle1.usoFor() |
fd69d180689caf8ef8a7640ab5ed5686d99718a9 | rodrilinux/Python | /Python/_2.9-composicao.py | 430 | 3.546875 | 4 | # coding: iso-8859-1_*_
''' Uma das caractersticas mais prticas das linguagens de programao a possibilidade de pegar pequenos blocos e
combin-los numa composio. Por exemplo, ns sabemos como somar nmeros e sabemos como exibi-los; acontece
que podemos fazer as duas coisas ao mesmo tempo: '''
print(17 + 3)
a = 30
print('Estamos atribuindo o valor' , a , 'a varivel a.')
print('A varivel a vale:' , a)
|
79f204f464eecb9112af84fa59c9e3235272dcb4 | ShyamPraveenSingh/Python-Basic-Tasks | /wordDocumentCreator.py | 504 | 4.21875 | 4 | #Prpgram to create a new Word document and save the inputs in it given by the user.
#This is a third party module install it by typing 'pip install python-docx'
#import the 'python-docx'
import docx
#inputs from the user
print('Enter your name: ')
name = input()
print('Enter your age: ')
age = input()
#Opening a new document object
d = docx.Document()
#add the respective inputs in new paragraphs
d.add_paragraph(name)
d.add_paragraph(age)
#save the file
d.save('file_Location/file_name.docx')
|
e10066740fdea7f507aa65d11c409827cc037871 | rchaud03/my_Pycharm | /learn_Python3/03.8-Strings 2.py | 439 | 4.21875 | 4 | """
Strings
"""
a = "this is a string"
b = "alsoAString"
c = "im a string 2"
d = "string4"
e = "This string will contain 'apostrophes' or single quotes to distinguish from double quotes"
f = "THis string will contain \"double quotes\" preceeded by a forward slash to tell python to treat them as part of the string"
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
g = "This is a string that i \
continue on the next line"
print(g) |
1cae773196abe6a5798288078736e2f2dab9bfc5 | rashidbilgrami/piaic_studies | /binary_to_decimal.py | 702 | 4 | 4 | '''
This code is for the study purpose the code is developed by
Rashid Imran Bilgrami, If you have any concerns please email me at
[email protected] or comments on GITHUB
'''
# Print Welcome Message
print("###### Welcome to Binary to Decimal Program ####")
# Getting input from the user, \n is using for new line
# cast in to float to make sure the input is number
binary_number = list(input("Enter The Binary Number:: \n"))
result = 0
caption = ""
# call decimal to binary
for i in range(len(binary_number)):
single_digit = binary_number.pop()
caption += str(single_digit)
if int(single_digit) == 1:
result += pow(2, i)
print("Decimal Representation of", caption, "is ", result)
|
903d628315415b6e7207e5683ed53468a85c634a | Gabrielcarvfer/Introducao-a-Ciencia-da-Computacao-UnB | /aulas/aula7/palavras_alice.py | 247 | 3.5 | 4 |
file = open('alice.txt')
dictionary = {}
text = file.read()
words = text.split()
for word in words:
if word not in dictionary.keys():
dictionary[word] = 1
else:
dictionary[word] += 1
print(dictionary)
pass |
ad0936a6e1459ba0310054b2743e46dbfd7213fb | promoscow/stepik_python | /stepik_ex_4.py | 2,619 | 3.640625 | 4 | n = int(input())
games = []
teams = dict()
def fill_games():
for i in range(n):
entry = input().split(';')
game = dict()
game[entry[0]] = entry[1]
game[entry[2]] = entry[3]
games.append(game)
if not teams.__contains__(entry[0]):
teams[entry[0]] = []
teams[entry[0]].append(0)
teams[entry[0]].append(0)
teams[entry[0]].append(0)
teams[entry[0]].append(0)
teams[entry[0]].append(0)
if not teams.__contains__(entry[2]):
teams[entry[2]] = []
teams[entry[2]].append(0)
teams[entry[2]].append(0)
teams[entry[2]].append(0)
teams[entry[2]].append(0)
teams[entry[2]].append(0)
def fill_results():
for game1 in games:
counter = 0
first_team = ''
first_result = 0
second_team = ''
second_result = 0
for k, v in game1.items():
if counter == 0:
first_team = k
first_result = int(v)
counter = 1
else:
second_team = k
second_result = int(v)
counter = 0
if first_result > second_result:
left_win(first_team, second_team)
elif first_result < second_result:
left_win(second_team, first_team)
else:
draw(first_team, second_team)
increment_draw_points(first_team)
increment_draw_points(second_team)
def draw(first_team, second_team):
increment_game(first_team)
increment_game(second_team)
increment_draw(first_team)
increment_draw(second_team)
def left_win(winner, loser):
increment_game(winner)
increment_win(winner)
increment_win_points(winner)
increment_game(loser)
increment_lose(loser)
def increment_draw(second_team):
value = teams[second_team][2]
value += 1
teams[second_team][2] = value
def increment_win_points(team):
value = teams[team][4]
value += 3
teams[team][4] = value
def increment_draw_points(team):
value = teams[team][4]
value += 1
teams[team][4] = value
def increment_lose(team):
value = teams[team][3]
value += 1
teams[team][3] = value
def increment_win(team):
value = teams[team][1]
value += 1
teams[team][1] = value
def increment_game(team):
value = teams[team][0]
value += 1
teams[team][0] = value
fill_games()
fill_results()
for k, v in teams.items():
print('{}:{} {} {} {} {}'.format(k, v[0], v[1], v[2], v[3], v[4]))
|
adc727beaa7f8946f526b975d08cdec3efe85593 | ayanuchausky/TP_algo | /test_ahorcado.py | 6,637 | 3.828125 | 4 | """
Parte hecha por Agustín Esteban Conti - Etapa 1
Esta parte del codigo es la estructura principal
del juego.
"""
"""palabra_a_adivinar = "auto" #palabra usada para testear"""
def palabra_insertada_a_interrogacion(palabra_a_adivinar, letras_usadas):
# Agustín Conti: Crea una cadena de interrogaciones igual de larga que la palabra
interrogaciones=""
for caracter in palabra_a_adivinar:
if letras_usadas.count(caracter) != 0:
interrogaciones += caracter
else:
interrogaciones += "?"
return interrogaciones
def victoria(letras_usadas, palabraParaJuego):
# Agustín Conti: Si todas las letras fueron adivinadas regresa un True
ganar = False
if palabra_insertada_a_interrogacion(palabraParaJuego, letras_usadas).count("?") == 0:
ganar = True
return ganar
def contar_aciertos(letra_ingresada, palabraParaJuego):
# Agustín Conti: Suma un acierto si la letra ingresada esta en la palabra a adivinar
aciertos=0
if palabraParaJuego.count(letra_ingresada)!=0:
aciertos+=1
return aciertos
def print_interfaz(palabra_a_adivinar, aciertos, desaciertos,mensaje,letra_derrota,letras_usadas):
# Agustín Conti: Imprime la interfaz del juego
if desaciertos==0:
print(mensaje,palabra_insertada_a_interrogacion(palabra_a_adivinar,letras_usadas), "Aciertos:",aciertos , "Desaciertos:",desaciertos)
else:
print(mensaje,palabra_insertada_a_interrogacion(palabra_a_adivinar,letras_usadas), "Aciertos:",aciertos , "Desaciertos:",desaciertos,"-",letra_derrota)
def ingrese_letra(letras_usadas):
# Agustín Conti: Pide al usuario que ingrese una letra y verifica que sea apropiada
letra_ingresada=str(input("Ingrese letra: ")).casefold()
if letra_ingresada!="0" and letra_ingresada!= "fin":
while (not letra_ingresada.isalpha() or len(letra_ingresada)!=1 or letras_usadas.count(letra_ingresada) != 0):
if letras_usadas.count(letra_ingresada) != 0:
print (letra_ingresada, "ya fue ingresada")
else:
print ("Ingreso inválido")
letra_ingresada=str(input("Ingrese letra: ")).casefold()
letras_usadas.append(letra_ingresada)
return letra_ingresada
def ejecutarJuego(palabraParaJuego):
# Ejecuta el juego
letras_usadas=[]
aciertos=0
desaciertos=0
CANTIDAD_DESACIERTOS_PERDER= 8
letra_ingresada=""
letras_derrota=""
print("Palabra a adivinar:",palabra_insertada_a_interrogacion(palabraParaJuego, letras_usadas), "Aciertos:",aciertos , "Desaciertos:",desaciertos, letras_derrota)
while desaciertos < CANTIDAD_DESACIERTOS_PERDER and not victoria(letras_usadas, palabraParaJuego) and letra_ingresada != "fin" and letra_ingresada!="0":
letra_ingresada=ingrese_letra(letras_usadas)
if letra_ingresada!="fin" and letra_ingresada!="0":
if contar_aciertos(letra_ingresada, palabraParaJuego) > 0:
aciertos += contar_aciertos(letra_ingresada, palabraParaJuego)
print_interfaz(palabraParaJuego, aciertos, desaciertos, "Muy bien!!!", letras_derrota, letras_usadas)
else:
desaciertos += 1
letras_derrota += " " + letra_ingresada
print_interfaz(palabraParaJuego, aciertos, desaciertos, "Lo siento!!!", letras_derrota, letras_usadas)
if not desaciertos<CANTIDAD_DESACIERTOS_PERDER:
print("Has perdido","- La palabra era:",palabraParaJuego)
elif victoria(letras_usadas, palabraParaJuego):
print("Has ganado")
else:
print("Game over")
"""
Parte hecha por Juan Ignacio D`Angona - Etapa 2
Esta parte del codigo se encarga de clasificar
las palabras del texto dado, acorde a las condiciones
impuestas por la consigna.
"""
from texto import obtener_texto
def palabras_candidatas():
texto_a_procesar=str(obtener_texto())
texto_procesado=((texto_a_procesar.casefold()).replace(".","")).split() #Esta funcion es para separar cada palabra del texto
diccionario_palabras={}
contador_palabras_diccionario=0
for palabra in texto_procesado:
if (palabra.isalpha()) and len(palabra)>=5: #Son las condiciones para que la palabra sea aceptada
if palabra not in diccionario_palabras:
diccionario_palabras[palabra]=1
else:
diccionario_palabras[palabra]+=1
lista_palabras =sorted(diccionario_palabras.items())
for elemento in lista_palabras:
contador_palabras_diccionario+=1
print(elemento)
print("Palabras distintas en total:", contador_palabras_diccionario)
return diccionario_palabras
"""ETAPA 3"""
import random
def define_word_list(dictionary):
pre_candidatas = []
for key in dictionary:
pre_candidatas += key
return pre_candidatas
"""ver como se comporta esta funcion cuando el usuario simplementer retorna enter; toma el -1 por default correctamente?"""
def longitud_deseada():
ingresar_long = int(input("Ingrese la longitud deseada para la palabra: "))
return ingresar_long
def filtrar_palabras(lista_de_palabras,longitud):
palabras_candidatas = []
palabras_no_candidatas = 0
if(longitud == -1):
palabras_candidatas = lista_de_palabras
else:
for palabra in lista_de_palabras:
"""Creo que esta parte esta mal porque se trabaja con el input de la funcion como si fuera una lista en vez de un diccionario"""
if len(palabra) == longitud:
palabras_candidatas += [palabra]
elif len(palabra) != longitud:
palabras_no_candidatas += 1
if palabras_no_candidatas == len(lista_de_palabras):
ingresar_nueva_longitud = int(input("No hay palabras la longitud deseada en el texto. Ingrese otra longitud: "))
palabras_candidatas = filtrar_palabras(lista_de_palabras,ingresar_nueva_longitud)
return palabras_candidatas
def random_word(lista_de_candidatas):
palabra_elegida = lista_de_candidatas[random.randint(0,len(lista_de_candidatas) - 1)]
return palabra_elegida
def obtenerPalabra(diccionarioDePalabras, longitudDeseada = -1):
"""longitud = longitud_deseada()"""
"""lista_de_palabras = ["hola", "como", "estas", "estamos", "haciendo", "un", "TP"]"""
longitud = longitudDeseada
lista_de_palabras = diccionarioDePalabras
palabras_filtradas = filtrar_palabras(lista_de_palabras,longitud)
palabra_elegida = random_word(palabras_filtradas)
return palabra_elegida
def main():
palabraParaJuego = obtenerPalabra(palabras_candidatas(), longitud_deseada())
ejecutarJuego(palabraParaJuego)
main() |
cbd928cae24bbd74b46ba80f7f1bb564e9285c2c | hogitayden/nguyenhoanggiang-fundametal-c4e22 | /Session1/homework/c2f_hws1.py | 113 | 3.65625 | 4 | C = input ("Enter the temperature in Celsius? ")
F = 33.8 * float(C)
F = round(F,2)
print (C, "(C) = ", F, "(F)") |
ef7895ee1ce8f1726ee8fdf6a01fdb8434defc89 | jayske/VYA_test | /vya_luhn.py | 855 | 3.703125 | 4 | def sum_luhn(total):
if (total % 10 == 0) and (total > -1):
return "the number is valid"
else:
return "the number is invalid"
# 371612019985236
def do_luhn(lst):
sum = 0
for index in range(len(lst)):
if (index%2 != 0) and (int(lst[index]) >= 0):
x2value = int(lst[index]) * 2
if x2value > 9:
sum = sum + (x2value%10 + 1)
else:
sum = sum + x2value
elif (int(lst[index]) < 0):
return -1
else:
sum = sum + int(lst[index])
return sum
def start(input_number):
input_list = list(input_number)
input_list.reverse()
sum = do_luhn(input_list)
print(sum_luhn(sum))
if __name__ == "__main__":
input_= str(input('enter your credit card number '))
start(input_)
|
1fcbf47cf0079779779dca9485fa384d928a4531 | alexsorr-it/Gruppo11 | /Esercizio3Intracorso/due_otto_tree.py | 32,025 | 3.71875 | 4 | from collections.abc import MutableMapping
class MapBase(MutableMapping):
"""Our own abstract base class that includes a nonpublic _Item class."""
# ------------------------------- nested _Item class -------------------------------
class _Item:
"""Lightweight composite to store key-value pairs as map items."""
__slots__ = '_key', '_value', '_figlio'
def __init__(self, k, v):
self._key = k
self._value = v
self._figlio = SortedTableMap()
def __eq__(self, other):
return self._key == other._key # compare items based on their keys
def __ne__(self, other):
return not (self == other) # opposite of __eq__
def __lt__(self, other):
return self._key < other._key # compare items based on their keys
class SortedTableMap(MapBase):
"""Map implementation using a sorted table."""
# ----------------------------- nonpublic behaviors -----------------------------
def _find_index(self, k, low, high):
"""Return index of the leftmost item with key greater than or equal to k.
Return high + 1 if no such item qualifies.
That is, j will be returned such that:
all items of slice table[low:j] have key < k
all items of slice table[j:high+1] have key >= k
"""
# devi applicare il metodo inorder per cercare nel modo illustrato a pagina 331
if high < low:
return high + 1 # no element qualifies
else:
mid = (low + high) // 2
if k == self._table[mid]._key:
return mid # found exact match
elif k < self._table[mid]._key:
return self._find_index(k, low, mid - 1) # Note: may return mid
else:
return self._find_index(k, mid + 1, high) # answer is right of mid
# ----------------------------- public behaviors -----------------------------
def __init__(self):
"""Create an empty map."""
self._table = []
def __len__(self):
"""Return number of items in the map."""
return len(self._table)
def __getitem__(self, k):
"""Return value associated with key k (raise KeyError if not found)."""
j = self._find_index(k, 0, len(self._table) - 1)
if j == len(self._table) or self._table[j]._key != k:
# raise KeyError('Key Error: ' + repr(k))
return None
return self._table[j]._value
def __setitem__(self, k, v):
"""Assign value v to key k, overwriting existing value if present."""
j = self._find_index(k, 0, len(self._table) - 1)
if j < len(self._table) and self._table[j]._key == k:
self._table[j]._value = v # reassign value
else:
self._table.insert(j, self._Item(k, v)) # adds new item
def __getson__(self, k):
"""Return value associated with key k (raise KeyError if not found)."""
j = self._find_index(k, 0, len(self._table) - 1)
if j == len(self._table) or self._table[j]._key != k:
raise KeyError('Key Error: ' + repr(k))
return self._table[j]._figlio
def __setson__(self, k, sm2):
j = self._find_index(k, 0, len(self._table) - 1)
iteratore = sm2.__iter__()
for i in iteratore:
self._table[j]._figlio.__setitem__(i, sm2.__getitem__(i))
def __delitem__(self, k):
"""Remove item associated with key k (raise KeyError if not found)."""
j = self._find_index(k, 0, len(self._table) - 1)
if j == len(self._table) or self._table[j]._key != k:
raise KeyError('Key Error: ' + repr(k))
self._table.pop(j) # delete item
def __iter__(self):
"""Generate keys of the map ordered from minimum to maximum."""
for item in self._table:
yield item._key
def __reversed__(self):
"""Generate keys of the map ordered from maximum to minimum."""
for item in reversed(self._table):
yield item._key
def find_min(self):
"""Return (key,value) pair with minimum key (or None if empty)."""
if len(self._table) > 0:
return (self._table[0]._key, self._table[0]._value)
else:
return None
def find_max(self):
"""Return (key,value) pair with maximum key (or None if empty)."""
if len(self._table) > 0:
return (self._table[-1]._key, self._table[-1]._value)
else:
return None
def find_le(self, k):
"""Return (key,value) pair with greatest key less than or equal to k.
Return None if there does not exist such a key.
"""
j = self._find_index(k, 0, len(self._table) - 1) # j's key >= k
if j < len(self._table) and self._table[j]._key == k:
return (self._table[j]._key, self._table[j]._value) # exact match
elif j > 0:
return (self._table[j - 1]._key, self._table[j - 1]._value) # Note use of j-1
else:
return None
def find_ge(self, k):
"""Return (key,value) pair with least key greater than or equal to k.
Return None if there does not exist such a key.
"""
j = self._find_index(k, 0, len(self._table) - 1) # j's key >= k
if j < len(self._table):
return (self._table[j]._key, self._table[j]._value)
else:
return None
def find_lt(self, k):
"""Return (key,value) pair with greatest key strictly less than k.
Return None if there does not exist such a key.
"""
j = self._find_index(k, 0, len(self._table) - 1) # j's key >= k
if j > 0:
return (self._table[j - 1]._key, self._table[j - 1]._value) # Note use of j-1
else:
return None
def find_gt(self, k):
"""Return (key,value) pair with least key strictly greater than k.
Return None if there does not exist such a key.
"""
j = self._find_index(k, 0, len(self._table) - 1) # j's key >= k
if j < len(self._table) and self._table[j]._key == k:
j += 1 # advanced past match
if j < len(self._table):
return (self._table[j]._key, self._table[j]._value)
else:
return None
def find_range(self, start, stop):
"""Iterate all (key,value) pairs such that start <= key < stop.
If start is None, iteration begins with minimum key of map.
If stop is None, iteration continues through the maximum key of map.
"""
if start is None:
j = 0
else:
j = self._find_index(start, 0, len(self._table) - 1) # find first result
while j < len(self._table) and (stop is None or self._table[j]._key < stop):
yield (self._table[j]._key, self._table[j]._value)
j += 1
from Esercizio3Intracorso.my_binary_tree_search import TreeMap as TM
class abTree():
def __init__(self):
self._Mappa = SortedTableMap()
self._Albero = TM()
self._dictionary = {}
self._greatSorted = SortedTableMap() # utile nella ricerca di tutte le entry che rispettano il vincolo ">=c1 e <=c2", Esercizio1Finale
def reset_key(self, p, k):
mappa = SortedTableMap()
iteratore2 = p.value().__iter__()
for i in iteratore2:
mappa.__setitem__(i, p.value().__getitem__(i))
mappa.__setson__(i, p.value().__getson__(i))
self._Albero.__delitem__(p.key()) # cancello la entry con chiave minima
self._Albero.__setitem2__(k, mappa) # reinserisco la entry con nuova chiave minima
def addElement(self, k, v):
if self._Albero.is_empty():
self._Mappa.__setitem__(k, v)
self._Albero.__setitem__(k, self._Mappa)
return
p = self._Albero.find_position(k)
if (k > p.value().find_max()[0] and not self._Albero.is_leaf(p) or (k < p.key() and self._Albero.parent(p).key() < p.key() and self._Albero.is_leaf(p))):
p = self._Albero.parent(p)
self._dictionary.__setitem__("position", p)
self.ins2(k, v, p, p.value())
def ins2(self, k, v, p, sorted):
tupla = sorted.find_ge(k)
if tupla is not None:
k_pot = tupla[0]
if k_pot == k:
sorted.__setitem__(k, v)
elif k_pot > k:
if sorted.__getson__(k_pot).__len__() > 0:
self._dictionary.__setitem__(k_pot, sorted)
self.ins2(k, v, p, sorted.__getson__(k_pot))
else:
sorted.__setitem__(k, v)
if p.value() == sorted:
self.split(p, None) # split nodo
else:
self.split(None, sorted) # split riferimento
self._dictionary = {}
else:
sorted.__setitem__(k, v)
if p.value() == sorted:
self.split(p, None) # split nodo
else:
self.split(None, sorted) # split riferimento
self._dictionary = {}
def split(self, p, map):
if p is None and map is not None:
mappa = map
elif map is None and p is not None:
mappa = p.value()
else:
return None
if mappa.__len__() >= 8:
middle = (mappa.__len__() - 1) // 2
k_mid = mappa._table[middle]._key
sm1 = SortedTableMap()
sm2 = SortedTableMap()
sm3 = SortedTableMap()
iteratore = mappa.__iter__()
for i in iteratore:
if i < k_mid:
sm2.__setitem__(i, mappa.__getitem__(i))
elif i > k_mid:
sm3.__setitem__(i, mappa.__getitem__(i))
sm1.__setitem__(k_mid, mappa.__getitem__(k_mid))
self.son_recursive(sm1, mappa)
self.son_recursive(sm2, mappa)
self.son_recursive(sm3, mappa)
if map is None and p is not None:
if self._Albero.is_root(p):
self._Albero.__setitem2__(sm1.find_min()[0], sm1)
self._Albero.__setitem2__(sm2.find_min()[0], sm2)
self._Albero.__setitem2__(sm3.find_min()[0], sm3)
return
self._Albero.parent(p).value().__setitem__(k_mid, sm1.__getitem__(k_mid))
if p.key() > self._Albero.parent(p).key(): # parte destra
self._Albero.parent(p).value().__setson__(k_mid, sm2)
self.son_recursive(self._Albero.parent(p).value().__getson__(k_mid), mappa)
self._Albero.__delitem__(p.key())
self._Albero.__setitem2__(sm3.find_min()[0], sm3)
p = self._Albero.find_position(sm3.find_min()[0])
elif p.key() < self._Albero.parent(p).key(): # parte sinistra
self._Albero.parent(p).value().__setson__(self._Albero.parent(p).key(), sm3)
self.son_recursive(self._Albero.parent(p).value().__getson__(self._Albero.parent(p).key()), mappa)
self._Albero.parent(p).value().__setson__(k_mid, mappa.__getson__(k_mid))
self.son_recursive(self._Albero.parent(p).value().__getson__(k_mid), mappa)
self._Albero.__delitem__(p.key())
self._Albero.__setitem2__(sm2.find_min()[0], sm2)
p = self._Albero.find_position(sm2.find_min()[0])
self.reset_key(self._Albero.parent(p), k_mid)
p = self._Albero.find_position(sm2.find_min()[0])
if (self._Albero.parent(p).value().__len__() >= 8):
self.split(self._Albero.parent(p), None)
elif map is not None and p is None:
tup = self._dictionary.popitem()
tup_k, tup_v = tup[0], tup[1]
tup_v.__setitem__(k_mid, sm1.__getitem__(k_mid))
tup_v.__setson__(k_mid, sm2)
map.clear()
it = sm3.__iter__()
for i in it:
map.__setitem__(i, sm3.__getitem__(i))
p = self._dictionary.__getitem__("position")
if p.value() == tup_v:
if k_mid < p.key():
self.reset_key(p, k_mid)
p = self._Albero.find_position(k_mid)
self.split(p, None)
else:
self.split(None, self._dictionary.popitem()[1])
def son_recursive(self, sm, mappa):
it = mappa.__iter__()
for i in it:
if mappa.__getson__(i).__len__() > 0 and sm.__getitem__(i) is not None:
sm.__setson__(i, mappa.__getson__(i))
self.son_recursive(mappa.__getson__(i), mappa.__getson__(i))
def search(self, k):
if self._Albero.is_empty():
return None
p = self._Albero.find_position(k)
if (k > p.value().find_max()[0] and not self._Albero.is_leaf(p) or (k < p.key() and self._Albero.parent(p).key() < p.key())):
p = self._Albero.parent(p)
return self.search2(k, p.value())
def search2(self, k, sorted):
tupla = sorted.find_ge(k)
if tupla is not None:
k_pot, v_pot = tupla[0], tupla[1]
if k_pot == k:
return v_pot
elif k_pot > k:
if sorted.__getson__(k_pot).__len__() > 0:
return self.search2(k, sorted.__getson__(k_pot))
else:
return None
else:
return None
# Esercizio1Finale - Cerco i nodi cui appartengono c1 e c2
def greatSearch(self, c1, c2):
if self._Albero.is_empty():
return None
p1 = self._Albero.find_position(c1)
p2 = self._Albero.find_position(c2)
if (c1 > p1.value().find_max()[0] and not self._Albero.is_leaf(p1) or (c1 < p1.key() and self._Albero.parent(p1).key() < p1.key())) and (c2 > p2.value().find_max()[0] and not self._Albero.is_leaf(p2) or (c2 < p2.key() and self._Albero.parent(p2).key() < p2.key())):
p1 = self._Albero.parent(p1)
p2 = self._Albero.parent(p2)
return self.greatSearch2(p1.key(), p2.key())
# Esercizio1Finale - Itero sui nodi dell'albero
def greatSearch2(self, k1, k2):
it = self._Albero.__iter__()
for i in it: # itero sull'albero
if i >= k1 and i <= k2:
sorted1 = self._Albero.__getitem__(i)
it1 = sorted1.__iter__()
for j in it1: # itero sulla sorted di ogni nodo
if sorted1.__getson__(j).__len__() > 0:
self.greatSearch3(sorted1.__getson__(j))
else:
self._greatSorted.__setitem__(j, sorted1.find_min()[0])
return self._greatSorted
# Esercizio1Finale - Itero sulle SortedTableMap (riferimenti)
def greatSearch3(self, sortedFiglio):
it = sortedFiglio.__iter__()
for i in it:
if sortedFiglio.__getson__(i).__len__() > 0:
self.greatSearch3(sortedFiglio.__getson__(i))
else:
self._greatSorted.__setitem__(i, sortedFiglio.find_min()[0])
def delete(self, k):
if self._Albero.is_empty():
return None
p = self._Albero.find_position(k)
if (k > p.value().find_max()[0] and not self._Albero.is_leaf(p) or (k < p.key() and self._Albero.parent(p).key() < p.key())):
p = self._Albero.parent(p)
self.del2(k, p, p.value())
def del2(self, k, p, sorted):
tupla = sorted.find_ge(k)
if tupla is not None:
k_pot, v_pot = tupla[0], tupla[1]
if k_pot == k:
if self._Albero.is_root(p) and self._Albero.num_children(p) == 0:
sorted.__delitem__(k)
if p.value().__len__() >= 1 and self._Albero.is_leaf(p) and k == p.key():
self.reset_key(p, sorted.find_min()[0])
elif sorted.__len__() == 0:
self._Albero.__delitem__(k)
return
if self._Albero.is_root(p) and self._Albero.left(p).value().__len__() == 1 and self._Albero.right(p).value().__len__() == 1:
sx = self._Albero.left(p).value().find_min()
dx = self._Albero.right(p).value().find_min()
p.value().clear()
p.value().__setitem__(sx[0], sx[1])
p.value().__setitem__(dx[0], dx[1])
self._Albero.__delitem__(sx[0])
self._Albero.__delitem__(dx[0])
self.reset_key(p, sx[0])
return
if (sorted.__getson__(k).__len__() == 0 and sorted.__len__() > 1) or (p.value().__len__() > 1 and self._Albero.is_leaf(p)):
if k == p.value().find_min()[0] and not self._Albero.is_leaf(p):
if self._Albero.left(p).value().__len__() > 1 and p.value.__getson__(k).__len__() == 0:
max = self._Albero.left(p).value().find_max()
p.value().__setitem__(max[0], max[1])
self._Albero.left(p).value().__delitem__(max[0])
p.value().__delitem__(k)
self.reset_key(p, max[0])
return
elif p.value().__getson__(k).__len__() > 1:
bigger = p.value().__getson__(k).find_max()
p.value().__setitem__(bigger[0], bigger[1])
p.value().__getson__(k).__delitem__(bigger[0])
sons = p.value().__getson__(k)
p.value().__setson__(bigger[0], sons)
p.value().__delitem__(k)
self.reset_key(p, bigger[0])
return
elif p.value().__getson__(k).__len__() == 1 and self._Albero.left(p).value().__len__() > 1:
x = self._Albero.left(p).value().find_max()
p.value().__setitem__(x[0], x[1])
sons = p.value().__getson__(k)
p.value().__setson__(x[0], sons)
p.value().__delitem__(k)
self._Albero.left(p).value().__delitem__(x[0])
self.reset_key(p, x[0])
return
elif p.value().__getson__(k).__len__() == 1 and self._Albero.left(p).value().__len__() == 1:
son = p.value().__getson__(k).find_min()
self._Albero.left(p).value().__setitem__(son[0], son[1])
p.value().__delitem__(k)
self.reset_key(p, p.value().find_gt(k)[0])
return
if (sorted.__getson__(k).__len__() == 0 and sorted.__len__() == 1) or (p.value().__len__() == 1 and self._Albero.is_leaf(p)):
if p.value().__len__() == 1 and self._Albero.is_leaf(p):
if p.key() > self._Albero.parent(p).key():
padre = self._Albero.parent(p)
max = padre.value().find_max()
if self._Albero.is_root(padre) and padre.value().__len__() == 1:
son_nodo = self._Albero.left(padre)
son = son_nodo.value()
else:
son = padre.value().__getson__(max[0])
if son.__len__() > 1:
max_son = son.find_max()
padre.value().__setitem__(max_son[0], max_son[1])
if not (self._Albero.is_root(padre) and padre.value().__len__() == 2):
figli = padre.value().__getson__(max[0])
padre.value().__setson__(max_son[0], figli)
padre.value().__getson__(max_son[0]).__delitem__(max_son[0])
padre.value().__getson__(max[0]).clear()
else:
son.__delitem__(max_son[0])
if padre.key() > max_son[0]:
self.reset_key(padre, max_son[0])
p.value().clear()
p.value().__setitem__(max[0], max[1])
self.reset_key(p, max[0])
self._Albero.root().value().__delitem__(max[0])
elif padre.value().__len__() > 1:
bigger = padre.value().find_max()
son_bigger = padre.value().__getson__(bigger[0]).find_min()
p.value().__setitem__(bigger[0], bigger[1])
p.value().__setitem__(son_bigger[0], son_bigger[1])
p.value().__delitem__(p.key())
self.reset_key(p, son_bigger[0])
padre.value().__delitem__(bigger[0])
elif son.__len__() == 1 and self._Albero.is_root(padre):
padre.value().__setitem__(son.find_min()[0], son.find_min()[1])
self.reset_key(padre, son.find_min()[0])
self._Albero.__delitem__(p.key())
elif p.key() < self._Albero.parent(p).key():
padre = self._Albero.parent(p)
min = padre.value().find_min()
if padre.value().__getson__(min[0]).__len__() > 0:
son = padre.value().__getson__(min[0])
sm = SortedTableMap()
sm.__setitem__(son.find_min()[0], son.find_min()[1])
self.son_recursive(sm, son)
c = 0
while sm.__getson__(sm.find_min()[0]).__len__() > 0:
c += 1
sm = sm.__getson__(sm.find_min()[0])
if c > 0:
son.clear()
it = sm.__iter__()
for i in it:
son.__setitem__(i, sm.__getitem__(i))
elif padre.value().__len__() == 1:
son = self._Albero.right(padre).value()
else:
son = padre.value().__getson__(padre.value().find_gt(min[0])[0])
sm = SortedTableMap()
sm.__setitem__(son.find_min()[0], son.find_min()[1])
self.son_recursive(sm, son)
c = 0
while sm.__getson__(sm.find_min()[0]).__len__() > 0:
c += 1
sm = sm.__getson__(sm.find_min()[0])
if c > 0:
son.clear()
it = sm.__iter__()
for i in it:
son.__setitem__(i, sm.__getitem__(i))
if son.__len__() > 1:
min_son = son.find_min()
padre.value().__setitem__(min_son[0], min_son[1])
son.__delitem__(min_son[0])
min_padre = padre.value().find_min()
nodo_sinistro = self._Albero.left(padre)
padre.value().__delitem__(padre.key())
if padre.value().__len__() == 1:
self.reset_key(self._Albero.right(padre), son.find_min()[0])
self.reset_key(padre, min_son[0])
nodo_sinistro.value().clear()
nodo_sinistro.value().__setitem__(min_padre[0], min_padre[1])
self.reset_key(nodo_sinistro, min_padre[0])
elif son.__len__() == 1 and self._Albero.is_root(padre):
padre.value().__setitem__(son.find_min()[0], son.find_min()[1])
self._Albero.__delitem__(p.key())
self._Albero.__delitem__(self._Albero.right(padre).key())
elif not self._Albero.is_leaf(p) and p.value().__len__() > 1 and p.key() > self._Albero.parent(p).key():
if k == p.value().find_max()[0]:
max_son = p.value().find_max()
if p.value().__getson__(max_son[0]).__len__() > 1:
son = p.value().__getson__(max_son[0])
x = son.find_max()
p.value().__setitem__(x[0], x[1])
son.__delitem__(x[0])
p.value().__setson__(x[0], son)
p.value().__delitem__(p.value().find_max()[0])
elif p.value().__getson__(max_son[0]).__len__() == 1 and self._Albero.right(p).value().__len__() > 1:
x = self._Albero.right(p).value().find_min()
p.value().__setitem__(x[0], x[1])
sons = p.value().__getson__(k)
it = sons.__iter__()
for i in it:
p.value().__setson__(x[0], sons)
p.value().__delitem__(k)
self._Albero.right(p).value().__delitem__(x[0])
self.reset_key(self._Albero.right(p), self._Albero.right(p).value().find_min()[0])
elif p.value().__getson__(max_son[0]).__len__() == 1 and self._Albero.right(p).value().__len__() == 1:
son = p.value().__getson__(max_son[0]).find_min()
self._Albero.right(p).value().__setitem__(son[0], son[1])
self.reset_key(self._Albero.right(p), son[0])
p.value().__delitem__(k)
elif k != p.value().find_max()[0] and p.key() > self._Albero.parent(p).key():
if p.value().__getson__(k).__len__() > 1:
x = p.value().__getson__(k)
max = x.find_max()
p.value().__setitem__(max[0], max[1])
x.__delitem__(max[0])
p.value().__setson__(max[0], x)
p.value().__delitem__(k)
if max[0] < k:
self.reset_key(p, max[0])
elif p.value().__getson__(k).__len__() == 1 and p.value().__getson__(p.value().find_gt(k)[0]).__len__() > 1:
x = p.value().__getson__(p.value().find_gt(k)[0])
min = x.find_min()
p.value().__setitem__(min[0], min[1])
x.__delitem__(min[0])
j = p.value().__getson__(k)
p.value().__setson__(min[0], j)
p.value().__delitem__(k)
if max[0] < k:
self.reset_key(p, max[0])
elif not self._Albero.is_leaf(p) and p.value().__len__() > 1 and p.key() < self._Albero.parent(p).key():
if k != p.value().find_min()[0]:
if p.value().__getson__(k).__len__() > 1:
x = p.value().__getson__(k)
max = x.find_max()
p.value().__setitem__(max[0], max[1])
x.__delitem__(max[0])
p.value().__setson__(max[0], x)
p.value().__delitem__(k)
elif p.value().__getson__(k).__len__() == 1 and p.value().__getson__(p.value().find_gt(k)[0]).__len__() > 1:
x = p.value().__getson__(p.value().find_gt(k)[0])
min = x.find_min()
p.value().__setitem__(min[0], min[1])
x.__delitem__(min[0])
j = p.value().__getson__(k)
p.value().__setson__(min[0], j)
p.value().__delitem__(k)
elif k_pot > k:
if sorted.__getson__(k_pot).__len__() > 0:
return self.del2(k, p, sorted.__getson__(k_pot))
else:
return
else:
return
def stampa(self):
iteratore3 = self._Albero.__iter__()
c = 0
for i in iteratore3:
if c > 0:
print("\n")
c += 1
iteratore4 = self._Albero.__getitem__(i).__iter__() # creo un iteratore per ciascun nodo
for j in iteratore4:
riferimento = self._Albero.__getitem__(i).__getson__(
j) # controllo se il figlio memorizzato in key,value non sia vuoto
if riferimento.__len__() > 0:
print("\n")
iteratore5 = riferimento.__iter__()
for m in iteratore5:
print(m, riferimento.__getitem__(m))
print("\n")
print(j, self._Albero.__getitem__(i).__getitem__(j))
def getKeys(self):
iteratore3 = self._Albero.__iter__()
lista = []
for i in iteratore3:
lista.append(i)
return lista
# #-----------------TEST----------------#
#
# abt = abTree()
#
# from Esercizio2Intracorso.Currency import Currency
#
# #----------CURRENCY INITIALIZATION-----------#
# curr1 = Currency("EUR")
# curr2 = Currency("USD")
#
# #----------CURRENCY CONSTRUCTION OBJECT----------#
# curr1.AddDenomination(0.05)
# curr1.AddDenomination(0.1)
# curr1.AddDenomination(0.2)
# curr1.AddDenomination(0.5)
# curr1.AddDenomination(1)
# curr1.AddDenomination(2)
# curr1.AddDenomination(5)
# curr1.AddDenomination(10)
# curr1.AddDenomination(20)
# curr1.AddDenomination(50)
# curr1.AddDenomination(100)
# curr1.AddDenomination(200)
# curr1.AddDenomination(500)
# curr1.addChange("USD", 1.2)
#
# curr2.AddDenomination(0.01)
# curr2.AddDenomination(0.05)
# curr2.AddDenomination(0.1)
# curr2.AddDenomination(0.25)
# curr2.AddDenomination(0.5)
# curr2.AddDenomination(1)
# curr2.AddDenomination(2)
# curr2.AddDenomination(5)
# curr2.AddDenomination(10)
# curr2.AddDenomination(20)
# curr2.AddDenomination(50)
# curr2.AddDenomination(100)
# curr2.addChange("EUR", 0.85)
#
# #------ADDING-------#
# abt.addElement(curr1._Code, curr1)
# abt.addElement(curr2._Code, curr2)
#
# #----PRINTING INITIAL RESULTS-----#
# abt.stampa()
#
# #-----SEARCHING-----#
# print("\n\n")
# print("Research results:", abt.search("EUR"))
#
# #-----DELETING------#
# abt.delete("EUR")
# print("\n\n")
#
# #----PRINTING FINAL RESULTS-----#
# abt.stampa() |
442d1a1a4fb1855fb2f496e8bb52f7ff24740829 | Md-Monirul-Islam/Python-code | /Numpy/Array Manipulation - flatten and ravel.py | 259 | 3.546875 | 4 | import numpy as np
#flatten
a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print(a)
print(a.flatten())
print(a.flatten(order='F'))
print(a.flatten(order='A'))
#ravel
b = np.array([[1,2,3],[4,5,6]])
print(b)
print(np.ravel(b))
print(np.ravel(a,order="F")) |
28434868c192a8380b854c521745b9d3517c17f5 | carlcrede/python-elective | /ses9/small_exercises.py | 842 | 3.90625 | 4 | from datetime import datetime
""" Write a decorator that writes to a log file the time stamp
of each time this function is called.
Change the log decorator to also printing the values
of the argument together with the timestamp.
Print the result of the decorated function to the log file also.
Create a new function and call it printer(text)
that takes a text as parameter and returns the text.
Decorate it with your logfunction. Does it work? """
def log(func):
def wrapper(*args):
result = func(*args)
with open('log.txt', 'a') as f:
f.write(f'Timestamp: {datetime.now()}\nArgs: {args}\nResult: {result}\n\n')
return result
return wrapper
@log
def add(*args):
sum = 0
for i in args:
sum += i
return sum
@log
def printer(text):
return f'From printer: {text}\n'
|
e83232ea26dc85c2a212f25f77d885d47f8923b5 | E2394/python_assignments | /prime.py | 360 | 4.21875 | 4 | # for theory, check out https://en.wikipedia.org/wiki/Primality_test
number= float(input("Enter a number..:"))
root = number**(1/2)
rootint = round(root)
divisors = []
for i in range(2,rootint+1):
if (number % i) == 0:
divisors.append(i)
i+=1
if not bool(divisors):
print(f"{number} is prime.")
else:
print(f"{number} is NOT prime.") |
014fb1b4bc3d182cabf34eeb7fd7c84b7d405ecf | choroba/perlweeklychallenge-club | /challenge-214/sgreen/python/ch-2.py | 1,354 | 4.15625 | 4 | #!/usr/bin/env python
import sys
def shrink_list(array):
'''Shrink the list if it has consecutive numbers'''
new_array = []
for i in array:
number, count = i
if len(new_array) and new_array[-1][0] == number:
new_array[-1] = (number, count + new_array[-1][1])
else:
new_array.append((number, count))
return new_array
def score_array(array):
'''Recursive function to get the highest score'''
# Shrink the list if it has consecutive numbers
array = shrink_list(array)
if len(array) == 1:
# There is only one remaining number
return array[0][1] ** 2
max_score = 0
for i, tup in enumerate(array):
# Create a copy of the array without the chosen element
new_array = array.copy()
del new_array[i]
# Calculate the maximum possible score recursively
score = tup[1] ** 2 + score_array(new_array)
if score > max_score:
max_score = score
# Return the maximum score
return max_score
def main(array):
# Turn the list in a list of tuples of the number and the occurrences of it
array = [ (x, 1) for x in array]
score = score_array(array)
print(score)
if __name__ == '__main__':
# Turn the strings into integers
n = [int(i) for i in sys.argv[1:]]
main(n)
|
2305c477b3c04ce193486ac6c7d27dfaffc90877 | aashya/Reinforcement-Learning | /Reinforcement Learning.py | 5,611 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[22]:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Epsilon Greedy
class Bandit_eps:
# print("Bandit")
def __init__(self,m):
self.m = m
self.mean = 0
self.N = 0
def pull(self):
return np.random.randn() + self.m
def update(self,x):
self.N += 1
self.mean = (1-(1.0/self.N))*self.mean + (1.0/self.N)*x
# Comparing three different bandits
def run_eps(m1,m2,m3,eps,N):
print("epsilon greedy")
bandits_eps = [Bandit_eps(m1), Bandit_eps(m2), Bandit_eps(m3)]
data = np.empty(N)
# choosing exploit or explore based on epsilon value
for i in range(N):
p=np.random.random()
if p < eps:
# explore
j=np.random.choice(3)
else:
# exploit
j=np.argmax([b.mean for b in bandits_eps])
x=bandits_eps[j].pull()
bandits_eps[j].update(x)
# for the plot
data[i] = x
cumulative_average = np.cumsum(data) / (np.arange(N) + 1)
# plot moving average ctr
# matplotlib.rcParams['figure.figsize'] = [80, 80]
plt.plot(cumulative_average)
plt.plot(np.ones(N)*m1)
plt.plot(np.ones(N)*m2)
plt.plot(np.ones(N)*m3)
plt.xscale('log')
plt.show()
for b in bandits_eps:
print(b.mean)
return cumulative_average
# Optimistic Initial Value
class Bandit_oiv:
# print("Bandit")
def __init__(self,m, upper_limit):
self.m = m
self.mean = upper_limit
self.N = 1
def pull(self):
# print("pull")
return np.random.randn() + self.m
def update(self,x):
self.N += 1
self.mean = (1-(1.0/self.N))*self.mean + (1.0/self.N)*x
# Comparing three different bandits
def run_oiv(m1,m2,m3,N, upper_limit=10):
print("optimistic value")
bandits_oiv = [Bandit_oiv(m1, upper_limit), Bandit_oiv(m2, upper_limit), Bandit_oiv(m3, upper_limit)]
data = np.empty(N)
# choosing exploit or explore based on epsilon value
for i in range(N):
j=np.argmax([b.mean for b in bandits_oiv])
x=bandits_oiv[j].pull()
# print(x)
bandits_oiv[j].update(x)
# for the plot
data[i] = x
cumulative_average = np.cumsum(data) / (np.arange(N) + 1)
# plot moving average ctr
# matplotlib.rcParams['figure.figsize'] = [80, 80]
plt.plot(cumulative_average)
plt.plot(np.ones(N)*m1)
plt.plot(np.ones(N)*m2)
plt.plot(np.ones(N)*m3)
plt.xscale('log')
plt.show()
for b in bandits_oiv:
print(b.mean)
return cumulative_average
# UCB1
class Bandit_ucb:
# print("Bandit")
def __init__(self,m):
self.m = m
self.mean = 0
self.N = 0
def pull(self):
# print("pull")
return np.random.randn() + self.m
def update(self,x):
self.N += 1
self.mean = (1-(1.0/self.N))*self.mean + (1.0/self.N)*x
def ucb(mean, n, nj):
if nj == 0:
return float('inf')
return mean + np.sqrt(2*np.log(n) / nj)
# Comparing three different bandits
def run_ucb(m1,m2,m3,N):
print("UCB1")
bandits_ucb = [Bandit_ucb(m1), Bandit_ucb(m2), Bandit_ucb(m3)]
data = np.empty(N)
# choosing exploit or explore based on epsilon value
for i in range(N):
j=np.argmax([ucb(b.mean, i+1, b.N) for b in bandits_ucb])
x=bandits_ucb[j].pull()
# print(x)
bandits_ucb[j].update(x)
# for the plot
data[i] = x
cumulative_average = np.cumsum(data) / (np.arange(N) + 1)
# plot moving average ctr
# matplotlib.rcParams['figure.figsize'] = [80, 80]
plt.plot(cumulative_average)
plt.plot(np.ones(N)*m1)
plt.plot(np.ones(N)*m2)
plt.plot(np.ones(N)*m3)
plt.xscale('log')
plt.show()
for b in bandits_ucb:
print(b.mean)
return cumulative_average
if __name__ == '__main__':
c_1=run_eps(1.0,2.0,3.0,0.1,100000)
c_2=run_eps(1.0,2.0,3.0,0.05,100000)
c_3=run_eps(1.0,2.0,3.0,0.01,100000)
oiv1=run_oiv(1.0,2.0,3.0,100000)
ucb = run_ucb(1.0, 2.0, 3.0, 100000)
# log scale plot
# matplotlib.rcParams['figure.figsize'] = [50, 50]
print("log scale plots")
plt.plot(c_1, label='eps = 0.1')
plt.plot(c_2, label='eps = 0.05')
plt.plot(c_3, label='eps = 0.01')
plt.plot(oiv1, label='optimistic')
plt.plot(ucb, label='ucb')
plt.legend()
plt.xscale('log')
plt.show()
# linear plot
# matplotlib.rcParams['figure.figsize'] = [40, 50]
print ("linear plots")
plt.plot(c_1, label ='eps = 0.1')
plt.plot(c_2, label ='eps = 0.05')
plt.plot(c_3, label ='eps = 0.01')
plt.plot(oiv1, label ='optimistic')
plt.plot(ucb, label='ucb')
plt.legend()
plt.show()
# # log scale plot
# plt.plot(eps, label='decaying-epsilon-greedy')
# plt.plot(oiv, label='optimistic')
# plt.plot(ucb, label='ucb1')
# plt.plot(bayes, label='bayesian')
# plt.legend()
# plt.xscale('log')
# plt.show()
# # linear plot
# plt.plot(eps, label='decaying-epsilon-greedy')
# plt.plot(oiv, label='optimistic')
# plt.plot(ucb, label='ucb1')
# plt.plot(bayes, label='bayesian')
# plt.legend()
# plt.show()
# In[ ]:
|
b54872107fbfebcdd4c469addf986255026d22cb | rm-hull/luma.core | /tests/baseline_data.py | 975 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-18 Richard Hull and contributors
# See LICENSE.rst for details.
def primitives(device, draw):
padding = 2
shape_width = 20
top = padding
bottom = device.height - padding - 1
draw.rectangle(device.bounding_box, outline="white", fill="black")
x = padding
draw.ellipse((x, top, x + shape_width, bottom), outline="red", fill="black")
x += shape_width + padding
draw.rectangle((x, top, x + shape_width, bottom), outline="blue", fill="black")
x += shape_width + padding
draw.polygon([(x, bottom), (x + shape_width / 2, top), (x + shape_width, bottom)], outline="green", fill="black")
x += shape_width + padding
draw.line((x, bottom, x + shape_width, top), fill="yellow")
draw.line((x, top, x + shape_width, bottom), fill="yellow")
x += shape_width + padding
draw.text((x, top), 'Hello', fill="cyan")
draw.text((x, top + 20), 'World!', fill="purple")
|
d0f6b35ff7ac0aa0978eeecd3e0f73d5510b92f7 | Crazybus/pumbaku | /pumbaku_test.py | 1,322 | 3.65625 | 4 | from pumbaku import find_haiku
def test_a_valid_haiku():
message = find_haiku('An old silent pond. A frog jumps into the pond. Splash silence again')
assert message == (
'AN OLD SILENT POND\n'
'A FROG JUMPS INTO THE POND\n'
'SPLASH SILENCE AGAIN'
)
def test_a_valid_haiku_with_new_lines():
message = find_haiku('An old silent pond.\nA frog jumps into the pond.\nSplash silence again')
assert message == (
'AN OLD SILENT POND\n'
'A FROG JUMPS INTO THE POND\n'
'SPLASH SILENCE AGAIN'
)
def test_an_unknown_word():
message = find_haiku('An old silent crazybus. A frog jumps into the pond. Splash silence again')
assert message == 'PUMBAKU DO NOT KNOW CRAZYBUS'
def test_not_a_valid_haiku():
message = find_haiku('haiku')
assert message == 'HAS 2 SYLLABLES! IS NOT HAIKU!'
def test_not_a_valid_haiku_with_too_many_syllables():
message = find_haiku('hi ' * 18)
assert message == 'HAS 18 SYLLABLES! IS NOT HAIKU!'
def test_a_valid_haiku_with_commas():
message = find_haiku('An old silent pond, A frog jumps into the pond, Splash silence again')
assert message == (
'AN OLD SILENT POND\n'
'A FROG JUMPS INTO THE POND\n'
'SPLASH SILENCE AGAIN'
)
|
4686e97717b169d60c13f4fa741e30611ad8a95e | Swagatamkar/Restaurant_Management_System | /Tkinter project 1.py | 6,143 | 3.8125 | 4 | price={'Rice':150,
'Daal':100, # in this dict items stored as key and price of that item as value
' Kadai Paneer':130,
'Butter paneer':150,
'chicken Kasa':190,
'Butter Chicken':200,
'None':0}
def click():
# this func will be called when submit button will be pressed
Customers_name=Name.get()
Customers_phone=ph.get()
A1=price[n1.get()]*q1.get()
A2= price[n2.get() ]* q2.get()
A3 = price[n3.get() ]* q3.get()
A4 = price[n4.get() ]* q4.get() #A sotres (price of item * quantity of that item) and calculates sub total
A5 = price[n5.get() ]* q5.get()
A6 = price[n6.get() ]* q6.get()
A7 = price[n7.get() ]* q7.get()
A8 = price[n8.get() ]* q8.get()
A9 = price[n9.get() ]* q9.get()
A10 = price[n10.get()] * q10.get()
s1.set(A1)
s2.set(A2)
s3.set(A3)
s4.set(A4)
s5.set(A5)
s6.set(A6) # setting the sub ammount entries
s7.set(A7)
s8.set(A8)
s9.set(A9)
s10.set(A10)
total=A1+A2+A3+A4+A5+A6+A7+A8+A9+A10 # total amount to be payed
AmmountToBePaid.set(total) #setting total ammount
Payment_Mode=M.get()
print(Payment_Mode)
from tkinter import *
root=Tk()
root.geometry('1200x600')
root.title('WELCOME TO Get Ready To Pay')
#Labels
Label(root,text="Contact Number").grid(row=1,column=3)
Label(root,text="Customer Name").grid(row=1)
Label(root,text=" Item Ordered").grid(row=2)
Label(root,text=" Item Ordered").grid(row=3)
Label(root,text=" Item Ordered").grid(row=4)
Label(root,text=" Item Ordered").grid(row=5)
Label(root,text=" Item Ordered").grid(row=6)
Label(root,text=" Item Ordered").grid(row=7)
Label(root,text=" Item Ordered").grid(row=8)
Label(root,text=" Item Ordered").grid(row=9)
Label(root,text=" Item Ordered").grid(row=10)
Label(root,text=" Item Ordered").grid(row=11)
Label(root,text="Ammount To Be Paid").grid(row=14)
Label(root,text="Quantity").grid(row=2,column=3)
Label(root,text="Quantity").grid(row=3,column=3)
Label(root,text="Quantity").grid(row=4,column=3)
Label(root,text="Quantity").grid(row=5,column=3)
Label(root,text="Quantity").grid(row=6,column=3)
Label(root,text="Quantity").grid(row=7,column=3)
Label(root,text="Quantity").grid(row=8,column=3)
Label(root,text="Quantity").grid(row=9,column=3)
Label(root,text="Quantity").grid(row=10,column=3)
Label(root,text="Quantity").grid(row=11,column=3)
Label(root,text="Amount").grid(row=2,column=6)
Label(root,text="Amount").grid(row=3,column=6)
Label(root,text="Amount").grid(row=4,column=6)
Label(root,text="Amount").grid(row=5,column=6)
Label(root,text="Amount").grid(row=6,column=6)
Label(root,text="Amount").grid(row=7,column=6)
Label(root,text="Amount").grid(row=8,column=6)
Label(root,text="Amount").grid(row=9,column=6)
Label(root,text="Amount").grid(row=10,column=6)
Label(root,text="Amount").grid(row=11,column=6)
# Payment mode
Label(root,text="Mode Of Payment").grid(row=15)
#Entry
#n stores name of item
n1 = StringVar()
n2 = StringVar()
n3= StringVar()
n4 = StringVar()
n5 = StringVar()
n6 = StringVar()
n7 = StringVar()
n8 = StringVar()
n9 = StringVar()
n10 = StringVar()
Name=StringVar()
ph=StringVar()
#q stores quantity
q1=IntVar()
q2=IntVar()
q3=IntVar()
q4=IntVar()
q5=IntVar()
q6=IntVar()
q7=IntVar()
q8=IntVar()
q9=IntVar()
q10=IntVar()
#S store Sub Ammount
s1=IntVar()
s2=IntVar()
s3=IntVar()
s4=IntVar()
s5=IntVar()
s6=IntVar()
s7=IntVar()
s8=IntVar()
s9=IntVar()
s10=IntVar()
# M stores payment mode
M=StringVar()
AmmountToBePaid=IntVar()
Entry(root,textvariable=Name).grid(row=1,column=2)
Entry(root,textvariable=ph).grid(row=1,column=4)
Entry(root,textvariable=AmmountToBePaid).grid(row=14,column=2)
# Entries for Quantity
Entry(root,textvariable=q1).grid(row=2,column=4)
Entry(root,textvariable=q2).grid(row=3,column=4)
Entry(root,textvariable=q3).grid(row=4,column=4)
Entry(root,textvariable=q4).grid(row=5,column=4)
Entry(root,textvariable=q5).grid(row=6,column=4)
Entry(root,textvariable=q6).grid(row=7,column=4)
Entry(root,textvariable=q7).grid(row=8,column=4)
Entry(root,textvariable=q8).grid(row=9,column=4)
Entry(root,textvariable=q9).grid(row=10,column=4)
Entry(root,textvariable=q10).grid(row=11,column=4)
# Entries for SubAmmount
Entry(root,textvariable=s1).grid(row=2,column=7)
Entry(root,textvariable=s2).grid(row=3,column=7)
Entry(root,textvariable=s3).grid(row=4,column=7)
Entry(root,textvariable=s4).grid(row=5,column=7)
Entry(root,textvariable=s5).grid(row=6,column=7)
Entry(root,textvariable=s6).grid(row=7,column=7)
Entry(root,textvariable=s7).grid(row=8,column=7)
Entry(root,textvariable=s8).grid(row=9,column=7)
Entry(root,textvariable=s9).grid(row=10,column=7)
Entry(root,textvariable=s10).grid(row=11,column=7)
#Drop Down Menu from this we can select items
items=['None','Rice',
'Daal',
' Kadai Paneer',
'Butter paneer',
'chicken Kasa',
'Butter Chicken']
OptionMenu(root, n1, *items).grid(row=2,column=2)
OptionMenu(root, n2, *items).grid(row=3,column=2)
OptionMenu(root, n3, *items).grid(row=4,column=2)
OptionMenu(root, n4, *items).grid(row=5,column=2)
OptionMenu(root, n5, *items).grid(row=6,column=2)
OptionMenu(root, n6, *items).grid(row=7,column=2)
OptionMenu(root, n7, *items).grid(row=8,column=2)
OptionMenu(root, n8, *items).grid(row=9,column=2)
OptionMenu(root, n9, *items).grid(row=10,column=2)
OptionMenu(root, n10, *items).grid(row=11,column=2)
#setting default value of the drop down as None
n1.set(items[0])
n2.set(items[0])
n3.set(items[0])
n4.set(items[0])
n5.set(items[0])
n6.set(items[0])
n7.set(items[0])
n8.set(items[0])
n9.set(items[0])
n10.set(items[0])
# Drop Down Menu For Selecting Payment Mode
mode=[
'Cash',
'Debit Card',
'Credit Card',
'UPI',
'Google Pay',
'Paytm']
OptionMenu(root, M, *mode).grid(row=15,column=2)
# Button
Button(root,text="SUBMIT",bg='Red',fg='Blue',command=click).grid(row=12,column=3)
root.mainloop()
|
4e120180809eb65a203cdafc570e39afbc2c8f46 | EdwinVan/Python | /Python Homework/20-10-09-week05/4-6.py | 4,622 | 3.71875 | 4 | # 4-6.py 验证羊车门更换选择是否会增加猜中汽车的机会demo
# fyj
# 2020/10/11
num_times = 100000
from random import *
nochange_success = 0
change_success = 0
nochange_loser = 0
change_loser = 0
for times in range(num_times):
print("**********{}**********".format(times+1))
list = ["sheep","sheep","sheep"] # 初始化,每个门后都为羊
num = randint(0,2)
list[num] = "car" # 1、2、3号门随机取一个放入car
list2 = [" "," "," "]
for i in range(len(list)):
if list[i] != "car":
list2[i] = list[i]
else:
list2[i] = " "
print(list)
list4 = [0,0,0] # list4=[car_num,sheep_num1]
list5 = [0,0,0] # list5=[sheep_num2,num_2]
while True:
# 第1次做出选择
your_num1 = randint(0,2)
print("你第1次选择了{}号门".format(your_num1+1))
for i in range(2):
if list2[i] == "car":
car_num = i
list4[0] = car_num # car所在索引位置,此门可能被参赛者选择
# 第2次做出选择
# 参赛者第一次选中的是车的门
if your_num1 == list4[0]:
for i in range(2):
if list[i] != "car" and i != your_num1:
print("主持人提示你:{}号门后是羊".format(i + 1)) # sheep_num1为主持人所开门后露出的小羊,此门参赛者不会再选
sheep_num1 = i
list4[1]= sheep_num1
for m in range(2):
if m not in list4:
sheep_num2 = m # sheep_num2为没有被主持人开门露出的小羊,此门可能被参赛者选择
list5[0] = sheep_num2
break
list3 = [your_num1,list5[0]] # 第一次选择的门(后面是车)、除主持人所开门之外的另一个门(后面是另一只羊)
for i in range(2):
num_2 = list3[randint(0, 1)] # 从主持人所开门后的另外两扇门随机选择一扇
list5[1] = num_2
break
your_num2 = list5[1]
# 参赛者第一次选中的是羊的门
else:
for i in range(2):
if list[i] != "car" and i != your_num1:
print("主持人提示你:{}号门后是羊".format(i + 1)) # sheep_num1为主持人所开门后露出的小羊,此门参赛者不会再选
sheep_num1 = i
list4 += [sheep_num1]
for m in range(2):
if m not in list4:
sheep_num2 = m # sheep_num2为没有被主持人开门露出的小羊,此门可能被参赛者选择
list5[0] = sheep_num2
break
list3 = [your_num1, list5[0]] # 第一次选择的门(后面是羊)、除主持人所开门之外的另一个门(后面是车)
for i in range(2):
select = randint(0, 1) # 从上面两个门中随机选择一个门
num_2 = list3[select] # 从主持人所开门后的另外两扇门随机选择一扇
list5[1] = num_2
break
your_num2 = list5[1]
# 揭晓选择结果
print("你第2次选择了{}号门".format(your_num2+1))
if list[your_num2] == "car":
if your_num2 == your_num1:
print("你坚定了你的选择,你猜对了!".format(your_num2+1))
nochange_success += 1
break
else:
print("你改变了你的选择,你猜对了!".format(your_num2 + 1))
change_success += 1
break
else:
if your_num2 == your_num1:
print("你坚定了你的选择,你猜错了!".format(your_num2 + 1))
nochange_loser += 1
break
else:
print("你改变了你的选择,你猜错了!".format(your_num2 + 1))
change_loser += 1
break
print("循环执行了{}次,总结如下:".format(num_times))
print("参赛者改变选择获胜了{}次".format(change_success))
print("参赛者坚持选择获胜了{}次".format(nochange_success))
print("参赛者改变选择失败了{}次".format(change_loser))
print("参赛者坚持选择失败了{}次".format(nochange_loser))
print("改变选择的胜率:{}".format())
print("坚持选择的胜率:{}".format()) |
9258aaf8d5248e37ee7000bf99a877c50ed1819a | Panda-Lewandowski/Programming-in-Python | /first semester/lab2.py | 5,395 | 3.9375 | 4 | from math import sqrt
x1, y1 = map(int, input('Введите координаты вершины А ').split())
x2, y2 = map(int, input('Введите координаты вершины B ').split())
x3, y3 = map(int, input('Введите координаты вершины C ').split())
print('''
B
/\\
/ \\
/ \\
/ \\
/ \\
/ \\
A /____________\\ C
''')
# найдем длины сторон по формуле расстояния между точками
ab = sqrt((x1-x2)**2 + (y1-y2)**2) # длина стороны ав
print('\nДлина стороны AB: ', ab)
bc = sqrt((x2-x3)**2 + (y2-y3)**2) # длина стороны bc
print('Длина стороны BC: ', bc)
ac = sqrt((x1-x3)**2 + (y1-y3)**2) # длина стороны ac
print('Длина стороны AC: ', ac)
# найдем наибольшую сторону => наибольший угол
p = (ab + bc + ac) / 2 # полупериметр
if ab == bc or ab == ac or (ab == bc and ab == ac): # равнобедренный или равносторонний треугольник
h = (2 * sqrt(p * (p - ab) * (p - bc) * (p - ac))) / ab
if bc == ac or bc == ab or (ab == bc and ab == ac): # равнобедренный или равносторонний треугольник
h = (2 * sqrt(p * (p - ab) * (p - bc) * (p - ac))) / bc
if ab > bc and ab > ac:
h = (2 * sqrt(p * (p - ab) * (p - bc) * (p - ac))) / ab
elif bc > ab and bc > ac:
h = (2 * sqrt(p * (p - ab) * (p - bc) * (p - ac))) / bc
else:
h = (2 * sqrt(p * (p - ab) * (p - bc) * (p - ac))) / ac
print('\nДлина высоты, проведенной из наибольшего угла равна ', h)
# определим нахождение точки относительно треугольника
x0, y0 = map(int, input('\nВведите координаты точки для проверки'). split())
# сразу заменим вычисления через уравнения прямых переменными
# для точки С и прямой АВ
m1 = (y0 - y1) * (x2 - x1) - (x0 - x1) * (y2 - y1)
m2 = (y3 - y1) * (x2 - x1) - (x3 - x1) * (y2 - y1)
# для точки B и прямой AC
n1 = (y0 - y1) * (x3 - x1) - (x0 - x1) * (y3 - y1)
n2 = (y2 - y1) * (x3 - x1) - (x2 - x1) * (y3 - y1)
# для точки A и прямой BC
k1 = (y0 - y2) * (x3 - x2) - (x0 - x2) * (y3 - y2)
k2 = (y1 - y2) * (x3 - x2) - (x1 - x2) * (y3 - y2)
if x0 == x1 and y0 == y1:
print('\nТочка совпадает с вершиной A')
elif x0 == x2 and y0 == y2:
print('\nТочка совпадает с вершиной B')
elif x0 == x2 and y0 == y2:
print('\nТочка совпадает с вершиной C')
else:
if m1 != 0 and m2 != 0 and m1 * m2 > 0:
if n1 != 0 and n2 != 0 and n1 * n2 > 0:
if k1 != 0 and k2 != 0 and k1 * k2 > 0:
print('\nТочка лежит внутри треугольника или лежит на его стороне')
# найдем площадь 3-х треугольников с вершинами на сторонах треугольника и на точке
s1 = abs((x2 - x1) * (y0 - y1) - (x0 - x1) * (y2 - y1)) / 2 # для а и в
s2 = abs((x3 - x2) * (y0 - y2) - (x0 - x2) * (y3 - y2)) / 2 # для b и c
s3 = abs((x3 - x1) * (y0 - y1) - (x0 - x1) * (y3 - y1)) / 2 # для A и c
# найдем их высоты и найдем среди них наибольшую
h1 = 2 * s1 / ab
h2 = 2 * s2 / bc
h3 = 2 * s3 / ac
if h1 == 0:
print('Точка лежит на стороне AB')
elif h2 == 0:
print('Точка лежит на стороне BC')
elif h3 == 0:
print('Точка лежит на стороне AC')
else:
if (h1 >= h2 and h1 > h3) or (h1 > h2 and h1 >= h3):
print('Расстояние от заданной точки до наиболее удаленной стороны треугольника равно ', h1)
elif (h2 >= h1 and h2 > h3) or (h2 > h1 and h2 >= h3):
print('Расстояние от заданной точки до наиболее удаленной стороны треугольника равно ', h2)
elif (h3 >= h1 and h3 > h2) or (h3 > h1 and h3 >= h2):
print('Расстояние от заданной точки до наиболее удаленной стороны треугольника равно ', h3)
elif h1 == h2 and h2 == h3:
print('Точка равноудалена от сторон треугольника')
else:
print('\nТочка не лежит внутри треугольника')
else:
print('\nТочка не лежит внутри треугольника')
|
f89edc2d4a13a522d2980e561017ae2c0542e9fc | plutmercury/OpenEduProject | /w05/task_w05e12.py | 855 | 3.96875 | 4 | # Дана строка. Выведите слово, которое в этой строке встречается чаще всего.
# Если таких слов несколько, выведите то, которое меньше в лексикографическом
# (алфавитном) порядке.
#
# Sample Input:
#
# apple orange banana banana orange
#
# Sample Output:
#
# banana
words = input().split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
count_word = {}
for word in word_count:
if word_count[word] in count_word:
count_word[word_count[word]].append(word)
else:
count_word[word_count[word]] = [word]
sorted_count_word = sorted(count_word, reverse=True)
print(sorted(count_word[sorted_count_word[0]])[0])
|
03e2b82c00d1b11ed410e5f17e62769eacf14956 | vhsw/CodeMasters_Tourney | /Python 3/chessKnight.py | 927 | 3.65625 | 4 | # Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.
# The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it.
# The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares.
def chessKnight(cell):
row = ord(cell[1])-ord('1')+1
column = ord(cell[0]) - ord('a') + 1
steps = [
[-2, -1], [-1, -2], [1, -2], [2, -1],
[2, 1], [1, 2], [-1, 2], [-2, 1]
]
answer = 0
for i in range(len(steps)):
tmpRow = row + steps[i][0]
tmpColumn = column + steps[i][1]
if (tmpRow >= 1 and tmpRow <= 8 and
tmpColumn >= 1 and tmpColumn <= 8):
answer += 1
return answer
|
9b6665f7499292214f365aa7395844881c060d4b | SkiMsyk/AtCoder | /BeginnerContest104/b.py | 298 | 3.609375 | 4 | s = list(input())
def conditionA(s_list):
return s[0] == "A"
def conditionC(s_list):
return "C" in s_list[2:-1]
def conditionLower(s_list):
return sum([e.isupper() for e in s_list]) == 2
if conditionA(s) and conditionC(s) and conditionLower(s):
print("AC")
else:
print("WA") |
7f188d0ab7afebe5db88e78549cd01705820f86f | FangShinDeng/LeetCodeLearning | /1047LeetCode刪除重複項.py | 273 | 3.859375 | 4 | def removeDuplicates(S: str) -> str:
stk = list()
for ch in S:
if stk != [] and stk[-1] == ch:
stk.pop()
else:
stk.append(ch)
return "".join(stk)
S = 'abbaca'
ans = removeDuplicates(S = S)
print('ans: ' + ans)
|
711c4e8ca5707482ec28ec16884609c4091650ec | zikingwang/data-structure-in-py | /search/search.py | 1,333 | 3.796875 | 4 | # -*- coding: utf-8 -*-
def index_of_min(lyst):
"""
Returns the index of the minnum item.
搜索列表的最小值
O(n)
:param lyst:
:return:
"""
min_index = 0
current_index = 1
while current_index < len(lyst):
if lyst[current_index] < lyst[min_index]:
min_index = current_index
current_index += 1
return min_index
def sequential_search(target, lyst):
"""
Returns the position of the target itrm if found, or -1 otherwise.
顺序搜索,如果找到返回目标索引,如果没找到,返回-1
O(n)
:param target:
:param lyst:
:return:
"""
position = 0
while position < len(lyst):
if target == lyst[position]:
return position
position += 1
return -1
def binary_search(target, sorted_lyst):
"""
Binary search need sourted list
二分查找算法
O(log2n)
:param target:
:param sorted_lyst:
:return:
"""
left = 0
right = len(sorted_lyst) - 1
while left <= right:
midpoint = (left + right) // 2
if target == sorted_lyst[midpoint]:
return midpoint
elif target < sorted_lyst[midpoint]:
right = midpoint - 1
elif target > sorted_lyst[midpoint]:
left = midpoint + 1
return -1
|
e4751dfd454d6817fd46084d1ce17ecbb0f599d7 | EphTron/neural-acw | /neural_acw_part1.py | 7,938 | 3.96875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import math
from math import floor
import random
def sigmoid(input_value):
return 1.0 / (1.0 + math.exp(-input_value))
def step_func(input_value):
return 0 if input_value > 0 else 1
class Perceptron:
def __init__(self, input_units, activation_function, learning_rate=0.05):
"""
Create simple perceptron with n inputs and one output.
Set an activation function and set learn rate
Weights and bias get set to a random value
:param input_units: int # Define the number of inputs needed
:param activation_function: function # Pass activation function f(x) = y
:param learning_rate: float # Define learning rate
"""
self.input_units = input_units
self.weights = [random.uniform(0.0, 1.0) for _ in range(input_units)]
self.bias = random.uniform(-1.0, 1.0)
self.learning_rate = learning_rate
self.activation_function = activation_function
def calc_output(self, inputs):
"""
Calculate output of perceptron
:param inputs: list # length of inputs must be equal to perceptron inputs
:return: float # return output
"""
if len(inputs) is self.input_units:
x = np.dot(np.array(self.weights), np.array(inputs)) + self.bias
return self.activation_function(x)
def train(self, inputs, target):
"""
Train perceptron with given inputs and adjust weights based on target.
:param inputs: list # length of inputs must be equal to perceptron inputs
:param target: float # wanted output of the perceptron
:return: float # returns difference between
"""
if len(inputs) is self.input_units:
# new_weights = [random.uniform(0.0, 1.0) for _ in range(input_units)]
output = self.calc_output(inputs)
error = target - output
# error = math.sqrt(pow(target - output, 2))
for idx, w in enumerate(self.weights):
self.weights[idx] = w + self.learning_rate * error * inputs[idx]
self.bias = self.bias + self.learning_rate * error
return output, error
def create_input_list(data, inputs, idx):
input_vec = []
if inputs > 1:
for i in reversed(range(1, inputs)):
input_vec.append(data[idx - i]) if (idx - i >= 0) else input_vec.append(0)
input_vec.append(data[idx])
return input_vec
def split_to_test_and_training(data, train_size=0.8, shuffle=True):
if shuffle:
random.shuffle(data)
split_idx = floor(len(data) * train_size)
trainings_set = data[:split_idx]
test_set = data[split_idx:]
return trainings_set, test_set
def main():
# read data and transform to list
xls_data = pd.ExcelFile("track.xls")
data = [x[0] for x in pd.Series.tolist(xls_data.parse('data1'))]
input_units, learn_rate = 10, 0.05
# activation = step_func
activation = sigmoid
ac_label = 'Activation f: Sigmoid'
in_label = 'Input units: ' + str(input_units)
lr_label = 'learn rate = ' + str(learn_rate)
# create perceptron with step function
perceptron = Perceptron(input_units, activation, learning_rate=learn_rate)
# show calculated output of perceptron after training
graphs = {'average-error': [], 'best': [], 'output': [], 'r-output': [], 'delta-error': [], 'o-before': [],
'e-before': [],
'o-after': [], 'e-after': [], 'test-error': []}
trainings_set, test_set = split_to_test_and_training(list(data), 0.80, True)
# assess output of data before training
for idx, val in enumerate(data):
input_vec = create_input_list(data, input_units, idx)
value = perceptron.calc_output(input_vec)
graphs['o-before'].append(value)
graphs['e-before'].append(abs(value - data[idx]))
graphs['r-output'].append(data[idx])
# setup parameters and train perceptron
best = 1
epoch_counter, epochs, error, running = 0, 250, 1, True
while epoch_counter < epochs and running:
# indices = list(range(len(data))) # when training with all data sets
indices = list(range(len(trainings_set))) # when using cross validation
random.shuffle(indices)
iter_count = 0
error_sum = 0
for idx in indices:
input_vec = create_input_list(trainings_set, input_units, idx)
value, error = perceptron.train(input_vec, trainings_set[idx])
error_sum += abs(error)
iter_count += 1
print(perceptron.weights)
graphs['average-error'].append(error_sum / len(trainings_set))
if (error_sum / len(trainings_set)) < best:
best = error_sum / len(trainings_set)
graphs['best'].append(best)
print('Epoch ', epoch_counter, ' Best ', best)
test_epoch_error = 0
indices = list(range(len(test_set)))
for idx in indices:
input_vec = create_input_list(test_set, input_units, idx)
value = perceptron.calc_output(input_vec)
error = abs(test_set[idx] - value)
test_epoch_error += error
graphs['test-error'].append(test_epoch_error / len(test_set))
epoch_counter += 1
# show calculated output of perceptron after training
for idx, val in enumerate(data):
input_vec = create_input_list(data, input_units, idx)
value = perceptron.calc_output(input_vec)
graphs['o-after'].append(value)
graphs['e-after'].append(abs(value - data[idx]))
print()
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.title.set_text('Neuron Output before Training')
ax1.set(xlabel='Samples of track.xls', ylabel='Predicted Position')
ax1.grid()
ax1.plot(graphs['e-before'], 'r')
ax1.plot(graphs['o-before'], 'b')
ax1.plot(graphs['r-output'], 'black')
ax2.title.set_text('Neuron Output after Training (' + str(epochs) + ' Epochs)')
ax2.set(xlabel='Samples of track.xls', ylabel='Predicted Position')
ax2.grid()
ac = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0, label=ac_label)
iu = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0, label=in_label)
lr = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0, label=lr_label)
p1, = ax2.plot(graphs['e-after'], 'r', label='Error')
p3, = ax2.plot(graphs['r-output'], 'black', label='Real Position')
p2, = ax2.plot(graphs['o-after'], 'b', label='Predicted Position')
ax2.legend([ac, iu, lr, p2, p3, p1],
[ac_label, in_label, lr_label, 'Predicted Position', 'Real Position', 'Error'], prop={'size': 14})
# setup plots for errors
f2, (ax1) = plt.subplots(1, 1, sharey=True)
ax1.title.set_text('ACW I: Neuron Average Error Improvement')
ax1.set(xlabel='Epochs', ylabel='Avg. Error in Epoch')
ax1.grid()
ac = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0, label=ac_label)
iu = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0, label=in_label)
lr = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0, label=lr_label)
test_set_err_plot, = ax1.plot(graphs['test-error'], 'grey', label='Avg. Error of Test Set')
best_error, = ax1.plot(graphs['best'], 'g', label='Lowest NN Error')
avg_error, = ax1.plot(graphs['average-error'], 'r', label='Avg. Error of Epoch')
ax1.legend([ac, iu, lr, avg_error, test_set_err_plot, best_error],
[ac_label, in_label, lr_label, 'Avg. Error of Training Set', 'Avg. Error of Test Set',
'Lowest NN Error'], prop={'size': 14})
plt.show()
if __name__ == "__main__":
main()
|
71c72cedb6bee19ab5eab50e25c47b631cf9ceee | excid3/neon | /apps/graph_app.py | 1,064 | 3.71875 | 4 | import random
from neon import NeonApp
class GraphApp(NeonApp):
"""This is a simple example application that draws 6 moving bar graphs"""
def on_init(self):
self.graphs = [400, 1000, 600, 900, 800, 1200]
self.colors = [(0.1, 0.8, 0.1),
(0.8, 0.1, 0.1),
(0.8, 0.8, 0.1),
(0.8, 0.8, 0.8),
(0.1, 0.8, 0.8),
(0.1, 0.1, 0.8)]
def on_draw(self):
# Add a little change to each
for i in range(0, len(self.graphs)):
v = self.graphs[i] + random.randint(-10, 10)
if v < 0: v = 0
elif v > self.h: v = self.h
self.graphs[i] = v
# GRAPH!
for i, v in enumerate(self.graphs):
self.draw_polygon((
self.x + 525*i + 200, self.y,
self.x + 525*i + 200, self.y + v,
self.x + 525*i + 600, self.y + v,
self.x + 525*i + 600, self.y),
color=self.colors[i]
)
|
ef0b1b6e9def3922934ad312e26291aee43bd73e | eladkehat/soong | /soong/dml.py | 3,442 | 3.640625 | 4 | """SQL DML (data manipulation language) helper functions that minimize boilerplate code.
These functions support the most common scenarios of data manipulation - insert, update and delete,
while saving you from writing the boilerplate code around connections and cursors, or even writing
the SQL itself.
"""
from typing import Any, Dict, List, Tuple, Union
import psycopg2
def insert(conn: psycopg2.extensions.connection,
table: str,
values: Dict[str, Any],
returning: Union[None, str, List[str]] = None) -> Union[None, Any, Tuple[Any]]:
"""Insert a new row into the table.
Args:
conn: An open database connection object.
table: The table name.
values: A dict that maps column names to their new values.
returning: The name of a column whose new value you wish to return,
or a list of of such column names.
Returns:
A row with the columns specified in `returning` and their values,
or None if `returning` is None.
"""
result = None
keys = list(values.keys())
interpolations = dict(
table=table,
cols=', '.join(keys),
values=', '.join([f'%({key})s' for key in keys]))
if returning:
returning_clause = 'RETURNING {}'.format(
returning if isinstance(returning, str)
else ', '.join(str(col) for col in returning))
interpolations['returning'] = returning_clause
else:
interpolations['returning'] = ''
sql = 'INSERT INTO {table} ({cols}) VALUES ({values}) {returning};'.format(**interpolations)
with conn:
with conn.cursor() as cursor:
cursor.execute(sql, values)
if returning:
result = cursor.fetchone()
if result and len(result) == 1:
result = result[0]
return result
def update(conn: psycopg2.extensions.connection, table: str, id: Any, values: Dict[str, Any]) -> None:
"""Update the row with the given id using the values.
Use this function on tables with an indexed column (like a primary key) called `id`,
when you would like to update some columns in a row whose id you know.
Args:
conn: An open database connection object.
table: The table name.
id: Searches for this value in the `id` column.
values: A dict that maps column names for update to their new values.
"""
keys = list(values.keys())
sql = 'UPDATE {table} SET {values} WHERE id = %s;'.format(
table=table,
values=', '.join(f'{key} = %s' for key in keys))
params = tuple([values[key] for key in keys] + [id])
with conn:
with conn.cursor() as cursor:
cursor.execute(sql, params)
def execute(
conn: psycopg2.extensions.connection, sql: str, params: Tuple, returning: bool = False
) -> Union[Any, None]:
"""Execute an arbitrary SQL statement.
Args:
conn: An open database connection object.
sql: The DML SQL statement to execute.
params: Parameters that go with the SQL.
returning: Whether the SQL statements contains a RETURNING clause.
Returns:
If returning is True, returns the row with the values that the SQL specified.
"""
result = None
with conn:
with conn.cursor() as cursor:
cursor.execute(sql, params)
if returning:
result = cursor.fetchone()
return result
|
0558be126544b48654f350b2ee573a9b9e03853a | ekmahama/Mircosoft | /backtracking/wordSearchII.py | 1,349 | 3.734375 | 4 | class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
def backtrack(board, i, j, word):
if len(word) == 0:
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return False
if board[i][j] != word[0]:
return False
board[i][j] = '#'
ret = False
for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
ret = backtrack(board, x+i, y+j, word[1:])
if ret:
break
board[i][j] = word[0]
return ret
result = []
for word in words:
found = False
for i in range(len(board)):
for j in range(len(board[0])):
if not backtrack(board, i, j, word):
continue
result.append(word)
found = True
break
if found:
break
return result
board = [["o", "a", "a", "n"], ["e", "t", "a", "e"],
["i", "h", "k", "r"], ["i", "f", "l", "v"]]
words = ["oath", "pea", "eat", "rain"]
r = Solution().findWords(board, words)
print()
|
a1e1e9fac578d8f1339a85c64afe5a537a8d97e6 | SymJAX/SymJAX | /docs/auto_examples/01_nns/plot_comparison.py | 5,492 | 3.65625 | 4 | """
Image classification, Keras and SymJAX
======================================
example of image classification with deep networks using Keras and SymJAX
"""
import symjax.tensor as T
from symjax import nn
import symjax
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.setrecursionlimit(3500)
def classif_tf(train_x, train_y, test_x, test_y, mlp=True):
import tensorflow as tf
from tensorflow.keras import layers
batch_size = 128
inputs = layers.Input(shape=(3, 32, 32))
if not mlp:
out = layers.Permute((2, 3, 1))(inputs)
out = layers.Conv2D(32, 3, activation="relu")(out)
for i in range(3):
for j in range(3):
conv = layers.Conv2D(
32 * (i + 1), 3, activation="linear", padding="SAME"
)(out)
bn = layers.BatchNormalization(axis=-1)(conv)
relu = layers.Activation("relu")(bn)
conv = layers.Conv2D(
32 * (i + 1), 3, activation="linear", padding="SAME"
)(relu)
bn = layers.BatchNormalization(axis=-1)(conv)
out = layers.Add()([out, bn])
out = layers.AveragePooling2D()(out)
out = layers.Conv2D(32 * (i + 2), 1, activation="linear")(out)
print(out.shape)
out = layers.GlobalAveragePooling2D()(out)
else:
out = layers.Flatten()(inputs)
for i in range(6):
out = layers.Dense(4000, activation="linear")(out)
bn = layers.BatchNormalization(axis=-1)(out)
out = layers.Activation("relu")(bn)
outputs = layers.Dense(10, activation="linear")(out)
model = tf.keras.Model(inputs, outputs)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
for epoch in range(5):
accu = 0
for x, y in symjax.data.utils.batchify(
train_x, train_y, batch_size=batch_size, option="random"
):
with tf.GradientTape() as tape:
preds = model(x, training=True)
loss = tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(y, preds)
)
accu += tf.reduce_mean(tf.cast(y == tf.argmax(preds, 1), "float32"))
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
print("training", accu / (len(train_x) // batch_size))
accu = 0
for x, y in symjax.data.utils.batchify(
test_x, test_y, batch_size=batch_size, option="continuous"
):
preds = model(x, training=False)
accu += tf.reduce_mean(tf.cast(y == tf.argmax(preds, 1), "float32"))
print(accu / (len(test_x) // batch_size))
def classif_sj(train_x, train_y, test_x, test_y, mlp=True):
symjax.current_graph().reset()
from symjax import nn
batch_size = 128
input = T.Placeholder((batch_size, 3, 32, 32), "float32")
labels = T.Placeholder((batch_size,), "int32")
deterministic = T.Placeholder((), "bool")
if not mlp:
out = nn.relu(nn.layers.Conv2D(input, 32, (3, 3)))
for i in range(3):
for j in range(3):
conv = nn.layers.Conv2D(out, 32 * (i + 1), (3, 3), pad="SAME")
bn = nn.layers.BatchNormalization(
conv, [1], deterministic=deterministic
)
bn = nn.relu(bn)
conv = nn.layers.Conv2D(bn, 32 * (i + 1), (3, 3), pad="SAME")
bn = nn.layers.BatchNormalization(
conv, [1], deterministic=deterministic
)
out = out + bn
out = nn.layers.Pool2D(out, (2, 2), pool_type="AVG")
out = nn.layers.Conv2D(out, 32 * (i + 2), (1, 1))
# out = out.mean((2, 3))
out = nn.layers.Pool2D(out, out.shape.get()[-2:], pool_type="AVG")
else:
out = input
for i in range(6):
out = nn.layers.Dense(out, 4000)
out = nn.relu(
nn.layers.BatchNormalization(out, [1], deterministic=deterministic)
)
outputs = nn.layers.Dense(out, 10)
loss = nn.losses.sparse_softmax_crossentropy_logits(labels, outputs).mean()
nn.optimizers.Adam(loss, 0.001)
accu = T.equal(outputs.argmax(1), labels).astype("float32").mean()
train = symjax.function(
input,
labels,
deterministic,
outputs=[loss, accu, outputs],
updates=symjax.get_updates(),
)
test = symjax.function(input, labels, deterministic, outputs=accu)
for epoch in range(5):
accu = 0
for x, y in symjax.data.utils.batchify(
train_x, train_y, batch_size=batch_size, option="random"
):
accu += train(x, y, 0)[1]
print("training", accu / (len(train_x) // batch_size))
accu = 0
for x, y in symjax.data.utils.batchify(
test_x, test_y, batch_size=batch_size, option="continuous"
):
accu += test(x, y, 1)
print(accu / (len(test_x) // batch_size))
mnist = symjax.data.cifar10()
train_x, train_y = mnist["train_set/images"], mnist["train_set/labels"]
test_x, test_y = mnist["test_set/images"], mnist["test_set/labels"]
train_x /= train_x.max()
test_x /= test_x.max()
# classif_sj(train_x, train_y, test_x, test_y, False)
# classif_tf(train_x, train_y, test_x, test_y, False)
|
5a1358311cbb0bdc66db0346198758492b3f9355 | rohan9769/Python-Coding-and-Practice | /PythonBasicPractice/41.Tuples 2.py | 197 | 3.859375 | 4 | my_tuple = (1,2,3,4,5)
new_tuple = my_tuple[1:2]
print(new_tuple)
x,y,z,*other = (6,7,8,9,10,11)
print(other)
#Tuple Methods
print(my_tuple.count(3))
print(my_tuple.index(4))
print(len(my_tuple)) |
f22d7bc8f70fafc2f801c74c343b99369a9f27d7 | joelapsansky/election-analysis | /Python_practice.py | 5,980 | 4.53125 | 5 | print("Hello World")
counties = ["Arapahoe", "Denver", "Jefferson"]
if counties[1] == "Denver":
print(counties[1])
# This will give an index error so comment out
if counties[3] != 'Jefferson':
print(counties[2])
# Break
temperature = int(input("What is the temperature outside?"))
if temperature > 80:
print("Turn on the AC.")
else:
print("Open the windows.")
# What is the score?
score = int(input("What is your test score?"))
# Determine the grade
if score >= 90:
print('Your grade is an A.')
else:
if score >= 80:
print('Your grade is a B.')
else:
if score >= 70:
print('Your grade is a C.')
else:
if score >= 60:
print('Your grade is a D.')
else:
print('Your grade is an F.')
# if-elif-else statements are better sometimes
# Determine the grade.
if score >= 90:
print('Your grade is an A.')
elif score >= 80:
print('Your grade is a B.')
elif score >= 70:
print('Your grade is a C.')
elif score >= 60:
print('Your grade is a D.')
else:
print('Your grade is an F.')
# Determine if "El Paso" is in the counties list
if "El Paso" in counties:
print("El Paso is in the list of counties.")
else:
print("El Paso is not in the list of counties.")
# Break
if "Arapahoe" in counties or "El Paso" in counties:
print("Arapahoe or El Paso are in the list of counties.")
else:
print("Arapahoe or El Paso is not in the list of counties.")
# Another check
if "Arapahoe" in counties and "El Paso" not in counties:
print("Only Arapahoe is in the list of counties.")
else:
print("Arapahoe is in the list of counties and El Paso is not in the list of counties.")
# Repetition practice
x = 0
while x <= 5:
print(x)
x = x + 1
# Iterate through list of counties... I had county, but I changed it to "i" to see if it would work (it does, and the iterator doesn't matter here)
for i in counties:
print(i)
# Basically, i is the variable, and the for loop is setting it each time
# Using Range
numbers = [0, 1, 2, 3, 4]
for num in numbers:
print(num)
# Don't do above, do this:
for num in range(5):
print(num)
# Interesting - if I just print num, it gives me "4" because num = 4 is the last stored variable
# Indexing... just remember that 'i' is a variable here. I is used for symplicity, but any variable can be used.
for i in range(len(counties)):
print(counties[i])
# Iterate through a tuple the same way
counties_tuple = ("Arapahoe","Denver","Jefferson")
counties_tuple
for ctys in range(len(counties_tuple)):
print(counties_tuple[ctys])
# Practice to answer question
for i in range(len(counties_tuple)):
print(counties_tuple[i])
for founty in counties_tuple:
print(founty)
# Iterate through dictionaries
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
for county in counties_dict:
print(county)
for county in counties_dict.keys():
print(county)
print(counties_dict.keys())
for voters in counties_dict.values():
print(voters)
# Both of these give the values
for county in counties_dict:
print(counties_dict.get(county))
for county in counties_dict:
print(counties_dict[county])
# Key Values
for county, voters in counties_dict.items():
print(county, voters)
# Skill drill
for county, voters in counties_dict.items():
print(str(county) + " county has " + str(voters) + " registerd voters.")
# Get dictionaries in a list of dictionaries
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"county":"Jefferson", "registered_voters": 432438}]
for county_dict in voting_data:
print(county_dict)
for i in range(len(voting_data)):
print(voting_data[i])
for i in range(len(voting_data)):
print(i)
for county_dict in voting_data:
for value in county_dict.values():
print(value)
# This doesn't work because it prints every value as a list
for county_dict in voting_data:
print(county_dict.values())
# This doesen't work because you're not using the values method after county_dict
for county_dict in voting_data:
for value in county_dict:
print(value)
# This doesn't work because it will print every value from each dictionary
for county_dict in voting_data:
for key, value in county_dict.items():
print(value)
# This gives you just the values
for county_dict in voting_data:
print(county_dict['registered_voters'])
# This gives us just the keys of the dictionaries
for county_dict in voting_data:
print(county_dict['county'])
# f strings
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What is the total votes in the election? "))
percentage_votes = (my_votes / total_votes) * 100
print("I received " + str(percentage_votes)+"% of the total votes.")
# New
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What is the total votes in the election? "))
print(f"I received {my_votes / total_votes * 100}% of the total votes.")
message_to_candidate = (
f"You received {my_votes:,} number of votes. "
f"The total number of votes in the election was {total_votes:,}. "
f"You received {my_votes / total_votes * 100:.2f}% of the total votes.")
print(message_to_candidate)
# Skill drill
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
for county, voters in counties_dict.items():
message = (f"{county} county has {voters:,} registered voters.")
print(message)
# Skill drill 2
voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}]
for count_dict in voting_data:
my_message = (f"{count_dict['county']} county has {count_dict['registered_voters']:,} registered voters.")
print(my_message)
|
ba350761e59eb2c8ada4590d245e68d107f00a5c | RahulBalu31/Python-projects | /division.py | 117 | 4 | 4 | num = int(input("Enter a Number :"))
if(num%6==0):
print("Yes")
else:
print("No")
|
4d6c46f0d4bd91c13fd6f8b6c2fe134e35d460e1 | xndong/ML-foundation-and-techniques | /Decision stump/old_compute_gini_and_information_gain.py | 4,226 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
@author: Dong Xiaoning
"""
# compute information gain from gini index or entrophy
'''
gini index and entrophy---> measure the impurity of a group.
In two or more groups(eg a dataset is splited into two groups),
we weightly add gini index from coresponding group together to compute information gain.
'''
import numpy as np
import operator
import collections
import sklearn.datasets
def compute_gini(data,label,row_index):
m,n = data.shape
assert row_index <= m and row_index >= 0,'row index is out of boundary'
group1 = label[:row_index]
group2 = label[row_index:]
dict_group1 = collections.Counter(group1)
dict_group2 = collections.Counter(group2)
group1_size = float(row_index)
group2_size = m - float(row_index)
# group1's gini and weight
if group1_size == 0:
gini_group1 = 0
else:
proportion1 = np.array(list(dict_group1.values()))/group1_size
gini_group1 = 1 - np.dot(proportion1,proportion1)
weight_group1 = group1_size / m
# group2's gini and weight
if group2_size == 0:
gini_group2 = 0
else:
proportion2 = np.array(list(dict_group2.values()))/group2_size
gini_group2 = 1 - np.dot(proportion2,proportion2)
weight_group2 = group2_size / m
# total gini of two groups
gini_index = gini_group1 * weight_group1 + gini_group2 * weight_group2
return gini_index
def compute_gini_2(data,label,row_index):
m,n = data.shape
assert row_index <= m and row_index >= 0,'row index is out of boundary'
categories = list(set(label))
group1 = label[:row_index]
group2 = label[row_index:]
group1_size = float(row_index)
group2_size = m - float(row_index)
# group1' gini
if group1_size == 0:
gini_group1 = 0
else:
proportion = []
for category in categories:
mask = group1 == category
count, = group1[mask].shape
proportion.append(count/group1_size)
proportion = np.array(proportion)
gini_group1 = 1 - np.dot(proportion,proportion)
weight_group1 = group1_size / m
# group2's gini and weight
if group2_size == 0:
gini_group2 = 0
else:
proportion = []
for category in categories:
mask = group2 == category
count, = group2[mask].shape
proportion.append(count/group2_size)
proportion = np.array(proportion)
gini_group2 = 1 - np.dot(proportion,proportion)
weight_group2 = group2_size / m
# total gini of two groups and weight
gini_index = gini_group1 * weight_group1 + gini_group2 * weight_group2
return gini_index
# compute information gain from gini index or entrophy
#
# information gain = gini(group) - [gini(subgroup_one)* weight + gini(subgroup_two)* weight ]
#
# weight = subgroup / group
#
# weighted gini: gini(subgroup_one)* weight
#
# when we split one group into two or more subgroups, we use information gain to describe/measure这个过程中purity or impurity的变化。
def compute_information_gain(gini_group,gini_two_groups):
return gini_group - gini_two_groups
if __name__ == '__main__':
breast_dataset = sklearn.datasets.load_breast_cancer()
breast_data = breast_dataset.data
m,n = breast_data.shape
breast_label =breast_dataset.target
# compute gini index of group
dict_label = collections.Counter(breast_label)
proportion = np.array(list(dict_label.values())) / m
gini_group = 1 - np.dot(proportion,proportion)
# compute gini index of splited data(i.e. two groups)
gini_index_dict = {}
for i in range(m): # 这只是自上而下一行行地split。理论上你可以随意shuffle,split--->所以有 C(m,0) + C(m,1) + C(m,2) +...+ C(m,m-1) + C(m,m)种split
gini_index = compute_gini(breast_data,breast_label,i)
gini_index_dict[i] = gini_index
least_gini_index,least_gini_value = min(gini_index_dict.items(),key=operator.itemgetter(1))
largest_info_gain = gini_group - least_gini_value
print(f'largest info gain is: {largest_info_gain}, index is: {least_gini_index}')
|
cf24e6acc35ab91e205abc1cca8837cd28ca2d3a | kkkansal/FSDP_2019 | /DAY 03/answer/teen_cal.py | 1,346 | 3.875 | 4 | """
Code Challenge
Name:
Teen Calculator
Filename:
teen_cal.py
Problem Statement:
Take dictionary as input from user with keys, a b c, with some integer
values and print their sum. However, if any of the values is a teen --
in the range 13 to 19 inclusive -- then that value counts as 0, except
15 and 16 do not count as a teens. Write a separate helper "def
fix_teen(n):"that takes in an int value and returns that value fixed for
the teen rule. In this way, you avoid repeating the teen code 3 times
Input:
{"a" : 2, "b" : 15, "c" : 13}
Output:
Sum = 17
"""
def fix_teen(number):
teen_list = [13,14,17,18,19]
if number in teen_list:
return 0
else:
return number
def no_teen_sum ( dictionary ):
list_of_numbers = dictionary.values()
Sum = 0
for number in list_of_numbers:
Sum += fix_teen ( number )
return Sum
user_input = input("Enter the dictionary input")
splitted_string = user_input.split(',')
splitted_string[0] = splitted_string[0][1:]
splitted_string[len(splitted_string)-1] =splitted_string[len(splitted_string)-1][0:-1]
dictionary = {}
for i in splitted_string:
i = i.split(':')
i[0] = i[0].replace('"','')
i[1] = int(i[1])
dictionary[i[0]] = i[1]
print("Sum = " + str(no_teen_sum ( dictionary )))
|
4966b9b8544ce2cc9f88e9470c04fa95487243a8 | sjraaijmakers/informatica | /Programmeertalen/python2/LS.py | 5,732 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# Student: Steven Raaijmakers
# Number: 10804242
# Desc: Programma tekent figuur op basis van het Lindenmayer systeem
#
from graphics import *
from math import sin, cos, pi
class LS:
def __init__(self, defstep, defangle):
self.rules = {}
self.axiom = 0
self.defstep = defstep
self.defangle = defangle
def setAxiom(self, ax):
self.axiom = ax
def addRule(self, letter, word):
self.rules[letter] = word
# Replace each letter out of axiom if there exists a rule for it
def generate(self, n):
axiom = self.axiom
for x in range(0, n):
newax = ""
for y in axiom:
if y in self.rules:
newax = newax + self.rules[y]
else:
newax = newax + y
axiom = newax
return axiom
def __repr__(self):
toPrint = "LS(" + str(self.defstep) + ", " + str(self.defangle) + ", " + "\"" + self.axiom + "\"" + ", " + str(self.rules) + ")"
return toPrint
class TurtleState:
def __init__(self, pos, step, angle, width):
self.pos = pos
self.step = step
self.angle = angle
self.width = width
# Clone (?)
def clone(self):
clone = TurtleState(self.pos, self.step, self.angle, self.width)
return clone
def __repr__(self):
toPrint = str(self.pos) + ", " + str(self.step) + ", " + str(self.angle) + ", " + str(self.width)
return toPrint
# Stack list, used to draw banches
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
self.stack.pop()
# Filter axiom, return letters with their associated paramaters
def parseWord(word, startIndex):
c = word[startIndex]
if startIndex < len(word) - 1: # if is not latest letter
if word[startIndex + 1] == "(":
for i in range(startIndex + 2, len(word)):
if word[i] == ")":
par = float(word[startIndex + 2:i])
return c, par, i + 1
else:
par = None
else:
par = None
pastIndex = startIndex + 1
return c, par, pastIndex
# Draw function
class Turtle:
def __init__(self, win, defwidth):
self.window = win
self.width = defwidth
self.s = Stack()
# declare values (so they can be configured)
self.lsys = None
self.angle = 0
self.length = 0
self.startx = 0
self.starty = 0
def stepPenUp(self):
self.step(False)
def stepPenDown(self):
self.step(True)
def step(self, isPenDown):
# Calculate end point, based on pythagoras' algorithm
self.endx = self.startx + (sin(self.angle) * self.length) #sos
self.endy = self.starty + (cos(self.angle) * self.length) #cas
# Make new line based on 2 points
self.p1 = Point(self.startx, self.starty)
self.p2 = Point(self.endx, self.endy)
# Update startpoint to old endpoint
self.startx = self.endx
self.starty = self.endy
# Draw line
if isPenDown == True:
line = Line(self.p1, self.p2)
line.setWidth(self.width)
line.draw(self.window)
def left(self):
self.angle = self.angle - self.lsys.defangle
def right(self):
self.angle = self.angle + self.lsys.defangle
def scale(self, scale):
if scale != None:
x = scale
elif scale == None: # thicker line
x = 2
elif scale == -1:
x = 0.5 # smaller line
self.width = self.width * x
self.length = self.length * x
def push(self):
# Put position in Point
pos = Point(self.startx, self.starty)
# Put state into stack
t = TurtleState(pos, self.length, self.angle, self.width)
self.s.push(t.clone())
def pop(self):
# Return lasts item in stack
clone = self.s.stack.pop()
# Put returned values in Turtle
self.startx = clone.pos.x
self.starty = clone.pos.y
self.length = clone.step
self.angle = clone.angle
self.width = clone.width
def drawLS(self, lsys, n, startx, starty, startangle):
# Default values
self.lsys = lsys
self.length = lsys.defstep
# Start & Draw first line
self.startx = startx
self.starty = starty
self.angle = - startangle
self.right()
# Execute associated action for each letter in generated word
i = 0
while i < len(lsys.generate(n)):
c, par, i = parseWord(lsys.generate(n), i)
if c == "F":
self.stepPenDown()
elif c == "f":
self.stepPenUp()
elif c == "+":
self.left()
elif c == "-":
self.right()
elif c == "[":
self.push()
elif c == "]":
self.pop()
elif c == "\"":
self.scale(par)
elif c == "\'":
self.scale(-1)
# Execution
if __name__=='__main__':
win = GraphWin('Lindenmayer System', 400, 400)
win.yUp()
ls = LS(3,pi/2)
ls.setAxiom('F-F-F-F')
ls.addRule('F','F-F+F+FF-F-F+F')
print ls
print ls.generate(1)
t = Turtle(win, 1)
t.drawLS(ls, 3, 100, 100, pi/2)
tree = LS(80,pi/2)
tree.setAxiom('"(1.5)FFA')
tree.addRule('A', '"(0.687)[+FA][-FA]')
t2 = Turtle(win, 12)
t2.drawLS(tree, 10, 200, 30, pi/2)
win.promptClose(win.getWidth()/2,20)
|
d8f860240cff0ade0950173dca7eeb29e6181e04 | gunzigun/Python-Introductory-100 | /12.py | 616 | 3.859375 | 4 | # -*- coding: UTF-8 -*-
"""
题目:判断101-200之间有多少个素数,并输出所有素数。
程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。
"""
from math import sqrt
nAllNum = 0
for num in range(101,201):
nNumqrt = int(sqrt(num+1))
isSu = True
for i in range(2,nNumqrt+1):
if num % i == 0:
isSu = False
break
if isSu:
nAllNum += 1
print num
if nAllNum % 10 == 0:
print ''
print 'The total is %d' % nAllNum
|
2f5df7a655a39a7b305d5b33382197059bae02e0 | panyanyany/Python_100_Exercises | /exercises_011_to_020/016/m3.py | 288 | 3.78125 | 4 | score = int(input('输入成绩:'))
# 仅对 Python 3.7 及以上版本有效
standard = {
90: 'A',
60: 'B',
0: 'C',
}
grade = None
for key_score in standard:
if score >= key_score:
grade = standard[key_score]
break
print('%d 属于 %s' % (score, grade))
|
6c8856de70f85b1cdae1d07edca7771cc4c80f3c | serosc95/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 211 | 3.578125 | 4 | #!/usr/bin/python3
""" Module """
import json
def save_to_json_file(my_obj, filename):
""" Function save_to_json_file """
with open(filename, 'w') as myFile:
myFile.write(json.dumps(my_obj))
|
5467db72b7d48e677fa07200179c5dbd657974ee | aumit210780/Practice-Python | /Sequences and for loop.py | 146 | 3.6875 | 4 | data = [1,2,3,4,5]
for i in range(0,len(data)):
print(data[i])
data2 = "Hello"
print()
for i in range(0,len(data2)):
print(data2[i]) |
e5e17a3e91c4d88b6220b830b1f2dc54d37ff7e7 | 4ndrewJ/CP1404_Practicals | /prac_03/password_check.py | 714 | 4.09375 | 4 | """
Password check program from prac 3 CP1404
"""
MIN_LENGTH = 8
def main():
"""
Tests get_password() and print_password_asterisks()
"""
password = get_password()
print_password_asterisks(password)
def print_password_asterisks(password):
"""
Prints asterisks of same length as password
"""
print('*' * len(password))
def get_password():
"""
Prompts user for password until entered len(password) >= MIN_LENGTH
Returns the password
"""
password = input('Enter Password: ')
while len(password) < MIN_LENGTH:
print(f'Password must have length of at least {MIN_LENGTH}')
password = input('Enter Password: ')
return password
main()
|
867ba60789651014d061517b4fd178ad8c5e6c78 | yibwu/box | /max_two_sum.py | 452 | 4.0625 | 4 | def max_two_sum1(x, y, z):
if x < y and x < z:
return y + z
if y < x and y < z:
return x + z
if z < x and z < y:
return x + y
# beautiful and elegant
def max_two_sum2(x, y, z):
if x < y and x < z:
return y + z
else:
return max_two_sum2(y, z, x)
if __name__ == '__main__':
x, y, z = 2, 1, 3
ret = max_two_sum1(x, y, z)
print(ret)
ret = max_two_sum2(x, y, z)
print(ret)
|
b4e216e8e03dee354dc734b5d21da38c460d02dd | takadhi1030/class-sample | /customer.py | 538 | 3.765625 | 4 | class Customer:
def __init__(self, first_name, family_name, age):
self.first_name = first_name
self.family_name = family_name
self.age = age
def full_name(self):
return self.first_name + self.family_name
def display_profil(self):
print(f"Name: {self.full_name()}, Age: {self.age}")
if __name__ == "__main__":
Tom = Customer("Tom", "Ford", 57)
Ken = Customer("Ken", "Yokoyama", 49)
Tom.display_profil() # "Name: Tom Ford, Age: 57"と出力する
Ken.display_profil()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.