From 1f0f4b2c92da453a5cb6c9c4325c9893302419dc Mon Sep 17 00:00:00 2001 From: Ankit Dhankhar Date: Fri, 29 Sep 2017 23:15:33 +0530 Subject: [PATCH 01/20] Fixed heading's formatting errors --- sorts/normal_distribution_QuickSort_README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sorts/normal_distribution_QuickSort_README.md b/sorts/normal_distribution_QuickSort_README.md index d56f934cc..635262bfd 100644 --- a/sorts/normal_distribution_QuickSort_README.md +++ b/sorts/normal_distribution_QuickSort_README.md @@ -1,15 +1,15 @@ -#Normal Distribution QuickSort +# Normal Distribution QuickSort Algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution. This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one. -##Array Elements +## Array Elements The array elements are taken from a Standard Normal Distribution , having mean = 0 and standard deviation 1. -####The code +#### The code ```python @@ -52,7 +52,7 @@ The array elements are taken from a Standard Normal Distribution , having mean = -- -##Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort +## Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort ```python >>>import matplotlib.pyplot as plt From 247089decc980b44bed38093c599d79c64c87e78 Mon Sep 17 00:00:00 2001 From: Sayan Bandyopadhyay Date: Thu, 12 Oct 2017 03:28:43 +0530 Subject: [PATCH 02/20] Update minimum_partition.py The loop for finding differences had issues of float being iterated. Has been fixed. --- dynamic_programming/minimum_partition.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic_programming/minimum_partition.py b/dynamic_programming/minimum_partition.py index 25b7621e1..18aa1faa2 100644 --- a/dynamic_programming/minimum_partition.py +++ b/dynamic_programming/minimum_partition.py @@ -20,7 +20,7 @@ def findMin(arr): if (arr[i-1] <= j): dp[i][j] = dp[i][j] or dp[i-1][j-arr[i-1]] - for j in range(s/2, -1, -1): + for j in range(int(s/2), -1, -1): if dp[n][j] == True: diff = s-2*j break; From 80bdfbb9f9f828f39633e6f59deb7559340b4700 Mon Sep 17 00:00:00 2001 From: himangSharatun Date: Sat, 18 Nov 2017 10:34:07 +0700 Subject: [PATCH 03/20] add mean bias deviation in scoring functions --- machine_learning/scoring_functions.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) mode change 100644 => 100755 machine_learning/scoring_functions.py diff --git a/machine_learning/scoring_functions.py b/machine_learning/scoring_functions.py old mode 100644 new mode 100755 index 4204716cd..861d45c1f --- a/machine_learning/scoring_functions.py +++ b/machine_learning/scoring_functions.py @@ -1,4 +1,4 @@ -import numpy +import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. @@ -41,7 +41,7 @@ def rmse(predict, actual): actual = np.array(actual) difference = predict - actual - square_diff = np.square(dfference) + square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score @@ -61,3 +61,18 @@ def rmsle(predict, actual): score = np.sqrt(mean_square_diff) return score + +#Mean Bias Deviation +def mbd(predict, actual): + predict = np.array(predict) + actual = np.array(actual) + + difference = predict - actual + numerator = np.sum(difference) / len(predict) + denumerator = np.sum(actual) / len(predict) + print str(numerator) + print str(denumerator) + + score = float(numerator) / denumerator * 100 + + return score \ No newline at end of file From 50d39561e4748f44840f08dc90eeac9f36ebe2fb Mon Sep 17 00:00:00 2001 From: christianbender Date: Sat, 18 Nov 2017 16:29:34 +0100 Subject: [PATCH 04/20] primelib This python library contains some useful functions to deal with prime numbers and whole numbers. The ideas came by the problems sets from ProjectEuler. --- other/primelib.py | 605 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 605 insertions(+) create mode 100644 other/primelib.py diff --git a/other/primelib.py b/other/primelib.py new file mode 100644 index 000000000..16c44a093 --- /dev/null +++ b/other/primelib.py @@ -0,0 +1,605 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Oct 5 16:44:23 2017 + +@author: Christian Bender + +This python library contains some useful functions to deal with +prime numbers and whole numbers. + +Overview: + +isPrime(number) +sieveEr(N) +getPrimeNumbers(N) +primeFactorization(number) +greatestPrimeFactor(number) +smallestPrimeFactor(number) +getPrime(n) +getPrimesBetween(pNumber1, pNumber2) + +---- + +isEven(number) +isOdd(number) +gcd(number1, number2) // greatest common divisor +kgV(number1, number2) // least common multiple +getDivisors(number) // all divisors of 'number' inclusive 1, number +isPerfectNumber(number) + +NEW-FUNCTIONS + +simplifyFraction(numerator, denominator) +factorial (n) // n! +fib (n) // calculate the n-th fibonacci term. + +----- + +goldbach(number) // Goldbach's assumption + +""" + +def isPrime(number): + """ + input: positive integer 'number' + returns true if 'number' is prime otherwise false. + """ + import math # for function sqrt + + # precondition + assert isinstance(number,int) and (number >= 0) , \ + "'number' must been an int and positive" + + status = True + + # 0 and 1 are none primes. + if number <= 1: + status = False + + for divisor in range(2,int(round(math.sqrt(number)))+1): + + # if 'number' divisible by 'divisor' then sets 'status' + # of false and break up the loop. + if number % divisor == 0: + status = False + break + + # precondition + assert isinstance(status,bool), "'status' must been from type bool" + + return status + +# ------------------------------------------ + +def sieveEr(N): + """ + input: positive integer 'N' > 2 + returns a list of prime numbers from 2 up to N. + + This function implements the algorithm called + sieve of erathostenes. + + """ + + # precondition + assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" + + # beginList: conatins all natural numbers from 2 upt to N + beginList = [x for x in range(2,N+1)] + + ans = [] # this list will be returns. + + # actual sieve of erathostenes + for i in range(len(beginList)): + + for j in range(i+1,len(beginList)): + + if (beginList[i] != 0) and \ + (beginList[j] % beginList[i] == 0): + beginList[j] = 0 + + # filters actual prime numbers. + ans = [x for x in beginList if x != 0] + + # precondition + assert isinstance(ans,list), "'ans' must been from type list" + + return ans + + +# -------------------------------- + +def getPrimeNumbers(N): + """ + input: positive integer 'N' > 2 + returns a list of prime numbers from 2 up to N (inclusive) + This function is more efficient as function 'sieveEr(...)' + """ + + # precondition + assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" + + ans = [] + + # iterates over all numbers between 2 up to N+1 + # if a number is prime then appends to list 'ans' + for number in range(2,N+1): + + if isPrime(number): + + ans.append(number) + + # precondition + assert isinstance(ans,list), "'ans' must been from type list" + + return ans + + +# ----------------------------------------- + +def primeFactorization(number): + """ + input: positive integer 'number' + returns a list of the prime number factors of 'number' + """ + + import math # for function sqrt + + # precondition + assert isinstance(number,int) and number >= 0, \ + "'number' must been an int and >= 0" + + ans = [] # this list will be returns of the function. + + # potential prime number factors. + + factor = 2 + + quotient = number + + + if number == 0 or number == 1: + + ans.append(number) + + # if 'number' not prime then builds the prime factorization of 'number' + elif not isPrime(number): + + while (quotient != 1): + + if isPrime(factor) and (quotient % factor == 0): + ans.append(factor) + quotient /= factor + else: + factor += 1 + + else: + ans.append(number) + + # precondition + assert isinstance(ans,list), "'ans' must been from type list" + + return ans + + +# ----------------------------------------- + +def greatestPrimeFactor(number): + """ + input: positive integer 'number' >= 0 + returns the greatest prime number factor of 'number' + """ + + # precondition + assert isinstance(number,int) and (number >= 0), \ + "'number' bust been an int and >= 0" + + ans = 0 + + # prime factorization of 'number' + primeFactors = primeFactorization(number) + + ans = max(primeFactors) + + # precondition + assert isinstance(ans,int), "'ans' must been from type int" + + return ans + + +# ---------------------------------------------- + + +def smallestPrimeFactor(number): + """ + input: integer 'number' >= 0 + returns the smallest prime number factor of 'number' + """ + + # precondition + assert isinstance(number,int) and (number >= 0), \ + "'number' bust been an int and >= 0" + + ans = 0 + + # prime factorization of 'number' + primeFactors = primeFactorization(number) + + ans = min(primeFactors) + + # precondition + assert isinstance(ans,int), "'ans' must been from type int" + + return ans + + +# ---------------------- + +def isEven(number): + """ + input: integer 'number' + returns true if 'number' is even, otherwise false. + """ + + # precondition + assert isinstance(number, int), "'number' must been an int" + assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" + + return number % 2 == 0 + +# ------------------------ + +def isOdd(number): + """ + input: integer 'number' + returns true if 'number' is odd, otherwise false. + """ + + # precondition + assert isinstance(number, int), "'number' must been an int" + assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" + + return number % 2 != 0 + +# ------------------------ + + +def goldbach(number): + """ + Goldbach's assumption + input: a even positive integer 'number' > 2 + returns a list of two prime numbers whose sum is equal to 'number' + """ + + # precondition + assert isinstance(number,int) and (number > 2) and isEven(number), \ + "'number' must been an int, even and > 2" + + ans = [] # this list will returned + + # creates a list of prime numbers between 2 up to 'number' + primeNumbers = getPrimeNumbers(number) + lenPN = len(primeNumbers) + + # run variable for while-loops. + i = 0 + j = 1 + + # exit variable. for break up the loops + loop = True + + while (i < lenPN and loop): + + j = i+1; + + + while (j < lenPN and loop): + + if primeNumbers[i] + primeNumbers[j] == number: + loop = False + ans.append(primeNumbers[i]) + ans.append(primeNumbers[j]) + + j += 1; + + + i += 1 + + # precondition + assert isinstance(ans,list) and (len(ans) == 2) and \ + (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ + "'ans' must contains two primes. And sum of elements must been eq 'number'" + + return ans + +# ---------------------------------------------- + +def gcd(number1,number2): + """ + Greatest common divisor + input: two positive integer 'number1' and 'number2' + returns the greatest common divisor of 'number1' and 'number2' + """ + + # precondition + assert isinstance(number1,int) and isinstance(number2,int) \ + and (number1 >= 0) and (number2 >= 0), \ + "'number1' and 'number2' must been positive integer." + + rest = 0 + + while number2 != 0: + + rest = number1 % number2 + number1 = number2 + number2 = rest + + # precondition + assert isinstance(number1,int) and (number1 >= 0), \ + "'number' must been from type int and positive" + + return number1 + +# ---------------------------------------------------- + +def kgV(number1, number2): + """ + Least common multiple + input: two positive integer 'number1' and 'number2' + returns the least common multiple of 'number1' and 'number2' + """ + + # precondition + assert isinstance(number1,int) and isinstance(number2,int) \ + and (number1 >= 1) and (number2 >= 1), \ + "'number1' and 'number2' must been positive integer." + + ans = 1 # actual answer that will be return. + + # for kgV (x,1) + if number1 > 1 and number2 > 1: + + # builds the prime factorization of 'number1' and 'number2' + primeFac1 = primeFactorization(number1) + primeFac2 = primeFactorization(number2) + + elif number1 == 1 or number2 == 1: + + primeFac1 = [] + primeFac2 = [] + ans = max(number1,number2) + + count1 = 0 + count2 = 0 + + done = [] # captured numbers int both 'primeFac1' and 'primeFac2' + + # iterates through primeFac1 + for n in primeFac1: + + if n not in done: + + if n in primeFac2: + + count1 = primeFac1.count(n) + count2 = primeFac2.count(n) + + for i in range(max(count1,count2)): + ans *= n + + else: + + count1 = primeFac1.count(n) + + for i in range(count1): + ans *= n + + done.append(n) + + # iterates through primeFac2 + for n in primeFac2: + + if n not in done: + + count2 = primeFac2.count(n) + + for i in range(count2): + ans *= n + + done.append(n) + + # precondition + assert isinstance(ans,int) and (ans >= 0), \ + "'ans' must been from type int and positive" + + return ans + +# ---------------------------------- + +def getPrime(n): + """ + Gets the n-th prime number. + input: positive integer 'n' >= 0 + returns the n-th prime number, beginning at index 0 + """ + + # precondition + assert isinstance(n,int) and (n >= 0), "'number' must been a positive int" + + index = 0 + ans = 2 # this variable holds the answer + + while index < n: + + index += 1 + + ans += 1 # counts to the next number + + # if ans not prime then + # runs to the next prime number. + while not isPrime(ans): + ans += 1 + + # precondition + assert isinstance(ans,int) and isPrime(ans), \ + "'ans' must been a prime number and from type int" + + return ans + +# --------------------------------------------------- + +def getPrimesBetween(pNumber1, pNumber2): + """ + input: prime numbers 'pNumber1' and 'pNumber2' + pNumber1 < pNumber2 + returns a list of all prime numbers between 'pNumber1' (exclusiv) + and 'pNumber2' (exclusiv) + """ + + # precondition + assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \ + "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" + + number = pNumber1 + 1 # jump to the next number + + ans = [] # this list will be returns. + + # if number is not prime then + # fetch the next prime number. + while not isPrime(number): + number += 1 + + while number < pNumber2: + + ans.append(number) + + number += 1 + + # fetch the next prime number. + while not isPrime(number): + number += 1 + + # precondition + assert isinstance(ans,list) and ans[0] != pNumber1 \ + and ans[len(ans)-1] != pNumber2, \ + "'ans' must been a list without the arguments" + + # 'ans' contains not 'pNumber1' and 'pNumber2' ! + return ans + +# ---------------------------------------------------- + +def getDivisors(n): + """ + input: positive integer 'n' >= 1 + returns all divisors of n (inclusive 1 and 'n') + """ + + # precondition + assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1" + + from math import sqrt + + ans = [] # will be returned. + + for divisor in range(1,n+1): + + if n % divisor == 0: + ans.append(divisor) + + + #precondition + assert ans[0] == 1 and ans[len(ans)-1] == n, \ + "Error in function getDivisiors(...)" + + + return ans + + +# ---------------------------------------------------- + + +def isPerfectNumber(number): + """ + input: positive integer 'number' > 1 + returns true if 'number' is a perfect number otherwise false. + """ + + # precondition + assert isinstance(number,int) and (number > 1), \ + "'number' must been an int and >= 1" + + divisors = getDivisors(number) + + # precondition + assert isinstance(divisors,list) and(divisors[0] == 1) and \ + (divisors[len(divisors)-1] == number), \ + "Error in help-function getDivisiors(...)" + + # summed all divisors up to 'number' (exclusive), hence [:-1] + return sum(divisors[:-1]) == number + +# ------------------------------------------------------------ + +def simplifyFraction(numerator, denominator): + """ + input: two integer 'numerator' and 'denominator' + assumes: 'denominator' != 0 + returns: a tuple with simplify numerator and denominator. + """ + + # precondition + assert isinstance(numerator, int) and isinstance(denominator,int) \ + and (denominator != 0), \ + "The arguments must been from type int and 'denominator' != 0" + + # build the greatest common divisor of numerator and denominator. + gcdOfFraction = gcd(abs(numerator), abs(denominator)) + + # precondition + assert isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) \ + and (denominator % gcdOfFraction == 0), \ + "Error in function gcd(...,...)" + + return (numerator // gcdOfFraction, denominator // gcdOfFraction) + +# ----------------------------------------------------------------- + +def factorial(n): + """ + input: positive integer 'n' + returns the factorial of 'n' (n!) + """ + + # precondition + assert isinstance(n,int) and (n >= 0), "'n' must been a int and >= 0" + + ans = 1 # this will be return. + + for factor in range(1,n+1): + ans *= factor + + return ans + +# ------------------------------------------------------------------- + +def fib(n): + """ + input: positive integer 'n' + returns the n-th fibonacci term , indexing by 0 + """ + + # precondition + assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" + + tmp = 0 + fib1 = 1 + ans = 1 # this will be return + + for i in range(n-1): + + tmp = ans + ans += fib1 + fib1 = tmp + + return ans From 567f2adab87baaec6872e28571a9725e6228f7a9 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 14:54:30 +0100 Subject: [PATCH 05/20] Correction: Remove semicolons I have remove the semicolons in line 8 and line 12 --- Project Euler/Problem 01/sol1.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Project Euler/Problem 01/sol1.py b/Project Euler/Problem 01/sol1.py index 512154e29..0c87df75d 100644 --- a/Project Euler/Problem 01/sol1.py +++ b/Project Euler/Problem 01/sol1.py @@ -5,8 +5,8 @@ we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' n = int(raw_input().strip()) -sum=0; +sum=0 for a in range(3,n): if(a%3==0 or a%5==0): sum+=a -print sum; \ No newline at end of file +print sum From a5c954ff6e66404a632c0f663f585363ebfdf006 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 15:06:42 +0100 Subject: [PATCH 06/20] Correction: File solv3.py I have remove some semicolons. line 11, 12 and 42 --- Project Euler/Problem 01/sol3.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Project Euler/Problem 01/sol3.py b/Project Euler/Problem 01/sol3.py index 0caa30a53..5448cb897 100644 --- a/Project Euler/Problem 01/sol3.py +++ b/Project Euler/Problem 01/sol3.py @@ -8,8 +8,8 @@ Find the sum of all the multiples of 3 or 5 below N. This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. ''' n = int(raw_input().strip()) -sum=0; -num=0; +sum=0 +num=0 while(1): num+=3 if(num>=n): @@ -39,4 +39,4 @@ while(1): if(num>=n): break sum+=num -print sum; \ No newline at end of file +print sum From 8d9da8f623141657e2fe69773a5f2a0408806261 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 15:10:09 +0100 Subject: [PATCH 07/20] Correction: File solv01.py I have remove some semicolons. --- Project Euler/Problem 02/sol1.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Project Euler/Problem 02/sol1.py b/Project Euler/Problem 02/sol1.py index 6cf520767..065af1ebd 100644 --- a/Project Euler/Problem 02/sol1.py +++ b/Project Euler/Problem 02/sol1.py @@ -8,11 +8,13 @@ e.g. for n=10, we have {2,8}, sum is 10. ''' n = int(raw_input().strip()) -i=1; j=2; sum=0 +i=1 +j=2 +sum=0 while(j<=n): if((j&1)==0): #can also use (j%2==0) sum+=j temp=i i=j j=temp+i -print sum \ No newline at end of file +print sum From 01f48e708d4f1b093b02818510dc2ab58154382a Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 15:13:50 +0100 Subject: [PATCH 08/20] Correction: File solv01.py Identifier 'max' changed in 'maxNumber' , since 'max' is a function. --- Project Euler/Problem 03/sol1.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Project Euler/Problem 03/sol1.py b/Project Euler/Problem 03/sol1.py index bd3e237e7..23ab8746a 100644 --- a/Project Euler/Problem 03/sol1.py +++ b/Project Euler/Problem 03/sol1.py @@ -17,7 +17,7 @@ def isprime(no): return False return True -max=0 +maxNumber = 0 n=int(input()) if(isprime(n)): print n @@ -31,8 +31,8 @@ else: for i in range(3,n1,2): if(n%i==0): if(isprime(n/i)): - max=n/i + maxNumber = n/i break elif(isprime(i)): - max=i - print max + maxNumber = i + print maxNumber From c787a22d932f8506792bb46057930aaa4e73f2f8 Mon Sep 17 00:00:00 2001 From: Thejus-Paul Date: Mon, 20 Nov 2017 01:34:21 +0530 Subject: [PATCH 09/20] Problem 16 Added Solution to the Problem 16 has been added. --- Project Euler/Problem 16/sol1.py | 15 +++++++++++++++ Project Euler/README.md | 3 +++ 2 files changed, 18 insertions(+) create mode 100644 Project Euler/Problem 16/sol1.py diff --git a/Project Euler/Problem 16/sol1.py b/Project Euler/Problem 16/sol1.py new file mode 100644 index 000000000..05c7916bd --- /dev/null +++ b/Project Euler/Problem 16/sol1.py @@ -0,0 +1,15 @@ +power = int(input("Enter the power of 2: ")) +num = 2**power + +string_num = str(num) + +list_num = list(string_num) + +sum_of_num = 0 + +print("2 ^",power,"=",num) + +for i in list_num: + sum_of_num += int(i) + +print("Sum of the digits are:",sum_of_num) diff --git a/Project Euler/README.md b/Project Euler/README.md index 5d7238e40..c9dc2b468 100644 --- a/Project Euler/README.md +++ b/Project Euler/README.md @@ -49,3 +49,6 @@ PROBLEMS: Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 Which starting number, under one million, produces the longest chain? + +16. 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. + What is the sum of the digits of the number 2^1000? From abe0f29b8be567d99f01cec362dafa301219e5a0 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 22:01:31 +0100 Subject: [PATCH 10/20] Problem 29 -- Project Euler On this solution I used a 'set' data structure, since more efficient. --- main.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 main.py diff --git a/main.py b/main.py new file mode 100644 index 000000000..9d6148da3 --- /dev/null +++ b/main.py @@ -0,0 +1,34 @@ +def main(): + """ + Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: + + 22=4, 23=8, 24=16, 25=32 + 32=9, 33=27, 34=81, 35=243 + 42=16, 43=64, 44=256, 45=1024 + 52=25, 53=125, 54=625, 55=3125 + If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: + + 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 + + How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? + """ + + collectPowers = set() + + currentPow = 0 + + N = 101 # maximum limit + + for a in range(2,N): + + for b in range (2,N): + + currentPow = a**b # calculates the current power + collectPowers.add(currentPow) # adds the result to the set + + + print "Number of terms ", len(collectPowers) + + +if __name__ == '__main__': + main() From 01ae338b75a92b37d9463c12640e1cdf11a8034f Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 22:02:06 +0100 Subject: [PATCH 11/20] Delete main.py --- main.py | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 main.py diff --git a/main.py b/main.py deleted file mode 100644 index 9d6148da3..000000000 --- a/main.py +++ /dev/null @@ -1,34 +0,0 @@ -def main(): - """ - Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: - - 22=4, 23=8, 24=16, 25=32 - 32=9, 33=27, 34=81, 35=243 - 42=16, 43=64, 44=256, 45=1024 - 52=25, 53=125, 54=625, 55=3125 - If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: - - 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 - - How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? - """ - - collectPowers = set() - - currentPow = 0 - - N = 101 # maximum limit - - for a in range(2,N): - - for b in range (2,N): - - currentPow = a**b # calculates the current power - collectPowers.add(currentPow) # adds the result to the set - - - print "Number of terms ", len(collectPowers) - - -if __name__ == '__main__': - main() From 31ebde6e17c2d4b996701779eeb9bc05837834fa Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 19 Nov 2017 22:03:30 +0100 Subject: [PATCH 12/20] Problem 29 On this solution I used a 'set' data structure, since more efficient. --- Project Euler/Problem 29/solution.py | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Project Euler/Problem 29/solution.py diff --git a/Project Euler/Problem 29/solution.py b/Project Euler/Problem 29/solution.py new file mode 100644 index 000000000..9d6148da3 --- /dev/null +++ b/Project Euler/Problem 29/solution.py @@ -0,0 +1,34 @@ +def main(): + """ + Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: + + 22=4, 23=8, 24=16, 25=32 + 32=9, 33=27, 34=81, 35=243 + 42=16, 43=64, 44=256, 45=1024 + 52=25, 53=125, 54=625, 55=3125 + If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: + + 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 + + How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? + """ + + collectPowers = set() + + currentPow = 0 + + N = 101 # maximum limit + + for a in range(2,N): + + for b in range (2,N): + + currentPow = a**b # calculates the current power + collectPowers.add(currentPow) # adds the result to the set + + + print "Number of terms ", len(collectPowers) + + +if __name__ == '__main__': + main() From 69f009e0a58945e74a7e051a34052c84ecbb96c9 Mon Sep 17 00:00:00 2001 From: Erdenezul Date: Tue, 21 Nov 2017 15:28:55 +0800 Subject: [PATCH 13/20] add abbrevation solution to dp --- dynamic_programming/abbreviation.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 dynamic_programming/abbreviation.py diff --git a/dynamic_programming/abbreviation.py b/dynamic_programming/abbreviation.py new file mode 100644 index 000000000..44a168980 --- /dev/null +++ b/dynamic_programming/abbreviation.py @@ -0,0 +1,29 @@ +""" +https://www.hackerrank.com/challenges/abbr/problem +You can perform the following operation on some string, : + +1. Capitalize zero or more of 's lowercase letters at some index i + (i.e., make them uppercase). +2. Delete all of the remaining lowercase letters in . + +Example: +a=daBcd and b="ABC" +daBcd -> capitalize a and c(dABCd) -> remove d (ABC) +""" +def abbr(a, b): + n = len(a) + m = len(b) + dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] + dp[0][0] = True + for i in range(n): + for j in range(m + 1): + if dp[i][j]: + if j < m and a[i].upper() == b[j]: + dp[i + 1][j + 1] = True + if a[i].islower(): + dp[i + 1][j] = True + return dp[n][m] + + +if __name__ == "__main__": + print abbr("daBcd", "ABC") # expect True From f920e2a80959eb982e1695cd48ae2da6e1f85f85 Mon Sep 17 00:00:00 2001 From: nautiyaldeepak Date: Tue, 21 Nov 2017 22:04:04 +0530 Subject: [PATCH 14/20] ftp client server connection --- File_Transfer_Protocol/ftp_client_server.py | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 File_Transfer_Protocol/ftp_client_server.py diff --git a/File_Transfer_Protocol/ftp_client_server.py b/File_Transfer_Protocol/ftp_client_server.py new file mode 100644 index 000000000..ff7a8ec2e --- /dev/null +++ b/File_Transfer_Protocol/ftp_client_server.py @@ -0,0 +1,58 @@ +# server + +import socket # Import socket module + +port = 60000 # Reserve a port for your service. +s = socket.socket() # Create a socket object +host = socket.gethostname() # Get local machine name +s.bind((host, port)) # Bind to the port +s.listen(5) # Now wait for client connection. + +print 'Server listening....' + +while True: + conn, addr = s.accept() # Establish connection with client. + print 'Got connection from', addr + data = conn.recv(1024) + print('Server received', repr(data)) + + filename='mytext.txt' + f = open(filename,'rb') + l = f.read(1024) + while (l): + conn.send(l) + print('Sent ',repr(l)) + l = f.read(1024) + f.close() + + print('Done sending') + conn.send('Thank you for connecting') + conn.close() + + +# client side server + +import socket # Import socket module + +s = socket.socket() # Create a socket object +host = socket.gethostname() # Get local machine name +port = 60000 # Reserve a port for your service. + +s.connect((host, port)) +s.send("Hello server!") + +with open('received_file', 'wb') as f: + print 'file opened' + while True: + print('receiving data...') + data = s.recv(1024) + print('data=%s', (data)) + if not data: + break + # write data to a file + f.write(data) + +f.close() +print('Successfully get the file') +s.close() +print('connection closed') \ No newline at end of file From bc53e2e618d9e99ced19841835282874de510150 Mon Sep 17 00:00:00 2001 From: cclauss Date: Sat, 25 Nov 2017 00:06:39 +0100 Subject: [PATCH 15/20] import numpy as np Lines like 19, 20, 29, 30, etc. use np but it is never defined. --- machine_learning/scoring_functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/scoring_functions.py b/machine_learning/scoring_functions.py index 4204716cd..64806a096 100644 --- a/machine_learning/scoring_functions.py +++ b/machine_learning/scoring_functions.py @@ -1,4 +1,4 @@ -import numpy +import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. From 033744155c5f26fda1fd09746b4ccc019980a232 Mon Sep 17 00:00:00 2001 From: Thejus-Paul Date: Mon, 27 Nov 2017 10:44:32 +0530 Subject: [PATCH 16/20] Added Solution Added Solution for Problem 20 --- Project Euler/Problem 20/sol1.py | 27 +++++++++++++++++++++++++++ Project Euler/README.md | 4 ++++ 2 files changed, 31 insertions(+) create mode 100644 Project Euler/Problem 20/sol1.py diff --git a/Project Euler/Problem 20/sol1.py b/Project Euler/Problem 20/sol1.py new file mode 100644 index 000000000..73e41d5cc --- /dev/null +++ b/Project Euler/Problem 20/sol1.py @@ -0,0 +1,27 @@ +# Finding the factorial. +def factorial(n): + fact = 1 + for i in range(1,n+1): + fact *= i + return fact + +# Spliting the digits and adding it. +def split_and_add(number): + sum_of_digits = 0 + while(number>0): + last_digit = number % 10 + sum_of_digits += last_digit + number = int(number/10) # Removing the last_digit from the given number. + return sum_of_digits + +# Taking the user input. +number = int(input("Enter the Number: ")) + +# Assigning the factorial from the factorial function. +factorial = factorial(number) + +# Spliting and adding the factorial into answer. +answer = split_and_add(factorial) + +# Printing the answer. +print(answer) diff --git a/Project Euler/README.md b/Project Euler/README.md index c9dc2b468..9f77f719f 100644 --- a/Project Euler/README.md +++ b/Project Euler/README.md @@ -52,3 +52,7 @@ PROBLEMS: 16. 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? +20. n! means n × (n − 1) × ... × 3 × 2 × 1 + For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, + and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. + Find the sum of the digits in the number 100! From d7a94a1135aab6dca5577c6040bece579f326fa2 Mon Sep 17 00:00:00 2001 From: RiptideBo <245885195@qq.com> Date: Tue, 28 Nov 2017 14:23:59 +0800 Subject: [PATCH 17/20] add a framework of bp neural network and delete the old one --- Neural_Network/bpnn.py | 190 ++++++++++++++++++++++++++++ Neural_Network/neuralnetwork_bp3.py | 152 ---------------------- 2 files changed, 190 insertions(+), 152 deletions(-) create mode 100644 Neural_Network/bpnn.py delete mode 100644 Neural_Network/neuralnetwork_bp3.py diff --git a/Neural_Network/bpnn.py b/Neural_Network/bpnn.py new file mode 100644 index 000000000..ed5d4c8cb --- /dev/null +++ b/Neural_Network/bpnn.py @@ -0,0 +1,190 @@ +''' + +A Framework of Back Propagation Neural Network(BP) model + +Easy to use: + * add many layers as you want !!! + * clearly see how the loss decreasing +Easy to expand: + * more activation functions + * more loss functions + * more optimization method + +Author: Stephen Lee +Github : https://github.com/RiptideBo +Date: 2017.11.23 + +''' + +import numpy as np +import matplotlib.pyplot as plt + + +def sigmoid(x): + return 1 / (1 + np.exp(-1 * x)) + +class DenseLayer(): + ''' + Layers of BP neural network + ''' + def __init__(self,units,activation=None,learning_rate=None,is_input_layer=False): + ''' + common connected layer of bp network + :param units: numbers of neural units + :param activation: activation function + :param learning_rate: learning rate for paras + :param is_input_layer: whether it is input layer or not + ''' + self.units = units + self.weight = None + self.bias = None + self.activation = activation + if learning_rate is None: + learning_rate = 0.3 + self.learn_rate = learning_rate + self.is_input_layer = is_input_layer + + def initializer(self,back_units): + self.weight = np.asmatrix(np.random.normal(0,0.5,(self.units,back_units))) + self.bias = np.asmatrix(np.random.normal(0,0.5,self.units)).T + if self.activation is None: + self.activation = sigmoid + + def cal_gradient(self): + if self.activation == sigmoid: + gradient_mat = np.dot(self.output ,(1- self.output).T) + gradient_activation = np.diag(np.diag(gradient_mat)) + else: + gradient_activation = 1 + return gradient_activation + + def forward_propagation(self,xdata): + self.xdata = xdata + if self.is_input_layer: + # input layer + self.wx_plus_b = xdata + self.output = xdata + return xdata + else: + self.wx_plus_b = np.dot(self.weight,self.xdata) - self.bias + self.output = self.activation(self.wx_plus_b) + return self.output + + def back_propagation(self,gradient): + + gradient_activation = self.cal_gradient() # i * i 维 + gradient = np.asmatrix(np.dot(gradient.T,gradient_activation)) + + self._gradient_weight = np.asmatrix(self.xdata) + self._gradient_bias = -1 + self._gradient_x = self.weight + + self.gradient_weight = np.dot(gradient.T,self._gradient_weight.T) + self.gradient_bias = gradient * self._gradient_bias + self.gradient = np.dot(gradient,self._gradient_x).T + # ----------------------upgrade + # -----------the Negative gradient direction -------- + self.weight = self.weight - self.learn_rate * self.gradient_weight + self.bias = self.bias - self.learn_rate * self.gradient_bias.T + + return self.gradient + + +class BPNN(): + ''' + Back Propagation Neural Network model + ''' + def __init__(self): + self.layers = [] + self.train_mse = [] + self.fig_loss = plt.figure() + self.ax_loss = self.fig_loss.add_subplot(1,1,1) + + def add_layer(self,layer): + self.layers.append(layer) + + def build(self): + for i,layer in enumerate(self.layers[:]): + if i < 1: + layer.is_input_layer = True + else: + layer.initializer(self.layers[i-1].units) + + def summary(self): + for i,layer in enumerate(self.layers[:]): + print('------- layer %d -------'%i) + print('weight.shape ',np.shape(layer.weight)) + print('bias.shape ',np.shape(layer.bias)) + + def train(self,xdata,ydata,train_round,accuracy): + self.train_round = train_round + self.accuracy = accuracy + + self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) + + x_shape = np.shape(xdata) + for round_i in range(train_round): + all_loss = 0 + for row in range(x_shape[0]): + _xdata = np.asmatrix(xdata[row,:]).T + _ydata = np.asmatrix(ydata[row,:]).T + + # forward propagation + for layer in self.layers: + _xdata = layer.forward_propagation(_xdata) + + loss, gradient = self.cal_loss(_ydata, _xdata) + all_loss = all_loss + loss + + # back propagation + # the input_layer does not upgrade + for layer in self.layers[:0:-1]: + gradient = layer.back_propagation(gradient) + + mse = all_loss/x_shape[0] + self.train_mse.append(mse) + + self.plot_loss() + + if mse < self.accuracy: + print('----达到精度----') + return mse + + def cal_loss(self,ydata,ydata_): + self.loss = np.sum(np.power((ydata - ydata_),2)) + self.loss_gradient = 2 * (ydata_ - ydata) + # vector (shape is the same as _ydata.shape) + return self.loss,self.loss_gradient + + def plot_loss(self): + if self.ax_loss.lines: + self.ax_loss.lines.remove(self.ax_loss.lines[0]) + self.ax_loss.plot(self.train_mse, 'r-') + plt.ion() + plt.show() + plt.pause(0.1) + + + + +def example(): + + x = np.random.randn(10,10) + y = np.asarray([[0.8,0.4],[0.4,0.3],[0.34,0.45],[0.67,0.32], + [0.88,0.67],[0.78,0.77],[0.55,0.66],[0.55,0.43],[0.54,0.1], + [0.1,0.5]]) + + model = BPNN() + model.add_layer(DenseLayer(10)) + model.add_layer(DenseLayer(20)) + model.add_layer(DenseLayer(30)) + model.add_layer(DenseLayer(2)) + + model.build() + + model.summary() + + model.train(xdata=x,ydata=y,train_round=100,accuracy=0.01) + +if __name__ == '__main__': + example() diff --git a/Neural_Network/neuralnetwork_bp3.py b/Neural_Network/neuralnetwork_bp3.py deleted file mode 100644 index 896411a5d..000000000 --- a/Neural_Network/neuralnetwork_bp3.py +++ /dev/null @@ -1,152 +0,0 @@ -#-*- coding:utf-8 -*- -''' -Author: Stephen Lee -Date: 2017.9.21 - -BP neural network with three layers -''' - -import numpy as np -import matplotlib.pyplot as plt - -class Bpnn(): - - def __init__(self,n_layer1,n_layer2,n_layer3,rate_w=0.3,rate_t=0.3): - ''' - :param n_layer1: number of input layer - :param n_layer2: number of hiden layer - :param n_layer3: number of output layer - :param rate_w: rate of weight learning - :param rate_t: rate of threshold learning - ''' - self.num1 = n_layer1 - self.num2 = n_layer2 - self.num3 = n_layer3 - self.rate_weight = rate_w - self.rate_thre = rate_t - self.thre2 = -2*np.random.rand(self.num2)+1 - self.thre3 = -2*np.random.rand(self.num3)+1 - self.vji = np.mat(-2*np.random.rand(self.num2, self.num1)+1) - self.wkj = np.mat(-2*np.random.rand(self.num3, self.num2)+1) - - def sig(self,x): - return 1 / (1 + np.exp(-1*x)) - - def sig_plain(self,x): - return 1 / (1 + np.exp(-1*x)) - - def do_round(self,x): - return round(x, 3) - - def trian(self,patterns,data_train, data_teach, n_repeat, error_accuracy, draw_e=False): - ''' - :param patterns: the number of patterns - :param data_train: training data x; numpy.ndarray - :param data_teach: training data y; numpy.ndarray - :param n_repeat: echoes - :param error_accuracy: error accuracy - :return: None - ''' - data_train = np.asarray(data_train) - data_teach = np.asarray(data_teach) - # print('-------------------Start Training-------------------------') - # print(' - - Shape: Train_Data ',np.shape(data_train)) - # print(' - - Shape: Teach_Data ',np.shape(data_teach)) - rp = 0 - all_mse = [] - mse = 10000 - while rp < n_repeat and mse >= error_accuracy: - alle = 0 - final_out = [] - for g in range(np.shape(data_train)[0]): - net_i = data_train[g] - out1 = net_i - - net_j = out1 * self.vji.T - self.thre2 - out2=self.sig(net_j) - - net_k = out2 * self.wkj.T - self.thre3 - out3 = self.sig(net_k) - - # learning process - pd_k_all = np.multiply(np.multiply(out3,(1 - out3)),(data_teach[g]-out3)) - pd_j_all = np.multiply(pd_k_all * self.wkj,np.multiply(out2,1-out2)) - #upgrade weight - self.wkj = self.wkj + pd_k_all.T * out2 *self.rate_weight - self.vji = self.vji + pd_j_all.T * out1 * self.rate_weight - #upgrade threshold - self.thre3 = self.thre3 - pd_k_all * self.rate_thre - self.thre2 = self.thre2 - pd_j_all * self.rate_thre - #calculate sum of error - errors = np.sum(abs((data_teach[g] - out3))) - - alle = alle + errors - final_out.extend(out3.getA().tolist()) - final_out3 = [list(map(self.do_round,each)) for each in final_out] - - rp = rp + 1 - mse = alle/patterns - all_mse.append(mse) - def draw_error(): - yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] - plt.plot(all_mse, '+-') - plt.plot(yplot, 'r--') - plt.xlabel('Learning Times') - plt.ylabel('All_mse') - plt.grid(True,alpha = 0.7) - plt.show() - # print('------------------Training Complished---------------------') - # print(' - - Training epoch: ', rp, ' - - Mse: %.6f'%mse) - # print(' - - Last Output: ', final_out3) - if draw_e: - draw_error() - - def predict(self,data_test): - ''' - :param data_test: data test, numpy.ndarray - :return: predict output data - ''' - data_test = np.asarray(data_test) - produce_out = [] - # print('-------------------Start Testing-------------------------') - # print(' - - Shape: Test_Data ',np.shape(data_test)) - # print(np.shape(data_test)) - for g in range(np.shape(data_test)[0]): - - net_i = data_test[g] - out1 = net_i - - net_j = out1 * self.vji.T - self.thre2 - out2 = self.sig(net_j) - - net_k = out2 * self.wkj.T - self.thre3 - out3 = self.sig(net_k) - produce_out.extend(out3.getA().tolist()) - res = [list(map(self.do_round,each)) for each in produce_out] - return np.asarray(res) - - -def main(): - #example data - data_x = [[1,2,3,4], - [5,6,7,8], - [2,2,3,4], - [7,7,8,8]] - data_y = [[1,0,0,0], - [0,1,0,0], - [0,0,1,0], - [0,0,0,1]] - - test_x = [[1,2,3,4], - [3,2,3,4]] - - #building network model - model = Bpnn(4,10,4) - #training the model - model.trian(patterns=4,data_train=data_x,data_teach=data_y, - n_repeat=100,error_accuracy=0.1,draw_e=True) - #predicting data - model.predict(test_x) - -if __name__ == '__main__': - main() From f069c20715ed5a33a6610c3068eb46a952fa7e06 Mon Sep 17 00:00:00 2001 From: Richie Bendall Date: Wed, 29 Nov 2017 21:02:02 +1300 Subject: [PATCH 18/20] Easier Solution To Problem 7 --- Project Euler/Problem 07/sol2.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Project Euler/Problem 07/sol2.py diff --git a/Project Euler/Problem 07/sol2.py b/Project Euler/Problem 07/sol2.py new file mode 100644 index 000000000..fdf39cbc4 --- /dev/null +++ b/Project Euler/Problem 07/sol2.py @@ -0,0 +1,16 @@ +# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the Nth prime number? +def isprime(number): + for i in range(2,int(number**0.5)+1): + if number%i==0: + return False + return True +n = int(input('Enter The N\'th Prime Number You Want To Get: ')) # Ask For The N'th Prime Number Wanted +primes = [] +num = 2 +while len(primes) < n: + if isprime(num): + primes.append(num) + num += 1 + else: + num += 1 +print(primes[len(primes) - 1]) From 0330d8896b3350f157eb717ee0505ea93245e4a4 Mon Sep 17 00:00:00 2001 From: PiyushPawar17 Date: Fri, 1 Dec 2017 18:57:53 +0530 Subject: [PATCH 19/20] Added Modular Exponential --- Maths/ModularExponential.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Maths/ModularExponential.py diff --git a/Maths/ModularExponential.py b/Maths/ModularExponential.py new file mode 100644 index 000000000..b3f4c00bd --- /dev/null +++ b/Maths/ModularExponential.py @@ -0,0 +1,20 @@ +def modularExponential(base, power, mod): + if power < 0: + return -1 + base %= mod + result = 1 + + while power > 0: + if power & 1: + result = (result * base) % mod + power = power >> 1 + base = (base * base) % mod + return result + + +def main(): + print(modularExponential(3, 200, 13)) + + +if __name__ == '__main__': + main() From a81084c58608ac4b0888bdcd57725e8394ed043f Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Sun, 3 Dec 2017 15:39:13 +0100 Subject: [PATCH 20/20] Refactoring solv1.py Little embellishment of the code. I put some comments and put readable identifiers. I documented the code. --- Project Euler/Problem 04/sol1.py | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/Project Euler/Problem 04/sol1.py b/Project Euler/Problem 04/sol1.py index f8ed832d8..247de2557 100644 --- a/Project Euler/Problem 04/sol1.py +++ b/Project Euler/Problem 04/sol1.py @@ -3,13 +3,26 @@ Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers which is less than N. ''' -n=int(input()) -for i in range(n-1,10000,-1): - temp=str(i) - if(temp==temp[::-1]): - j=999 - while(j!=99): - if((i%j==0) and (len(str(i/j))==3)): - print i +limit = int(input("limit? ")) + +# fetchs the next number +for number in range(limit-1,10000,-1): + + # converts number into string. + strNumber = str(number) + + # checks whether 'strNumber' is a palindrome. + if(strNumber == strNumber[::-1]): + + divisor = 999 + + # if 'number' is a product of two 3-digit numbers + # then number is the answer otherwise fetch next number. + while(divisor != 99): + + if((number % divisor == 0) and (len(str(number / divisor)) == 3)): + + print number exit(0) - j-=1 + + divisor -=1 \ No newline at end of file