blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
032107e7803703a94b9a81e1508bdaa3030e2c5c | dxe4/project_euler | /python/7.py | 472 | 3.8125 | 4 | '''
Also read:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Probably better than bforce?
'''
def is_prime(n):
if n < 2:
return False
elif n == 2:
return True
else:
for i in range(2, int(n / 2) + 1, 1):
if n % i == 0:
return False
return True
current = 3
count = 1
while True:
if is_prime(current):
count += 1
if count == 10001:
break
current += 1
print(current)
|
ae5807bc71a45643fa6ac2c830a6aa75e60f31ee | adamorhenner/Fundamentos-programacao | /exercicios/exercicio-8.py | 220 | 4.03125 | 4 | #8. Faça um programa que lê um número inteiro, o incrementa em 1 e exibe o resultado
print("====== Incremento do numero ======")
x = (int)(input("Digite um numero inteiro"))
x += 1
print("o valor do incremento eh", x) |
719cb4e6b2c0042354680dbf019a58ff4dae652b | steveSuave/practicing-problem-solving | /turtle-graphics/pyth-with-angle-input.py | 923 | 3.9375 | 4 | import turtle
import math
def square(side):
for i in range(4):
turtle.forward(side)
turtle.left(90)
def pyth(length, depth, angle):
# make sure the output will resemble a tree
if angle>83: angle%=83
if angle<0 : angle=-angle
if angle<7 : angle*=7
square(length)
if depth==1:
return
turtle.left(90)
turtle.forward(length)
turtle.right(angle)
pyth(length*math.cos((90-angle)*math.pi/180),depth-1, angle)
turtle.forward(length*math.cos((90-angle)*math.pi/180))
turtle.right(90)
pyth(length*math.sin((90-angle)*math.pi/180),depth-1, angle)
turtle.left(90)
turtle.backward(length*math.cos((90-angle)*math.pi/180))
turtle.left(angle)
turtle.backward(length)
turtle.right(90)
turtle.up()
turtle.goto(-100,-300)
turtle.down()
turtle.pensize(4)
turtle.speed(0)
turtle.shape("turtle")
turtle.color("green")
pyth(100, 7, 32)
|
e6960a989543cec8f79c0ae759ef03e1d44036d2 | gigix/machine-learning-specialization | /course-3/module-3-probability.py | 334 | 3.5 | 4 | import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
for n in [2.5, 0.3, 2.8, 0.5]:
print('{0} - {1}'.format(n, sigmoid(n)))
print sigmoid(2.5) * (1 - sigmoid(0.3)) * sigmoid(2.8) * sigmoid(0.5)
print 2.5 * (1 - sigmoid(2.5)) + 0.3 * (0 - sigmoid(0.3)) + \
2.8 * (1 - sigmoid(2.8)) + 0.5 * (1 - sigmoid(0.5))
|
1e6b3e564091cd78959dbe936040dd9aa9365f3d | Ph0enixxx/PyDict | /App.py | 152 | 3.53125 | 4 | from Data import Data
def display(Data):
print("type the word:",end="")
print(Data(input()))
if __name__ == '__main__':
while True:
display(Data) |
9274ea0543c6f61d6a056d2ee5f176d6cf7d5313 | BillyDevEnthusiast/Programming-with-Python | /Python Fundamentals/Regular Expressions/02_match_phone_number.py | 146 | 3.5625 | 4 | import re
pattern = r"(\+359-2-\d{3}-\d{4}|\+359 2 \d{3} \d{4})\b"
text = input()
phones = re.findall(pattern, text)
print(", ".join(phones))
|
d85f9cbccb242a6912e8e3a17d2492eb90719744 | nehavari/beginnerspython | /src/sorting/quicksort.py | 1,409 | 4.09375 | 4 | """
Time Complexity: Worst case time complexity is O(N2) and average case time complexity is O(N*logN)
Auxiliary Space: O(1)
"""
import random
def partition(start, end, nums):
"""
output of partition is =>
1. pivot has moved to its correct position in sorted array
2. all the elements left to pivot are smaller than pivot
and all the elements right to pivot are greater than pivot
"""
pivot = random.randrange(start, end + 1)
nums[pivot], nums[end] = nums[end], nums[pivot]
pivot = start
for index in range(start, end): # it will not go till end because end contains nothing but pivot
if nums[index] <= nums[end]:
nums[pivot], nums[index] = nums[index], nums[pivot]
pivot += 1
nums[pivot], nums[end] = nums[end], nums[pivot]
return pivot
def quicksort(start, end, nums):
if start >= end:
return
pivot = partition(start, end, nums)
quicksort(start, pivot - 1, nums)
quicksort(pivot + 1, end, nums)
def main():
nums = [100, 56, 34, 56, 3, 78, 6, 3, 67, 45, 67, 4, 23, 89, 21]
quicksort(0, len(nums) - 1, nums)
print(nums)
nums = [104, 34, 56, 31, 78, 6, 3, 67, 67, 4, 23, 89, 21]
quicksort(0, len(nums) - 1, nums)
print(nums)
nums = [104, 34, 57, 31, 78, 4, 23, 899, 21]
quicksort(0, len(nums) - 1, nums)
print(nums)
if __name__ == "__main__":
main()
|
b57ccfc7086c44bbfffc5cac57fd4fc1acb0a770 | misshebe/PycharmProjects | /s14/day3/decode.py | 214 | 3.828125 | 4 | #python3.x
#-*- coding:utf-8 -*-
# a = "正视你的邪恶" #现在编码是unicode 因为python3默认 不能指定utf-8就能看中文
a = "正视你的邪恶".encode("utf-8") #unicode转utf-8编码
print(a) |
3794bea1700068e702b0605bef26f1c520682980 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2901/49361/245588.py | 265 | 3.859375 | 4 | def solution(number):
(number, flag) = divmod(number, 2)
while number:
(number, remainder) = divmod(number, 2)
if remainder == flag:
return False
flag = remainder
return True
num = int(input())
print(solution(num))
|
0836c66cacbf05f6cc2fee35594bbdd9fba71318 | xZoomy/word2vec-korea | /codes/extractASM.py | 1,122 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 14:46:36 2019
@author: jlphung
"""
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def select_assembly(conn):
"""
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT assembly || char(10) FROM functions;")
rows = cur.fetchall()
f=open("../input/assembly.asm","w+")
for row in rows:
for i in range(0,len(row)):
f.write(row[i])
#print(type(row))
print("input/assembly.asm created")
f.close()
def main():
database = "../databases/kernel.sqlite"
conn = create_connection(database)
with conn:
select_assembly(conn)
if __name__ == '__main__':
main()
|
62e038c21bf2868aa979ff7689b01aade8db4bbb | yukraven/vitg | /Archive/Sources/Tools/Instruments.py | 1,037 | 3.671875 | 4 | import random
from Archive.Sources.Tools.Exceptions import ValueIsNotProbabilityError
def getRandFromArray(array, withWhat):
""" Returns a random index from an array of probabilities """
if type(array) is not list:
raise TypeError
if len(array) == 0:
raise ValueError
if withWhat == "withProbs":
for i in array:
if not (isinstance(i, int) or isinstance(i, float)):
raise ValueError
for i in array:
if i < 0:
raise ValueIsNotProbabilityError(i)
temp = 0
resultArray = []
for i in array:
temp += i
resultArray.append(temp) # Converting of the array into a form convenient for calculation
randomValue = random.randint(1, temp)
for i in range(len(resultArray)):
if randomValue <= resultArray[i]:
return i
if withWhat == "withValues":
randomValue = random.randint(0, len(array) - 1)
return array[randomValue]
|
fc18c7a92523d66d7f79d3cf273d18d97335f11c | happinessbaby/Project_Euler | /fib1000.py | 248 | 3.59375 | 4 | fib = {}
def find_fib():
fib[0] = 1
fib[1] = 1
n = 2
fib_length = 0
while fib_length < 1000:
fib[n] = fib[n-1] + fib[n-2]
fib_length = len(str(fib[n]))
n += 1
return n
print(find_fib())
|
e48be50d8c3ec2b4cc01d89ada1a208859db735e | FelipeMacenaAlves/Project_Euler | /Even_Fibonacci_numbers/Even_Fibonacci_numbers.py | 319 | 3.78125 | 4 | def fibonacci(n,limit=None):
data = [1,2]
if limit:
while data[-1] < limit:
data.append(data[-1] + data[-2])
else:
data = data[:-1]
else:
if n < 3:
return data
for element in range(n-2):
data.append(data[-1] + data[-2])
return data
print(sum(filter(lambda x: x%2 == 0,fibonacci(None,4000000)))) |
2b1afbec0bb98c6cf3d244cbc263687a574cf8fb | a100kpm/daily_training | /problem 0083.py | 751 | 4.09375 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
'''
class Node:
def __init__(self,data):
self.left = None
self.right = None
self.data = data
tree=Node('a')
tree.left=Node('b')
tree.left.left=Node('d')
tree.right=Node('c')
tree.left.right=Node('e')
tree.right.left=Node('f')
def tree_inverter(tree):
a=tree.left
tree.left=tree.right
tree.right=a
if tree.left:
tree_inverter(tree.left)
if tree.right:
tree_inverter(tree.right)
return tree
|
bbcbe86d5f902fed12113aa2ff2cafdb7fe9019b | Gayatr12/Data_Structures | /linklist.py | 2,044 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 16:20:25 2020
@author: STSC
"""
#LinkedList
# creating LinkedList and printing
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
def printlink(self,head):
temp = head
while (temp):
print(temp.data,"--->", end =" ")
temp = temp.next
print("None")
# reverse the linklist
def reverse(self,head):
temp = head
prev = None
while(temp):
Nxt =temp.next
temp.next =prev
prev = temp
temp = Nxt
return prev
# check if linklist is has cycle
def checkCycle(self, head):
slow = head
fast = head
while (fast.next !=None):
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False
#
# Code execution starts here
if __name__=='__main__':
# Start with the empty list
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second;
second.next = third
print("LinkedList:")
llist.printlink(llist.head)
rev_list = llist.reverse(llist.head)
print("Reverse LinkList:")
llist.printlink(rev_list)
if llist.checkCycle(llist.head):
print("Linklist contain Cycle")
else:
print("Linklist does not contain Cycle")
|
33eccc02fbbca665a68d4ddea024269decfd9666 | westgate458/LeetCode | /P0498.py | 1,654 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 14:03:42 2020
@author: Tianqi Guo
"""
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
# trivial case
if not matrix: return []
# initial position, direction d=0 for upward move
i = j = d = 0
# size of the matrix
m, n = len(matrix), len(matrix[0])
# final path
res = [0]*(m*n)
# deal with each point
for idx in range(m*n):
# record value
res[idx] = matrix[i][j]
# deal with upward move
if d == 0:
# if at right edge
if j == n-1:
# move to the one below and change direction
i += 1
d = 1
# if at top edge
elif i == 0:
# move to the one on the right and change direction
j += 1
d = 1
# for interior points, continue moving along the direction
else:
i -= 1
j += 1
# similarly, deal with downward move
else:
if i == m-1:
j += 1
d = 0
elif j == 0:
i += 1
d = 0
else:
i += 1
j -= 1
# return the values along the path
return res
|
2012b904e6af6533751d661a205d538aaa187153 | bingli8802/leetcode | /0958_Check_Completeness_of_a_Binary_Tree.py | 814 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
q = [root]
for i in range(100):
node = q.pop(0)
# 当遇到第一个none 判断q里面是不是所有元素都是none 如果不是 就说明右边还有节点
if node == None:
if set(q) == {None}:
return True
else:
return False
# 把root左右子树都入队 不论是否为none
q.append(node.left)
q.append(node.right)
|
4361e0152eaf364f27e799fed182118a16e586e0 | jinger02/testcodes | /exer5_9.py | 1,105 | 4.125 | 4 | #Exercise 1&2: Write a program which repeatedly reads numbers until the user enters "done".
#Once "done" is entered, print out the total, count, and average of the numbers.
#if the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
total = 0
count = 0
average = 0
largest = None
smallest = None
while True:
line = input('Enter a number\n')
if line == 'done':
print('Total',total)
print('Count',count)
print ('average',average)
print('smallest', smallest)
print('largest', largest)
break
else:
try:
line = int(line)
total = line + total
count = count +1
average = (total / count)
for itervar in [line]:
if smallest is None or itervar < smallest:
smallest = itervar
if largest is None or itervar > largest:
largest = itervar
continue
except ValueError:
print('Enter a number or done')
|
7f2927ae1943864e1c0fcafd2a258e208b59f234 | talt001/Java-Python | /Python-Fundamentals/Loan Calculations/combs_loan_calculations_program.py | 1,840 | 4.3125 | 4 | #Step 1 write a python function that will calculate monthly payments on
# a loan.
#Step 2 pass the following to your function
#Principle of $20,000, with an APR of 4% to be paid in
# 1.) 36 months
# 2.) 48 months
# 3.) 60 months
# 4.) 72 months
#Step 3 include code for user supplied loan terms and comment out
#define the main function
def main():
#set some global constants for loan terms
Principle = 20000.00
APR = 0.04
rate = APR / 12
print('On a $20,000.00 loan, with 4% APR:')
print()
#iterate through 3, 4, 5, and 6 'years' and multiply by twelve to provide the argument 'n' in
#the proper terms - months
for years in range(3, 7):
n = years * 12
#assign the function to a variable for formatting in the print statements to follow
#calling the function directly within print() produces an error
payment = Calculate_monthly_payment(Principle, n, rate)
print('Your monthly payments will be $', format(payment, ',.2f'), ' when you borrow for ', n,' months.', sep = '')
print()
# code for user provided loan terms
# x, y, z = Get_loan_terms()
# payment = Calculate_monthly_payment(x, y, z)
# print('Your monthly payment will be $', format(payment, ',.2f'), sep = '')
# code for user provided loan terms
##def Get_loan_terms():
## Principle = float(input('Enter the loan amount: '))
## n = int(input('Enter duration of loan in months: '))
## APR = float(input('Enter the APR: '))
## rate = APR / 12
## return Principle, n, rate
#define the function to calculate monthly payments by writing a math expression
#return the value to mainn()
def Calculate_monthly_payment(Principle, n, rate):
monthly = Principle*((rate*(1+rate)**n))/((1+rate)**n - 1)
return monthly
#call the main function
main()
|
fb44cad292742f3bf54372af37d96e3b39f4bfb5 | cbhust8025/primary-algorithm | /LeetCode/python/2_addTwoNumbers.py | 1,362 | 3.859375 | 4 | # Definition for singly-linked list.
import string
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def show(self, a):
while(a):
print a.val,
a = a.next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
num_1 = ''
while (l1):
num_1 += str(l1.val)
l1 = l1.next
list_1 = list(num_1)
list_1.reverse()
num1 = int(''.join(list_1))
num_2 = ''
while(l2):
num_2 += str(l2.val)
l2 = l2.next
list_2 = list(num_2)
list_2.reverse()
num2 = int(''.join(list_2))
res = num1 + num2
num3 = list(str(res))
num3.reverse()
l3 = ListNode(0)
temp = l3
for i in range(len(num3)):
t = ListNode(int(num3[i]))
temp.next = t
temp = temp.next
return l3.next
so = Solution()
L = ListNode(0)
t= ListNode(2)
m = ListNode(3)
a = ListNode(1)
n = ListNode(6)
k = ListNode(4)
b = ListNode(3)
b.next = k
k.next = n
a.next = t
t.next =m
L.show(a)
print '\n'
L.show(b)
print '\n'
L.show(so.addTwoNumbers(a,b))
|
9f8dd7132bc87b76549886774eea5a750fdeea17 | FarhatJ/HackerRank | /10DaysOfStatistics/Day 4- Binomial Distribution II.py | 1,379 | 3.90625 | 4 | # Objective
# In this challenge, we go further with binomial distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.
# Task
# A manufacturer of metal pistons finds that, on average, of the pistons they manufacture are rejected because they are incorrectly sized. What is the probability that a batch of pistons will contain:
# No more than rejects?
# At least rejects?
# Input Format
# A single line containing the following values (denoting the respective percentage of defective pistons and the size of the current batch of pistons):
# 12 10
# If you do not wish to read this information from stdin, you can hard-code it into your program.
# Output Format
# Print the answer to each question on its own line:
# The first line should contain the probability that a batch of pistons will contain no more than rejects.
# The second line should contain the probability that a batch of pistons will contain at least rejects.
# Round both of your answers to a scale of decimal places (i.e., format).
import math
p = 0.12
q = 1-p
n = 10
x_all = 2
pr = 0
for x in range(x_all+1):
pr += (math.factorial(n)/math.factorial(x)/math.factorial(n-x)) * p**x * q**(n-x)
print round(pr, 3)
pr = 0
for x in range(x_all, n+1):
pr += (math.factorial(n)/math.factorial(x)/math.factorial(n-x)) * p**x * q**(n-x)
print round(pr, 3) |
f4638e39bb78bcb942270ad7334d4e6ebdb4096d | sjwar455/PythonCodeChallenges | /diceSim.py | 1,178 | 3.84375 | 4 | ##############################################################################################
# File: diceSim.py
# Author: Sam Wareing
# Description: script to determine probability of dice rolls using monte carlo simulation
#
#
#
##############################################################################################
import sys
from random import randint
from collections import Counter
def simulateDiceRolls(dice, num_simulations):
counts = Counter()
for roll in range(num_simulations):
counts[sum((randint(1, sides) for sides in dice))] += 1
print("\nOUTCOME\tPROBABILITY")
for outcome in range(len(dice), sum(dice)+1):
print('{}\t{:0.2f}%'.format(outcome, counts[outcome]*100/num_simulations))
def usage():
print("diceSim.py # # #....")
if __name__ == "__main__":
print("let's sim some dice")
if len(sys.argv) < 2:
usage()
exit()
num_simulations = input("How many simulations? press enter for default 1000000 ")
if num_simulations == "":
num_simulations = 1000000
else:
num_simulations = int(num_simulations)
n = len(sys.argv)
dice = [int(sys.argv[i]) for i in range(1, n)]
simulateDiceRolls(dice, num_simulations)
|
ae61084ed337666de0d355ec54bb404ca201fc4d | pbrandiezs/python-ex15 | /Ex15.py | 158 | 4.125 | 4 | the_string = input("Enter a long string? ")
result = the_string.split(" ")
backwards_result = result[::-1]
reverse = " ".join(backwards_result)
print(reverse) |
d2154f94c4375f395ef1f1b027ee3872a4eb0d52 | shanminlin/Cracking_the_Coding_Interview | /chapter-4/5_validate_BST.py | 4,183 | 3.90625 | 4 | """
Chapter 4 - Problem 4.5 - Validate BST
Problem:
Implement a function to check if a binary tree is a binary search tree.
Solution:
1. Clarify the question:
Repeat the question: We are given a binary tree, and we need to check whether it is a binary search tree.
Clarify assumptions: - Definition of a BST:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
2. Inputs and outputs:
So we're taking in a binary tree and returning True or False for whether it is a BST.
3. Test and edge cases:
edge: We can also take in an empty tree or None object.
test: We can also take in regular inputs like this:
4
/ \
1 6
/ \
5 7
and we will return True.
4
/ \
1 3
/ \
5 7
and we will return False as 3 is in the right subtree of its parent node 4.
4. Brainstorm solution:
Because of BST condition, we could do In-Order Traversal of the given tree and store the result in a temp array.
Then check if the temp array is sorted in ascending order, if it is, then the tree is BST.
Time-Complexity of the solution would be O(N) for in-order traversal and O(N) to check if the list is sorted.
Space-complexity would be O(N) since you need to hold the traversed list in memory. We can avoid the use of Auxiliary
Array. While doing In-Order traversal, we can keep track of previously visited node. If the value of the currently
visited node is less than the previous value, then tree is not BST.
We could also look at each node only once. We could traverse down the tree keeping track of the narrowing min and max
allowed values as it goes, looking at each node only once. The initial values for min and max should be INT_MIN and
INT_MAX — they narrow from there.
Note that we need to prepare a Class for the node which will hold and initialize the data for the node.
5. Runtime analysis:
Time complexity: O(N) as we traverse all the nodes in the tree once.
Space complexity: O(1) as we do not use any additional memory.
6. Code
"""
import sys
import unittest
class TreeNode:
def __init__(self, value):
"""
Creates a node for a tree.
Attributes:
value: A value of the node
left: A reference to left child node
right: A reference to right child node
"""
self.value = value
self.left = None
self.right = None
"""
NOTE: Maximum integer value is sys.maxsize and minimum integer value is one less number on negative side i.e. -(sys.maxsize - 1)
"""
def is_bst(node, min_value=-(sys.maxsize - 1), max_value=sys.maxsize):
"""
Checks if the tree/sub-tree rooted by the specified node is BST
Args:
node: An instance of the class TreeNode
min_value: Lower bound for node values in the tree
max_value: Upper bound for node values in the tree
Returns:
A boolean for whether it is a BST.
"""
if node is None:
return True
# False if this node violates min/max constraint
if node.value < min_value or node.value > max_value:
return False
# check recursively for every node.
# tightening the min or max constraint
return is_bst(node.left, min_value, node.value-1) and is_bst(node.right, node.value+1, max_value)
class TestBst(unittest.TestCase):
def test_none(self):
self.assertTrue(is_bst(None))
def test_left_skewed(self):
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
self.assertTrue(is_bst(root))
def test_right_skewed(self):
root = TreeNode(4)
root.left = TreeNode(1)
root.right = TreeNode(6)
root.right.left = TreeNode(5)
root.right.right = TreeNode(7)
self.assertTrue(is_bst(root))
def test_non_bst(self):
root = TreeNode(4)
root.left = TreeNode(5)
root.right = TreeNode(6)
self.assertFalse(is_bst(root))
if __name__ == '__main__':
unittest.main() |
b22e269c2c5c02aff496d9570e9e934292973656 | andreaorlando333/EserciziTPSIT | /Python/Es_DizionarioFunzioni.py | 478 | 3.765625 | 4 |
# Esercizio con Dizionario Funzioni
# Programma per somma/moltiplicazione
def somma(a, b):
return a+b
def moltiplicazione(a, b):
return a*b
dizionario_funzioni = {0: somma, 1: moltiplicazione}
def main():
print("Seleziona un'opzione:")
val_utente = int(input("0. Somma \n1. Moltiplicazione:\n\nInput: "))
a = int(input("Primo numero: "))
b = int(input("Secondo numero: "))
x = dizionario_funzioni[val_utente](a, b)
print(x)
if __name__ == "__main__":
main()
|
15e554a4e61cfb50460a99421ca822b809f150a5 | rjadmscpfl/HelloGitHub | /while-for-range.py | 1,133 | 3.875 | 4 |
#num = 0
#while num <10:
# print(num)
# num += 1
#for i in range(1, 101):
# print(i)
#score_list = [90, 45, 70, 60, 55]
#num = 1
#for score in score_list:
# if score >= 60:
# result = "Pass"
# print("Num {} is Pass".format(num))
# else:
# result = "Fail"
# print("Num {} is Fail".format(num))
# print("Student {} is {}".format(num,result))
# num = num + 1
#for i in range(10):
# print(i, end=" ")
import random
#random_num = random.randint(1, 20)
#while True:
# num = int(input("Input Number >> "))
# if num < random_num:
# print("it is bigger than {}".format(num))
# elif num > random_num:
# print("it is smaller than {}".format(num))
# else:
# print("You are right!!")
# break
#start = int(input("first input number >> "))
#end = int(input("last input number >> "))
#for i in range(start,end+1):
# print(i, end=" ")
#for i in range(1, 10):
# print ("2 * {} = {}".format(i, 2*i))
#num = int(input("input number = "))
#for i in range(1, num+1):
# if num%i==0:
# print(i)
i = random.randint(1, 100)
print(i)
|
807d884981d42182ab9837f8979e4df698594c4c | kkejian/pytests | /p6/p6e09.py | 723 | 3.6875 | 4 | class Statement:
def __init__(self):
self.line = ''
def state(self):
print('%s:\t%s' % (self.__class__.__name__, self.line))
class Parrot(Statement):
def __init__(self):
self.line = None
class Customer(Statement):
def __init__(self):
self.line = '"That\'s one ex-bird!"'
class Clerk(Statement):
def __init__(self):
self.line = '"No it isn\'t..."'
class Scene(Parrot,Customer,Clerk):
def __init__(self):
self.parrot = Parrot()
self.customer = Customer()
self.clerk = Clerk()
def action(self):
self.customer.state()
self.clerk.state()
self.parrot.state()
if __name__ == '__main__':
Scene().action()
|
f49d6c449768f2d678d17dc06586864932bdd69f | helloarthur0623/happy_code | /weather_1to100/pandas_perfect.py | 3,909 | 3.59375 | 4 | # 讀取 CSV File
import pandas as pd # 引用套件並縮寫為 pd
import time
df = pd.read_csv('2014-08-30.csv',encoding='utf-8')
print(df)
df= df.dropna()
print(df)
df = df.drop(columns=['Unnamed: 0'])
print(df)
df.index = range(len(df))
df=df.reset_index()
df=df.drop(['index'],axis=1)
print(df)
def column_filter(s):
return s.split('°')[0].strip()
df['feel1'] = df['feel1'].apply(column_filter)
df['feel2'] = df['feel2'].apply(column_filter)
df['feel3'] = df['feel3'].apply(column_filter)
df['temp1'] = df['temp1'].apply(column_filter)
df['temp2'] = df['temp2'].apply(column_filter)
df['temp3'] = df['temp3'].apply(column_filter)
def column_filter2(s):
return s.split('%')[0].strip()
df['precip1'] = df['precip1'].apply(column_filter2)
df['precip2'] = df['precip2'].apply(column_filter2)
df['precip3'] = df['precip3'].apply(column_filter2)
def column_filter3(s):
return s[:4].strip()
print(df['speed1'].apply(column_filter3))
df['speed1'] = df['speed1'].apply(column_filter3)
df['speed2'] = df['speed2'].apply(column_filter3)
df['speed3'] = df['speed3'].apply(column_filter3)
def convert_to_24(time):
if time[-3:-1] == "AM":
return time[:-3] + ':00'
elif int(str(int(time.split(':')[0]) + 12)) >= 24:
return time[:-3] + ':00'
else:
return str(int(time.split(':')[0]) + 12)+':' + time.split(':')[1][:-3] + ':00'
print(df['time'].apply(convert_to_24))
df['time'] = df['time'].apply(convert_to_24)
def column_filter4(s):
return s.strip()
df['park'] = df['park'].apply(column_filter4)
df['fightteam1'] = df['fightteam1'].apply(column_filter4)
df['fightteam2'] = df['fightteam2'].apply(column_filter4)
df['weather1'] = df['weather1'].apply(column_filter4)
df['weather2'] = df['weather2'].apply(column_filter4)
df['weather3'] = df['weather3'].apply(column_filter4)
df = df[(~df['weather1'].isin(['N/A']))&(~df['weather1'].isin(['N/A']))&(~df['weather3'].isin(['N/A']))]
def column_filterPAPA(s):
return int(s)/100
df['precip1'] = df['precip1'].apply(column_filterPAPA)
df['precip2'] = df['precip2'].apply(column_filterPAPA)
df['precip3'] = df['precip3'].apply(column_filterPAPA)
df.to_csv(r'887788.csv',index=0, encoding='utf-8')
#df.to_csv(r'clean_mlb_weather.csv', encoding='utf-8')
# def team_rename(name):
# if name == "Dodgers":
# return "LAD"
# if name == "Red Sox":
# return "BOS"
# if name == "Brewers":
# return "MIL"
# if name == "Astros":
# return "HOU"
# if name == "Yankees":
# return "NYY"
# if name == "Braves":
# return "ATL"
# if name == "Indians":
# return "CLE"
# if name == "Rockies":
# return "COL"
# if name == "Cubs":
# return "CHC"
# if name == "Royals":
# return "KCR"
# if name == "Mariners":
# return "SEA"
# if name == "Padres":
# return "SDP"
# if name == "Mets":
# return "NYM"
# if name == "Twins":
# return "MIN"
# if name == "Reds":
# return "CIN"
# if name == "Angels":
# return "ANA"
# if name == "Giants":
# return "SFG"
# if name == "Phillies":
# return "PHI"
# if name == "Orioles":
# return "BAL"
# if name == "Diamondbacks":
# return "ARI"
# if name == "White Sox":
# return "CHW"
# if name == "Cardinals":
# return "STL"
# if name == "Blue Jays":
# return "TOR"
# if name == "Nationals":
# return "WSN"
# if name == "Athletics":
# return "OAK"
# if name == "Rangers":
# return "TEX"
# if name == "Pittsburgh Pirates":
# return "PIT"
# if name == "Miami Marlins" or name == "Florida Marlins":
# return "FLA"
# if name == "Detroit Tigers":
# return "DET"
# if name == "Tampa Bay Rays":
# return "TBD"
# else:
# print("No name match found for "+name)
# return ""
# |
435ebd93fb5f8bc00a36504995eb64048d426917 | valbertoenoc/basic-datastructures-python | /ArrayQueue.py | 1,614 | 4.03125 | 4 | class ArrayQueue:
"""FIFO queue implementation using a Python list as underlying storage."""
def __init__(self):
"""Create an empty queue."""
self.m_data = [None]*ArrayQueue.DEFAULT_CAPACITY
self.m_size = 0
self.m_front = 0
def __len__(self):
"""Return the number of elements in the queue"""
return self.m_size
def isEmpty(self):
"""Return True if the queue is empty."""
return self.m_size == 0
def first(self):
"""Return (but do not remove) the element at the front of the queue.
Raise Empty exception if the queue is empty
"""
if self.isEmpty():
raise Empty('Queue is empty.')
return self.m_data[self.m_front]
def dequeue(self):
"""Remove and return the first element of the queue (i.e., FIFO).
Raise Empty exception if the queue is empty.
"""
if self.isEmpty():
raise Empty('Queue is empty')
answer = self.m_data[self.m_front]
self.m_data[self.m_front] = None
self.m_front = (self.m_front + 1) % len(self.m_data)
self.m_size -= 1
return answer
def enqueue(self, elem):
"""Add an element to the back of the queue."""
if self.m_size == len(self.m_data):
self.resize(2*len(self.m_data)) #double the array size
avail = (self.m_front + self.m_size) % len(self.m_data)
self.m_data[avail] = elem
self.m_size += 1
def m_resize(self, cap):
"""Resize to a new list of capacity >= len(self)."""
old = self.m_data
self.m_data = [None]*cap
walk = self.m_front
for k in range(self.m_size):
self.m_data[k] = old[walk]
walk = (1 + walk) % len(old)
self.m_front = 0
def main():
pass
if __name__ == '__main__':
main()
|
3a3017f8a2bedcf845f8d1006ed30853e575ac8e | crebiz76/checkio | /python/HOME/LongRepeat.py | 832 | 3.921875 | 4 | def long_repeat(line: str) -> int:
"""
length the longest substring that consists of the same char
"""
# your code here
ret = 0
buf = ''
Max = 0
linelist = list(line)
for i in linelist:
if i == buf:
ret += 1
if ret >= Max:
Max = ret
else:
ret = 1
buf = i
if Max >= ret:
print(Max)
return Max
else:
print(ret)
return ret
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert long_repeat('sdsffffse') == 4, "First"
assert long_repeat('ddvvrwwwrggg') == 3, "Second"
assert long_repeat('abababaab') == 2, "Third"
assert long_repeat('') == 0, "Empty"
print('"Run" is good. How is "Check"?') |
e348d6a1651563b8a1d2b6959cc4c01077fc9dd7 | guilmeister/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 440 | 3.984375 | 4 | #!/usr/bin/python3
def text_indentation(text):
if isinstance(text, str) is False:
raise TypeError("text must be a string")
x = 0
while x < len(text):
if text[x] == '.' or text[x] == '?' or text[x] == ':':
print(text[x], end="")
print("")
print("")
x = x + 1
if text[x] == ' ':
x = x + 1
print(text[x], end="")
x = x + 1
|
b8d58f0ea95acbc38f8f4c743e0f23355d5f04c5 | engenmt/Lingo | /main.py | 2,224 | 3.796875 | 4 | from setup import words
def response(guess, correct):
"""Return the information received upon guessing the word `guess` into the word `correct`."""
guess = list(guess)
correct = list(correct)
known = []
misplaced = []
for idx in range(5):
if guess[idx] == correct[idx]:
known.append(idx)
guess[idx] = None
correct[idx] = None
for idx in range(5):
if (char_guess := guess[idx]) is not None and char_guess in correct:
misplaced.append(idx)
correct[correct.index(char_guess)] = None
return (tuple(known), tuple(misplaced))
def score(*guesses):
"""Return the score of a sequence of guesses. The score is proportional to how good the guesses are.
Consider all correct words. Each correct word gives information (1) the first letter and
(2) the sequence of responses based on the guessed words. There is an equivalence relation
on the set of correct words, where two words are equivalent with respect to the guesses if
their information returned is identical. The probability that you guess correctly given
a sequence of guesses is proportional to the number of equivalence classes, so this function
returns the number of equivalence classes.
"""
return len(set(
sum((response(guess, correct) for guess in guesses), (correct[0],)) for correct in words
))
def best_addition(*guesses):
"""Given a sequence of guesses, return the best guessed word to add on."""
return max(words, key = lambda w: score(w, *guesses))
if __name__ == '__main__':
guesses = [
('blocs', 'fumed', 'garth', 'pinky']), # 8211
('blots', 'cager', 'dinky', 'whump']), # 8238
('chomp', 'furan', 'gybed', 'kilts']), # 8239
('bumpy', 'cadge', 'knits', 'whorl']), # 8240
('clipt', 'gybed', 'khoum', 'warns']), # 8246 # Mine
('bumpy', 'cares', 'klong', 'width']), # 8268
('bares', 'clomp', 'gunky', 'width']), # 8272
('blink', 'chomp', 'gudes', 'warty']), # 8282
('bints', 'cloak', 'gyred', 'whump']), # 8287
]
for g in sorted(guesses, key = lambda t: score(*t)):
print(g, score(*g))
|
7d98121dc7ec94ef176697800b5473db958b00ae | kimgwanghoon/openbigdata | /01_jumptopy/chap03/135.py | 193 | 3.546875 | 4 | #coding:cp949
print("<< α ver1>>")
for i in range(2,10):
print("**%d**"%i)
for j in range(1,10):
print("{0}*{1}={2}".format(i,j,i*j))
print('')
|
bfe1f48e4da80437fbf932ed5200ab18bdb089fc | bobcaoge/my-code | /python/leetcode_bak/925_Long_Pressed_Name.py | 799 | 3.65625 | 4 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
if set(name) != set(typed):
return False
index_of_name = 0
length = len(name)
for index, c in enumerate(typed):
if name[index_of_name] == c:
index_of_name += 1
if index_of_name == length:
return True
else:
if index != 0 and typed[index] != typed[index-1]:
return False
return index_of_name == length
def main():
s = Solution()
print(s.isLongPressedName("saeed", "ssaaedd"))
if __name__ == "__main__":
main()
|
cbe336705a436b7b704858273a80127ece50a0c2 | chl218/leetcode | /python/stuff/0231-power-of-two.py | 532 | 4.09375 | 4 | """
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: false
Constraints:
-2^31 <= n <= 2^31 - 1
Follow up: Could you solve it without loops/recursion?
"""
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n-1) == 0)
|
73340653ea02720c283edddc5d5787b1036b8505 | algorithm005-class01/algorithm005-class01 | /Week_02/G20190343020234/LeetCode_49_0234.py | 578 | 3.671875 | 4 | import collections
class Solution:
def groupAnagrams(self, strs):
# res = collections.defaultdict(list)
# for s in strs:
# count = [0] * 26
# for c in s:
# count[ord(c) - ord('a')] += 1
# res[tuple(count)].append(s)
# return res.values()
res = collections.defaultdict(list)
for s in strs:
res[tuple(sorted(s))].append(s)
return res.values()
if __name__ == "__main__":
solu = Solution()
print(solu.groupAnagrams(["eat","tea","tan","ate","nat","bat"]))
|
85f24ce855ad72f3e1dbee6f8e5529be951d92f5 | tiaedmead/Data_24_repo | /UnitTesting_TDD/testing.py | 324 | 4.125 | 4 | # from addition import *
#
# if addition(1, 2) == 3:
# print("addition function working as expected")
# else:
# print("addition function not working as expected")
#
#
# if subtraction(3, 2) == 1:
# print("subtraction function working as expected")
# else:
# print("addition function not working as expected") |
a114c079e28f7cbb0fb996646f7e551c64ab71a7 | UkrainianProgrammer/Client-Server-Architecture | /PythonModel/client.py | 520 | 3.546875 | 4 | # Written by Oleksandr Sofishchenko
# Simple socket programming in Python.
# Server socket does not receive any data. Instead, it produces
# client sockets.
# client.py
import socket
# create a socket object
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# fetching local machine's name
server_address = ("localhost", 10000)
# connection to hostname on the port
skt.connect(server_address)
# receive no more than 1024 bytes
tm = skt.recv(1024)
skt.close()
print("The time got from the server is %s" %tm.decode("ascii")) |
60001fb88d93af6ab02030383ff69de4df7cc70c | ktyagi12/Driving_License_Initial_Validations | /DLApplication.py | 836 | 3.921875 | 4 | # Driving License Application Form
print '*' * 150
print '\t\t\tSaarthi Driving License Application'
print '\t\t', '*' * 150
vision_thres = 6
fname = raw_input('Enter your first name: ')
lname = raw_input('Enter your last name: ')
year_birth = input('Enter your year of birth: ')
vision = input('Enter your eyesight (eg. 6): ')
city = raw_input('Enter your city name: ').upper()
if (fname == ''or year_birth == '' or vision=='' or city =='' or vision <0):
print ' Either of the fields is not filled.'
else:
if (city != 'PUNE' or vision != 6):
print 'Sorry!! Either you are applying region other than Pune or your vision is not appropriate...'
else:
if (year_birth <=2000):
print'Congratulations!! You can proceed for the license application...'
else:
print'Sorry!! You are not eligible for the license application...'
|
f0583af002084271bf6ab0b110162b3c5c7226f7 | barbieauglend/Learning_python | /Lvl01/Ladebalken/ladebalken_2.py | 554 | 3.515625 | 4 | #python 2.7 and python 3.5
import sys
import time
def progressbar(it, size):
count = len(it) + start
def _show(_i):
x = int(size * (_i + start) / count)
sys.stdout.write("[%s%s] %i %s\r" % ("#" * x, " " * (size - x), _i + start, '%'))
sys.stdout.flush()
_show(0)
for i, item in enumerate(it):
yield item
_show(i + 1)
sys.stdout.write("\n")
sys.stdout.flush()
input_start = input("Enter State: ")
start = int(input_start)
for i in progressbar(range(100-start), 10):
time.sleep(0.1) |
c835dddbcdc61682489a8bd025337e32238aad36 | Aniketgupta2007/prepinsta-top100-codes-python | /29.LargeAndSmall.py | 238 | 3.890625 | 4 | arr = list(map(int, input().split(" ")))
large = arr[0]
small = arr[0]
for i in range(1, len(arr)):
if arr[i] < small:
small = arr[i]
if arr[i] > large:
large = arr[i]
print('Smallest', small, 'Largest', large)
|
e9bd56303d5a025354a977cbf1fb5a286242fe3c | PedroMorenoTec/practica-examen | /2.1/lustros.py | 204 | 3.625 | 4 | nacimiento = int(input('Introduzca su año de nacimiento: '))
year = int(input('Introduzca el año en el que estamos: '))
lustros = (year - nacimiento)/5
print(f'Usted ha vivido {lustros} lustros') |
e33f738367bbe437122e2af2c242192a175e38b6 | OleksandrNikitin/100-Days-of-Code---The-Complete-Python-Pro-Bootcamp-for-2021 | /day-4/main.py | 1,218 | 4.09375 | 4 | import secrets
rock = """
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
"""
paper = """
_______
---' ____)____
______)
_______)
_______)
---.__________)
"""
scissors = """
_______
---' ____)____
______)
__________)
(____)
---.__(___)
"""
options = [rock, paper, scissors]
computer_choice = secrets.choice(options)
user_choice = int(
input("What do you choose, Type 0 for Rock, 1 for Paper or 2 for Scissors:\n")
)
print(f"You chose:\n{options[user_choice]}\n")
print(f"Computer chose:\n{computer_choice}\n")
if (
user_choice == 0
and computer_choice is rock
or user_choice == 1
and computer_choice is paper
or user_choice == 2
and computer_choice is scissors
):
print("No winner")
elif (
user_choice == 0
and computer_choice is paper
or user_choice == 1
and computer_choice is scissors
or user_choice == 2
and computer_choice is rock
):
print("You lose")
elif (
user_choice == 0
and computer_choice is scissors
or user_choice == 1
and computer_choice is rock
or user_choice == 2
and computer_choice is paper
):
print("You win")
|
9a3498f23f3dfaf3c7e86a57729913a132441f6d | ruidazeng/online-judge | /Kattis/cetiri.py | 218 | 3.625 | 4 | lst = sorted([int(x) for x in input().split()])
diff1 = lst[1] - lst[0]
diff2 = lst[2] - lst[1]
if diff2 > diff1:
print(lst[1] + diff1)
elif diff1 > diff2:
print(lst[0] + diff2)
else:
print(lst[2] + diff1) |
14f61595a5eac990a23c3593af3b580907d9e1e4 | KakaC009720/Ptyhon_train | /質數判斷.py | 212 | 3.890625 | 4 | n = int(input())
sum = 0
for i in range(1, n+1):
a = n%i
if a == 0:
sum = sum + i
else:
pass
if sum == n + 1:
print(n, "is prime")
else:
print(n, "is not prime") |
84ab6534c6eae23ff75049b2cc1a09701bac82c8 | nghiattran/playground | /hackerrank/palandir-degree/expand_the_acronyms.py | 1,408 | 4.03125 | 4 | dictionary = {}
def parse_abbr(entry, i):
i += 1
abbr = ''
while entry[i] != ')':
abbr += entry[i]
i += 1
return abbr, i
def parse_real(entry, abbr, i):
i -= 2
end_pos = i
stop = False
name = ''
uppercase_cnt = 0
while not stop and i >= 0:
name = entry[i] + name
uppercase_cnt += 1 if 'A' <= entry[i] and entry[i] <= 'Z' else 0
stop = uppercase_cnt == len(abbr)
i -= 1
return name
def parse(entry):
i = 0
while i < len(entry):
ch = entry[i]
if ch == '(':
start_abbr = i
abbr, i = parse_abbr(entry, i)
name = parse_real(entry, abbr, start_abbr)
dictionary[abbr] = name
i += 1
snippets = """The United Nations Children's Fund (UNICEF) is a United Nations Programme headquartered in New York City, that provides long-term humanitarian and developmental assistance to children and mothers in developing countries.
The National University of Singapore is a leading global university located in Singapore, Southeast Asia. NUS is Singapore's flagship university which offers a global approach to education and research.
Massachusetts Institute of Technology (MIT) is a private research university located in Cambridge, Massachusetts, United States."""
snippets = snippets.split('\n')
for s in snippets:
parse(s)
print(dictionary) |
ae5f9e6524794939647ebbeebe7b7895bc99671a | coder-dipesh/Basic_Python | /labwork2/checking_item_in_list.py | 145 | 3.96875 | 4 | # Check wether 5 is in list of first 5 natural numbers or not.
# Hint List => [1,2,3,4,5]
list=[1,2,3,4,5]
if 5 in list:
print('It is there') |
b5942e81ce5c5d01d7ef94bfcc64f8c1261c16b1 | TapeshN/Portfolio | /Python1_CourseWork/HW03_TapeshNagarwal.py | 902 | 4 | 4 | #Tapesh Nagarwal CS100-H01
#1
a = 3
b = 4
c = 5
if a < b:
print('OK')
if c < b:
print('OK')
if a+b == c:
print('OK')
if a**2 and b**2 == c**2:
print('OK')
#2
if a < b:
print('OK')
else:
print('NOT OK')
if c < b:
print('OK')
else:
print('NOT OK')
if a+b == c:
print('OK')
else:
print('NOT OK')
if a**2 and b**2 == c**2:
print("OK")
else:
print('NOT OK')
#3
color = input('What color?')
lineWidth = input('What line width?')
lineLength = input('What line length?')
shape = input('line, triangle or square?')
import turtle
s = turtle.Screen()
t = turtle.Turtle()
t.pencolor(color)
t.pensize(lineWidth)
t.forward(lineLength)
if shape == 'line':
t.forward(lineLength)
if shape == 'triangle':
for i in range(3):
t.lineLength
t.right(120)
if shape == 'square':
for i in range(4):
t.lineLength
t.right(90)
|
7192425bcebb4b8772b5aa8f5ac6c76dcb2e0074 | RyanClement/100-Days-of-Code | /Day5/highest_score-day5.py | 508 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created: Apr 25 2021
@author: Ryan Clement
Day #5: Highest Score.
"""
# Can't change block: start
student_scores = input("Input a list of student scores ").split()
for n in range(0,len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# Can't change block: stop
high_score = 0
for score in student_scores:
if score > high_score:
high_score = score
print("The highest score in the class is: {:d}".format(high_score)) |
34649c24c99b0b69f182f5fe03939fe80e600af4 | Antikythera/SkriptJezici | /Practice/zadatak_11.py | 630 | 3.921875 | 4 | #!/usr/local/bin/python3
# Napisati Python funkciju check_duplicates koja kao parametar
# prima listu brojeva na osnovu kojih se proverava da li
# postoje duplikati. Funkcija treba vratiti True ili False
# vrednost u zavisnosti od toga da li se u listi nalazi duplikat
# nekog elementa ili ne.
#
# Primer:
#
# check_duplicates([1, 2, 3, 4]) # => False
# check_duplicates([1, 4, 2, 1]) # => True
def check_duplicates(inlist):
return len(inlist) != len(set(inlist))
def main():
print(check_duplicates([1, 2, 3, 4])) # => False
print(check_duplicates([1, 4, 2, 1])) # => True
if __name__ == "__main__":
main()
|
5443c5073db5bc1d670963c2881089e90a2da19e | NoirKomBatman/leetcode | /617.py | 1,156 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 == None and t2 == None:
return None
if t1 == None:
return t2
if t2 == None:
return t1
ret = t1
stack1 = []
stack1.append(t1)
stack2 = []
stack2.append(t2)
while stack2:
temp1 = stack1.pop()
temp2 = stack2.pop()
if temp2:
temp1.val += temp2.val
else:
continue
if temp2.left and temp1.left == None:
temp1.left = TreeNode(0)
if temp2.right and temp1.right == None:
temp1.right = TreeNode(0)
stack2.append(temp2.left)
stack2.append(temp2.right)
stack1.append(temp1.left)
stack1.append(temp1.right)
return ret
|
df31e3e3b7309e9b0594a09e8d107caced35d3f8 | nathannicholson/dominion | /Dominion Sim.py | 28,251 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 13:08:56 2020
@author: NNicholson
"""
import random
import shelve
class Game:
def __init__(self,game_name,card_dict,supply,trash_pile,players):
self.game_name = game_name
self.card_dict = card_dict
self.supply = supply
self.players = players
self.trash_pile = trash_pile
self.turn_phase = 'Beginning'
self.running = True
def input_handler(self,prompt,allowables):
allowables += ['help']
text = input(prompt).lower()
if text not in allowables:
print('Invalid entry, try again.')
return self.input_handler(prompt,allowables)
if text == 'help':
command = ''
while command != 'done':
command = self.input_handler('Enter a card name for information or enter Done to return to the game: ',[key for key in self.card_dict.keys()] + ['done'])
if command == 'done':
break
else:
print(self.card_dict[command].get_info())
return self.input_handler(prompt,allowables)
else:
return text
def new_game(self):
print('Welcome to Dominion! Enter help at any time to get card text.')
if self.players == []:
self.choose_players([])
if self.supply == {}:
self.choose_kingdoms(len(self.players))
self.play_game()
def choose_players(self,player_names):
if self.players == []:
command = ''
while command.lower() != 'stop':
command = input('Enter a player name, or enter stop to finish entering players: ')
if command.lower() == 'stop':
if len(player_names) > 0:
break
else:
print('Must enter at least one player')
return self.choose_players(player_names)
if command == '':
print('Must enter a name (can be anything)')
return self.choose_players(player_names)
else:
player_names.append(command)
self.players = [Player(name,[],[],[]) for name in player_names]
def choose_kingdoms(self,number_of_players):
number_of_players = min(4,number_of_players)
curse_quantity = {1:10,2:10,3:20,4:30}
victory_quantity = {1:8,2:8,3:12,4:12}
money_quantity = {1:50,2:100,3:100,4:100}
self.supply = {'Copper':money_quantity[number_of_players],'Silver':money_quantity[number_of_players],'Gold':money_quantity[number_of_players],'Estate':victory_quantity[number_of_players],
'Duchy':victory_quantity[number_of_players],'Province':victory_quantity[number_of_players],'Curse':curse_quantity[number_of_players]}
command = self.input_handler('Enter random to choose 10 random kingdom cards for the supply, or enter custom to choose your own: ',['random','custom'])
if command == 'random':
kingdoms_chosen = sorted(random.sample([card for card in self.card_dict.values() if card.is_kingdom],10),key = lambda card: card.cost)
for card in kingdoms_chosen:
if 'Victory' in card.type:
self.supply[card.name] = victory_quantity[number_of_players]
else:
self.supply[card.name] = 10
print('10 random kingdom cards chosen:',', '.join([card.name for card in kingdoms_chosen]))
elif command == 'custom':
print('Available kingdom cards:',', '.join([card.name for card in self.card_dict.values()]))
kingdom_count = 0
while kingdom_count < 10:
target = self.card_dict[self.input_handler(str('Enter a card to add to the supply. '+str(10 - kingdom_count)+' choices remaining: '),[key for key in self.card_dict if key in self.card_dict and self.card_dict[key].is_kingdom])]
if 'Victory' in target.type:
self.supply[target.name] = victory_quantity[number_of_players]
else:
self.supply[target.name] = 10
kingdom_count += 1
print('Finished choosing kingdoms, starting game')
def display_supply(self):
return self.supply
def play_game(self,from_save = False):
print(str('Game begins! \nPlayers: '+', '.join([player.name for player in self.players])+'\nEnter Help at any time to get card text.'))
if from_save == False:
for player in self.players:
player.set_starting_deck()
player.draw(5)
while self.running:
self.save_game()
if self.input_handler('Continue? Enter Y to keep playing or N to quit: ',['y','n'])=='n':
self.running = False
print('Game ended')
break
for player in self.players:
print(player.take_turn(self))
if self.game_over():
self.running = False
self.end()
break
def save_game(self):
save_file = shelve.open(self.game_name)
save_file['Name'] = self.game_name
save_file['Card Dict'] = self.card_dict
save_file['Players'] = self.players
save_file['Supply'] = self.supply
save_file['Trash'] = self.trash_pile
print('Game saved as \'',self.game_name,'\'',sep='')
def game_over(self):
return sum(1 for x in self.supply.values() if x <= 0) >= 3 or self.supply['Province'] <= 0
def end(self):
for player in self.players:
player.victory_points = sum(card.victory_value for card in player.hand) + sum(card.victory_value for card in player.deck) + sum(card.victory_value for card in player.discard_pile) + sum(card.victory_value for card in player.play_area)
self.winner_list = sorted([player for player in self.players],key = lambda player:player.victory_points,reverse = True)
print('\nGame ends!',self.winner_list[0].name,'wins with',str(self.winner_list[0].victory_points),'victory points. \n\nRunners-up:\n')
for player in self.winner_list[1:]:
print(player.name,': ',str(player.victory_points),' victory points',sep='')
class Player:
def __init__(self,name, hand, discard_pile, deck):
self.victory_points = 0
self.hand = hand
self.discard_pile = discard_pile
self.deck = deck
self.play_area = []
self.name = name
self.actions_remaining = 1
self.buys_remaining = 1
self.coins_elsewhere = 0
self.coins_spent = 0
def set_starting_deck(self):
for i in range(7): self.deck.append(Copper())
for i in range(3): self.deck.append(Estate())
random.shuffle(self.deck)
def shuffle(self):
random.shuffle(self.discard_pile)
self.deck += self.discard_pile
self.discard_pile = []
def draw(self,number_of_cards):
for i in range(number_of_cards):
if len(self.deck) + len(self.discard_pile) == 0:
print('No cards left,',self.name,'drew their deck!')
else:
if len(self.deck) == 0:
print("Out of cards, shuffling")
self.shuffle()
print(self.name,'draws a card')
self.hand.append(self.deck.pop(0))
def discard(self):
self.discard_pile += self.hand
self.discard_pile += self.play_area
self.hand = []
self.play_area = []
def display_all(self,game):
print(self.name,'\'s hand is:',sep='')
print([card for card in self.hand])
#print(self.name,'deck is:',[card for card in self.deck])
#print(self.name,'discard pile is:',[card for card in self.discard_pile])
#print(self.name,'play area is:',[card for card in self.play_area])
print('Available:',self.actions_remaining,'actions,',self.buys_remaining,'buys,',self.count_coins(),'coins')
print('Cards for purchase: ',game.display_supply())
def reset_resources(self):
self.actions_remaining = 1
self.buys_remaining = 1
self.coins_elsewhere = 0
self.coins_spent = 0
def count_coins(self):
return sum(card.coin_value for card in self.hand) + self.coins_elsewhere - self.coins_spent
def trigger_reactions(self,attacking_player,attack,game):
reactions = [card for card in self.hand if 'Reaction' in card.type]
results = []
for reaction in reactions:
results.append(reaction.trigger(self,attacking_player,attack,game))
return sum(results) >= 1
def take_turn(self,game):
print(self.name,'\'s turn begins',sep='')
self.reset_resources()
self.display_all(game)
game.turn_phase = 'Action'
while game.turn_phase == 'Action' and game.running:
game = self.action(game)
while game.turn_phase == 'Buy' and game.running:
game = self.buy(game)
while game.turn_phase == 'Cleanup' and game.running:
self.discard()
self.draw(5)
game.turn_phase = 'Beginning'
return 'Turn over'
def action(self,game):
if sum('Action' in card.type for card in self.hand) == 0:
print('No actions in hand, buy phase begins')
game.turn_phase = 'Buy'
return game
if self.actions_remaining <= 0:
print('No actions for turn remaining, buy phase begins')
game.turn_phase = 'Buy'
return game
print('Actions in hand:',[card.name for card in self.hand if 'Action' in card.type])
command = game.input_handler(str(self.name+', enter action to play it, or enter Skip: '),[card.name.lower() for card in self.hand if 'Action' in card.type]+['skip'])
if command == 'skip':
game.turn_phase = 'Buy'
return game
for i in range(len(self.hand)):
if self.hand[i].name.lower() == command:
self.play_area.append(self.hand.pop(i))
game = game.card_dict[command].resolve(self, game)
break
self.display_all(game)
return game
def buy(self,game):
command = game.input_handler(str(self.name+', enter a card to buy, or enter Skip: '),[card for card in game.card_dict.keys()]+['skip'])
if command == 'skip':
game.turn_phase = 'Cleanup'
return game
target = game.card_dict.get(command)
if game.supply.get(target.name,0) <= 0:
print("No more", target.name, "cards available")
return game
elif self.count_coins() < target.cost:
print("Not enough money to buy a", target.name)
return game
else:
self.discard_pile.append(target)
self.coins_spent += target.cost
self.buys_remaining -= 1
game.supply[target.name] -= 1
print(self.name, "bought a",target.name)
if self.buys_remaining <= 0:
game.turn_phase = 'Cleanup'
print('No buys remaining, cleanup phase begins')
return game
self.display_all(game)
return game
class Card:
def __init__(self):
self.victory_value = 0
self.coin_value = 0
self.cost = 0
self.name = ''
self.type = []
self.is_kingdom = True
self.description = ''
def resolve(self):
pass
def __repr__(self):
return self.name
def get_info(self):
return ' ' + self.name +'\n Type: ' +', '.join([type for type in self.type])+'\n Cost: '+str(self.cost)+ '\n Description: '+self.description
class Copper(Card):
def __init__(self):
Card.__init__(self)
self.coin_value = 1
self.name = 'Copper'
self.type = ['Treasure']
self.is_kingdom = False
self.description = 'Treasure worth 1 coin'
class Curse(Card):
def __init__(self):
Card.__init__(self)
self.name = 'Curse'
self.type = ['Curse']
self.is_kingdom = False
self.victory_value = -1
self.description = 'Junk worth -1 victory points'
class Silver(Card):
def __init__(self):
Card.__init__(self)
self.cost = 3
self.coin_value = 2
self.name = 'Silver'
self.type = ['Treasure']
self.is_kingdom = False
self.description = 'Treasure worth 2 coins'
class Gold(Card):
def __init__(self):
Card.__init__(self)
self.cost = 6
self.coin_value = 3
self.name = 'Gold'
self.type = ['Treasure']
self.is_kingdom = False
self.description = 'Treasure worth 3 coins'
class Estate(Card):
def __init__(self):
Card.__init__(self)
self.victory_value = 1
self.name = 'Estate'
self.type = ['Victory']
self.is_kingdom = False
self.description = 'Victory card worth 1 victory point'
class Duchy(Card):
def __init__(self):
Card.__init__(self)
self.cost = 5
self.victory_value = 3
self.name = 'Duchy'
self.type = ['Victory']
self.is_kingdom = False
self.description = 'Victory card worth 5 victory points'
class Province(Card):
def __init__(self):
Card.__init__(self)
self.cost = 8
self.victory_value = 6
self.name = 'Province'
self.type = ['Victory']
self.is_kingdom = False
self.description = 'Victory card worth 8 victory points'
class Cellar(Card):
def __init__(self):
Card.__init__(self)
self.cost = 2
self.name = 'Cellar'
self.type = ['Action']
self.description = '+1 Action. Discard any number of cards, then draw that many cards.'
def resolve(self,player,game):
print(player.name,'plays a',self.name)
cards_discarded = 0
command = ''
while command != 'stop':
print(player.name,'\'s hand is:',[card for card in player.hand])
command = game.input_handler(str(player.name+', enter a card to discard, or enter stop if finished: '),[key for key in game.card_dict]+['stop'])
if command == 'stop':
continue
if sum(card.name.lower() == command for card in player.hand) == 0:
print('No such card in hand, try again')
continue
if len(player.hand) > 0:
for i in range(len(player.hand)):
if player.hand[i].name.lower() == command:
print(player.name,'discards a',player.hand[i].name)
player.discard_pile.append(player.hand.pop(i))
cards_discarded +=1
break
else:
print('No more cards in hand to discard')
break
player.draw(cards_discarded)
return game
class Chapel(Card):
def __init__(self):
Card.__init__(self)
self.cost = 2
self.name = 'Chapel'
self.type = ['Action']
self.description = 'Trash up to 4 cards from your hand.'
self.cards_trashed = 0
def resolve(self,player,game):
print(player.name,'plays a',self.name)
self.cards_trashed = 0
command = ''
while command != 'stop' and self.cards_trashed < 4:
print(player.name,'\'s hand is:',[card for card in player.hand])
command = game.input_handler(str(player.name+', enter a card to trash, or enter stop if finished: '),[key for key in game.card_dict]+['stop'])
if command == 'stop':
continue
if sum(card.name.lower() == command for card in player.hand) == 0:
print('No such card in hand, try again')
continue
if len(player.hand) > 0:
for i in range(len(player.hand)):
if player.hand[i].name.lower() == command:
print(player.name,'trashes a',player.hand[i].name)
game.trash_pile.append(player.hand.pop(i))
self.cards_trashed += 1
break
else:
print('No more cards in hand to trash')
break
print(player.name,'finished resolving',self.name)
player.actions_remaining -= 1
return game
class CouncilRoom(Card):
def __init__(self):
Card.__init__(self)
self.cost = 5
self.name = 'Council Room'
self.type =['Action']
self.description = '+4 cards, +1 buy. Each other play draws a card.'
def resolve(self,player,game):
print(player.name,'plays a',self.name)
player.draw(4)
player.buys_remaining += 1
for person in game.players:
if person.name != player.name:
person.draw(1)
player.actions_remaining -= 1
return game
class Harbinger(Card):
def __init__(self):
Card.__init__(self)
self.cost = 3
self.name = 'Harbinger'
self.type = ['Action']
self.description = '+1 Card, +1 Action. Look through your discard pile. You may put a card from it on top of your deck.'
def resolve(self,player,game):
print(player.name,'plays a',self.name)
command = ''
while command != 'skip':
print(player.name,'\'s discard pile is:',[card for card in player.discard_pile])
command = game.input_handler(str(player.name+', enter a card to put on top of your deck, or enter skip: '),[key for key in game.card_dict]+['skip'])
if command == 'skip':
continue
if sum(card.name.lower() == command for card in player.discard_pile) == 0:
print('No such card in discard pile, try again')
continue
if len(player.discard_pile) > 0:
for i in range(len(player.discard_pile)):
if player.discard_pile[i].name.lower() == command:
print(player.name,'puts a',player.discard_pile[i].name,'on top of their deck.')
player.deck.insert(0,player.discard_pile.pop(i))
break
break
else:
print('No cards in discard pile')
break
return game
class Market(Card):
def __init__(self):
Card.__init__(self)
self.cost = 5
self.name = 'Market'
self.type = ['Action']
self.description = '+1 card, +1 action, +1 buy, +1 coin.'
def resolve(self,player, game):
print(player.name,'plays a',self.name)
player.draw(1)
player.buys_remaining += 1
player.coins_elsewhere += 1
return game
class Moat(Card):
def __init__(self):
Card.__init__(self)
self.cost = 2
self.name = 'Moat'
self.type = ['Action','Reaction']
self.description = '+2 cards. Whenever another player plays an attack card, you may reveal this to be unaffected by the attack.'
def trigger(self,owning_player,attacking_player,attack,game):
print('Hey ',owning_player.name,', ',attacking_player.name,' is playing a ',attack.name,'!. Reveal Moat to nullify the attack against you?',sep = '')
command = game.input_handler('Enter Y or N: ',['y','n'])
if command == 'y':
print(owning_player.name,'reveals a',self.name,'and is unaffected by',attack.name,'.')
return True
else:
print(owning_player.name,'declines to reveal',self.name)
return False
def resolve(self,player, game):
print(player.name,'plays a',self.name)
player.draw(2)
player.actions_remaining -= 1
return game
class Moneylender(Card):
def __init__(self):
Card.__init__(self)
self.cost = 4
self.name = 'Moneylender'
self.type = ['Action']
self.description = 'You may trash a Copper from your hand for 3 coins.'
def resolve(self,player, game):
print(player.name,'plays a',self.name)
if sum(card.name == 'Copper' for card in player.hand) > 0:
command = game.input_handler('Trash a Copper for 3 coins? Enter Y or N: ',['y','n'])
if command == 'y':
player.coins_elsewhere += 3
print(player.name, 'trashed a Copper for 3 coins.')
for i in range(len(player.hand)):
if player.hand[i].name == 'Copper':
game.trash_pile.append(player.hand.pop(i))
break
else:
print('No coppers in hand, nothing to trash')
player.actions_remaining -= 1
return game
class Smithy(Card):
def __init__(self):
Card.__init__(self)
self.cost = 4
self.name = 'Smithy'
self.type = ['Action']
self.description = '+3 cards.'
def resolve(self,player, game):
print(player.name,'plays a',self.name)
player.draw(3)
player.actions_remaining -= 1
return game
class ThroneRoom(Card):
def __init__(self):
Card.__init__(self)
self.cost = 4
self.name = 'Throne Room'
self.type = ['Action']
self.description = 'You may play an action card from your hand twice.'
def resolve(self,player, game):
print(player.name,' plays a',self.name)
player.actions_remaining -= 1
command = ''
while command != 'skip':
if sum('Action' in card.type for card in player.hand) > 0:
print('Actions in hand:',[card for card in player.hand if 'Action' in card.type])
command = game.input_handler(str(player.name+', enter a card to play twice, or enter skip to cancel: '),[key for key in game.card_dict]+['skip'])
if command == 'skip':
continue
if sum(card.name.lower() == command for card in player.hand) == 0:
print('No such card in hand, try again')
continue
if len(player.hand) > 0:
for i in range(len(player.hand)):
if player.hand[i].name.lower() == command:
player.actions_remaining += 2
player.play_area.append(player.hand.pop(i))
game = game.card_dict[command].resolve(player, game)
game = game.card_dict[command].resolve(player, game)
break
break
else:
print('No actions in hand, nothing to',self.name)
break
return game
class Vassal(Card):
def __init__(self):
Card.__init__(self)
self.cost = 3
self.name = 'Vassal'
self.type = ['Action']
self.description = '+2 coins. Discard the top card of your deck. If it\'s an action card, you may play it.'
def resolve(self,player,game):
print(player.name,' plays a',self.name)
if len(player.deck) < 1:
print('No cards remaining in deck, so nothing discarded to',self.name)
else:
target = player.deck[0]
print(player.name,'discards a',target.name)
if 'Action' in target.type:
command = game.input_handler(str('Play the discarded '+target.name+'? Enter Y or N: '),['y','n'])
if command == 'y':
player.play_area.append(player.deck.pop(0))
game = target.resolve(player, game)
else:
player.discard_pile.append(player.deck.pop(0))
else:
player.discard_pile.append(player.deck.pop(0))
player.coins_elsewhere += 2
player.actions_remaining -= 1
return game
class Village(Card):
def __init__(self):
Card.__init__(self)
self.cost = 3
self.name = 'Village'
self.type = ['Action']
self.description = '+1 card, +2 actions.'
def resolve(self,player,game):
print(player.name,' plays a',self.name)
player.draw(1)
player.actions_remaining += 1
return game
class Witch(Card):
def __init__(self):
Card.__init__(self)
self.cost = 5
self.name = 'Witch'
self.type = ['Action']
self.description = '+2 cards. Each other player gains a Curse.'
def resolve(self,player,game):
immunity = False
print(player.name,'plays a',self.name)
player.draw(2)
player.actions_remaining -= 1
for victim in game.players:
if victim.name != player.name:
immunity = victim.trigger_reactions(player,self,game)
if immunity == False:
if game.supply['Curse'] > 0:
victim.discard_pile.append(Curse())
game.supply['Curse'] -= 1
print(victim.name,'gains a Curse')
else:
print('No curses remain,',victim.name,'is unaffected by Witch')
immunity = False
return game
class Workshop(Card):
def __init__(self):
Card.__init__(self)
self.cost = 3
self.name = 'Workshop'
self.type = ['Action']
self.description = 'Gain a card costing up to 4.'
def resolve(self,player,game):
print(player.name,'plays a',self.name)
command = game.input_handler('Enter a card to gain, costing up to 4: ',[card.lower() for card in game.supply.keys() if game.supply.get(card,0) > 0])
while game.card_dict.get(command,0).cost > 4:
command = game.input_handler('Too expensive, enter another card: ',[card.lower() for card in game.supply.keys() if game.supply.get(card,0) > 0])
target = game.card_dict.get(command)
player.discard_pile.append(game.card_dict[target.name.lower()])
game.supply[target.name] -= 1
print(player.name,'gained a ',target.name)
player.actions_remaining -= 1
return game
def load_game(filename):
save_file = shelve.open(filename)
loaded_game = Game(save_file['Name'],save_file['Card Dict'],save_file['Supply'],save_file['Trash'],save_file['Players'])
loaded_game.play_game(True)
master_card_dict = {'gold':Gold(),'silver':Silver(),'copper':Copper(),'estate':Estate(),'duchy':Duchy(),'province':Province(),
'smithy':Smithy(),'village':Village(),'cellar':Cellar(),'moat':Moat(),'harbinger':Harbinger(),'moneylender':Moneylender(),'council room':CouncilRoom(),'throne room':ThroneRoom(),'curse':Curse(),'witch':Witch(),'chapel':Chapel(),'vassal':Vassal(),'market':Market(),'workshop':Workshop()}
mygame = Game('My game',master_card_dict,{},[],[])
mygame.new_game()
|
0e99419b90d9bdaafa76ebbda14479182632f074 | dzieber/python-crash-course | /ch4/dimensions.py | 492 | 3.828125 | 4 | '''
chapter 4, Tuples
'''
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
# to copy a tuple into a list you have to cast it
temp_dimensions = list(dimensions[:])
print(temp_dimensions)
temp_dimensions[0] = 250
print(temp_dimensions)
# and it works the other way as well. Note that you don't need to make it
# a slice when copying with the type cast
dimensions = tuple(temp_dimensions)
print(dimensions)
temp_dimensions.append(1000)
print(temp_dimensions)
print(dimensions)
|
43f1caa94b1a6e66ee5143314e66f9fa8b4fa190 | Williandasilvacode/Calculadora | /index.py | 1,064 | 4.34375 | 4 | print('\n <<------Calculadora Simples----->>')
print('+ Adição')
print('- Subtração')
print('* Multiplicação')
print('/ Divisão')
print('Presione a tecla "s" para encerra o programa!')
# (\n) faz uma quebra de linha
while True:
op = input('\n Qual operação deseja fazer? ')
if op == '+' or op =='-' or op =='*' or op =='/':
x = float(input('Digite o primeiro número:'))
y = float(input('Digite o segundo número:'))
if (op == '+'):
res = x + y
print('\n Resultado: {} + {} = {}'.format(x, y, res))
continue
elif (op == '-'):
res = x - y
print('\n Resultado: {} - {} = {}'.format(x, y, res))
continue
elif (op == '*'):
res = x * y
print('\n Resultado: {} * {} = {}'.format(x, y, res))
continue
elif (op == '/'):
res = x / y
print('\n Resultado: {} / {} = {}'.format(x, y, res))
continue
elif (op == 's'):
break
else:
print('\n Operação invalida!')
print('\n Encerrando o programa...!') |
72c6c1035e7eac46699d7b528415c3c567abec3c | prerna2896/Percept | /CreateDatabase.py | 2,293 | 4.25 | 4 | # A program to create the tables for the inventory database.
# There are 4 tables to store the data in the inventory.
# Table Users
# The username for the user
# The password for the user
# Table Students
# First Name of student
# Middle Name of student
# Last Name of student
# Age of student
# University of student
# Year of student
# Stream of student
# Table Mentors
# First Name of mentor
# Middle Name of mentor
# Last Name of mentor
# Age of mentor
# Profession of mentor
# Experience of mentor
# Interest of mentor
import sqlite3
# Create a connection with the database
conn = sqlite3.connect('Percept.db')
# cur is used to talk to the database
# cur.execute(Query) will execute queries
cur = conn.cursor()
#Create a table for the users with the login credentials of the user
# username and password
cur.execute("Create Table Users(" +
"Username VARCHAR(100) PRIMARY KEY, " +
"password VARCHAR(100) NOT NULL);")
conn.commit()
#Create a table for the details of student
# first name, middle name, last name, age, university, year, stream
cur.execute("Create Table Students(" +
"FirstName VARCHAR(100) NOT NULL, " +
"MiddleName VARCHAR(100), " +
"LastName VARCHAR(100) NOT NULL, " +
"age INT NOT NULL, " +
"University VARCHAR(100) NOT NULL, " +
"year INT NOT NULL, " +
"stream VARCHAR(100) NOT NULL, "
"Username VARCHAR(100) PRIMARY KEY, " +
"FOREIGN KEY(Username) REFERENCES Users(Username));" )
conn.commit()
#Create a table for the details of mentor
# first name, middle name, last name, age, profession, experience, interest
cur.execute("Create Table Mentors(" +
"FirstName VARCHAR(100) NOT NULL, " +
"MiddleName VARCHAR(100), " +
"LastName VARCHAR(100) NOT NULL, " +
"age INT NOT NULL, " +
"Profession VARCHAR(100) NOT NULL, " +
"Experience INT NOT NULL, " +
"Interest VARCHAR(100) NOT NULL, " +
"Username VARCHAR(100) PRIMARY KEY, " +
"FOREIGN KEY(Username) REFERENCES Users(Username));" )
conn.commit() |
4dd4c5e53ac89e98f775616d4158f76c72da9dab | jsngo/hackbright | /week3/sweep-count.py | 986 | 4.0625 | 4 | # http://labs.bewd.co/putting-it-together/
import csv
days_counts = {
"Mon": 0,
"Tues": 0,
"Wed": 0,
"Thu": 0,
"Fri": 0,
"Sat": 0,
"Sun": 0,
"Holiday": 0
}
ordered_days = [
"Mon",
"Tues",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun",
"Holiday"
]
def day_counter():
with open('sweep.csv') as f:
reader = csv.DictReader(f)
for row in reader:
day = row['WEEKDAY']
count = days_counts[day]
days_counts[day] += 1
for d in ordered_days:
print "{} blocks swept on {}".format(days_counts[d], d)
def swept_most():
max_sweeps = 0
max_day = ""
for d in days_counts:
if days_counts[d] > max_sweeps:
max_sweeps = days_counts[d]
max_day = d
print "{} is the day with the most street sweeping: {}".format(max_day, max_sweeps)
def main():
day_counter()
print "\n"
swept_most()
if __name__=="__main__":
main() |
9cded9d0208286821735967df6ad0172606b5024 | keivanipchihagh/Intro-to-ML-and-Data-Science | /Courses/MIT-OpenCourseWare/MIT-6.0001/Lecture 8 - Object Oriented Programming/My codes/Object Oriented Programming.py | 1,380 | 3.875 | 4 | class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
c = Coordinate(3,4)
origin = Coordinate(0,0)
print(c.distance(origin))
print(Coordinate.distance(c, origin))
print(origin.distance(c))
class Fraction(object):
def __init__(self, num, denom):
assert type(num) == int and type(denom) == int,
self.num = num
self.denom = denom
def __str__(self):
return str(self.num) + "/" + str(self.denom)
def __add__(self, other):
top = self.num*other.denom + self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __sub__(self, other):
top = self.num*other.denom - self.denom*other.num
bott = self.denom*other.denom
return Fraction(top, bott)
def __float__(self):
return self.num/self.denom
def inverse(self):
return Fraction(self.denom, self.num)
a = Fraction(1,4)
b = Fraction(3,4)
c = a + b
print(Fraction.__float__(c))
print(float(b.inverse()))
#c = Fraction(3.14, 2.7) # assertion error
#print a*b # error, did not define how to multiply two Fraction objects
|
59246d41af97e32e491bab6c3dc97bed24474815 | pipazi/leetcode | /index/2.py | 615 | 3.5625 | 4 | from util.ListNode import ListNode
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a = l3 = ListNode(0)
quo = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
res = x + y + quo
rem = res if res < 10 else res - 10
quo = 0 if res < 10 else 1
l3.next = ListNode(rem)
if l1:
l1 = l1.next
if l2:
l2 = l2.next
l3 = l3.next
if quo:
l3.next = ListNode(quo)
return a.next
|
838a43a53a5473563c2cf47dbcadf2e9ab5e87de | abhisheksahu92/Programming | /Solutions/93-Sentence from list of words.py | 1,060 | 4.15625 | 4 | # Recursively print all sentences that can be formed from list of word lists
# Given a list of word lists How to print all sentences possible taking one word from a list at a time via recursion?
# Example:
#
# Input: {{"you", "we"},
# {"have", "are"},
# {"sleep", "eat", "drink"}}
#
# Output:
# you have sleep
# you have eat
# you have drink
# you are sleep
# you are eat
# you are drink
# we have sleep
# we have eat
# we have drink
# we are sleep
# we are eat
# we are drink
def sentence_from_list(d1,d2,d3):
x = 0
y = 0
z = 0
while True:
if x < len(d1):
if y < len(d2):
if z < len(d3):
print(d1[x],d2[y],d3[z])
z += 1
else:
y += 1
z = 0
else:
x += 1
y = 0
else:
break
for value in [[["you", "we"],["have", "are"],["sleep", "eat", "drink"]]]:
print(f'Input is {value}')
sentence_from_list(*value) |
4182910fe564422cb6fbe07d5037f71b00219414 | hazzel-cn/leetcode-python | /80.py | 848 | 3.5625 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
j = 0
jcount = 0
for i in range(1, len(nums)):
if nums[i] == nums[j]:
jcount += 1
# When two elements equal to each other
# the former one can be replaced only
# when in first two rounds. After that,
# j should not be changed.
if jcount < 2:
nums[j+1] = nums[i]
j += 1
else:
nums[j+1] = nums[i]
jcount = 0
j += 1
# print nums
return j + 1
if __name__ == '__main__':
print Solution().removeDuplicates([1,1]) |
0abbb4ed4b69676ee6d58292bb04153879c2cf64 | momentum-team-6/python-oo-money-matthewbenton224 | /blackjack.py | 547 | 3.734375 | 4 | SUITS = ["♥️", "♠️", "♣️", "♦️"]
RANKS = ["Ace", "J", "Q", "K", 2, 3, 4, 5, 6, 7, 8, 9, 10]
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'card is a {self.rank} of {self.suit}'
class Deck:
def __init__(self, suits, ranks):
self.cards = []
for suit in suits:
for rank in ranks:
self.cards.append(Card(suit, rank))
my_deck = Deck(SUITS, RANKS)
for card in my_deck.cards:
print(card)
|
b4d19986fe7e9137c3b9bfcc97cfdaa073692160 | nbrahman/HackerRank | /02 30 Days of Code Challenges/Day11-2D-Arrays.py | 2,038 | 4.125 | 4 | '''
Objective
Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!
Context
Given a 6 X 6 2D Array, A:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation:
a b c
d
e f g
There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass' values.
Task
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.
Input Format
There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array A; every value in A will be in the inclusive range of -9 to 9.
Constraints
-9<=A[i][j]=<=9
0<=i,j<=5
Output Format
Print the largest (maximum) hourglass sum found in A.
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
Explanation
A contains the following hourglasses:
1 1 1 1 1 0 1 0 0 0 0 0
1 0 0 0
1 1 1 1 1 0 1 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0
1 1 0 0
0 0 2 0 2 4 2 4 4 4 4 0
1 1 1 1 1 0 1 0 0 0 0 0
0 2 4 4
0 0 0 0 0 2 0 2 0 2 0 0
0 0 2 0 2 4 2 4 4 4 4 0
0 0 2 0
0 0 1 0 1 2 1 2 4 2 4 0
The hourglass with the maximum sum (19) is:
2 4 4
2
1 2 4
'''
#!/bin/python3
import sys
def findMaxHourglassSum(arr):
max = -10000000
for i in range(len(arr)-2):
for j in range(len(arr[0])-2):
sumHourGlass = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] \
+ arr[i + 1][j + 1] \
+ arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]
if max < sumHourGlass:
max = sumHourGlass
return max
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
print (findMaxHourglassSum(arr)) |
33636ed7a66b1a87961c8f5c4e979606f77ba803 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/maths/is_strobogrammatic.py | 731 | 4.3125 | 4 | """
A strobogrammatic number is a number that looks
the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic.
The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
"""
def is_strobogrammatic(num):
"""
:type num: str
:rtype: bool
"""
comb = "00 11 88 69 96"
i = 0
j = len(num) - 1
while i <= j:
x = comb.find(num[i]+num[j])
if x == -1:
return False
i += 1
j -= 1
return True
def is_strobogrammatic2(num: str):
"""Another implementation."""
return num == num[::-1].replace('6', '#').replace('9', '6').replace('#', '9')
|
dd47a473a78bee9e24b56cd91a7627f1ef6fb27d | maykkk1/curso-em-video-python | /exercicios/MUNDO 1/Condições (Parte 1)/ex032.py | 466 | 3.9375 | 4 | from datetime import date
x = int(input('digite o ano '))
if x == 0:
x = date.today().year
if x > 3:
r4 = x % 4
r100 = x % 100
r400 = x % 400
if r100 == 0:
if r400 == 0:
print('Esse ano é bissexto')
else:
print('Esse ano não é bissexto')
if r4 == 0 and r100 != 0:
print('Esse ano é bissexto')
else:
print('Esse ano não é bissexto')
else:
print('Esse ano não é bissexto') |
eab354b7e65ba7d8fd766e037f8e5e5097a37224 | rendersonjunior/UriOnlineJudge-Python | /1051_Taxes.py | 689 | 3.828125 | 4 | # Taxes
def main():
salary_taxes = [(0.00, 2000.00, 0.00),
(2000.01, 3000.00, 0.08),
(3000.01, 4500.00, 0.18),
(4500.00, 9999999999999.00, 0.28)]
salary_taxes.sort(reverse=True)
salary = float(input())
salary_tax = 0
for min_s, max_s, perc_s in salary_taxes:
if min_s <= salary <= max_s:
tax_value = round((salary - round(min_s)), 2)
salary_tax += round((tax_value * perc_s), 2)
salary -= tax_value
if salary_tax > 0:
print("R$ %.2f" % salary_tax)
else:
print("Isento")
if __name__ == "__main__":
main()
|
86d9214e5c4b4e43ab21b182cd28bd1769074592 | TheAutomationWizard/learnPython | /pythonUdemyCourse/Interview_Questions/LogicMonitor/Reverse_strings.py | 2,298 | 4.34375 | 4 | """
Available Concepts :
1) slicing
2) reversed keyword
3) join keyword
4) list comprehension
"""
"""
Reverse a string
"""
def string_reversal_one(*args):
for input in args:
print('Original \t : ', input, '\nReversed\t : ', input[::-1], '\n' + '*' * 40)
def string_reversal_two(*args):
for test_string in args:
output = ''
for char in test_string:
output = char + output
print('Original \t : ', test_string, '\nReversed\t : ', output, '\n' + '*' * 40)
def string_reversal_three(string):
if len(string) == 0:
return string
else:
return string_reversal_three(string[1:]) + string[0]
def string_reversal_four(*args):
for input in args:
print('Original \t : ', input, '\nReversed\t : ', "".join(reversed(input)), '\n' + '*' * 40)
string1 = 'Test this string'
string2 = 'Aditya'
string3 = 'Reverse It'
string_reversal_one(string1, string2, string3)
string_reversal_two(string1, string2, string3)
print('\n', string_reversal_three(string1), '\n')
string_reversal_four(string1, string2, string3)
"""
:: String Palindrome ::
"""
def multiple_ways_to_check_palindrome(input):
if input == input[::-1]:
if input == "".join(reversed(input)):
if input == "".join([last_Char for last_Char in reversed(input)]):
temp = ""
if input == "".join([last_Char + temp for last_Char in input]):
print('Yes a Palindrome')
return
else:
print('Failed Method 3')
else:
print('Failed Method 2')
else:
print('Failed Method 1')
print('Not a Palindrome')
multiple_ways_to_check_palindrome('abccba')
multiple_ways_to_check_palindrome('abccbao')
def integer_palindrome(*args):
for integer_number in args:
temp = 0
copy_number = integer_number
for counter in range(0, len(str(integer_number))):
temp = 10 * temp + copy_number % 10
copy_number = int(copy_number / 10)
if integer_number == temp:
print(f'{integer_number} is a palindrome.')
else:
print(f'{integer_number} is not a palindrome.')
integer_palindrome(121, 1001, 1001, 110, 1010, 1221)
|
643d89e1ee42170a18a516e86e0f89b25e9c5977 | thanhdao/data_science | /histogram.py | 164 | 3.59375 | 4 | import matplotlib.pyplot as plt
numbers = [0.1, 0.5, 1, 1.5, 2, 4, 5.5, 6, 8, 9]
plt.hist(numbers, bins=3)
plt.xlabel('Number')
plt.ylabel('Frequency')
plt.show() |
6edcb3df883d5de2de49413dfd64a39c9c98b8e2 | danielsimonebeira/cesusc-lista1 | /exe26.py | 1,359 | 4 | 4 | # 26 - Faça um programa que receba duas listas e
# retorne True se são iguais ou
# False caso contrário,
# além do número de ocorrências do primeiro elemento da lista.
import random
def gera_lista(numero_lista):
lista = []
contador = 1
quantidade = random.randint(2, 9)
while contador < quantidade:
variavel = random.randint(1, 9)
lista.append(variavel)
contador += 1
print("Lista {} gerada: {}".format(numero_lista, lista))
return lista
def valida_true_false(lista1, lista2):
resultado = False
for x in lista1:
for y in lista2:
if x == y:
resultado = True
return resultado
return resultado
def numero_ocorrencia(lista1, lista2):
posicao_lista1 = lista1[0]
posicao_lista2 = lista2[0]
uniao_lista = lista1 + lista2
posicao_uniao_lista = uniao_lista[0]
print("Número de ocorrências do primeiro elemento da lista1: ", lista1.count(posicao_lista1))
print("Número de ocorrências do primeiro elemento da lista2: ", lista2.count(posicao_lista2))
print("Número de ocorrências do primeiro elemento da união das listas: ", uniao_lista.count(posicao_uniao_lista))
lista1 = gera_lista(1)
lista2 = gera_lista(2)
print("\nResultado: ", valida_true_false(lista1, lista2), "\n")
numero_ocorrencia(lista1, lista2)
|
edd8ae88bdb716c28936f6ba5eae0823e83962f7 | beenorgone-notebook/python-notebook | /py-recipes/mutilpe_dispatch-rock_paper_scissors.py | 2,049 | 3.65625 | 4 | # To explain how multiple dispatch can make more readable and less
# bug-prone code, let us implement the game of rock/paper/scissors in
# three styles.
class Thing(object):
pass
class Rock(Thing):
pass
class Paper(Thing):
pass
class Scissors(Thing):
pass
# First, a purely imperative version
def beats(x, y):
if isinstance(x, Rock):
if isinstance(y, Rock):
return None # No winner
elif isinstance(y, Paper):
return y
elif isinstance(y, Scissors):
return x
else:
raise TypeError("Unknown second thing.")
if isinstance(x, Paper):
if isinstance(y, Paper):
return None # No winner
elif isinstance(y, Scissors):
return y
elif isinstance(y, Rock):
return x
else:
raise TypeError("Unknown second thing.")
if isinstance(x, Scissors):
if isinstance(y, Scissors):
return None # No winner
elif isinstance(y, Rock):
return y
elif isinstance(y, Paper):
return x
else:
raise TypeError("Unknown second thing.")
# Mulitple dispatch version:
from multipledispatch import dispatch
@dispatch(Rock, Rock)
def beats_dp(x, y): return None
@dispatch(Rock, Scissors)
def beats_dp(x, y): return x
@dispatch(Rock, Paper)
def beats_dp(x, y): return y
@dispatch(Paper, Paper)
def beats_dp(x, y): return None
@dispatch(Paper, Scissors)
def beats_dp(x, y): return y
@dispatch(Paper, Rock)
def beats_dp(x, y): return x
@dispatch(Scissors, Scissors)
def beats_dp(x, y): return None
@dispatch(Scissors, Rock)
def beats_dp(x, y): return y
@dispatch(Scissors, Paper)
def beats_dp(x, y): return x
@dispatch(object, object)
def beats_dp(x, y):
if not isinstance(x, (Rock, Paper, Scissors)):
raise TypeError("Unknown first thing")
else:
raise TypeError("Unknown second thing")
r, s, p = Rock(), Scissors(), Paper()
print(beats(r, s))
print(beats_dp(s, p))
|
03da09f98cc59fcd777c511991bf42e2869abdd6 | FronTexas/Fron-Algo-practice | /beautifuly.py | 2,871 | 3.59375 | 4 | def isOdd(n):
return n % 2 != 0
def beautifulSubarrays(a, m):
dp = [0 for i in range(len(a))]
dp[0] = 1
ans = 0
odd_counter = 0
for i in range(1,len(dp)):
if isOdd(a[i]):
if odd_counter + 1 > m:
ans += 1
odd_counter = m
dp[i] = 1
elif odd_counter + 1 == m:
ans += dp[i-1]
odd_counter += 1
if odd_counter == 1: dp[i] = 1
dp[i] += dp[i-1]
else:
odd_counter += 1
if odd_counter == 1: dp[i] = 1
dp[i] += dp[i-1]
else:
if odd_counter == m:
ans += dp[i-1]
dp[i] = dp[i-1]
else:
dp[i] = dp[i-1]
print 'dp = ' + str(dp)
return ans
def __beautifulSubarrays(a, m):
dp = [0 for i in range(len(a))]
dp[0] = 1
answer = 0
odd_counter = 0
for i in range(1,len(dp)):
if isOdd(a[i]):
if odd_counter + 1 == m:
answer += dp[i-1]
odd_counter = 1
dp[i] = dp[i-1]
else:
odd_counter += 1
dp[i] = dp[i-1] + 1
else:
dp[i] = dp[i-1]
return answer
def _beautifulSubarrays(a, m):
dp = [0 for i in range(len(a))]
dp[0] = 1
answer = 0
odd_counter = 0
for i in range(1,len(dp)):
if odd_counter == m:
answer += dp[i-1]
if isOdd(a[i]):
if odd_counter + 1 > m:
odd_counter = 0
if odd_counter + 1 == m:
answer += dp[i-1]
dp[i] = dp[i-1]
else:
dp[i] = dp[i-1] + 1
odd_counter += 1
else:
dp[i] = dp[i-1]
return answer
def countOdds(a):
return sum([1 if isOdd(e) else 0 for e in a ])
def bruteForce(a,m):
answer = 0
for i in range(len(a)):
for j in range(i,len(a)):
if countOdds(a[i:j+1]) == m:
answer += 1
return answer
def test(actual,expected,_input):
print 'input = ' + str(_input)
if actual != expected:
print '** FAILED **'
print 'actual = ' + str(actual)
print 'expected = ' + str(expected)
else:
print 'actual = ' + str(actual)
print 'PASSED'
print '----'
a = [2,5,4,9]
m = 2
test(beautifulSubarrays(a,m),bruteForce(a,m),(a,m))
a = [2,5,4,9]
m = 3
test(beautifulSubarrays(a,m),bruteForce(a,m),(a,m))
a = [2,5,4,9,11]
m = 2
test(beautifulSubarrays(a,m),bruteForce(a,m),(a,m))
a = [2,5,4,9,2,2,2,2,2,2,2,2,2,2,2,11,13]
m = 2
test(beautifulSubarrays(a,m),bruteForce(a,m),(a,m))
a = [2,5,4,9]
m = 1
test(beautifulSubarrays(a,m),bruteForce(a,m),(a,m))
|
0d9d78880f6718a982379f6cff4cc7f9b0c08d0f | MrJouts/learn-python | /ch6/04.glossary2.py | 418 | 3.8125 | 4 | glossary = {
"string": "chain of characters",
"indentation": "left espace at the beginning of a line",
"if": "conditional clause",
"or": "comparicion operator",
"python": "Programming language",
"for": "loop through a list",
"dictionaries": "key value pair storage",
"list": "list of values",
}
for word, meaning in glossary.items():
print(str(word.title()) + ": " + str(meaning))
|
e3fb2935b7a3453d1b42e6ad60f7dc4cd3ac0fef | Matheus-Novoa/Python-Scripts | /neural_network/neural_network.py | 1,693 | 4.15625 | 4 | import numpy as np
def sigmoid(x):
# Activation function: f(x) = 1 / (1 + e^(x))
return 1 / (1 + np.exp(-x))
def deriv_sigmoid(x):
"""Derivate of sigmoid: f'(x) = f(x) * (1 - f(x))
Args:
x (float): Sigmoid function argument
Returns:
float: Sigmoid function derivate
"""
fx = sigmoid(x)
return fx + (1 - fx)
def mse_loss(y_true, y_pred):
# y_true and y_pred are numpy arrays of the same length.
return ((y_true - y_pred) ** 2).mean()
# class Neuron:
# def __init__(self, weights, bias):
# self.weights = weights
# self.bias = bias
# def feedforward(self, inputs):
# Weight inputs, add bias, then use the activation function
# total = np.dot(self.weights, inputs) + self.bias
# return sigmoid(total)
class OurNeuralNetwork:
"""
A neural network with:
- 2 inputs
- a hidden layer with 2 neurons (h1, h2)
- an output layer with 1 neuron (o1)
"""
def __init__(self):
weights = np.array([0, 1])
bias = 0
# The Neuron class here is from the previous section
self.h1 = Neuron(weights, bias)
self.h2 = Neuron(weights, bias)
self.o1 = Neuron(weights, bias)
def feedforward(self, x):
out_h1 = self.h1.feedforward(x)
out_h2 = self.h2.feedforward(x)
# The inputs for o1 are the outputs from h1 and h2
out_o1 = self.o1.feedforward(np.array([out_h1, out_h2]))
return out_o1
# network = OurNeuralNetwork()
# x = np.array([2, 3])
# print(network.feedforward(x))
y_true = np.array([1, 0, 0, 1])
y_pred = np.array([0, 0, 0, 0])
print(mse_loss(y_true, y_pred))
|
94df0b1a6e328cccbd94960edbe0db4ff8cb0c1d | BenjaminElifLarsen/PythonPratice | /class.py | 1,259 | 3.8125 | 4 | class TestingClass:
__privateValue = 4
_protectedValue = 3
def __init__(self):
self.__number = 5
def GetValue(self):
return self.__privateValue
def SetValue(self,value):
self.__privateValue = value
@property
def value(self):
return self.__number
@value.setter
def value(self, value):
self.__number = value
class Person:
something = "old"
def __init__(self, name, age):
self.name = name
self.age = age
def sayMyName(self):
return self.name
def testing(self):
return self.sayMyName() + " 2"
class Kid(Person):
kidStuff = "bugs"
def __init__(self, firstName, lastName, age):
super().__init__(firstName + " " + lastName, age)
def nestedFunction(self):
print("Outer")
def innerFunction():
print("Inner")
innerFunction()
p1 = TestingClass()
try:
print(p1.__number)
p1.__number = 2
p1.__number = 15
print(p1.__number)
except Exception as e:
print(e)
try:
print(p1.value)
p1.value = 223
print(p1.value)
except Exception as e:
print(e)
p2 = Person("Bob",1223)
print(p2.name + " " + str(p2.age) + " is " + p2.something)
print(p2.sayMyName())
print(p2.testing())
k1 = Kid("Kid", "Ding",5)
print(k1.sayMyName())
print(k1.kidStuff)
k1.nestedFunction() |
bd3e8d1670f528401a2a16088c26322131dce209 | suresh3870/WorkingWithPy | /addnumber.py | 106 | 3.6875 | 4 | # program to add
a=5
b=10
def add_number (x,y):
z= x+y
return z
c= add_number(a, b)
print(c) |
c0dc2e4ae61ca0653d8036521fc7859c86def1d0 | madeibao/PythonAlgorithm | /PartA/PyMapFunction2.py | 224 | 3.5625 | 4 |
m2 = [1, 2, 3, 4, 5, 6, 7]
print(list(map(lambda x: x+10, m2)))
# 结果为:[11, 12, 13, 14, 15, 16, 17]
res = lambda sex:"带把的" if sex == "男" else "仙女降世"
res2 = res("男")
print(res2)
|
015b5a144fa84b43ad034e6bc83cf5eafb48da5b | antrent/Cursos | /01_datos.py | 641 | 3.859375 | 4 | x = 'Hola'
print(x,type(x))
# Tipado dinamico
x = 34
print(x,type(x))
# Tipado estatico (OTROS LENGUAJES), no existe en Python
# Tipado float
x = 34.78
print(x,type(x))
# Tipado palabras reservadas
x = True
print(x,type(x))
x = False
print(x,type(x))
x = None
print(x,type(x))
# Tipos complejos
# listas, arrays, arreglos
c = ['Pepe', 23, True]
print(c,type(c))
# tupla, array inmutable
c = ('Pepe', 23, True)
print(c,type(c))
# set, array de elementos únicos
c = {'Pepe', 23, True}
print(c,type(c))
# diccionarios, array asociativos, hash, objetos, literales
c = {'nombre':'Pepe','edad':'23','isAlumno':True}
print(c,type(c)) |
d088ee076b5ed33903bb8c3f93134443b2c73859 | rbadvaith/Hybrid-Ciphers | /autokey2.py | 1,058 | 3.96875 | 4 | ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('enter message:\n')
key = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
if mode == 'encrypt':
cipher = encryptMessage(message, key)
elif mode == 'decrypt':
cipher = decryptMessage(message, key)
print(cipher)
def encryptMessage (messages, keys):
return cipherMessage(messages, keys, 'encrypt')
def decryptMessage(messages, keys):
return cipherMessage(messages, keys, 'decrypt')
def cipherMessage (messages, keys, mode):
cipher = []
k_index = 0
key = keys.upper()
for i in messages:
text = ALPHA.find(i.upper())
if mode == 'encrypt':
text += ALPHA.find(key[k_index])
key += i.upper()
elif mode == 'decrypt':
text -= ALPHA.find(key[k_index])
key += ALPHA[text]
text %= len(ALPHA)
k_index += 1
cipher.append(ALPHA[text])
return ''.join(cipher)
if __name__ == "__main__":
main()
|
1d72ca747228ee6fb74bce0bfc0eb597d156f620 | felipeonf/Exercises_Python | /exercícios_fixação/025.py | 383 | 4.125 | 4 | # Desenvolva um programa que leia um número inteiro e mostre se ele é PAR ou ÍMPAR.
stop = 'y'
while stop == 'y':
number = int(input('Write a number: '))
if number % 2 == 0:
print('This number is pair.')
else:
print('This number is odd.')
stop = input('Do you want to continue?(y/n)')
if stop == 'n':
print('Bye!')
|
79da11b8d911fc21de9d192f398aa2c076dc0e72 | wujjpp/tensorflow-starter | /py/l2.py | 2,213 | 3.84375 | 4 | # 关键字参数
def person(name, age, **kw):
if 'city' in kw:
# 有city参数
pass
if 'job' in kw:
# 有job参数
pass
print('name:', name, 'age:', age, 'other:', kw)
person('Jane', 20)
person('Jack', 20, city='Suzhou', job='Test')
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
person('Jack', 24, **extra)
# 关键字参数
def person2(name, age, *, city, job):
print('name:', name, 'age:', age, 'city:', city, 'job:', job)
person2('Jack', 24, city='SuZhou', job='Test')
# 关键字参数调用必须命名,下面代码将抛出异常
# person2('Jack', 24, 'Suzhou', 'Job')
# 如果函数定义中已经有了一个可变参数(*args),后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
def person3(name, age, *args, city, job):
print(name, age, args, city, job)
person3('Jack', 24, 'test1', 'test2', city='suzhou', job='test')
# 组合使用
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
f1(1, 2)
# a = 1 b = 2 c = 0 args = () kw = {}
f1(1, 2, c=3)
# a = 1 b = 2 c = 3 args = () kw = {}
f1(1, 2, 3, 'a', 'b')
# a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
f1(1, 2, 3, 'a', 'b', x=99)
# a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
f2(1, 2, d=99, ext=None)
# a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
# 递归函数
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(10))
# 尾递归 - Python不支持
def fact2(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)
print(fact(5))
# 汉诺塔: a:原始柱子, b:辅助柱子, c:目标柱子
def move(n, a, b, c):
if n == 1:
print(a, ' --> ', c)
else:
move(n - 1, a, c, b) # 把A柱上的n-1个珠子借助C, 移到B柱
move(1, a, b, c) # 把A柱上第n的珠子移到C柱
move(n - 1, b, a, c) # 把B柱上n-1个珠子借助A柱,移到C柱
move(3, 'A', 'B', 'C')
|
f2584a67cc6b402b3475b565aaeb916db9593216 | rakheg/calculator | /prj2calculator.py | 1,626 | 3.890625 | 4 | import tkinter as tk
from tkinter import messagebox
mainWindow=tk.Tk()
mainWindow.title("calculator")
heading_label1 = tk.Label(mainWindow,text="first number")
heading_label1.pack()
first_number=tk.Entry(mainWindow)
first_number.pack()
heading_label2= tk.Label(mainWindow,text="second number")
heading_label2.pack()
second_number=tk.Entry(mainWindow)
second_number.pack()
operations=tk.Label(mainWindow,text="operations")
operations.pack()
def addition():
number1=int(first_number.get())
number2=int(second_number.get())
add=number1+number2
print(add)
def subtraction():
number1=int(first_number.get())
number2=int(second_number.get())
sub=number1-number2
print(sub)
def multiply():
number1=int(first_number.get())
number2=int(second_number.get())
mul=number1*number2
print(mul)
def division():
number1=int(first_number.get())
number2=int(second_number.get())
try :
div = (number1 / number2)
print(div)
except ZeroDivisionError:
messagebox.showerror("error", "cannot divide by 0.")
add_button=tk.Button(mainWindow,text='+',command=lambda:addition())
add_button.pack()
sub_button=tk.Button(mainWindow,text='-',command=lambda:subtraction())
sub_button.pack()
mul_button=tk.Button(mainWindow,text='*',command=lambda:multiply())
mul_button.pack()
div_button=tk.Button(mainWindow,text='/',command=lambda:division())
div_button.pack()
result_label=tk.Label(mainWindow,text="operations result is:")
result_label.pack()
mainWindow.mainloop()
|
03db618b9ddc44eb97cc4e85b0e827c461a47509 | joy3968/Algorithm_Python | /stack.py | 429 | 4.09375 | 4 | ## Stack Class
class stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
# 비어있는지 확인하는 메서드
def isEmpty(self):
return not self.items
stk = stack()
print(stk)
print(stk.isEmpty())
stk.push(1)
stk.push(2)
print(stk.pop())
print(stk.pop())
print(stk.isEmpty()) |
841d906493793e8157b061633dff9e579bd1b2de | JoshW-G/peaDetection | /xml_to_csv.py | 1,299 | 3.59375 | 4 | ##
#Author: Josh Gardner
#Parses XML data into a pandas DataFrame to be saved in a csv
#
##
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
import argparse
import csv
def xml_to_csv(path):
#function to parse xml files and extract the data to a dataframe
xml_list = []
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (root.find('path').text,
int(member[4][0].text),
int(member[4][1].text),
int(member[4][2].text),
int(member[4][3].text),
member[0].text
)
xml_list.append(value)
column_name = ['path', 'x1', 'y1', 'x2', 'y2', 'class']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df
path = "Data/Slices/train"
xml_df = xml_to_csv(path)
xml_df.to_csv('train_labels.csv', index=None)
with open("classes.csv", mode='w', newline='') as class_file:
class_writer = csv.writer(class_file,delimiter=",",quotechar='"',quoting=csv.QUOTE_MINIMAL)
class_writer.writerow(["pea", 0])
print('Successfully converted xml to csv.')
|
327fe87813a71f0e02fffeaf9d8442c32185ce69 | Olddays/myExercise | /Python/LeetCodeTest/lc098_ValidateBinarySearchTree.py | 1,329 | 3.8125 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root:
dataSet = []
self.doCheck(root, dataSet)
for i in range(len(dataSet) - 1):
if dataSet[i] >= dataSet[i + 1]:
return False
return True
def doCheck(self, root: TreeNode, dataSet: List[int]):
if root.left:
self.doCheck(root.left, dataSet)
dataSet.append(root.val)
if root.right:
self.doCheck(root.right, dataSet)
if __name__ == "__main__":
solution = Solution()
input = TreeNode(2)
input.left = TreeNode(1)
input.right = TreeNode(3)
result = solution.isValidBST(input)
print(result)
input = TreeNode(5)
input.left = TreeNode(1)
input.right = TreeNode(4)
input.right.left = TreeNode(3)
input.right.right = TreeNode(6)
result = solution.isValidBST(input)
print(result)
input = TreeNode(10)
input.left = TreeNode(5)
input.right = TreeNode(15)
input.right.left = TreeNode(6)
input.right.right = TreeNode(20)
result = solution.isValidBST(input)
print(result)
|
db95fe3975f545a0554e37739177481eabc14f19 | rakietaosx/osx | /pprogram_ulamki.py | 251 | 3.75 | 4 | print("Program ulamki Olafa.")
while True:
licznik = input("wpisz licznik:")
mianownik = input("wpisz mianownik:")
if mianownik == 0:
print("gamonie")
else:
print(" " + str(licznik))
print("--- ")
print(" " + str( mianownik))
|
5b9613c9a3ba1eb0e19902b2f50b4e946c4d96f1 | Zerobitss/Python-101-ejercicios-proyectos | /practica31.py | 496 | 3.84375 | 4 | """
Escribir un programa en el que se pregunte al usuario por una frase y una letra, y muestre por pantalla el número de veces
que aparece la letra en la frase.
"""
def run():
contador = 0
word = str(input("Ingresa una frase: "))
letter = str(input("Ingresa una letra: "))
for i in word:
if i == letter:
contador +=1
print(f"La cantidiad de veces que la letra {letter}, se repite en la palabra {word}, es: {contador}")
if __name__ == '__main__':
run() |
b8e214b4499b4904e1c13d41086d483eca8c52f1 | monicador/Python | /1_Ciclo_While1.py | 632 | 4.34375 | 4 | '''
Mientras que (While)
El Ciclo Mientras que es conocido en los lenguajes de programación como
ciclo While, una de sus características es que verifica si la condición
se cumple antes de ingresar al bloque de código que se va a repetir, el
límite de ejecuciones estará dado por la condición, se ejecutará mientras
la condición devuelva un valor lógico verdadero.
mientras {condición}
acción 1
acción 2
acción 3
.....
acción n
fin mientras
instrucción X
'''
x = 5
while x > 0:
x -= 1
print(x) |
c102e69ffef15a0a566a92af7fa5939c752b64b4 | angishen/algorithms-datastructures | /ch07_linkedlists.py | 9,667 | 3.953125 | 4 | # 7.1 MERGE TWO SORTED LISTS
class ListNode(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def merge_sorted_lists(L1, L2):
result = head = ListNode()
while L1 and L2:
if L1.data <= L2.data:
result.next = L1
result = result.next
L1 = L1.next
elif L2.data < L1.data:
result.next = L2
result = result.next
L2 = L2.next
if L1:
result.next = L1
if L2:
result.next = L2
head = head.next
return head
def merge_two_sorted_lists_BOOK(L1, L2):
# create a placeholder for the result
dummy_head = tail = ListNode()
while L1 and L2:
if L1.data < L2.data:
tail.next, L1 = L1, L1.next
else:
tail.next, L2 = L2, L2.next
tail = tail.next
# Append the remaining nodes of L1 or L2
tail.next = L1 or L2
return dummy_head.next
# 7.2 REVERSE A SINGLE SUBLIST
def reverse_sublist(L, s, f):
# splice out subarray
head, count = L, 1
if not L or not L.next:
return head
sub_L = None
while L.next:
if count == s-1:
sub_L = L.next
sub_head = sub_L
temp_node = L
if count == f:
temp_node.next = L.next
sub_L.next = None
break
count += 1
L = L.next
if sub_L:
sub_L = sub_L.next
L = head
sub_L = sub_head
# reverse sublist
sub_tail = sub_L
prev, curr = None, sub_L
while current:
next = current.next
curr.next = prev
prev = curr
curr = next
sub_head = prev
# re-insert reversed subarray
while L:
if L == temp_node:
sub_tail.next = L.next
L.next = sub_head
break
L = L.next
return head
def reverse_sublist_BOOK(L, start, finish):
dummy_head = sublist_head = ListNode(0, L)
for _ in range(1, start):
sublist_head = sublist_head.next
# reverse sublist
sublist_iter = sublist_head.next
for _ in range(finish - start):
temp = sublist_iter.next
sublist_iter.next, temp.next, sublist_head.next = temp.next, sublist_head.next, temp
return dummy_head.next
# 7.3 TEST FOR CYCLICITY
def check_for_cycles(L):
while L:
L2 = L.next
while L2:
if L2 == L:
return L
L2 = L2.next
L = L.next
return None
# 7.4 TEST FOR OVERLAPPING LISTS - LISTS ARE CYCLE-FREE
# 7.5 TEST FOR OVERLAPPING LISTS - LISTS MAY HAVE CYCLES
# 7.6 DELETE A NODE FROM A SINGLY LINKED LIST
def delete_node(L, data):
head = L
while L and L.next and L.next.next:
if L.next.data == data:
L.next = L.next.next
return head
def delete_node2(node):
node.data = node.next.data
node.next = node.next.next
# 7.7 REMOVE THE KTH LAST ELEMENT FROM A LIST
def remove_kth_from_end(L, k):
count = k
iter1 = iter2 = L
while count > 0:
iter1 = iter1.next
count -= 1
while iter1:
iter1 = iter1.next
iter2 = iter2.next
delete_node2(iter2)
def remove_kth_last_BOOK(L, k):
dummy_head = ListNode(0, L)
first = dummy_head.next
for _ in range(k):
first = first.next
second = dummy_head
while first:
first, second = first.next, second.next
# second points to (k+1)th last node, delete its successor
second.next = second.next.next
return dummy_head
# 7.8 REMOVE DUPLICATES FROM A SORTED LIST
def delete_duplicates(L):
dummy_head = ListNode(0, L)
while L.next:
if L.next.data == L.data:
L.next = L.next.next
else:
L = L.next
return dummy_head.next
# 7.9 IMPLEMENT CYCLIC RIGHT SHIFT FOR SINGLY LINKED LIST
def rotate_right(L, k):
def get_length(L):
length = 1
while L:
L = L.next
length += 1
return length
head = L
k = k % get_length(L)
iter1 = L
for _ in range(k):
iter1 = iter1.next
iter2 = L
while iter1.next:
iter1 = iter1.next
iter2 = iter2.next
iter1.next = head
head = iter2.next
iter2.next = None
return head
# 7.10 IMPLEMENT EVEN ODD MERGE
def even_odd_merge(L):
dummy_head1 = ListNode(None, L)
dummy_head2 = ListNode()
L2 = dummy_head2
count = 0
while L.next:
next_node = L.next
if count % 2 == 0:
L.next = L.next.next
L = next_node
else:
L2.next = L
L2 = L2.next
L = next_node
count += 1
L.next = dummy_head2.next
return dummy_head1.next
def even_odd_merge_BOOK(L):
if not L:
return L
dummy_head_even, dummy_head_odd = ListNode(0), ListNode(0)
tails, turn = [dummy_head_even, dummy_head_odd], 0
while L:
tails[turn].next = L
L = L.next
tails[turn] = tails[turn].next
turn ^= 1
tails[1].next = None
tails[0].next = dummy_head_odd.next
return dummy_head_even.next
# 7.11 TEST WHETER A SINGLY LINKED LIST IS PALINDROMIC
def is_palindrome(L):
iter1 = iter2 = L
while iter2 and iter2.next:
iter2 = iter2.next.next
iter1 = iter1.next
L1, L2 = L, reverse_linked_list(iter1)
while L1 and L2:
if L1.data != L2.data:
return False
L1 = L1.next
L2 = L2.next
return True
def is_linked_list_a_palindrome_BOOK(L):
slow = fast = L
while fast and fast.next:
fast, slow = fast.next.next, slow.next
first_half_iter, second_half_iter = L, reverse_linked_list(slow)
while second_half_iter and first_half_iter:
if second_half_iter.data != first_half_iter.data:
return False
second_half_iter, first_half_iter = second_half_iter.next, first_half_iter.next
return True
# 7.12 IMPLEMENT LIST PIVOTING
def pivot_linked_list(L, k):
less = equal = greater = ListNode(0)
tails = [less, equal, greater]
while L:
if L.data < k:
tails[0].next = L
tails[0] = tails[0].next
elif L.data == k:
tails[1].next = L
tails[1] = tails[1].next
else:
tails[2].next = L
tails[2] = tails[2].next
L = L.next
tails[2].next = None
tails[1].next = greater.next
tails[0].next = equal.next
return less.next
def list_pivoting_BOOK(L, k):
less_head = less_iter = ListNode()
equal_head = equal_iter = ListNode()
greater_head = greater_iter = ListNode()
while L:
if L.data < k:
less_iter.next = L
less_iter = less_iter.next
elif L.data == k:
equal_iter.next = L
equal_iter = equal_iter.next
else:
greater_iter.next = L
greater_iter = greater_iter.next
L = L.next
greater_iter.next = None
equal_iter.next = greater_head.next
less_iter.next = equal_head.next
return less_head.next
# 7.13 ADD LIST BASED INTEGERS
def add_two_lists(L1, L2):
result = dummy_head = ListNode()
while L1 and L2:
L1.data += L2.data
result.next = L1
result, L1, L2 = result.next, L1.next, L2.next
if L1:
result.next = L1
if L2:
result.next = L2
result = dummy_head.next
while result.next:
if result.data > 9:
result.data %= 10
result.next.data += 1
result = result.next
if result.data > 9:
result.data %= 10
result.next = ListNode(1)
return dummy_head.next
def reverse_linked_list(L):
prev, curr = None, L
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
def print_list_nodes(L):
while L:
print(L.data)
L = L.next
if __name__ == "__main__":
node1_3 = ListNode(4)
node1_2 = ListNode(1, node1_3)
node1_1 = ListNode(3, node1_2)
node2_3 = ListNode(9)
node2_2 = ListNode(0, node2_3)
node2_1 = ListNode(7, node2_2)
print_list_nodes(add_two_lists(node1_1, node2_1))
# L1_4 = ListNode(12)
# L1_3 = ListNode(7, L1_4)
# L1_2 = ListNode(3, L1_3)
# L1_1 = ListNode(2, L1_2)
# L2_4 = ListNode(100)
# L2_3 = ListNode(12, L2_4)
# L2_2 = ListNode(11, L2_3)
# L2_1 = ListNode(4, L2_2)
# merged_list = merge_sorted_lists(L1_1, L2_1)
# node8 = ListNode(8)
# node7 = ListNode(7, node8)
# node6 = ListNode(6, node7)
# node5 = ListNode(5, node6)
# node4 = ListNode(4, node5)
# node3 = ListNode(3, node4)
# node2 = ListNode(2, node3)
# node1 = ListNode(1, node2)
# lst = reverse_sublist_BOOK(node1, 3, 6)
# while lst:
# print(lst.data)
# lst = lst.next
# node7 = ListNode(11)
# node6 = ListNode(5, node7)
# node5 = ListNode(7, node6)
# node4 = ListNode(11, node5)
# node3 = ListNode(2, node4)
# node2 = ListNode(2, node3)
# node1 = ListNode(3, node2)
# print_list_nodes(list_pivoting_BOOK(node1, 7))
# print(is_linked_list_a_palindrome_BOOK(node1))
# print_list_nodes(reverse_linked_list(node1))
# print_list_nodes(rotate_right(node1, 13))
# duplicates_removed = delete_duplicates(node1)
# print_list_nodes(duplicates_removed)
# print("before delete: ")
# print_list_nodes(node1)
# delete_node2(node4)
# print("after delete: ")
# print_list_nodes(node1)
# remove_kth_from_end(node1, 3)
# print_list_nodes(node1)
|
f9af2d519e174eafe39969cbe65517d477cb86ce | roblivesinottawa/python_bootcamp_three | /FUNCTIONS/fibo.py | 350 | 3.515625 | 4 | def fib(n):
if n >= 3:
return fib(n-1) + fib(n-2)
return 1
print(fib(10))
def fbnc(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fbnc(n-1) + fbnc(n-2)
print(fbnc(10))
def fibo(num):
a = 0
b = 1
for i in range(num):
a, b = b, a+b
return a
print(fibo(10)) |
e9c7b24e582755ae36a035a964d34b6085caef5a | jungiejungle/python-project | /.gitignore/hello.py | 384 | 3.9375 | 4 | print("Hello, World")
print("Python", 3)
print("Hello, World", sep=";", end="$")
print("{}{}".format("ADNU", 2018))
age = 18
weight = 60.21
print (type(age))
print (type(weight))
print (type("Hello"))
data = {"name" : "Juggernaut",
"age" : 18,
"height" : 178.50,
"fave_fruits" : ["apple" , "mango" , "batag"]
}
print("My name is {}".format.(data["name"]))
|
6ae55f5dfda37025fc5c7faff6a09842612aa31b | NicholasLePar/NicksNeuralNetwork | /Initialization.py | 5,446 | 3.796875 | 4 | import numpy as np
########################################################################################################################
"""
GROUP: Parameter Initialization
-Handles the initialization of the neural networks weights and biases
EXTERNAL FUNCTIONS:
1) initialize_parameters: initializes the weights and bias according to the init_type selected
INTERNAL FUNCTIONS:
1)initializ1e_parameters_xavier: uses the "Xavier" algorith for initialization
2)initializ1e_parameters_he: uses the "He" algorithm for initialization
3)initialize_parameters_random: initializes the weights by randNum[0,1)*scale and the biases to zero
"""
########################################################################################################################
###EXTERNAL FUNCTIONS###
def initialize_parameters(layers_dims, init_type, weight_scale=1, seed=3):
"""
Description:
initializes the weights and bias according to the init_type selected.
Arguments:
layer_dims -- python array (list) containing the size of each layer.
init_type -- the type of initialize method to use.
Optional Arguments:
weight_scale -- the scale to which an initialization technique will assign weights
seed -- seed use to intialize the numpy random function
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
if init_type == "random":
parameters = initialize_parameters_random(layers_dims,weight_scale,seed)
elif init_type == "he":
parameters = initialize_parameters_he(layers_dims,seed)
elif init_type == "xaiver":
parameters = initialize_parameters_xavier(layers_dims,seed)
else:
print("ERROR: intitialize_parameters - no init_type was selected")
print("init_type=" + init_type)
sys.exit(1)
return parameters
###INTERNAL FUNCTIONS###
def initialize_parameters_xavier(layers_dims,seed):
"""
Description:
Xavier initialization uses a scaling factor for the weights of `sqrt(1./layers_dims[l-1])`
Arguments:
layer_dims -- python array (list) containing the size of each layer.
seed -- seed use to intialize the numpy random function
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
np.random.seed(seed)
parameters = {}
L = len(layers_dims)
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * np.sqrt(1.0/layers_dims[l-1])
parameters['b' + str(l)] = np.zeros((layers_dims[l],1))
return parameters
def initialize_parameters_he(layers_dims,seed):
"""
Description:
He initialization is a published technique in 2015 similiar to Xavier initialization.
-Xavier initialization uses a scaling factor for the weights of `sqrt(1./layers_dims[l-1])`
-He initialization would use `sqrt(2./layers_dims[l-1])
He initialization recommended for layers with a ReLU activation.
Arguments:
layer_dims -- python array (list) containing the size of each layer.
seed -- seed use to intialize the numpy random function
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
np.random.seed(seed)
parameters = {}
L = len(layers_dims)
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * np.sqrt(2.0/layers_dims[l-1])
parameters['b' + str(l)] = np.zeros((layers_dims[l],1))
return parameters
def initialize_parameters_random(layers_dims,weight_scale,seed):
"""
Description:
initializes the weights of all neurons randomly between [0,1)*scale and their biases to zero.
Arguments:
layer_dims -- python array (list) containing the size of each layer.
weight_scale -- scalar to adjust the weight of the random numbers
seed -- seed use to intialize the numpy random function
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
b1 -- bias vector of shape (layers_dims[1], 1)
...
WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
bL -- bias vector of shape (layers_dims[L], 1)
"""
np.random.seed(seed) # This seed makes sure your "random" numbers will be the as ours
parameters = {}
L = len(layers_dims) # integer representing the number of layers
for l in range(1, L):
parameters['W' + str(l)] = np.random.randn(layers_dims[l],layers_dims[l-1])*weight_scale
parameters['b' + str(l)] = np.zeros((layers_dims[l],1))
return parameters
|
e433d756ca4aaca9abe1ac37737c4858d2d662ae | guoheng/ProjectEulerPy | /p046.py | 1,000 | 3.8125 | 4 | #It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
#
#9 = 7 + 2x1^2
#15 = 7 + 2x2^2
#21 = 3 + 2x3^2
#25 = 7 + 2x3^2
#27 = 19 + 2x2^2
#33 = 31 + 2x1^2
#
#It turns out that the conjecture was false.
#
#What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
import logging
from prime import PrimeNumberPool
squares = [1, 4, 9]
def Check(n, prime):
if prime.IsPrime(n):
return 0
while (squares[-1] < n//2):
squares.append(len(squares)*len(squares))
for sq in squares:
if (sq*2 >= n):
return 0
if (prime.IsPrime(n-sq*2)):
return 1
def main(args):
prime = PrimeNumberPool()
n = 33
done = 0
while (done == 0):
if (prime.IsPrime(n)):
n += 2
continue
if (Check(n, prime) == 0):
logging.info(n)
done = 1
else:
n += 2
|
0fc85d64f6653fd913bd485e2b7725aa07cdd3d7 | wiegandt/week_3 | /variable mutation.py | 515 | 3.546875 | 4 | a = 3
a = a + 10
print(a)
b = 100
b-=7
print(b)
c = 44
c*=2
print(c)
d = 125
d/=5
print(d)
e = 8
e^=3
print(e)
f1 = 123
f2 = 345
if f1 > f2:
print(True)
else:
print(False)
g1 = 350
g2 = 200
if 2*g2 > g1:
print(True)
else:
print(False)
h = 1357988018575474
if 11 / 1357988018575474:
print(True)
else:
print(False)
i1 = 10
i2 = 3
if i2^3 > i1 > i2^2:
print(True)
else:
print("What's this question?")
j = 1521
if j / 3 or j / 5:
print(True)
else:
print(False) |
81f10c9142a3fd138487e015ccaa957db1a7c0e0 | abhs26/Daily-Coding-Problem | /problem_85.py | 567 | 3.96875 | 4 | #!/usr/bin/env python
"""
Given three 32-bit integers x, y, and b,
return x if b is 1 and y if b is 0,
using only mathematical or bit operations.
You can assume b can only be 1 or 0.
"""
import sys
__author__ = "Abhishek Srivastava"
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Abhishek Srivastava"
__email__ = "abhs26@gmail.com"
__status__ = "Production"
def check_bit(x, y, b):
mask = 0
return (( int(b) ^ mask ) and x ) or (( int(b) ^ (~mask) ) and y )
if __name__ == "__main__":
if len(sys.argv) > 3:
print(check_bit(sys.argv[1], sys.argv[2], sys.argv[3]))
|
935116098e2c3123e543b49968db2f9b9014d76a | vietnguyen2000/CPU-Scheduling-and-Demand-Paging-question-for-CodeRunner | /CPU Scheduling/FCFS.py | 1,025 | 3.734375 | 4 | def findavgTime(processes):
#TODO: write function to calculate avgWaitingTime and avgTurnAroundTime of FCFS Algorithm
n = len(processes)
wt = [0] * n
tat = [0] * n
completeTime = [0]*n
# Function to find turn around time
for i in range(n):
completeTime[i] = max(completeTime[i-1],processes[i][0]) + processes[i][1] if i>0 else processes[i][0] + processes[i][1]
tat[i] = completeTime[i] - processes[i][0] # turn around time = completeTime - arrival time
# finding waiting time
wt[i] = tat[i] - processes[i][1]
avgWaitingTime = sum(wt) / n
avgTurnAroundTime = sum(tat) / n
#! DO NOT CHANGE
# print("Average waiting time = "+ "{:.2f}".format(avgWaitingTime))
# print("Average turn around time = "+ "{:.2f}".format(avgTurnAroundTime))
return "Average waiting time = "+ "{:.2f}".format(avgWaitingTime) + "\n" + "Average turn around time = "+ "{:.2f}".format(avgTurnAroundTime) + "\n"
# findavgTime([(0,2),(0,2)])
|
6612b6803bfef4c9ddc47fd0ea5874be62f26a54 | ynzerod/actual_06_homework | /02/songxiang/kuaisupaixu.py | 669 | 3.640625 | 4 | def kuaisupaixu(num_list,left,right):
i = left
j = right
if i == j:
return num_list
while j > i:
while j > i and num_list[j] >= key:
j = j - 1
num_list[i],num_list[j] = num_list[j],num_list[i]
while i < j and num_list[i] <= key:
i = i + 1
num_list[i],num_list[j] = num_list[j],num_list[i]
return num_list.index(key)
kuaisupaixu(num_list,num_list.index(key),i)
kuaisupaixu(num_list,j,num_list.index(key))
return num_list
if __name__ == '__main__':
num_list = [9999,99999,1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,65555,33,45]
key = num_list[0]
right = len(num_list)-1
left = 0
kuaisupaixu(num_list,left,right)
print num_list |
9dfec636c50c31524829f3ac65ac6646a695c1ba | shadiqurrahaman/python_DS | /Binary-tree/Binary_tree_to bst.py | 1,051 | 3.796875 | 4 | class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Main:
def inorder(self,root):
if root==None:
return
self.inorder(root.left)
print(root.data,end=' ')
self.inorder(root.right)
def insert_in_array(self,root,array):
if root==None:
return
self.insert_in_array(root.left,array)
array.append(root.data)
self.insert_in_array(root.right,array)
return array
def convert_bt_array(self,root):
array = []
converted = self.insert_in_array(root,array)
converted.sort()
root = self.bt_to_bst_convert(root,converted)
self.inorder(root)
def bt_to_bst_convert(self,root,array):
if root == None:
return
self.bt_to_bst_convert(root.left,array)
root.data = array.pop(0)
self.bt_to_bst_convert(root.right,array)
return root
root = Node(10)
root.left = Node(30)
root.right = Node(15)
root.left.left = Node(20)
root.right.right = Node(5)
main = Main()
main.convert_bt_array(root)
# main.inorder(root)
|
72c60a4d1e89249b46c912cfd48efc3aced37ca5 | vijaypalmanit/coding | /date to bned months.py | 1,197 | 3.5625 | 4 | import pandas as pd
import numpy as np
# normal datafrmae having date filed which needs to be labeled with corresponding business month
df=pd.DataFrame({'id':[23,45,65,76,21,54],'day':['2019-04-30','2019-05-31','2019-06-29','2019-07-15','2019-10-12','2019-11-22']})
df['day'] = pd.to_datetime(df['day'],format='%Y-%m-%d')
# this is dataframe consist of month ending for each business month eg. Business month May last from 2019-04-29 --- 2019-05-25 and so on....
df2=pd.DataFrame({'month_ending':['2019-04-28','2019-05-25','2019-06-29','2019-07-27','2019-08-24','2019-09-28','2019-10-26','2019-11-23','2019-12-28','2020-01-25','2020-02-22','2020-03-28','2020-05-02']})
df2['month_ending']=pd.to_datetime(df2['month_ending'])
bned_months=['May','June','July','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr']
df['month'] = pd.cut(df.day.astype(np.int64)//10**9,
bins=df2.month_ending.astype(np.int64)//10**9,
labels=bned_months)
print(df)
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filelocation = askopenfilename() # open the dialog GUI |
c40eee1967d02dbf6af7d3a95398f7822d23f785 | reanimation47/ledoananhquan-fundametal-c4e13 | /Session05/homework/bacteriaB.py | 322 | 4.125 | 4 | n = int(input("How many B bacterias are there?"))
t = int(input("How much time in minutes we will wait?"))
if t % 2 == 0:
T = t / 2
x = (2**T)*n
print("After", t, "minutes,we would have", x, "bacterias" )
else:
T = (t-1)/2
x = (2**T)*n
print("After", t, "minutes,we would have", x, "bacterias" )
|
88a9e82597df7206c7a11a836bb3bb65de10e0f2 | westonwilson08/Python | /brute_force1.py | 1,516 | 3.625 | 4 | import itertools
import string
import zipfile
import argparse
def extractFile(zFile, password):
try:
zFile.extractall(pwd=password)
print "[+] Found password = " + password
return True
except:
return False
def main():
parser = argparse.ArgumentParser("%prog -f <zipfile>")
parser.add_argument("-f", dest="zname", help="specify zip file")
args = parser.parse_args()
if (args.zname == None):
print parser.usage
exit(0)
else:
zname = args.zname
zFile = zipfile.ZipFile(zname)
#chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits #+ string.punctuation
attempts = 0
for password_length in range(3, 4):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
#print('guess: '+ guess)
found = extractFile(zFile, guess)
if found == True:
return 'password is {}. found in {} guesses.'.format(guess, attempts)
exit(0)
if guess[0]==guess[1] and guess[1] == guess[2]:
print(guess, attempts)
print('Password Not Found.')
if __name__ == "__main__":
main() |
96152d12a2474add6c324dd88b95e2974b62c0c5 | arnabs542/Leetcode-18 | /Palindrome Number.py | 548 | 3.96875 | 4 | class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
num = 0
tmp = x
while tmp > 0:
num = num*10 + tmp%10
tmp /= 10
return num == x
"""
:type x: int
:rtype: bool
"""
# Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
# Coud you solve it without converting the integer to a string?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.