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:
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:
- Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size.
- 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.
- 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.
- 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.
- allevens is declared as an empty list in Line 4. We then use append call to add elements to this list.
- 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.
- Loop else block runs if and only if the loop is exited normally (i.e., without hitting a break)
- Built-in ord function returns the actual binary value (ASCII or Unicode) used to represent the corresponding character in memory.
- 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
Comments
Post a Comment