Python - Week 6 - String join, List append, else with for loop and Fractions module

This week I worked on 2 problems.

Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line.

Pretty straight forward solution but it highlights use of a couple of new Python constructs. First the code:


Now some notes:
  1. Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size.
  2. The range statements I have used in the past have defaulted to 0 as the lower bound. Here the lower bound is specified as 1000.
  3. Line 11 shows a simple way to iterate over characters in string. You do not need to open up the string. The for loop does it automagically.
  4. Notice the else statement in Line 16. Only if the loop (which started in Line 11) succeeds without a break, this else is executed. Python provides this as a construct to eliminate use of flags.
  5. allevens is declared as an empty list in Line 4. We then use append call to add elements to this list.
  6. The join call in Line 19 is a way to create a comma separated list of strings. Could have been something else instead of comma had we mentioned that.
  7. Loop else block runs if and only if the loop is exited normally (i.e., without hitting a break) 
  8. Built-in ord function returns the actual binary value (ASCII or Unicode) used to represent the corresponding character in memory.
  9. Use the string join method to “implode” the list back into a string

Another program that I tried this week, dealt with fractions. And I was pleasantly surprised to find Fractions module in Python which makes things so simple.

Here is the problem statement followed by the solution:

Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0)
If the following n is given as input to the program: 5
Then, the output of the program should be: 3.55


The only thing of interest in above code is the use of Fraction package which supports rational number arithmetic. Using this package, we can create fractions from integers, floats, decimal and from some other numeric values and strings.

Comments

Popular posts from this blog

Python - Week 8 - Dictionaries, Tuples, Sorting and Filtering

Python - Week 3 - Lists, Tuples, Slicing, Math Functions

Python - Week 5 - Comprehensions