Archive
Python: Collatz Sequence
Python: Longest Collatz Sequence
Problem No.14 in ProjectEuler
Definition Wikipedia: Start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
So the formula is: Starting with n, the next n will be:
n/2 (if n is even)
3n + 1 (if n is odd)
If we start with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1.
A walk through:
n=13, 13 is odd, then n = 13 * 3 + 1 , n= 40
n=40, 40 is even, then n= 40/2, n=20
n=20, 20 is even, then n=20/2, n=10
n=10, 10 is even, then n=10/2, n=5
n=5, 5 is odd, then n=5*3+1 , n=16
n=16, 16 is even, then n=16/2, n=8
n=8, 8 is even, then n=8/2, n=4
n=4, 4 is even, then n=4/2, n=2
n=2, 2 is even, then n=2/2, n=1
n=1 then end of sequence
The Task: The task in ProjectEuler is to searching for a the Number N, under one million, that produces the longest chain.
Overview to my python cases: In my company, we are not allowed to download any software, so i don’t have any Python platform. To solve this i am using an online python interpreter, some time it’s become slow. So in this code (and others) i am spiting the range in 10 each with 100,000 then running the code to get the longest chain in each range. So the Number N, under one million, that produces the longest chain is:
The Answer: In my previous codes or math solving challenges in pybites or ProjectEuler I am solving the problems, writing the code, but not posting my answer to ProjectEuler platform. Today, and with Problem No.14 i decide to post the answer in the ProjectEuler platform for the first time just to see what will happen. The answer was 837799, and I get this page.
In the code bellow, i set the range from 1 to 50000.
The Code:
chain2=[]
longest=[0,0]
def collatz_Seq(num):
t= num
chain=[num]
while t !=1 :
if t%2==0:
t=t/2
chain.append(int(t))
else:
t=3*t+1
chain.append(int(t))
return chain
for num in range (1,50000):
chain2 = collatz_Seq(num)
if len(chain2) > longest[0]:
longest[0] = len(chain2)
longest[1] = num
chain2=[]
print(‘num:’,longest[1],’ has a longest chain: ‘,longest[0])
Python Project: Sum of the Square and Square of the Sum
Python: Sum of the Square and Square of the Sum
Difference of sum of the square and the square of the sum
I fond this on projecteuler.net Usually I add some steps to there problems to make it more application look and feel. Later on, we’ll see how.
Problem assumption: If we said that we have a range of numbers (1,10) then the sum of this range is 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55, Now the Square of the sum is 55^2; thats mean the Square of the sum of (55) = 3025.
And for the same range, the Sum of Square means that we will get the Square of each number in the range then will get there summation. So with our range (1,10) Sum of Square is 1^2 + 2^2 + 3^2 + 4^2 + 5^2 …. + 10^2 = 385
The Problem #6 in ProjectEuler
The sum of the squares of the first ten natural numbers is,12 + 22 + … + 102= 385
The square of the sum of the first ten natural numbers is,(1 + 2 + … + 10)2 = 552= 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
The Task:Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Inhancment Now to make this task workking as application and to get more general output of it, first we will ask the user to input a range of the numbers, then we will applay the function on that range.
The Code:
# Problem 6 in ProjectEuler.
def square_of_sum(num1, num2):
tot = 0
for x in range(num1, num2+1):
tot = tot+x
print(‘The Square of the Sun’,tot*tot)
return tot*tot
def sum_of_square(num1, num2):
tot = 0
for x in range(num1, num2+1):
tot = tot+(x*x)
print(‘The Sum of the Square ‘, tot)
return tot
#Ask the user for his input.
num1 = int(input(‘Enter First number in the range: ‘))
num2 = int(input(‘Enter the last number in the range: ‘))
#Call the functions.
w1 = square_of_sum(num1, num2)
w2 = sum_of_square(num1, num2)
#Output the Difference.
print(‘The Difference is: ‘, w1-w2)
Python Project: Is it a Prime
Python: Prime Number
Is it Prime
In a simple way, a Prime number is a number that cannot be made by multiplying other numbers. So 4 is Not Prime because we can say that 4 = 2 x 2, 6 is Not Prime because it can be produced by multiplying 3 x 2; but 5 Is Prime because we can’t find any integer numbers that can produce 5.
Numbers such as 1, 3, 5, 7, 11, 13 … all are Prime Numbers.
This function will ask the user to write a number then we will examine it to see whether it is a prime or not.
The Code:
num=int(input(“Enter a number: “))
def is_prime(num):
result=”Prime”
for t in range (2,num):
if num%t==0 :
result=”Not Prime”
break
return result
print num,’is’,is_prime(num)
Python Project: Fibonacci Numbers
Python: Fibonacci Numbers
Even Fibonacci Numbers
Fibonacci Sequence is generated by adding the previous two terms, so the N number in the sequence will be Xn=(Xn-1) + (Xn-2). Example: by starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
The Task: Get the Fibonacci sequence range from the user and count how many even valued terms is there. The user range should not be more than 10000 number.
The Code:
def get_Fibonacci_Sequence(rfrom,rto):
n1=rfrom
n2=rfrom+1
count=0
for x in range (rfrom,rto):
fab=n1+n2
n1=n2
n2=fab
# Check if the fab is even, the increment the counter
if fab%2==0 :
count =count +1
# After finish print the output
print”Between”,rfrom,” and “,rto,” there is “,count,”even Fibonacci number.”
range_ok =”no”
while range_ok==”no”:
print(‘Your range must be less than 10,000:’)
# Get the numbers from the user.
rfrom=int(input(‘Enter the range From:’))
rto=int(input(‘Enter the range To:’))
# Check if the numbers are less than 10000
if (rto – rfrom) < 10000 : range_ok ="yes"
#Call the function
get_Fibonacci_Sequence(int(rfrom),int(rto))
Python Project: Pluralise a Word
Python: Pluralise a Word
Loop through a dictionary and pluralise a word
One of Python Exercises on @PyBites codechalleng is to loop through a given dictionary of people and the number of games they’ve won then print out the users name and how many games they’ve won in the following format: “sara has won n games” and pluralise the word game to suit the number of games won.
we assume the dictionary is games_won = dict={‘sara’:0, ‘bob’:1, ‘tim’:5, ‘julian’:3, ‘jim’:1}
The Code:
games_won ={‘sara’:0, ‘bob’:1, ‘tim’:5, ‘julian’:3, ‘jim’:1}
def print_game_stats(games_won):
for key,val in games_won.items():
print(“{} has won {}{p}”.format(key, val,p=” game” if val ==1 else ” games” ))
print_game_stats(games_won)
Python Project: Sum N Numbers
Python: Sum N Numbers
Bites of Python exercises
I found this Python Exercises on the at PyBites codechalleng and i love the idea of solving problems and this will let me learn more, so thanks guys @pybites.
So this time the challenge is to Write a function that can sum up N numbers. The function should receive a list of N numbers, If no argument is provided, return sum of numbers 1..100.
I hope i did this right, here is my function; the result seems to be fine i am still learning so … sorry if i misunderstood.
def sum_up(my_nums=range(1,100)):
total=0
print”The List of number/s “,my_nums
for x in range (len(my_nums)):
total=total+int(my_nums[x])
print”Total is:”,total
print(“This function will sum up a given list of numbers.\nWhen you finish typping the numbers just press “”Enter””\nIf you did not enter any numbers i will assume the list is [1,100]”)
#Get the list from the user
n=input(“Type the numbers:”)
#In case the user enter some spaces in his number, we should remove it
the_n=n.replace(” “, “”)
#Here we are calling the functin
sum_up() if the_n ==”” else sum_up(the_n)

