Skip to content

Commit fb413e5

Browse files
committed
add exercise 3
1 parent 7248a6f commit fb413e5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
File renamed without changes.

exercises_3.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
'''
5+
Take a list, say for example this one:
6+
7+
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
8+
and write a program that prints out all the elements of the list that are less than 5.
9+
10+
Extras:
11+
12+
- Instead of printing the elements one by one,
13+
make a new list that has all the elements less than 5 from this list in it and print out this new list.
14+
15+
- Write this in one line of Python.
16+
17+
- Ask the user for a number and return a list that contains only elements from the original list that are smaller than the number given by the user.
18+
'''
19+
20+
numbers = raw_input('Please input a group of numbers seperated by ",": ')
21+
number_list = [int(number.strip()) for number in numbers.split(',')]
22+
23+
print 'Those are numbers in the group smaller than 5: '
24+
for number in number_list:
25+
if number < 5:
26+
print number
27+
28+
##########################
29+
# For Extras:
30+
##########################
31+
32+
print 'Filter numbers smaller than 5 to a new list: '
33+
# Method 1:
34+
new_number_list = [number for number in number_list if number<5]
35+
print 'filter list in Method 1: ', new_number_list
36+
37+
# Method 1:
38+
new_number_list2 = filter(lambda x:x<5, number_list)
39+
print 'filter list in Method 2: ', new_number_list2
40+
41+
ceiling = raw_input('Please input a custom filter number: ')
42+
ceiling = int(ceiling)
43+
44+
new_number_list3 = filter(lambda x:x<ceiling, number_list)
45+
print 'The following are numbers that are smaller than {0}: '.format(ceiling), new_number_list3

0 commit comments

Comments
 (0)