blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
5da1487437a7556fac90072c2d7dddbb01a965a6 | jonovik/cgptoolbox | /cgp/utils/extrema.py | 2,060 | 3.8125 | 4 | """Find local maxima and minima of a 1-d array"""
import numpy as np
from numpy import sign, diff
__all__ = ["extrema"]
# pylint:disable=W0622
def extrema(x, max=True, min=True, withend=True): #@ReservedAssignment
"""
Return indexes, values, and sign of curvature of local extrema of 1-d array.
The boolean arguments max, min, withend determine whether to
include maxima and minima, and include the endpoints.
Basic usage.
>>> x = [2, 1, 0, 1, 2]
>>> extrema(x) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
rec.array([(0, 2, -1), (2, 0, 1), (4, 2, -1)],
dtype=[('index', '<i...'), ('value', '<i...'), ('curv', '<i...')])
Options to include only certain types of extrema.
>>> extrema(x, withend=False)
rec.array([(2, 0, 1)],...
>>> extrema(x, max=False)
rec.array([(2, 0, 1)],...
>>> extrema(x, min=False)
rec.array([(0, 2, -1), (4, 2, -1)],...
>>> extrema(x, max=False, min=False)
rec.array([],...
The beginning and end of flat segments both count as extrema,
except the first and last data point.
>>> extrema([0, 0, 1, 1, 2, 2])
rec.array([(1, 0, 1), (2, 1, -1), (3, 1, 1), (4, 2, -1)],...
>>> extrema([0, 0, 0])
rec.array([],...)
>>> extrema([0, 0, 1, 1], withend=False)
rec.array([(1, 0, 1), (2, 1, -1)],...
@todo: Add options on how to handle flat segments.
"""
x = np.squeeze(x) # ensure 1-d numpy array
xpad = np.r_[x[1], x, x[-2]] # pad x so endpoints become minima or maxima
curv = sign(diff(sign(diff(xpad)))) # +1 at minima, -1 at maxima
i = curv.nonzero()[0] # nonzero() wraps the indices in a 1-tuple
ext = np.rec.fromarrays([i, x[i], curv[i]],
names=["index", "value", "curv"])
if not withend:
ext = ext[(i > 0) & (i < len(x) - 1)]
if not max:
ext = ext[ext.curv >= 0]
if not min:
ext = ext[ext.curv <= 0]
return ext
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS)
|
9247bc433012c2af963293105933a1e422af281e | bariskucukerciyes/280201035 | /lab9/harmonic.py | 146 | 3.5 | 4 | def harmonic(x):
h_sum = 0
if x == 1:
return 1
h_sum = (1 / x) + harmonic(x - 1)
return h_sum
print(harmonic(5)) |
f5ad9e7ceadf975f9c3af3917bd4c3557ef39972 | bariskucukerciyes/280201035 | /lab5/evens.py | 169 | 4.03125 | 4 | N = int(input("How many number?"))
evens = 0
for i in range(N):
number = int(input("Enter integer:"))
if number % 2 == 0:
evens += 1
print(evens/N * 100, "%")
|
ba5de5ac9904058a9c7a5d48e881b9bd564b2824 | bariskucukerciyes/280201035 | /lab1/fahrenheit.py | 162 | 4.0625 | 4 | Celcius = int(input("Enter celcius value:"))
Fahrenheit = int(Celcius*1.8 + 32)
print(Celcius, "Celcius degree is equals to", Fahrenheit, "Fahrenheits degree" ) |
6acb845b6105cc4253fbc3421ef3b3354a23be3d | bozkus7/Python_File | /neural.py | 985 | 3.84375 | 4 | import numpy
import matplotlib.pyplot
data_file = open('mnist_train_100.csv.txt', 'r')
data_list = data_file.readlines()
data_file.close()
#The numpy.asfarray() is a numpy function to convert the text strings into real numbers and to create an array of those numbers
all_values = data_list[0].split(',')
image_array = numpy.asfarray(all_values[1:]).reshape((28,28))
print(matplotlib.pyplot.imshow(image_array, cmap = 'Greys', interpolation = 'None'))
"""
Dividing the raw inputs which are in the range 0255
by 255 will bring them into the range 01.
We then need to multiply by 0.99 to bring them into the range 0.0 0.99.
We then add 0.01 to
shift them up to the desired range 0.01 to 1.00. The following Python code shows this in action
"""
scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
print(scaled_input)
#output node is 10 (ex)
onodes = 10
targets = numpy.zeros(onodes) + 0.01
targets[int(all_values[0])] = 0.99
|
38e59e24c8a8d4a11c1bc6d8bb9fe4a9071ef492 | amansharma2910/DataStructuresAlgorithms | /02_PythonAlgorithms/Sorting/singly_linked_list.py | 3,113 | 4.34375 | 4 | class Node:
# Node class constructor
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
# LinkedList constructor
def __init__(self):
self.head = None
def print_list(self):
"""Method to print all the elements in a singly linked list.
"""
node = self.head
while node is not None:
print(node.data, end=" ")
node = node.next
def append(self, data):
"""Method to add node to the end of the linked list."""
node = Node(data)
# check the base case where the singly linked list is empty, i.e., head is None
if self.head is None:
self.head = node
return
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def prepend(self, data):
"""Method to add node to the beginning of the linked list."""
node = Node(data)
node.next = self.head
self.head = node
def add_at_idx(self, data, idx):
"""Method to add node in a linked list at a given position.
"""
if idx == 0:
node = Node(data)
node.next = self.head
self.head = node
return
count = 0
curr_node = self.head
while curr_node != None and count != idx-1:
curr_node = curr_node.next
count += 1
if count == idx-1:
node = Node(data)
node.next = curr_node.next
curr_node.next = node
else:
print(f"{idx} is not present in the linked list.")
def delete_head(self):
"""Method to delete the head node in a linked list.
"""
temp = self.head
self.head = self.head.next
del(temp) # in python, dereferencing an object sends it to garbage collection, so this step is optional
def delete_tail(self):
"""Method to delete the last node of a linked list.
"""
curr_node = self.head
while curr_node.next.next != None:
curr_node = curr_node.next
curr_node.next = None
def delete_at_idx(self, idx):
"""Method to delete the node at a given index value.
"""
if idx == 0:
self.head = None
return
curr_node = self.head
count = 0
while curr_node != None and count != idx-1:
curr_node = curr_node.next
count += 1
if count == idx-1:
curr_node.next = curr_node.next.next
else:
print(f"{idx} does not exist for the given linked list.")
if __name__ == "__main__":
llist = SinglyLinkedList()
llist.append(3) # head -> 3
llist.prepend(5) # head -> 5 -> 3
llist.prepend(6) # head -> 6 -> 5 -> 3
llist.prepend(4) # head -> 4 -> 6 -> 5 -> 3
llist.add_at_idx(11, 2) # head -> 4 -> 6 -> 11 -> 5 -> 3
llist.delete_head() # head -> 6 -> 11 -> 5 -> 3
llist.delete_at_idx(1) # head -> 6 -> 5 -> 3
llist.print_list()
|
df369f3cd5db77a5ed5fa071a3a8badfcf404905 | ea3/Exceptions-Python | /exception.py | 887 | 4.03125 | 4 | def add(a1,a2):
print(a1 + a2)
add(10,20)
number1 = 10
number2 = input("Please provide a number ") # This gives back a string.
print("This will never run because of the type error")
try:
#You you want to attempt to try.
result= 10 + 10
except:
print("It looks like you are not adding correctly")
else:
print("NO ERRORS!")
print(result)
try:
f = open('testfile', 'w')
f.write('Write a test line')
except TypeError:
print('There was a type error')
except :
print('Hey, you have an OS Error')
finally:
print('I always run')
def ask_for_int():
while True:
try:
result = int(input("Pleae provide a number: "))
except:
print("Whoops!That is not a number")
continue
else:
print("Yes, thank you for the number")
break
finally:
print("End of try/except/finally")
print("I will always run at the end")
ask_for_int()
|
8f76584b2645bb0ef6d525cd456ab11b7b2933c7 | stanton101/Ansible-Training | /core_python_ep6.py | 462 | 3.90625 | 4 | # Tuples
# t = ("Norway", 4.953, 3)
# print(t * 3)
# print(t[0])
# print(t[2])
# print(len(t))
# for item in t:
# print(item)
# t + (338186)
# a = ((220, 284), (1184, 1210), (2620,2924), (5020, 5564), (6232, 6368))
# print(a[2][1])
# def minmax(self):
# return min(self), max(self)
# num = minmax([83, 33, 84, 32, 85, 31, 86])
# print(num)
# print("Hello world")
make = "500"
sum = 5 + int(make)
print(str(sum) + " rand in my pocket")
# print(500) |
e613ee5e149ff0ed9af83a11e1571421c9c8551c | charlesrwinston/nlp | /lab0/winston_Lab0.py | 1,326 | 3.5625 | 4 | # Winston_Lab0.py
# Charles Winston
# September 7 2017
from nltk.corpus import gutenberg
def flip2flop():
flip = open("flip.txt", "r")
flop = open("flop.txt", "w")
flip_text = flip.read()
flop.write(reverse_chars(flip_text) + "\n")
flop.write(reverse_words(flip_text) + "\n")
emma = gutenberg.words('austen-emma.txt')
flop.write(str(len(emma)) + "\n")
flop.write("Word.\n")
flop.write("It's lit.\n")
def reverse_chars(sentence):
length = len(sentence)
new_sentence = ""
for i in range(length):
new_sentence += sentence[length - 1 - i]
return new_sentence
def reverse_words(sentence):
words = get_words(sentence)
len_words = len(words)
new_sentence = ""
for i in range(len_words):
new_sentence += words[len_words - 1 - i]
if (i != (len_words - 1)):
new_sentence += " "
return new_sentence
def get_words(sentence):
length = len(sentence)
words = []
temp_word = ""
for i in range(length):
if sentence[i].isspace():
words.append(temp_word)
temp_word = ""
elif (i == (length - 1)):
temp_word += sentence[i]
words.append(temp_word)
else:
temp_word += sentence[i]
return words
if __name__ == '__main__':
flip2flop()
|
4074f1ca36b2ad151d2b918274f661c8e0ae4b80 | htars/leetcode | /algorithms/1_two_sum.py | 733 | 3.546875 | 4 | from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)-1):
n1 = nums[i]
for j in range(i+1, len(nums)):
n2 = nums[j]
if (n1+n2) == target:
return [i, j]
if __name__ == '__main__':
s = Solution()
inputs = [
[2, 7, 11, 15],
[3, 2, 4],
[3, 3],
]
targets = [
9,
6,
6,
]
outputs = [
[0, 1],
[1, 2],
[0, 1]
]
for nums, target, output in zip(inputs, targets, outputs):
result = s.twoSum(nums, target)
print(result)
assert result == output
|
742952425469528b62320860c834a73d8f52e444 | americanchauhan/problem-solving | /Find the maximum element and its index in an array/Find the maximum element and its index in an array.py | 428 | 4.0625 | 4 | def FindMax(arr):
#initialze first value as largest
max = arr[0]
for i in range(1, len(arr)):
#if there is any other value greater than max, max is updated to that element
if arr[i] > max:
max = arr[i]
ind = arr.index(max)
#Print the maximum value
print(max)
#return index of the maximum value
return ind
arr = list(map(int, input().split()))
print(FindMax(arr)) |
68e668797ce78e861ba24a295f05a4e7aaf07086 | rupalisinha23/problem-solving | /rotating_series.py | 517 | 3.9375 | 4 | """
given two arrays/lists A and B, return true if A is a rotation of B otherwise return false
"""
def is_rotation(A,B):
if len(A) != len(B): return False
key=A[0]
indexB = -1
for i in range(len(B)):
if B[i] == key:
indexB = i
break
if indexB == -1: return False
for i in range(len(A)):
j = (indexB + i)%len(A)
if A[i] != B[j]:
return False
return True
if __name__=='__main__':
print(is_rotation([1,2,3,4],[3,4,1,2]))
|
3da789960183c8f13bb5b22307c60fe57adf316b | rupalisinha23/problem-solving | /pallindrome_linked_list.py | 493 | 3.734375 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Pallindrome:
def isPallindrome(self, head:ListNode) -> bool:
if not head or not head.next:
return True
stack = []
while head:
stack.append(head.val)
head = head.next
length = len(stack)
for i in range(length/2):
if stack[i] != stack[len(stack)-i-1]:
return False
return True
|
75260678d000751037a56f69e517b253e7d82ad9 | aasmith33/GPA-Calculator | /GPAsmith.py | 647 | 4.1875 | 4 | # This program allows a user to input their name, credit hours, and quality points. Then it calculates their GPA and outputs their name and GPA.
import time
name = str(input('What is your name? ')) # asks user for their name
hours = int(input('How many credit hours have you earned? ')) # asks user for credit hours earned
points = int(input('How many quality points do you have? ')) # asks user for amount of quality points
gpa = points / hours # calculates GPA
gpa = round(gpa, 2) #rounds gpa 2 decimal places
print ('Hi ' + str(name) + '. ' + 'Your grade point average is ' + str(gpa) + '.') # displays users name and GPA
time.sleep(5)
|
89899700c49efdc29c14accb87082a865da2b896 | darpanhub/python1 | /task4.py | 2,041 | 3.984375 | 4 | # Python Program to find the area of triangle
a = 5
b = 6
c = 7
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
# python program finding square root
print('enter your number')
n = int(input())
import math
print(math.sqrt(n))
# Python program to swap two variables
x = 5
y = 10
swap = x
x = y
y = swap
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
# Program to generate a random number
import random
print(random.randint(1,10))
# to convert kilometers to miles
1 KILOMETER = O.621371 MILES
kilometers = float(input("Enter value in kilometers: "))
conv_factor = 0.621371
miles = kilometers * conv_factor
print('{} kilometers is equal to {} miles'.format(kilometers, miles))
# python programme to check leap years
print(' please enter year')
year = int(input())
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
else:
print(f'{year} is a leap year')
else:
print(f'{year} is not a leap year')
# proramme to print table
print('Enter your number')
n= int(input())
for i in range (1, 11):
print('{} * {} = {}'.format(n, i, n*i))
# find sum of natural numbers
n = int(input())
s = n*(n+1)/2
print(s)
# calculator
import math
def addition(a,b):
print ('sum is:', a+b)
def subtraction(a , b):
print ('subtractio is:', a-b)
def multiplication (a,b):
print ('multiplication is: ', a*b)
def division (a,b):
print ('division is:', int(a/b))
def reminder(a,b):
print('reminder :', a % b)
print('Welcome to Calulator : ')
print('Enter first number:')
n1 = int(input())
print('Enter second number:')
n2 = int(input())
addition(n1, n2)
subtraction(n1,n2)
multiplication(n1,n2)
division(n1,n2)
reminder(n1,n2)
math.sqrt(n1)
|
99a99291c1dc2b399b282914db4e5f57da7f46d8 | darpanhub/python1 | /list.py | 1,242 | 3.796875 | 4 | # student_list=[1,45,6,6,7]
# print(student_list)
# print('Welcome User')
# admin_list = ['manish' , 'darpan' , 'sandeep', 'mohammed']
# print('hey user, Please enter your name for verification')
# name = input()
# if name in admin_list:
# print('hey ' + name + ', happy to see you Welcome back')
# else:
# print('Hey ' + name + ',You are Not a member please register to continue')
# import random
# print('enter number')
# num = input()
# print('Your OTP is :')
# for i in range(6):
# otp = random.choice(num)
# print(otp, end='')
# user register
# user_database = ['darpan','manish','mohammed','sandeep']
# usernames_list = ['darpan','manish','mohammed','sandeep']
# print('Enter First Name')
# first_name = input().strip().lower()
# print('Enter last Name')
# last_name = input().strip().lower()
# print('Enter User Name')
# user_name = input().strip().lower()
# print('Enter your password')
# password = input().strip().lower()
# password2 = input().strip().lower()
# if password == password2:
# user_database['usernames_list'].insert(user_name)
# user_database[user_name +'_password']= password
# print('hey {} Your Account is Created'.format(user_name)) |
cf43e8c07ad2deeeb928439291b3fd97ddcde57c | ronaldoussoren/pyobjc | /pyobjc-core/Examples/Scripts/subclassing-objective-c.py | 1,656 | 4.09375 | 4 | #!/usr/bin/env python
# This is a doctest
"""
=========================================
Subclassing Objective-C classes in Python
=========================================
It is possible to subclass any existing Objective-C class in python.
We start by importing the interface to the Objective-C runtime, although
you'd normally use wrappers for the various frameworks, and then locate
the class we'd like to subclass::
>>> import objc
>>> NSEnumerator = objc.lookUpClass('NSEnumerator')
>>> NSEnumerator
<objective-c class NSEnumerator at 0xa0a039a8>
You can then define a subclass of this class using the usual syntax::
>>> class MyEnumerator (NSEnumerator):
... __slots__ = ('cnt',)
... #
... # Start of the method definitions:
... def init(self):
... self.cnt = 10
... return self
... #
... def nextObject(self):
... if self.cnt == 0:
... return None
... self.cnt -= 1
... return self.cnt
... #
... def __del__(self):
... global DEALLOC_COUNT
... DEALLOC_COUNT = DEALLOC_COUNT + 1
To check that our instances our deallocated we maintain a ``DEALLOC_COUNT``::
>>> DEALLOC_COUNT=0
As always, the creation of instances of Objective-C classes looks a bit odd
for Python programs:
>>> obj = MyEnumerator.alloc().init()
>>> obj.allObjects()
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
Destroy our reference to the object, to check if it will be deallocated::
>>> del obj
>>> DEALLOC_COUNT
1
"""
import doctest
import __main__
doctest.testmod(__main__, verbose=1)
|
eaa7fec6da4273925a0cb7b68c910a729bf26f3c | Yaguit/lab-code-simplicity-efficiency | /your-code/challenge-2.py | 822 | 4.15625 | 4 | """
The code below generates a given number of random strings that consists of numbers and
lower case English letters. You can also define the range of the variable lengths of
the strings being generated.
The code is functional but has a lot of room for improvement. Use what you have learned
about simple and efficient code, refactor the code.
"""
import random
import string
def StringGenerator():
a = int(input('Minimum length: '))
b = int(input('Maximum length: '))
n = int(input('How many strings do you want? '))
list_of_strings = []
for i in range(0,n):
length = random.randrange(a,b)
char = string.ascii_lowercase + string.digits
list_of_strings.append(''.join(random.choice (char) for i in range(length)))
print(list_of_strings)
StringGenerator() |
3b9eb781f9ae784e62b9e4324f34120772209576 | inniyah/MusicDocs | /HiddenMarkovModel.py | 11,115 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See: https://github.com/adeveloperdiary/HiddenMarkovModel
# See: http://www.adeveloperdiary.com/data-science/machine-learning/introduction-to-hidden-markov-model/
import numpy as np
# Hidden Markov Model (θ) has with following parameters :
#
# S = Set of M Hidden States
# A = Transaction Probability Matrix (aij)
# V = Sequence of T observations (vt)
# B = Emission Probability Matrix (Also known as Observation Likelihood) (bjk)
# π = Initial Probability Distribution
# Evaluation Problem: Given the model (θ), we want to determine the probability that
# a particular sequence of visible states/symbol (V) that was generated from the model (θ).
def forward(V, a, b, initial_distribution):
# αj(0) = πj·bjk
alpha = np.zeros((V.shape[0], a.shape[0]))
alpha[0, :] = initial_distribution * b[:, V[0]]
# αj(t+1) = bjkv(t+1)·∑i=1..M, aij·αi(t)
for t in range(1, V.shape[0]):
for j in range(a.shape[0]):
# Matrix Computation Steps
# ((1x2) . (1x2)) * (1)
# (1) * (1)
alpha[t, j] = alpha[t - 1].dot(a[:, j]) * b[j, V[t]]
return alpha
# Backward Algorithm is the time-reversed version of the Forward Algorithm. In Backward Algorithm
# we need to find the probability that the machine will be in hidden state si at time step t
# and will generate the remaining part of the sequence of the visible symbol V.
def backward(V, a, b):
beta = np.zeros((V.shape[0], a.shape[0]))
# setting beta(T) = 1
beta[V.shape[0] - 1] = np.ones((a.shape[0]))
# βi(t) = ∑j=0..M, βj(t+1)·bjkv(t+1)·aij
# Loop in backward way from T-1 to
# Due to python indexing the actual loop will be T-2 to 0
for t in range(V.shape[0] - 2, -1, -1):
for j in range(a.shape[0]):
beta[t, j] = (beta[t + 1] * b[:, V[t + 1]]).dot(a[j, :])
return beta
# Learning Problem: Once the high-level structure (Number of Hidden & Visible States) of
# the model is defined, we want to estimate the Transition (a) & Emission (b) Probabilities
# using the training sequences.
def baum_welch(V, a, b, initial_distribution, n_iter=100):
M = a.shape[0]
T = len(V)
for n in range(n_iter):
alpha = forward(V, a, b, initial_distribution)
beta = backward(V, a, b)
xi = np.zeros((M, M, T - 1))
for t in range(T - 1):
denominator = np.dot(np.dot(alpha[t, :].T, a) * b[:, V[t + 1]].T, beta[t + 1, :])
for i in range(M):
numerator = alpha[t, i] * a[i, :] * b[:, V[t + 1]].T * beta[t + 1, :].T
xi[i, :, t] = numerator / denominator
gamma = np.sum(xi, axis=1)
a = np.sum(xi, 2) / np.sum(gamma, axis=1).reshape((-1, 1))
# Add additional T'th element in gamma
gamma = np.hstack((gamma, np.sum(xi[:, :, T - 2], axis=0).reshape((-1, 1))))
K = b.shape[1]
denominator = np.sum(gamma, axis=1)
for l in range(K):
b[:, l] = np.sum(gamma[:, V == l], axis=1)
b = np.divide(b, denominator.reshape((-1, 1)))
return (a, b)
# Decoding Problem: Once we have the estimates for Transition (a) & Emission (b) Probabilities,
# we can then use the model (θ) to predict the Hidden States W which generated the Visible Sequence V
def viterbi(V, a, b, initial_distribution):
T = V.shape[0]
M = a.shape[0]
omega = np.zeros((T, M))
omega[0, :] = np.log(initial_distribution * b[:, V[0]])
prev = np.zeros((T - 1, M))
# ωi(t+1) = max(i, ωi(t)·aij·bjkv(t+1))
# One implementation trick is to use the log scale so that we dont get the underflow error.
for t in range(1, T):
for j in range(M):
# Same as Forward Probability
probability = omega[t - 1] + np.log(a[:, j]) + np.log(b[j, V[t]])
# This is our most probable state given previous state at time t (1)
prev[t - 1, j] = np.argmax(probability)
# This is the probability of the most probable state (2)
omega[t, j] = np.max(probability)
# Path Array
S = np.zeros(T)
# Find the most probable last hidden state
last_state = np.argmax(omega[T - 1, :])
S[0] = last_state
backtrack_index = 1
for i in range(T - 2, -1, -1):
S[backtrack_index] = prev[i, int(last_state)]
last_state = prev[i, int(last_state)]
backtrack_index += 1
# Flip the path array since we were backtracking
S = np.flip(S, axis=0)
return S
def test_forward(V):
# Transition Probabilities
a = np.array(((0.54, 0.46), (0.49, 0.51)))
# Emission Probabilities
b = np.array(((0.16, 0.26, 0.58), (0.25, 0.28, 0.47)))
# Equal Probabilities for the initial distribution
initial_distribution = np.array((0.5, 0.5))
alpha = forward(V, a, b, initial_distribution)
print(alpha)
def test_backward(V):
# Transition Probabilities
a = np.array(((0.54, 0.46), (0.49, 0.51)))
# Emission Probabilities
b = np.array(((0.16, 0.26, 0.58), (0.25, 0.28, 0.47)))
beta = backward(V, a, b)
print(beta)
def test_baum_welch(V):
# Transition Probabilities
a = np.ones((2, 2))
a = a / np.sum(a, axis=1)
# Emission Probabilities
b = np.array(((1, 3, 5), (2, 4, 6)))
b = b / np.sum(b, axis=1).reshape((-1, 1))
# Equal Probabilities for the initial distribution
initial_distribution = np.array((0.5, 0.5))
print(baum_welch(V, a, b, initial_distribution, n_iter=100))
def test_viterbi(V):
# Transition Probabilities
a = np.ones((2, 2))
a = a / np.sum(a, axis=1)
# Emission Probabilities
b = np.array(((1, 3, 5), (2, 4, 6)))
b = b / np.sum(b, axis=1).reshape((-1, 1))
# Equal Probabilities for the initial distribution
initial_distribution = np.array((0.5, 0.5))
a, b = baum_welch(V, a, b, initial_distribution, n_iter=100)
print([['A', 'B'][int(s)] for s in viterbi(V, a, b, initial_distribution)])
def main():
W = np.array(['B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B',
'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A',
'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B',
'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'A'])
V = np.array([0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 1, 0, 2, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 2,
0, 2, 2, 0, 2, 2, 2, 0, 0, 1, 0, 1, 2, 2, 2, 2, 0, 2, 2, 2, 1, 2, 0, 1, 0, 0, 2, 1, 2, 1, 1, 1, 0, 2, 0, 0, 1,
1, 2, 0, 1, 2, 0, 1, 0, 2, 1, 0, 0, 2, 0, 1, 0, 2, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 1, 2,
2, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 1, 0, 1, 0, 1, 0, 1, 2, 0, 2, 2, 1, 0, 0, 1, 1, 2, 2, 0, 2, 0,
0, 0, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 1, 2, 1, 1, 1, 2, 2,
2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 0, 2, 0, 1, 2, 0, 1, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
0, 0, 1, 2, 1, 0, 2, 2, 1, 2, 2, 2, 1, 0, 1, 2, 2, 2, 1, 0, 1, 0, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 0, 2, 0, 1,
1, 2, 0, 0, 2, 2, 2, 1, 1, 0, 0, 1, 2, 1, 2, 1, 0, 2, 0, 2, 2, 0, 0, 0, 1, 0, 1, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0,
1, 1, 2, 2, 0, 1, 2, 2, 2, 2, 2, 2, 0, 1, 2, 2, 0, 2, 0, 2, 2, 2, 1, 2, 2, 2, 1, 1, 1, 1, 2, 0, 0, 0, 2, 2, 1,
1, 2, 1, 0, 2, 1, 1, 1, 0, 1, 2, 1, 2, 1, 2, 2, 2, 0, 2, 0, 0, 2, 2, 2, 2, 2, 2, 1, 0, 1, 1, 1, 2, 1, 2, 2, 2,
2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 0, 1, 2, 0, 1, 2, 1, 2, 0, 2, 1, 0, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2, 2, 1,
2, 0, 2, 1, 2, 2, 2, 1, 2, 2, 2, 0, 0, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 1, 2, 2, 2, 2, 1, 2, 0,
2, 1, 2, 2, 0, 1, 0, 1, 2, 1, 0, 2, 2, 2, 1, 0, 1, 0, 2, 1, 2, 2, 2, 0, 2, 1, 2, 2, 0, 1, 2, 0, 0, 1, 0, 1, 1,
1, 2, 1, 0, 1, 2, 1, 2, 2, 0, 0, 0, 2, 1, 1, 2, 2, 1, 2])
print("\nTest: Forward:")
test_forward(V)
print("\nTest: Backward:")
test_backward(V)
print("\nTest: Baum Welch:")
test_baum_welch(V)
print("\nTest: Viterbi:")
test_viterbi(V)
if __name__ == '__main__':
main()
|
2e36c061760bd5fc34c226ecbe4b57ef3965c52c | tchen01/tupper | /tupper.py | 368 | 3.515625 | 4 | from PIL import Image
im = Image.open("bd.jpg")
width = im.size[0]
height = im.size[1]
k = ''
def color( c ):
sum = c[0] + c[1] + c[2]
if ( sum < 383 ):
return 1
else:
return 0
for x in range(0, width):
for y in reversed(range(0, height)):
k += str( color( im.getpixel( (x,y) ) ))
k = int(k, base = 2) * height
print("k=",k, "height=", height)
|
661d4a1116284d03356f5114ff955edac0b00c90 | AlberVini/exp_regulares | /aulas_exemplos/aula06.py | 443 | 3.546875 | 4 | # ^ a expressão deve começar de x maneira
# ^ [^a-z] serve para negar algo em especifico
# $ a expressão deve terminar de x maneira
# os meta caracteres acima servem para a busca exata da expressão passada
import re
cpf = '293.457.246-99'
cpf2 = 'a 293.457.246-99'
print(re.findall(r'^((?:[0-9]{3}\.){2}[0-9]{3}-[0-9]{2})$', cpf))
print(re.findall(r'^((?:[0-9]{3}\.){2}[0-9]{3}-[0-9]{2})$', cpf2))
print(re.findall(r'[^a-z]+', cpf2))
|
d32928cf7ee10d8298ed8eb9272759b53f94b85a | aktilekpython/pyth-on | /new.py | 1,801 | 4.03125 | 4 | #1 задание
# number = int(input("Введите первое число"))
# number2 = int(input("Введите второе число"))
# print(number - number2)
#name =input ("Введите свое имя:")
#print(name* 18
#2 задание
#print(36 % 5)
#3 задание
#a = input ("Введите свое имя:")
#b = (a[::-1])
#if a==b:
#print ("Полиндром")
#else:
#print("это не полидром")
#4задание
# string = ("I love java")
# string.replace("java","python")
#print(string.replace('java', "python"))
#5 задание
# a = input('Введите свое имя')
# print(a * 10)
#6 задание
# list_ = input("Введите все что хотите:" )
# list_2 = list_[::-1]
# print(list_2)
#8 задание
# a = str(input("Введите что хотите"))
# b = len(a)
# c = a[::-1]
# if b>4:
# print(a[0:2] + c[1]+c[0])
# print("Введите свое имя")
#else:
# print("Введите свое имя")
# b = (a[::-1])
#7 задание
# b = (input("Введите число"))
# print(b[10:11:])
# if len(b) > 10:
# print('Число содержит мене 10 цифр')
# #9 задание
# a = int(input("Выводите первое число"))
# print(1+a)
# print(a-1)
# 10задание
#a = input ("Выводите первое число")
#b = input ("Выводите второе число")
#if a < b:
#print (" b больше a")
#11 задание
# a =int(input("Введите любое число:"))
# if a > 0:
# print ("это положительное число")
# elif a < 0:
# print('это отрицательное число')
# else:
# print("это не отрицательное и не положительное")
|
c5dd8782dfe182b77f0afbd5bbc9700c3237fcd1 | 100sun/hackerrank | /sherlock-and-the-valid-string.py | 2,283 | 3.71875 | 4 | # https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings&h_r=next-challenge&h_v=zen
from collections import Counter
import time
# Complete the isValid function below.
def isValid_sun_1(s):
freq = Counter(s).values()
freq_removed_dup = list(set(freq))
freq_cnt = Counter(freq)
if len(freq_removed_dup) == 1:
return 'YES'
if len(freq_cnt) == 2:
if freq_cnt[1] == 1 or 1 in set(freq_cnt) and abs(list(set(freq))[0] - list(set(freq))[1]) == 1:
return 'YES'
return 'NO'
def isValid_ans(string):
string = Counter(Counter(string).values())
# print(string)
if len(string.keys()) == 1:
print("YES")
elif len(string.values()) == 2:
key1, key2 = string.keys()
if string[key1] == 1 and (key1 - 1 == key2 or key1 - 1 == 0):
print("YES")
elif string[key2] == 1 and (key2 - 1 == key1 or key2 - 1 == 0):
print("YES")
else:
print("NO")
else:
print("NO")
def isValid_ho(s):
freq = {}
cnt = set()
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
for num in freq.values():
cnt.add(num)
if len(cnt) == 1:
return 'YES'
elif len(cnt) > 2:
return 'NO'
else:
for key in freq:
freq[key] -= 1
temp = list(freq.values())
try:
temp.remove(0)
except:
pass
if len(set(temp)) == 1:
return 'YES'
else:
freq[key] += 1
return 'NO'
if __name__ == '__main__':
s = input()
start_time = time.time()
isValid_ans(s)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
isValid_sun_1(s)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
isValid_ho(s)
print("--- %s seconds ---" % (time.time() - start_time))
# https://hr-testcases-us-east-1.s3.amazonaws.com/8816/input13.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1618547009&Signature=2bnRZDGAFefVszdbJzgQEuX%2FTAU%3D&response-content-type=text%2Fplain
|
695bcb02901af251d4ece24a84976015eb7201d0 | newkstime/PythonLabs | /Lab14/Problem2/electricity_bill.py | 1,113 | 3.8125 | 4 | from Problem2.utility_bill import Utility_bill
class Electricity_bill(Utility_bill):
def __init__(self, customer_name, customer_address):
base = super()
base.__init__(customer_name, customer_address)
self._kwh_used = 0
def calculate_charge(self):
while isinstance(self._kwh_used, float) == False or self._kwh_used <= 0:
try:
self._kwh_used = float(input("Enter the kWh of electricity used: "))
while self._kwh_used <= 0:
print("Usage cannot be negative.")
self._kwh_used = float(input("Enter the kWh of electricity used: "))
except ValueError:
print("Invalid entry")
if self._kwh_used <= 500:
self._total = self._kwh_used * 0.12
else:
self._total = (500 * 0.12) + ((self._kwh_used - 500) * 0.15)
def display_bill(self):
print("Electricity Bill\nName: ", self._customer_name, "\nAddress: ", self._customer_address,
"\nkWh used: ", self._kwh_used, "\nTotal due: ${0:.2f}".format(self._total))
|
59a5e4e86c2ccfd9b33ca254a220754fe981ebf7 | newkstime/PythonLabs | /Lab07/Lab07P4.py | 2,277 | 4.1875 | 4 | def main():
numberOfLabs = int(input("How many labs are you entering?"))
while numberOfLabs <= 0:
print("Invalid input")
numberOfLabs = int(input("How many labs are you entering?"))
labScores = []
i = 0
while i < numberOfLabs:
score = float(input("Enter a lab score:"))
labScores.append(score)
i += 1
print("Lab scores:", labScores)
numberOfTests = int(input("How many tests are you entering?"))
while numberOfTests <= 0:
print("Invalid input")
numberOfTests = int(input("How many tests are you entering?"))
testScores = []
i = 0
while i < numberOfTests:
score = float(input("Enter a test score:"))
testScores.append(score)
i += 1
print("Test scores:", testScores)
print("The default weight for scores is 50% labs and 50% tests.")
weightSelection = input("To change weight scale enter C, to use default weights, enter D:").lower()
while weightSelection != "c" and weightSelection != "d":
print("Invalid input.")
weightSelection = input("To change weight scale enter C, to use default weights, enter D:").lower()
if weightSelection == "c":
labWeight = float(input("What % weight do you want labs to count for? (Do not use % sign):"))
while labWeight < 0:
print("Invalid input.")
labWeight = float(input("What % weight do you want labs to count for? (Do not use % sign):"))
testWeight = float(input("What % weight do you want tests to count for? (Do not use % sign):"))
while testWeight < 0:
print("Invalid input.")
testWeight = float(input("What % weight do you want tests to count for? (Do not use % sign):"))
grade_calculator(labScores, testScores, labWeight, testWeight)
else:
grade_calculator(labScores, testScores)
def grade_calculator(labScores, testScores, labWeight = 50, testWeight = 50):
labAverage = sum(labScores) / len(labScores)
print("Lab Average:", labAverage)
testAverage = sum(testScores) / len(testScores)
print("Test Average:", testAverage)
courseGrade = (labAverage * (labWeight/100)) + (testAverage * (testWeight/100))
print("Course Grade:", courseGrade)
main()
|
842938b66f413e4a260395823d59a0a589bbdecf | newkstime/PythonLabs | /Lab03 - Selection Control Structures/Lab03P2.py | 824 | 4.21875 | 4 | secondsSinceMidnight = int(input("Please enter the number of seconds since midnight:"))
seconds = '{:02}'.format(secondsSinceMidnight % 60)
minutesSinceMidnight = secondsSinceMidnight // 60
minutes = '{:02}'.format(minutesSinceMidnight % 60)
hoursSinceMidnight = minutesSinceMidnight // 60
if hoursSinceMidnight < 24 and hoursSinceMidnight >= 12:
meridiem = "PM"
hours = hoursSinceMidnight - 12
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
elif hoursSinceMidnight < 12:
meridiem = "AM"
hours = hoursSinceMidnight
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
else:
print("The input seconds exceeds the number of seconds in a single day.")
|
f97e5dbe14092f39d82077b6d610022bee8dd921 | newkstime/PythonLabs | /Lab02 - Variables/Problem5.py | 532 | 3.859375 | 4 | jackpot = int(input("Enter in the jackpot amount:"))
jackpot_annual = jackpot / 20
jackpot_annual_taxed = jackpot_annual * .70
jackpot_lump = jackpot * .65
jackpot_lump_taxed = jackpot_lump * .70
print("Your pre tax annual installment amount is: $", format(jackpot_annual, ",.2f"))
print("Your annual installment amount after tax is: $", format(jackpot_annual_taxed, ",.2f"))
print("Your pre tax lump sum amount is: $", format(jackpot_lump, ",.2f"))
print("Your lump sum amount after tax is: $", format(jackpot_lump_taxed, ",.2f"))
|
f02598ce41301d20062740172132e99841afa6f7 | newkstime/PythonLabs | /Lab11/Lab11P01.py | 782 | 3.96875 | 4 | import re
user_input = input("Enter a string:")
user_input = user_input.upper()
user_input = re.sub("[^a-zA-Z]","", user_input)
occurs_dict = {}
for n in user_input:
keys = occurs_dict.keys()
if n in keys:
occurs_dict[n] += 1
else:
occurs_dict[n] = 1
print("Dictionary:", occurs_dict)
find_count = input("Choose a letter:")
find_count = re.sub("[^a-zA-Z]","", find_count)
find_count = find_count.upper()
if find_count not in occurs_dict.keys():
print("Value not in dictionary.")
quit()
print("The letter", find_count, "appears", occurs_dict[find_count], "times.")
del occurs_dict[find_count]
print("Dictionary after removing", find_count, ":", occurs_dict)
letter_list = list(occurs_dict.keys())
print("Letters sorted:", sorted(letter_list))
|
fca87e784502567925ce41bdd5574ba263c30fe0 | newkstime/PythonLabs | /Lab08/Lab08P1.py | 614 | 3.984375 | 4 | def get_kWh_used():
kWh = float(input("Enter the number of kilowatt hours used:"))
while kWh < 0:
print("Invalid input.")
kWh = float(input("Enter the number of kilowatt hours used:"))
return kWh
def bill_calculator(kWhUsed):
lowRate = 0.12
highRate = 0.15
kWhLimit = 500
if kWhUsed <= kWhLimit:
charge = kWhUsed * lowRate
else:
charge = ((kWhUsed - kWhLimit) * highRate) + (kWhLimit * lowRate)
return charge
def main():
printBill = bill_calculator(get_kWh_used())
print("Please pay this amount: $", format(printBill, ",.2f"))
main()
|
269dde29e6bc2a138c37e57bfcbe02a3e9c31da7 | newkstime/PythonLabs | /Lab13/fly_drone_new/fly_drone_main.py | 531 | 3.640625 | 4 | from drone import Drone
drone1 = Drone()
keep_going = True
while keep_going == True:
user_input = input("Enter 1 for accelerate, 2 for decelerate, 3 for ascend, 4 for desend, 0 to exit:")
if user_input == "1":
drone1.accelerate()
elif user_input == "2":
drone1.decelerate()
elif user_input == "3":
drone1.ascend()
elif user_input == "4":
drone1.descend()
elif user_input == "0":
keep_going = False
else:
print("Unrecognized command.")
print (drone1)
|
5b6c65b831d23d515d1374ff1d16fbf451bd15a9 | newkstime/PythonLabs | /Lab14/Problem1/main.py | 862 | 3.890625 | 4 | from Problem1.dinner_combo import Dinner_combo
from Problem1.deluxe_dinner_combo import Deluxe_dinner_combo
def main():
choose_dinner_type = input("For Dinner Combo, enter [1]. For Deluxe Dinner Combo, enter [2]: ")
while choose_dinner_type != '1' and choose_dinner_type != '2':
print("Invalid selection. Please try again.")
choose_dinner_type = input("For Dinner Combo, enter [1]. For Deluxe Dinner Combo, enter [2]: ")
if choose_dinner_type == '1':
final_order = Dinner_combo()
final_order.choose_main_dish()
final_order.choose_soup()
final_order.display_order()
elif choose_dinner_type == '2':
final_order = Deluxe_dinner_combo()
final_order.choose_main_dish()
final_order.choose_soup()
final_order.choose_appetizer()
final_order.display_order()
main()
|
762f0115352b4b776ece45f8d5998b5ec06cd2ea | M-Karthik7/Numpy | /main.py | 2,932 | 4.125 | 4 | Numpy Notes
Numpy is faster than lists.
computers sees any number in binary fromat
it stores the int in 4 bytes ex : 5--> 00000000 00000000 00000000 00000101 (int32)
list is an built in int type for python it consists of 1) size -- 4 bytes
2) reference count -- 8 bytes
3) object type -- 8 bytes
4) object value -- 8 bytes
since numpy uses less bytes of memory it is faster than lists.
Another reason for numpy is faster than list is it uses contiguous memory. contiguous memory -- continues memory.
benefits :
->SIMD Vector processing
SIMD-Single Instruction Multiple Data.
->Effective cache utilization
lists | numpy
|
-> List can perform |-> Numpy can perforn insertion Deletion
insertion,delection | , appending , concatenation etc. we can perform lot more actions here.
appending,concatenation |
ex : | ex :
a=[1,3,5] | import numpy as np
b=[1,2,3] | a=np.array([1,3,5])
a*b = ERROR | b=np.array([1,2,3])
| c=a*b
| print(c)
|
| o/p : [1,6,15]
Applications of Numpy?
-> we can do maths with numpy. (MATLAB Replacement)
-> Plotting (Matplotlib)
-> Backend ( Pandas , Connect4 , Digital Photography)
-> Machine Learing.
Codes.
1) input
import numpy as np
a=np.array([1,2,3])
print(a)
1) o/p
[1 2 3] (one dimentional array)
2) input
b=np.array([[9.0,3.9,4],[6.0,5.0,4.0]])
print(b)
2) 0/p
[[9. 3.9 4. ] ( both the array inside must be equal or else it will give error )
[6. 5. 4. ]] --> Two dimentional array.
3) input
#To get dimension.
->print(a.ndim)
n-number,dim-dimention
3) o/p
1
4) input
# To get shape.
print(b.shape)
print(a.shape)
4) o/p
(2, 3) # { 2 rows and 3 columns }
(3,) # { 1 row and 3 columns }
5) input
# to get type.
print(a.dtype)
d-data,type
5) o/p
int32
6) input
to get size.
print(a.itemsize)
6) o/p
4 ( because 4 * 8 = 32 ) 8 - bytes
7) input
note :
we can specify the dtype in the beginning itself ex:
a=np.array([2,3,4],dtype='int16')
print(a.itemsize)
7) o/p
2 (because 2 * 8 = 16 ) 8 - bytes
8) input
# to get total size.
a=np.array([[2,5,4],[3,5,4]])
print(a.nbytes) # gets total size.
print(a.size * a.itemsize) # gets the total size.
8) o/p
24
24
9) input
#to get specific element [row,column]
print(a)
print(a[1,2]) or print(a[-1,-1]) '-' Refers to reverse indexing.
o/p
[[2 5 4]
[3 5 4]]
( indexing strats from 0 so a[1,2] means 2st row and 3rd column which is 4. )
4
input
#to get specific row only.
print(a[0:1])
o/p
[2 5 4]
input
#to get specific column.
print(a[:,2])
o/p
[4 4]
|
7aed164cec411ae8a7cc3675a7b7b06512f6c742 | satishkmrsuman/tg | /printboard.py | 843 | 3.9375 | 4 | def create_board(num_place):
if(num_place-1)%3 != 0:
return ""
space_count=num_place*2
brace_space_count=0
hyphen_count=1
brace_string=""
board=" "*space_count+" {}\n"
for i in range(num_place-2):
if hyphen_count%3==0:
brace_string=" "*space_count+"{}"+"-"*(int((brace_space_count-1)/2))+"-{}"+"-"*(int((brace_space_count-1)/2))+"{}\n"
else:
brace_string=" "*space_count+"/"+" "*(int((brace_space_count/2)))+"|"+" "*(int((brace_space_count/2)))+"\\\n"
board=board+brace_string
space_count=space_count-1
brace_space_count=brace_space_count+2
hyphen_count=hyphen_count+1
brace_string=" "*space_count+"{}"+"-"*(int((brace_space_count-1)/2))+"-{}"+"-"*(int((brace_space_count-1)/2))+"{}\n"
board=board+brace_string
return board |
1334de81ce0e73855b4ee93b6ddd6b009271bb43 | Arkelis/adventofcode-2020 | /python/day06.py | 567 | 3.765625 | 4 | def count_yes(possible_answers, group_answers, need_all=False):
if need_all:
group_answers = set.intersection(*map(set, group_answers.split(" ")))
return sum(q in group_answers for q in possible_answers)
if __name__ == "__main__":
with open("inputs/day06.txt", "r") as f:
lines = (f.read() + "\n").replace("\n", " ").split(" ") # one line per group
print("Part 1:", sum(count_yes("abcdefghijklmnopqrstuvwxyz", line) for line in lines))
print("Part 2:", sum(count_yes("abcdefghijklmnopqrstuvwxyz", line, True) for line in lines))
|
9344dfc77da748a5bcfc5c2eac7a1cd0b0e810f3 | Panda-ing/practice-py | /python_course/pentagram/pentagram_v3.0.py | 573 | 4.25 | 4 | """
作者:xxx
功能:五角星绘制
版本:3.0
日期:17/6/2020
新增功能:加入循环操作绘制不同大小的图形
新增功能:使用迭代绘制不同大小的图形
"""
import turtle
def draw_pentagram(size):
count = 1
while count <= 5:
turtle.forward(size)
turtle.right(144)
count = count + 1
def main():
"""
主函数
"""
size = 50
while size <= 100:
draw_pentagram(size)
size += 10
turtle.exitonclick()
if __name__ == '__main__':
main()
|
785112f03098cc2414e8c6ac891305497ad58767 | yujin75/python | /6-6.py | 524 | 3.609375 | 4 | from random import randint
i = 4
#랜덤수 생성
answer = randint(1, 20)
#4번의 기회
while i>0:
guess = int(input("기회가 %d번 남았습니다. 1-20 사이의 숫자를 맞춰보세요: " % i))
if(guess == answer):
print("축하합니다. %d번만에 숫자를 맞추셨습니다." % (4-i+1))
break
elif(guess > answer):
print("Down")
i = i - 1
else:
print("Up")
i = i - 1
if(i == 0):
print("아쉽습니다. 정답은 %d였습니다." % answer) |
9ced4b8770aae2448d8e2e248bd5d6a1c654b595 | sverma1012/HackerRank-30-Days-of-Code | /Day 2: Operators.py | 601 | 3.890625 | 4 | # Day 2
# Goal: Operators
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(meal_cost, tip_percent, tax_percent):
meal_tip = meal_cost + (meal_cost * (tip_percent / 100)) # The meal cost plus the tip given
meal_tip_tax = meal_tip + (meal_cost * (tax_percent / 100)) # The meal cost plus the tip plus the tax
print(round(meal_tip_tax)) # print resultant value
if __name__ == '__main__':
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
solve(meal_cost, tip_percent, tax_percent)
|
3e250750eca7c8bbb2796ee95d8dd61a2ffe27b1 | GrayThinker/PyAlgorithms | /test/test_sorts.py | 2,761 | 3.953125 | 4 | from src.sort import *
import unittest
"""
TODO:
Even number of elements
odd number of elements
empty list
single elements
only letters
only integers (+ve)
only floats (+ve)
mix of floats and integers (+ve)
mix of floats and letters (+ve)
mix of floats, letters, and integers (+ve)
only integers (+ve)
only floats (+ve)
mix of floats and integers (+ve)
mix of floats and letters (+ve)
mix of floats, letters, and integers (+ve)
symbols
"""
class TestSorts(unittest.TestCase):
def test_bubble_sort(self):
self.assertEqual(bubble_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(bubble_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(bubble_sort([7]), [7])
self.assertEqual(bubble_sort([]), [])
def test_insertion_sort(self):
self.assertEqual(insertion_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(insertion_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(insertion_sort([7]), [7])
self.assertEqual(insertion_sort([]), [])
def test_selection_sort(self):
self.assertEqual(selection_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(selection_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(selection_sort([7]), [7])
self.assertEqual(selection_sort([]), [])
def test_pigeon_hole_sort(self):
self.assertEqual(pigeon_hole_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(pigeon_hole_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(pigeon_hole_sort([7]), [7])
self.assertEqual(pigeon_hole_sort([]), [])
def test_merge_sort(self):
self.assertEqual(merge_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(merge_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(merge_sort([7]), [7])
self.assertEqual(merge_sort([]), [])
def test_quick_sort(self):
self.assertEqual(quick_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(quick_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(quick_sort([7]), [7])
self.assertEqual(quick_sort([]), [])
def test_bogo_sort(self):
self.assertEqual(bogo_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(bogo_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(bogo_sort([7]), [7])
self.assertEqual(bogo_sort([]), [])
def test_cocktail_sort(self):
self.assertEqual(cocktail_sort([3, 4, 1, 8, 9]), [1, 3, 4, 8, 9])
self.assertEqual(cocktail_sort([3, -1, 1, 0, 3]), [-1, 0, 1, 3, 3])
self.assertEqual(cocktail_sort([7]), [7])
self.assertEqual(cocktail_sort([]), [])
if __name__ == '__main__':
unittest.main() |
700fb28af3caa49e9b8acc28cc41c7452f945845 | chenchaojie/leetcode350 | /stack/二叉树的前序遍历-144.py | 1,093 | 3.796875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
def preorder(root):
if not root:
return
ret.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return ret
def preorderTraversal2(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
s = []
if root:
s.append(root)
while s:
node = s.pop()
ret.append(node.val)
if node.right:
s.append(node.right)
if node.left:
s.append(node.left)
return ret
if __name__ == "__main__":
head = TreeNode(1)
head.right = TreeNode(2)
head.right.left = TreeNode(3)
print(Solution().preorderTraversal2(head))
|
0f80eb652915be236193605ce1a2a088ed74adc0 | helkey/algorithm | /python/1114_PrintInOrder.py | 1,806 | 3.90625 | 4 | # 1114. Print in Order
TypeError: '_thread.lock' object is not callable
# Python offers mutexes, semaphores, and events for syncronization
import threading
import threading
class Foo:
def __init__(self):
self.lock2nd = threading.Lock()
self.lock3rd = threading.Lock()
self.lock2nd.acquire()
self.lock3rd.acquire()
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.lock2nd.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
self.lock2nd.acquire()
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
# self.lock2nd.release()
self.lock3rd.release()
def third(self, printThird: 'Callable[[], None]') -> None:
self.lock3rd.acquire()
# printThird() outputs "third". Do not change or remove this line.
printThird()
# self.lock3rd.release()
# USING EVENTS
class Foo:
def __init__(self):
self.ev2nd = threading.Event()
self.ev3rd = threading.Event()
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.ev2nd.set()
def second(self, printSecond: 'Callable[[], None]') -> None:
self.ev2nd.wait()
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
self.ev3rd.set()
def third(self, printThird: 'Callable[[], None]') -> None:
self.ev3rd.wait()
# printThird() outputs "third". Do not change or remove this line.
printThird()
|
949b5ed3ca2e1c8e5b2c35834e8bdb201aec08fd | helkey/algorithm | /python/277FindCelebrity.py | 1,423 | 3.765625 | 4 | """ Find the Celebrity
Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity.
The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
https://leetcode.com/problems/find-the-celebrity/
Faster than 65% of Python submissions
"""
class Solution:
def findCelebrity(self, n: int) -> int:
# Identify single candidate as possible celebrity
iStart, iEnd = 0, n - 1
while iEnd - iStart > 0:
if knows(iStart, iEnd):
iStart += 1
else:
iEnd -= 1
# Everybody knows celebrity; celebrity doesn't know anybody
# celebDoesntKnow = not any([knows(iStart, i) for i in range(n) if i != iStart])
for i in range(n):
if i != iStart and not knows(i, iStart):
return -1 # somebody doesn't know celebrity candidate
if i != iStart and knows(iStart, i):
return -1 # celebrity candidate knows someone else
return iStart
s = Solution()
graph1 = [[1,1,0],
[0,1,0],
[1,1,1]] # 1
graph = [[1,0,1],
[1,1,0],
[0,1,1]] # -1
graph = [[1,1],[1,1]] # -1
def knows(i1, i2) -> bool:
# iCeleb = 8
# return (i2 == iCeleb)
return graph[i1][i2]
print(s.findCelebrity(2))
|
9f32a55e154df63cb2abcccebe2204529d452a4d | helkey/algorithm | /python/912_sortarray.py | 1,323 | 3.703125 | 4 | # 912. Sort Array
# Merge Sort: Faster than 33% of Python submissions
# Merge sort has good cache performance and [parallelizes well](https://en.wikipedia.org/wiki/Parallel_algorithm)
# Time complexity O(n log n)
# Space complexity O(n)
# (illustration why not O(n log n): stackoverflow.com/questions/10342890/merge-sort-time-and-space-complexity)
from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def merge(nums1: List, nums2: List) -> List[int]:
""" Merge two sorted, non-empty lists """
ln1, ln2 = len(nums1), len(nums2)
# Allocate empty list
nums = [None] * (ln1 + ln2)
i1, i2 = 0, 0
for k in range(ln1 + ln2):
if (i2 == ln2) or ((i1 !=ln1) and (nums1[i1] < nums2[i2])):
nums[k] = nums1[i1]
i1 += 1
else:
nums[k] = nums2[i2]
i2 += 1
return nums
if len(nums) <= 1:
return nums
if len(nums) == 2:
return [min(nums), max(nums)]
nSplit = round(len(nums)/2)
return merge(self.sortArray(nums[:nSplit]), self.sortArray(nums[nSplit:]))
|
4fbbed2f514176ecc901224d3c1c487ef2389059 | helkey/algorithm | /python/111_Min_Dept_Binary_Tree.py | 592 | 3.671875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
def mindp(node):
if not node: return 0
if node.left and node.right:
return min(mindp(node.left)+1, mindp(node.right)+1)
if node.left: return mindp(node.left)+1
if node.right: return mindp(node.right)+1
return 1
return mindp(root)
|
1ab4306672ddfc5d4b2f0816942e097b06e1d0ca | helkey/algorithm | /python/110_Balanced_Binary.py | 1,879 | 3.625 | 4 | // 110.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def treeDepth(node: TreeNode) -> int:
if (node == None):
return 0
depL = treeDepth(node.left)
depR = treeDepth(node.right)
isBal = ((depL <= depR + 1) and (depR <= depL + 1))
if not isBal:
raise Exception
return max(depL, depR) + 1
try:
_ = treeDepth(root)
return True
except:
return False
""" SCALA: Similar implementatin blows up stack
object Solution {
def isBalanced(root: TreeNode): Boolean = {
val (_, balanced) = treeDepth(root)
return balanced
}
def treeDepth(node: TreeNode): (Int, Boolean) = {
if (node == null) {
return (0, true)
}
val (depL, balL) = treeDepth(node.left)
val (depR, balR) = treeDepth(node.right)
val bal = ((depL <= depR + 1) && (depR <= depL + 1)) // this node is balanced
return (List(depL, depR).max + 1, (bal && balL && balR))
}
} """
""" This approach checks for minimum height tree;
which does not satisfy problem test case:
Input: [1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5]
Output: False; Expected: True
object Solution {
def isBalanced(root: TreeNode): Boolean = {
val (minD, maxD) = minMaxDepth(root)
return (maxD <= minD + 1)
}
def minMaxDepth(node: TreeNode): (Int, Int) = {
if (node == null) {
return (0, 0)
}
val (minL, maxL) = minMaxDepth(node.left)
val (minR, maxR) = minMaxDepth(node.right)
return (List(minL, minR).min + 1, List(maxL, maxR).max + 1)
}
} """
|
7b827ff1f40b044c83f6aec9c06008840b550404 | hercules261188/python-studies | /Fibonacci/Iterative.py | 178 | 3.5625 | 4 | def fib(n):
if n == 0:
return 0
left = 0
right = 1
for i in range(1, n):
left, right = right, left + right
return right
print(fib(1)) |
dd11f7442672f3c2408d563d7924bd2d2b0d8ad3 | hercules261188/python-studies | /Fibonacci/Recursive.py | 509 | 3.90625 | 4 | # def fib(n):
# if n == 0 or n == 1:
# return n
# return fib(n - 1) + fib(n - 2)
# print(fib(2))
## Kotu cozum. Cunku olusan agacta fib degerleri sol ve sag
## dallanmalarda da hesaplaniyor.
## fib(3) + fib(2) icin => agacta fib(1), fib(2) iki kere hesaplaniyor
################# Daha iyi yol #################
memo = {}
def fib(n):
if n == 0 or n == 1:
return n
if n not in memo.keys():
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
print(fib(50)) |
9c87465b70bef73db613262b8d219b9cc92817d7 | BipronathSaha99/dailyPractiseCode | /class_4_help.py | 655 | 4.09375 | 4 | # Write a program to determine the smallest number among the four integers.
num_1=int(input('1st number:'))
num_2=int(input('2nd number:'))
num_3=int(input('3rd number:'))
num_4=int(input('4th number:'))
#==================> Condition<======================#
if (num_1<num_2 and num_1<num_3 and num_1<num_4):
print("{} is the smallest number".format(num_1))
elif (num_2<num_1 and num_2<num_3 and num_2<num_4):
print("{} is the smallest number".format(num_2))
elif (num_3<num_1 and num_3<num_2 and num_3<num_4):
print("{} is the smallest number".format(num_3))
else:
print("{} is the smallest number".format(num_4)) |
c23c54bbb0e2d2d322eabb501e0bf5954e9216d8 | BipronathSaha99/dailyPractiseCode | /pravin.py | 239 | 3.953125 | 4 | a=str(input("Enter numbers:"))
b=list(a) #type caste
print(b,type(b))
d= tuple(a) # type casting
print(d,type(d))
e={'a':2,'b':'d','c':4,'v':'u'}
print(e,type(e))
f=list(e)
print(f,type(f))
g=tuple(e)
print(g,type(g))
|
b9a452d73d50db7f8a601032ad5d7ce121ebfa21 | BipronathSaha99/dailyPractiseCode | /try_2.py | 431 | 4.09375 | 4 | #----------------------------Second list operation----------------------------------#
#--------------------------- Changing a member--------------------------------------#
my_list=["car","chalk","phone","bag"]
#--------------------------Q--------------------------------------#
#----------------------replace "phone" and "car" with "pen" and "pencil"-----------------#
my_list[0]="pencil"
my_list[2]="pen"
print(my_list)
|
23cbfdbc4c65c7b5c4b3012d6bd2d1938d27e4cb | BipronathSaha99/dailyPractiseCode | /oop_11.py | 4,332 | 4.78125 | 5 | '''Python datetime
In this article, you will learn to manipulate date and time in
Python with the help of examples.
Python has a module named datetime to work with dates and times.
Let's create a few simple programs related to date and time before we dig deeper.'''
# Example 1: Get Current Date and Time
# import datetime
# print(dir(datetime.datetime))
# print(datetime.datetime.now())
# x=datetime.datetime.now()
# print("Todays time and dates are:",x)
# Example 2: Get Current Date
# import datetime
# print("Todays date is:",datetime.date.today())
# Commonly used classes in the datetime module are:
# date Class
# time Class
# datetime Class
# timedelta Class
# datetime.date Class
# Example 3: Date object to represent a date
# import datetime
# print(datetime.date(2020,7,1))
# print(datetime.datetime.today())
# from datetime import date
# print(date(2020,7,1))
# # Example 4: Get current date
# from datetime import date
# print(date.today())
# Example 5: Get date from a timestamp
# from datetime import date
# print(date.fromtimestamp(1593549645.0))
# from datetime import date as timestamp
# print(timestamp.fromtimestamp(13012210010))
# Example 6: Print today's year, month and day
# from datetime import date
# print(date.today().year)
# print(date.today().month)
# print(date.today().day)
# Example 7: Time object to represent time
# from datetime import time
# a=time() #hour=0 min=0 sec=0
# print("a=",a)
# a=time(2,35,34)
# print("a=",a)
# datetime.datetime
# Example 9: Python datetime object
# from datetime import datetime
# a=datetime(2020,7,1,2,40,45)
# print(a)
# Example 10: Print year, month, hour, minute and timestamp
# print(a.year)
# print(a.month)
# print(a.day)
# print(a.hour)
# print(a.minute)
# print(a.second)
# print(a.timestamp())
# datetime.timedelta
# Example 11: Difference between two dates and times
# from datetime import datetime,date
# t1=date(year=2020,month=7,day=1)
# t2=date(year=2021,month=12,day=12)
# t3=t2-t1
# print(t3,type(t3))
# Example 12: Difference between two timedelta objects
# from datetime import timedelta
# t1=timedelta(weeks=2,days=5,hours=4,minutes=34)
# t2=timedelta(weeks=3,days=3,hours=3,minutes=35)
# t3=t2-t1
# print(t3,type(t3))
# Example 13: Printing negative timedelta object
# from datetime import timedelta
# t1=timedelta(seconds=33)
# t2=timedelta(seconds=56)
# t3=t1-t2
# print(t3)
# print(abs(t3))
# Example 14: Time duration in seconds
# from datetime import timedelta
# t=timedelta(days=2,hours=4,minutes=45,seconds=45)
# print(t.total_seconds())
# strpttime()
#strfttime()
# from datetime import datetime
# print(datetime.now())
# print(datetime.now().strftime("%H:%M:%S"))
# print(datetime.now().strftime("%d/%m/%Y"))
# print(datetime.today().strftime("%b"))
# print(datetime.now().strftime("%B"))
# print(datetime.now().strftime("%a"))
# print(datetime.now().strftime("%A"))
# %a=day ,%b=month
# print(datetime.now().strftime("%I"))
# %I=12 hours clock time
# print(datetime.now().strftime("%I %p"))
# %p=local am/pm time
# print(datetime.now().strftime("%f"))
# %f = microsecond
# print(datetime.now().strftime("%x"))
# print(datetime.now().strftime("%X"))
# %x=local's appropriate date and %X=local's appropriate time
# print(datetime.now().strftime("%c"))
# print(datetime.now().strftime("%C"))
# %c= local time and date
# %C = last digit of the year
# print(datetime.now().strftime("%U"))
# print(datetime.now().strftime("%j"))
# using datetime finding execution time of a time
# from datetime import datetime
# p=datetime.today()
# n=int(input("Enter the last digit:"))
# sum=(n*(n+1))/2
# print("Sum=",sum)
# q=datetime.today()
# print(q-p)
# from datetime import datetime
# r=datetime.today()
# # n=int(input("Enter the last digit:"))
# sum_1=0
# for i in range(0,n+1):
# sum_1+=i
# print("Sum=",sum_1)
# s=datetime.today()
# print(s-r)
# python time module
# time.time()
# import time
# seconds=time.time()
# print(seconds)
# time.ctime()
# import time
# seconds=1593756271.8245046
# print(time.ctime(seconds))
# time.asctime()
# import time
# print(time.asctime())
|
842537dd9dc81702334029a1f9b2e702ae4900e8 | BipronathSaha99/dailyPractiseCode | /operator_presidence.py | 395 | 3.921875 | 4 | # operator presidency
# Precedence of or & and
# meal = "fruit"
# money = 0
# if meal == "fruit" or meal == "sandwich" and money >= 2:
# print("Lunch being delivered")
# else:
# print("Can't deliver lunch")
meal = "fruit"
money = 0
if (meal == "fruit" or meal == "sandwich") and money >= 2:
print("Lunch being delivered")
else:
print("Can't deliver lunch") |
c3fa208e407461517404f378a50ca85af3802e36 | sasa233/myLeetcode | /median-of-two-orderd-arrays.py | 1,567 | 4.0625 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
'''
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
len1, len2 = len(nums1), len(nums2)
if (len1 + len2) % 2 == 1:
return self.getKth(nums1, nums2, (len1 + len2) // 2 + 1)
else:
return (self.getKth(nums1, nums2, (len1 + len2) // 2) + \
self.getKth(nums1, nums2, (len1 + len2) // 2 + 1)) * 0.5
def getKth(self, A, B, k): #获取两排序数组合并后第k大的数
m, n = len(A), len(B)
if m > n:
return self.getKth(B, A, k)
left, right = 0, m
while left < right:
mid = left + (right - left) // 2
if 0 <= k - 1 - mid <n and A[mid] >= B[k - 1 - mid]:
right = mid
else:
left = mid + 1
Ai_minus_1 = A[left - 1] if left - 1 >= 0 else float("-inf")
Bj = B[k - 1 - left] if k - 1 - left >= 0 else float("-inf")
return max(Ai_minus_1, Bj)
#print(Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]))
print(Solution().findMedianSortedArrays([1,2,3], [4,5,6,7,8,9])) |
cdde76101e71f71436ab7201a9453101b6127bc9 | sasa233/myLeetcode | /search-a-2d-matrix.py | 2,420 | 3.890625 | 4 | '''
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
'''
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
result = False
if matrix == [[]] or matrix == []:
return result
arrayCol = [a[0] for a in matrix]
left, right = self.binarySearch(arrayCol, target)
if left != right and left >= 0 and right <= len(matrix):
left, right = self.binarySearch(matrix[left], target)
if left == right:
result = True
return result
def binarySearch(self, nums, target):
if nums == []:
return 0, 0
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if target < nums[mid]:
right = mid - 1
elif target > nums[mid]:
left = mid + 1
else:
return mid, mid
return left - 1, right + 1
def searchMatrix1(self, matrix, target): # 此方法速度更快,是因为少了两次函数调用么?
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
m, n = len(matrix), len(matrix[0])
# 可对二维数组中所有元素做二分查找,因为从左到右从上到下元素顺序排列
left, right = 0, m * n
while left < right:
mid = left + (right - left) // 2
if matrix[mid // n][mid % n] >= target:
right = mid
else:
left = mid + 1
return left < m * n and matrix[left // n][left % n] == target
#print(Solution().binarySearch([1, 10, 23], 25))
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
print(Solution().searchMatrix(matrix, 50))
print(Solution().searchMatrix1(matrix, 50)) |
21f34d90b397554ace70954070fa42d55e402dfa | Yzoni/leren_2015-2016 | /leren2/schrijven3.py | 3,159 | 3.59375 | 4 | #!/bin/env python3.4
import csv
from enum import Enum
import math
# Enum to identify column index by name
class VarType(Enum):
x1 = 0
x2 = 1
y = 2
# Return the csvfile as a list of lists. A list for every row.
def readFile(csvfilename):
list = []
with open(csvfilename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
next(reader) # Skip first header line
for row in reader:
list.append(row)
return list
# Return from two rows of the datafile
def createdatalists(csvlist, typex1, typex2, typey):
x1 = []
x2 = []
y = []
for entry in csvlist:
x1.append(int(entry[typex1.value]))
x2.append(int(entry[typex2.value]))
y.append(int(entry[typey.value]))
return x1, x2, y
# Execute hypothesis function with t0 and t1
def generatehypopoints(t0, t1, t2, x1, x2):
y = 1 / (1 + math.e **(-(t0 + t1 * x1 + t2 * x2)))
return y
# Returns the cost
def costFunction(t0, t1, t2, listx1, listx2, listy):
totalCost = 0
for x1, x2, y in zip(listx1, listx2, listy):
h0 = generatehypopoints(t0, t1, t2, x1, x2)
totalCost += (math.log(h0) * int(y) + (1 - int(y)) * math.log(1-h0))
listlength = len(listx1)
return -(1 / listlength) * totalCost
# Returns t0 and t1 for one gradient step
def gradient(t0, t1, t2, listx1, listx2, listy, learnrate):
gradt0 = 0
gradt1 = 0
gradt2 = 0
n = len(listx1)
for x1, x2, y in zip(listx1, listx2, listy):
h0 = generatehypopoints(t0, t1, t2, x1, x2)
gradt0 += (1/n) * (h0 - int(y))
gradt1 += (1/n) * (h0 - int(y)) * int(x1)
gradt2 += (1/n) * (h0 - int(y)) * int(x2)
t0 -= (learnrate * gradt0)
t1 -= (learnrate * gradt1)
t2 -= (learnrate * gradt2)
return t0, t1, t2
# Returns t0 and t1 for set iterations and learnrate
def univLinReg(initt0, initt1, initt2, listx1, listx2, listy, iterations, learnrate):
t0 = initt0
t1 = initt1
t2 = initt2
for _ in range(iterations):
t0, t1, t2 = gradient(t0, t1, t2, listx1, listx2, listy, learnrate)
return t0, t1, t2
# Main function with pretty print
def Main(csvfile, typex1, typex2, typey, learnrate, iterations):
print("Learnrate: " + str(learnrate) + "\t Iterations: " + str(iterations))
print("Startvalues: t0=0.5 \t t1=0.5 \t t2=0.5")
csvlist = readFile(csvfile)
listx1, listx2, listy = createdatalists(csvlist, typex1, typex2, typey)
t0, t1, t2 = univLinReg(0.5, 0.5, 0.5, listx1, listx2, listy, iterations, learnrate)
if not math.isnan(t0) or not math.isnan(t1):
print("Finalvalues: t0=" + str(t0) + "\t t1=" + str(t1) + "\t t2=" + str(t2))
print("Startcost: " + str(costFunction(0.5, 0.5, 0.5, listx1, listx2, listy)) + "\t Finalcost: " + str(costFunction(t0, t1, t2, listx1, listx2, listy)))
#print('Url to the plot ' + typex1.x1 + ' vs ' + typey.name + ": " + plot(listx, listy, t0, t1, typex.name, typey.name))
else:
print("t0 or t1 is NaN, try to decrease the learning rate with this dataset")
print("\n")
Main('opdracht3.csv', VarType.x1, VarType.x2, VarType.y, 0.001, 1) |
b332c5e5c54e330ff2b79c644cafab78924f158e | YiwenPang/Python-Code | /测试用解决方案/测试用解决方案/测试用解决方案.py | 1,081 | 3.515625 | 4 | def is_magicsquare(ls):
ls_width=len(ls[0])
s=set()
for i in range(0,ls_width):
for j in range(0,ls_width):
s.add(ls[i][j])
s_width=len(s)
if ls_width**2!=s_width:
return False
else:
answer = set()
for i in range(0,ls_width):
sum=0
for j in range(0,ls_width):
sum+=ls[i][j]
answer.add(sum)
for j in range(0,ls_width):
sum=0
for i in range(0,ls_width):
sum+=ls[i][j]
answer.add(sum)
sum1,sum2=0,0
for i in range(0,ls_width):
sum1+=ls[i][ls_width-1-i]
answer.add(sum1)
for i in range(0,ls_width):
sum2+=ls[i][i]
answer.add(sum2)
if len(answer)==1:
return True
else:
return False
if __name__=='__main__':
n = eval(input())
ls = []
for i in range(n):
ls.append(list(eval(input())))
#print(ls)
if is_magicsquare(ls)==True:
print('Yes')
else:
print('No') |
596529267281c086f4c763d565158516e423abd9 | ankitcs03/Python | /ind.py | 369 | 3.5 | 4 |
# Define an alphabetic indexing tuple.
ind = tuple('abcdefghijklmnopqrstuvwxyz')
typ = ('DVD_FULL_SCREEN','DVD_WIDE_SCREEN','BLU-RAY')
mat = {}
stmt=""
for j, e in enumerate(typ):
mat[str(ind[j])] = typ[j]
if j == len(typ) - 1:
stmt = stmt + ":" + str(ind[j])
else:
stmt = stmt + ":" + str(ind[j]) + ", "
print (stmt)
print ()
print (mat) |
80c382ad5fcdcb2b4f38760c0b3fb02af3737cf5 | ankitcs03/Python | /class.py | 445 | 3.6875 | 4 |
class Test:
def __init__(self, name=None):
print("Initial method has been called")
self.name = name
def say_hi(self):
if self.name:
print("Hello ! " + self.name + " Good Morning. ")
else:
print("Hello ! there, Good Morning")
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
x = Test()
#x.name = "Ankit"
#x.say_hi()
print(x.get_name())
print()
x.set_name("Rahul")
print(x.get_name()) |
92715a493240b5629dc84ae4c219cbe9b89e287e | ankitcs03/Python | /decorator.py | 286 | 3.578125 | 4 |
def our_decorator(func):
def function_wrapper(x):
print("Before calling the function " + func.__name__)
func(x)
print("After calling the function " + func.__name__)
return function_wrapper
@our_decorator
def foo(x):
print("function is called with string " + str(x))
foo(25)
|
4da010af3dc4c4175ee18da9c57a2e7296b7ec9b | kenilpatel/Analysis-of-search-algorithm | /BST.py | 2,482 | 4 | 4 | class node:
def __init__(self,val):
self.key=val
self.right=None
self.left=None
def data(self):
print(self.key)
def add(root,val):
if(val<root.key):
if(root.left==None):
temp=node(val)
root.left=temp
else:
add(root.left,val)
elif(val>root.key):
if(root.right==None):
temp=node(val)
root.right=temp
else:
add(root.right,val)
def bst(root,key,i):
if(root==None):
return -1
elif(root.key==key):
return key
elif(key<root.key):
return bst(root.left,key,i+1)
elif(key>root.key):
return bst(root.right,key,i+1)
def BFS(root):
h = height(root)
for i in range(1, h+1):
printGivenLevel(root, i)
def printGivenLevel(root , level):
if root is None:
return
if level == 1:
print(root.key,end=" ")
elif level > 1 :
printGivenLevel(root.left , level-1)
printGivenLevel(root.right , level-1)
def height(node):
if node is None:
return 0
else :
lheight = height(node.left)
rheight = height(node.right)
if lheight > rheight :
return lheight+1
else:
return rheight+1
def searchtree(root,key,i):
if(root==None):
return -1
elif(root.key==key):
return i
elif(key<root.key):
return searchtree(root.left,key,i+1)
elif(key>root.key):
return searchtree(root.right,key,i+1)
print("Welcome to Binary search tree")
print("Press 1 to run algorithm on inbuilt data")
print("Press 2 to run algorithm from user input")
choice=int(input("enter ur choice:"))
if(choice==1):
data=[23, 57, 42, 36, 84, 66, 33, 46, 51, 31, 65, 52, 12, 89, 55, 83, 8, 99, 87, 27]
print(data)
root=node(data[0])
for i in range(1,len(data)):
add(root,data[i])
print("\nBFS\n")
BFS(root)
key1=83
print("key:",key1)
index1=searchtree(root,key1,0)
if(index1!=-1):
print("\nElement found at level ",index1)
else:
print("\nElement not found")
elif(choice==2):
n=int(input("enter size of data:"))
data=[]
for i in range(0,n):
d=int(input("enter data:"))
data.append(d)
root=node(data[0])
for i in range(1,len(data)):
add(root,data[i])
print("\nBFS\n")
BFS(root)
key1=int(input("enter key:"))
index1=searchtree(root,key1,0)
if(index1!=-1):
print("\nElement found at level ",index1)
else:
print("\nElement not found")
print("\n\nEnd of Binary search tree") |
eecff8d0603298af3c4f90363a039b4437065f75 | NateTheGrate/Fretboard-Memorizer | /src/main.py | 1,119 | 3.546875 | 4 | from note import AltNote, Note
from card import Card
import constants
import util
import random
guitar = util.generateGuitar()
cards = []
for string in guitar:
for note in string:
cards.append(Card(note))
def leveler(card: Card, isRight):
cardLevel = card.getLevel()
if(isRight):
card.setLevel(cardLevel + 1)
elif(cardLevel > 0):
card.setLevel(cardLevel - 1)
# else do nothing because you can't go negative in levels
def fretQuiz():
randCard = random.choice(cards)
print(randCard)
val = input("Enter fret number: ")
userNote = util.fretToNote(guitar, int(val), randCard.getNote().getString())
isRight = randCard.getNote() == userNote
leveler(randCard, isRight)
print("level on card is now", str(randCard.getLevel()))
def noteQuiz():
randNote = util.getRandomNote(guitar)
if(isinstance(randNote, AltNote)):
randNote.switch()
randFret = randNote.getFret()
print(str(randFret) + ", " + randNote.getString() + " string")
val = input("Enter note: ")
print(randNote.note == val)
fretQuiz() |
59cd9b98d34273e0b122c715419209a30650260f | fifabell/Algorithm | /real_/test_.py | 106 | 3.609375 | 4 | t = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
# for k in range(3):
# for i in range(3):
print(t[0]) |
584535e69b9d25a407d577481b2d16fe72715f4e | fifabell/Algorithm | /real_/test08_.py | 1,124 | 3.625 | 4 | T = int(input())
for i in range(T):
deque = input() # R과 D를 저장
ar_size = int(input()) # 배열의 크기를 저장
if deque.count("D") > ar_size: # D의 개수가 ar의 크기보다 많으면 error출력
print("error")
input()
continue
if deque.count("R") % 2 == 0: # R이 짝수이면 최종 값은 reverse를 하지않아도 됨.
final_reverse = False
else: # 홀수면 최종 reverse!
final_reverse = True
direc = 0 # 방향
ar = list(input()[1:-1].split(',')) # 배열 크기가 1이상일 경우 받아온 배열로 list를 만들어 줌
for j in range(len(deque)):
if deque[j] == "R":
if direc == 0 :
direc = -1 # 뒤에 1자리
else :
direc = 0 # 앞에 1자리
else :
ar.pop(direc) # 삭제
if final_reverse == True:
ar.reverse()
#출력함수
print("[", end='')
for i in range(len(ar)):
if i == len(ar) - 1:
print(ar[i], end = '')
else:
print("%s," %(ar[i]), end='')
print("]") |
1ca0d3089cf33131b408c6f11ff4ec813a02f6f4 | chengyin38/python_fundamentals | /Fizz Buzz Lab.py | 2,092 | 4.53125 | 5 | # Databricks notebook source
# MAGIC %md
# MAGIC # Fizz Buzz Lab
# MAGIC
# MAGIC * Write a function called `fizzBuzz` that takes in a number.
# MAGIC * If the number is divisible by 3 print `Fizz`. If the number is divisible by 5 print `Buzz`. If it is divisible by both 3 and 5 print `FizzBuzz` on one line.
# MAGIC * If the number is not divisible by 3 or 5, just print the number.
# MAGIC
# MAGIC HINT: Look at the modulo (`%`) operator.
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def fizzBuzz(i):
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
# COMMAND ----------
# MAGIC %md
# MAGIC This function expects a numeric type. If it receives a different type, it will throw an error.
# MAGIC
# MAGIC * Add a check so that if the input to the function is not numeric (either `float` or `int`) print `Not a number`.
# MAGIC
# MAGIC HINT: Use the `type()` function.
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def typeCheckFizzBuzz(i):
if type(i) == int or type(i) == float:
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
else:
print("Not a number")
# COMMAND ----------
# MAGIC %md But what if the argument passed to the function were a list of values? Write a function that accepts a list of inputs, and applies the function to each element in the list.
# MAGIC
# MAGIC A sample list is provided below to test your function.
# COMMAND ----------
my_list = [1, 1.56, 3, 5, 15, 30, 50, 77, "Hello"]
# COMMAND ----------
# TODO
# COMMAND ----------
# ANSWER
def listFizzBuzz(my_list):
for i in my_list:
if (type(i) == int) or (type(i) == float):
if (i % 5 == 0) and (i % 3 == 0):
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else:
print(i)
else:
print("Not a number")
listFizzBuzz(my_list)
|
faa3bd2bb899f33f45daa9ce54a38f75183459db | dennis1219/baekjoon_code | /if/9498.py | 146 | 3.875 | 4 | a = int(input())
if 90<=a<=100:
print("A")
elif 80<=a<=89:
print("B")
elif 70<=a<=79:
print("C")
elif 60<=a<=69:
print("D")
else:
print("F") |
7cea3bb59ffc5beddadd98aef1857a15ad21acd8 | koichi210/Python | /OfficialTutorial/03_1_3_1_list.py | 342 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# リスト型
param = [1, 2, 4, 8, 16]
introduction = 'my name is python'
# すべての値
print(param)
# 先頭の値
print(param[0])
# 最後の値
print(param[-1])
# 指定Index以降の値
print(param[-3:])
# 要素追加
param.append(32)
print(param[:])
# リストの連結
print(param[:] + [64, 128])
|
10279b24d88b34263fa954797876b26ddb3baeb7 | koichi210/Python | /Pytest/main/counter.py | 575 | 3.6875 | 4 | class Counter:
def __init__(self):
print("init")
self.counter = 0
def Increment(self):
print("inc=", self.counter)
self.counter += 1
return self.counter
def Decrement(self):
print("dec=", self.counter)
self.counter -= 1
return self.counter
def main():
print ( "1. " , Counter().Increment() )
print ( "2. " , Counter().Increment() )
print ( "3. " , Counter().Decrement() )
print ( "4. " , Counter().Decrement() )
print ( "5. " , Counter().Decrement() )
if __name__ == '__main__':
main()
|
8a58f4a0d6625b2f191d0fefdc1e45f06edd8ebe | cc200723/My-way-of-learning | /python project/程序员.py | 2,037 | 3.90625 | 4 | from turtle import *
import math
# 设置画布宽高/背景色和设置画笔粗细/速度/颜色
screensize(600, 500, '#99CCFF')
pensize(5),speed(10),color('red')
# 定义椭圆函数: 绘制蜡烛火焰和被圆柱函数调用
def ellipse(x,y,a,b,angle,steps):
penup(),goto(x,y),forward(a),pendown()
theta = 2*math.pi*angle/360/steps
for i in range(steps):
nextpoint = [x+a*math.cos((i+1)*theta),y+b*math.sin((i+1)*theta)]
setpos(nextpoint)
# 定义圆柱函数: 绘制生日蛋糕和蜡烛柱体
def cylinder(x,y,a,b,angle,steps,height):
ellipse(x,y,a,b,angle,steps)
ellipse(x,y-height,a,-b,angle/2,steps)
penup(),goto(x,y),forward(a),pendown()
right(90),forward(height)
penup(),right(90),forward(2*a),pendown()
right(90),forward(height)
setheading(0)
x = 0; y = 50
# 调用圆柱函数绘制生日蛋糕
cylinder(x,y,200,50,360,90,150)
# 调用圆柱函数绘制4个蜡烛柱体
begin_fill(),cylinder(x+100,y+100,10,5,360,20,70),goto(x+100,y+100),end_fill()
begin_fill(),cylinder(x-50, y+100,10,5,360,20,70),goto(x-50, y+100),end_fill()
begin_fill(),cylinder(x+50, y+80, 10,5,360,20,70),goto(x+50, y+80 ),end_fill()
begin_fill(),cylinder(x-100,y+80, 10,5,360,20,70),goto(x-100,y+80 ),end_fill()
# 调用椭圆函数绘制4个蜡烛火焰
color('yellow')
begin_fill(),ellipse(x+100,y+100+10,5,15,360,20),goto(x+100,y+100+10),end_fill()
begin_fill(),ellipse(x-50, y+100+10,5,15,360,20),goto(x-50, y+100+10),end_fill()
begin_fill(),ellipse(x+50, y+80+10, 5,15,360,20),goto(x+50, y+80+10 ),end_fill()
begin_fill(),ellipse(x-100,y+80+10, 5,15,360,20),goto(x-100,y+80+10 ),end_fill()
# 在生日蛋糕上添加文字'1024'和'程序员节日快乐'
penup(),goto(0,-100),pendown(),
color('yellow')
write('1 0 2 4',move=False,
align='center',
font=('Time New Roman',50,'bold'))
penup(),goto(0,-230),
pendown(),color('red')
write('程序员节日快乐',move=False,
align='center',
font=('黑体',45,'normal'))
hideturtle();mainloop()
|
26eaae35a73bf292aa9a4a2b637eb9dca6a9b11d | aseruneko/diceforge-ai | /src/main/resolve.py | 3,433 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
効果解決用のモジュール
"""
"""
- 後で書く
"""
__author__ = "seruneko"
__date__ = "30 May 2020"
from main.Board import Board
from main.Face import Face
"""
[関数]
resolve_effect(player, effect):
何らかのエフェクトを処理するメソッド。
将来的にどこかに切り出したい。
resolve_face(player, face):
一つのフェイズを処理するメソッド。
将来的にどこかに切り出したい。
"""
def resolve_effect(board, player, effect):
print("> [Player {0}] causes effect [{1}]".format(player.id, effect)) # 開発用のログ
if effect == "roll_2_dices":
for dice in player.dices:
dice.roll()
print("> dice top is {0}".format(dice.top.name))
elif effect == "resolve_2_dices":
for dice in player.dices:
resolve_face(player, dice.top)
elif effect == "buy_face":
board.show_playable_dice_face()
while(True):
chosen_face_number = input("choose number you want to buy (your gold is {0}) (or exit)\n".format(player.resource.gold))
if chosen_face_number == "exit":
return
elif chosen_face_number.isdecimal() == True:
chosen_face_number = int(chosen_face_number)
if 0 <= chosen_face_number and chosen_face_number <= len(board.face_distribution) - 1:
if Face.cost_list[board.face_distribution[chosen_face_number]] in player.dice_cost_list_you_buy_in_action:
print("you've already bought a face in the same cost.")
else:
if player.resource.gold < Face.cost_list[board.face_distribution[chosen_face_number]]:
print("you don't have enough gold.")
else:
break
chosen_face_id = board.face_distribution.pop(chosen_face_number)
all_faces_list = []
all_faces_list.extend(player.dices[0].faces)
all_faces_list.extend(player.dices[1].faces)
for face_index_number , face_number in enumerate(all_faces_list):
print("{0}: {1}".format(face_index_number,str(face_number)))
while(True):
chosen_replace_number = input("choose number you want to discard\n")
if chosen_replace_number.isdecimal() == True:
chosen_replace_number = int(chosen_replace_number)
if 0 <= chosen_replace_number and chosen_replace_number <= len(all_faces_list) - 1:
break
if chosen_replace_number > 5 :
player.dices[1].replace(Face(chosen_face_id),chosen_replace_number-6)
else:
player.dices[0].replace(Face(chosen_face_id),chosen_replace_number)
player.dice_cost_list_you_buy_in_action.append(Face.cost_list[chosen_face_id])
player.resource.substract("gold", Face.cost_list[chosen_face_id])
def resolve_face(player, face):
if face.tag in ["gold", "sun", "moon", "vp"]:
player.resource.add(face.tag, face.val)
# print("> Player {0} yields {1} {2}".format(player.id, face.val, face.tag))
elif face.tag == "+":
for ef in face.val:
player.resource.add(ef["tag"], ef["val"])
# print("> Player {0} yields {1} {2}".format(player.id, ef["val"], ef["tag"])) |
b81f7ec2dd98736d89a62899636f9f2b1abe7025 | greywolf37/my_playground | /merge.py | 2,385 | 3.984375 | 4 | '''
algorithm
introduce a splitting function
introduce merge function
takes two lists
ind_1 and ind_2 as indexes for the two lists (initial at 0)
while both are smaller tahn length
the smaller one is appended to a new list, and that counter in increases
when on index reaches its lenth -1, append and asing it inf
return merged list
split the list
while length of array > 1
initiate empty list
Take length divide by 2 and find number of pairs (if odd inividual append the last element)
loop through the number of pairs
merge and append to empty list
assign empty list to lst
lst = lst[0]
'''
def split(arr):
'''
takes in a list and makes it a list of lists
'''
emt = []
for i in range(len(arr)):
emt.append([arr[i]])
return emt
def merge(arr_1, arr_2):
'''
Merges two lists in accending order
'''
#initializing both indexes and empty list
ind_1 = 0
ind_2 = 0
emt = []
#appending infinity to the list
arr_1.append(float('inf'))
arr_2.append(float('inf'))
while ind_1 < len(arr_1) -1 or ind_2 < len(arr_2) -1:
if arr_1[ind_1] < arr_2[ind_2]:
emt.append(arr_1[ind_1])
ind_1 += 1
else:
emt.append(arr_2[ind_2])
ind_2 += 1
return emt
def merge_sort(lst):
print('The unsorted list is:')
print(lst)
#counter of number of iterations passed
iterations = 0
lst = split(lst)
#when the are still splits in the list
while len(lst) > 1:
print("length", len(lst))
#Initiating an empty list
emt = []
#Iterating through each pair
for i in range((len(lst)//2)):
#appending to empty list
emt.append(merge(lst[2*i],lst[2*i+1]))
iterations += 1
if len(lst)%2 != 0:
emt.append(lst[-1])
lst = emt
lst = lst[0]
print('The list was sorted in ' + str(iterations) + ' iterations' )
print('The sorted list is:')
print(lst)
return lst
def test():
lst = []
n = int(input('Enter number of elements'))
for j in range(n):
if j == n-1:
print('enter the last element')
ele = int(input())
lst.append(ele)
lst = merge_sort(lst)
test()
|
ad50eac801550d2fc0df1580e457b048f06076f7 | angelfaraldo/intro_python_music | /ejercicios/2-02E_text-drum-sequencer.py | 986 | 3.875 | 4 | """
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
EJERCICIO 2 - DÍA 2
======
En este ejercicio te pido que crees un secuenciador de batería
polifónico que convierta secuencias de texto en un patrón de batería.
REGLAS:
- Este ejercicio es una oportunidad para revisar los métodos de listas y cadenas
- Puedes crear tantos instrumentos como desees, pero al menos ha de haber 3:
- Hi hat
- Snare
- Bass Drum
- Puedes combinar los tres instrumentos en una misma cadena de texto, o crear
cadenas de texto separadas para cada instrumento. Por ejemplo:
hihat = "x x x x x x x x x x x x x x x x"
snare = "- - - x - - x - - - - x - - - x"
- Las posibilidades son ilimitadas.
- El output del programa debe ser un patrón de batería con los intrumentos
apropiados, que se repita 4 compases.
- Mi sugerencia es utilizar un 4/4 con subdivisión a CORCHEAS.
"""
|
a85d09e57b7a1e7fdaa8055003c922b494b7e437 | angelfaraldo/intro_python_music | /1-01_crear-y-ejecutar-programas.py | 1,424 | 4.46875 | 4 | """
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
"1-01_crear-y-ejecutar-programas"
contenidos: print(), comentarios, input(), variables, string concatenation
"""
# PRINT y CADENAS
print("hola, chicas y chicos!")
print("")
print('Estamos utilizando la función "print" para imprimir texto en la consola.')
# COMMENTS
# es bueno introducir comentarios para explicar vuestro código, documentar dudas, etc.
# el carácter "\n" es "newline", y crea una línea en blanco después de la cadena.
print("Espero que durante esta semana aprendáis cosas interesantes,\ny que os resulte entretenido.")
# INPUT
# aquí acabamos de concatenar dos strings ("cadenas", en castellano)
input("Hola, Cómo te llamas?")
print("Encantado")
# VARIABLES (almacenamiento)
# convenciones para llamar variables
mi_nombre = input("Hola, Cómo te llamas?")
# concatenación de cadenas
print("Mucho gusto, " + mi_nombre)
# tipos de data: int, float, strings, boolean
type(mi_nombre)
edad = 40
type(edad)
temperatura = 35.7
type(temperatura)
soltero = True
type(soltero)
# type casting
# nos sirve para convertir un tipo en otro
# esto es útil, por ejemplo para imprimir en la consola valores numéricos
edad = str(edad)
print("Hola, me llamo " + edad)
# o con una f-string
print("hola, me llamo {mi_nombre}, y tengo {edad} años.")
|
5cbc0e9ee358b075eca47fe9ee07467bd89bbbc9 | angelfaraldo/intro_python_music | /1-03_timbre.py | 584 | 3.53125 | 4 | """
INTRODUCCIÓN A LA PROGRAMACIÓN EN PYTHON A TRAVÉS DE LA MÚSICA
Ángel Faraldo, del 19 al 23 de julio de 2021
Campus Junior, Universitat Pompeu Fabra
"1-03_aritmetica-y-parametros-del-sonido"
contenidos: intensidad, timbre
"""
from sine_tone import *
# ============================================================
# TIMBRE
# forma de onda
# espectro...
# serie harmónica de la nota ~SOL1
sine_tone(100)
sine_tone(200)
sine_tone(300)
sine_tone(400)
sine_tone(500)
sine_tone(600)
sine_tone(700)
sine_tone(800)
sine_tone(900)
sine_tone(1000)
# ver ejemplo con simple-additive-synth
|
fa1ae280d38126576183aa11dd92a9bffc54f075 | imjs90/Python_Exercises | /Username_Password.py | 403 | 3.78125 | 4 | #create a username and password system for a Email service
name = ['','']
while name[0] != 'iman' or name[1] != "123":
name[0] = input("enter name:")
name[1] = input("enter pass:")
print('Thank you!')
'''
stars = ''
for i in ('*'):
i = ' ' + i
while stars != '**':
stars += i
print(stars)
'''
'''
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
'''
|
6c5346e39123497c12ed7e01cf956fefb2aa456d | NToepke/glowing-spoon | /Python Intro Projects/Gradebook/gradebook.py | 3,102 | 3.78125 | 4 | # gradebook.py
# Nathan Toepke NST9FK
# Display the average of each student's grade.
# Display tthe average for each assignment.
gradebook = [[61, 74, 69, 62, 72, 66, 73, 65, 60, 63, 69, 63, 62, 61, 64],
[73, 80, 78, 76, 76, 79, 75, 73, 76, 74, 77, 79, 76, 78, 72],
[90, 92, 93, 92, 88, 93, 90, 95, 100, 99, 100, 91, 95, 99, 96],
[96, 89, 94, 88, 100, 96, 93, 92, 94, 98, 90, 90, 92, 91, 94],
[76, 76, 82, 78, 82, 76, 84, 82, 80, 82, 76, 86, 82, 84, 78],
[93, 92, 89, 84, 91, 86, 84, 90, 95, 86, 88, 95, 88, 84, 89],
[63, 66, 55, 67, 66, 68, 66, 56, 55, 62, 59, 67, 60, 70, 67],
[86, 92, 93, 88, 90, 90, 91, 94, 90, 86, 93, 89, 94, 94, 92],
[89, 80, 81, 89, 86, 86, 85, 80, 79, 90, 83, 85, 90, 79, 80],
[99, 73, 86, 77, 87, 99, 71, 96, 81, 83, 71, 75, 91, 74, 72]]
# gradebook = [[100, 100, 100, 96],[97, 87, 92, 88],[91, 90, 92, 91]]
# ^ other provided input with given output
number_assignments = len(gradebook[0])
number_students = len(gradebook)
# save number of assignments and students for later use
i = 0 # first iterator for various loops
# first deal with the averages for the students
student_average=0
student_averages=[]
# two variables are used so that the number can be stored in its final form
while (i < number_students ):
# loop through all students and get the sum of all values in their list
student_average = sum(gradebook[i])
i+=1
student_average/=number_assignments
# divide by number of assignments and then save the finalized average to the list
student_averages.append(student_average)
assignment_averages=[]
i=0
# reset iterator and declare the assignment avereages list
while(i < number_assignments):
assignment_averages.append(0)
i+=1
# above loop initializes all instances in the assignment averages list
i=0
# reset iterator and use nested loop to go through all values in the list
while ( i < number_assignments): # start with assignments as thats the number of indices in the average list
j=0 # create iterator for nested loop
while ( j < number_students):
assignment_averages[i] += gradebook[j][i] # index values may seem backwards, but j is tracking the student,
# while i tracks the assignment. Because we want the assignment to be the same on the inside of the nested loop,
# i is the second bracketed number
j+=1 #increase iterator to prevent infinite loop
i+=1 #increase iterator to prevent infinite loop
i=1 #reset iterators to work on following for loops to track which student/ assignment is being printed
j=1
print("Assignment Averages:")
for x in assignment_averages:
x /= number_students #division of assignment averages is done here instead of in a separate loop, mostly for fun
print("Assignment ",j,": %.2f" % x) #print formatting prints out each average with 2 decimal places
j+=1
print("\nStudent Averages:")
for x in student_averages:
print("Student ",i,": %.2f" % x) #print formatting prints out each average with 2 decimal places
i+=1
|
d9a10876de3734ff92d0aa77aff01c8fe5f280f8 | maslyankov/python-small-programs | /F87302_L3_T1.py | 550 | 4.28125 | 4 | # Encrypt a string using Cesar's cipher.
import sys
plain = sys.argv[1]
key = int(sys.argv[2])
translated = ''
for i in plain:
if i.isalpha():
num = ord(i)
num += key
if i.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif i.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += i
print translated
|
90ffafae4bd67ca781bb3022287c9cf0adda7e57 | opi-lab/preliminares-pedroelectronico1995 | /ch01-example1.py | 1,784 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 01 21:12:08 2018
@author: PEDRO NEL MENDOZA
"""
# The module Image of PIL is imported:
from PIL import Image
mod_image = Image.open('data/torres_blancas.jpg') # Read an image
mod_image.show() # Show the image
pil_image = Image.open('data/torres_blancas.jpg').convert('L') # Read an image and convert it to grayscale
pil_image.show() # Show the image in grayscale
# to create a thumbnail with longest side 150 pixels, use the method like this:
pil_image.thumbnail((150,150))
pil_image.show() # Show the thumbnail image
# to rotate the thumbnail image use counterclockwise angles and rotate(), in this case rotate(45):
out = pil_image.rotate(45)
out.show() # Show the thumbnail image rotated 45 degrees.
# Cropping a region from an image is done using the crop() method:
box1 = (100,100,300,300) # Coordinates are (left, upper, right, lower)
region = mod_image.crop(box1) # Crop a region from an image
region = region.transpose(Image.ROTATE_180) # The extracted region is rotated 180 degrees.
mod_image.paste(region,box1) # The region puts back using the paste() method
mod_image.show() # Show the region on the image
im = Image.open('data/perros.jpg').convert('L') # Read an image and convert it to grayscale
box3 = (200,200,400,400) # Coordinates are (left, upper, right, lower)
region3 = im.crop(box3) # Crop a region from an image
region3 = region3.transpose(Image.ROTATE_90) # The extracted region is rotated 90 degrees.
im.paste(region3,box3) # The region puts back using the paste() method
im.show() # Show the region on the image
|
cef9193396d0cf4e87b7bd0e595b1168ffd13e17 | claudewill1/CodingDojo | /python/fundamentals/oop/Ninjas_vs_Pirates/classes/ninjas.py | 828 | 3.546875 | 4 | import random
import math
class Ninja:
def __init__(self,name) -> None:
self.name = name
self.strength = 15
self.speed = 5
self.health = 100
def show_stats(self):
print(f"Name: {self.name}\nStrength: {self.strength}\nSpeed: {self.speed}\nHealth: {self.health}")
def attack(self, pirate):
pirate.health -= self.strength
pirate.defend(self)
return self
def defend(self,pirate):
rng = random.randint(1,2)
if rng == 2:
pirate.health -= math.round(self.strength/2)
print(f"{self.name} defended against {math.pi.name}nHealth: {self.health}\n{pirate.name}\nHealth: {pirate.health}")
else:
print(f"{self.name} Faield to defend against {pirate.name}\n{pirate.health} Health: {pirate.health}") |
c3581471b802aad77a47e9b0bd6ce01b7493d910 | jcwyatt/speedtrap | /speedtrap.py | 1,432 | 4 | 4 | import datetime as dt
#speed trap
def timeValidate(t):
#check the length
if len(t) != 8:
print(t, "invalid length, must be hh:mm:ss")
return False
#check for numbers in the right places
numPosns=(0,1,3,4,6,7)
for i in numPosns:
if not t[i].isnumeric():
print (t,"invalid time format, must be numeric eg 01:04:02.")
return False
#check values are valid times
if int(t[0:2])>23 or int(t[3:5])>59 or int(t[6:8])>59:
print(t,"invalid time. Check values for hours, minutes, seconds.")
return False
#check format has correct separators:
colonPosns=(2,5)
for i in colonPosns:
if t[i]!=":":
print (t, "invalid separator. Must be ':'")
return False
return True
print("Speed Trap Calculator. \nDistance = 1 Mile.")
dist = 1
#input("All times are 6 digit 24hr format, eg:03:44:02\nPress 'Enter' key to continue.")
#t1 = input("Enter time through first gate : (hh:mm:ss) : ")
#t2 = input("Enter time through second gate : (hh:mm:ss) : ")
#print(t2,t1)
s1 = '00:06:00'
s2 = '00:06:08' # for example
#validate the times
valid = timeValidate(s1)
valid = timeValidate(s2)
#convert to timedeltas
t1 = dt.timedelta(hours=int(s1[0:2]),minutes=int(s1[3:5]),seconds=int(s1[6:8]))
t2 = dt.timedelta(hours=int(s2[0:2]),minutes=int(s2[3:5]),seconds=int(s2[6:8]))
elapsedSeconds = (t2-t1).total_seconds()
print('time',elapsedSeconds,'s')
speed = int(1*3600/elapsedSeconds)
print ("Speed =",speed,"mph")
|
42fdc065b4d1a8935e37d3d4abb7a2703916cc77 | suntyneu/test | /test/2个数字比较大小.py | 379 | 3.84375 | 4 | print("请输入2个2位数")
num1 = int(input())
num2 = int(input())
if num1 // 10 > num2 // 10:
print("第一个输入的数字大。")
if num1 // 10 == num2 // 10 and num1 % 10 > num2 % 10:
print("第一个输入的数字大。")
if num1 // 10 == num2 // 10 and num1 % 10 == num2 % 10:
print("两个数字相等。")
else:
print("第二个输入的数字大")
|
78c81da0381174869334638036a3d11d5bb493a0 | suntyneu/test | /test/类Class/6、析构函数.py | 915 | 4.15625 | 4 | """
析构函数:__del__(): 释放对象时候自动调用
"""
class Person(object):
def run(self):
print("run")
def eat(self, food):
print("eat" + food)
def say(self):
print("Hello!my name is %s,I am %d years old" % (self.name, self.age))
def __init__(self, name, age, height, weight): # 可以有其他的参数列表
# print(name, age, height, weight)
self.name = name # self 表示要实例化对象的那个对象
self.age = age
self.height = height
self.weight = weight
def __del__(self):
print("这里是析构函数")
per = Person("tom", 20, 160, 70)
# 释放对象
# del per # 对象释放以后不能再访问
# print(per.age)
# 在函数里定义的对象,会在函数结束时自动释放,用来减少内存空间的浪费
def func():
per2 = Person("aa", 1, 1, 1)
func()
|
6755aead3f29751165fd43e89e2cbc338d6be20b | suntyneu/test | /.idea/8、Checkbutton多选框按钮控件.py | 943 | 3.671875 | 4 | import tkinter
# 创建主窗口
win = tkinter.Tk()
# 创建标题
win.title("sunty")
# 设置大小和位置
win.geometry("400x400+200+20")
def update():
message = ""
if hobby1.get() == True:
message += "money\n"
if hobby2.get() == True:
message += "power\n"
if hobby3.get() == True:
message += "girl"
#清除text中的所有内容
text.delete(0.0, tkinter.END)
text.insert(tkinter.INSERT, message)
text = tkinter.Text(win, width=50, height=10)
text.pack()
# 绑定变量
hobby1 = tkinter.BooleanVar()
check1 = tkinter.Checkbutton(win, text="money", variable=hobby1, command=update)
check1.pack()
hobby2 = tkinter.BooleanVar()
check2 = tkinter.Checkbutton(win, text="power", variable=hobby2, command=update)
check2.pack()
hobby3 = tkinter.BooleanVar()
check3 = tkinter.Checkbutton(win, text="girl", variable=hobby3, command=update)
check3.pack()
# 进入消息循环
win.mainloop() |
650d4aef4badd81c9fa5ca857488a3210ec2c735 | suntyneu/test | /test/类Class/对象属性与类属性/3、运算符重载.py | 417 | 3.96875 | 4 | # 不同的类型用加法会有不同的解释
class Person(object):
# name = "运算符重载"
def __init__(self, num1):
self.num1 = num1
def __add__(self, other):
return Person(self.num1 + other.num1)
def __str__(self):
return "num = " + str(self.num1)
per1 = Person(1)
per2 = Person(2)
print(per1 + per2)
# 等同于
print(per1.__add__(per2))
print(per1)
print(per2)
|
516e25c0109b5f341a09918ad53f0cf929399a1c | suntyneu/test | /test/Tkinter/23、相对布局.py | 476 | 3.59375 | 4 | import tkinter
# 创建主窗口
win = tkinter.Tk()
# 创建标题
win.title("sunty")
# 设置大小和位置
win.geometry("600x400+200+20")
label1 = tkinter.Label(win, text="good", bg="red")
label2 = tkinter.Label(win, text="ok", bg="yellow")
label3 = tkinter.Label(win, text="nice", bg="blue")
# 相对布局 窗体改变对控件有影响
label1.pack(fill=tkinter.Y, side=tkinter.LEFT)
label2.pack(fill=tkinter.Y, side=tkinter.TOP)
# 进入消息循环
win.mainloop()
|
01fad2b064745800f95aed23c0ecfdd00e339d35 | suntyneu/test | /test/while-else语句.py | 250 | 3.875 | 4 | """
while 表达式:
语句1
else:
语句2
逻辑:在条件语句(表达式)为False时,执行else中的的“语句2”
"""
a = 1
while a <= 3:
print("sunck is a good man!")
a += 1
else:
print("very very good!")
|
065abbd254823c5bd5cfdcc7a14a5b66b36441fa | suntyneu/test | /for语句.py | 733 | 4.1875 | 4 | """
for 语句
格式:
for 变量名 in 集合:
语句
逻辑:按顺序取 "集合" 中的每个元素,赋值给 "变量"
在执行语句。如此循环往复,直到取完“集合”中的元素截止。
range([start,]end[,step]) 函数 列表生成器 start 默认为0 step 步长默认为1
功能:生成数列
for i in [1, 2, 3, 4, 5]:
print(i)
"""
a = range(12)
print(a)
for x in range(12):
print(x)
for y in range(2, 20, 2):
print(y)
# enumerate 同时指定下标和元素
for index, m in enumerate([1, 2, 3, 4, 5]): # index, m = 下标,元素
print(index, m)
# for 实现1+2+3+...100的和
sum = 0
for n in range(1, 101):
sum += n
print(sum)
|
634ec7c51e7db7cdc6a46c67478617c4f8d1748c | suntyneu/test | /面向对象/练习.py | 916 | 4.1875 | 4 | """
公路(Road):
属性:公路名称,公路长度
车 (car):
属性:车名,时速
方法:1.求车名在那条公路上以多少时速行驶了都吃,
get_time(self,road)
2.初始化车属性信息__init__方法
3、打印显示车属性信息
"""
class Road(object):
def __init__(self, road_name, road_len):
self.road_name = road_name
self.road_len = road_len
print(self.road_name, self.road_len)
class Car(object):
def __init__(self, car_name, speed):
self.car_name = car_name
self.speed = speed
# print(self.car_name, self.speed)
def __str__(self):
return "%s-%d" % (self.car_name, self.speed)
def get_time(self):
pass
r = Road("泰山路", "2000") # r和road指向同一个地址空间
golf = Car("高尔夫", 50)
print(golf)
#Car.get_time(1000)
Road.road_len
Car.speed
|
7b29da5b17daf339adaeb121a55e425007daa363 | suntyneu/test | /类Class/对象属性与类属性/2、@property.py | 852 | 3.890625 | 4 | class Person(object):
def __init__(self, age):
# self.age = age
# 限制访问
self.__age = age
# per = Person(18)
# print(per.age)
# 属性直接暴露,不安全,没有数据的过滤
# def get_age(self):
# return self.__age
#
# def set_age(self, age):
# if age < 0:
# age = 0
# else:
# self.__age = age
# 使用set和get方法
# 方法名为受限制变得去掉双下划线
@property
def age(self):
return self.__age
@age.setter # 去掉下划线.setter
def age(self, age):
if age < 0:
age = 0
self.__age = age
per = Person(18)
# per.set_age(15)
# print(per.get_age())
per.age = 100 # 相当于调用 set_age
print(per.age) # 相当于调用 get_age
d |
f93465e46e7201df11fcd754cf9bcffeb9fe17f1 | suntyneu/test | /函数/装饰器.py | 2,659 | 4.15625 | 4 | """
装饰器
概念:一个闭包,把一个函数当成参数,返回一个替代版的函数。
本质上就是一个返回函数的函数
"""
def func1():
print("sunck is a good man")
def outer(func):
def inner():
print("*******************")
func()
return inner
# f 是函数func1的加强版本
f = outer(func1)
f()
"""
那么,函数装饰器的工作原理是怎样的呢?假设用 funA() 函数装饰器去装饰 funB() 函数,如下所示:
纯文本复制
#funA 作为装饰器函数
def funA(fn):
#...
fn() # 执行传入的fn参数
#...
return '...'
@funA
def funB():
#...
实际上,上面程序完全等价于下面的程序:
def funA(fn):
#...
fn() # 执行传入的fn参数
#...
return '...'
def funB():
#...
funB = funA(funB)
通过比对以上 2 段程序不难发现,使用函数装饰器 A() 去装饰另一个函数 B(),其底层执行了如下 2 步操作:
将 B 作为参数传给 A() 函数;
将 A() 函数执行完成的返回值反馈回 B。
"""
# funA 作为装饰器函数
def funA(fn):
print("C语言中文网")
fn() # 执行传入的fn参数
print("http://c.biancheng.net")
return "装饰器函数的返回值"
@funA
def funB():
print("学习 Python")
print(funB)
"""
显然,被“@函数”修饰的函数不再是原来的函数,而是被替换成一个新的东西(取决于装饰器的返回值),
即如果装饰器函数的返回值为普通变量,那么被修饰的函数名就变成了变量名;
同样,如果装饰器返回的是一个函数的名称,那么被修饰的函数名依然表示一个函数。
实际上,所谓函数装饰器,就是通过装饰器函数,在不修改原函数的前提下,来对函数的功能进行合理的扩充。
"""
"""
带参数的函数装饰器
在分析 funA() 函数装饰器和 funB() 函数的关系时,细心的读者可能会发现一个问题,
即当 funB() 函数无参数时,可以直接将 funB 作为 funA() 的参数传入。
但是,如果被修饰的函数本身带有参数,那应该如何传值呢?
比较简单的解决方法就是在函数装饰器中嵌套一个函数,该函数带有的参数个数和被装饰器修饰的函数相同。例如:
"""
print("last")
def funA(fn):
# 定义一个嵌套函数
def say(arc):
print("Python教程:", arc)
say(arc)
return fn
@funA
def funB(arc):
print("funB():", arc)
funB("http://c.biancheng.net/python")
|
d1a5fb15360cd089ab69ac5a15ab6a8f3228e662 | ClementRabec/Project-Euler | /Problem 25/1000-digit_Fibonacci_number.py | 166 | 3.6875 | 4 | Fn1 = 1
Fn2 = 1
length = 0
index = 2
digits = 1000
while length < digits:
Fn = Fn1 +Fn2
Fn2 = Fn1
Fn1 = Fn
length = len(str(Fn))
index += 1
print index
|
96bebcfc1ae29d264dc7607edcc6da21d59830fd | AniketGurav/PyTorch-learning | /MorvanZhou/MorvanZhou_2_NeuralNetwork_2_Classification.py | 2,895 | 3.921875 | 4 | """
Title: 莫烦/ 建造第一个神经网络/ Lesson2-区分类型(分类)
Main Author: Morvan Zhou
Editor: Shengjie Xiu
Time: 2019/3/21
Purpose: PyTorch learning
Environment: python3.5.6 pytorch1.0.1 cuda9.0
"""
# 分类问题:类型0和类型1,分别在(2,2)附近和(-2,2)附近
import torch
import matplotlib.pyplot as plt
# 假数据
n_data = torch.ones(100, 2) # 数据的基本形态
x0 = torch.normal(2 * n_data, 1) # 类型0 x data (tensor), shape=(100, 2)
y0 = torch.zeros(100) # 类型0 y data (tensor), shape=(100, )
x1 = torch.normal(-2 * n_data, 1) # 类型1 x data (tensor), shape=(100, 1)
y1 = torch.ones(100) # 类型1 y data (tensor), shape=(100, )
# 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是在合并数据)
# FloatTensor = 32-bit floating 按维数0(行)拼接
x = torch.cat((x0, x1), 0).type(torch.FloatTensor)
y = torch.cat(
(y0, y1), 0).type(
torch.LongTensor) # LongTensor = 64-bit integer
# 画图
#plt.scatter(x.data.numpy(), y.data.numpy())
plt.scatter(x[:, 0], x[:, 1], c=y, s=100, lw=0, cmap='RdYlGn')
plt.show()
# 构建网络
class Net(torch.nn.Module): # 继承 torch 的 Module
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__() # 继承 __init__ 功能
# 定义每层用什么样的形式
self.hidden = torch.nn.Linear(n_feature, n_hidden) # 隐藏层线性输出
self.predict = torch.nn.Linear(n_hidden, n_output) # 输出层线性输出
def forward(self, x): # 这同时也是 Module 中的 forward 功能
# 正向传播输入值, 神经网络分析出输出值
x = torch.relu(self.hidden(x)) # 激励函数(隐藏层的线性值)
x = self.predict(x) # 输出值
return x
net = Net(n_feature=2, n_hidden=10, n_output=2) # 几个类别就几个 output
print(net)
# 训练网络
loss_func = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.005)
for t in range(100):
out = net(x)
loss = loss_func(out, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 接着上面来
if t % 2 == 0:
plt.cla()
prediction = torch.max(torch.softmax(out, 1), 1)[1] #此处softmax可以不做
pred_y = prediction.data.numpy().squeeze()
target_y = y.data.numpy()
plt.scatter(
x.data.numpy()[
:, 0], x.data.numpy()[
:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')
accuracy = sum(pred_y == target_y) / 200. # 预测中有多少和真实值一样
plt.text(
1.5, -4, 'Accuracy=%.2f' %
accuracy, fontdict={
'size': 20, 'color': 'red'})
plt.pause(0.1)
if t % 10 == 0:
print(loss)
plt.ioff() # 停止画图
plt.show()
|
f72939444cd1d81c5330aa59aceda121e1d85c04 | Gangamagadum98/Python-Programs | /revision/insertionSort.py | 294 | 3.796875 | 4 |
def insertion(num, x, pos):
b = []
if pos <= len(num):
for i in range(0, len(num)):
if i == pos:
num[i] = x
else:
b = num
return b
num = [4, 5,1, 3,8]
x=7
pos=3
res = insertion(num, x, pos)
print(res) |
d0808e2744eb995a353a7dc85c55644ccfa00825 | Gangamagadum98/Python-Programs | /revision/array.py | 781 | 3.5 | 4 | from array import *
vals = array('i',[2,6,4,3])
print(vals.buffer_info())
vals.append(9)
print(vals)
vals.reverse()
print(vals)
for i in range(4):
print(vals[i])
for e in vals:
print(e)
value = array('i',[3,2,1,4,5,6,7])
newarr = array(value.typecode,(a*a for a in value))
print(newarr)
arr = array('i',[])
n = int(input("enter length of array"))
for i in range(n):
a = int(input("enter next no"))
arr.append(a)
print(arr)
x = int(input("enter no to search"))
k=0
for i in arr:
if(x==i):
print(k)
break
k+=1
y = array('i',[])
z=int(input("enter length"))
for i in range(z):
x=int(input("enter nxt no"))
y.append(x)
print(y)
d=int(input("enter no to delete"))
for e in y:
if e==d:
continue
else:
print(e)
|
91d973b7cb61b34c9fbc5d2570ca43c0984e6b21 | Gangamagadum98/Python-Programs | /revision/jump.py | 549 | 3.65625 | 4 | import math
def jump(a, num):
n = len(li)
prev = 0
step = math.sqrt(n)
while a[int(min(step, n-1))] < num:
prev = step
step += math.sqrt(n)
if prev >= n:
return -1
while a[int(prev)] < num:
prev += 1
if prev == min(step, n):
return -1
if a[int(prev)] == num:
return prev
return -1
li = [1, 2, 3, 4, 5, 6,7 , 8, 9, 10, 11, 12, 13, 14, 15, 16]
num = 15
index = jump(li, num)
if index == -1:
print("not found")
else:
print(int(index)) |
42213a5ffbb32930905ca90352602b247c5c2b2d | Gangamagadum98/Python-Programs | /prgms/main.py | 464 | 3.59375 | 4 | # import test
# print(__name__)
#If we r executing in the same file than (__name__) vl print as (__main__), but if we r import file from another module
# In that module is(__name__) is present then it vl display the file name not (__main__)
def func():
print("Hello")
print("Hi")
if __name__=="__main__": # if you want to print only this file add this condition, if another file imports this file also it won't display msg from this file
func()
|
d87ea216dac12fd6c38edc1816f8a4b8b75dbba9 | Gangamagadum98/Python-Programs | /prgms/tuple.py | 113 | 3.75 | 4 | t=(1,3,"hi",7.3,"Hello")
print(t[1])
print(t[1:4])
print(t[:3])
print(t*2)
print(t+t)
print(t[0])
print(type(t))
|
82c60df06ae44e6306e3849563c3b195408e7429 | Gangamagadum98/Python-Programs | /prgms/ex.py | 1,009 | 3.734375 | 4 | from array import *
def fact(x):
fact = 1
for i in range(1,x+1):
fact= fact*i
return fact
result = fact(4)
print(result)
def fact(n):
if n == 0:
return 1
return n*fact(n-1)
result1 =fact(4)
print(result1)
def fib(n):
a=0
b=1
if n==1:
return a
else:
print(a)
print(b)
for i in range(2,n):
c=a+b #1
a=b #1
b=c #1
print(c)
fib(4)
arr= array('i',[1,2,3,4])
print(arr)
arr.append(8)
print(arr)
arr.reverse()
print(arr)
arr.insert(2,7)
print(arr)
arr1=array('i',[])
n=int(input("enter the length of array"))
for i in range(n):
x=int(input("enter next element"))
arr1.append(x)
print(arr1)
z=int(input("enter search value"))
for e in arr1:
if e==z:
print(e)
print('index',arr1.index(e))
x=array('i',[3,5,2])
y=array('i',[4,1,6])
z=array('i',[])
for i in range(len(x)):
z.append(x[i]+y[i])
print(z)
|
d8e7380b90c6b5ce1452fd8b6dcfec04ace3aff6 | Gangamagadum98/Python-Programs | /PythonClass/LearningPython.py | 774 | 3.9375 | 4 | name="Ganga"
#print(name)
def learnPython(x):
# print("We are learning python")
# print(x)
return 12
num=learnPython(10)
#print(num)
def add(a,b):
return a+b
num1 =add(5,1)
#print(num1)
def sub(a,b):m1 =mul(5,4)
#print(num1)
def random(*x):
#print("Inside the func")
sum=0
for y in x:
sum=sum+y
return sum
result=random(10,20,30,40,50)
#print(result)
def random(*x):
#print("Inside the func")
sum=0
for y in x:
if y%2==0:
sum=sum+y
return sum
result=random(1,2,4,5,6)
print(result)
def mul(a,b=2):
return a*b
value=mul(4)
print(value)
def divide(a=80,b=2):
return a/b
res=divide(b=40)
print(res)
|
77091f08b893364629e2d7170dbf1aeffe5fab5a | Gangamagadum98/Python-Programs | /sample/Calculator.py | 451 | 4.15625 | 4 | print("Enter the 1st number")
num1=int(input())
print("Enter the 2nd number")
num2=int(input())
print("Enter the Operation")
operation=input()
if operation=="+":
print("the addition of two numbers is",num1+num2)
elif operation == "-":
print("the addition of two numbers is", num1 - num2)
print("the asubstraction of two numbers is", num1 - num2)
print("enter the valid input")
|
6a9bbf06a420871ba02156e8b2edd1f74accf35a | Gangamagadum98/Python-Programs | /PythonClass/BubbleSort.py | 409 | 4.09375 | 4 | def bubbleSort(unsorted_list):
for i in range (0, len(unsorted_list)-1):
for j in range (0, len(unsorted_list)-i-1):
if unsorted_list[j] > unsorted_list[j+1]:
temp = unsorted_list[j]
unsorted_list[j] = unsorted_list[j+1]
unsorted_list[j+1] = temp
print(unsorted_list)
unsorted_list = [5,2,1,9,3,8,0]
bubbleSort(unsorted_list) |
84f0474f6b6a62bb456200998e037c6efbd9c294 | Gangamagadum98/Python-Programs | /prgms/Decorators.py | 353 | 3.65625 | 4 | # Decorators - Add the extra features to the existing functions'
#suppose code is in another functioon , you dont want to change that function that time use decorators
def div(a,b):
print(a/b)
def smart_div(func):
def inner(a,b):
if a<b:
a,b=b,a
return func(a,b)
return inner
div = smart_div(div)
div(2,4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.