Python project: Drawing with Python – Flower
Python: Draw Flower
Drawing with Python
In this post i tried to draw another flower using arcs of circles, i get a simple one and i guess with more sizes we can do more complex shape.
You can play with the code and change the numbers, size and rotation degree and let’s see what we will have.
t = turtle.Turtle()
t.hideturtle()
t.pendown()
for x in range (30):
t.circle(60,70)
if x %3==0:
t.circle (10,90)

Python Project: Binary Search
Python: Binary Search
Binary Search
Definition:
Binary Search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
In this code we are writing a Python code to find the target in a sorted given array and get its position without using any python math packages.
The case: We have an Array (arr=[2,3,5,6,8,10,11,13,15,16,19]) our target is 13, so we want the position of 13.
We are setting the first position as (pos_s=0) and the end position as (pos_e= the length of the array -1) and we will use recursive function.
Recursive Function: is a computer function or procedure that calling it self
The Code:
arr=[2,3,5,6,8,10,11,13,15,16,19]
target=11
pos_s =0
pos_e=int(len(arr)-1)
midarr =0
def bsearch(arr,target,pos_s,pos_e):
midarr=(pos_s+pos_e)/2
if arr[midarr] < target:
pos_s = midarr +1
bsearch(arr,target,pos_s,pos_e)
elif arr[midarr] > target:
pos_e = midarr -1
bsearch(arr,target,pos_s,pos_e)
elif arr[midarr] == target:
print(‘The target was: ‘,target, ‘ The key of our target is: ‘,midarr)
return
print(arr)
# Call the functin
bsearch(arr,target,pos_s,pos_e)
Python : Expenditure App
Expenditure Application
leveling the Ground:
In this post we will assume that we have a folder for our application, and we will create two files one is for our python code and we will name it “expen.py”, the other is for our data and we will name it “expen_dat.json” this file extension is ‘json’. Also I assume that we have json pack is installed in the PC so if you don’t have json this is the time to install it.
json file:After you create expen_dat.json file just open it with any text editor and copy a test data of our expenditure as shown.
{“expenditure”:
[
{“date”:”02/03/2016″,”amount”:300},
{“date”:”10/04/2016″,”amount”:550},
{“date”:”02/05/2016″,”amount”:300},
{“date”:”10/04/2016″,”amount”:550},
{“date”:”02/03/2016″,”amount”:300},
{“date”:”10/04/2016″,”amount”:550},
{“date”:”05/01/2017″,”amount”:400},
{“date”:”10/02/2017″,”amount”:400},
{“date”:”15/03/2017″,”amount”:400},
{“date”:”20/04/2017″,”amount”:400}
}]
In next post we will start with coding and testing our Expenditure Application.
I will use the @pycharm to write the code and test it, but any other code editors can be used. Also, I assume we have Python and json installed in your PC.
From my Sketch Book
Bird From my Sketch Book
I am sketching to enhance my skill, here is one of sketches from my sketchbook using pencil as a guide-line and ink-pen to finish the drawing.
Click to Enlarge
::My SketchBook::
Sketch of: Bird
Using: Ink-Pen
Date: 5/12/2017
SketchBook: SketchBook # 22
More Sketches: Click Here
Ali,


Follow me on Twitter..







