print() is a function just like every other function (#1101)

* print() is a function just like every other function
This commit is contained in:
Christian Clauss 2019-08-06 12:14:23 +02:00 committed by Harshil
parent 6654e1ec7d
commit 89acf5d017
13 changed files with 133 additions and 133 deletions

View File

@ -8,25 +8,25 @@ def NewtonRaphson(func, a):
''' Finds root from the point 'a' onwards by Newton-Raphson method '''
while True:
c = Decimal(a) - ( Decimal(eval(func)) / Decimal(eval(str(diff(func)))) )
a = c
# This number dictates the accuracy of the answer
if abs(eval(func)) < 10**-15:
return c
# Let's Execute
if __name__ == '__main__':
# Find root of trigonometric function
# Find value of pi
print ('sin(x) = 0', NewtonRaphson('sin(x)', 2))
print('sin(x) = 0', NewtonRaphson('sin(x)', 2))
# Find root of polynomial
print ('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4))
print('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4))
# Find Square Root of 5
print ('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1))
print('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1))
# Exponential Roots
print ('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0))
print('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0))

View File

@ -41,12 +41,12 @@ def main():
print("4.Quit")
choice = input("What would you like to do?: ")
if choice not in ['1', '2', '3', '4']:
print ("Invalid choice, please enter a valid choice")
print("Invalid choice, please enter a valid choice")
elif choice == '1':
strng = input("Please enter the string to be encrypted: ")
key = int(input("Please enter off-set between 1-94: "))
if key in range(1, 95):
print (encrypt(strng.lower(), key))
print(encrypt(strng.lower(), key))
elif choice == '2':
strng = input("Please enter the string to be decrypted: ")
key = int(input("Please enter off-set between 1-94: "))
@ -57,7 +57,7 @@ def main():
brute_force(strng)
main()
elif choice == '4':
print ("Goodbye.")
print("Goodbye.")
break

View File

@ -71,11 +71,11 @@ def decrypt(message):
def main():
message = "Morse code here"
result = encrypt(message.upper())
print (result)
print(result)
message = result
result = decrypt(message)
print (result)
print(result)
if __name__ == '__main__':

View File

@ -3,7 +3,7 @@
def __encryptPart(messagePart, character2Number):
one, two, three = "", "", ""
tmp = []
for character in messagePart:
tmp.append(character2Number[character])
@ -11,7 +11,7 @@ def __encryptPart(messagePart, character2Number):
one += each[0]
two += each[1]
three += each[2]
return one+two+three
def __decryptPart(messagePart, character2Number):
@ -25,7 +25,7 @@ def __decryptPart(messagePart, character2Number):
tmp += digit
if len(tmp) == len(messagePart):
result.append(tmp)
tmp = ""
tmp = ""
return result[0], result[1], result[2]
@ -48,7 +48,7 @@ def __prepare(message, alphabet):
for letter, number in zip(alphabet, numbers):
character2Number[letter] = number
number2Character[number] = letter
return message, alphabet, character2Number, number2Character
def encryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
@ -57,7 +57,7 @@ def encryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
for i in range(0, len(message)+1, period):
encrypted_numeric += __encryptPart(message[i:i+period], character2Number)
for i in range(0, len(encrypted_numeric), 3):
encrypted += number2Character[encrypted_numeric[i:i+3]]
@ -70,7 +70,7 @@ def decryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
for i in range(0, len(message)+1, period):
a,b,c = __decryptPart(message[i:i+period], character2Number)
for j in range(0, len(a)):
decrypted_numeric.append(a[j]+b[j]+c[j])
@ -83,4 +83,4 @@ if __name__ == '__main__':
msg = "DEFEND THE EAST WALL OF THE CASTLE."
encrypted = encryptMessage(msg,"EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
print ("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted))
print("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted))

View File

@ -122,7 +122,7 @@ class XORCipher(object):
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
@ -188,22 +188,22 @@ class XORCipher(object):
# key = 67
# # test enrcypt
# print crypt.encrypt("hallo welt",key)
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print crypt.decrypt(crypt.encrypt("hallo welt",key), key)
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))
# # test encrypt_string
# print crypt.encrypt_string("hallo welt",key)
# print(crypt.encrypt_string("hallo welt",key))
# # test decrypt_string
# print crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))
# if (crypt.encrypt_file("test.txt",key)):
# print "encrypt successful"
# print("encrypt successful")
# else:
# print "encrypt unsuccessful"
# print("encrypt unsuccessful")
# if (crypt.decrypt_file("encrypt.out",key)):
# print "decrypt successful"
# print("decrypt successful")
# else:
# print "decrypt unsuccessful"
# print("decrypt unsuccessful")

View File

@ -16,14 +16,14 @@ class FenwickTree:
ret += self.ft[i]
i -= i & (-i)
return ret
if __name__ == '__main__':
f = FenwickTree(100)
f.update(1,20)
f.update(4,4)
print (f.query(1))
print (f.query(3))
print (f.query(4))
print(f.query(1))
print(f.query(3))
print(f.query(4))
f.update(2,-5)
print (f.query(1))
print (f.query(3))
print(f.query(1))
print(f.query(3))

View File

@ -2,13 +2,13 @@ from __future__ import print_function
import math
class SegmentTree:
def __init__(self, N):
self.N = N
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
self.flag = [0 for i in range(0,4*N)] # flag for lazy update
def left(self, idx):
return idx*2
@ -34,7 +34,7 @@ class SegmentTree:
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if r < a or l > b:
return True
if l >= a and r <= b :
@ -74,18 +74,18 @@ class SegmentTree:
showList = []
for i in range(1,N+1):
showList += [self.query(1, 1, self.N, i, i)]
print (showList)
print(showList)
if __name__ == '__main__':
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
N = 15
segt = SegmentTree(N)
segt.build(1,1,N,A)
print (segt.query(1,1,N,4,6))
print (segt.query(1,1,N,7,11))
print (segt.query(1,1,N,7,12))
print(segt.query(1,1,N,4,6))
print(segt.query(1,1,N,7,11))
print(segt.query(1,1,N,7,12))
segt.update(1,1,N,1,3,111)
print (segt.query(1,1,N,1,15))
print(segt.query(1,1,N,1,15))
segt.update(1,1,N,7,8,235)
segt.showData()

View File

@ -2,12 +2,12 @@ from __future__ import print_function
import math
class SegmentTree:
def __init__(self, A):
self.N = len(A)
self.st = [0] * (4 * self.N) # approximate the overall size of segment tree with array N
self.build(1, 0, self.N - 1)
def left(self, idx):
return idx * 2
@ -22,10 +22,10 @@ class SegmentTree:
self.build(self.left(idx), l, mid)
self.build(self.right(idx), mid + 1, r)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
def update(self, a, b, val):
return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)
def update_recursive(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
if r < a or l > b:
return True
@ -55,17 +55,17 @@ class SegmentTree:
showList = []
for i in range(1,N+1):
showList += [self.query(i, i)]
print (showList)
print(showList)
if __name__ == '__main__':
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
N = 15
segt = SegmentTree(A)
print (segt.query(4, 6))
print (segt.query(7, 11))
print (segt.query(7, 12))
print(segt.query(4, 6))
print(segt.query(7, 11))
print(segt.query(7, 12))
segt.update(1,3,111)
print (segt.query(1, 15))
print(segt.query(1, 15))
segt.update(7,8,235)
segt.showData()

View File

@ -1,40 +1,40 @@
from __future__ import print_function
# Python code to demonstrate working of
# Python code to demonstrate working of
# extend(), extendleft(), rotate(), reverse()
# importing "collections" for deque operations
import collections
# initializing deque
de = collections.deque([1, 2, 3,])
# using extend() to add numbers to right end
# using extend() to add numbers to right end
# adds 4,5,6 to right end
de.extend([4,5,6])
# printing modified deque
print ("The deque after extending deque at end is : ")
print (de)
# using extendleft() to add numbers to left end
print("The deque after extending deque at end is : ")
print(de)
# using extendleft() to add numbers to left end
# adds 7,8,9 to right end
de.extendleft([7,8,9])
# printing modified deque
print ("The deque after extending deque at beginning is : ")
print (de)
print("The deque after extending deque at beginning is : ")
print(de)
# using rotate() to rotate the deque
# rotates by 3 to left
de.rotate(-3)
# printing modified deque
print ("The deque after rotating deque is : ")
print (de)
print("The deque after rotating deque is : ")
print(de)
# using reverse() to reverse the deque
de.reverse()
# printing modified deque
print ("The deque after reversing deque is : ")
print (de)
print("The deque after reversing deque is : ")
print(de)

View File

@ -1,52 +1,52 @@
'''
The stock span problem is a financial problem where we have a series of n daily
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.
The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
'''
from __future__ import print_function
def calculateSpan(price, S):
n = len(price)
# Create a stack and push index of fist element to it
st = []
st.append(0)
# Span value of first element is always 1
S[0] = 1
# Calculate span values for rest of the elements
for i in range(1, n):
# Pop elements from stack whlie stack is not
# empty and top of stack is smaller than price[i]
while( len(st) > 0 and price[st[0]] <= price[i]):
st.pop()
# If stack becomes empty, then price[i] is greater
# than all elements on left of it, i.e. price[0],
# price[1], ..price[i-1]. Else the price[i] is
# greater than elements after top of stack
S[i] = i+1 if len(st) <= 0 else (i - st[0])
# Push this element to stack
st.append(i)
# A utility function to print elements of array
def printArray(arr, n):
for i in range(0,n):
print (arr[i],end =" ")
# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price)+1)]
# Fill the span values in array S[]
calculateSpan(price, S)
# Print the calculated span values
printArray(S, len(price))
def calculateSpan(price, S):
n = len(price)
# Create a stack and push index of fist element to it
st = []
st.append(0)
# Span value of first element is always 1
S[0] = 1
# Calculate span values for rest of the elements
for i in range(1, n):
# Pop elements from stack whlie stack is not
# empty and top of stack is smaller than price[i]
while( len(st) > 0 and price[st[0]] <= price[i]):
st.pop()
# If stack becomes empty, then price[i] is greater
# than all elements on left of it, i.e. price[0],
# price[1], ..price[i-1]. Else the price[i] is
# greater than elements after top of stack
S[i] = i+1 if len(st) <= 0 else (i - st[0])
# Push this element to stack
st.append(i)
# A utility function to print elements of array
def printArray(arr, n):
for i in range(0,n):
print(arr[i],end =" ")
# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price)+1)]
# Fill the span values in array S[]
calculateSpan(price, S)
# Print the calculated span values
printArray(S, len(price))

View File

@ -9,7 +9,7 @@
# importing all the required libraries
''' Implementing logistic regression for classification problem
''' Implementing logistic regression for classification problem
Helpful resources : 1.Coursera ML course 2.https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac'''
import numpy as np
@ -63,10 +63,10 @@ def logistic_reg(
if step % 10000 == 0:
print(log_likelihood(X,y,weights)) # Print log-likelihood every so often
return weights
if iterations == max_iterations:
print ('Maximum iterations exceeded!')
print ('Minimal cost function J=', J)
print('Maximum iterations exceeded!')
print('Minimal cost function J=', J)
converged = True
return theta
@ -79,7 +79,7 @@ if __name__ == '__main__':
alpha = 0.1
theta = logistic_reg(alpha,X,y,max_iterations=70000,num_steps=30000)
print (theta)
print(theta)
def predict_prob(X):

View File

@ -12,7 +12,7 @@ def QuadraticEquation(a,b,c):
if Delta >= 0:
Solution1 = (-b + math.sqrt(Delta))/(2*a)
Solution2 = (-b - math.sqrt(Delta))/(2*a)
print ("The equation solutions are: ", Solution1," and ", Solution2)
print("The equation solutions are: ", Solution1," and ", Solution2)
else:
"""
Treats cases of Complexes Solutions(i = imaginary unit)
@ -25,7 +25,7 @@ def QuadraticEquation(a,b,c):
print("The equation solutions are: (",b,"+",math.sqrt(-Delta),"*i)/2 and (",b,"+",math.sqrt(-Delta),"*i/",2*a)
if b == 0:
print("The equation solutions are: (",math.sqrt(-Delta),"*i)/2 and ",math.sqrt(-Delta),"*i)/", 2*a)
else:
else:
print("Error. Please, coeficient 'a' must not be zero for quadratic equations.")
def main():
a = 5
@ -33,7 +33,7 @@ def main():
c = 1
QuadraticEquation(a,b,c) # The equation solutions are: -0.2 and -1.0
if __name__ == '__main__':
main()

View File

@ -17,6 +17,6 @@ def FYshuffle(LIST):
if __name__ == '__main__':
integers = [0,1,2,3,4,5,6,7]
strings = ['python', 'says', 'hello', '!']
print ('Fisher-Yates Shuffle:')
print ('List',integers, strings)
print ('FY Shuffle',FYshuffle(integers), FYshuffle(strings))
print('Fisher-Yates Shuffle:')
print('List',integers, strings)
print('FY Shuffle',FYshuffle(integers), FYshuffle(strings))